Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,156
» Latest member: levlotus1998
» Forum threads: 21,839
» Forum posts: 22,714

Full Statistics

Online Users
There are currently 723 online users.
» 0 Member(s) | 718 Guest(s)
Applebot, Baidu, Bing, DuckDuckGo, Google

 
  [Tut] Python Regex – ¿Cómo contar el número de coincidencias?
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: Python - No Replies

Python Regex – ¿Cómo contar el número de coincidencias?

Para contar un patrón de expresión regular varias veces en una cadena dada, usa el método len(re.findall(pattern, string)) que devuelve el número de subcadenas coincidentes o len([*re.finditer(pattern, text)]) que desempaqueta todas las subcadenas coincidentes en una lista y también devuelve la longitud de la misma.

Hace unas horas, escribí una expresión regular en Python que coincidía no una sino varias veces en el texto y me pregunté: ¿cómo contar el número de coincidencias?

Considera el ejemplo mínimo en el que buscas un número arbitrario de caracteres de palabras '[a-z]+' en una frase dada 'python is the best programming language in the world'.

Puedes ver mi vídeo explicativo a medida que lees el tutorial:




Artículo relacionado: Superpoderes Regex de Python – La guía definitiva

Los ingenieros de Google, Facebook y Amazon son auténticos maestros de expresiones regulares. Si quieres convertirte en uno también, echa un vistazo a nuestro nuevo libro: La forma más inteligente de aprender Python Regex (Amazon Kindle/Print, se abre en una nueva pestaña).

¿Cuántas coincidencias hay en la cadena? Para contar el número de coincidencias, puede usar varios métodos:

Método 1: Python re.findall()


Usa el método re.findall(pattern, string) que devuelve una lista de subcadenas coincidentes. Luego cuenta la longitud de la lista devuelta. Aquí hay un ejemplo:

>>> import re
>>> pattern = '[a-z]+'
>>> text = 'python is the best programming language in the world'
>>> len(re.findall(pattern, text))
9

¿Por qué es 9 el resultado? Debido a que hay nueve subcadenas coincidentes en la lista devuelta por el método re.findall():

>>> re.findall(pattern, text)
['python', 'is', 'the', 'best', 'programming', 'language', 'in', 'the', 'world']

Este método funciona muy bien si no hay coincidencias solapadas.

¿Quieres dominar el superpoder regex? Echa un vistazo a mi nuevo libro La forma más inteligente de aprender expresiones regulares en Python con el innovador enfoque de 3 pasos para el aprendizaje activo: (1) estudia un capítulo de libro, (2) resuelve un rompecabezas de código y (3) mira un video de capítulo educativo.

Método 2: Python re.finditer()


También puedes contar el número de veces que un patrón determinado coincide en un texto utilizando el método re.finditer(pattern, text):

Especificación: re.finditer(pattern, text, flags=0)

Definición: devuelve un iterador que repasa todas las coincidencias no solapadas del patrón en el texto.

El argumento flags te permite personalizar algunas propiedades avanzadas del motor regex, como por ejemplo si se debe ignorar el uso de mayúsculas en los caracteres. Puedes saber más sobre el argumento flags en el tutorial detallado de mi blog.

Ejemplo: puedes usar el iterador para contar el número de coincidencias. A diferencia del método re.findall() descrito anteriormente, esto tiene la ventaja de que puedes analizar los propios objetos coincidentes que contienen mucha más información que la simple subcadena coincidente.

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world'
for match in re.finditer(pattern, text): print(match) '''
<re.Match object; span=(0, 6), match='python'>
<re.Match object; span=(7, 9), match='is'>
<re.Match object; span=(10, 13), match='the'>
<re.Match object; span=(14, 18), match='best'>
<re.Match object; span=(19, 30), match='programming'>
<re.Match object; span=(31, 39), match='language'>
<re.Match object; span=(40, 42), match='in'>
<re.Match object; span=(43, 46), match='the'>
<re.Match object; span=(47, 52), match='world'> '''

Si quieres contar el número de coincidencias, puedes utilizar una simple variable count:

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world' count = 0
for match in re.finditer(pattern, text): count += 1 print(count)
# 9

O una solución más pitónica:

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world' print(len([*re.finditer(pattern, text)]))
# 9

Este método funciona muy bien si no hay coincidencias solapadas. Utiliza el operador asterisco * para desempaquetar todos los valores del iterable.

Método 3: Coincidencias solapadas


Los dos métodos anteriores funcionan muy bien si no hay coincidencias solapadas. Si hay coincidencias solapadas, el motor regex simplemente las ignorará porque “consume” todas las subcadenas coincidentes y comienza a comparar el siguiente patrón sólo después del índice stop de la coincidencia anterior.

Así que si necesitas encontrar el número de coincidencias superpuestas, necesitas usar un enfoque diferente.

La idea es hacer un seguimiento de la posición inicial de la coincidencia precedente e incrementarla en uno después de cada coincidencia:

import re
pattern = '99'
text = '999 ways of writing 99 - 99999' left = 0
count = 0
while True: match = re.search(pattern, text[left:]) if not match: break count += 1 left += match.start() + 1
print(count)
# 7

Al hacer un seguimiento del índice start de la coincidencia anterior en la variable left, podemos controlar dónde hay que buscar la siguiente coincidencia en la cadena. Ten en cuenta que utilizamos la operación de rebanado de Python text[left:] para ignorar todos los caracteres a la izquierda que ya se han considerado en las coincidencias anteriores. En cada iteración del bucle, emparejamos otro patrón en el texto. Esto funciona incluso si esas coincidencias se solapan.

A dónde ir desde aquí


Has aprendido tres formas de encontrar el número de coincidencias de un patrón dado en una cadena.

