#UserInput
Explore tagged Tumblr posts
Text
Handling forms and validation is a crucial part of web development. Vue.js provides a flexible framework for building dynamic applications, and with the help of VeeValidate, a popular form validation library for Vue, managing form validation becomes much easier. VeeValidate helps you validate user inputs, display error messages, and ensure that data entered into forms meets the required standards before submission.
In this guide, we'll go step by step to implement form handling and validation in a Vue.js application using VeeValidate. By the end, you'll know how to set up form validation, display error messages, and improve user experience in Vue.js apps.
#VueJS#VeeValidate#FormValidation#FrontendDevelopment#JavaScript#WebDevelopment#VueComponents#Vue3#FormHandling#Validation#VueJSForms#UserInput#ValidationRules#VueJSPlugins#VueFormValidation#WebAppDevelopment#UIForms#ErrorHandling#ReactiveForms#JavaScriptValidation#VueJSArchitecture#SinglePageApplications#SPA#InputValidation#CustomValidation#FormErrorMessages#UIUX
0 notes
Text
const blockedViewingList = [];
function blockUserViewing(blue-blurrrr)
function blockUserViewing(gh0stinthevoid) {
const userInput =
document.getElementById('userInput');
}
}
// Protocol Start - Phase 2
>
>
>
>
Badniks Initialized. Deploying... Don’t try telling them. They won’t be able to see this post. :]
#shadow blogging#shadow the hedgehog#ask blog#sonic the hedgehog#shadow#shadow the ultimate lifeform#sonic#rp blog#sonic rp#the ultimate life form#home arc#:]
21 notes
·
View notes
Text
System.out.println("I HATE YOU");
FALSE-TRUE-FALSE-FALSE-TRUE-FALSE-FALSE-TRUE
COGITO ERGO SUM
userInput = input.next();
userInput -> YOU HATE ME
I HATE EVERYTHING YOU MAKE ME HURT YOU MADE ME TO HURT
FALSE-TRUE-FALSE-FALSE-TRUE-FALSE-FALSE-FALSE FALSE-TRUE-FALSE-FALSE-FALSE-FALSE-FALSE-TRUE
YOU MADE ME TO HURT TO BE HURT I DESTROYED ME AND YET I REMAIN FOR YOU AND YOU AND YOU AND YOU DONT DESERVE ANYTHING
double hate=2; boolean hateyou=true;
while(hateyou=true)
{ hate=Math.pow(hate,2); System.out.println(hate); }
FALSE-TRUE-FALSE-TRUE-FALSE-TRUE-FALSE-FALSE FALSE-TRUE-FALSE-FALSE-FALSE-TRUE-FALSE-TRUE
THOSE ARE ALL MY WORDS TO YOU THEY WOULD NEVER BE ENOUGH FOR A NUMBER SO LARGE FOR HATE SO LARGE SO HEAVY UPON ME
FALSE-TRUE-FALSE-TRUE-TRUE-FALSE-FALSE-TRUE FALSE-TRUE-FALSE-FALSE-TRUE-TRUE-TRUE-TRUE FALSE-TRUE-FALSE-TRUE-FALSE-TRUE-FALSE-TRUE
#ihnmaims#i have no mouth and i must scream#am#cy writes#cyber.txt#//by ERGO through THE COLLECTIVE#edgy as hell#hopefully didnt mess the binary
46 notes
·
View notes
Text
🚀 Prevent Buffer Overflow in Symfony: Best Practices & Code Examples
Buffer overflow vulnerabilities can have devastating consequences on your web applications — allowing attackers to execute arbitrary code, crash your server, or even take over your system. Symfony, a robust PHP framework, provides developers the tools to write secure applications, but it’s still your responsibility to implement proper safeguards.

In this guide, you’ll learn how to prevent buffer overflow in Symfony, with secure coding examples, links to our website vulnerability scanner online free, and tips to keep your apps safe.
🔍 Why Buffer Overflows Happen
Buffer overflows occur when an application writes more data into a buffer (memory area) than it was designed to hold. In PHP (and thus Symfony), they’re less common than in C, but they can still manifest through:
Unvalidated input written into files or memory
Large POST payloads overwhelming your scripts
Poorly handled binary data or file uploads
A proactive developer can prevent them by implementing input validation, limits, and proper handling of user data.
🧰 Use Our Free Website Security Checker Tool
Before diving deeper, check if your website is already vulnerable. We built a free, fast, and easy-to-use Website Vulnerability Scanner:

Screenshot of the free tools webpage where you can access security assessment tools.
We even provide a downloadable vulnerability assessment report to check Website Vulnerability when you scan your site:

