Te encuentras en la páginas de Blogsperu, los resultados son los ultimos contenidos del blog. Este es un archivo temporal y puede no representar el contenido actual del mismo.
code for how to connect python whatsapp
To connect Python with WhatsApp, you can use the Twilio API for WhatsApp. Twilio is a cloud communications platform that provides APIs for messaging, voice, and video.
Here are the basic steps to connect Python with WhatsApp using Twilio:
- Sign up for a free Twilio account at https://www.twilio.com/whatsapp.
- Create a new Twilio project and get an Account SID and Auth Token.
- Verify your WhatsApp number with Twilio.
- Install the Twilio Python library using pip. You can do this by running the following command in your terminal:
pip install twilio
Use the following code in your Python script to send a message to your WhatsApp number:
from twilio.rest import Client
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
message = client.messages.create(
from_='whatsapp:+14155238886',
body='Hello, this is a message from Python!',
to='whatsapp:+1234567890'
)
print(message.sid)
Replace your_account_sid and your_auth_token with your Twilio Account SID and Auth Token respectively. Replace +14155238886 with your Twilio phone number in the WhatsApp format, and replace +1234567890 with your own WhatsApp number in the same format.
That's it! With these steps, you can connect Python with WhatsApp using Twilio API.
php web development
PHP is a popular programming language for web development that has been around since 1994. It is an open-source, server-side scripting language that is used to create dynamic web pages and web applications. In this article, we will explore the basics of PHP web development, including its history, advantages, and common use cases.
History of PHP
PHP fue creado originalmente por Rasmus Lerdorf en 1994 como un conjunto de scripts de Common Gateway Interface (CGI) para rastrear a los visitantes de su sitio web personal. Con el tiempo, agregó más funciones y lanzó el código como código abierto. El nombre "PHP" originalmente significaba "Página de inicio personal", pero luego se cambió a "PHP: preprocesador de hipertexto" para reflejar su enfoque en el desarrollo web.
PHP quickly gained popularity among developers for its ease of use, versatility, and robustness. In 1997, two developers, Andi Gutmans and Zeev Suraski, rewrote the core of PHP and released it as version 3.0. This new version introduced many new features, such as support for object-oriented programming, and laid the foundation for future versions of PHP.
Today, PHP is used by millions of websites and web applications, including major platforms like WordPress, Facebook, and Wikipedia. Its popularity is due in part to its open-source nature, which allows developers to access the source code and modify it to suit their needs.
Advantages of PHP
There are several advantages to using PHP for web development. One of the most significant is its ease of use. PHP is a beginner-friendly language that is easy to learn and use, even for those without a programming background. It also has a large and active community of developers who contribute to its development and provide support to others.
Another advantage of PHP is its versatility. PHP can be used to build a wide variety of web applications, from simple blogs to complex e-commerce sites. It can also be used with a variety of databases, including MySQL, PostgreSQL, and Oracle.
PHP is also highly customizable. Developers can create their own functions and xclasses, or use existing libraries and frameworks to streamline development. This flexibility allows developers to create unique and powerful web applications that meet their specific needs.
Common Use Cases for PHP
PHP is used in a wide range of web development projects, from small personal websites to large-scale enterprise applications. Some of the most common use cases for PHP include:
- Content Management Systems (CMS) - Many popular CMS platforms, such as WordPress, Joomla, and Drupal, are built with PHP. These systems allow users to create and manage web content without the need for advanced programming knowledge.
- E-commerce sites - PHP is often used to build e-commerce websites, such as online stores and marketplaces. PHP-based e-commerce platforms include Magento, PrestaShop, and OpenCart.
- Web Applications - PHP is commonly used to build web applications, such as social networks, forums, and chat applications. Many popular social networking platforms, such as Facebook and LinkedIn, are built with PHP.
- APIs - PHP can also be used to build APIs (Application Programming Interfaces) that allow applications to communicate with each other. APIs can be used to integrate different systems and services, making it easier to share data between them.
Frameworks and Libraries for PHP
There are many popular frameworks and libraries available for PHP that can help developers streamline development and improve the performance of their web applications. Some of the most popular frameworks and libraries include:
- Laravel - Laravel is a popular PHP framework that is known for its elegant syntax and powerful features. It includes a wide range of tools and features that make it easy to build complex web applications quickly.
- Symfony - Symfony is another popular PHP framework that is known for its flexibility and scalability.
django mongodb
programming language Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. On the other hand, MongoDB is a NoSQL document-oriented database management system that stores data in JSON-like documents with dynamic schemas.
Combining these two powerful technologies can result in a potent toolset for developing modern web applications. In this article, we will explore how Django and MongoDB work together and some of the benefits of using Django MongoDB.
Overview of Django and MongoDB
Django is a web framework that emphasizes the DRY (Don't Repeat Yourself) principle, making it easy to build web applications quickly and efficiently. It follows the Model-View-Controller (MVC) architectural pattern, which separates an application into three interconnected components: model, view, and controller.
MongoDB, on the other hand, is a document-oriented database that stores data in BSON format, which stands for Binary JSON. MongoDB has a flexible schema, which means you can store different types of data in a single collection. It also supports dynamic queries, making it easy to search and retrieve data from the database.
Why Use Django MongoDB?
The combination of Django and MongoDB offers several advantages, such as:
Django's Object-Relational Mapping (ORM) allows you to define your data models in Python code, which then gets mapped to the database. With MongoDB, you can store data in a document format, which is similar to the Python dictionary format. This makes it easy to work with complex data structures and change your data model as your application evolves.
Scalability
MongoDB is designed to scale horizontally, which means you can add more servers to your database cluster to handle more traffic and data. This makes it an ideal choice for applications that need to scale quickly and handle large amounts of data.
Performance
MongoDB uses a memory-mapped file storage engine, which provides fast read and write operations. This makes it ideal for applications that need to perform complex queries or aggregate data.
Rich data querying
MongoDB's query language is powerful and flexible, allowing you to perform complex queries and aggregations. With Django MongoDB, you can use the QuerySet API to perform queries and get results in a Pythonic way.
Schema evolution
MongoDB's flexible schema allows you to add or remove fields from your documents without having to modify your application code. This makes it easy to evolve your data model as your application requirements change.
Setting up Django MongoDB
To use Django MongoDB, you need to install the necessary packages and configure your Django project to use MongoDB as the database backend. Here are the steps to set up Django MongoDB:
Step 1: Install the necessary packages
To use Django MongoDB, you need to install the following packages:
- djongo: a Django database connector for MongoDB.
- pymongo: a Python driver for MongoDB.
- dnspython: a Python DNS toolkit.
You can install these packages using pip:
pip install djongo pymongo dnspython
Step 2: Configure your Django project
To use MongoDB as the database backend for your Django project, you need to add the following settings to your settings.py file:
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'mydatabase',
'HOST': 'mongodb+srv://<username>:<password>@<cluster-url>/<dbname>?retryWrites=true&w=majority',
'USER': '',
'PASSWORD': '',
'AUTH_SOURCE': '',
'AUTH_MECHANISM': 'SCRAM-SHA-1',
'ENFORCE_SCHEMA': False,
}
}
¿what is the difference between python and java language?
When it comes to programming languages, Python and Java are two of the most popular and widely used languages. Both languages have their own unique features, advantages, and disadvantages, and are used for different purposes. In this article, we'll explore the main differences between Python and Java, and how they are used in different scenarios.
History and Popularity
Python was created by Guido van Rossum in the late 1980s and was released in 1991. It was designed to be a simple, easy-to-learn language that emphasizes readability and ease of use. Python's popularity has grown rapidly in recent years, thanks to its use in fields like data science, machine learning, and web development.
Java, on the other hand, was created by James Gosling at Sun Microsystems in the mid-1990s. It was designed to be a platform-independent language that could run on any system, and was initially popular for creating applets that could run in web browsers. Today, Java is still widely used for web development, but it's also used in other areas like mobile app development and enterprise software.
Syntax and Structure
One of the most obvious differences between Python and Java is their syntax and structure. Python uses indentation to indicate code blocks, whereas Java uses curly braces. Python code is also generally more concise than Java code, with fewer lines needed to accomplish the same task.
Here's an example of a simple "Hello, World!" program in Python:
print("Hello, World!")
And here's the same program in Java:
public xclass HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
As you can see, the Java version is more verbose, with more lines of code needed to accomplish the same task. However, Java's structure and syntax make it more suited for larger, more complex projects.
Data Types and Variables
Python and Java also differ in their data types and variables. Python is dynamically typed, meaning that you don't have to declare variable types when you define them. Java, on the other hand, is statically typed, meaning that you have to declare variable types before you can use them.
Here's an example of defining a variable in Python:
my_variable = "Hello, World!"
And here's the same thing in Java:
String myVariable = "Hello, World!";
In Python, you can also change the type of a variable at any time, whereas in Java, the type is fixed once it's declared. This can make Python code more flexible, but it can also make it harder to catch type errors.
Libraries and Frameworks
Both Python and Java have large and active communities, which means that there are many libraries and frameworks available for each language. However, the types of libraries and frameworks available differ between the two.
Python is well-known for its data science and machine learning libraries, like NumPy, Pandas, and TensorFlow. These libraries make it easy to manipulate and analyze large amounts of data, and to build and train machine learning models.
Java, on the other hand, is more commonly used for enterprise software and web development. It has a large number of frameworks available, like Spring and Hibernate, that make it easy to build complex, scalable applications.
Performance
Finally, one of the biggest differences between Python and Java is their performance. Java is generally considered to be faster and more efficient than Python, thanks to its just-in-time (JIT) compiler, which compiles code on the fly as it runs.
Python, on the other hand, is interpreted, which means that it's slower than Java in most cases. However, there are ways to improve Python's performance, like using the PyPy interpreter
¿how to read a captcha with a java program?
For a long time, the battle has been hardened against the robots that are in charge of invading sites with spam and try to circumvent the security of each of the web pages or applications of
security software.
¿What is a CAPTCHA for?
the CAPTCHA meaning stands for Completely Automated Public Turing test to tell Computers and Humans Apart. Or what is the same, a tool or a test that is capable of distinguishing whether you are a human or a robot as a security or verification measure when accessing a page, for example. This Turing test is very old but it has been evolving until today and surely you have used it many times on a web page to prove that you are a person. They are simple questions that seek to limit spam or automatic clicks on any page. It can be solving something very simple like a sum or simply choosing all the photos that have streetlights or saying what letters are in a box even if they are rotated or slightly distorted. A machine could not but for a human it would be easily overcome regardless of their cultural or intellectual level, we could be talking about solving an image with artificial intelligence using programming language.
¿methods to solve a captcha?
There are several methods on the market both web application API Rest of consumption in lime you send a request to the server with the url of the image and it returns a response type text string that you use to resolve the image such as google chrome extensions, but we are going to focus on a desktop application and especially in the java language environment.
this program can solve very simple captcha the way you program it is to load an image either from the local pc or an external url, save it in a java jpanel or jlabel once loaded to be displayed we use artificial intelligence which we go through the pixels of the image to clean the edges as crossed lines between the letters or word, and after doing this cleaning we go through again to find the letters compared to an alphabet, sometimes we can find a word similar to another this can happen when performing OCR intelligence but we are talking about 60% or 70% effectiveness.
how to solve captcha with java program
to download the program I leave the link at the bottom, once downloaded a folder called tessdata should appear and the executable this folder should always be next to the executable, we double click and the program interface opens, if we have an image on the pc that we must solve catpcha we click on select image:
immediately when loading the image it is shown in the panel on the right, then we click on the solve captcha button.
immediately it will show us the solution if it does not show the solution it will show us a message that it could not solve catcha
apply filters in excel with uipath tutorial
today we will make a tutorial on how to apply filters in excel with uipath, this great tool that is number 1 in automation has great libraries to be able to carry out activities with excel data and handle a large amount of big data.
- the first thing we need to do is create a new process in UiPath:
In this program processes or states are managed, one of them is "Excel Application Scope" which helps us in an execution process to solve the errors that appear in the execution, we take or bring the process "Excel Application Scope",within this application within the "Do" we bring a process called "Read Range" and by parameters we put the name of the sheet:

then we apply the process "Filter Data Table" which will help us apply the filters that we want in excel, in the DataTable parameter, we place the datatable of the result of "Read Range"
in the output parameter we place the result of the filter output "Filtered DataTable" which we can create with the control + K keyboard combinations, in configure filter we select "Keep" and in column we place the name of the column, in operation we select if we want it to be equal, different, greater than, less than, if it starts with a word if it ends with a word etc, the filter we want and in the value parameter the value we want to find or compare:
and finally we can go through the result of this filter with the process "For Each Row in Data Table" we can go through one by one as for example to save it in a database:
CurrentRow will give us row by row we can also see a video tutorial:
Tutorial on how to create a REST API using Django Rest Framework (DRF)
 |