¡Si tienes problemas con las expresiones regulares, echa un vistazo a nuestro tutorial de regex gratuito de 20.000 palabras en el blog de Finxter! ¡Te dará superpoderes de regex!

¿Quieres dominar el superpoder regex? Echa un vistazo a mi nuevo libro La forma más inteligente de aprender expresiones regulares en Python con el innovador enfoque de 3 pasos para el aprendizaje activo: (1) estudia un capítulo de libro, (2) resuelve un rompecabezas de código y (3) mira un video de capítulo educativo.

Curso Regex de Python


Los ingenieros de Google son maestros de expresiones regulares. El motor de búsqueda de Google es un motor de procesamiento de texto masivo que extrae valor de billones de páginas web.

Los ingenieros de Facebook son maestros de expresiones regulares. Las redes sociales como Facebook, WhatsApp e Instagram conectan a los humanos a través de mensajes de texto.

Los ingenieros de Amazon son maestros de expresiones regulares. Los gigantes del comercio electrónico envían productos basados en descripciones de productos textuales.Las expresiones regulares rigen el juego cuando el procesamiento de texto se encuentra con la informática.

Si quieres convertirte también en un maestro de expresiones regulares, echa un vistazo al curso de Python regex más completo del planeta:

¿Por qué Finxter?

“Dadme una palanca lo suficientemente larga […] y moveré el mundo”. ?Arquímedes

¡Finxter pretende ser tu palanca! ¡Nuestro único propósito es aumentar la inteligencia colectiva de la humanidad a través de tutoriales de programación para que pueda aprovechar la inteligencia computacional infinita para su éxito! ?

Recursos de aprendizaje


¡Únase a nuestra academia gratuita de correo electrónico con más de 1000 tutoriales en Python, freelance, ciencia de datos y aprendizaje automático, y tecnología Blockchain!

Además, no dude en consultar nuestros libros de Finxter y el curso de freelancer #1 del mundo para crear su próspero negocio de codificación en línea. ⭐⭐⭐⭐⭐

Codificador independiente

Si no estás listo para hacerlo, no dudes en leer nuestro artículo de blog sobre cómo ganar tus primeros $ 3,000 como programador freelance.

¡TODOS LOS ENLACES DE LA BARRA LATERAL SE ABREN EN UNA NUEVA PESTAÑA!



https://www.sickgaming.net/blog/2022/03/...cidencias/

Print this item

  [Oracle Blog] The OpenJDK Community TCK License Agreement (OCTLA)
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: Java Language, JVM, and the JRE - No Replies

The OpenJDK Community TCK License Agreement (OCTLA)

After launching the OpenJDK Community as the place to collaborate on open source implementations of the Java SE Platform back in 2006, the next logical step was to make the Java SE TCK (JCK) available to those working in and contributing to OpenJDK. Sun Microsystems did this via the “OpenJDK Communi...

https://blogs.oracle.com/java/post/the-o...ment-octla

Print this item

  [Tut] PHP Login Form with MySQL database and form validation
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: PHP Development - No Replies

PHP Login Form with MySQL database and form validation

by Vincy. Last modified on March 1st, 2022.

Login form – an entry point of a website to authenticate users. PHP login system requires users to register with the application first to log in later.

The registered users are managed in a database at the back end. On each login attempt via the PHP login form, it verifies the database to find a match.

It is a very simple and essential job. At the same time, it should be designed with security to guard the site. It should filter anonymous hits 100% not to let unregistered users get in.

The PHP login form action stores the logged-in user in a session. It uses PHP $_SESSION one of its superglobals. It’s better to validate the existence of this session at the beginning of each page to be protected.

This PHP code can also be used to add an admin login for your control panel. Also, it can be used as a common authentication entry for both admin and user side of an application.

PHP login form code


This example is to design a PHP login form working with backend processing. The login page in PHP shows the UI elements like social login, forgot password and etc.

It posts data to process a username/password-based login authentication. This example uses the database to authenticate the user login.

This PHP login system is capable of linking the following code to the additional login form controls.

  1. Link PHP forgot/reset password feature.
  2. Link User registration PHP example to the sign-up option.
  3. Also, Link Oauth login with Facebook, Twitter and Linkedin.

php login form

HTML form template


The landing page renders this template into the UI to let the user log in. It will happen when there is no logged-in session.

This form accepts the user’s login details username or email and a secure password. The submit event triggers the PHP login form validation and posts the login data to the PHP.

This PHP login form is responsive to the different viewport sizes. It uses simple CSS media queries for adding site responsiveness.

The form tag calls a JavaScript function validate() on the submit event. The below code includes the PHP login form validation script at the end.

view/login-form.php


<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Login</title>
<link href="./view/css/form.css" rel="stylesheet" type="text/css" />
<style>
body { font-family: Arial; color: #333; font-size: 0.95em; background-image: url("./view/images/bg.jpeg");
}
</style>
</head>
<body> <div> <form action="login-action.php" method="post" id="frmLogin" on‌Submit="return validate();"> <div class="login-form-container"> <div class="form-head">Login</div> <?php if (isset($_SESSION["errorMessage"])) { ?> <div class="error-message"><?php echo $_SESSION["errorMessage"]; ?></div> <?php unset($_SESSION["errorMessage"]); } ?> <div class="field-column"> <div> <label for="username">Username</label><span id="user_info" class="error-info"></span> </div> <div> <input name="user_name" id="user_name" type="text" class="demo-input-box" placeholder="Enter Username or Email"> </div> </div> <div class="field-column"> <div> <label for="password">Password</label><span id="password_info" class="error-info"></span> </div> <div> <input name="password" id="password" type="password" class="demo-input-box" placeholder="Enter Password"> </div> </div> <div class=field-column> <div> <input type="submit" name="login" value="Login" class="btnLogin"></span> </div> </div> <div class="form-nav-row"> <a href="#" class="form-link">Forgot password?</a> </div> <div class="login-row form-nav-row"> <p>New user?</p> <a href="#" class="btn form-link">Signup Now</a> </div> <div class="login-row form-nav-row"> <p>May also signup with</p> <a href="#"><img src="view/images/icon-facebook.png" class="signup-icon" /></a><a href="#"><img src="view/images/icon-twitter.png" class="signup-icon" /></a><a href="#"><img src="view/images/icon-linkedin.png" class="signup-icon" /></a> </div> </div> </form> </div> <script> function validate() { var $valid = true; document.getElementById("user_info").innerHTML = ""; document.getElementById("password_info").innerHTML = ""; var userName = document.getElementById("user_name").value; var password = document.getElementById("password").value; if(userName == "") { document.getElementById("user_info").innerHTML = "required"; $valid = false; } if(password == "") { document.getElementById("password_info").innerHTML = "required"; $valid = false; } return $valid; } </script>
</body>
</html>