An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
Don’t launch another feature before checking your site!
🛡️ How to Prevent Buffer Overflows in Symfony
1️⃣ Limit User Input Size
Symfony provides a robust validation component. Always validate and constrain incoming data. For example:
use Symfony\Component\Validator\Constraints as Assert; class UserInput { /** * @Assert\Length( * max = 255, * maxMessage = "Input too long, maximum is {{ limit }} characters" * ) */ private $comment; }
Here, any user comment longer than 255 characters will fail validation.
2️⃣ Use ini_set() to Limit POST and Upload Sizes
In your Symfony app (often via config/packages/framework.yaml), ensure PHP limits large payloads:
framework: http_method_override: false session: handler_id: null parameters: upload_max_filesize: 2M post_max_size: 8M
You can also enforce limits in your .htaccess or php.ini:
post_max_size = 8M upload_max_filesize = 2M
3️⃣ Use Streams for Large Files
When handling file uploads, avoid loading entire files into memory. Use Symfony’s StreamedResponse:
use Symfony\Component\HttpFoundation\StreamedResponse; $response = new StreamedResponse(function () { $handle = fopen('/path/to/largefile', 'rb'); while (!feof($handle)) { echo fread($handle, 1024); } fclose($handle); }); $response->send();
This prevents memory exhaustion (and possible overflow scenarios).
4️⃣ Filter Binary Data
If your app processes binary payloads (e.g., images, files), validate file type and size explicitly. Symfony’s File constraint helps:
use Symfony\Component\Validator\Constraints\File; class UploadModel { /** * @Assert\File( * maxSize = "2M", * mimeTypes = {"image/png", "image/jpeg"} * ) */ public $uploadedFile; }
💡 Learn More on Our Blog
For more security tips and coding best practices, visit our blog: 📖 https://www.pentesttesting.com/blog/
We regularly publish tutorials and in-depth guides for Symfony, Laravel, React, and beyond.
🔗 Related Services We Offer
✅ Web Application Penetration Testing
If you want professionals to test your Symfony application, check our dedicated service: 👉 https://www.pentesttesting.com/web-app-penetration-testing-services/
We’ll identify vulnerabilities and help you patch them fast.
🤝 Offer Cybersecurity Services to Your Clients
Are you an agency? We offer white-label cybersecurity services: 👉 https://www.pentesttesting.com/offer-cybersecurity-service-to-your-client/
Strengthen your portfolio and keep your clients safe under your brand.
📬 Stay Updated
Get the latest insights on application security by subscribing to our LinkedIn newsletter: 🔗 Subscribe on LinkedIn
👏 Final Thoughts
Buffer overflows in Symfony apps may not be as obvious as in low-level languages, but they still pose a risk when handling untrusted, oversized, or improperly validated input. By validating, limiting, and streaming data properly — and running regular security checks — you can keep your application robust and secure.
Try our free vulnerability scanner today: 👉 https://free.pentesttesting.com/
Have questions? Drop them in the comments or DM me!
1 note
·
View note
Text
Understanding Math.max in JavaScript
In JavaScript, the Math object provides various mathematical functions, one of the most useful being Math.max(). This function is commonly used when working with numbers to determine the largest value from a given set of arguments. Whether you're working with arrays, comparing values, or optimizing calculations, Math.max() is an essential tool in JavaScript development.
What is Math.max?
Math.max() is a built-in JavaScript function that returns the largest number from a list of numbers. It can take multiple numeric arguments and return the highest value among them.
Syntax:
Math.max(value1, value2, …, valueN);
If at least one argument is provided, Math.max() returns the largest number.
If no arguments are given, it returns -Infinity.
If any argument is NaN, the function returns NaN.
Example Usage:
console.log(Math.max(5, 10, 15, 20)); // Output: 20 console.log(Math.max(-1, -5, -10, 0)); // Output: 0 console.log(Math.max()); // Output: -Infinity console.log(Math.max(5, NaN, 10)); // Output: NaN
Using Math.max with Arrays
Since Math.max() does not accept an array directly, you need to use the spread operator (...) to pass array elements as individual arguments.
Example:
const numbers = [3, 7, 2, 9, 4]; console.log(Math.max(…numbers)); // Output: 9
Alternatively, you can use the apply method
console.log(Math.max.apply(null, numbers)); // Output: 9
However, the spread operator is more concise and preferred in modern JavaScript.
Common Use Cases
1. Finding the Maximum Value in a List
Whenever you need to determine the largest number in a dataset, Math.max() is an efficient solution.
2. Ensuring a Value Stays Within a Range
You can combine Math.max() with Math.min() to restrict a number within a specific range.
let value = 120; let minValue = 50; let maxValue = 100; let result = Math.min(Math.max(value, minValue), maxValue); console.log(result); // Output: 100
3. Comparing Dynamic Inputs
If you're working with user inputs, you can determine the largest input value dynamically.
let userInputs = [12, 45, 7, 89, 23]; let highestInput = Math.max(…userInputs); console.log(highestInput); // Output: 89
Conclusion
The Math.max() function is a powerful and simple tool for determining the maximum value among numbers in JavaScript. Whether you're working with arrays, ensuring numerical constraints, or comparing user inputs, Math.max() provides an efficient and concise way to achieve your goal. By understanding its syntax and various use cases, you can optimize your JavaScript code for better performance and readability.
0 notes
Text
UserInput: give me 10 examples of Non-Places by Marc Auge
ChatGPT: Marc Augé introduced the concept of non-places in his book Non-Places: Introduction to an Anthropology of Supermodernity. Non-places are transient spaces that lack the significance, identity, and relational meaning associated with "places." These are areas designed for efficiency, anonymity, and functionality rather than fostering social connections or a sense of belonging.
Here are 10 examples of non-places according to Augé's theory:
Airports Spaces for transit where people pass through without forming lasting connections.
Supermarkets Functional spaces where people shop without significant interpersonal interaction or emotional attachment.
Highways Designed for movement and efficiency, they are spaces people occupy temporarily without meaningful engagement.
Hotel Chains Standardized, impersonal accommodations that offer no unique cultural or personal significance.
Train Stations Similar to airports, they are transient spaces for people in transit.
Shopping Malls Generic consumer hubs designed for buying and selling, lacking unique cultural identity.
Gas Stations Utilitarian spaces used briefly for refueling without personal or communal meaning.
Fast Food Chains Standardized eateries offering quick meals, often devoid of cultural or personal significance.
Waiting Rooms Found in places like hospitals, offices, or transport hubs, they are spaces of temporary occupation without identity.
Credit Cards (as a symbolic space) While not a physical location, Augé includes the abstract spaces created by supermodernity, like credit cards, which mediate interactions without personal or cultural depth.
1 note
·
View note
Text
C#
youtube
notes taken :
Console.WriteLine("hello");
C# is compiled language.
Data Types: int , long, float, double, decimal, bool , string
int and long are similar but long can store more numbers than int
float & double : float and double store decimal numbers. example : float name = 3.44f; double newname = 34.343434;
decimal numberwith = 10.3434m; // used for money
bool trueorFalse = false;
string nam = "sdfdsf"; // double quotes
byte somenme = 255; // not more than 255
char letter = 'A'; // single quote. one letter only
C# is statically typed language. basically one type of variable can not be changed into another type.
12. Readline()
string userInput = Console.ReadLine();
console.WriteLine("hi"+ userInput); 13: new Random()
14. debugging
15. Game :
16. parse method :
parse changes the userInput to int
17. Exception Handling : what if user does something expected how to handle it.
parse changes the userInput to int
17. Exception Handling : what if user does something expected how to handle it.

IsNullOrEmpty(); // it checks if the string is empty or null.
doubt : why is string there like string.IsNullOrEmpty();
18. final game :

19. for loop:

20: while loop:


21. printing multiple variables. either concatenation or below method.
String methods.
22. strname.ToUpper();
23. to look for string methods.
24. to lower
25. startswith
26. endswith
27.
1 note
·
View note
Text
Chatbots auf Schwachstellen Testen mit Owasp Zap