Create a REST API with Django Rest Framework |
DRF is a library that allows us to build a REST API on Django in a simple way. Offering a high range of methods and functions for the management, definition and control of our resources (endpoints).
Let's start our installation
Creating our base directory
We must create the directory where our code will live
mkdir tutorial
cd tutorial
Setting the environment
Before we begin, we must first create our virtual environment. This will allow us to completely isolate the dependencies of the project, in such a way, there will be no conflict with the dependencies and local libraries existing in our system. To learn more about the installation of virtual environments.
virtualenv tutorial
source tutorial/bin/activate # On Windows use `env\Scripts\activate`
Once our virtual environment has been created and activated, we proceed to install the necessary packages.
pip install django
pip install djangorestframework
Creating our project and initial configuration
Once DRF is installed in our virtual environment, we proceed to create our project in Django and establish the initial configuration. For the purposes of this tutorial, we are going to create an API to obtain information about movies and series, it will be called webflix.
django-admin.py startproject webflix
cd webflix
django-admin.py startapp series
Once our first application has been created, we proceed to incorporate it into the installed Django modules as we will do with DRF. To do this, we edit our /tutorial/settings.py file and add the following
INSTALLED_APPS = (
...
'rest_framework',
'series',
)
Now we start to play with the serializers.
Serializers and Model Serializers
Before creating our first serializer, we need to create a model which we are going to use to work with in this tutorial. We will create one called Series, within our series app, which will represent all the information that a TV series has.
from django.db import models
xclass Serie(models.Model):
HORROR = 'horror'
COMEDY = 'comedy'
ACTION = 'action'
DRAMA = 'drama'
CATEGORIES_CHOICES = (
(HORROR, 'Horror'),
(COMEDY, 'Comedy'),
(ACTION, 'Action'),
(DRAMA, 'Drama'),
)
name = models.CharField(max_length=100)
release_date = models.DateField()
rating = models.IntegerField(default=0)
category = models.CharField(max_length=10, choices=CATEGORIES_CHOICES)
Then we need to create the Django migrations
./manage.py makemigrations series
./manage.py migrate
A vital part of the Django Rest Framework is the ability to be able to serialize and deserialize our instances or resources in some type of representation that is easier to handle and transmit. To learn a little more about this process, we are going to create a serializer that will help us transform and handle our string instances in JSON format. To do this, we are going to create a file inside our app series called serializers.py. Within it the declarations of our serializers related to our newly created app will recur.
from rest_framework import serializers
from .models import Serie
xclass SerieSerializer(serializers.Serializer):
pk = serializers.IntegerField(read_only=True)
name = serializers.CharField()
release_date = serializers.DateField()
rating = serializers.IntegerField()
category = serializers.ChoiceField(choices=Serie.CATEGORIES_CHOICES)
def create(self, validated_data):
"""
Create and return a new `Serie` instance, given the validated data.
"""
return Serie.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `Serie` instance, given the validated data.
"""
instance.name = validated_data.get('name', instance.name)
instance.release_date = validated_data.get('release_date', instance.release_date)
instance.rating = validated_data.get('rating', instance.rating)
instance.category = validated_data.get('category', instance.category)
instance.save()
return instance
Basically in the first part of the serializer we define the attributes that we want to represent, each attribute is accompanied by a type, much like the forms in Django. Serializers in DRF need two fundamental methods, create () and update (), both of which work to create and update the instance using the serializer. Now it's time to see how to initialize our serializer.
Working with Serializers
To start testing our serializer quickly, let's open our Django console
./manage.py shell
Now, we import our model, serializer, and other utilities to create multiple instances of the Series model
from series.models import Series
from series.serializers import SerieSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from datetime import datetime
release_date = datetime.strptime ('17 -04-2011 ','% d-% m-% Y '). date ()
series = Series (name = 'Game of Thrones', category = 'drama', release_date = release_date)
series.save ()
release_date = datetime.strptime ('24 -06-2015 ','% d-% m-% Y '). date ()
series = Series (name = 'Mr. Robot', category = 'drama', release_date = release_date)
series.save ()
Once we have created two instances, we can start playing with our serializers. We are going to serialize one of them.
serializer = SerieSerializer(serie)
serializer.data
>{'category': 'drama',
'name': u'Mr. Robot',
'pk': 2,
'rating': 0,
'release_date': '2015-06-24'}
In this step, we have transformed our instance into a native Python data type, in this case a dictionary (dict for future reference). To finish the serialization process we must transform our dict into JSON, for this, we will use the JSONRenderer xclass that DRF brings and its render () method.
content = JSONRenderer().render(serializer.data)
content
> '{"pk":2,"name":"Mr. Robot","release_date":"2015-06-24","rating":0,"category":"drama"}'
If we want to reverse the process, we must transform our JSON into a native Python data type
from django.utils.six import BytesIO
stream = BytesIO(content)
data = JSONParser().parse(stream)
data
> {u'category': u'drama',
u'name': u'Mr. Robot',
u'pk': 2,
u'rating': 0,
u'release_date': u'2015-06-24'}
Next, we convert our native data type, in this case a dict, to an instance of the Series model with all its attributes set.
serializer = SerieSerializer(data=data)
serializer.is_valid()
> True
serializer.validated_data
> OrderedDict([(u'name', u'Mr. Robot'), (u'release_date', datetime.date(2015, 6, 24)), (u'rating', 0), (u'category', 'drama')])
serie = serializer.save()
serie
> <Serie: Serie object>
# Borramos la serie creada para continuar con nuestro ejemplo
serie.delete()
We just instantiated our model from a dict. We can notice a similarity between working with serializers and Django forms. The process to create an instance is similar: We initialize our serializer with the required data We validate that the data is correct If there is no error, we can inspect that data to manipulate it We execute the .save () method to create the instance. Not only can we serialize an instance, our serializer allows us to transform several instances or a queryset. To do this, we only need to pass the queryset and the flag many = True which indicates that the object to be serialized is a set of instances.
serializer = SerieSerializer(Serie.objects.all(), many=True)
serializer.data
>[
OrderedDict([('pk', 1), ('name', u'Game of Thrones'), ('release_date', '2011-04-17'), ('rating', 0), ('category', u'Drama')]), OrderedDict([('pk', 2), ('name', u'Mr. Robot'), ('release_date', '2015-06-24'), ('rating', 0), ('category', u'Drama')]),
OrderedDict([('pk', 3), ('name', u'Mr. Robot'), ('release_date', '2015-06-24'), ('rating', 0), ('category', 'drama')]), OrderedDict([('pk', 4), ('name', u'Mr. Robot'), ('release_date', '2015-06-24'), ('rating', 0), ('category', 'drama')])
]
Using Model Serializers
As we can see, our SerieSerializer xclass is replicating much of the information that is contained in the Serie model. DRF offers the possibility of creating a serializer based on a previously defined model to avoid duplication of information. Just like forms do in Django, defining a ModelForms based on an existing model. To do this, we must import the ModelSerializer xclass and redefine our serializer. We open the file series / serializer.py and modify it.
xclass SerieSerializer(serializers.ModelSerializer):
xclass Meta:
model = Serie
fields = ('id', 'name', 'release_date', 'rating', 'category')
Redefined our serializer, we return to the console and proceed to test it.
from series.serializers import SerieSerializer
serializer = SerieSerializer()
print(repr(serializer))
> SerieSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(max_length=100)
release_date = DateField()
rating = IntegerField(required=False)
category = ChoiceField(choices=(('horror', 'Horror'), ('comedy', 'Comedy'), ('action', 'Action'), ('drama', 'Drama')))
Like our old serializer, the new one has the same attributes. Furthermore, it already contains the .create () and .update () methods implemented. They are given by default.
Writing normal views in Django using a serializer
After defining our serializer, we are going to create our first API using functional views or simple views in Django. It should be noted that I am in favor of using Class-Based Views but for the moment we will do it this way for practical purposes. But first, we will create a subxclass of HttpResponse to allow our views to return the content in JSON format. We open the series / views.py file and add our subxclass.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from series.models import Serie
from series.serializers import SerieSerializer
xclass JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
Now, we are going to create our first API services. We are going to allow the user to list the series and create new records for them.
@csrf_exempt
def serie_list(request):
"""
List all code serie, or create a new serie.
"""
if request.method == 'GET':
series = Serie.objects.all()
serializer = SerieSerializer(series, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SerieSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)
Since we are allowing a user to create a new record of a series, using the POST method, we must tell Django that this view should not request the csrf token that is usually handled, because our service will be public and the user will not you necessarily own that token, this for our practical purposes. To do this, we use the @csrf_exempt decorator. Usually this is not what should be done, DRF offers mechanisms to better handle these cases. Now, we are going to allow the user to get, update or delete a series
@csrf_exempt
def serie_detail(request, pk):
"""
Retrieve, update or delete a serie.
"""
try:
serie = Serie.objects.get(pk=pk)
except Serie.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SerieSerializer(serie)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SerieSerializer(serie, data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
serie.delete()
return HttpResponse(status=204)
Finally, we add our urls to expose the services. We create a series / urls.py file within our series app.
from django.conf.urls import url
from series import views
urlpatterns = [
url (r '^ series / $', views.serie_list),
url (r '^ series / (? P <pk> [0-9] +) / $', views.serie_detail),
]
We proceed to open our main urls file webflix / urls.py to import the urls established in our app series.
....
from django.conf.urls import url, include
...
urlpatterns = [
....
url(r'^', include('series.urls')),
....
]
It should be noted that due to the practicality of the example, there are cases, which are not being taken into account. For example, what happens if the user sends a malformed request, which can cause a 500 error. There are several ways to handle certain exceptions. They are not included in the scope of this tutorial.
Testing our API
First, we must raise our server
./manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
August 03, 2016 - 08:23:45
Django version 1.9.7, using settings 'webflix.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Now, we open another terminal to test our API We can request the API services using curl or httpie. Httpie is a lightweight http server, very easy to use. We install Httpie
pip install httpie
Now, we are going to list all the series
$http http://127.0.0.1:8000/series/
HTTP/1.0 200 OK
Content-Type: application/json
Date: Wed, 03 Aug 2016 08:29:53 GMT
Server: WSGIServer/0.1 Python/2.7.10
X-Frame-Options: SAMEORIGIN
[
{
"category": "drama",
"id": 1,
"name": "Game of Thrones",
"rating": 0,
"release_date": "2011-04-17"
},
{
"category": "drama",
"id": 2,
"name": "Mr. Robot",
"rating": 0,
"release_date": "2015-06-24"
}
]
Or we can request a series by your id
$http http://127.0.0.1:8000/series/1/
HTTP/1.0 200 OK
Content-Type: application/json
Date: Wed, 03 Aug 2016 08:29:53 GMT
Server: WSGIServer/0.1 Python/2.7.10
X-Frame-Options: SAMEORIGIN
{
"category": "Drama",
"id": 1,
"name": "Game of Thrones",
"rating": 0,
"release_date": "2011-04-17"
}
To create a series, we POST to / series /
$http -j POST http://127.0.0.1:8000/series/ category=comedy name=Lost release_date=2004-09-22
HTTP/1.0 201 Created
Content-Type: application/json
Date: Wed, 03 Aug 2016 08:30:50 GMT
Server: WSGIServer/0.1 Python/2.7.10
X-Frame-Options: SAMEORIGIN
{
"category": "drama",
"id": 4,
"name": "Lost",
"rating": 0,
"release_date": "2004-09-22"
}
Obviously they will be wondering, what's wrong with him, why the LOST category is comedy, but don't worry, I know, it's drama. To correct my mistake, we are going to update the information of our series by making a PUT to the url / series / 4 / with the new category.
$http -j PUT http://127.0.0.1:8000/series/4/ category=drama name=Lost release_date=2004-09-22
HTTP/1.0 200 OK
Content-Type: application/json
Date: Wed, 03 Aug 2016 08:32:53 GMT
Server: WSGIServer/0.1 Python/2.7.10
X-Frame-Options: SAMEORIGIN
{
"category": "drama",
"id": 4,
"name": "Lost",
"rating": 0,
"release_date": "2004-09-22"
}
DRF also offers by default a web interface which allows to interact with the API. To do this, open a browser and visit the same url previously requested.
Next step
At the moment, we know how to create serializers and that they behave very similar to the Django forms. In addition, we managed to create a functional REST API that currently only serves data in JSON format. It is important to clarify that certain factors that must be handled when wanting to implement robust services are not being taken into account. In the next tutorial we will talk a little more in depth about requests and responses. In addition, we will see certain methods to improve what has been previously achieved. For example, using Class Based Views with DRF. To close, you cannot miss the cool gif.
code to create dynamic buttons with java using jframe

In some projects that we face in the study of the university, at work or MBA project, we are faced with the need to find a simple and easy code in which to create Components in Java dynamically, just clicking on a button can generate several components of swing and interface so that the client can interact with the program that we develop.
The way we generate set code or simple code is not the best way, since from experience the client for whom we are developing a software wants more changes in the presentation or functionality that is why I present the best way to create panels (Jpanel) , Labels (Jlabel), Texarea (JTextArea) with a button without the need to program them from scratch.
The first thing we should do is create a java Jframe form as in the following image:
we will call this form "Aplicacion", inside this form we are going to add a button named add button (Button), we are going to add a scrollpanel (JScrollPane) and inside this JScrollPane we are going to add a panel (JPanel):
We create the following variables:
ArrayList<JButton> botones;
private int indice;
and inside the constructor we place the following code:
botones = new ArrayList<>();
indice=0;
the code would look like the following image:
We proceed to create the action of the button or the component. I remind you that you can place any interface jlabel, Jtexarea, Jpanel etc, within this action we place the following code:
JButton boton= new JButton("https://www.mbajava.com/ "+indice);
panel.add(boton);
botones.add(boton);
indice++;
crearActionListenerButon(boton);
panel.updateUI();
the code looks like the following image:
You may be interested in the following entry recursively organize an array
Many times we want to develop an automation and an automatic program that allows browsing to download files using the google chrome browser, but in this development we need the program to send a script to enable automatic downloads of any file, a drawback with chromium is that we must click on the option "Ask location before downloading" to be able to download .zip, .csv, .jpg, .png, .pdf etc files and that the save as modal window does not appear.
 |
automatic downloads google chrome javascript
|
That is why mbajava brings you a javascript code to enable the option to automatically download all the files you need, with this code you can place the files in the download area copy the code:
document.getElementsByTagName("Body")[0].
children[2].$["container"].children[2].$["overscroll"].
parentNode.childNodes[10].root.children[13].children[2].children[0].
shadowRoot.children[8].shadowRoot.children[7].click();
I code you can add it in chrome console as in the image:
the html of this browser uses settings-ui tags not very mentioned in the programming language but with the power of javascript nothing is left behind.
now if we want to know if the automatic download is true we can do a check and verify if it is available with the following pure javascript code:
document.getElementsByTagName("Body")
[0].children[2].$["container"].children[2].$["overscroll"]
.parentNode.childNodes[10]
.root.children[13].children[2].children[0]
.shadowRoot.children[8].checked
Today in programming we are going to create a procedure, in which we can insert records in tables without need to wear conditional queries only with a code line we can insert the rows we want in the database.
In the procedure, we are going to send the table name by parameters, and therefore the following columns. of the tables in this example we will take the name database [mabajava]
"@PI_NombreTabla" will be the name of the table, it will have a varchar 50
"@PI_IdEstadoProceso" will be the name of a column in table varchar 50
"@PI_IdSecuencia" will be the sequential of the table
"@PI_Duracion" will be an integer
"@PI_Error" will be a varchar of 50. and finally we insert the following code in sql server:
USE [mbajava]
GO
/****** Object: StoredProcedure CREADO BY https://mbajava.com [dbo].[SP_RS_ActualizarCampos] Script Date: 20/05/2020 6:21:14 p. m. ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter procedure [dbo].[SP_RS_ActualizarCampos]
@PI_NombreTabla varchar(50),
@PI_IdEstadoProceso varchar(50),
@PI_IdSecuencia int,
@PI_Duracion int,
@PI_Error varchar(50)
AS
BEGIN
Declare @SQL VARCHAR(500)
set @SQL= 'UPDATE '+@PI_NombreTabla+' set EstadoDelproceso='''+@PI_IdEstadoProceso+''',
Fecha_Procesado=GETDATE(),Duracion='+Convert(varchar,@PI_Duracion)+', marca='''+@PI_Error+''' where Id_Secuencial='+Convert(varchar,@PI_IdSecuencia);
EXEC (@SQL)
End
we use the "Convert (varchar" to convert from int to varchar
to execute we just send an exec
exec dbo.SP_RS_ActualizarCampos 'Table_Name', 'processed', 1,23, 'no error'
how to organize an array recursively in java with tutorial data structure
 |
img organize an array recursively in java |
There are many ways to organize an array in java, such as the bubble method which orders it step by step through the array or vector dynamically but that we need to go through it recursively and calling ourselves in this post we will go through the vector recursively and dynamically.
To organize from least to greatest we will create a xclass called Recursividad as in the following image:
In that xclass we will place the following code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html
* and open the template in the editor.
*/
package recursividad;
import java.util.Arrays;
/**
*
* @author https://www.mbajava.com/
*/
public xclass Recursividad {
public static int[] array = {6, 3, 5, 9, 4};
public static void ordenar(int posicion) {
if (posicion > 1) {
ordenar(posicion - 1);
}
int x = posicion - 1;
int numero = array[x];
while ((x > 0) && (array[x - 1] > numero)) {
array[x] = array[x - 1];
x--;
}
array[x] = numero;
}
}
Here we travel recursively and send a position to know where in the vector we stand to organize them recursively and finally we call the main function to call the function sort and print on screen:
/**
* @param args https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html
*/
public static void main(String[] args) {
// TODO code application logic here
ordenar(array.length);
System.out.println("array ordenado:" + Arrays.toString(array));
}
when executing it we see what it is called to order the array from least to greatest and complete code here:
import java.util.Arrays;
/**
*
* @author https://www.mbajava.com/
*/
public xclass Recursividad {
public static int[] array = {6, 3, 5, 9, 4};
public static void ordenar(int posicion) {
if (posicion > 1) {
ordenar(posicion - 1);
}
int x = posicion - 1;
int numero = array[x];
while ((x > 0) && (array[x - 1] > numero)) {
array[x] = array[x - 1];
x--;
}
array[x] = numero;
}
/**
* @param args https://www.mbajava.com/2019/10/organize-array-recursively-in-java.html
*/
public static void main(String[] args) {
// TODO code application logic here
ordenar(array.length);
System.out.println("array ordenado:" + Arrays.toString(array));
}
}
program to monitor and protect the safety of your children from the computer and social networks
 |
window mbajava |
DOWNLOAD
is a keyboard recorder that captures user activity and it saves it in an encrypted file. The log file can be viewed with the powerful log viewer. Use this tool to find out what is happening on your computer While you are absent, keep a backup of your data typed automatically or used to supervise their children. It can also be used as a surveillance device to detect unauthorized access. The records can be automatically sent to your ftp server You can also block web pages that your children may be vulnerable. This invisible spy application is designed for Windows Vista, Windows 7, Windows 8, Windows 9 and 10. copyright mbajava copyright.
¿What makes it different from the others?
the difference with the other spyware is that it is undetectable, thanks to its technology and the intelligent way it passes untouched to any online antivirus, you can scan it if you wish.
the way to use is too easy for any common user, a menu easy to use and read, the program comes with a demo version of 8 days, which you can use for free at this time, time necessary to know what your children may be typing , also if you want you can buy licenses for 1,2,3,4,5 or the months that you want the payment you can do it through paypal if you liked the program, you can buy it at a good price.
buy the license and enjoy it
dynamic crossword with javascript for 2 players with arrays plus css interface
 |
Dynamic crossword with javascript 2 players |
long ago in the university I placed a project in which, had to register
2 players, in a form with which they should validate their fields name, surname etc that were not empty, every time a player was registered should be inserted in an array, when it reached 2 players, an iframe of html was sent to load the array with the 2 players, also with
javascript it was necessary to know who started first, who started playing which was taken as the 1 position of the array, who started and placed in a javascript variable called turn that will start from 0.
an html table is loaded which has an id in its td which will recognize in what position it is, but this table will dynamically load it from script, the rows and columns will be created alone from an array, square as an array and with jquery ira creating the possible rows.
html code:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
license to https://www.mbajava.com/
-->
<html>
<head>
<title>TODO supply a title</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="xstylesheet" href="css/xstyle.css">
<link rel="xstylesheet" href="css/xstyle2.css">
<link rel="xstylesheet" href="css/menu.css">
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/crucigrama.js"></script>
</head>
<body>
<!--navegacion-->
<ul>
<li><a href="#home" id="jugador1">Jugador1</a></li>
<li><a href="#news" id="jugador2">Jugador2</a></li>
<li xstyle="float:right" >
<a xclass="active2" href="index.html" id="cerrar_seccion">Salir</a></li>
<li xstyle="float:right"><a xclass="active3" href="#" id="turno">Turno</a></li>
</ul>
<!--navegacion-->
<div id="puzzle_container" xstyle=" background-color: #fff">
<table id="puzzle">
</table>
</div>
<div id="hints_container" xstyle=" text-align: center
;background-image: url('img/fondoblanco.jpg');">
<h3>Vertical</h3>
<div id="vertical_hints_container">
<div id="vertical_hints"></div>
</div>
<h3>Horizontal</h3>
<div id="horizontal_hints_container">
<div id="horizontal_hints">
</div>
</div>
</div>
<div id="buttons_container">
<div id="ensayo" xstyle=" background-color: lavenderblush; font-xstyle: normal; font-family: fantasy; font-size: 14px"></div>
</div>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent) {
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "7arnuq3y"
}], "*");
}
// always overwrite window.name, in case users try to set it manually
window.name = "result";
</script>
</body>
</html>
Now let's load the first xstyle:
<link rel="xstylesheet" href="css/xstyle.css">
First xstyle code:
*, *:before, *:after {
box-sizing: border-box;
}
html {
overflow-y: scroll;
}
body {
background: #c1bdba;
font-family: 'Titillium Web', sans-serif;
}
a {
text-decoration: none;
color: #1ab188;
transition: .5s ease;
}
a:hover {
color: #179b77;
}
.form {
background: rgba(19, 35, 47, 0.9);
padding: 40px;
max-width: 600px;
margin: 40px auto;
border-radius: 4px;
box-shadow: 0 4px 10px 4px rgba(19, 35, 47, 0.3);
}
.tab-group {
list-xstyle: none;
padding: 0;
margin: 0 0 40px 0;
}
.tab-group:after {
content: "";
display: table;
clear: both;
}
.tab-group li a {
display: block;
text-decoration: none;
padding: 15px;
background: rgba(160, 179, 176, 0.25);
color: #a0b3b0;
font-size: 20px;
float: left;
width: 50%;
text-align: center;
cursor: pointer;
transition: .5s ease;
}
.tab-group li a:hover {
background: #179b77;
color: #ffffff;
}
.tab-group .active a {
background: #1ab188;
color: #ffffff;
}
.tab-content > div:last-child {
display: none;
}
h1 {
text-align: center;
color: #ffffff;
font-weight: 300;
margin: 0 0 40px;
}
label {
position: absolute;
-webkit-transform: translateY(6px);
transform: translateY(6px);
left: 13px;
color: rgba(255, 255, 255, 0.5);
transition: all 0.25s ease;
-webkit-backface-visibility: hidden;
pointer-events: none;
font-size: 22px;
}
label .req {
margin: 2px;
color: #1ab188;
}
label.active {
-webkit-transform: translateY(50px);
transform: translateY(50px);
left: 2px;
font-size: 14px;
}
label.active .req {
opacity: 0;
}
label.highlight {
color: #ffffff;
}
input, textarea {
font-size: 22px;
display: block;
width: 100%;
height: 100%;
padding: 5px 10px;
background: none;
background-image: none;
border: 1px solid #a0b3b0;
color: #ffffff;
border-radius: 0;
transition: border-color .25s ease, box-shadow .25s ease;
}
input:focus, textarea:focus {
outline: 0;
border-color: #1ab188;
}
textarea {
border: 2px solid #a0b3b0;
resize: vertical;
}
.field-wrap {
position: relative;
margin-bottom: 40px;
}
.top-row:after {
content: "";
display: table;
clear: both;
}
.top-row > div {
float: left;
width: 48%;
margin-right: 4%;
}
.top-row > div:last-child {
margin: 0;
}
.button {
border: 0;
outline: none;
border-radius: 0;
padding: 15px 0;
font-size: 2rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .1em;
background: #1ab188;
color: #ffffff;
transition: all 0.5s ease;
-webkit-appearance: none;
}
.button:hover, .button:focus {
background: #179b77;
}
.button-block {
display: block;
width: 100%;
}
.forgot {
margin-top: -20px;
text-align: right;
}
With the previous xstyle we take care of the personalization of the body of the html buttons etc. now we continue with the 2 xstyle that is in charge of the appearance of the crossword puzzle, like the edges, the frames, the turn changes the assigned turn, the next turn of the player etc.
<link rel="xstylesheet" href="css/xstyle2.css">
body {
background-image: url("../img/mbajava.jpg");
background-color: #ee6e73;
}
#puzzle {
width:100%;
margin: 0;
padding: 10px;
border: 1px solid black;
}
.square{
width:50px;
height:50px;
margin: 0;
padding: 0;
border-collapse: collapse;
position: relative;
}
.empty{
background-color:black;
}
.letter{
/* border: 1px solid black;
text-align: center;
cursor: pointer;*/
border: 1px solid #000000;
background: transparent;
position: relative;
z-index: 100;
text-align: center;
font-size: 20px;
font-weight: bold;
text-transform: uppercase;
cursor: pointer;
}
#puzzle_container{
float: left;
/* width:50%*/
height: 50%;
}
#hints_container{
float: left;
/* width:50%*/
height: 50%;
margin-left: 25px;
border-top-xstyle: dotted;
border-right-xstyle: solid;
border-bottom-xstyle: dotted;
border-left-xstyle: solid;
}
#buttons_container{
clear: both;
padding-top: 20px;
margin-left: 50px;
}
.active{
border-color: red;
}
.question_number{
position: absolute;
font-size: 12px;
color: grey;
left: 3px;
top: 3px;
}
td{
position:relative;
}
now we continue with the xstyle of the menu that is the one at the top of the game:
ul {
list-xstyle-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change the link color to #111 (black) on hover */
li a:hover {
background-color: #111;
}
.active {
background-color: #4CAF50;
}
.active2 {
background-color: #FF1744;
}
.active3 {
background-color: #4CAF50;
}
for now let's finish with the xstyles we keep loading jquery:
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
for jquery we use version 1.8.3 we can upload online:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
and finally we put my crossword script that is responsible for all of arming the crossword from 0, is dynamic is responsible for the cells and the search for the letter and word if it is correct to find the winner of both the word and the total of the crossword:
var turno = 0;
var puntaje_asignado = 500;
var jugadores = new Array();
var puntaje_jugador1 = new Array();
var puntaje_jugador2 = new Array();
var respuestas_ya_realizadas = new Array();
//jugadores=parent.parent.get_array_username();
jugadores.push("mbajava");
jugadores.push("andres");
//alert(jugadores);
$(window).load(function () {
var grid = [
[0, 0, 0, 0, '1', 0, 0, 0, 0, 0, 0, '7', 0, 0, 0],
[0, 0, 0, 0, '1', 0, 0, 0, 0, 0, '8', '7,8', '8', '8', 0],
[0, 0, 0, 0, '1', 0, '2', 0, 0, 0, 0, '7', 0, 0, 0],
[0, '3', '3', '3', '3,1', '3', '3,2', '3', '3', '3,4', 0, '7', 0, 0, '10'],
[0, 0, 0, 0, 0, 0, '2', 0, 0, '4', 0, '7', 0, 0, '10'],
[0, 0, 0, 0, 0, 0, '2', 0, 0, '4', 0, '7', 0, 0, '10'],
[0, 0, '5', '5', '5', '5', '5,2', '5', 0, '4', 0, '7', 0, 0, '10'],
[0, 0, 0, 0, 0, 0, '2', 0, 0, '4', 0, '7', 0, 0, '10'],
[0, 0, 0, 0, 0, 0, '2', 0, 0, 0, 0, '7', 0, 0, '10'],
['6', '6', '6', '6', '6', '6', '6,2', 0, 0, 0, 0, '9,7', '9', '9', '9,10'],
[0, 0, 0, 0, 0, 0, '2', 0, 0, 0, 0, 0, 0, 0, '10'],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '10'],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '10'],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
//alert(grid[3][4]);
var preguntas = ["producto colombiano",
"capital de caldas",
"Forma de comunicarse con la mente",
"congregacion a dioses",
"1 de los 7 pecados capitales",
"compañía francesa fabricante de ropa ",
"cuarto",
"animal con 7 vidas",
"entidad que estudia el espacio",
"máquina digital que lee <br>y realiza operaciones para convertirlos en datos. "
];
var repuestas = ["cafe",
"manizales",
"telepatia",
"altar",
"pereza",
"lacoste",
"habitacion",
"gato",
"nasa",
"computador"
];
//Dibuja grid
$.each(grid, function (i) {
var row = $('<tr></tr>');
$.each(this, function (j) {
if (this == 0) {
$(row).append('<td xclass="square empty"></td>');
} else {
var question_number = String(grid[i][j]).split(",");
// console.log("i" + i + " j" + j + " question" + question_number)
var starting_number = '';
var question_number_span = '';
for (var k = 0; k < question_number.length; k++) {
var direction = saber_direccion(question_number[k]);
var startpos = get_empieza_en_la_posicion(question_number[k], direction);
if (direction == "horizontal" && startpos[0] == i && startpos[1] == j) {
starting_number += question_number[k] + ",";
} else if (direction == "vertical" && startpos[0] == j && startpos[1] == i) {
starting_number += question_number[k] + ",";
}
}
if (starting_number != "") {
question_number_span = '<span xclass="question_number">' + starting_number.replace(/(^,)|(,$)/g, "") + '</span>';
}
var postablai = i + 1;
var postablaj = j + 1;
$(row).append('<td>' + question_number_span + '<div xclass="square letter" id="' + postablai + '_' + postablaj + '" data-number="' + this + '" contenteditable="true" onclick="tomar_celda('' + postablai + '_' + postablaj + '')"></div></td>');
}
});
$("#puzzle").append(row);
});
//Draw hints
var vertical_hints = $('<div id="vertical_hints"></div>');
var horizontal_hints = $('<div id="horizontal_hints"></div>');
$.each(preguntas, function (index) {
var direction = saber_direccion(index + 1);
if (direction == "horizontal") {
$(horizontal_hints).append('<div xclass="hint"><b>' + (index + 1) + '</b>.-' + preguntas[index] + '</hint>');
} else if (direction == "vertical") {
$(vertical_hints).append('<div xclass="hint"><b>' + (index + 1) + '</b>.-' + preguntas[index] + '</hint>');
}
});
$("#vertical_hints_container").append(vertical_hints);
$("#horizontal_hints_container").append(horizontal_hints);
$(".letter").keyup(function () {
var this_text = $(this).text();
if (this_text.length > 1) {
$(this).text(this_text.slice(0, 1));
}
if (this_text.length > 0) {
console.log("coloco una letra" + this_text);
cheakeamos_letra_por_letra();
miramos_si_gano();
}
});
$(".letter").click(function () {
// document.execCommand('selectAll', false, null);
$(".letter").removeClass("active");
$(this).addClass("active");
$(".hint").css("color", "initial");
var question_numbers = String($(this).data("number")).split(",");
//alert("ss"+this.id);
$.each(question_numbers, function () {
// alert("el this"+"#hints .hint:nth-child(" + this + ")");
// $("#hints .hint:nth-child(" + this + ")").css("color", "yellow");
});
});
function cambia_turno() {
if (turno === 0) {
turno = 1;
} else {
turno = 0;
}
$("#turno").text("!!turno para :" + jugadores[turno]);
//efectos jquery
animacion_jquery("#turno");
//efectos jquery
}
function animacion_jquery(elid) {
$(elid).fadeTo("normal", 0.2, function () {
// función callback
$(elid).removeClass("active3").addClass("active2");
});
$(elid).fadeTo("normal", 1.0, function () {
$(elid).removeClass("active2").addClass("active3");
});
$(elid).animate({left: '+=150'}, "slow");
$(elid).animate({top: '+=150'}, "slow");
$(elid).animate({left: '-=150'}, "slow");
$(elid).animate({top: '-=150'}, "slow");
}
$("#solve").click(function () {
var contador = 0;
if ($(".letter.active").length === 0)
return;
var question_numbers = String($(".letter.active").data("number")).split(",");
$.each(question_numbers, function () {
// var separar_letras = question_numbers.split("");
var question_numbers2 = question_numbers[contador];
contador++;
//fillAnswer(this) ;
console.log("evaluamos la pregunta" + question_numbers2);
if (evaluar_respuesta(this) === 1) {
if (respuestas_ya_realizadas.indexOf(question_numbers2) !== -1) {
console.log("ya respondistes la pregunta" + question_numbers2);
} else {
respuestas_ya_realizadas.push(question_numbers2);
console.log("respuesta correcta la agregamos a la lista" + question_numbers2 + " contador" + contador);
agregamos_puntaje();
}
// respuestas_ya_realizadas.push(question_numbers);
// alert("respuesta correcta" + contador);
} else {
console.log("respuesta incorrecta seguimos contador:" + contador + " pregunta:" + question_numbers2);
}
console.log("respuestas ya realizadas array es:" + respuestas_ya_realizadas);
});
});
function el_ganador_del_juego() {
if (respuestas_ya_realizadas.length === repuestas.length) {
if(sum(puntaje_jugador1)>sum(puntaje_jugador2)){
alert("se acabo el juego el ganador es:"+jugadores[0]);
} else if(sum(puntaje_jugador2)>sum(puntaje_jugador1)){
alert("se acabo el juego el ganador es:"+jugadores[1]);
}else{
alert("se acabo el juego hubo un empate");
}
} else {
//alert("no se ha terminado el juego"+respuestas_ya_realizadas.length
// +" y respuestas"+repuestas.length);
}
}
function miramos_si_gano() {
var contador = 0;
if ($(".letter.active").length === 0)
return;
var question_numbers = String($(".letter.active").data("number")).split(",");
$.each(question_numbers, function () {
// var separar_letras = question_numbers.split("");
var question_numbers2 = question_numbers[contador];
contador++;
//fillAnswer(this) ;
console.log("evaluamos la pregunta" + question_numbers2);
if (evaluar_respuesta(this) === 1) {
if (respuestas_ya_realizadas.indexOf(question_numbers2) !== -1) {
console.log("ya respondistes la pregunta" + question_numbers2);
} else {
respuestas_ya_realizadas.push(question_numbers2);
console.log("respuesta correcta la agregamos a la lista" + question_numbers2 + " contador" + contador);
agregamos_puntaje();
el_ganador_del_juego();
}
// respuestas_ya_realizadas.push(question_numbers);
// alert("respuesta correcta" + contador);
} else {
console.log("respuesta incorrecta seguimos contador:" + contador + " pregunta:" + question_numbers2);
}
console.log("respuestas ya realizadas array es:" + respuestas_ya_realizadas);
});
}
function agregamos_puntaje() {
if (turno === 0) {
puntaje_jugador1.push(puntaje_asignado);
animacion_jquery("#jugador1");
} else {
puntaje_jugador2.push(puntaje_asignado);
animacion_jquery("#jugador2");
}
enviamos_puntaje_a_la_interfaz();
}
function enviamos_puntaje_a_la_interfaz() {
$("#jugador1").text(jugadores[0] + ":" + sum(puntaje_jugador1));
$("#jugador2").text(jugadores[1] + ":" + sum(puntaje_jugador2));
$("#jugador1").removeClass("active3");
$("#jugador2").removeClass("active3");
}
function sum(array) {
var acum = 0;
for (var i = 0; i < array.length; i++) {
acum = acum + array[i];
}
return acum;
}
$("#check").click(function () {
// $("#puzzle td div").css("color", "initial");
for (var i = 0; i < repuestas.length; i++) {
comprobar_respuesta(i + 1);
}
});
function cheakeamos_letra_por_letra() {
for (var i = 0; i < repuestas.length; i++) {
comprobar_respuesta(i + 1);
}
}
function evaluar_respuesta(numero_pregunta) {
var bandera = 1;
var question_answer = repuestas[numero_pregunta - 1];
var la_direccion_a_donde_va = saber_direccion(numero_pregunta);
var empieza_en_la_posicion = get_empieza_en_la_posicion(numero_pregunta, la_direccion_a_donde_va);
var answer_letters = question_answer.split("");
if (la_direccion_a_donde_va === "horizontal") {
for (var i = 0; i < answer_letters.length; i++) {
if (evaluar_respuesta_ayuda($("#puzzle tr:nth-child(" + (empieza_en_la_posicion[0] + 1) + ") td:nth-child(" +
(empieza_en_la_posicion[1] + 1 + i) + ") div").text(), answer_letters[i]) === 0) {
bandera = 0;
}
}
} else if (la_direccion_a_donde_va === "vertical") {
for (var i = 0; i < answer_letters.length; i++) {
if (evaluar_respuesta_ayuda($("#puzzle tr:nth-child(" + (empieza_en_la_posicion[1] + 1 + i) + ") td:nth-child(" +
(empieza_en_la_posicion[0] + 1) + ") div").text(), answer_letters[i]) === 0) {//si al recorrer la letra de la tabla en esa parte es diferente a la letra de la respuesta no ha ganado
bandera = 0;
}
}
}
return bandera;
}
function evaluar_respuesta_ayuda(lo_que_esta_en_la_casilla, la_respuesta) {
// alert("lo que llega es:" + lo_que_esta_en_la_casilla + " " + la_respuesta);
if (lo_que_esta_en_la_casilla === la_respuesta)
{
// alert("si esta bien");
return 1;
} else {
// alert("esta mal")
return 0;
}
}
//borramos
function fillAnswer(question_number) {
// $("#puzzle td div").css("color", "initial");
var question_answer = repuestas[question_number - 1];
var direction = saber_direccion(question_number);
var startpos = get_empieza_en_la_posicion(question_number, direction);
var answer_letters = question_answer.split("");
if (direction === "horizontal") {
for (var i = 0; i < answer_letters.length; i++) {
$("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").text(answer_letters[i]);
}
} else if (direction === "vertical") {
for (var i = 0; i < answer_letters.length; i++) {
$("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").text(answer_letters[i]);
}
}
}
//borramos
function saber_direccion(numero_de_la_pregunta) {
var dire = "vertical";
console.log("numero pregunta:" + numero_de_la_pregunta);
//recorremos la matriz array
//y miramos si por los lados o arriba o abajo esta el mismo numero para saber la direccion
for (var i = 0; i < grid.length; i++) {
for (var j = 0; j < grid.length; j++) {
if (String(grid[i][j]).indexOf(numero_de_la_pregunta) !== -1) {
var errori = i - 1;
var errorj = j - 1;
if (grid[i + 1][j] === numero_de_la_pregunta) {
dire = "vertical";
}
if (errori !== -1) {
if (grid[i - 1][j] === numero_de_la_pregunta) {
dire = "vertical";
}
}
if (grid[i][j + 1] === numero_de_la_pregunta) {
dire = "horizontal";
}
if (errorj !== -1) {
if (grid[i][j - 1] == numero_de_la_pregunta) {
dire = "horizontal";
}
}
}
}
}
return dire;
}
function get_empieza_en_la_posicion(pregunta_numero, direction) {
if (direction == "horizontal") {
for (var i = 0; i < grid.length; i++) {
for (var j = 0; j < grid.length; j++) {
if (String(grid[i][j]).indexOf(pregunta_numero) != -1) {
return [i, j];
}
}
}
} else if (direction == "vertical") {
for (var i = 0; i < grid.length; i++) {
for (var j = 0; j < grid.length; j++) {
if (String(grid[j][i]).indexOf(pregunta_numero) != -1) {
return [i, j];
}
}
}
}
}
function comprobar_respuesta(numero_pregunta) {
var question_answer = repuestas[numero_pregunta - 1];
var direction = saber_direccion(numero_pregunta);
var startpos = get_empieza_en_la_posicion(numero_pregunta, direction);
var respuesta_separado_por_comas = question_answer.split("");
if (direction === "horizontal") {
for (var i = 0; i < respuesta_separado_por_comas.length; i++) {
if ($("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").text()
!== question_answer[i] &&
$("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").text() !== "") {
$("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").css("color", "red");
cambia_turno();
console.log("letra incorrecta continua el turno" + turno);
} else if ($("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").text()
=== question_answer[i] &&
$("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").text() !== "") {
$("#puzzle tr:nth-child(" + (startpos[0] + 1) + ") td:nth-child(" + (startpos[1] + 1 + i) + ") div").css("color", "green");
console.log("letra correcta continua el turno" + turno);
}
}
} else if (direction === "vertical") {
for (var i = 0; i < respuesta_separado_por_comas.length; i++) {
if ($("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").text()
!= question_answer[i]
&& $("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").text() != "") {
// alert("respuesta invalidad");
$("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").css("color", "red");
cambia_turno();
console.log("letra incorrecta continua el turno" + turno);
} else if ($("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").text()
=== question_answer[i]
&& $("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").text() != "") {
// alert("respuesta correcta");
$("#puzzle tr:nth-child(" + (startpos[1] + 1 + i) + ") td:nth-child(" + (startpos[0] + 1) + ") div").css("color", "green");
console.log("letra correcta continua el turno" + turno);
}
}
}
}
//mostrarmos jugadores
if (jugadores.length > 0) {
// alert(jugadores);
$("#jugador1").html("" + jugadores[0]);
$("#jugador2").html("" + jugadores[1]);
$("#turno").html("!comienza a jugar " + jugadores[turno]);
}
//mostrarmos jugadores
/* $("#cerrar_seccion").click(function () {
}); */
});//cerrando windowsload
function tomar_celda(posicion) {
var elpost = "#" + posicion;
var laultima_letra = $(elpost).text();
//alert(donde_puso_la_letra);
}
finally we finish, I hope I helped you do not forget about the credits quote my page mbajava thanks see you in another tutorial
how to create a table automatically with javascript and html
 |
create a table dynamically with javascript |
to create a table dynamically, that looks like an array, for an array tour:
<html>
<head>
<title>tuto mbaja.com</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="button" value="Genera una tabla" onclick="genera_tabla()">
<script>
function genera_tabla() {
var tamañoi=10;
var tamañoj=10;
// Get the reference of the body element
var body = document.getElementsByTagName("body")[0];
// Create a <table> element and a <tbody> element
var tabla = document.createElement("table");
var tblBody = document.createElement("tbody");
// Create the cells
for (var i = 0; i < tamañoi; i++) {
// Create the rows of the table
var hilera = document.createElement("tr");
for (var j = 0; j < tamañoj; j++) {
// Create a <td> element and a text node, make the node
// text be the content of <td>, place the <td> element at the end
// of the row of the table
var celda = document.createElement("td");
var textoCelda = document.createTextNode("["+i+","+j+"]");
celda.appendChild(textoCelda);
hilera.appendChild(celda);
}
// add the row to the end of the table (at the end of the tblbo elementdy)
tblBody.appendChild(hilera);
}
// position the <tbody> under the <table> element
tabla.appendChild(tblBody);
// append <table> into <body>
body.appendChild(tabla);
// modify the "border" attribute of the table and set it to "2";
tabla.setAttribute("border", "2");
}</script>
</body>
</html>
how to read a flat text file hosted from the server with javascript only line by line
 |
Read flat file txt with javascript |
welcome to mbajava the website where you learn to program step by step, in this xclass you will learn to read a flat file txt only using javascript, as online security can not read a file without first being loaded by the visitor, then we must have a flat file on the server which will load your content line by line, eliminating annoying line breaks,
the first is that we should create a notebook called mbajava.txt and we will add any content
therefore we create a .js and javascript file where we place the code that will be responsible for reading this flat file mba.js
var arrayData = new Array();
var archivoTxt = new XMLHttpRequest();
var fileRuta = 'mbajava.txt';
var dataSum = 0;
var tami=0;
var tamj=0;
archivoTxt.open("GET", fileRuta, false);
archivoTxt.send(null);
var txt = archivoTxt.responseText;
//console.log("" + txt + "");
//alert(txt);
var lines = txt.split("\n");
for (var n = 0; n < lines.length; n++)
{
var line = lines[n];
console.log(line);
}
We use XMLHttpRequest to load the flat file and get the answer or content.
of course we must have an html file to execute the javascript, we create an html file next to it called
mba.html
<!DOCTYPE html>
<!--
https://www.mbajava.com/
-->
<html>
<head>
<script src="mba.js"></script>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
execute this html file in the browser, and in the navigator for example chrome we type f12 to see the results by console:
dynamic puzzle in java with artificial intelligence solves the puzzle automatically with path in depth
 |
Dynamic puzzle in java artificial intelligence |
dynamic puzzle in java with artificial intelligence solves the riddle automatically with path in depth, is a project that I had to do while studying my career in computer engineering and systems at the University of Harvard in the field of data structures where I had to perform the game with artificial intelligence and when solving it it had to show the route in depth and the binary tree.
the condition that he asked us was to read an entry pad where the main configuration was to assemble the puzzle (1,2,3,4,5,6) and then solve the exit to the end with the armed tree and the route.
The first thing we must do is create a package or folder called puzzle and another called images, as we see in the following image:
 |
Dynamic puzzle in java artificial intelligence code structure |
inside the puzzle folder, we create a xclass called Arbol inside this xclass we place the following code:
package Puzzle;
import imagenes.Puzzle;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public xclass Arbol implements Cloneable,Runnable {
// Lista de tipo nodo creada para obtener el camino de la busqueda
public ArrayList camino;
// Se declara una lista de tipo nodo la cual contendr� los nodos abiertos
// es decir los nodos que aun no se han recorrido
ArrayList abiertos;
// Se declara una lista de tipo nodo la cual contendrq
// los nodos que han sido recorridos
// es decir, los nodos a los cuales se les han revisado los sucesores
ArrayList cerrados;
// Se declara una lista de tipo nodo que contendr�
// los sucesores obtenidos en cada busqueda
ArrayList sucesores;
//Se declara una lista de tipo element que contendra
// los elementos para forma el archivo xml
LinkedList datos = new LinkedList();
//variable de tipo int que contendra la secuencia de los nodos
int secuencia=0;
public Arbol() {
}
/**
* M�todo que realiza la b�squeda por anchura
*
* @author https://www.mbajava.com/
* @author mbajava.com
*
* @param inicial estado inicial del nodo
*
*/
public Node busquedaAnchura(Node inicial) {
System.out.println("/***********Busqueda por anchura***********/\n");
// Se declara una variable q de tipo Cola
Queue q = new LinkedList();
// Se inicializan las listas de abiertos y
// cerrados para asegurar que sean unicas
// dentro de la b�squeda
abiertos = new ArrayList();
cerrados = new ArrayList();
// Variable booleana que indica si ya se lleg� a la soluci�n o no
boolean esSolucion = false;
// Se adiciona a la Cola el estado inicial del nodo
q.add(inicial);
// Se adiciona a abiertos el estado inicial del nodo,
// es decir el nodo con el cual se
// comenzar� la iteracion
abiertos.add(inicial);
// Se llama el metodo printNode para imprimir el nodo,
// en este caso se pasa el nodo inicial
// y el padre nulo por ser el nodo Raiz
printNode(inicial, null);
// Se realiza un bucle mientras la Cola no est� vacia y
// la variable esSolucion no sea verdadera
while (!q.isEmpty() && esSolucion != true) {
// Se declara una variable de tipo nodo, se le asigna el primir
// objeto
// de la Cola y al mismo tiempo
// este elemento de la cola es eliminado
Node n = (Node) q.remove();
// Se inicializa la lista sucesores para asegurar que sea
// unica en el metodo de busqueda
sucesores = new ArrayList();
// Se obtiene los sucesores del nodo n
sucesores = n.sucesoresNodos(n);
// Se realiza un foreach para recorrer los sucesores
for (Node s : sucesores) {
// Se verifica que el sucesor s no se encuentre en
// las listas de abiertos y cerrados
if (s != null) {
if (!abiertos.contains(s) && !cerrados.contains(s)) {
// Si la validacion se cumple se adiciona el nodo s
// a la lista de abiertos
// evitando asi crear sucesores que realicen el mismo
// movimiento
abiertos.add(s);
// Se llama al metodo que imprime el nodo s
// con su respectivo nodo padre
printNode(s, s.papa);
// Se valida si el nodo s es una posible solucion
if (s.esEstadoFinal(s.getL1())) {
// Si s es solucion el estado de la
// variable esSolucion a verdadero
esSolucion = true;
// Se llama al metodo camino y se envia por parametros
// el nodo s
return s;
// camino(s);
// Se realiza un break para salirse del forEach
}
// Se adiciona el nodo s a la Cola
q.add(s);
}
}
}
// Se adiciona a la lista de cerrados el nodo que se
// encuentra en la posicion 0 de la lista de abiertos
// porque ya ha sido recorrido
cerrados.add(abiertos.get(0));
// Se remueve el nodo en la posicion 0 de dicha lista porque
// ha pasado a la lista de cerrados
// es decir, ya ha sido recorrido
abiertos.remove(0);
}
System.out.println("Numero de movimientos totales c: " + cerrados.size());
System.out.println("Numero de movimientos totales a: " + abiertos.size());
System.out.println("\n------Termina la b�squeda------\n");
return null;
}
/**
* M�todo que realiza la b�squeda por profundidad
*
* @author https://www.mbajava.com/
* @author https://www.mbajava.com/
*
* @param inicial estado inicial del nodo
*/
public Node busquedaProfundidad(Node inicial) {
System.out.println("/***********Busqueda por profundidad***********/\n");
// Se declara una variable s de tipo Pila y se inicializa
Stack s = new Stack();
// Se inicializan las listas de abiertos y cerrados
// para asegurar que sean unicas
// dentro de la b�squeda
abiertos = new ArrayList();
cerrados = new ArrayList();
// Se adiciona a abiertos el nodo inicial,
// es decir el nodo con el cual se
// comenzar� la iteracion
abiertos.add(inicial);
// Se adiciona a la Pila el nodo inicial
s.push(inicial);
// Se llama el metodo printNode para imprimir el nodo,
// en este caso se pasa el nodo inicial
// y el padre nulo por ser el nodo Raiz
printNode(inicial, null);
// Se declara una variable nodo n y se le asigna
// el primer elemento de la Pila, en este caso
// el estado inicial
Node n = (Node) s.peek();
// Se realiza un bucle mientras la Pila no este vacia y
// mientras n no sea un estado final (para esto se llama el
// metodo esEstadoFinal enviando por parametros las dos listas del nodo)
while (!s.isEmpty() && !n.esEstadoFinal(n.getL1())) {
// Se declara una variable hijo de tipo nodo y se inicializa en null
Node hijo = null;
// Se verifica que el nodo n no se encuentre nulo
if (n != null) {
// si se cumple la validacion anterior se realiza un
// forEach para recorrer los sucesores de n
for (Node a : n.sucesoresNodos(n)) {
if (a != null) {
// Se valida que el sucesor a no se encuentre
// en la lista de abiertos y cerrados
if (!abiertos.contains(a) && !cerrados.contains(a)) {
// Si se cumple la condicion anterior se asigna el valor
// a a la variable hijo
hijo = a;
// Se adiciona el nodo a a la lista de abiertos
abiertos.add(a);
// Se realiza un break para que solo evalue el primer
// sucesor del nodo n y realice
// la busqueda por profundidad
break;
}
}
}
// Se verifica que la variable hijo no sea nula
if (hijo != null) {
// Si se cumple la condicion anterior se llama al metodo
// printNode para que imprima el nodo hijo
// con su respectivo nodo padre
printNode(hijo, hijo.papa);
// Se adiciona el nodo hijo a la pila
s.push(hijo);
} else {
// Si la condicion if no se cumple se elimina el primer
// elemento de la pila
s.pop();
}
// Se verifica que la lista de abiertos no este vacia, esta
// validacion es necesaria
// ya que al llegar al ultimo elemento abiertos va a estar vacio
// y generaria una excepcion de desbordamiento
if (!abiertos.isEmpty()) {
// Se adiciona a la lista de cerrados el primer nodo de la
// lista de abiertos indicando que este elemto
// ya fue recorrido
cerrados.add(abiertos.get(0));
// Se elimina el primer elemento de la lista de abiertos
// porque ya fue recorrido
abiertos.remove(0);
}
// Se verifica que la pila no se encuentre vacia, esta
// validacion es necesaria porque en pasos anteriores
// se esta eliminando de la pila y si llega vacia generaria una
// excepcion
if (!s.isEmpty()) {
// Si se cumple la validacion anterior se asigna el primer
// elemento de la pila a la variable n
n = (Node) s.peek();
}
}
}
// Se llama al metodo camino y se envia por parametros el nodo s
System.out.println("Numero de movimientos totales: " + abiertos.size() + cerrados.size());
System.out.println("\n------Termina la b�squeda------\n");
return n;
}
public Node busquedaAEstrella2(Node inicial) throws IOException {
// Se inicializan las listas de abiertos y cerrados
// para asegurar que sean unicas
// dentro de la b�squeda
Puzzle pu= new Puzzle();
abiertos = new ArrayList();
cerrados = new ArrayList();
Node x = inicial;
// System.out.println("padre");
datos= pu.printNode(x, null,4);
printNode(x, null);
for (Node sucesor : x.sucesoresNodos(x)) {
if (sucesor != null) {
x.listaSucesores.add(sucesor);
}
}
abiertos.add(x);
boolean fallo = false;
while (!x.esEstadoFinal(x.getL1()) && fallo != true) {
if (abiertos.isEmpty()) {
fallo = true;
System.out.println("ERROR: La lista de abiertos est� vacia");
} else {
Node m = x;
if (m.esEstadoFinal(m.getL1())) {
camino(m);
break;
} else {
boolean b = false;
for (Node nprima : m.sucesoresNodos(m)) {
// Bandera implementacion codigo del cuaderno
if (nprima != null) {
for (int i = 0; i < abiertos.size(); i++) {
if (abiertos.get(i).getL1().equals(nprima.getL1())) {
b = true;
if ((Integer) nprima.getL2().get(0) < (Integer) abiertos.get(i).getL2().get(0)) {
Node copia = abiertos.get(i);
// printNode(copia, copia.papa);
copia.papa = m;
copia.getL2().set(0, nprima.getL2().get(0));
copia.getL2().set(2, ((Integer) nprima.getL2().get(0) + (Integer) copia.getL2().get(1)));
abiertos.remove(abiertos.get(i));
abiertos.add(copia);
break;
}
}
}
if (b != true) {
ArrayList temp = (ArrayList) cerrados.clone();
for (int i = 0; i < temp.size(); i++) {
Node copia = temp.get(i);
if (copia.getL1().equals(nprima.getL1())) {
b = true;
if ((Integer) nprima.getL2().get(0) < (Integer) copia.getL2().get(0)) {
cerrados.remove(copia);
nprima.listaSucesores = copia.listaSucesores;
cerrados.add(nprima);
recursionCambioGDeN(nprima);
}
break;
}
}
}
if (b != true) {
for (Node hijo : nprima.sucesoresNodos(nprima)) {
if (hijo != null) {
nprima.listaSucesores.add(hijo);
}
}
abiertos.add(nprima);
}
b = false;
m.listaSucesores.add(nprima);
}
}
}
//Se movieron de la linea donde se asigna x
abiertos.remove(x);
cerrados.add(m);
}
calcularMenorF(abiertos);
if (!abiertos.isEmpty()) {
x = abiertos.get(0);
//printNode(x, x.papa);
} else {
fallo = true;
}
}
System.out.println("N�mero de movimientos entre cerrados: " + cerrados.size());
System.out.println("N�mero de movimientos entre abiertos: " + abiertos.size());
// camino(x);
return x;
}
public void busquedaAEstrella(Node inicial) throws IOException {
// Se inicializan las listas de abiertos y cerrados
// para asegurar que sean unicas
// dentro de la b�squeda
Puzzle pu= new Puzzle();
abiertos = new ArrayList();
cerrados = new ArrayList();
Node x = inicial;
// System.out.println("padre");
datos= pu.printNode(x, null,4);
//printNode(x, null);
for (Node sucesor : x.sucesoresNodos(x)) {
if (sucesor != null) {
x.listaSucesores.add(sucesor);
}
}
abiertos.add(x);
boolean fallo = false;
while (!x.esEstadoFinal(x.getL1()) && fallo != true) {
if (abiertos.isEmpty()) {
fallo = true;
System.out.println("ERROR: La lista de abiertos est� vacia");
} else {
Node m = x;
if (m.esEstadoFinal(m.getL1())) {
camino(m);
break;
} else {
boolean b = false;
for (Node nprima : m.sucesoresNodos(m)) {
// Bandera implementacion codigo del cuaderno
if (nprima != null) {
for (int i = 0; i < abiertos.size(); i++) {
if (abiertos.get(i).getL1().equals(nprima.getL1())) {
b = true;
if ((Integer) nprima.getL2().get(0) < (Integer) abiertos.get(i).getL2().get(0)) {
Node copia = abiertos.get(i);
// printNode(copia, copia.papa);
copia.papa = m;
copia.getL2().set(0, nprima.getL2().get(0));
copia.getL2().set(2, ((Integer) nprima.getL2().get(0) + (Integer) copia.getL2().get(1)));
abiertos.remove(abiertos.get(i));
abiertos.add(copia);
break;
}
}
}
if (b != true) {
ArrayList temp = (ArrayList) cerrados.clone();
for (int i = 0; i < temp.size(); i++) {
Node copia = temp.get(i);
if (copia.getL1().equals(nprima.getL1())) {
b = true;
if ((Integer) nprima.getL2().get(0) < (Integer) copia.getL2().get(0)) {
cerrados.remove(copia);
nprima.listaSucesores = copia.listaSucesores;
cerrados.add(nprima);
recursionCambioGDeN(nprima);
}
break;
}
}
}
if (b != true) {
for (Node hijo : nprima.sucesoresNodos(nprima)) {
if (hijo != null) {
nprima.listaSucesores.add(hijo);
}
}
abiertos.add(nprima);
}
b = false;
m.listaSucesores.add(nprima);
}
}
}
//Se movieron de la linea donde se asigna x
abiertos.remove(x);
cerrados.add(m);
}
calcularMenorF(abiertos);
if (!abiertos.isEmpty()) {
x = abiertos.get(0);
//printNode(x, x.papa);
} else {
fallo = true;
}
}
System.out.println("Numero de movimientos entre cerrados: " + cerrados.size());
System.out.println("Numero de movimientos entre abiertos: " + abiertos.size());
camino(x);
}
// LLamar metodo que es recursivo
public ArrayList calcularMenorF(ArrayList listaAbiertos) {
Collections.sort(listaAbiertos);
return listaAbiertos;
}
public void recursionCambioGDeN(Node node) {
if (node.listaSucesores.size() == 0 && !node.listaSucesores.isEmpty()) {
for (int i = 0; i < node.listaSucesores.size(); i++) {
Node suc = node.listaSucesores.get(i);
if (abiertos.remove(suc)) {
int pesoMov = (Integer) suc.getL2().get(0) - (Integer) suc.papa.getL2().get(1);
suc.getL2().set(0, (Integer) node.getL2().get(0) + pesoMov);
suc.getL2().set(2, (Integer) suc.getL2().get(0) + (Integer) suc.getL2().get(1));
suc.papa = node;
abiertos.add(suc);
} else if (cerrados.remove(suc)) {
int pesoMov = (Integer) suc.getL2().get(0) - (Integer) suc.papa.getL2().get(1);
suc.getL2().set(0, (Integer) node.getL2().get(0) + pesoMov);
suc.getL2().set(2, (Integer) suc.getL2().get(0) + (Integer) suc.getL2().get(1));
suc.papa = node;
cerrados.add(suc);
recursionCambioGDeN(suc);
}
}
}
}
/**
* Metodo que imprime el camino de acuerdo a la busqueda que lo invoque
*
* @author https://www.mbajava.com/
* @author https://www.mbajava.com/
*
* @param nodoFinal recibe el nodo objetivo o el nodo respectivo al estado
* final
*/
public void camino(Node nodoFinal) throws IOException {
datos.clear();
// Se verifica que la variable nodoFinal no sea nula
if (nodoFinal != null) {
// Si la validacion anterior se cumple, se declara la variable
// nodoEvaluado de tipo nodo
// y se le asigna el valor de nodoFinal
Node nodoEvaluado = nodoFinal;
// Se inicializa la variable camino
camino = new ArrayList();
System.out.println("\nEl mejor camino es:\n ");
// Se realiza un bucle mientras el padre del nodo evaluado no sea
// nulo
while (nodoEvaluado.papa != null) {
// Si la validacion anterior se cumple se adiciona el nodo
// evaluado a la lista camino
camino.add(nodoEvaluado);
// Se reasigna el valor de nodoEvaluado por el padre de dicho
// nodo
nodoEvaluado = nodoEvaluado.papa;
}
// Se verifica que el nodo padre del nodo evaluado es igual a null
// para indicar que es el nodo raiz
if (nodoEvaluado.papa == null) {
// Se adiciona el nodoEvaluado a la lista camino
camino.add(nodoEvaluado);
}
// Se llama al metodo impimir camino enviando como parametro la
// lista de nodos camino
imprimirCamino(camino);
}
}
/**
* Metodo que imprime el nodo enviado por parametros,su nodo padre y su
* respectivo movimiento
*
* @author https://www.mbajava.com/
* @author https://www.mbajava.com/
*
* @param n : es el nodo evaluado
* @param papa : es el padre del nodo evaluado
*/
private void printNode(Node n, Node papa) {
int temp0=0;
int temp1=0;
int temp2=0;
int temp3=0;
int dato1=0;
int dato2=0;
// se crea el elemento inicial del grafo
Element root1 = new Element("Grafo");
// se adiciona el elemento a la lista de datos para ir formando el archivo xml
datos.add(root1);
// Se verificaque el nodo padre sea diferente de nulo
if (papa != null) {
if (!papa.getL2().isEmpty() && papa.getL2().size() > 3 && papa.getL2().get(3) != null) {
Object[][] matriz = (Object[][]) papa.getL2().get(3);
Object[][] matrizHijo = (Object[][]) n.getL2().get(3);
System.out.println("Papa");
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[0].length; j++) {
System.out.print(matriz[i][j]);
}
System.out.println();
}
System.out.println("Hijo");
boolean estado= true;
for (int i = 0; i < matrizHijo.length; i++) {
for (int j = 0; j < matrizHijo[0].length; j++) {
System.out.print(matrizHijo[i][j]);
if (matrizHijo[i][j] != matriz[i][j]) {
if(estado){
// System.out.println("boton " + i + j);
temp0=i;
temp1=j;
estado= false;
}else
{
// System.out.println("boton " + i + j);
temp2=i;
temp3=j;
estado= true;
}
}
}
System.out.println();
}
// Juego ju =new Juego();
System.out.println("temporales "+temp0+temp1 +temp2+temp3);
if(temp0==0 && temp1==0)
dato1=1;
if(temp0==0 && temp1==1)
dato1=2;
if(temp0==0 && temp1==2)
dato1=3;
if(temp0==1 && temp1==0)
dato1=4;
if(temp0==1 && temp1==1)
dato1=5;
if(temp0==1 && temp1==2)
dato1=6;
if(temp0==2 && temp1==0)
dato1=7;
if(temp0==2 && temp1==1)
dato1=8;
if(temp0==2 && temp1==2)
dato1=9;
if(temp2==0 && temp3==0)
dato2=1;
if(temp2==0 && temp3==1)
dato2=2;
if(temp2==0 && temp3==2)
dato2=3;
if(temp2==1 && temp3==0)
dato2=4;
if(temp2==1 && temp3==1)
dato2=5;
if(temp2==1 && temp3==2)
dato2=6;
if(temp2==2 && temp3==0)
dato2=7;
if(temp2==2 && temp3==1)
dato2=8;
if(temp2==2 && temp3==2)
dato2=9;
// tre if(matrizHijo[temp0][temp1]==0){
// ju.cambiar2(temp0,temp1);
// }
// else{
// ju.cambiar2(temp1,temp0);
// }
System.out.println();
} else {
System.out.println("Papa " + papa.getL1() + " con movimiento --> "
+ n.getMovimiento() + " llega al hijo " + n.getL1() + " g,h,f" + n.getL2());
conectarNodos(n, papa);
}
} else {
// Si no se cumple la verificacion del if est� indicando que es el
// nodo raiz
System.out.println("Raiz del grafo" + n.getL1() + " g,h,f " + n.getL2().get(3));
// Se crea el elemento raiz con el atributo movimiento
//y el texto correspondiente
Element item1 = new Element("Nodo_raiz");
item1.setText("" + n.getL1());
datos.add(item1);
}
}
//metodo que se encarga de conectar los nodos que forman el archivo XML
public void conectarNodos(Node n, Node padre) {
Element item2 = null;
secuencia++;
for (int i = 1; i < datos.size(); i++) {
if (datos.get(i).getText().equals("" + padre.getL1())) {
item2 = new Element("Nodo");
item2.setAttribute("movimiento", "" + n.getMovimiento());
item2.setAttribute("secuencia", "" + secuencia);
item2.setText("" + n.getL1());
}
if (item2 != null) {
if (!datos.get(i).getText().equals("" + item2.getText())) {
datos.get(i).addContent(item2);
datos.add(item2);
item2 = null;
}
}
}
}
public void generarXML(String url) {
datos.get(0).addContent(datos.get(1));
/*
* for (int i = 1; i < datos.size(); i++) {
* datos.get(0).addContent(datos.get(i)); }
*/
XMLOutputter outputter = new XMLOutputter();
try {
outputter.output(new Document(datos.get(0)), new FileOutputStream(url));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
/**
* Metodo que imprime el camino desde el nodo raiz hasta el nodo objetivo y
* sus respectivos movimientos
*
* @author https://www.mbajava.com/
* @author https://www.mbajava.com/
*
* @param camino : lista que contiene los nodos desde el nodo objetivo o
* nodo final hasta el nodo raiz
*/
public void imprimirCamino(ArrayList camino) throws IOException {
// Se realiza un bucle que recorra la lista descendentemente para
// imprimir los nodos desde la raiz
// hasta el nodo final o nodo objetivo
Puzzle pu = new Puzzle( );
int tamano = camino.size();
for (int i = tamano - 1; i >= 0; i--) {
pu.printNode(camino.get(i), camino.get(i).papa,i);
}
System.out.println();
pu.setVisible(true);
System.out.println("Numero de movimientos del camino: " + camino.size());
for (int j = 0; j < pu.lista.size(); j++) {
System.out.println(pu.lista.get(j));
}
pu.cambiar3(pu.lista);
pu.setVisible(true);
}
/***
*este metodo genera una archivo xml de la estructura del grafo actual
*@author Juan Carlos Vargas
* @param url url del archivo XML
*/
public void generateXML(String url) {
XMLGenerator xml = new XMLGenerator();
for (Node node : cerrados) {
xml.addNodeAndCreateArc(node);
}
for (Node node : abiertos) {
xml.addNodeAndCreateArc(node);
}
xml.addRoad(this.camino);
XMLGenerator.createFile(url, xml);
}
@Override
public void run() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
then in the same folder we created another xclass called juego:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Puzzle;
import java.awt.Label;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author mbajava.com
*/
public xclass Juego implements Runnable {
public LinkedList lista = new LinkedList();
public int[] cartas;
int j = -1;
int[] dato33;
int contador;
String[] dato23;
public JButton jb = new JButton();
public JButton m = new JButton();
public JButton uno;
public JButton dos;
public JButton tres;
public JButton cuatro;
public JButton cinco;
public JButton seis;
public JButton siete;
public JButton ocho;
public JButton nueve;
public JButton diez;
public JButton once;
public JButton doce;
public JButton trece;
public JButton catorce;
public JButton quince;
public JButton vacio;
public JLabel label = new JLabel();
public Juego() {
}
public Juego(JButton uno1, JButton dos2, JButton tres3, JButton cuatro4, JButton cinco5, JButton seis6, JButton siete7, JButton ocho8, JButton nueve9, JButton diez10, JButton once11, JButton doce12, JButton trece13, JButton catorce14, JButton quince15, JButton vacio1, int[] dato11) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("entrada.txt"));
jb = vacio1;
uno = uno1;
dos = dos2;
tres = tres3;
cuatro = cuatro4;
cinco = cinco5;
seis = seis6;
siete = siete7;
ocho = ocho8;
nueve = nueve9;
diez = diez10;
once = once11;
doce= doce12;
trece = trece13;
catorce = catorce14;
quince = quince15;
vacio = vacio1;
System.out.println("listo " + dato11[0]);
int pos = 0;
int n = 0;
contador = 0;
label.setText("" + contador);
boolean p;
String linea = reader.readLine();
dato23 = linea.split(",");
int tamaño = dato23.length;
dato33 = new int[tamaño];
for (int i = 0; i < dato23.length; i++) {
dato33[i] = Integer.parseInt(dato23[i]);
}
this.cartas = dato33;
// cartas= new int [8];
//// String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");
//// int [] dato33=new int [8];
//// 1,2,3,4,5,6,8,7has
//// dato23 = dato.split(",");
//// for (int i = 0; i < dato23.length; i++) {
//// dato33[i]=Integer.parseInt(dato23[i]);
//// cartas[i]=dato33[i];
//// System.out.println("descompuesto " + dato23[i]);
//// }2,3,1,4,6,7,5,8
// b,c,a,d,f,g,e,
// cartas[0]= dato11[0];
//
// cartas[1]=dato11[1];
//
// cartas[2]=dato11[2];
//
// cartas[3]=dato11[3];
//
// cartas[4]=dato11[4];
//
// cartas[5]=dato11[5];
//
// cartas[6]=dato11[6];
// cartas[7]=dato11[7];
// for (int x = 0; x < 8; x++) {
// do {
// n = (int) (Math.random() * 8 + 1);
// p = true;
// for (int y = 0; y < 8; y++) {
// if (cartas[y] == n) {
// p = false;
// break;
// }
// }
//
// } while (p == false);
// do {
// pos = (int) (Math.random() * 8 + 0);
// p = true;
// if (cartas[pos] != 0) {
// p = false;
// }
// } while (p == false);
// cartas[pos] = n;
// }
// for (int x = 0; x < 8; x++) {
// System.out.println(cartas[x]);
// }
if(tamaño<=8){
uno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[0] + ".jpg")));
uno.setMnemonic(cartas[0]);
uno.setToolTipText(Integer.toString(cartas[0]));
dos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[1] + ".jpg")));
dos.setMnemonic(cartas[1]);
dos.setToolTipText(Integer.toString(cartas[1]));
tres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[2] + ".jpg")));
tres.setMnemonic(cartas[2]);
tres.setToolTipText(Integer.toString(cartas[2]));
cuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[3] + ".jpg")));
cuatro.setMnemonic(cartas[3]);
cuatro.setToolTipText(Integer.toString(cartas[3]));
cinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[4] + ".jpg")));
cinco.setMnemonic(cartas[4]);
cinco.setToolTipText(Integer.toString(cartas[4]));
seis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[5] + ".jpg")));
seis.setMnemonic(cartas[5]);
seis.setToolTipText(Integer.toString(cartas[5]));
siete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[6] + ".jpg")));
siete.setMnemonic(cartas[6]);
siete.setToolTipText(Integer.toString(cartas[6]));
ocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[7] + ".jpg")));
ocho.setMnemonic(cartas[7]);
ocho.setToolTipText(Integer.toString(cartas[7]));
nueve.setVisible(false);
diez.setVisible(false);
once.setVisible(false);
doce.setVisible(false);
trece.setVisible(false);
catorce.setVisible(false);
quince.setVisible(false);
}
else
{
uno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[0] + ".jpg")));
uno.setMnemonic(cartas[0]);
uno.setToolTipText(Integer.toString(cartas[0]));
dos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[1] + ".jpg")));
dos.setMnemonic(cartas[1]);
dos.setToolTipText(Integer.toString(cartas[1]));
tres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[2] + ".jpg")));
tres.setMnemonic(cartas[2]);
tres.setToolTipText(Integer.toString(cartas[2]));
cuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[3] + ".jpg")));
cuatro.setMnemonic(cartas[3]);
cuatro.setToolTipText(Integer.toString(cartas[3]));
cinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[4] + ".jpg")));
cinco.setMnemonic(cartas[4]);
cinco.setToolTipText(Integer.toString(cartas[4]));
seis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[5] + ".jpg")));
seis.setMnemonic(cartas[5]);
seis.setToolTipText(Integer.toString(cartas[5]));
siete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[6] + ".jpg")));
siete.setMnemonic(cartas[6]);
siete.setToolTipText(Integer.toString(cartas[6]));
ocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[7] + ".jpg")));
ocho.setMnemonic(cartas[7]);
ocho.setToolTipText(Integer.toString(cartas[7]));
nueve.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[8] + ".jpg")));
nueve.setMnemonic(cartas[8]);
nueve.setToolTipText(Integer.toString(cartas[8]));
diez.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[9] + ".jpg")));
diez.setMnemonic(cartas[8]);
diez.setToolTipText(Integer.toString(cartas[9]));
once.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[10] + ".jpg")));
once.setMnemonic(cartas[10]);
once.setToolTipText(Integer.toString(cartas[10]));
doce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[11] + ".jpg")));
doce.setMnemonic(cartas[11]);
doce.setToolTipText(Integer.toString(cartas[11]));
trece.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[12] + ".jpg")));
trece.setMnemonic(cartas[12]);
trece.setToolTipText(Integer.toString(cartas[12]));
catorce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[13] + ".jpg")));
catorce.setMnemonic(cartas[13]);
catorce.setToolTipText(Integer.toString(cartas[13]));
quince.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen" + cartas[14] + ".jpg")));
quince.setMnemonic(cartas[14]);
quince.setToolTipText(Integer.toString(cartas[14]));
}
vacio.setMnemonic(9);
}
public void cambiar(JButton a, JButton b) {
JButton tem = new JButton();
tem.setIcon(a.getIcon());
a.setIcon(b.getIcon());
b.setIcon(tem.getIcon());
tem.setMnemonic(a.getMnemonic());
a.setMnemonic(b.getMnemonic());
b.setMnemonic(tem.getMnemonic());
tem.setToolTipText(a.getToolTipText());
a.setToolTipText(b.getToolTipText());
b.setToolTipText(tem.getToolTipText());
}
public synchronized void cambiar2(int j, int i) {
JButton tem = new JButton();
JButton a = new JButton();
// Thread t= new Thread("Puzzle");
// t.sleep(1000);
JButton b = new JButton();
//
// if(i==1)
// a=this.uno;
// if(i==2)
// a=this.dos;
// if(i==3)
// a=this.tres;
// if(i==4)
// a=this.cuatro;
// if(i==5)
// a=this.cinco;
// if(i==6)
// a=this.seis;
// if(i==7)
// a=this.siete;
// if(i==8)
// a=this.ocho;
// if(i==0)
a = this.vacio;
//
// if(j==0)
// b=this.vacio;
if (j == 1) {
b = this.uno;
}
if (j == 2) {
b = this.dos;
}
if (j == 3) {
b = this.tres;
}
if (j == 4) {
b = this.cuatro;
}
if (j == 5) {
b = this.cinco;
}
if (j == 6) {
b = this.seis;
}
if (j == 7) {
b = this.siete;
}
if (j == 8) {
b = this.ocho;
}
System.out.println("movio el " + j + "con el " + i);
tem.setIcon(a.getIcon());
a.setIcon(b.getIcon());
b.setIcon(tem.getIcon());
tem.setMnemonic(a.getMnemonic());
a.setMnemonic(b.getMnemonic());
b.setMnemonic(tem.getMnemonic());
tem.setToolTipText(a.getToolTipText());
a.setToolTipText(b.getToolTipText());
b.setToolTipText(tem.getToolTipText());
}
public void recibe(LinkedList hola) {
for (int i = 0; i < hola.size(); i++) {
this.lista.add(hola.get(i));
}
}
public void cambiar3(LinkedList hola) {
System.out.println("lista terminada");
for (int i = 0; i < hola.size(); i++) {
try {
i++;
JButton tem = new JButton();
JButton a = new JButton();
Thread t = new Thread("Puzzle");
t.sleep(1000);
JButton b = new JButton();
//
// if(i==1)
// a=this.uno;
// if(i==2)
// a=this.dos;
// if(i==3)
// a=this.tres;
// if(i==4)
// a=this.cuatro;
// if(i==5)
// a=this.cinco;
// if(i==6)
// a=this.seis;
// if(i==7)
// a=this.siete;
// if(i==8)
// a=this.ocho;
// if(i==0)
a = this.vacio;
//
// if(j==0)
// b=this.vacio;
if (lista.get(i) == 1) {
b = this.uno;
}
if (lista.get(i) == 2) {
b = this.dos;
}
if (lista.get(i) == 3) {
b = this.tres;
}
if (lista.get(i) == 4) {
b = this.cuatro;
}
if (lista.get(i) == 5) {
b = this.cinco;
}
if (lista.get(i) == 6) {
b = this.seis;
}
if (lista.get(i) == 7) {
b = this.siete;
}
if (lista.get(i) == 8) {
b = this.ocho;
}
System.out.println("movio el " + lista.get(i - 1) + "con el " + lista.get(i));
tem.setIcon(a.getIcon());
a.setIcon(b.getIcon());
b.setIcon(tem.getIcon());
tem.setMnemonic(a.getMnemonic());
a.setMnemonic(b.getMnemonic());
b.setMnemonic(tem.getMnemonic());
tem.setToolTipText(a.getToolTipText());
a.setToolTipText(b.getToolTipText());
b.setToolTipText(tem.getToolTipText());
} catch (InterruptedException ex) {
Logger.getLogger(Juego.xclass.getName()).log(Level.SEVERE, null, ex);
}
}
}
public JLabel botonUno() {
if (dos.getIcon() == null) {
cambiar(uno, dos);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 2");
} else if (cuatro.getIcon() == null) {
cambiar(uno, cuatro);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 4");
}
return label;
}
public JLabel botonDos() {
if (tres.getIcon() == null) {
cambiar(dos, tres);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 3");
} else if (cinco.getIcon() == null) {
cambiar(dos, cinco);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 5");
} else if (uno.getIcon() == null) {
cambiar(dos, uno);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 1");
}
return label;
}
public JLabel botonTres() {
if (seis.getIcon() == null) {
cambiar(tres, seis);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 6");
} else if (dos.getIcon() == null) {
cambiar(tres, dos);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 2");
}
return label;
}
public JLabel botonCuatro() {
if (siete.getIcon() == null) {
cambiar(cuatro, siete);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 7");
} else if (cinco.getIcon() == null) {
cambiar(cuatro, cinco);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 5");
} else if (uno.getIcon() == null) {
cambiar(cuatro, uno);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 1");
}
return label;
}
public JLabel botonCinco() {
if (seis.getIcon() == null) {
cambiar(cinco, seis);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 6");
}
if (dos.getIcon() == null) {
cambiar(cinco, dos);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 2");
} else if (cuatro.getIcon() == null) {
cambiar(cinco, cuatro);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 4");
} else if (ocho.getIcon() == null) {
cambiar(cinco, ocho);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 8");
}
return label;
}
public JLabel botonSeis() {
if (tres.getIcon() == null) {
cambiar(seis, tres);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 3");
} else if (cinco.getIcon() == null) {
cambiar(seis, cinco);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 5");
} else if (vacio.getIcon() == null) {
cambiar(seis, vacio);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 9");
}
return label;
}
public JLabel botonSiete() {
if (cuatro.getIcon() == null) {
cambiar(siete, cuatro);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 4");
} else if (ocho.getIcon() == null) {
cambiar(siete, ocho);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 8");
}
return label;
}
public JLabel botonOcho() {
if (siete.getIcon() == null) {
cambiar(ocho, siete);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 7");
} else if (cinco.getIcon() == null) {
cambiar(ocho, cinco);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 5");
} else if (vacio.getIcon() == null) {
cambiar(ocho, vacio);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 9");
}
return label;
}
public JLabel botonNueve() {
if (siete.getIcon() == null) {
cambiar(nueve, siete);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 7");
} else if (cinco.getIcon() == null) {
cambiar(nueve, cinco);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 5");
} else if (vacio.getIcon() == null) {
cambiar(nueve, vacio);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 9");
}
return label;
}
public JLabel botonVacio() {
if (seis.getIcon() == null) {
cambiar(vacio, seis);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 6");
} else if (ocho.getIcon() == null) {
cambiar(vacio, ocho);
contador++;
label.setText("" + contador);
System.out.println("vacio boton 8");
}
if (uno.getMnemonic() == 1 & cuatro.getMnemonic() == 4 & siete.getMnemonic() == 7 & dos.getMnemonic() == 2 & cinco.getMnemonic() == 5 & ocho.getMnemonic() == 8 & tres.getMnemonic() == 3 & seis.getMnemonic() == 6 & vacio.getMnemonic() == 9) {
JOptionPane.showMessageDialog(null, "Numero de Nodos " + contador);
// vacio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen.jpg")));
// JOptionPane.showMessageDialog(null, "Has Ganado"+"puntos "+contador);
//System.exit(0);
}
return label;
}
@Override
public void run() {
}
}
then in the same folder we created another xclass called Node:
then in the same folder we created another xclass called PuzzleModelo
then in the same folder we created another xclass called Vertices:
package Puzzle;
/**
*
* @author https://www.mbajava.com/
*/
public xclass Vertices {
private int x; //posiciòn en x del vertice
private int y; //posicion en y del vertice
private String txt; // texto que va en la posiciòn X y Y
private Object padre; //el padre del vertice actual
/**
* Constructor
* @param x posiciòn en x del vertice
* @param y posicion en y del vertice
* @param txt texto que va en la posiciòn X y Y
* @param padre el padre del vertice actual
*/
public Vertices(int x, int y, String txt, Object padre) {
this.x = x;
this.y = y;
this.txt = txt;
this.padre = padre;
}
/**
* @return retorna la posición en x
*/
public int getX() {
return x;
}
/**
* @param valor de la posicion en x
*/
public void setX(int x) {
this.x = x;
}
/**
* @return retorna la posicion en y
*/
public int getY() {
return y;
}
/**
* @param valor de la posicion en y
*/
public void setY(int y) {
this.y = y;
}
/**
* @return retorna el texto que va en la posiciòn X y Y
*/
public String getTxt() {
return txt;
}
/**
* @param establece el texto que va en la posiciòn X y Y
*/
public void setTxt(String txt) {
this.txt = txt;
}
/**
* @return retorna el padre del vertice actual
*/
public Object getPadre() {
return padre;
}
/**
* @param padre establece el padre del vertice actual
*/
public void setPadre(Object padre) {
this.padre = padre;
}
}
then in the same folder we create another xclass called XMLGenerator:
package Puzzle;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
*
* @author https://www.mbajava.com/
* @see es una representacion de la clase LibreriaBusquedas.Graph en un XML
* se pueden agregar nodos y arcos o un nodo con referencia a su padre y la clase
* ira constuyendo su estructura XML interna
*/
public xclass XMLGenerator {
private Element states;
private Element nodes;
private Element arcs;
private Element road;
public XMLGenerator() {
this.states = new Element("graph");
this.nodes = new Element("nodes");
this.arcs = new Element("arcs");
this.road = new Element("road");
this.states.addContent(nodes);
this.states.addContent(arcs);
this.states.addContent(road);
}
/**
* este metodo crea la estructura xml del grafo a partir de un nodo
* asignado nombre y conexiones con otros nodos
*
* su estructura final de nodo se representa de la sigueinte manera:
* entrada:
*
* Nodo:{
* my_id:1,
* l1<0>,
* l2
* parent:
* Nodo:{
* my_id:3,
* l1<0>,
* l2,
* movimiento:"LLenar jarra 3"
* }
* }
*
* creara una estructura como la siguente:
*
*
*
*
*
*
* LLenar jarra 3
*
*
*
* @author Juan Carlos Vargas
* @param node nodo de entrada con la estrucura correspondiente
* @see LibreriaBusquedas.Graph
* @see LibreriaBusquedas.Node
*/
public void addNodeAndCreateArc(Node node) {
Element xml_node = new Element("node");
xml_node.setAttribute("id", node.getMy_id() + "");
this.nodes.addContent(xml_node);
String state="";
for (Object stm : node.getL1()) {
Element xml_state = new Element("state");
state+=stm+",";
}
for (Object stm : node.getL2()) {
Element xml_state = new Element("state");
state+=stm+",";
}
state=(state.lastIndexOf(",")== state.length()-1)?state.substring(0,state.lastIndexOf(",")):state;
xml_node.setAttribute("state",state);
if (node.getPapa() != null) {
Element xml_arc = new Element("arc");
xml_arc.setAttribute("from", node.getPapa().getMy_id() + "");
xml_arc.setAttribute("to", node.getMy_id() + "");
xml_arc.setText(node.getMovimiento());
this.arcs.addContent(xml_arc);
}
}
/**
* crea el elemento road en el xml haciendo referencia a el camino solucion
* @author Juan Carlos Vargas
* @param lst lista de nodos con el cmaino solucion
* @return una variable string con los id de los nodos visitados en el camino separados por
* @see LibreriaBusquedas.Node
* un coma ','
*/
public void addRoad(ArrayList lst) {
String res = "";
for (Node node : lst) {
res += node.getMy_id() + ",";
}
res=(res.lastIndexOf(",")== res.length()-1)?res.substring(0,res.lastIndexOf(",")):res;
this.road.setAttribute("nodes", res);
}
//XML
/***
* @author Juan Carlos Vargas
*
*/
public static void createFile(String url,XMLGenerator xml_g) {
Element xml=xml_g.getRoot();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
try {
outputter.output(new Document(xml), new FileOutputStream(url));
} catch (Exception e) {
e.getMessage();
}
}
public static Document openFile(String url) {
SAXBuilder builder = new SAXBuilder(false);
Document res = null;
try {
res = builder.build(url);
} catch (JDOMException ex) {
Logger.getLogger(XMLGenerator.xclass.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(XMLGenerator.xclass.getName()).log(Level.SEVERE, null, ex);
}
return res;
}
public Element getRoot(){
return this.states;
}
}
0>0>
then in the same folder we create another NewJFrame xclass called FrmVisor:
package Puzzle;
import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;
import java.awt.*;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
/**
*
* @author https://www.mbajava.com/
*/
public xclass FrmVisor extends javax.swing.JDialog {
LinkedList datos = new LinkedList();
mxGraph graph; //se declara el elemento principal para dibujar el grafo
mxGraphComponent graphComponent; //se declara el panel sobre el cual sera dibujado el grafo
LinkedList vertices; //se declara la lista de vertices creados
String nom; //se declara el nombre del archivo XML a cargar
double numZoom = 1;
int numero;
BufferedReader reader = new BufferedReader(new FileReader("salida.txt"));
/**
*
* @param parent propietario del frame. si es null quiere decir que no tiene dueño
* @param modal especifica si se muestra o no el frame
* @param nom nombre del archivo XML a cargar
* @param zoom valor en double que incrementa o disminuye el tamano de vista de los nodos
* @throws JDOMException se lanza cuando ocurre error al leer o escribir datos del xml
* @throws IOException Excepción que se produce cuando se produce un error de E/S
*/
public FrmVisor(java.awt.Frame parent, boolean modal, String nom, double zoom) throws JDOMException, IOException {
super(parent, nom);
initComponents();
getContentPane().setBackground(new Color(204, 204, 255));
getContentPane().setLayout(new BorderLayout());
vertices = new LinkedList();
this.nom = "jarraBusquedaProfundida";
Zoom.setOrientation(JSlider.HORIZONTAL);
Zoom.setMajorTickSpacing(20);
Zoom.setMinorTickSpacing(1);
Zoom.setPaintTicks(true);
Zoom.setPaintLabels(true);
Zoom.setMinimum(-50);
Zoom.setMaximum(50);
Zoom.setValue(0);
Zoom.setMajorTickSpacing(10);
Zoom.setMinorTickSpacing(2);
Zoom.addChangeListener(new SliderListener());
jPanelZoom.setVisible(false);
initGUI(zoom);
}
/**
* Metodo en el que se encarga de inicializar y cargar todos los elementos
* de la interfaz Grafica
* @param num valor que es aplicado al tamaño de los elementos graficados. entre 0.01 y 0.99 aleja el foco y >1.0 acerca
* @throws JDOMException se lanza cuando ocurre error al leer o escribir datos del xml
* @throws IOException Excepción que se produce cuando se produce un error de E/S
*/
private void initGUI(double num) throws JDOMException, IOException {
setSize(800, 750); // se le asigna el tamaño al Frame
setLocationRelativeTo(null); // centramos en la pantalla el Frame
graph = new mxGraph(); //instanciamos el graph para dibujar el grafo
graphComponent = new mxGraphComponent(graph); //se enlaza el panel grafico con el graph
graphComponent.setPreferredSize(new Dimension(800, 750));
graphComponent.zoomTo(num, graphComponent.isCenterZoom()); //metodo que permite aplicar zoom a los elementos graficados
getContentPane().add(graphComponent); // conectamos el Frame con el panel en el que se grafica
// cargar(); //llama al metodo encargado de de cargar el archivo XML que se deseea dibujar
String linea = reader.readLine();
dibujarNodos(linea, this.getWidth() / 2, 60, null); //metodo que se encarga de dibujar los elementos hijos del nodo raiz
}
xclass SliderListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
numZoom = source.getValue();
}
}
/**
* Metodo que se encarga de cargar el XML y obtener el elemento principal
* para dibujar los nodos del grafo
* @throws JDOMException
* @throws IOException
*/
public void cargar() throws JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
// variable Document en la cual se carga todos los datos del archivo XML especificado
Document doc = builder.build(new FileInputStream("src\\Xml\\" + nom + "" + ".xml" + ""));
Element root = doc.getRootElement(); //se obtiene el elemento raiz el XML
List elementos = root.getChildren(); //Lista en la cual se cargan los elementos Hijos del elemento raiz
// dibujarNodos(elementos, this.getWidth() / 2, 90, null); //metodo que se encarga de dibujar los elementos hijos del nodo raiz
}
/**
* Metodo que se encarga de Graficar los nodos
* @param elementos lista de elementos hijos
* @param x posicion en x donde se desea dibujar el nodo
* @param y posicion en y donde se desea dibujar el nodo
* @param padre elemento padre
*/
public void dibujarNodos(String linea, int x, int y, Object padre) throws FileNotFoundException, IOException {
if (linea != null)
{
// lineapadre=reader.readLine();
// Aquí lo que tengamos que hacer con la línea puede ser esto
int d = posicion(padre);
//se verifica si se ha asignado una nueva posicion
if (d != 0) {
// si se cumple con la condiciòn anterior se le asigna a x el nuevo valor calculado
x = d;
}
// se valida si la posicion X y Y no se encuentra ocupada
x = validarPosicion(x, y);
// se actualiza el elemento proncipal para dibujar
graph.getModel().beginUpdate();
Object parent = graph.getDefaultParent();
int tamañoTexto = (linea.length()) * 6;
//Se crea el vertice con el contenido del texto del hijo
Object v1 = graph.insertVertex(parent, null, linea, x, y, tamañoTexto, 40, "shape=ellipse;perimeter=ellipsePerimeter;strokeColor=#871F78;fillColor=#EAEAAE");
//Se adiciona el nuevo vertice a la lista de vertices
vertices.add(new Vertices(x, y, linea, padre));
//Se verifica si el elemento es diferente al nodo raiz
if (padre != null) {
// se crea el arco entre el vertice padre y el vertice hijo la cual tiene la secuencia y el movimiento
graph.insertEdge(null, null, linea, padre, v1, "strokeColor=#871F78");
}
// se finaliza la actualizaciòn
graph.getModel().endUpdate();
//se verifica si la posiciòn en X es la mitad de frame es decir el nodo raiz
if (x == this.getWidth() / 2) {
// Se modifica la posicion en x
x = 50;
}
// y=y+10;
numero++;
//se hace un llamado recursivo con los hijos del nodo actual para graficarlos
dibujarNodos(reader.readLine(), x, (y + 50), v1);
// padre= linea;
//linea = reader.readLine();
}
// for (Element hijo : elementos) {
//
// se verifica que el elemento sea difente al ultimo elemento del archivo XML
// debido a que este no se grafica
// if (!hijo.getName().equals("Total")) {
//
// si se cumple la validacion anterior se verifica que en la posicion indicada
// no se encuentre ningun nodo graficado, si es el caso se asigna una posiciòn
// int d = posicion(padre);
//
// se verifica si se ha asignado una nueva posicion
// if (d != 0) {
// si se cumple con la condiciòn anterior se le asigna a x el nuevo valor calculado
// x = d;
// }
//
// se valida si la posicion X y Y no se encuentra ocupada
// x = validarPosicion(x, y);
//
// se actualiza el elemento proncipal para dibujar
// graph.getModel().beginUpdate();
// Object parent = graph.getDefaultParent();
//
// int tamañoTexto = (hijo.getText().length() - 1) * 6;
//
// Se crea el vertice con el contenido del texto del hijo
// Object v1 = graph.insertVertex(parent, null, hijo.getText(), x, y, tamañoTexto, 40, "shape=ellipse;perimeter=ellipsePerimeter;strokeColor=#871F78;fillColor=#EAEAAE");
//
// Se adiciona el nuevo vertice a la lista de vertices
// vertices.add(new Vertices(x, y, hijo.getText(), padre));
//
// Se verifica si el elemento es diferente al nodo raiz
// if (padre != null) {
// se crea el arco entre el vertice padre y el vertice hijo la cual tiene la secuencia y el movimiento
// graph.insertEdge(null, null, hijo.getAttribute("secuencia").getValue() + "---" + hijo.getAttribute("movimiento").getValue()+"--"+hijo.getAttribute("ghf").getValue(), padre, v1, "strokeColor=#871F78");
//
// }
// se finaliza la actualizaciòn
// graph.getModel().endUpdate();
//
// se verifica si la posiciòn en X es la mitad de frame es decir el nodo raiz
// if (x == this.getWidth() / 2) {
// Se modifica la posicion en x
// x = 100;
// }
//
// se hace un llamado recursivo con los hijos del nodo actual para graficarlos
// dibujarNodos(hijo.getChildren(), x, (y + 100), v1);
// }
// }
// }
}
/**
* Metodo que se encarga de calcular la nueva posiciòn de un nodo si ya
* existe uno en esta posiciòn
* @param x posiciòn en x de un nodo
* @param y posiciòn en y de un nodo
* @return x es el nuevo valor de x .
*/
public int validarPosicion(int x, int y) {
//se recorre la lista de vertices
for (Vertices v : vertices) {
//se verifica si ya existe un nodo en esta posiciòn
if (v.getX() == x && v.getY() == y) {
// si se cumple con la condiciòn anterior se a signa una nueva posiciòn a x
int newP = x + 400;
// retorna la nueva posicion de x
return newP;
}
}
//devuelve el valor original de x si no hay ningun nodo en esa posiciòn
return x;
}
/**
* Metodo que se encarga de asignar la posicion a un nodo dependiendo de su
* nodo hermano
* @param padre elemento padre
* @return xHermano es el nuevo valor de x calculado con respecto a la
* posicion de su ultimo hermano
*/
public int posicion(Object padre) {
//se declara una variable que contendra la posicion en x de un nodo
int xHermano = 0;
//se verifica si tiene padre
if (padre != null) {
//si cumple la condiciòn anterior se verifica
//si existen vertices en la lista de vertices
if (vertices.size() != 0) {
//si se cumple la condiciòn anterior se recorre la lista de vertices
for (Vertices v : vertices) {
//se verifica si el vertice actual tiene padre
if (v.getPadre() != null) {
//si se cumple la condiciòn anterior se verifica si el padre del
//vertice actual es igual al padre ingresado
if (v.getPadre().equals(padre)) {
//si se cumple la condiciòn anterior se le asigana a Xhermano
//la posicion en x del vertice mas 200
xHermano = v.getX() + 200;
}
}
}
//devuelve el valor de xHermano cuando se termina la lista
return xHermano;
}
}
//devuelve 0 en caso de que no tenga padre
return 0;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
//
private void initComponents() {
jPanelZoom = new javax.swing.JPanel();
Zoom = new javax.swing.JSlider();
jButton1 = new javax.swing.JButton();
btnZoom = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
formMouseWheelMoved(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
jPanelZoom.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton1.setFont(new java.awt.Font("Century", 1, 12)); // NOI18N
jButton1.setForeground(new java.awt.Color(102, 102, 102));
jButton1.setText("Aplicar Zoom");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanelZoomLayout = new javax.swing.GroupLayout(jPanelZoom);
jPanelZoom.setLayout(jPanelZoomLayout);
jPanelZoomLayout.setHorizontalGroup(
jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelZoomLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Zoom, javax.swing.GroupLayout.DEFAULT_SIZE, 569, Short.MAX_VALUE)
.addContainerGap())
);
jPanelZoomLayout.setVerticalGroup(
jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelZoomLayout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanelZoomLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Zoom, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)))
);
btnZoom.setFont(new java.awt.Font("Century", 1, 12)); // NOI18N
btnZoom.setForeground(new java.awt.Color(102, 102, 102));
btnZoom.setText("Zoom");
btnZoom.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnZoomActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 6, Short.MAX_VALUE)
.addComponent(btnZoom)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanelZoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanelZoom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(btnZoom)))
.addGap(0, 682, Short.MAX_VALUE))
);
pack();
}//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanelZoom.setVisible(false);
btnZoom.setVisible(true);
double tam = 1 + (0.01 * numZoom);
try {
FrmVisor visor = new FrmVisor(new javax.swing.JFrame(), true, nom, tam);
visor.setVisible(true);
this.setVisible(false);
} catch (JDOMException ex) {
Logger.getLogger(FrmVisor.xclass.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FrmVisor.xclass.getName()).log(Level.SEVERE, null, ex);
}
}
private void formMouseMoved(java.awt.event.MouseEvent evt) {
}
private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
// TODO add your handling code here:
}
private void btnZoomActionPerformed(java.awt.event.ActionEvent evt) {
jPanelZoom.setVisible(true);
btnZoom.setVisible(false);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FrmVisor.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmVisor.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmVisor.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmVisor.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/*
* Create and display the dialog
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrmVisor dialog = null;
try {
dialog = new FrmVisor(new javax.swing.JFrame(), true, "", 1);
} catch (JDOMException ex) {
Logger.getLogger(FrmVisor.xclass.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FrmVisor.xclass.getName()).log(Level.SEVERE, null, ex);
}
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JSlider Zoom;
private javax.swing.JButton btnZoom;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanelZoom;
// End of variables declaration
}
then we have formed the xclasses where we form the route and the trees as the puzzle, proceed to create a new package called images where we will place the images of the puzzle and the main xclass, we create within this folder the main xclass that is a derivative of NewJFrame called Puzzle:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package imagenes;
import Puzzle.*;
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
/**
*
* @author https://www.mbajava.com/
*/
public xclass Puzzle extends javax.swing.JFrame implements Runnable {
Element root1 = new Element("Grafo");
LinkedList datos = new LinkedList();
Juego juego;
BufferedReader reader = new BufferedReader(new FileReader("entrada.txt"));
int[] dato33 = null;
public LinkedList lista = new LinkedList();
public JButton uno1;
public JButton dos1;
public JButton tres1;
public JButton cuatro1;
public JButton cinco1;
public JButton seis1;
public JButton siete1;
public JButton ocho1;
public JButton vacio1;
public JButton nueve1;
public JButton diez1;
public JButton once1;
public JButton doce1;
public JButton trece1;
public JButton catorce1;
public JButton quince1;
String[] dato23;
public ArrayList camino;
// Se declara una lista de tipo nodo la cual contendr� los nodos abiertos
// es decir los nodos que aun no se han recorrido
ArrayList abiertos;
// Se declara una lista de tipo nodo la cual contendrq
// los nodos que han sido recorridos
// es decir, los nodos a los cuales se les han revisado los sucesores
ArrayList cerrados;
// Se declara una lista de tipo nodo que contendr�
// los sucesores obtenidos en cada busqueda
ArrayList sucesores;
int secuencia = 0;
public Puzzle() throws FileNotFoundException, IOException {
initComponents();
// String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");
// 1,2,3,4,5,6,8,7
// dato23 = dato.split(",");
// for (int i = 0; i < dato23.length; i++) {
// dato33[i]=Integer.parseInt(dato23[i]);
// System.out.println("descompuesto " + dato23[i]);
// }
// juego.cartas=dato33;
String linea =reader.readLine();
dato23 = linea.split(",");
int tamaño= dato23.length;
System.out.println(tamaño);
dato33 = new int[tamaño];
for (int i = 0; i < dato23.length; i++) {
dato33[i]=Integer.parseInt(dato23[i]);
}
// linea = reader.readLine();
//
// String dato = JOptionPane.showInputDialog("Ingrese las letras separadas por ,");
// // 1,2,3,4,5,6,8,7
// String[] dato23 = dato.split(",");
// for (int i = 0; i < dato23.length; i++) {
// dato33[i] = Integer.parseInt(dato23[i]);
// // cartas[i]=dato33[i];
//https://www.mbajava.com/
// System.out.println("descompuesto " + dato23[i]);
// }
juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho,btnNueve,btnDiez,btnOnce,btnDoce,btnTrece,btnCatorce,btnQuince, btnvacio, dato33);
// this.cambiar2(, 8);
// lista.add(6);
// lista.add(9);
// lista.add(5);
// lista.add(6);
// this.cambiar3(lista);
uno1 = this.btnUno;
dos1 = this.btndos;
tres1 = this.btntres;
cuatro1 = this.btncuatro;
cinco1 = this.btncinco;
seis1 = this.btnseis;
siete1 = this.btnsiete;
ocho1 = this.btnocho;
vacio1 = this.btnvacio;
nueve1 = this.btnNueve;
diez1= this.btnDiez;
once1= this.btnOnce;
doce1=this.btnTrece;
trece1= this.btnTrece;
catorce1= this.btnCatorce;
quince1=this.btnQuince;
//juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);
// this.setVisible(true);
// juego.lista.add(9);
// juego.lista.add(6);
//
// juego.lista.add(6);
// juego.lista.add(3);
// juego.cambiar3();
}
public LinkedList printNode(Node n, Node papa, int xx) throws IOException {
File f;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
File file = new File("salida.txt");
if (!file.exists()) {
if (file.createNewFile()) {
System.out.println("El fichero se ha creado correctamente");
} else {
System.out.println("No ha podido ser creado el fichero");
}
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF8"));
//PrintWriter wr = new PrintWriter(bw);
Element item3= new Element("Nodo_raiz");
JButton tem = new JButton();
JButton a = new JButton();
Element item1 = new Element("Nodo");
JButton b = new JButton();
int temp0 = 0;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;
int dato1 = 0;
int dato2 = 0;
// se crea el elemento inicial del grafo
// se adiciona el elemento a la lista de datos para ir formando el archivo xml
datos.add(root1);
// Se verificaque el nodo padre sea diferente de nulo
if (papa != null) {
if (!papa.getL2().isEmpty() && papa.getL2().size() > 3 && papa.getL2().get(3) != null) {
Object[][] matriz = (Object[][]) papa.getL2().get(3);
Object[][] matrizHijo = (Object[][]) n.getL2().get(3);
System.out.println("Papa");
System.out.println("Hijo");
boolean estado = true;
String dato11="";
for (int i = 0; i < matrizHijo.length; i++) {
for (int j = 0; j < matrizHijo[0].length; j++) {
dato11=dato11+matrizHijo[i][j]+"";
item1.setText("" + matrizHijo[i][j]);
datos.add(item1);
System.out.println(matrizHijo[i][j]);
if (matrizHijo[i][j] != matriz[i][j]) {
if (estado) {
// System.out.println("boton " + i + j);
temp0 = i;
temp1 = j;
estado = false;
} else {
// System.out.println("boton " + i + j);
temp2 = i;
temp3 = j;
estado = true;
// System.out.println("temporales "+temp0+temp1 +temp2+temp3);
if (temp0 == 0 && temp1 == 0) {
dato1 = 1;
}
if (temp0 == 0 && temp1 == 1) {
dato1 = 2;
}
if (temp0 == 0 && temp1 == 2) {
dato1 = 3;
}
if (temp0 == 1 && temp1 == 0) {
dato1 = 4;
}
if (temp0 == 1 && temp1 == 1) {
dato1 = 5;
}
if (temp0 == 1 && temp1 == 2) {
dato1 = 6;
}
if (temp0 == 2 && temp1 == 0) {
dato1 = 7;
}
if (temp0 == 2 && temp1 == 1) {
dato1 = 8;
}
if (temp0 == 2 && temp1 == 2) {
dato1 = 9;
}
if (temp2 == 0 && temp3 == 0) {
dato2 = 1;
}
if (temp2 == 0 && temp3 == 1) {
dato2 = 2;
}
if (temp2 == 0 && temp3 == 2) {
dato2 = 3;
}
if (temp2 == 1 && temp3 == 0) {
dato2 = 4;
}
if (temp2 == 1 && temp3 == 1) {
dato2 = 5;
}
if (temp2 == 1 && temp3 == 2) {
dato2 = 6;
}
if (temp2 == 2 && temp3 == 0) {
dato2 = 7;
}
if (temp2 == 2 && temp3 == 1) {
dato2 = 8;
}
if (temp2 == 2 && temp3 == 2) {
dato2 = 9;
}
if ((Integer)matrizHijo[temp0][temp1] != 0) {
lista.add(dato2);
} else {
lista.add(dato1);
}
}
}
}
System.out.println();
}
//wr.write(dato11);//escribimos en el archivo
//BufferedReader reader = new BufferedReader(new FileReader("nombreArchivo"));
//String linea = reader.readLine();
//while (linea != null)
//{
// // Aquí lo que tengamos que hacer con la línea puede ser esto
// wr.append(linea);
//
// linea = reader.readLine();
//}
System.out.println("escribe "+dato11);
out.write(dato11+"|");
out.write("\n");
out.close();
//ahora cerramos los flujos de canales de datos, al cerrarlos el archivo quedará guardado con información escrita
//de no hacerlo no se escribirá nada en el archivo
System.out.println();
} else {
System.out.println("Papa " + papa.getL1() + " con movimiento --> "
+ n.getMovimiento() + " llega al hijo " + n.getL1() + " g,h,f" + n.getL2());
// conectarNodos(n, papa);
}
} else {
// Si no se cumple la verificacion del if est� indicando que es el
// nodo raiz
System.out.println("Raiz del grafo" + n.getL1() + " g,h,f " + n.getL2().get(3));
// Se crea el elemento raiz con el atributo movimiento
//y el texto correspondiente
item3.setText("" + n.getL1());
datos.add(item3);
}
// if(xx==0){
// juego.cambiar3();
// juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);
return datos;
}
public LinkedList conectarNodos(Node n, Node padre) {
Element item2 = null;
secuencia++;
for (int i = 1; i < datos.size(); i++) {
if (datos.get(i).getText().equals("" + padre.getL1())) {
item2 = new Element("Nodo");
item2.setAttribute("movimiento", "" + n.getMovimiento());
item2.setAttribute("secuencia", "" + secuencia);
item2.setText("" + n.getL1());
}
if (item2 != null) {
if (!datos.get(i).getText().equals("" + item2.getText())) {
datos.get(i).addContent(item2);
datos.add(item2);
item2 = null;
}
}
}
return datos;
}
public void generateXML(String url) {
XMLGenerator xml = new XMLGenerator();
for (Node node : cerrados) {
xml.addNodeAndCreateArc(node);
}
for (Node node : abiertos) {
xml.addNodeAndCreateArc(node);
}
xml.addRoad(this.camino);
XMLGenerator.createFile(url, xml);
}
public void generarXML(String url) {
// System.out.println("GENERANDO DATOS");
/// datos.get(0).addContent(datos.get(1));
/*
* for (int i = 1; i < datos.size(); i++) {
* datos.get(0).addContent(datos.get(i)); }
*/
XMLOutputter outputter = new XMLOutputter();
try {
outputter.output(new Document(datos.get(0)), new FileOutputStream(url));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
//
private void initComponents() {
btnUno = new javax.swing.JButton();
btndos = new javax.swing.JButton();
btntres = new javax.swing.JButton();
btncuatro = new javax.swing.JButton();
btncinco = new javax.swing.JButton();
btnseis = new javax.swing.JButton();
btnsiete = new javax.swing.JButton();
btnocho = new javax.swing.JButton();
btnvacio = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
btnDiez = new javax.swing.JButton();
btnDoce = new javax.swing.JButton();
btnOnce = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
btnQuince = new javax.swing.JButton();
btnNueve = new javax.swing.JButton();
btnCatorce = new javax.swing.JButton();
btnTrece = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem2 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnUno.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
btnUno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUnoActionPerformed(evt);
}
});
btndos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen2.jpg"))); // NOI18N
btndos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btndosActionPerformed(evt);
}
});
btntres.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen3.jpg"))); // NOI18N
btntres.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btntresActionPerformed(evt);
}
});
btncuatro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen4.jpg"))); // NOI18N
btncuatro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btncuatroActionPerformed(evt);
}
});
btncinco.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen5.jpg"))); // NOI18N
btncinco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btncincoActionPerformed(evt);
}
});
btnseis.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen6.jpg"))); // NOI18N
btnseis.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnseisActionPerformed(evt);
}
});
btnsiete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen7.jpg"))); // NOI18N
btnsiete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnsieteActionPerformed(evt);
}
});
btnocho.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen8.jpg"))); // NOI18N
btnocho.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnochoActionPerformed(evt);
}
});
btnvacio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnvacioActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel3.setForeground(new java.awt.Color(204, 0, 102));
btnDiez.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
btnDiez.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDiezActionPerformed(evt);
}
});
btnDoce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen3.jpg"))); // NOI18N
btnDoce.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDoceActionPerformed(evt);
}
});
btnOnce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen2.jpg"))); // NOI18N
btnOnce.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOnceActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tempus Sans ITC", 1, 36)); // NOI18N
jLabel4.setForeground(new java.awt.Color(204, 0, 102));
btnQuince.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen7.jpg"))); // NOI18N
btnQuince.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnQuinceActionPerformed(evt);
}
});
btnNueve.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
btnNueve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNueveActionPerformed(evt);
}
});
btnCatorce.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen4.jpg"))); // NOI18N
btnCatorce.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCatorceActionPerformed(evt);
}
});
btnTrece.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imagen1.jpg"))); // NOI18N
btnTrece.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTreceActionPerformed(evt);
}
});
jMenu1.setText("File");
jMenuItem2.setText("Automatico");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(517, 517, 517)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(btnNueve, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnQuince, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCatorce, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnTrece, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(5, 5, 5)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(btnDiez, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnOnce, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDoce, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(btnsiete, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnocho, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnvacio, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btncuatro, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnUno, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btncinco, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btndos, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btntres, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnseis, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btnOnce, 0, 0, Short.MAX_VALUE)
.addComponent(btnDoce, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnDiez, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnNueve, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btndos, 0, 0, Short.MAX_VALUE)
.addComponent(btntres, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnUno, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btncuatro, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btncinco, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE)
.addComponent(btnseis, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnsiete, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(btnocho, 0, 0, Short.MAX_VALUE)
.addComponent(btnvacio, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(388, 388, 388))
.addGroup(layout.createSequentialGroup()
.addGap(226, 226, 226)
.addComponent(btnTrece, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnCatorce, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnQuince, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))))
.addContainerGap())
);
pack();
}//
private void btnUnoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonUno().getText());
}
private void btncincoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonCinco().getText());
}
private void btnvacioActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonVacio().getText());
}
private void btncuatroActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonCuatro().getText());
}
private void btndosActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonDos().getText());
}
private void btntresActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonTres().getText());
}
private void btnseisActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonSeis().getText());
}
private void btnsieteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonSiete().getText());
}
private void btnochoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jLabel3.setText(juego.botonOcho().getText());
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
PuzzleModelo pu = new PuzzleModelo(dato33);
Thread t = new Thread(pu);
t.start();
}
private void btnDiezActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnDoceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnOnceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnQuinceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnNueveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnCatorceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnTreceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Puzzle.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Puzzle.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Puzzle.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Puzzle.xclass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new Puzzle().setVisible(true);
Thread t = null;
try {
t = new Thread(new Puzzle());
} catch (FileNotFoundException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
}
t.start();
// pu.archivoInicial("s");
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnCatorce;
private javax.swing.JButton btnDiez;
private javax.swing.JButton btnDoce;
private javax.swing.JButton btnNueve;
private javax.swing.JButton btnOnce;
private javax.swing.JButton btnQuince;
private javax.swing.JButton btnTrece;
private javax.swing.JButton btnUno;
private javax.swing.JButton btncinco;
private javax.swing.JButton btncuatro;
private javax.swing.JButton btndos;
private javax.swing.JButton btnocho;
private javax.swing.JButton btnseis;
private javax.swing.JButton btnsiete;
private javax.swing.JButton btntres;
private javax.swing.JButton btnvacio;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem2;
// End of variables declaration
public void cambiar3(LinkedList hola) {
System.out.println("lista terminada");
for (int j = 0; j < hola.size(); j++) {
try {
Thread t = new Thread("Puzzle");
t.sleep(1000);
if (hola.get(j) == 1) {
juego.botonUno();
}
if (hola.get(j) == 2) {
juego.botonDos();
}
if (hola.get(j) == 3) {
juego.botonTres();
}
if (hola.get(j) == 4) {
juego.botonCuatro();
}
if (hola.get(j) == 5) {
juego.botonCinco();
}
if (hola.get(j) == 6) {
juego.botonSeis();
}
if (hola.get(j) == 7) {
juego.botonSiete();
}
if (hola.get(j) == 8) {
juego.botonOcho();
}
if (hola.get(j) == 9) {
juego.botonVacio();
}
System.out.println("llego el " + hola.get(j));
} catch (InterruptedException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void cambiar2(int i) {
try {
Thread t = new Thread("Puzzle");
t.sleep(1000);
if (i == 1) {
juego.botonUno();
}
if (i == 2) {
juego.botonDos();
}
if (i == 3) {
juego.botonTres();
}
if (i == 4) {
juego.botonCuatro();
}
if (i == 5) {
juego.botonCinco();
}
if (i == 6) {
juego.botonSeis();
}
if (i == 7) {
juego.botonSiete();
}
if (i == 8) {
juego.botonOcho();
}
repaint();
} catch (InterruptedException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
Puzzle p = null;
try {
p = new Puzzle();
// juego = new Juego(btnUno, btndos, btntres, btncuatro, btncinco, btnseis, btnsiete, btnocho, btnvacio);
} catch (FileNotFoundException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Puzzle.xclass.getName()).log(Level.SEVERE, null, ex);
}
p.setVisible(true);
}
}
and finally the images for the puzzle:
you can also download the project by mediafire executable java
click herechange the type of html form input when clicking on JavaScript, without jquery
 |
change input type when clicking,html JavaScript |
Sometimes we want to change the type of the input of a form of an HTML code, in order to show the user information when they click on a form or field, wbmaster is not necessary JavaScript only with HTML code is everything, in this example we are going to change a text type input to date to enter for example the system date in a database you can see this example here below
it's that easy and it is not necessary to load jquery, we only place the following code:
<input xclass="fieldname" id="acom_fechanaci1"
name="acom_fechanaci1" onfocus="(this.type='date')"
placeholder="click here to go from type text to date" type="text" />
as you can see, we use onfocus from html to be able to change the type of data in an input, I hope I have helped you share this entry and see you in the next
Download Roulette game in java socket socket multi-client
 |
Roulette game in java socket socket multi-clients gif |
In my free afternoons I developed a game of roulette made in pure java, which the environment was a spinning wheel that turned in itself using animation in java threads and socket, which only with a click of the mouse turned the roulette and stopped in a certain time, giving a score to the present user, or rather with the current ip.
the mechanism is easy we must have 2 pcs, or 2 machines, the 1 will be a server which will connect to the ip of the pc, and wait for one or more clients to connect, another pc with another ip will connect to the server giving the server ip, when you have made the connection the server saves it in a list and waits for other clients and so on, the good thing about this program is that it is multi-client, you can connect n users, all you want to connect, the same program I look below them so they can rehearse the program, we continue ...
 |
download Roulette game in java socket socket multi-client |
After connecting, we start the game, anyone can start playing, when they play the spinning wheel and it falls on a score this score sends it to the server and saves it in a list and so on, each client sends and returns the server's response, when it arrives to a certain percentage the winner is defined and the server will send the answer to the client who won to terminate the game, and to know if the winner.
On the server or the server owner can see the total score in real time, as well as the score of each client that connects and plays, the messages that arrive at the server are displayed in real time, to have a correct information of the data sent and received.
The program sells the pure code, made in java, it does not have any bookstore, and they can distribute it as long as they put the source code link, the code has a very cheap value, with respect to the strict and efficient code in which is developed, has a price of $ dollars and can pay it by paypal, will not regret this great code with its animation, besides having a good structure and intelligent at the time of receiving messages and respond both server and client.
The code handles linked lists, threads in java, and functions with which the development lends itself for large projects.
The code can be downloaded by mediafire, you can also watch a video on youtube which is in spanish here the YouTube video with its respective tutorial and operation:
Download of the complete project for pc with java Roulette game in java socket socket multi-clientsthe size of the download is very influential in the images because the code is simple and lightweight, the images gained weight as it was intended to give a good appearance on the spinner when turning.
the payment can be made by paypal, in the following link:
how to write notepad files in PHP and overwrite information in txt
 |
how to write notepad files in PHP and overwrite information in txt |
Today I will teach you how to write php files on the same server, can be a paid vps server or using any webmaster tool such as xampp for example, which can execute
PHP code, in this mini tutorial we will use as libraries or reference,
fwrite , PHP_EOL, File, fopen, and which will perform a function that allows to send by parameters the text, to which we want to record information in a file.
we will call the function create a file which we will pass by a parameter 1 text which we can place the text you want to record or write in the file, text 2 which would be another extra text that you want to show and another parameter that would show errors that would be a boolean if we want to use it later to indicate the function when writing the file and when not to write.
<?php
function createfile($texto1, $texto2,$showfile) {
if($showfile==1){
$file = fopen("archivo.txt", "a");
fwrite($file, "[" . $texto1 . ']' . PHP_EOL);
fwrite($file, "(" . $texto2 . ')' . PHP_EOL);
fclose($file);
}
}
?>
to use it is only to call the create file function, passing through parameters the variables mentioned above, below, I show an example code of how to call it:
<?php
createfile(a first message, a second message,1);
?>
after executing the function in this case a blog of notes .txt will be created with the messages sent by parameters, this file will create it next to the assigned php xclass or executed, if this code served you please give a like or share with your friend programmer thanks
show the days results between 2 dates in PHP code tutorial and free code | difference between 2 dates
 |
subtract 2 dates in PHP and show the days results tutorial and free code |
when the programmers in a php project we must use a function in php where you can show the days subtracted between 2 dates in this case we will take an old date: 11/05/2018 where this post was written and the date of today , we will use format which will give us the solution to know the days.
First we will change the old date as DateTime, to be able to use the function and subtract the days, but we will first use the function of php time (), in the following way:
date_default_timezone_set('America/new_york');
$time = time();
$dia1 = date("d", $time);
$mes1 = date("m", $time);
$ano1 = date("Y", $time);
$hhorao = date("h", $time);
$fechadehoy = $ano1 . '-' . $mes1 . '-' . $dia1;
where
$fechadehoy in php date takes today's exact date in both days, months and year,
date_default_timezone_set takes the local time on the server at the time it is captured.
then we use a function called
restardias which will return the days subtracted between these 2 dates:
function restardias($datetime1, $datetime2) {
// echo '' . $datetime1 . ' ' . $datetime2;
$interval = $datetime1->diff($datetime2);
$restar = $interval->format('%R%a');
return $restar;
}
In the old date we save it in a variable $fecha_ temp = "05/11/2018"; finally I will leave the complete code calling the function and showing the days subtracted with echo:
<?php
date_default_timezone_set('America/new_york');
function restardias($datetime1, $datetime2) {
// echo '' . $datetime1 . ' ' . $datetime2;
$interval = $datetime1->diff($datetime2);
$restar = $interval->format('%R%a');
return $restar;
}
$time = time();
$dia1 = date("d", $time);
$mes1 = date("m", $time);
$ano1 = date("Y", $time);
$hhorao = date("h", $time);
$fechadehoy = $ano1 . '-' . $mes1 . '-' . $dia1;
$fecha_temp="11/05/2018";
$datetime2 = new DateTime($fechadehoy);
$datetime1 = new DateTime($fecha_temp);
$rest = restardias($datetime1, $datetime2);
echo 'days results of the 2 dates:'.$rest;
?>
if you liked this post please share on social networks or with a friend programmer who is interested in the buttons on the web, I hope I have helped you until our next code
Hello, I bring you a bootstrap dashboard type template, which is done in my programming times, this template is optimized for mobile and adapts to any screen
the template programmed in php, has its mysql database, has its respective connections
the program has admission of administrators and super administrators, how much with income of employees and income of tenants, has management of invoices, payroll payments, etc. is only the template the part of programming will touch you.
the license is free but not commercial, can be used in condominiums and internal apartments not inlinea
zoom a java image from the pc and save it to the desktop
when we have a project in which we must take an image of the pc from java, and with the same OS of java to be able to zoom it for that we are going to take the bookstores AffineTransform,BufferedImage,Graphics2D,ImageIO , what we are going to do is load the image in a buffer then we keep it in a Graphics,we process it with ImageIO and we save it again with another name first the code which is a function to call it the function we will call it
cortaunpedazotyloacerca:
public void cortaunpedazotyloacerca() throws IOException{
BufferedImage bufferedImage = ImageIO.read(new File("a.jpg"));
BufferedImage dstinoimagencambiadabuffer = new BufferedImage(700, 700, BufferedImage.TYPE_INT_RGB);
Graphics2D g = dstinoimagencambiadabuffer.createGraphics();
AffineTransform httpswwwmbajavacom = AffineTransform.getScaleInstance(2, 2);
g.drawRenderedImage(bufferedImage, httpswwwmbajavacom);
ImageIO.write(dstinoimagencambiadabuffer, "JPG", new File("b.jpg"));
}
which is obvious that the image we want to edit is a.jpg and the image we want to zoom it to is b.jpg
for example a.jpg:
and when you apply zoom java and cut it would be as follows:
as we see we gave it a small, small-scale zoom.
we edit the scale in the part of the code AffineTransform.getScaleInstance(2, 2); where 2.2 is the zoom scale and you play with the zoom scale.
it's very easy, if you need to call the function you could call it from a main suppose that the xclass is called ImgJavaZoom:
/*
* https://www.mbajava.com/
* https://www.mbajava.com/
* and open the template in the editor.
*/
package ensayo;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
*
* @author andres
*/
public xclass ImgJavaZoom {
public void cortaunpedazotyloacerca() throws IOException{
BufferedImage bufferedImage = ImageIO.read(new File("a.jpg"));
BufferedImage dstinoimagencambiadabuffer = new BufferedImage(700, 700, BufferedImage.TYPE_INT_RGB);
Graphics2D g = dstinoimagencambiadabuffer.createGraphics();
AffineTransform httpswwwmbajavacom = AffineTransform.getScaleInstance(2, 2);
g.drawRenderedImage(bufferedImage, httpswwwmbajavacom);
ImageIO.write(dstinoimagencambiadabuffer, "JPG", new File("b.jpg"));
}
public static void main(String[] args) throws Exception {
ImgJavaZoom e= new ImgJavaZoom();
e.cortaunpedazotyloacerca();
}
}
Avoid losing your AdSense account with this anti-fraud click for blogger
many times we lose our account for not having protected the ads and banning the Adsense account as google tells us that we as publishers must protect from invalid clicks that make malicious users, by the Google Adsense policies this 2019 maximum you could receive 3 clicks per ad and the rest could be taken as invalid clicks.
This is why MBA java has taken the honor, to highlight a code in javascript to avoid that danger of our account be discharged and lose our dollars in that way easy that we give you the free code without much more preamble we proceed to install our code in blogger.
1. The first thing we should do is go to our blog:
2.the second thing we should do is go to topic -> edit html:
3.the third thing that we must do is when we are already inside html we look for the label </body> it's like at the end:
4. Just before that label you must paste this code, just before:
.estilotextarea4 {background-color: transparent;border: 1px solid #000000;scrollbar-arrow-color: #000066;scrollbar-base-color: #000033;scrollbar-dark-shadow-color: #336699;scrollbar-track-color: #666633;scrollbar-face-color: #cc9933;scrollbar-shadow-color: #DDDDDD;scrollbar-highlight-color: #CCCCCC;} get the year, month, day, hour, minute, second with php code easy
for the programming and php MBA data of dates is very necessary, especially when using any database manager such as MySQL, PostgreSQL, Oracle, etc.
and have the exact time of a record in a tuple, here on this web page we will teach you how to take the exact date, to be able to register it in the database or show it on the page.
the first thing to do is call the variable date_default_timezone_set this variable is responsible for obtaining the time zone of the region in this case we are going to use America / Los_Angeles.
date_default_timezone_set('America/Los_Angeles');
So we will tell you to take the region of the angels if you want to know more about this variable here:
date_default_timezone_set php.netwe just need to call the variable time (), which will give us the exact time of the server to which we consulted and we will obtain in several variables the year, month, day, hour, minute, second with its respective letter:
$time = time();
$day = date("d", $time);
$month = date("m", $time);
$year = date("Y", $time);
$hour = date("h", $time);
$minute = date("i", $time);
$second = date("s", $time);
- date("d", $time); we will get the day.
- date("m", $time); we will get the month.
- date("Y", $time); we will get the year
- date("h", $time); we will get the time
- date("i", $time); we will get the minute
- date("s", $time); we will get the second
In this way we can store it in a string, concatenate it and show it on an exact date:
$todaydate = '' . $year . '-' . $month . '-' . $day. ' ' . $hour.':'.$minute.':'.$second;
and finally all the code as it would be:
<?php
date_default_timezone_set('America/Los_Angeles');
$time = time();
$day = date("d", $time);
$month = date("m", $time);
$year = date("Y", $time);
$hour = date("h", $time);
$minute = date("i", $time);
$second = date("s", $time);
$todaydate = '' . $year . '-' . $month . '-' . $day. ' '
. $hour.':'.$minute.':'.$second;
echo "today date is: ".$todaydate;
?>
if you liked it you can leave a comment or share this post with a friend programmer =)
In our MBA course in java Many times we find that in the login of our project, especially when starting the section, we must send some parameters to get the data entered and verified in the user record to save them in a section in php, and use them later in our project in java but it turns out that it is unorthodox and ordinary to have to call or save several $ _SESSION or sections knowing that we can use an arrangement in php, a bad programming tendency is to use it in the following way, consulting in the base of data an example so to speak:
Send an array object for $ _SESSION php and use it in another xclass by calling the row
$_POST['userlogin']=$row['user_login'];
$_POST['useremail']=$row['user_email'];
$_POST['username']=$row['user_name'];
$_POST['userphone']=$row['user_phone'];
echo 'etc...etc... =)';
The above is a shame for programming should not use it, for that there are the arrays or programming vectors a way to use it in our project is like this:
1. obviously we must load the start section in our project:
session_start();
Where we are going to use the $ _SESSION we must add the code above hopefully in the first lines of php, now suppose that you already have the configuration and the connection with the database
now once the users enter by means of the login in the part where the section is saved, let's take as validadar.php that comes after the login.php where you enter the data in this way:
$lasentencia="select * from mytable";
$sql= mysqli_query($link,$lasentencia);
where mytable is the name of your table and $link is the result of @mysqli_connect connection.php:
$link = @mysqli_connect($db_host,$db_usuario,$db_password,$db_nombre)
or die(mysqli_connect_error($link));
now we only search the row with a condition that if there are results of that query:
if($row = mysqli_fetch_array($sql)){
$_SESSION['objLogin'] = $row;
}
$_SESSION['objLogin'] = $row; we save it in this object as an array or vector here all the data of the query will be saved name, surname, telephone etc ...
with this we are sending an array to the section and ask it to save that vector to use it later, now after saving let's say we are in validar.php we use it in another xclass for example called content.php let's say we need user information as the name:
session_start();
if (isset($_SESSION['objLogin']['name'])) {//we validate that it does not arrive empty https://www.mbajava.com/
echo 'your name is:
'.$_SESSION['objLogin']['name'];
}else{
echo 'sorry not data';
}
and so we can consult each row of our database in a single line another way is to call it by means of its location of the vector example the first attribute or data of the vector in position 0 is name then we will call it like this:
session_start();
if (isset($_SESSION['objLogin'][0])) {//we validate that it does not arrive empty https://www.mbajava.com/
echo 'your name is:
'.$_SESSION['objLogin'][0];
}else{
echo 'sorry not data';
}
and so we can call each one in a different way I hope I have helped them do not forget to subscribe to this page of masters of MBA programming leave a comment if I help you or any questions