PHP login form action


A PHP endpoint script that is an action target of the login form handles the login data.

This login page in PHP sanitizes the data before processing them. It uses PHP filter_var function to sanitize the user entered authentication details.

It conducts the authentication process after receiving the user credentials.

This program puts the authenticated user details in a session. Then, it acknowledges the user accordingly.

login-action.php


<?php
namespace Phppot; use \Phppot\Member;
if (! empty($_POST["login"])) { session_start(); $username = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); $password = filter_var($_POST["password"], FILTER_SANITIZE_STRING); require_once (__DIR__ . "/class/Member.php"); $member = new Member(); $isLoggedIn = $member->processLogin($username, $password); if (! $isLoggedIn) { $_SESSION["errorMessage"] = "Invalid Credentials"; } header("Location: ./index.php"); exit();
}

PHP login authentication model class


It contains the processLogin() function to check the PHP login form data with the database. It uses PHP password_verify() function to validate the user-entered password. This PHP function compares the password with the hashed password on the database.

The getMemberById() function reads the member result by member id. After successful login, it is called from the case to display the dashboard. It returns the array of data to be displayed on the dashboard.

class/Member.php


<?php
namespace Phppot; use \Phppot\DataSource; class Member
{ private $dbConn; private $ds; function __construct() { require_once "DataSource.php"; $this->ds = new DataSource(); } function getMemberById($memberId) { $query = "select * FROM registered_users WHERE id = ?"; $paramType = "i"; $paramArray = array($memberId); $memberResult = $this->ds->select($query, $paramType, $paramArray); return $memberResult; } public function processLogin($username, $password) { $query = "select * FROM registered_users WHERE user_name = ? OR email = ?"; $paramType = "ss"; $paramArray = array($username, $username); $memberResult = $this->ds->select($query, $paramType, $paramArray); if(!empty($memberResult)) { $hashedPassword = $memberResult[0]["password"]; if (password_verify($password, $hashedPassword)) { $_SESSION["userId"] = $memberResult[0]["id"]; return true; } } return false; }
}

Show dashboard and logout link after PHP login


After successful login, the site says there exists a session of the logged-in user. It can be shown in different ways.

In most sites, the site header displays the logged-in user’s profile link. It can be a clickable avatar that slides down a profile menu.

This PHP login system redirects the user to a dashboard page after login. This dashboard page shows a welcome message, about-user with an avatar.

The landing page checks the PHP session if any user has already login. If so, it will redirect to this dashboard page.

view/dashboard.php


<?php
namespace Phppot; use \Phppot\Member; if (! empty($_SESSION["userId"])) { require_once __DIR__ . './../class/Member.php'; $member = new Member(); $memberResult = $member->getMemberById($_SESSION["userId"]); if(!empty($memberResult[0]["display_name"])) { $displayName = ucwords($memberResult[0]["display_name"]); } else { $displayName = $memberResult[0]["user_name"]; }
}
?>
<html>
<head>
<title>User Login</title>
<style>
body { font-family: Arial; color: #333; font-size: 0.95em;
} .dashboard { background: #d2edd5; margin: 15px auto; line-height: 1.8em; color: #333; border-radius: 4px; padding: 30px; max-width: 400px; border: #c8e0cb 1px solid; text-align: center;
} a.logout-button { color: #09f;
}
.profile-photo { width: 100px; border-radius: 50%; }
</style>
</head>
<body> <div> <div class="dashboard"> <div class="member-dashboard"> <p>Welcome <b><?php echo $displayName; ?>!</b></p> <p><?php echo $memberResult[0]["about"]; ?></p> <p><img src="./view/images/photo.jpeg" class="profile-photo" /></p> <p>You have successfully logged in!</p> <p>Click to <a href="./logout.php" class="logout-button">Logout</a></p> </div> </div> </div>
</body>
</html>

PHP Logged in User Dashboard

Logging out from the site


This is a general routine to log out from the site. The following script clears the PHP session. Then it redirects back to login page in PHP.

Sometimes, the logout case may clear cookies. Example: In the case of using a cookie-based Remember Me feature in login.

view/dashboard.php


<?php session_start();
$_SESSION["user_id"] = "";
session_destroy();
header("Location: index.php");

Files structure


See the below image that shows the file structure of this simple PHP login form example. It contains a featured login form UI with the application view files.

The login action calls the PHP model on the submit event. It performs backend authentication with the database.

php login form files

Database script


Look at this SQL script which contains the CREATE statement and sample row data.

By importing this SQL, it creates database requisites in your development environment.

The sample data helps to try a login that returns success response on the authentication.

Test data: username: kate_91 password: admin123

sql/database.sql