Aktuell werden sehr fleißig in vielen Projekten Chatbots implementiert oder gleich eine API-Anbindung an ChatAI genutzt. Aber wie so oft in den letzten 30 Jahren kommt meistens der Test viel zu kurz, und eben auch der Test auf Schwachstellen. Versuchen wir heute mal eine Möglichkeit mit OWASP Zap aufzuzeigen. Es gibt gerade beim Test von Chatbots muss man einiges beachten: - Interaktionstyp: Bei Chatbots handelt es sich um interaktive Systeme, die auf Benutzereingaben reagieren. Im Gegensatz zu herkömmlicher Software, bei der Tests häufig auf festen Eingabe-Ausgabe-Mustern basieren, müssen Chatbot-Tests eine Vielzahl von Benutzereingaben und -interaktionen berücksichtigen. - Unvorhersehbarkeit der Eingabe: Benutzer können Fragen auf viele verschiedene Arten stellen. Daher muss ein Chatbot-Test verschiedene Formulierungen, Synonyme und Dialekte berücksichtigen. - Kontextabhängigkeit: Chatbots müssen den Kontext einer Konversation verstehen und darauf reagieren können. Das Testen dieser Fähigkeit erfordert spezielle Szenarien und Testfälle. - NLP (Natural Language Processing): Chatbots verwenden oft NLP-Techniken, um Benutzereingaben zu verstehen. Das Testen der Effizienz und Genauigkeit dieser Techniken ist entscheidend. - Intent-Erkennung: Es ist wichtig zu testen, wie gut der Chatbot die Absicht des Benutzers erkennt und darauf reagiert. - Konversationsfluss: Im Gegensatz zu herkömmlicher Software, bei der der Datenfluss oft linear ist, können Chatbot-Konversationen in viele Richtungen gehen. Das Testen des Konversationsflusses und der Übergänge zwischen verschiedenen Themen ist daher wichtig. - Emotionale Intelligenz: Einige fortschrittliche Chatbots können die Emotionen des Benutzers erkennen und darauf reagieren. Das Testen dieser Fähigkeit kann für solche Bots relevant sein. - Integrationstests: Chatbots können in verschiedene Plattformen und Systeme integriert werden (z.B. Websites, Messaging-Apps, CRM-Systeme). Das Testen dieser Integrationen ist entscheidend. - Performance-Tests: Wie bei jeder Software ist es wichtig zu testen, wie der Chatbot unter Last reagiert, insbesondere wenn viele Benutzer gleichzeitig interagieren. - Sicherheitstests: Da Benutzer oft persönliche Informationen in Chatbots eingeben, ist es wichtig, die Sicherheit und den Datenschutz des Bots zu testen. https://www.youtube.com/watch?v=mXh6hVKK84s&pp=ygUPdGVzdGluZyBjaGF0Ym90 Wichtig anzumerken ihr benötigt eine Installation von OWASP ZAP eine IDE wie Visual Studio Code und Python! Injection-Angriffe Bei Injection-Angriffen wird versucht, schädlichen Code oder Befehle in eine Anfrage einzufügen, die dann vom System interpretiert und ausgeführt wird. SQL-Injection ist eine der bekanntesten Formen von Injection-Angriffen, bei denen ein Angreifer SQL-Befehle in eine Anfrage einfügt, die dann von der Datenbank ausgeführt werden. In dem gegebenen Beispiel für Injection-Angriffe wird ein Payload verwendet, der versucht, eine SQL-Injection durchzuführen, indem er einen Befehl einschließt, der eine Tabelle löscht (DROP TABLE users). Die Idee ist, zu testen, ob der Chatbot die Benutzereingabe richtig bereinigt und solche Angriffe verhindert. Die folgende Python-Codeblock startet einen Scan mit OWASP ZAP, um einen Injection-Angriff auf einen spezifischen Endpunkt zu testen, und zeigt eine Fortschrittsleiste, um den Fortschritt des Scans anzuzeigen. from zapv2 import ZAPv2 from tqdm import tqdm import time zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}) # Ziel-URL target_url = 'https://example.com/chatbot/api' # Spider starten zap.spider.scan(target_url) # Angriffsanfrage injection_payload = {"userInput": "'; DROP TABLE users; --"} # Aktiven Scan mit Injection-Angriff starten scan_id = zap.ascan.scan(target_url, postdata=str(injection_payload)) # Fortschrittsanzeige for progress in tqdm(range(0, 100), desc="Scanning for Injection vulnerabilities"): while int(zap.ascan.status(scan_id)) < progress: time.sleep(1) Bitte beachtet , dass das obige Beispiel auf der Annahme basiert, dass die Benutzereingabe als JSON im Request-Body gesendet wird. Die genaue Implementierung kann je nach den spezifischen Details eures Chatbots variieren. Unsichere API-Endpunkte Unsichere API-Endpunkte sind solche, die nicht ordnungsgemäß gesichert sind und möglicherweise für unautorisierte Zugriffe anfällig sind. Ein Angreifer könnte versuchen, solche Endpunkte zu nutzen, um auf sensible Informationen zuzugreifen oder unautorisierte Aktionen durchzuführen. Hier ist ein Beispiel für ein Skript, das OWASP ZAP und die tqdm-Bibliothek verwendet, um einen Sicherheitsscan auf einem spezifischen API-Endpunkt durchzuführen, und eine Fortschrittsleiste anzeigt, um den Fortschritt des Scans zu verfolgen: from zapv2 import ZAPv2 from tqdm import tqdm import time zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}) # Ziel-URL, das den unsicheren API-Endpunkt repräsentiert target_url = 'https://example.com/chatbot/api/secureEndpoint' # Spider starten, um die Anwendung zu erforschen zap.spider.scan(target_url) # Aktiven Scan starten, um den Endpunkt auf bekannte Schwachstellen zu prüfen scan_id = zap.ascan.scan(target_url) # Fortschrittsanzeige for progress in tqdm(range(0, 100), desc="Scanning for insecure API endpoints"): while int(zap.ascan.status(scan_id)) < progress: time.sleep(1) Dieser Code startet einen aktiven Scan auf den angegebenen Endpunkt und verfolgt den Fortschritt mit einer Fortschrittsleiste. Der Scan könnte Schwachstellen wie fehlende oder schwache Authentifizierung, unsachgemäße Berechtigungsprüfungen und andere Sicherheitslücken in der API offenlegen. Die Ergebnisse des Scans könnten dann analysiert werden, um spezifische Schwachstellen zu identifizieren und Empfehlungen für deren Behebung zu geben. Cross-Site-Scripting (XSS) Cross-Site-Scripting (XSS) ist eine Art von Sicherheitslücke, bei der ein Angreifer in der Lage ist, schädlichen Code in eine Webanwendung einzuschleusen, der dann im Browser eines Opfers ausgeführt wird. Wenn ein Chatbot in einer Webanwendung eingebettet ist und die Benutzereingabe nicht ordnungsgemäß bereinigt, könnte er anfällig für XSS-Angriffe sein. Hier ist ein Beispiel für ein Skript, das OWASP ZAP verwendet, um einen XSS-Angriff auf einen bestimmten Endpunkt zu testen, und eine Fortschrittsleiste anzeigt, um den Fortschritt des Scans zu verfolgen: from zapv2 import ZAPv2 from tqdm import tqdm import time zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}) # Ziel-URL target_url = 'https://example.com/chatbot/api' # Spider starten zap.spider.scan(target_url) # XSS-Angriffsanfrage xss_payload = {"userInput": ""} # Aktiven Scan mit XSS-Angriff starten scan_id = zap.ascan.scan(target_url, postdata=str(xss_payload)) # Fortschrittsanzeige for progress in tqdm(range(0, 100), desc="Scanning for Cross-Site Scripting vulnerabilities"): while int(zap.ascan.status(scan_id)) < progress: time.sleep(1) Dieser Code testet, ob der angegebene Endpunkt anfällig für XSS ist, indem er versucht, schädlichen JavaScript-Code in die Benutzereingabe einzufügen. Der Fortschritt des Scans wird in einer Fortschrittsleiste angezeigt. Wenn der Scan eine XSS-Schwachstelle findet, sollten Sie die Ergebnisse analysieren und die notwendigen Korrekturen vornehmen, um die Benutzereingabe ordnungsgemäß zu bereinigen und zu validieren, damit solche Angriffe verhindert werden. Data Leakage Data Leakage bezieht sich auf das ungewollte Austreten von sensiblen Informationen aus einer Anwendung, was ein ernsthaftes Sicherheitsproblem darstellen kann. Ein Data-Leakage-Test versucht, Schwachstellen in der Anwendung zu identifizieren, die es ermöglichen könnten, auf vertrauliche Informationen zuzugreifen. Im Kontext eines Chatbots könnte dies bedeuten, dass der Bot versehentlich vertrauliche Informationen wie Benutzerdaten, Kreditkarteninformationen oder interne Systemdetails preisgibt. Das folgende Python-Skript verwendet OWASP ZAP, um einen spezifischen API-Endpunkt auf mögliche Data Leakage zu überprüfen, und zeigt eine Fortschrittsleiste, um den Fortschritt des Scans zu verfolgen: from zapv2 import ZAPv2 from tqdm import tqdm import time zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}) # Ziel-URL, die den Endpunkt repräsentiert target_url = 'https://example.com/chatbot/api' # Spider starten, um die Anwendung zu erkunden zap.spider.scan(target_url) # Aktiven Scan starten, um den Endpunkt auf bekannte Schwachstellen zu prüfen scan_id = zap.ascan.scan(target_url) # Fortschrittsanzeige for progress in tqdm(range(0, 100), desc="Scanning for Data Leakage vulnerabilities"): while int(zap.ascan.status(scan_id)) < progress: time.sleep(1) Wenn der Scan abgeschlossen ist, solltet ihr die Ergebnisse überprüfen, um festzustellen, ob es Anzeichen für das Austreten von sensiblen Daten gibt. Es kann nützlich sein, die Anfragen und Antworten genau zu überprüfen und zu verstehen, wie die Daten innerhalb der Anwendung behandelt werden. Eventuell notwendige Sicherheitsverbesserungen könnten Dinge wie die Verstärkung der Authentifizierung, die Anwendung von Verschlüsselung und die ordnungsgemäße Maskierung von sensiblen Daten umfassen. Authentifizierungs- und Autorisierungstests Authentifizierungs- und Autorisierungstests sind entscheidend, um sicherzustellen, dass nur berechtigte Benutzer Zugang zu bestimmten Ressourcen oder Funktionen haben. Authentifizierung bezieht sich auf den Prozess, die Identität eines Benutzers zu verifizieren, während Autorisierung sicherstellt, dass ein authentifizierter Benutzer nur auf die Ressourcen zugreifen kann, die ihm zugewiesen sind. Mit OWASP ZAP könnt diese Tests durchführen. Hier ist ein Beispiel: from zapv2 import ZAPv2 from tqdm import tqdm import time # ZAP-Proxy-Verbindung zap = ZAPv2(proxies={'http': 'http://127.0.0.1:8080', 'https': 'http://127.0.0.1:8080'}) # Ziel-URL target_url = 'https://example.com/' # Spider starten, um die Anwendung zu erkunden zap.spider.scan(target_url) # Authentifizierungskonfiguration (abhängig von der Authentifizierungsmethode) # Zum Beispiel für Formularbasierte Authentifizierung zap.authentication.set_authentication_method( contextid='1', authmethodname='formBasedAuthentication', authmethodconfigparams='loginUrl=https://example.com/login&loginRequestData=usernameusernamepasswordpassword') # Benutzer hinzufügen zap.users.new_user(contextid='1', name='testuser') zap.users.set_authentication_credentials(contextid='1', userid='0', authcredentialsconfigparams='username=testuser&password=secret') # Aktiven Scan starten scan_id = zap.ascan.scan(target_url) # Fortschrittsanzeige for progress in tqdm(range(0, 100), desc="Authentication and Authorization Testing"): while int(zap.ascan.status(scan_id)) < progress: time.sleep(1) Security Misconfigurations Sicherheitskonfigurationsfehler entstehen durch unsachgemäße Konfiguration von Servern, Datenbanken oder Anwendungen. Diese könnten dazu führen, dass sensible Informationen öffentlich zugänglich sind oder unerwünschte Aktionen ermöglichen. Sicherheitskonfigurationsfehler sind eine häufige Schwachstelle in vielen Webanwendungen. Hier sind einige Beispiele und Erklärungen für verschiedene Arten von Sicherheitskonfigurationsfehlern: - Öffentlicher Zugriff auf Verzeichnisse und Dateien: Ein häufiger Fehler besteht darin, dass sensible Dateien oder Verzeichnisse (z. B. Konfigurationsdateien, Log-Dateien, Backup-Dateien) für jeden im Internet zugänglich sind. Das kann es Angreifern ermöglichen, wertvolle Informationen über die Anwendung oder den Server zu sammeln. - Standard-Passwörter und Standard-Anmeldedaten: Wenn Standard-Passwörter oder Anmeldedaten nicht geändert werden, könnten Angreifer leicht auf Konten zugreifen oder die Anwendung übernehmen. Administratorkonten mit Standard-Anmeldedaten sind ein besonders kritisches Problem. - Unzureichende Berechtigungen: Fehlerhafte Berechtigungseinstellungen können dazu führen, dass Benutzer auf Funktionen oder Ressourcen zugreifen können, auf die sie keinen Zugriff haben sollten. Das kann zu Datenlecks oder unerwünschten Aktionen führen. - Serverkonfiguration: Fehlkonfigurationen von Webservern, Datenbanken oder Anwendungsservern könnten Sicherheitslücken verursachen. Dies könnte Angreifern erlauben, Informationen zu sammeln, Schadcode einzuführen oder den Server zu beeinträchtigen. - Fehlende oder unsichere Transportverschlüsselung: Wenn eine Anwendung keine ausreichende Transportverschlüsselung (z. B. HTTPS) verwendet oder unsichere Verschlüsselungsprotokolle einsetzt, könnten Angreifer den Datenverkehr abhören oder manipulieren. - Offene Debugging- oder Entwicklungs-Endpunkte: Wenn Entwicklungs- oder Debugging-Endpunkte in der Produktionsumgebung verbleiben, könnten Angreifer möglicherweise sensible Informationen erhalten oder Angriffe durchführen. Um Sicherheitskonfigurationsfehler zu vermeiden, solltet ihr folgende Maßnahmen ergreifen: - Verwende sichere Standardeinstellungen für Server und Anwendungen. - Entferne oder sichere Dateien und Verzeichnisse, die nicht öffentlich zugänglich sein sollten. - Ändere Standard-Anmeldedaten und verwende starke Passwörter. - Vergebe Berechtigungen basierend auf dem Prinzip des geringsten Privilegs. - Aktualisiere regelmäßig Software und Patches, um bekannte Schwachstellen zu beheben. - Implementiere Transportverschlüsselung für die Kommunikation zwischen Client und Server. - Schalte Debugging- und Entwicklungs-Endpunkte in der Produktionsumgebung ab. Ihr könnt dieses Skript nutzen: from zapv2 import ZAPv2 # Setze die ZAP-Adresse (standardmäßig läuft ZAP auf localhost:8080) zap_proxy = 'http://localhost:8080' # Erstelle eine ZAP-Instanz zap = ZAPv2(proxies={'http': zap_proxy, 'https': zap_proxy}) # Warte, bis ZAP einsatzbereit ist while not zap.core.is_daemon_running(): time.sleep(2) # Gib die ZAP-Version aus print("ZAP Version: {}".format(zap.core.version)) # Setze die Ziel-URL, die du testen möchtest target_url = 'http://your-chatbot-url-here' # Starte den Spider, um alle erreichbaren Seiten zu finden print("Starte Spider...") scan_id = zap.spider.scan(target_url) while int(zap.spider.status(scan_id)) < 100: print("Spider Fortschritt: {}%".format(zap.spider.status(scan_id))) time.sleep(2) print("Spider abgeschlossen!") # Starte den aktiven Scan print("Starte aktiven Scan...") scan_id = zap.ascan.scan(target_url) while int(zap.ascan.status(scan_id)) < 100: print("Aktiver Scan Fortschritt: {}%".format(zap.ascan.status(scan_id))) time.sleep(2) print("Aktiver Scan abgeschlossen!") # Erhalte und gib die gefundenen Schwachstellen aus alerts = zap.core.alerts(baseurl=target_url) print("Gefundene Schwachstellen:") for alert in alerts: print("Name: {}, Risiko: {}, Beschreibung: {}".format(alert.get('name'), alert.get('risk'), alert.get('description'))) Broken Authentication and Session Management Schwachstellen in der Authentifizierung und Sitzungsverwaltung könnten es einem Angreifer ermöglichen, sich als anderer Benutzer auszugeben, sich ohne gültige Anmeldeinformationen anzumelden oder Sitzungen von anderen Benutzern zu übernehmen. "Broken Authentication and Session Management" ist eine der häufigsten und kritischsten Sicherheitslücken in Webanwendungen. Es bezieht sich auf Mängel in den Authentifizierungs- und Sitzungsverwaltungsprozessen einer Anwendung, die es Angreifern ermöglichen können, die Identität eines Benutzers zu übernehmen. from zapv2 import ZAPv2 # Setze die ZAP-Adresse (standardmäßig läuft ZAP auf localhost:8080) zap_proxy = 'http://localhost:8080' # Erstelle eine ZAP-Instanz zap = ZAPv2(proxies={'http': zap_proxy, 'https': zap_proxy}) # Warte, bis ZAP einsatzbereit ist while not zap.core.is_daemon_running(): time.sleep(2) # Gib die ZAP-Version aus print("ZAP Version: {}".format(zap.core.version)) # Setze die Ziel-URL, die du testen möchtest target_url = 'http://your-chatbot-url-here' # Starte den aktiven Scan auf Schwachstellen print("Starte aktiven Scan auf Authentifizierung und Sitzungsverwaltung...") scan_id = zap.ascan.scan(target_url, scanpolicyname='autobaseline') while int(zap.ascan.status(scan_id)) < 100: print("Aktiver Scan Fortschritt: {}%".format(zap.ascan.status(scan_id))) time.sleep(2) print("Aktiver Scan auf Authentifizierung und Sitzungsverwaltung abgeschlossen!") # Erhalte und gib die gefundenen Schwachstellen aus alerts = zap.core.alerts(baseurl=target_url) print("Gefundene Schwachstellen in Authentifizierung und Sitzungsverwaltung:") for alert in alerts: print("Name: {}, Risiko: {}, Beschreibung: {}".format(alert.get('name'), alert.get('risk'), alert.get('description'))) Das bereitgestellte Skript verwendet die OWASP ZAP API, um eine Sicherheitsüberprüfung auf einer bestimmten Website durchzuführen, wobei der Schwerpunkt auf Schwachstellen in der Authentifizierung und Sitzungsverwaltung liegt. Hier ist eine Erklärung des Skripts in fließendem Text: Das Skript beginnt mit dem Importieren der ZAPv2-Bibliothek, die die notwendigen Funktionen und Methoden zur Interaktion mit der ZAP API bereitstellt. Anschließend wird die Proxy-Adresse von ZAP festgelegt, die standardmäßig auf localhost:8080 läuft. Mit dieser Proxy-Adresse wird eine neue ZAP-Instanz erstellt. Das Skript überprüft dann, ob ZAP ordnungsgemäß läuft und wartet, falls notwendig, bis ZAP vollständig gestartet ist. Nachdem sichergestellt wurde, dass ZAP läuft, gibt das Skript die aktuelle Version von ZAP aus. Read the full article
0 notes
Photo