--
-- Database: `blog_eg`
-- -- -------------------------------------------------------- --
-- Table structure for table `registered_users`
-- CREATE TABLE `registered_users` ( `id` int(8) NOT NULL, `user_name` varchar(255) NOT NULL, `display_name` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `photo` text DEFAULT NULL, `about` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --
-- Dumping data for table `registered_users`
-- INSERT INTO `registered_users` (`id`, `user_name`, `display_name`, `password`, `email`, `photo`, `about`) VALUES
(1, 'kate_91', 'Kate Winslet', '$2y$10$LVISX0lCiIsQU1vUX/dAGunHTRhXmpcpiuU7G7.1lbnvhPSg7exmW', 'kate@wince.com', 'images/photo.jpeg', 'Web developer'); --
-- Indexes for dumped tables
-- --
-- Indexes for table `registered_users`
--
ALTER TABLE `registered_users` ADD PRIMARY KEY (`id`); --
-- AUTO_INCREMENT for dumped tables
-- --
-- AUTO_INCREMENT for table `registered_users`
--
ALTER TABLE `registered_users` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

Secure DataSource using MySQL with prepared statements


This DataSource is a common file to be used in any stand-alone PHP application. It uses MySQLi with prepared statement to execute database queries. It works with PHP 8 and 7+

class/DataSource.php


<?php
namespace Phppot; /** * Generic datasource class for handling DB operations. * Uses MySqli and PreparedStatements. * * @version 2.3 */
class DataSource
{ // PHP 7.1.0 visibility modifiers are allowed for class constants. // when using above 7.1.0, declare the below constants as private const HOST = 'localhost'; const USERNAME = 'root'; const PASSWORD = ''; const DATABASENAME = 'blog_eg'; private $conn; /** * PHP implicitly takes care of cleanup for default connection types. * So no need to worry about closing the connection. * * Singletons not required in PHP as there is no * concept of shared memory. * Every object lives only for a request. * * Keeping things simple and that works! */ function __construct() { $this->conn = $this->getConnection(); } /** * If connection object is needed use this method and get access to it. * Otherwise, use the below methods for insert / update / etc. * * @return \mysqli */ public function getConnection() { $conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME); if (mysqli_connect_errno()) { trigger_error("Problem with connecting to database."); } $conn->set_charset("utf8"); return $conn; } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function select($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; } } if (! empty($resultset)) { return $resultset; } } /** * To insert * @param string $query * @param string $paramType * @param array $paramArray * @return int */ public function insert($query, $paramType, $paramArray) { print $query; $stmt = $this->conn->prepare($query); $this->bindQueryParams($stmt, $paramType, $paramArray); $stmt->execute(); $insertId = $stmt->insert_id; return $insertId; } /** * To execute query * @param string $query * @param string $paramType * @param array $paramArray */ public function execute($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType="", $paramArray=array()); } $stmt->execute(); } /** * 1. Prepares parameter binding * 2. Bind prameters to the sql statement * @param string $stmt * @param string $paramType * @param array $paramArray */ public function bindQueryParams($stmt, $paramType, $paramArray=array()) { $paramValueReference[] = & $paramType; for ($i = 0; $i < count($paramArray); $i ++) { $paramValueReference[] = & $paramArray[$i]; } call_user_func_array(array( $stmt, 'bind_param' ), $paramValueReference); } /** * To get database results * @param string $query * @param string $paramType * @param array $paramArray * @return array */ public function numRows($query, $paramType="", $paramArray=array()) { $stmt = $this->conn->prepare($query); if(!empty($paramType) && !empty($paramArray)) { $this->bindQueryParams($stmt, $paramType, $paramArray); } $stmt->execute(); $stmt->store_result(); $recordCount = $stmt->num_rows; return $recordCount; }
}

Conclusion


We have seen a simple example on the PHP login form. Hope this will be useful to have a featured, responsive login form.

The article interlinks the constellations of a login form. It will be helpful to integrate more features with the existing login template.

Let me know your feedback on the comments section if you need any improvements on this PHP login system.

Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/03/...alidation/

Print this item

  (Indie Deal) Anime Giveaways, Digimon, Furi & Yu-Gi-Oh Deals
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: Deals or Specials - No Replies

Anime Giveaways, Digimon, Furi & Yu-Gi-Oh Deals

Anime Giveaways
[www.indiegala.com]
SAO, Black Clover, MHA, DBZ anime giveaways are now live, but more are on their way!

Digimon Story Cyber Sleuth: Complete Edition Deal
[www.indiegala.com]
With engaging storylines, classic turn-based battles, and tons of Digimon to collect, Digimon Story Cyber Sleuth: Complete Edition delivers everything fans loved about Digimon Story: Cyber Sleuth and Digimon Story: Cyber Sleuth – Hacker’s Memory.

Yu-Gi-Oh! & PID Sales, up to 90% OFF
[www.indiegala.com]
[www.indiegala.com]
https://www.youtube.com/watch?v=EaO5vRkUiAc
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...4076807611

Print this item

  PC - Assassin's Creed Valhalla: Dawn of Ragnarok
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: New Game Releases - No Replies

Assassin's Creed Valhalla: Dawn of Ragnarok



In the most ambitious expansion in franchise history, Eivor must embrace their destiny as Odin, the Norse god of Battle and Wisdom. Unleash new divine powers as you embark on a desperate quest through a breathtaking world. Complete a legendary Viking saga and save your son in the face of the gods’ doom.

Publisher: Ubisoft

Release Date: Mar 10, 2022




https://www.metacritic.com/game/pc/assas...f-ragnarok

Print this item

  News - Elden Ring: Where To Get The Hookclaws
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: Lounge - No Replies

Elden Ring: Where To Get The Hookclaws

Elden Ring may have no shortage of cool weapons that you can find and equip, but let's be real--you're really just dying to get your hands on some claws and cosplay as Wolverine, right? Lucky for you, the Hookclaws are a solid option for mobility-focused players, and they can be found pretty early in the game. We'll tell you precisely where below.

Hookclaws explained

The Hookclaws are, as you might've guessed, a claw weapon that requires 8 Strength and 14 Dexterity to wield. You can use one claw alongside a shield, or you can two-hand the weapon to equip one claw on each hand for some frenetic and aggressive attacks that come along with some hefty bleed buildup--and they look cool doing it.

The Hookclaws' weapon skill is a fairly common one known as Quickstep. It functions similarly to the dodge from Bloodborne, allowing you to quickly maneuver around your enemies fluidly, even letting you get behind them quickly for some fast attacks.

Continue Reading at GameSpot

https://www.gamespot.com/articles/elden-...01-10abi2f

Print this item

  (Free Game Key) Knightfall: A Daring Journey - Free Steam Game
Posted by: xSicKxBot - 04-04-2022, 12:32 AM - Forum: Deals or Specials - No Replies

Knightfall: A Daring Journey - Free Steam Game

Of all the days a steam freebie would be available, it had to be on the day we pretended to be bought by Epic. :fomtlaugh:

Visit the store page and add the game to your account:

Knightfall: A Daring Journey

Available until Apr 2nd. !addlicense asf s/705132 for ASF users.

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: ✔️HumbleBundle Partner[www.humblebundle.com] Epic Tag: GrabFreeGames


https://steamcommunity.com/groups/GrabFr...9648492930

Print this item

  [Oracle Blog] Building JDK 11 Together
Posted by: xSicKxBot - 04-02-2022, 06:00 PM - Forum: Java Language, JVM, and the JRE - No Replies

Building JDK 11 Together

With the recent release of Java 11, it’s time to look back at the development of the second feature release in the new semi-annual release cadence. Let’s celebrate the many contributions in the OpenJDK Community from many individuals and organizations — we all built JDK 11, together! JDK 11 Fix Rati...

https://blogs.oracle.com/java/post/build...1-together

Print this item

  [Tut] Convert Bytes To Floating Point Numbers
Posted by: xSicKxBot - 04-02-2022, 06:00 PM - Forum: Python - No Replies

Convert Bytes To Floating Point Numbers

Summary: The struct module in Python, taken from the C programming language, lets you convert bytes to and from floating point numbers.


Problem: How to convert bytes to floating point numbers?

A quick look at the solution:


A Brief Introduction to Struct


The struct module has three main methods for data conversion:

  • unpack(),
  • pack()
  • calcsize().

➦ You can use the unpack() method to convert bytes to floating point numbers. The method accepts data format and the byte to be converted.

struct.unpack("f", <byte>)

➦ On the other hand, the pack() method helps in converting data types to bytes.

struct.pack("f", <floating point number>)

Where f stands for floats. As you will see in other parts of this tutorial, the struct module handles different data types such as characters, integers and floats. But before that, you should understand bytes, floating point numbers, and the concept of structs.

Definition Of Bytes And Floating Point Numbers


This section focuses on the roots of bytes and data formats.

Unlike humans that represent numbers in base 10 (0 to 9 digits), computers understand the language of 1s and 0s. A pair of 1 and 0 is a binary digit, shortened as a bit. So, the computer converts data into a series of 1s and 0s (bits) before storing them in the memory.

Likewise, non-numerical data get stored as bytes. For instance, a character occupies 1 byte of memory. An array of characters forms a string.


Format Type in C programming language size in bytes
c char 1
b signed char 1
B unsigned char 1
? _Bool 1
h short 2
H unsigned short 2
i int 4
I unsigned int 4
l long 4
L unsigned long 4
q long long 8
Q unsigned long long 8
s char[]
f float 4

Now that you understand how a computer interprets various data types, it would be best to learn how the struct module uses them to convert bytes to floating point numbers. Since struct has been taken from the C programming language, hence, a deeper understanding of how it works in C is crucial.

Struct Padding vs Packing


In the C programming language, a struct is a user-defined data type. Unlike other variables, a struct combines different data types in a structure. Here is an example.

struct Fruit { char firstLetter; int total;
};

We are creating a blueprint of a Fruit with a firstLetter character, and total integer. We can create a banana from the Fruit model, assigning it b as firstLetter and 23 as total.

struct Fruit fruit1 = { 'b', 23 };

Printing the size of each attribute,

printf("firstLetter is %d bytes and total is %d bytes \n", sizeof(fruit1.firstLetter),sizeof(fruit1.number));

we get the result as

firstLetter is 1 bytes and total is 4 bytes

The size of fruit1 should be (1 + 4 =) 5 bytes, right? Let’s check.

Size of fruit1 is 8 bytes

It turns out our computer uses more memory to store smaller data quantities. That happens due to a concept called padding.

CPU reads 4 bytes of data per cycle. For the first cycle, it adds three bytes of space to the available (1) byte and returns the result. Next, it finds 4 bytes and returns them. In total, it records (4 + 4 =) 8 bytes.

Padding wastes memory while reducing CPU cycles. Struct packing comes in to store more bytes in less memory.

#include <stdio.h>
#pragma pack(1) struct Fruit { char firstLetter; int number;
}; int main () { struct Fruit fruit1 = { 'b', 23 }; // printf("firstLetter is %d bytes and total is %d bytes \n", sizeof(fruit1.firstLetter),sizeof(fruit1.number)); printf("Size of fruit1 is %d bytes \n", sizeof(fruit1)); return 0;
}

We include #pragma pack(1) header with pack function of value 1 to reduce the memory wastage when compiling and assembling data. This time around, the struct size is what we expect: 1 byte + 4 bytes = 5 bytes.

Size of fruit1 is 5 bytes 

The key takeaway is that struct is a C programming language data structure for storing user-defined data types. Unlike other data types, it combines a continuous stream of different data types. The various data types consume more memory due to padding, something we can control using struct packing.

We can apply the concept of struct to convert data types to bytes in Python, as illustrated below.

How To Use The Struct Module In Python


Unlike C, which speaks to the memory through data types and compiling, Python is a high-level, dynamically-typed programming language. Most operations occur through modules (classes) that get translated and compiled to produce bytes. One such module is the struct module.
The struct module has three methods: pack(), unpack(), and calcsize(). The pack method accepts two parameters: format and data to be converted to bytes. Like the struct blueprint in C, the format part of the pack function in Python accepts various data types. For example,

struct.pack('iif', 2, 4, 7.68)

This means converting integer 2, integer 4 and float 7.68 to a stream of bytes. i stands for an integer while f represents floats.

You can represent repeating integers by a numeral. For example, iii can map to 3i. Also, you can separate the data types with a space. For example, 3i f is another representation for 3if.

We can check the format size by importing the module,