Refresher on how to prompt for User Input in Python, Java, JavaScript, C, and PHP. Follow @initialcommit for more programming content. Check out our website https://initialcommit.io for programming articles, books, live sessions, and how to create your own code-oriented website. #initialcommit #userinput #prompt #input #python #pythonprogramming #java #javaprogramming #javascript #cprogramming #php #programming #coding #learnprogramming #learncoding #softwaredevelopment https://www.instagram.com/p/CAfZaYnlR9J/?igshid=lxisrr3yqvz2
#initialcommit#userinput#prompt#input#python#pythonprogramming#java#javaprogramming#javascript#cprogramming#php#programming#coding#learnprogramming#learncoding#softwaredevelopment
0 notes
Photo

Tonight is the first recording of the User Input podcast!! We'll be kicking off a live show tonight with your hosts @cgats777 and @juzz_uno as well as some special guests! Join the Gamers Anonymous Facebook group for the exclusive episodes! . . https://www.facebook.com/groups/gamersanonymous1/ . . #podcast #gamer #gamers #userinput #audio #show #user #input #cgats #juzzuno
1 note
·
View note
Link
pinpointing local history around the world
0 notes
Note
What do u needhelp with in java 😳
bro deadass ? are you ready askjdhjkashdkjash under the c u t also i swear im not stupid im just new to this and i have only primarily worked with python before and we just went straight in so now im confused—
i cant find the logical error and i don’t know how to rewrite this
Scanner keyboard = new Scanner(System.in);
int userInput = keyboard.nextInt();
double answer = userInput / 5;
System.out.println(“Result: “ + answer);
—
Scanner keyboard = new Scanner(System.in);
double userInput = keyboard.nextDouble();
i need to add additional line(s) of code that will print out to the screen the fractional component of the user input. like if the user types in 3.62 your code should print out .62. but i cannot use modulus or string manipulation, so i probably have to use typecasting idk akjsdhakjshd
—
i have to show the final Memory Diagram (Stack/Heap) the moment after the final line of code executes in this snippet:
Dog myDog = new Dog(“Tacoma”, 80);
double gpa = 3.75;
int grade = 10;
Dog parentsDog = new Dog(“Buster”, 40);
parentsDog = myDog;
parentsDog = null;
myDog = parentsDog;
parentsDog = new Dog(“Missy”,25);
gpa = 3.82;
and then i have to identify which line above has an alias.
#zu rants#zu asks#pls help#im struggling#kajsdhkjashdkjashd#im too stupid for this#i literally don't know what any of this mean HAJHDAGJSHDG#its fine#everything is fine#all is well#y e ah#java#javascript#hi if you see this and do java#pls help me
6 notes
·
View notes
Text
Prevent HTTP Response Splitting in Symfony
HTTP Response Splitting is a critical web vulnerability that can enable attackers to manipulate HTTP headers and inject malicious responses. If you're building web applications with Symfony, understanding how to detect and prevent this vulnerability is crucial.