import struct 

and using its calcsize() method.

struct.calcsize('3if')

In the same way, we can convert a floating point number into bytes. Assume we want to convert 3.76 to bytes. We can do that using the following code.

byteData = struct.pack('f', 3.76) print(byteData)

Output:

b'\xd7\xa3p@'

Here, b stands for bytes. The other parts may differ as per computer depending on the memory address system and endianness. Let’s now find floating point numbers from bytes.

Convert Bytes To Floating Point Numbers


The unpack function accepts format, and the byte stream then converts it to a floating point number. For example, we can decode b'\xd7\xa3p@' as follows.

byteData = struct.unpack('f', b'\xd7\xa3p@') print(byteData)

The result is a tuple containing a floating point number with a massive number of decimal points.

(3.759999990463257,)

We can extract the result by surrounding the input with square brackets.

[byteData] = struct.unpack('f', b'\xd7\xa3p@')

The result of printing the output is 3.759999990463257.

The extended decimal output from a reduced input size shows the essence of scientific notation in computing. It also proves the reason for the preference of floating point numbers over integers.

Apart from efficiency, handling floating point numbers comes with speed since much work has gone into building floating point numbers over the years.

Conclusion


The struct module with its unpack() method helps convert bytes to floating point numbers. It would help to understand other methods such as pack() and calcsize because, from them, you can generate bytes from various data types.

Another way to ease handling the conversion is understanding the ins and outs of the struct module, as explained in this tutorial.




https://www.sickgaming.net/blog/2022/03/...t-numbers/

Print this item

  [Tut] PHP File Upload to Server with MySQL Database
Posted by: xSicKxBot - 04-02-2022, 06:00 PM - Forum: PHP Development - No Replies

PHP File Upload to Server with MySQL Database

by Vincy. Last modified on February 1st, 2022.

File upload is an important component in building websites. This article will help you to implement a file upload to the server feature with PHP and a MySQL database.

Example use cases of where the file upload may be needed in a website,

Let us see how to code PHP file upload for a website. You can split this article into the following sections.

  1. PHP file upload – A quick example.
  2. File upload – server-side validation.
  3. Upload file to the server with database.
  4. Upload file as a blob to the database.

PHP file upload – Quick example


<?php if (isset($_FILES['upload_file'])) { move_uploaded_file($_FILES["upload_file"]["tmp_name"], $_FILES["upload_file"]["name"]);
}
?>
<form name="from_file_upload" action="" method="post" enctype="multipart/form-data"> <div class="input-row"> <input type="file" name="upload_file" accept=".jpg,.jpeg,.png"> </div> <input type="submit" name="upload" value="Upload File">
</form>

This quick example shows a simple code to achieve PHP file upload. It has an HTML form to choose a file to upload. Let the form with the following attributes for supporting file upload.

  1. method=post
  2. enctype=multipart/form-data

By choosing a file, it will be in a temporary directory. The $_FILES[“upload_file”][“tmp_name”] has that path. The PHP move_uploaded_file() uploads the file from this path to the specified target.

$_FILES[‘<file-input-name>’][‘tmp_name’] PHP file upload temporary path
$_FILES[‘<file-input-name>’][‘name’] File name with extension
$_FILES[‘<file-input-name>’][‘type’] File MIME type. Eg: image/jpeg
$_FILES[‘<file-input-name>’][‘size’] File size (in bytes)
$_FILES[‘<file-input-name>’][‘error’] File upload error code if any
$_FILES[‘<file-input-name>’][‘full_path’] Full path as sent by the browser

The form allows multi-file upload by having an array of file input.

PHP file upload configuration


Ensure that the server environment has enough settings to upload files.

  • Check with the php.ini file if the file_uploads = on. Mostly, it will be on by default.

More optional directives to change the default settings


  • upload_tmp_dir – to change the system default.
  • upload_max_filesize – to exceed the default limit.
  • max_file_uploads – to break the per-request file upload limit.
  • post_max_size – to breaks the POST data size.
  • max_input_time – to set the limit in seconds to parse request data.
  • max_execution_time – time in seconds to run the file upload script.
  • memory_limit – to set the memory limit in bytes to be allocated.

File upload – server-side validation


When file uploading comes into the picture, then there should be proper validation. It will prevent unexpected responses from the server during the PHP file upload.

This code checks the following 4 conditions before moving the file to the target path. It validates,

  • If the file is not empty.
  • If the file does not already exist in the target.
  • If the file type is one of the allowed extensions.
  • If the file is within the limit.

It shows only the PHP script for validating the uploaded file. The form HTML will be the same as that of the quick example.

file-upload-validation.php