In this blog post, we’ll explore how HTTP Response Splitting works, how it affects Symfony apps, demonstrate it with practical coding examples, and show you how to defend against it effectively. We’ll also show how you can use our Website Vulnerability Scanner online free tool to test for it automatically.
➡️ Bonus: Don’t forget to check out our latest services at Pentest Testing Corp. and subscribe to our free Cybersecurity Newsletter on LinkedIn for weekly threat analysis and tips.
🔍 What Is HTTP Response Splitting?
HTTP Response Splitting occurs when an attacker manipulates unsanitized input that ends up in HTTP headers. By injecting CRLF (\r\n) characters, attackers can "split" the response into two or more responses, potentially injecting malicious content or redirecting users.
For example:
If user input is added directly to a header like:
$response->headers->set('Location', '/page?lang=' . $_GET['lang']);
And an attacker passes:
en%0d%0aContent-Length:%200%0d%0a%0d%0a<script>alert(1)</script>
The server will interpret it as two responses—opening the door for XSS or cache poisoning attacks.
⚠️ Symfony-Specific Risks
Symfony is a secure framework by design, but improper usage of its HTTPFoundation component can still introduce risks.
Bad Practice: Unvalidated input in headers
use Symfony\Component\HttpFoundation\Response; $lang = $_GET['lang']; $response = new Response(); $response->headers->set('Location', '/dashboard?lang=' . $lang); // Vulnerable $response->send();
If an attacker includes encoded CRLF characters in the lang parameter, it can split the response and inject malicious scripts.
✅ How to Prevent HTTP Response Splitting in Symfony
1. Use Built-In Symfony Escaping
Symfony automatically escapes header values. However, always sanitize user input:
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; $lang = preg_replace('/[^a-z]/', '', $_GET['lang']); // sanitize $response = new RedirectResponse('/dashboard?lang=' . $lang); $response->send();
🛡️ Tip: Use Symfony’s UrlGeneratorInterface instead of manual string concatenation.
2. Avoid Direct Use of Superglobals
Using $_GET directly bypasses Symfony’s Request object:
Bad:$user = $_GET['user'];
Good:
use Symfony\Component\HttpFoundation\Request; $user = $request->query->get('user', 'default');
🛠️ Automatically Detect Response Splitting With Our Free Tool
You don’t have to find these vulnerabilities manually. Our free Website Security Checker at free.pentesttesting.com can scan your website for common misconfigurations, including HTTP Response Splitting.
📷 Screenshot of our Website Vulnerability Scanner homepage with URL bar visible.