<?php
if (isset($_POST["upload"])) { // Validate if not empty if (!empty($_FILES['upload_file']["name"])) { $fileName = $_FILES["upload_file"]["name"]; $isValidFile = true; // Validate if file already exists if (file_exists($fileName)) { echo "<span>File already exists.</span>"; $isValidFile = false; } // Validate file extension $allowedFileType = array( 'jpg', 'jpeg', 'png' ); $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); if (! in_array($fileExtension, $allowedFileType)) { echo "<span>File is not supported. Upload only <b>" . implode(", ", $allowedFileType) . "</b> files.</span>"; $isValidFile = false; } // Validate file size if ($_FILES["upload_file"]["size"] > 200000) { echo "<span>File is too large to upload.</span>"; $isValidFile = 0; } if ($isValidFile) { move_uploaded_file($_FILES["upload_file"]["tmp_name"], $fileName); } } else { echo "No files have been chosen."; }
}
?>

Upload file to the server with database


This section gives a full-fledged PHP file upload example. It is with add, edit, preview, list images features. The add/edit allows users to choose an image file to upload to the server.

The home page displays a list of uploaded images with edit, delete action controls. The edit screen will show the preview of the existing file.

PHP file upload and add a new row to the database


This code is for showing a HTML form with a file upload option. This allows users to choose files to upload to the server.

The PHP code receives the uploaded file data in $_FILES. In this code, it checks for basic file validation to make sure of its uniqueness.

Then, it calls functions to upload and insert the file path to the database.

The uploadImage runs PHP move_upload_files() to put the uploaded file in a directory.

The insertImage calls database handlers to insert the uploaded path to the database.

image-upload-list-preview-edit/insert.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/lib/ImageModel.php';
$imageModel = new ImageModel();
if (isset($_POST['send'])) { if (file_exists('../uploads/' . $_FILES['image']['name'])) { $fileName = $_FILES['image']['name']; $_SESSION['message'] = $fileName . " file already exists."; } else { $result = $imageModel->uploadImage(); $id = $imageModel->insertImage($result); if (! empty($id)) { $_SESSION['message'] = "Image added to the server and database."; } else { $_SESSION['message'] = "Image upload incomplete."; } } header('Location: index.php');
} ?>
<html>
<head>
<link href="assets/style.css" rel="stylesheet" type="text/css" />
</head>
<body> <div class="form-container"> <h1>Add new image</h1> <form action="" method="post" name="frm-add" enctype="multipart/form-data" on‌submit="return imageValidation()"> <div Class="input-row"> <input type="file" name="image" id="input-file" class="input-file" accept=".jpg,.jpeg,.png"> </div> <input type="submit" name="send" value="Submit" class="btn-link"> <span id="message"></span> </div> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="assets/validate.js"></script>
</body>
</html>

php file upload form

List of uploaded images with edit, delete actions


This is an extension of a usual PHP file upload example. It helps to build a file library interface in an application.

This page reads the uploaded images from the database using PHP.  The getAllImages function returns the image path data in an array format.

The list page iterates this array and lists out the result. And it links the records with the appropriate edit, delete controls.

image-upload-list-preview-edit/index.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/lib/ImageModel.php';
$imageModel = new ImageModel();
?>
<html>
<head>
<title>Display all records from Database</title>
<link href="assets/style.css" rel="stylesheet" type="text/css" />
</head>
<body> <div class="image-datatable-container"> <a href="insert.php" class="btn-link">Add Image</a> <table class="image-datatable" width="100%"> <tr> <th width="80%">Image</th> <th>Action</th> </tr> <?php $result = $imageModel->getAllImages(); ?> <tr> <?php if (! empty($result)) { foreach ($result as $row) { ?> <td><img src="<?php echo $row["image"]?>" class="profile-photo" alt="photo"><?php echo $row["name"]?> </td> <td><a href="update.php?id=<?php echo $row['id']; ?>" class="btn-action">Edit</a> <a on‌click="confirmDelete(<?php echo $row['id']; ?>)" class="btn-action">Delete</a></td> </tr> <?php } } ?> </table> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script type="text/javascript" src="assets/validate.js"></script>
</body> </html>

list uploaded files from server

Edit form with file preview


This shows an edit form with an uploaded file preview. It allows replacing the file by uploading a new one.

The form action passes the id of the record to update the file path in the database.

The PHP code calls the updateImage with the upload result and the record id.

image-upload-list-preview-edit/update.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/lib/ImageModel.php';
$imageModel = new ImageModel();
if (isset($_POST["submit"])) { $result = $imageModel->uploadImage(); $id = $imageModel->updateImage($result, $_GET["id"]);
}
$result = $imageModel->selectImageById($_GET["id"]); ?>
<html>
<head>
<link href="assets/style.css" rel="stylesheet" type="text/css" />
</head>
<body> <div class="form-container"> <h1>View/Edit image</h1> <form action="?id=<?php echo $result[0]['id']; ?>" method="post" name="frm-edit" enctype="multipart/form-data" on‌submit="return imageValidation()"> <div class="preview-container"> <img src="<?php echo $result[0]["image"]?>" class="img-preview" alt="photo"> <div>Name: <?php echo $result[0]["name"]?></div> </div> <div Class="input-row"> <input type="file" name="image" id="input-file" class="input-file" accept=".jpg,.jpeg,.png" value=""> </div> <button type="submit" name="submit" class="btn-link">Save</button> <span id="message"></span> </div> </form> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="assets/validate.js"></script>
</body>
</html>

file edit form with preview

The delete action is triggered after user confirmation. It removes the file path from the database.

delete.php


<?php
namespace Phppot; use Phppot\DataSource;
require_once __DIR__ . '/lib/ImageModel.php';
$imageModel = new ImageModel();
$id=$_REQUEST['id'];
$result = $imageModel->deleteImageById($id);
header("Location: index.php");
?>

PHP model class to upload file


It contains functions to upload files to a directory and to the database. The PHP file upload function sets a target to put the uploaded file.

It processes the PHP $_FILES array to get the file data. It prepares the database query by using the file parameter to perform read, write.

imageModel.php


<?php
namespace Phppot; use Phppot\DataSource; class ImageModel
{ private $conn; function __construct() { require_once 'DataSource.php'; $this->conn = new DataSource(); } function getAllImages() { $sqlSelect = "SELECT * FROM tbl_image"; $result = $this->conn->select($sqlSelect); return $result; } function uploadImage() { $imagePath = "uploads/" . $_FILES["image"]["name"]; $name = $_FILES["image"]["name"]; $result = move_uploaded_file($_FILES["image"]["tmp_name"], $imagePath); $output = array( $name, $imagePath ); return $output; } public function insertImage($imageData) { print_r($imageData); $query = "INSERT INTO tbl_image(name,image) VALUES(?,?)"; $paramType = 'ss'; $paramValue = array( $imageData[0], $imageData[1] ); $id = $this->conn->insert($query, $paramType, $paramValue); return $id; } public function selectImageById($id) { $sql = "select * from tbl_image where id=? "; $paramType = 'i'; $paramValue = array( $id ); $result = $this->conn->select($sql, $paramType, $paramValue); return $result; } public function updateImage($imageData, $id) { $query = "UPDATE tbl_image SET name=?, image=? WHERE id=?"; $paramType = 'ssi'; $paramValue = array( $imageData[0], $imageData[1], $_GET["id"] ); $id = $this->conn->execute($query, $paramType, $paramValue); return $id; } /* * public function execute($query, $paramType = "", $paramArray = array()) * { * $id = $this->conn->prepare($query); * * if (! empty($paramType) && ! empty($paramArray)) { * $this->bindQueryParams($id, $paramType, $paramArray); * } * $id->execute(); * } */ function deleteImageById($id) { $query = "DELETE FROM tbl_image WHERE id=$id"; $result = $this->conn->select($query); return $result; }
}
?>

Upload image as a blob to the database


Though this example comes as the last, I guess it will be very useful for most of you readers.

Uploading the file as a blob to the database helps to move the file binary data to the target database. This example achieves this with very few lines of code.

Uploading image file blob using database insert


This file receives the uploaded file from PHP $_FILES. It extracts the file binary data by using PHP file_get_contents() function.

Then, it binds the file MIME type and the blob to the prepared query statement.

The code specifies the parameter type as ‘b’ for the file blob data. First, it binds a NULL value for the blob field.

Then, it sends the file content using send_long_data() function. This function specifies the query parameter index and file blob to bind it to the statement.

file-blob-upload/index.php

<?php
if (!empty($_POST["submit"])) { if (is_uploaded_file($_FILES['userImage']['tmp_name'])) { $conn = mysqli_connect('localhost', 'root', '', 'blog_eg'); $imgData = file_get_contents($_FILES['userImage']['tmp_name']); $imageProperties = getimageSize($_FILES['userImage']['tmp_name']); $null = NULL; $sql = "INSERT INTO tbl_image_data(image_type ,image_data) VALUES(?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param("sb", $imageProperties['mime'], $null); $stmt->send_long_data(1, $imgData); $stmt->execute(); $currentId = $stmt->insert_id; }
}
?> <html>
<head>
<link href="assets/style.css" rel="stylesheet" type="text/css" />
</head>
<body> <div class="form-container"> <h1>Upload Image Blob</h1> <form action="" method="post" name="frm-edit" enctype="multipart/form-data" > <?php if(!empty($currentId)) { ?> <div class="preview-container"> <img src="image-view.php?image_id=<?php echo $currentId; ?>" class="img-preview" alt="photo"> </div> <?php } ?> <div Class="input-row"> <input type="file" name="userImage" id="input-file" class="input-file" accept=".jpg,.jpeg,.png" value="" required> </div> <input type="submit" name="submit" class="btn-link" value="Save"> <span id="message"></span> </div> </form>
</body>
</html>

This file is to read a blob from the database and show the preview. It will be specified in the <img> tag ‘src’ attribute with the appropriate image id.

file-blob-upload/image-view.php

<?php $conn = mysqli_connect('localhost', 'root', '', 'blog_eg'); if(isset($_GET['image_id'])) { $sql = "SELECT image_type,image_data FROM tbl_image_data WHERE id = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("i", $_GET['image_id']); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_array(); header("Content-type: " . $row["image_type"]); echo $row["image_data"]; } mysqli_close($conn);
?>

php file upload blob to server

Conclusion


Thus, we have seen a detailed article to learn file upload. I swear we have covered most of the examples on PHP file upload.

We saw code in all levels from simple to elaborate file upload components. I hope, this will be helpful to know how to build this on your own.
Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/02/...-database/

Print this item

 
Latest Threads
Insta360 Coupon [INRSGY42...
Last Post: levlotus1998
58 minutes ago
Insta360 Discount Code [I...
Last Post: levlotus1998
59 minutes ago
Insta360 Coupon Codes | I...
Last Post: levlotus1998
1 hour ago
Insta360 Discount Code [I...
Last Post: levlotus1998
1 hour ago
Insta360 Discount Code | ...
Last Post: levlotus1998
1 hour ago
Insta360 Discount Code [I...
Last Post: levlotus1998
1 hour ago
Insta360 Discount Code [I...
Last Post: levlotus1998
1 hour ago
Insta360 Discount Code Ju...
Last Post: levlotus1998
1 hour ago
News - Love And Deepspace...
Last Post: xSicKxBot
1 hour ago
Temu Kod Promocyjny [ald9...
Last Post: lucas03215
3 hours ago

Forum software by © MyBB Theme © iAndrew 2016