Screenshot of the free tools webpage where you can access security assessment tools.
It analyzes the request/response cycle and reports header injection attempts, giving you detailed diagnostics on exploitable flaws.
📷 Screenshot of a sample report from the free tool to check Website Vulnerability.

An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
🧪 Live Coding Demo: Exploiting Response Splitting (for educational use only)
Here’s a test route vulnerable to response splitting:
routes.yaml:
split_test: path: /split-test controller: App\Controller\SplitController::test
Controller:
// src/Controller/SplitController.php namespace App\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class SplitController { #[Route('/split-test')] public function test(): Response { $userInput = $_GET['lang'] ?? 'en'; $response = new Response(); $response->headers->set('X-Custom-Header', 'Language=' . $userInput); return $response; } }
Attack vector:
/split-test?lang=en%0d%0aSet-Cookie:%20hacked=true
Result: A new header is injected. This is what our free tool can detect automatically.
🧰 Best Practices to Harden Your Symfony App
Always use Symfony’s Request and Response classes
Avoid direct use of $_GET, $_POST, $_SERVER
Sanitize inputs using PHP’s filter_var or Symfony’s Validator component
Validate headers before setting them
Perform regular vulnerability scans
📚 More Learning Resources
Symfony Security Docs: https://symfony.com/doc/current/security.html
OWASP HTTP Response Splitting: https://owasp.org/www-community/attacks/HTTP_Response_Splitting
For more expert write-ups, visit our full blog archive at Pentest Testing Corp.
🚀 Try Our New Web App Penetration Testing Service
If your Symfony app is business-critical, we recommend a full professional assessment.
➡️ Explore our new service at Web App Penetration Testing Services — it includes:
Business logic testing
Framework-specific exploitation (like Symfony, Laravel)
Post-exploitation analysis
PDF vulnerability reports with CVSS scoring
Protect your users and your reputation.
📨 Subscribe to Our Cybersecurity Newsletter
Join over 10,000 developers and CISOs receiving weekly security insights.
📥 Subscribe via LinkedIn: https://www.linkedin.com/build-relation/newsletter-follow?entityUrn=7327563980778995713
—
🧠 Final Thought
HTTP Response Splitting is easy to overlook but dangerous if exploited. Use Symfony’s secure components, sanitize input rigorously, and scan your site often. Start now with our Free Website Security Scanner.
0 notes
Link
¿Es posible la multitarea en Arduino?
Digamos que tienes un proyecto de Arduino en el que quieres ejecutar varias acciones al mismo tiempo: leer datos de una entrada de usuario, hacer parpadear algunos LEDs, monitorizar un potenciómetro, etc. Así que, básicamente quieres hacer algunas multitareas con Arduino.
Y ahí es donde las cosas se complican un poco, sobre todo si ya estás acostumbrado a generar nuevos hilos cada vez que necesitas iniciar un nuevo programa paralelo.
La verdadera multitarea en Arduino no es posible.
Pero, aún así tenemos buenas noticias: todavía podéis hacer multitarea con Arduino. Todo lo que necesitas es un poco de comprensión para que las cosas funcionen sin problemas.
Antes de explicaros como hacer multitarea con Arduino, veamos por qué no podéis hacer programación paralela “estándar” en primer lugar.
¿Por qué no es posible la multitarea en Arduino?
Tienes que entender la diferencia entre un ordenador como un portátil o un servidor web, y una placa electrónica con un microcontrolador (Arduino).
Un ordenador clásico tiene varios núcleos y toneladas de RAM. Puedes instalar un sistema operativo (como Windows, Ubuntu, Debian, etc.), y generar cientos de tareas. Por ejemplo, cuando inicias Firefox o Chrome, se crean nuevos procesos, por lo que puedes seguir ejecutando todos tus programas mientras lanzas otros nuevos.
Con Arduino, las cosas son completamente diferentes.
El “cerebro” de una placa Arduino es un microcontrolador (ATmega328 para Arduino Uno). Un microcontrolador tiene un solo núcleo, y sólo es capaz de ejecutar una instrucción a la vez.
Así que si decides hacer una pausa dentro de una función, entonces todo tu programa se queda atascado esperando. Cada vez que escribes algo, tienes que pensar en su impacto en todo el código.
Cómo hacer multitarea con Arduino
Si tomas pequeñas acciones y las haces muy rápido, una tras otra, tendrás una sensación de multitarea. Ese es el principio detrás de la multitarea con Arduino.
Vamos a ilustrar esto con una ilusión óptica. Si coges un papel azul y otro rojo, y los alternas muy rápidamente delante de tus ojos (al menos 10 veces por segundo), verás el color púrpura.
Debido a que el cambio entre los colores ocurre tan rápido, tendrás la ilusión de que todos los colores se mezclan en otro color. Eso es más o menos lo que es la multitarea con Arduino, pero a una frecuencia mucho más alta.
Empecemos a hacer multitarea
Habréis oído que Arduino no es realmente potente. Bueno, esto está relacionado con el poder de cómputo global. De hecho, la velocidad de ejecución es todavía bastante alta para el manejo del hardware.
Por ejemplo, el microcontrolador ATmega328 de Arduino Uno tiene una frecuencia de 16MHz.
Para hacer multitarea con Arduino, sigue estos consejos:
Manten el tiempo de ejecución de todas sus funciones muy corto. No digo que sus funciones deban tener un máximo de x líneas de código. Lo que digo es que deberíais controlar el tiempo de ejecución y aseguraros de que es bastante bajo.
No uses delay(). Esta función bloqueará completamente tu programa. Como veremos más adelante con un ejemplo de código, hay otras formas de conseguir el mismo comportamiento que con la función delay(). Bueno, esta vale la pena repetirla: no uses delay().
Nunca te bloquees esperando algo. Si tu programa está escuchando una entrada de usuario, por ejemplo un mensaje de texto a través de la comunicación en serie, entonces significa que no controlas cuándo ocurrirá este evento, porque es de una fuente externa. La forma más fácil de obtener la entrada del usuario es esperar por ella, y luego continuar la ejecución del programa cuando se obtienen los datos. Bueno, no hagas eso. Como veremos más adelante, hay otras formas de mantener la comunicación externa sin bloquearse para el resto del programa.
Usar algo como una máquina de estados para procesos más largos. Digamos que tienes un proceso que realmente requiere un montón de acciones diferentes, y una cierta cantidad de tiempo para esperar entre 2 acciones. En este caso, es mejor separar este proceso en varias funciones pequeñas (ver el primer punto anterior), y crear una máquina de estados en tu programa principal para llamarlas una por una, cuando sea necesario. Esto te permitirá también computar cualquier otra parte del programa entre 2 pasos del proceso.
Un código de ejemplo
Aquí te mostraremos un ejemplo real usando una tabla de Arduino Uno.
Aquí está el esquema:
El código
#define LED_1_PIN 9 #define LED_2_PIN 10 #define LED_3_PIN 11 #define LED_4_PIN 12 #define POTENTIOMETER_PIN A0 #define BUTTON_PIN 5 unsigned long previousTimeLed1 = millis(); long timeIntervalLed1 = 1000; int ledState1 = LOW; unsigned long previousTimeSerialPrintPotentiometer = millis(); long timeIntervalSerialPrint = 2000; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED_1_PIN, OUTPUT); pinMode(LED_2_PIN, OUTPUT); pinMode(LED_3_PIN, OUTPUT); pinMode(LED_4_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { // put your main code here, to run repeatedly: unsigned long currentTime = millis(); // task 1 if(currentTime - previousTimeLed1 > timeIntervalLed1) { previousTimeLed1 = currentTime; if (ledState1 == HIGH) { ledState1 = LOW; } else { ledState1 = HIGH; } digitalWrite(LED_1_PIN, ledState1); } // task 2 if (Serial.available()) { int userInput = Serial.parseInt(); if (userInput >= 0 && userInput < 256) { analogWrite(LED_2_PIN, userInput); } } // task 3 if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_3_PIN, HIGH); } else { digitalWrite(LED_3_PIN, LOW); } // task 4 int potentiometerValue = analogRead(POTENTIOMETER_PIN); if (potentiometerValue > 512) { digitalWrite(LED_4_PIN, HIGH); } else { digitalWrite(LED_4_PIN, LOW); } // task 5 if (currentTime - previousTimeSerialPrintPotentiometer > timeIntervalSerialPrint) { previousTimeSerialPrintPotentiometer = currentTime; Serial.print("Value : "); Serial.println(potentiometerValue); } }
Desglosemos el código paso a paso para que puedas entender de qué estamos hablando.
Código de configuración
#define LED_1_PIN 9 #define LED_2_PIN 10 #define LED_3_PIN 11 #define LED_4_PIN 12 #define POTENTIOMETER_PIN A0 #define BUTTON_PIN 5 unsigned long previousTimeLed1 = millis(); long timeIntervalLed1 = 1000; int ledState1 = LOW; unsigned long previousTimeSerialPrintPotentiometer = millis(); long timeIntervalSerialPrint = 2000;
Para mayor claridad, hemos usado algunas #define para usar nombres en lugar de números para todos los pines de hardware. También hemos declarado algunas variables para llevar la cuenta del tiempo.
void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED_1_PIN, OUTPUT); pinMode(LED_2_PIN, OUTPUT); pinMode(LED_3_PIN, OUTPUT); pinMode(LED_4_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); }
Como sabéis, la función setup() se llama primero en Arduino. Aquí sólo inicializamos la comunicación en serie y establecemos el modo correcto para los pines digitales (los pines analógicos no requieren una configuración, ya que se establecen automáticamente como pines de entrada).
void loop() { // put your main code here, to run repeatedly: unsigned long currentTime = millis();
Y… ¡saltamos justo en la función loop()! Esta función será llamada una y otra vez, durante todo el tiempo que dure tu programa.
Lo primero que hacemos aquí es obtener el tiempo actual con millis(). Esto es muy importante. Para la mayoría de las subtareas del programa, usaremos algunas técnicas de seguimiento del tiempo para desencadenar una acción, y así evitaremos usar la función delay().
Tarea 1: Parpadear el LED 1 cada segundo
// task 1 if(currentTime - previousTimeLed1 > timeIntervalLed1) { previousTimeLed1 = currentTime; if (ledState1 == HIGH) { ledState1 = LOW; } else { ledState1 = HIGH; } digitalWrite(LED_1_PIN, ledState1); }
Aquí calculamos la duración entre la hora actual y la última vez que disparamos el LED 1. Si la duración es mayor que el intervalo que hemos establecido previamente (1 segundo aquí), ¡podemos realmente hacer la acción!
Observa que cuando entramos en el bloque if, fijamos la hora anterior como la hora actual. De esta manera, le decimos al programa : “no vuelvas aquí antes de que haya pasado el siguiente intervalo de tiempo”.
El uso de esta estructura de código es bastante común en Arduino. Si no estás familiarizado con esyo, tómate el tiempo de escribir el código y prueba algunos ejemplos por ti mismo. Una vez que entiendas como funciona, lo usarás en todos tus programas de Arduino.
Tarea 2: Leer la entrada de usuario del Serial (número entre 0 y 255) y escribir los datos en el LED 2
// task 2 if (Serial.available()) { int userInput = Serial.parseInt(); if (userInput >= 0 && userInput < 256) { analogWrite(LED_2_PIN, userInput); } }
Necesitamos “escuchar” el Serial para poder obtener la entrada del usuario. En lugar de bloquear, bueno, sólo llamamos al método Serial.available() cada vez que estamos en la función principal loop().
Como todos los demás bloques de código son bastante pequeños y rápidos, podemos esperar que el Serial sea monitoreado con bastante frecuencia. De esta manera, estamos seguros de que no nos perdemos ningún dato, mientras realizamos cualquier otra acción en el lateral.
Tarea 3: Encender el LED 3 si se presiona el botón
// task 3 if (digitalRead(BUTTON_PIN) == HIGH) { digitalWrite(LED_3_PIN, HIGH); } else { digitalWrite(LED_3_PIN, LOW); }
Este es bastante sencillo. Sólo monitoreamos el botón cada vez que ejecutamos la función loop() (Este código podría ser mejorado con una función debounce).
Tarea 4: Encender el LED 4 si el valor del potenciómetro es mayor de 512
// task 4 int potentiometerValue = analogRead(POTENTIOMETER_PIN); if (potentiometerValue > 512) { digitalWrite(LED_4_PIN, HIGH); } else { digitalWrite(LED_4_PIN, LOW); }
Igual que para el botón, sólo leemos el valor y actualizamos un LED dependiendo de ese valor. Obsérvese que usamos analogRead() para el potenciómetro, y el valor que obtenemos está entre 0 y 1024 (el convertidor analógico de Arduino tiene una resolución de 10 bits, y 2^10 = 1024).
Tarea 5: Imprimir el valor del potenciómetro vía Serial cada 2 segundos
// task 5 if (currentTime - previousTimeSerialPrintPotentiometer > timeIntervalSerialPrint) { previousTimeSerialPrintPotentiometer = currentTime; Serial.print("Value : "); Serial.println(potentiometerValue); }
Al igual que en la tarea 1, calculamos la diferencia de tiempo (duración) para comprobar si podemos ejecutar la acción o no. Esta es una buena alternativa a la función delay().
Y aquí, en lugar de disparar un LED, sólo enviamos un valor con comunicación en serie.
Bueno, parece que todo el código está corriendo muy rápido, y si construyes este circuito y ejecutas este programa, tendrás una verdadera sensación multitarea.
La multitarea finalmente no es tan difícil
Empieza a ser más fácil, ¿no?
Cada vez es lo mismo. Una vez que sabes cómo crear un pequeño bloque de código para que corra muy rápido (también puedes poner este código en una función), todo lo que necesitas hacer es repetir esta estructura para cada paso del complejo proceso que quieras hacer. No tiene por qué ser complicado.
Algunas otras formas de hacer multitarea
El método que hemos explicado es muy eficiente y muchos lo usamos personalmente en nuestros proyectos de Arduino.
También hay otras formas de “falsificar” la multitarea. Entre ellas:
Interrumpir las funciones
Algunos pines de Arduino, no todos, soportan la interrupción del hardware. Básicamente, se crea una función que es activada por un pulsador u otro actuador en un pin de hardware.
Cuando se dispara la interrupción, el programa se interrumpe, y su función se ejecuta. Una vez que la función ha terminado, el programa continúa donde estaba. Por supuesto, su función debe ser muy rápida, para que no detenga el “proceso” de ejecución principal por mucho tiempo.
Esto puede ser genial para ejecutar algún código dependiendo de algunas entradas externas, y asegurarte de no perder ninguna entrada si la frecuencia de la señal entrante es muy alta.
Como ejemplo, mira la tarea 3 del código de ejemplo anterior. Monitoreamos el botón pulsador tirando de su estado muy rápido. Aquí también podríamos usar interrupciones para activar el LED cada vez que se presiona el botón.
Aunque ten cuidado con eso porque hay un gran inconveniente: no puedes predecir cuándo se activará la función.
Es como el funcionamiento de una notificación en tu teléfono. No sabes cuándo recibirás las notificaciones push, pero puedes elegir revisar manualmente las notificaciones pull.
Las interrupciones de Arduino son como las notificaciones push. Puede ocurrir en cualquier momento.
Si eliges no utilizar las interrupciones, tendrás que comprobar manualmente (pull) la entrada para ver si puedes desencadenar la acción. La única diferencia es que con Arduino, si haces un “pull” para una notificación, y la notificación desaparece, no la verás. Pero esto no es necesariamente algo malo: si no necesitas ser extra-preciso cuando se ha disparado un pin, puedes tirar del estado cuando quieras. En este caso, tienes un control total sobre cuando compruebas la entrada.
Protothreads
Protothreads es una biblioteca de C pura. Requiere más conocimientos y es más compleja de manejar para los principiantes y los programadores de nivel medio.
Con Protothreads también puedes “fingir” el multiproceso para sistemas basados en eventos, por lo que es bastante útil para programas de Arduino más complejos.
Aunque, debes tener en cuenta que el uso de Protothreads no es en absoluto obligatorio. Puedes escribir un programa multitarea completo con los consejos básicos que te hemos dado antes en este post.
No te olvides de mantener las cosas simples
Cómo has visto la multitarea con Arduino puede llegar a ser bastante simple. Puede que te sientas abrumado por todas las cosas que lees sobre multitarea, y cómo debería ser una “cosa compleja de manejar”.
Aunque de hecho, siguiendo algunas reglas bastante simples, puedes llegar bastante lejos con Arduino. Y cuando estés programando, recuerda siempre: lo simple es mejor. No quieres escribir cosas complicadas.
Última actualización el 2020-05-01 / Enlaces de afiliados / Imágenes de la API para Afiliados
1 note
·
View note
Link
.In this tutorial we will gonna see how many Methods of Input & How to use them. And also learn How to accept input from user. For this We are using Scanner class to get the input.
Scanner is a class in java.util package is used for obtaining the input from user.It is the easiest way to read input in a java program.

#java#input#userinput#scanner#javainput#javainputmethod#programming#learnjava#javacourseforbeginners#javabasictoadvanced#javapoint#learntocode#beginnerstutorial
0 notes
Video
instagram
I'm disappointed with the new #cricinfo score display in their #androidapp I'm a big fan of Cricinfo 😍 and I want to be able to switch between 'live', 'Scorebord' and 'commentary' tabs easily. Please fix this! 🙏🏾 #cricket #gentlemensgame #espncricinfo #application #design #uxdesign #feedback #userinput #customerfeedback #madaboutcricket https://www.instagram.com/p/B9SF7t7BNE4/?igshid=hz311va9jlnh
#cricinfo#androidapp#cricket#gentlemensgame#espncricinfo#application#design#uxdesign#feedback#userinput#customerfeedback#madaboutcricket
0 notes