问:
A PHP function that adds # hashtag to an array of words
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;
```

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

答:
How can it be optimized:

Limit amount instructions that needs to be executed for each needle

Use such instructions that are faster

Change execution path approach so whole app uses solution in more efficient way

so it goes:

strpos($haystack, $what) - this function can be removed

str_replace() can be replaced with in_array() that should be faster.

In your example code str_replace() needs to search for a letter to change whole $haystack length multiplied by count of needles so if haystack is 10 characters long and you have 5 needles this means that str_replace does search on total 500 characters (5 times search in 100 char string). If there are not 5 but 10 needles and haystack is 1000 chars then the length jumps up to 10k length in total characters for str_replace to process. That's why you see a dramatic slow down of execution when you increase number of needles or/and haystack length. Ideally the search should be done once for whole haystack length so if there are 5 needles and haystack is 100 chars the search should be done only once and at the total characters of 100 chars that the search need to look at.
Additionally: For long strings that are stored in files you may skip loading them into memory at all by using streams and read them one by one character directly from the file and replacing them on the fly.

code:

```<code><?php

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

function convert($needles, $haystack) {

    if(is_resource($haystack)) {
        $stream = $haystack;
    } else {
        $stream = fopen('data://text/plain,' . $haystack,'r');
    }

    while($char = fgetc($stream)) {
        if(in_array($char, $needles)) {
            $result = '#' . $char;
        } else {
            $result = $char;
        }

        yield $result;
    }

    if(is_resource($stream)) {
        fclose($stream);
    }
}

# use with haystack as string
$converted = convert($needles, $haystack);

# or use when haystack is in file
// $filePath = 'test-file.txt';
// $fileResource = fopen($filePath, 'r');
// $converted = convert($needles, $fileResource);

//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}
</code>```

gives:

```<code>#a b #c #d e f g
</code>```

how to use:

put function convert() {} definition wherever you like and later use it:

```<code>$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

$converted = convert($needles, $haystack);
</code>```

$converted is now a kind of array that each element of it is one character of the string that is converted. So to get all characters echoed you treat it as an array

['#a', 'b', '#c', '#d', 'e', 'f', 'g']

and echo inside foreach loop:

```<code>//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}
</code>```

the nice thing is that the "kind of array" is never created it only looks and feels like an array for foreach but actually it returns only one character modified foreach iteration. Therefore a memory consumption of convert() is almost nothing.

the second approach (ad 3.) is to read whole haystack from file and process it on the fly. This approach can handle even very large haystack because it does not read it to the memory at once and store whole before processing but reads one char from input and then change it and echoes, and another one.

comment this block of code:

```<code>//$converted = convert($needles, $haystack);
</code>```

and uncomment this:

```<code># or use when haystack is in file
$filePath = 'test-file.txt';
$fileResource = fopen($filePath, 'r');
$converted = convert($needles, $fileResource);
</code>```

then echo like before with foreach

```<code>//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}
</code>```

if you want to store converted text into string you can do it like that:

```<code>    $convertedStr = '';
    foreach($converted as $convertedChar) {
        $convertedStr .= $convertedChar;
    }

    //and echo or save later
    echo $convertedStr;
</code>```

Body:
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

Body:
How can it be optimized:

Limit amount instructions that needs to be executed for each needle

Use such instructions that are faster

Change execution path approach so whole app uses solution in more efficient way

so it goes:

strpos($haystack, $what) - this function can be removed

str_replace() can be replaced with in_array() that should be faster.

In your example code str_replace() needs to search for a letter to change whole $haystack length multiplied by count of needles so if haystack is 10 characters long and you have 5 needles this means that str_replace does search on total 500 characters (5 times search in 100 char string). If there are not 5 but 10 needles and haystack is 1000 chars then the length jumps up to 10k length in total characters for str_replace to process. That's why you see a dramatic slow down of execution when you increase number of needles or/and haystack length. Ideally the search should be done once for whole haystack length so if there are 5 needles and haystack is 100 chars the search should be done only once and at the total characters of 100 chars that the search need to look at.
Additionally: For long strings that are stored in files you may skip loading them into memory at all by using streams and read them one by one character directly from the file and replacing them on the fly.

code:

<?php

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

function convert($needles, $haystack) {

    if(is_resource($haystack)) {
        $stream = $haystack;
    } else {
        $stream = fopen('data://text/plain,' . $haystack,'r');
    }

    while($char = fgetc($stream)) {
        if(in_array($char, $needles)) {
            $result = '#' . $char;
        } else {
            $result = $char;
        }

        yield $result;
    }

    if(is_resource($stream)) {
        fclose($stream);
    }
}

# use with haystack as string
$converted = convert($needles, $haystack);

# or use when haystack is in file
// $filePath = 'test-file.txt';
// $fileResource = fopen($filePath, 'r');
// $converted = convert($needles, $fileResource);

//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}

gives:

#a b #c #d e f g

how to use:

put function convert() {} definition wherever you like and later use it:

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';

$converted = convert($needles, $haystack);

$converted is now a kind of array that each element of it is one character of the string that is converted. So to get all characters echoed you treat it as an array

['#a', 'b', '#c', '#d', 'e', 'f', 'g']

and echo inside foreach loop:

//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}

the nice thing is that the "kind of array" is never created it only looks and feels like an array for foreach but actually it returns only one character modified foreach iteration. Therefore a memory consumption of convert() is almost nothing.

the second approach (ad 3.) is to read whole haystack from file and process it on the fly. This approach can handle even very large haystack because it does not read it to the memory at once and store whole before processing but reads one char from input and then change it and echoes, and another one.

comment this block of code:

//$converted = convert($needles, $haystack);

and uncomment this:

# or use when haystack is in file
$filePath = 'test-file.txt';
$fileResource = fopen($filePath, 'r');
$converted = convert($needles, $fileResource);

then echo like before with foreach

//echo converted string char by char
foreach($converted as $convertedChar) {
    echo $convertedChar;
}

if you want to store converted text into string you can do it like that:

    $convertedStr = '';
    foreach($converted as $convertedChar) {
        $convertedStr .= $convertedChar;
    }

    //and echo or save later
    echo $convertedStr;


来源: stackexchange

问:
Airflow - No module named 'airflow.contrib.operators.mssql_to_gcs'
I found this operator in GitHub https://github.com/apache/airflow/blob/master/airflow/contrib/operators/mssql_to_gcs.py

but when I try to run, I get this error message:

```<code> No module named 'airflow.contrib.operators.mssql_to_gcs'.
</code>```

What do I need to do to make it work?

答:
MsSqlToGoogleCloudStorageOperator was introduced on Apr 22 2019. And it hasn't been released yet. If you want to use it, copy the code and use it as your own plugin.

Reference:
https://github.com/apache/airflow/commits/master/airflow/contrib/operators/mssql_to_gcs.py

ContentLicense: CC BY-SA 4.0

Body:
I found this operator in GitHub https://github.com/apache/airflow/blob/master/airflow/contrib/operators/mssql_to_gcs.py

but when I try to run, I get this error message:

 No module named 'airflow.contrib.operators.mssql_to_gcs'.

What do I need to do to make it work?


问:
Ajax GET returns 404 not found on CentOS
So I have a project in Laravel in which I use Ajax to move between views, so no data, only GET request.

This works fine on my local machine but I uploaded it to my VPS and when I click the button that should take me to another view, I get this error:

```<code>GET http://172.106.202.124/trabajos?_=1559303733962 404 (Not Found)
</code>```

So I've done some research and found some people with the same issue, but I haven't found any working answer.

Some said to modify .htaccess, I already did that and it's the same for me.

I've noticed that if I write /index.php/trabajos in the URL it gives me 'trabajos' view, but if I remove the /index.php/ it just gives me 'Not found'

This is my js code:

```<code> $(document).on('click', '#button1', function() {
        $.ajax({
                method: "GET",
                url:'/trabajos',
                success:function(result) {

                        $("#app").html(result).hide().fadeIn(1200);
                },
                error : function(e){
                        console.info("Error");
                }
                });
        });

</code>```

And these are my routes:

```<code>Route::get('/', function () {
    return view('master');
});
Route::get('/main', function () {
    return view('main');
});
Route::get('/trabajos', function(){
    return view('menu.trabajos');
});
Route::get('/contacto', function(){
    return view('menu.contacto');
});
Route::get('/empresa', function(){
    return view('menu.empresa');
});
</code>```

This is my httpd config:

```<code>#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory /var/www/laravel/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html/imprenta/public/"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
</code>```

I get this error with the config:

```<code>* httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-31 08:44:37 EDT; 24s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 28971 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 28969 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 28969 (code=exited, status=1/FAILURE)

May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Starting The Apache HTTP Server...
May 31 08:44:37 server.imprentasanchez.tk httpd[28969]: AH00534: httpd: Configuration erro....
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: main process exited, ...E
May 31 08:44:37 server.imprentasanchez.tk kill[28971]: kill: cannot find process ""
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: control process exite...1
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Failed to start The Apache HTTP Server.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Unit httpd.service entered failed state.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server conf]#
</code>```

Config file with suggested configuration:

```<code><VirtualHost *:80>
    ServerName MyProject
    ServerAlias imprentasanchez.tk www.imprentasanchez.tk
    DocumentRoot /var/www/html/imprenta/public
    <Directory  "/var/www/html/imprenta/public">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
    </Directory>
</VirtualHost>
</code>```

答:
Open conf file and edit this
sudo nano 000-default.conf

and write this code

```<code><VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</code>```

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

then run apache restart

sudo a2enmod rewrite

then run this
service httpd restart

hope its helpfull

Body:
So I have a project in Laravel in which I use Ajax to move between views, so no data, only GET request.

This works fine on my local machine but I uploaded it to my VPS and when I click the button that should take me to another view, I get this error:

GET http://172.106.202.124/trabajos?_=1559303733962 404 (Not Found)

So I've done some research and found some people with the same issue, but I haven't found any working answer.

Some said to modify .htaccess, I already did that and it's the same for me.

I've noticed that if I write /index.php/trabajos in the URL it gives me 'trabajos' view, but if I remove the /index.php/ it just gives me 'Not found'

This is my js code:

 $(document).on('click', '#button1', function() {
        $.ajax({
                method: "GET",
                url:'/trabajos',
                success:function(result) {

                        $("#app").html(result).hide().fadeIn(1200);
                },
                error : function(e){
                        console.info("Error");
                }
                });
        });

And these are my routes:

Route::get('/', function () {
    return view('master');
});
Route::get('/main', function () {
    return view('main');
});
Route::get('/trabajos', function(){
    return view('menu.trabajos');
});
Route::get('/contacto', function(){
    return view('menu.contacto');
});
Route::get('/empresa', function(){
    return view('menu.empresa');
});

This is my httpd config:

#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory /var/www/laravel/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html/imprenta/public/"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

I get this error with the config:

* httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Fri 2019-05-31 08:44:37 EDT; 24s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 28971 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 28969 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 28969 (code=exited, status=1/FAILURE)

May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Starting The Apache HTTP Server...
May 31 08:44:37 server.imprentasanchez.tk httpd[28969]: AH00534: httpd: Configuration erro....
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: main process exited, ...E
May 31 08:44:37 server.imprentasanchez.tk kill[28971]: kill: cannot find process ""
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service: control process exite...1
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Failed to start The Apache HTTP Server.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: Unit httpd.service entered failed state.
May 31 08:44:37 server.imprentasanchez.tk systemd[1]: httpd.service failed.
Hint: Some lines were ellipsized, use -l to show in full.
[root@server conf]#

Config file with suggested configuration:

<VirtualHost *:80>
    ServerName MyProject
    ServerAlias imprentasanchez.tk www.imprentasanchez.tk
    DocumentRoot /var/www/html/imprenta/public
    <Directory  "/var/www/html/imprenta/public">
        Options +Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
    </Directory>
</VirtualHost>

Body:
Open conf file and edit this
sudo nano 000-default.conf

and write this code

<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com

ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf

vim: syntax=apache ts=4 sw=4 sts=4 sr noet

then run apache restart

sudo a2enmod rewrite

then run this
service httpd restart

hope its helpfull


问:
Pointer arithmetic in 2D array
I am learning C++. So, please excuse me for this long question.

I have written the below program for arrays. I understand the base address of the array is returned and the name of the array points to that. So, in the case of a 1D array, I can understand that

arr + 1

returns the address of next item of the array i.e.

arr + 4bytes

However, in the case of a 2D array, it is a little different. What I understand from the below cout statements that in memory arr2D[0], arr2D[1]..arr2D[4] all will be allocated 20bytes one after another as there are 5 cols i.e. 5 * 4 bytes

arr2D & arr2D[0] points to the same base address as expected; lines 43 & 45

So, if I do

arr2D[0] + 5

I get the address of arr2D[1]; line 47. But, when I do

arr2D + 5

I get a memory address 100 bytes from the base address; line 50. I don't understand why. Could anyone explain to me this?

```<code>#include <iostream>

using namespace std;

int main() {

int arr[5] = {0,1,2,3,4};

cout << "Printing arr" << endl;
for (int i = 0; i < 5; i++) {
    cout << *(arr + i) << " ";
}
cout << endl;

cout << "Base address of 'arr': " << (unsigned long) arr
     << " EQUALS " << "&arr: " << (unsigned long) &arr
     << endl;

cout << "Address of 2nd item i.e. i = 1 is: " << (unsigned long) (arr+1)
     << endl;

cout << "arr[1] = " << arr[1] << ", "
     << "1[arr] = " << 1[arr] << ", "
     << "*(arr + 1) = " << *(arr + 1)
     << endl << endl;

int arr2D[5][5] = {{1,2,3,4,5},
                   {3,4,5,6,7},
                   {5,6,7,8,9},
                   {7,8,9,10,11},
                   {9,10,11,12,13}};

cout << "Printing arr2D" << endl;
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        cout << *(arr2D[i] + j) << " ";
    }
    cout << endl;
}
cout << endl;

cout << "Base address of arr2D = " << (unsigned long) arr2D << endl; // this is fine

cout << "Address of arr2D[0] = " << (unsigned long) &arr2D[0] << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " EQUALS "
     << (unsigned long)(arr2D[0] + 5) << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " NOT EQUALS "
     << (unsigned long)(arr2D + 5) << endl; // I do not understand this, as arr2D and arr2D[0] is same

cout << "Address of arr2D[1][0] = " << (unsigned long)&arr2D[1][0] << endl;

cout << "arr2D[1][0] = " << *((arr2D[0] + 5) + 0) << endl;
}
</code>```

答:
arr2D[0] and arr2D point to the same address, but they point to different types.

arr2D[0] is the first row of the 2D array, therefore it decays to a pointer to the first element of that row (a single int). Meanwhile, arr2D is a 2D array (an array of arrays), so it decays to a pointer to the first row (a 5 element array).

As you know, pointer arithmetic is scaled to the size of the objects being pointed to by a pointer. Since arr2D points to 5 element int arrays, each object being pointed to has a size of 4*5=20 bytes (assuming 32-bit ints) so increasing the pointer by 5 results in a difference of 20*5=100 bytes.

Title: Pointer arithmetic in 2D array

Body:
I am learning C++. So, please excuse me for this long question.

I have written the below program for arrays. I understand the base address of the array is returned and the name of the array points to that. So, in the case of a 1D array, I can understand that

arr + 1

returns the address of next item of the array i.e.

arr + 4bytes

However, in the case of a 2D array, it is a little different. What I understand from the below cout statements that in memory arr2D[0], arr2D[1]..arr2D[4] all will be allocated 20bytes one after another as there are 5 cols i.e. 5 * 4 bytes

arr2D & arr2D[0] points to the same base address as expected; lines 43 & 45

So, if I do

arr2D[0] + 5

I get the address of arr2D[1]; line 47. But, when I do

arr2D + 5

I get a memory address 100 bytes from the base address; line 50. I don't understand why. Could anyone explain to me this?

#include <iostream>

using namespace std;

int main() {

int arr[5] = {0,1,2,3,4};

cout << "Printing arr" << endl;
for (int i = 0; i < 5; i++) {
    cout << *(arr + i) << " ";
}
cout << endl;

cout << "Base address of 'arr': " << (unsigned long) arr
     << " EQUALS " << "&arr: " << (unsigned long) &arr
     << endl;

cout << "Address of 2nd item i.e. i = 1 is: " << (unsigned long) (arr+1)
     << endl;

cout << "arr[1] = " << arr[1] << ", "
     << "1[arr] = " << 1[arr] << ", "
     << "*(arr + 1) = " << *(arr + 1)
     << endl << endl;

int arr2D[5][5] = {{1,2,3,4,5},
                   {3,4,5,6,7},
                   {5,6,7,8,9},
                   {7,8,9,10,11},
                   {9,10,11,12,13}};

cout << "Printing arr2D" << endl;
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        cout << *(arr2D[i] + j) << " ";
    }
    cout << endl;
}
cout << endl;

cout << "Base address of arr2D = " << (unsigned long) arr2D << endl; // this is fine

cout << "Address of arr2D[0] = " << (unsigned long) &arr2D[0] << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " EQUALS "
     << (unsigned long)(arr2D[0] + 5) << endl; // this is fine

cout << "Address of arr2D[1] = " << (unsigned long) arr2D[1] << " NOT EQUALS "
     << (unsigned long)(arr2D + 5) << endl; // I do not understand this, as arr2D and arr2D[0] is same

cout << "Address of arr2D[1][0] = " << (unsigned long)&arr2D[1][0] << endl;

cout << "arr2D[1][0] = " << *((arr2D[0] + 5) + 0) << endl;
}


问:
DAO in Scala with type classes
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

```<code>trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}</code>```

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource: ```<code>def dataSource():DataSource = {...}</code>```
How would you implement the DAOs with type classes ?

答:
I don't think type class is the way to go here. Type classes are for describing capabilities, not as a replacement for DI.

For example, if your DAO writes to a key-value store, it may require the capability to convert a class to a Map of keys and values.

In such a case the type class is:

```<code>trait KeyValuable[T] {
  def toMap(t: T): Map[String, String]
}
</code>```

And it is obvious you can supply each business class with the right implementation regardless of environment. It is an inherit capability of the type, not tied to how you then use it.

ContentLicense: CC BY-SA 3.0

Title: DAO in Scala with type classes

Body:
Let my application contains business classes Order, Product, Customer, etc. and I would like to store/retrieve them in/from the database.

Usually, we use the DAO pattern for this purpose. That is, we define a DAO interface and implementation for every business class: OrderDAO, ProductDAO, etc. Now I would like to use the type class pattern:

trait DAO[T] {
  def create(t:T)
  ... // other CRUD operations
}
...
// DAO implementations for specific business objects
implicit object OrderDAO extends DAO[Order] {
   def create(o:Order) {...}
   ... // other CRUD operations
}
...
// create a business object in the database
def create[T](t:T)(implicit dao:DAO[T]) {dao.create(t)}

Now my problem is that all DAOs use a DataSource instance (a factory of database connections) and so I cannot define DAOs as objects. I should create a singleton instance of the DataSource and pass it to all DAOs upon their initialisation.

Let's say we have a function to create a DataSource:
def dataSource():DataSource = {...}

How would you implement the DAOs with type classes ?

Body:
I don't think type class is the way to go here. Type classes are for describing capabilities, not as a replacement for DI.

For example, if your DAO writes to a key-value store, it may require the capability to convert a class to a Map of keys and values.

In such a case the type class is:

trait KeyValuable[T] {
  def toMap(t: T): Map[String, String]
}

And it is obvious you can supply each business class with the right implementation regardless of environment. It is an inherit capability of the type, not tied to how you then use it.


问:
Got different ImageView sizes using ListView
i have got an strange issue, in my ListView, I've got an ImageView, which should have specifed by me size. Everything works just fine in the avd, but in real device, it's getting weird because of different sizes of ImageView. What should I do with it?

Initialization of ImageView

```<code><ImageView
        android:id="@+id/hourly_weatherIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginStart="15dp" />
</code>```

Here I set up the ImageView

```<code> ImageView weatherIcon = view.findViewById(R.id.hourly_weatherIcon);
 utils.setWeatherIcon(model.getForecastID(), weatherIcon);
</code>```

Following with this Picasso method

```<code>    String url = "https://openweathermap.org/img/w/";
    String fileExtension = ".png";
    String finalUrl = url + forecast + fileExtension;
    Picasso.get().load(finalUrl).resize(250,250).into(imageView);
</code>```

Here's what it's look like
1
2

答: Try to djust the width and height of the image manually in xml, then apply scaleType="centerCrop" attribute</p>

Body:
i have got an strange issue, in my ListView, I've got an ImageView, which should have specifed by me size. Everything works just fine in the avd, but in real device, it's getting weird because of different sizes of ImageView. What should I do with it?

Initialization of ImageView

<ImageView
        android:id="@+id/hourly_weatherIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginStart="15dp" />

Here I set up the ImageView

 ImageView weatherIcon = view.findViewById(R.id.hourly_weatherIcon);
 utils.setWeatherIcon(model.getForecastID(), weatherIcon);

Following with this Picasso method

    String url = "https://openweathermap.org/img/w/";
    String fileExtension = ".png";
    String finalUrl = url + forecast + fileExtension;
    Picasso.get().load(finalUrl).resize(250,250).into(imageView);

Here's what it's look like
1
2


问:
How To Use Progress Bar
I am making app with Android Studio, and i have added pull down to refresh url in app and after than my Progress Bar is not working , i mean when i pull down default progress bar shows but after that screen show only blank page until url loaded. this is my xml file

```<code><ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webview"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/adView" />

</ScrollView>

<ProgressBar
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/progressBar"/>
</code>```

and in java file i use this

```<code> myWebView.loadUrl("http://m.wahstatus.com/ws/english-status/?orderby=rand");
                WebSettings webSettings = myWebView.getSettings();
                myWebView.getSettings().setLoadWithOverviewMode(true);
                webSettings.setJavaScriptEnabled(true);
                swipeView.setColorScheme(android.R.color.holo_blue_dark,android.R.color.holo_blue_light, android.R.color.holo_green_light,android.R.color.holo_green_dark);
                swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
                {
                    @Override
                    public void onRefresh()
                    {
                        swipeView.setRefreshing(true);
                        ( new Handler()).postDelayed(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                swipeView.setRefreshing(false);
                                myWebView.loadUrl("http://m.wahstatus.com/ws/english-status/?orderby=rand");
                            }
                        }, 1000);
                    }

                });

                myWebView.setWebViewClient(new WebViewClient() {
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
                    }
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        findViewById(R.id.progressBar).setVisibility(View.GONE);
                    }
</code>```

On page loaded Progress bar not working

答:
you should add a webchromeClient()

```<code> webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
               findViewById(R.id.progressBar).setProgress(progress * 100); //Make the bar disappear after URL is loaded
            });
</code>```

Title: How To Use Progress Bar

Body:
I am making app with Android Studio, and i have added pull down to refresh url in app and after than my Progress Bar is not working , i mean when i pull down default progress bar shows but after that screen show only blank page until url loaded. this is my xml file

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/webview"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/adView" />

</ScrollView>

<ProgressBar
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/progressBar"/>

and in java file i use this

 myWebView.loadUrl("http://m.wahstatus.com/ws/english-status/?orderby=rand");
                WebSettings webSettings = myWebView.getSettings();
                myWebView.getSettings().setLoadWithOverviewMode(true);
                webSettings.setJavaScriptEnabled(true);
                swipeView.setColorScheme(android.R.color.holo_blue_dark,android.R.color.holo_blue_light, android.R.color.holo_green_light,android.R.color.holo_green_dark);
                swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
                {
                    @Override
                    public void onRefresh()
                    {
                        swipeView.setRefreshing(true);
                        ( new Handler()).postDelayed(new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                swipeView.setRefreshing(false);
                                myWebView.loadUrl("http://m.wahstatus.com/ws/english-status/?orderby=rand");
                            }
                        }, 1000);
                    }

                });

                myWebView.setWebViewClient(new WebViewClient() {
                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view, url, favicon);
                        findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
                    }
                    @Override
                    public void onPageFinished(WebView view, String url) {
                        findViewById(R.id.progressBar).setVisibility(View.GONE);
                    }

On page loaded Progress bar not working

Body:
you should add a webchromeClient()

 webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)
            {
               findViewById(R.id.progressBar).setProgress(progress * 100); //Make the bar disappear after URL is loaded
            });


问:
How to make automatic and manual image slider in one page but in different image container?
I want to make 2 image sliders with 2 different image containers in one page. Top image container would be manual slider and bottom image slider would be automatic slider.

I took the code from W3Schools.com and did some changes to the code. I added ++slideIndex and setTimeout function but it still didn't work.

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box}
.mySlides1, .mySlides2 {display: none}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a grey background color */
.prev:hover, .next:hover {
  background-color: #f1f1f1;
  color: black;
}
</style>
</head>
<body>

<h2 style="text-align:center">Multiple Slideshows</h2>

<p>Slideshow 1:</p>
<div class="slideshow-container">
  <div class="mySlides1">
    <img src="img_nature_wide.jpg" style="width:100%">
  </div>

  <div class="mySlides1">
    <img src="img_snow_wide.jpg" style="width:100%">
  </div>

  <div class="mySlides1">
    <img src="img_mountains_wide.jpg" style="width:100%">
  </div>

  <a class="prev" onclick="plusSlides(-1, 0)">❮</a>
  <a class="next" onclick="plusSlides(1, 0)">❯</a>
</div>

<p>Slideshow 2:</p>
<div class="slideshow-container">
  <div class="mySlides2">
    <img src="img_band_chicago.jpg" style="width:100%">
  </div>

  <div class="mySlides2">
    <img src="img_band_la.jpg" style="width:100%">
  </div>

  <div class="mySlides2">
    <img src="img_band_ny.jpg" style="width:100%">
  </div>

</div>
<script>
var slideIndex = [1,1];
var slideId = ["mySlides1", "mySlides2"]
showSlides(1, 0);
showSlides(1, 1);

function plusSlides(n, no) {
  showSlides(slideIndex[no] += n, no);
}

function showSlides(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]);
  if (n > x.length) {slideIndex[no] = 1}
  if (n < 1) {slideIndex[no] = x.length}
  if (n == undefined){
      n = ++slideIndex[no];
  }
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
  }
  x[slideIndex[no]-1].style.display = "block";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</code>```

The manual slider is working but the auto slider did not slide automatically. It just show the first image.

答:
Have a look here I added a separate code for the sliding the slider i.e carousel()

var slideIndex = 0;
showSlides(slideIndex,1);
showSlides(slideIndex,2);

function plusSlides(n,type) {
  showSlides(slideIndex += n,type);
}

function showSlides(n,type) {
  var i;
  if(type==1)
  {
  slideIndex = 1;
  var x = document.getElementsByClassName("mySlides1");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}

  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
  }
  else
  {
    carousel();
  }
}

function carousel() {
  var x = document.getElementsByClassName("mySlides2");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > x.length) {slideIndex = 1}
  x[slideIndex-1].style.display = "block";
  setTimeout(carousel, 2000); // Change image every 2 seconds
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {box-sizing: border-box}
.mySlides1, .mySlides2 {display: none}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a grey background color */
.prev:hover, .next:hover {
  background-color: #f1f1f1;
  color: black;
}</code>```

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Multiple Slideshows

Slideshow 1:

  ❮
  ❯

Slideshow 2:

```

Body:
I want to make 2 image sliders with 2 different image containers in one page. Top image container would be manual slider and bottom image slider would be automatic slider.

I took the code from W3Schools.com and did some changes to the code. I added ++slideIndex and setTimeout function but it still didn't work.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Multiple Slideshows

Slideshow 1:

  ❮
  ❯

Slideshow 2:

The manual slider is working but the auto slider did not slide automatically. It just show the first image.

Body:
Have a look here I added a separate code for the sliding the slider i.e carousel()

var slideIndex = 0;
showSlides(slideIndex,1);
showSlides(slideIndex,2);

function plusSlides(n,type) {
  showSlides(slideIndex += n,type);
}

function showSlides(n,type) {
  var i;
  if(type==1)
  {
  slideIndex = 1;
  var x = document.getElementsByClassName("mySlides1");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}

  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex-1].style.display = "block";
  }
  else
  {
    carousel();
  }
}

function carousel() {
  var x = document.getElementsByClassName("mySlides2");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > x.length) {slideIndex = 1}
  x[slideIndex-1].style.display = "block";
  setTimeout(carousel, 2000); // Change image every 2 seconds
}

* {box-sizing: border-box}
.mySlides1, .mySlides2 {display: none}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a grey background color */
.prev:hover, .next:hover {
  background-color: #f1f1f1;
  color: black;
}

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
  <h2 style="text-align:center">Multiple Slideshows</h2>

<p>Slideshow 1:</p>
<div class="slideshow-container">
  <div class="mySlides1">
    <img src="https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_1280.jpg" style="width:100%">
  </div>

  <div class="mySlides1">
    <img src="https://image.shutterstock.com/image-photo/shopping-online-payment-by-using-260nw-701873641.jpg" style="width:100%">
  </div>

  <a class="prev" onclick="plusSlides(-1,1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1,1)">&#10095;</a>
</div>

<p>Slideshow 2:</p>
<div class="slideshow-container">
  <div class="mySlides2">
    <img src="https://cdn.pixabay.com/photo/2015/05/15/14/38/computer-768608_1280.jpg" style="width:100%">
  </div>

  <div class="mySlides2">
    <img src="https://image.shutterstock.com/image-photo/shopping-online-payment-by-using-260nw-701873641.jpg" style="width:100%">
  </div>

</div>
</html>


问:
Python age calculator based on DOB
I am practicing by creating an age calculator which calculates age in years based on given date of birth.

However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.

Can anyone create the same program with the same concept in a better way?  Please add some explanation so that it is easy for me to understand.

I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)
```

答:
Suppose today is 01/01/2019 and input is 12/06/1989. The output we need is 29years and 7 months.

```<code>   if  condition >= 0:
    Totmonth = condition
  else:
     Totmonth = 12+condition
      age -= 1

  print "age is" , age,"years and", Totmonth,"months"
</code>```

Title: Python age calculator based on DOB

Body:
Suppose today is 01/01/2019 and input is 12/06/1989. The output we need is 29years and 7 months.

   if  condition >= 0:
    Totmonth = condition
  else:
     Totmonth = 12+condition
      age -= 1

  print "age is" , age,"years and", Totmonth,"months"


问:
Query gets data from two different users when I try to get data just from just one user
I want to get data just from only one specific user but I get data from both users. Why is that? I don't understand. How can I solve this?.

I have three tables:

```<code>/*User*/

    CREATE TABLE `User` (
    `IDUser` INT NOT NULL AUTO_INCREMENT,
    `Name` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`IDUser`)
);

/*Category*/

     CREATE TABLE `Category` (
      `IDCategory` CHAR(3) NOT NULL,
      `FK_User` INT NOT NULL,
      `CategoryName` VARCHAR(40) NOT NULL,
      PRIMARY KEY (`IDCategory`, `FK_User`)
    );

/*Product*/

    CREATE TABLE `Product` (
        `IDProduct` VARCHAR(18) NOT NULL,
        `FK_User` INT NOT NULL,
        `ProductName` VARCHAR(150) NOT NULL,
        `FK_Category` CHAR(3) NOT NULL,
        PRIMARY KEY (`IDProduct`, `FK_User`)
    );

ALTER TABLE `Product` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);
ALTER TABLE `Product` ADD FOREIGN KEY (`FK_Category`) REFERENCES `Category`(`IDCategory`);
ALTER TABLE `Category` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);

insert into User(Name) values('User1');
insert into User(Name) values('User2');

insert into Category(IDCategory,FK_User,CategoryName) values('CT1',1,'Category1User1');
insert into Category(IDCategory,FK_User,CategoryName) values('CT1',2,'Category1User2');
</code>```

If two different users insert both the same product with the same ID:

```<code>insert into Product values('001',1,'shoe','CT1');
insert into Product values('001',2,'shoe','CT1');
</code>```

Why do I keep getting data from both users if I try a query like this one:

```<code>SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C on P.FK_Category=C.IDCategory
WHERE P.FK_User=1
</code>```

this is the result I get:

答:
A PRIMARY KEY is a UNIQUE key.  Shouldn't CategoryID be unique?  That is, shouldn't Category have PRIMARY KEY(CategoryId)?

(Check other tables for a similar problem.)

Body:
I want to get data just from only one specific user but I get data from both users. Why is that? I don't understand. How can I solve this?.

I have three tables:

/*User*/

    CREATE TABLE `User` (
    `IDUser` INT NOT NULL AUTO_INCREMENT,
    `Name` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`IDUser`)
);

/*Category*/

     CREATE TABLE `Category` (
      `IDCategory` CHAR(3) NOT NULL,
      `FK_User` INT NOT NULL,
      `CategoryName` VARCHAR(40) NOT NULL,
      PRIMARY KEY (`IDCategory`, `FK_User`)
    );

/*Product*/

    CREATE TABLE `Product` (
        `IDProduct` VARCHAR(18) NOT NULL,
        `FK_User` INT NOT NULL,
        `ProductName` VARCHAR(150) NOT NULL,
        `FK_Category` CHAR(3) NOT NULL,
        PRIMARY KEY (`IDProduct`, `FK_User`)
    );

ALTER TABLE `Product` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);
ALTER TABLE `Product` ADD FOREIGN KEY (`FK_Category`) REFERENCES `Category`(`IDCategory`);
ALTER TABLE `Category` ADD FOREIGN KEY (`FK_User`) REFERENCES `User`(`IDUser`);

insert into User(Name) values('User1');
insert into User(Name) values('User2');

insert into Category(IDCategory,FK_User,CategoryName) values('CT1',1,'Category1User1');
insert into Category(IDCategory,FK_User,CategoryName) values('CT1',2,'Category1User2');

If two different users insert both the same product with the same ID:

insert into Product values('001',1,'shoe','CT1');
insert into Product values('001',2,'shoe','CT1');

Why do I keep getting data from both users if I try a query like this one:

SELECT P.IDProduct,P.ProductName,P.FK_Category,C.CategoryName
FROM Product P inner join Category C on P.FK_Category=C.IDCategory
WHERE P.FK_User=1

this is the result I get:


问:
"org.fusesource.scalate.TemplateException: loader constraint violation" when using SBTs embedded Jetty and scalatra/scalate
I started getting this error yesterday when using the embedded 'jetty-run' task in SBT. I reverted my code to a previous version and it's still happening.

Note that I packaged up the application and deployed it in an actual jetty instance and I don't get the error. I started getting this error after adding some dependencies to my project (may or may not be related), but have since removed them.

I tried 'clean' 'clean-lib' and 'clean-cache' as well as cleaning out my  ~/.m2/repository, ~/.ivy2/cache and project/boot directories.

Anybody have any other ideas?

The line that is blowing up is:

```
templateEngine.layout(uri, Map("flash" -> flash))
```

More of the stack trace is below:

```
org.fusesource.scalate.TemplateException: loader constraint violation: when resolving method "scala.tools.nsc.Settings.(Lscala/Function1;)V" the class loader (instance of sbt/jetty/LazyJettyRun7$SbtWebAppLoader$1) of the current class, org/fusesource/scalate/support/ScalaCompiler, and the class loader (instance of java/net/URLClassLoader) for resolved class, scala/tools/nsc/Settings, have different Class objects for the type scala/Function1 used in the signature
    at org.fusesource.scalate.TemplateEngine.compileAndLoad(TemplateEngine.scala:775)
    at org.fusesource.scalate.TemplateEngine.compileAndLoadEntry(TemplateEngine.scala:637)
    at org.fusesource.scalate.TemplateEngine.liftedTree1$1(TemplateEngine.scala:368)
    at org.fusesource.scalate.TemplateEngine.load(TemplateEngine.scala:362)
    at org.fusesource.scalate.TemplateEngine.load(TemplateEngine.scala:420)
    at org.fusesource.scalate.TemplateEngine.layout(TemplateEngine.scala:521)
    at com.ford.testbuilder.web.AppDefaults$class.com$ford$testbuilder$web$AppDefaults$$render(SharedTraits.scala:79)
    at com.ford.testbuilder.web.AppDefaults$$anonfun$6.apply(SharedTraits.scala:52)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2$$anonfun$6.apply(ScalatraKernel.scala:133)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2$$anonfun$6.apply(ScalatraKernel.scala:133)
    at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:61)
    at scala.collection.immutable.List.foreach(List.scala:45)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:44)
    at scala.collection.mutable.ListBuffer.foreach(ListBuffer.scala:42)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply$mcV$sp(ScalatraKernel.scala:133)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply(ScalatraKernel.scala:121)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(ScalatraKernel.scala:121)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply$mcV$sp(ScalatraKernel.scala:120)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply(ScalatraKernel.scala:120)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply(ScalatraKernel.scala:120)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$class.handle(ScalatraKernel.scala:119)
    at com.ford.testbuilder.web.LoginServlet.org$scalatra$CookieSupport$$super$handle(LoginServlet.scala:10)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(CookieSupport.scala:102)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(CookieSupport.scala:102)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(CookieSupport.scala:102)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply$mcV$sp(CookieSupport.scala:101)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply(CookieSupport.scala:101)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply(CookieSupport.scala:101)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.CookieSupport$class.handle(CookieSupport.scala:100)
    at com.ford.testbuilder.web.LoginServlet.org$scalatra$FlashMapSupport$$super$handle(LoginServlet.scala:10)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply$mcV$sp(flashMap.scala:101)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply(flashMap.scala:100)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply(flashMap.scala:100)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.FlashMapSupport$class.handle(flashMap.scala:100)
```

答:
I figured this out after trying a fresh checkout on someone else's machine (which was working fine) and comparing the classpaths. I found that I had both the scala-library-2.8.1.jar as well as the scala-library.jar in my classpath.

This was caused by the following line in my project file:

```
override def filterScalaJars = false
```

Wasted the better part of a day on this :(

Body:
I started getting this error yesterday when using the embedded 'jetty-run' task in SBT. I reverted my code to a previous version and it's still happening.

Note that I packaged up the application and deployed it in an actual jetty instance and I don't get the error. I started getting this error after adding some dependencies to my project (may or may not be related), but have since removed them.

I tried 'clean' 'clean-lib' and 'clean-cache' as well as cleaning out my  ~/.m2/repository, ~/.ivy2/cache and project/boot directories.

Anybody have any other ideas?

The line that is blowing up is:

templateEngine.layout(uri, Map("flash" -> flash))

More of the stack trace is below:

org.fusesource.scalate.TemplateException: loader constraint violation: when resolving method "scala.tools.nsc.Settings.(Lscala/Function1;)V" the class loader (instance of sbt/jetty/LazyJettyRun7$SbtWebAppLoader$1) of the current class, org/fusesource/scalate/support/ScalaCompiler, and the class loader (instance of java/net/URLClassLoader) for resolved class, scala/tools/nsc/Settings, have different Class objects for the type scala/Function1 used in the signature
    at org.fusesource.scalate.TemplateEngine.compileAndLoad(TemplateEngine.scala:775)
    at org.fusesource.scalate.TemplateEngine.compileAndLoadEntry(TemplateEngine.scala:637)
    at org.fusesource.scalate.TemplateEngine.liftedTree1$1(TemplateEngine.scala:368)
    at org.fusesource.scalate.TemplateEngine.load(TemplateEngine.scala:362)
    at org.fusesource.scalate.TemplateEngine.load(TemplateEngine.scala:420)
    at org.fusesource.scalate.TemplateEngine.layout(TemplateEngine.scala:521)
    at com.ford.testbuilder.web.AppDefaults$class.com$ford$testbuilder$web$AppDefaults$$render(SharedTraits.scala:79)
    at com.ford.testbuilder.web.AppDefaults$$anonfun$6.apply(SharedTraits.scala:52)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2$$anonfun$6.apply(ScalatraKernel.scala:133)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2$$anonfun$6.apply(ScalatraKernel.scala:133)
    at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:61)
    at scala.collection.immutable.List.foreach(List.scala:45)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:44)
    at scala.collection.mutable.ListBuffer.foreach(ListBuffer.scala:42)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply$mcV$sp(ScalatraKernel.scala:133)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1$$anonfun$apply$mcV$sp$2.apply(ScalatraKernel.scala:121)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(ScalatraKernel.scala:121)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(ScalatraKernel.scala:121)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply$mcV$sp(ScalatraKernel.scala:120)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply(ScalatraKernel.scala:120)
    at org.scalatra.ScalatraKernel$$anonfun$handle$1.apply(ScalatraKernel.scala:120)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.ScalatraKernel$class.handle(ScalatraKernel.scala:119)
    at com.ford.testbuilder.web.LoginServlet.org$scalatra$CookieSupport$$super$handle(LoginServlet.scala:10)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply$mcV$sp(CookieSupport.scala:102)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(CookieSupport.scala:102)
    at org.scalatra.CookieSupport$$anonfun$handle$1$$anonfun$apply$mcV$sp$1.apply(CookieSupport.scala:102)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply$mcV$sp(CookieSupport.scala:101)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply(CookieSupport.scala:101)
    at org.scalatra.CookieSupport$$anonfun$handle$1.apply(CookieSupport.scala:101)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.CookieSupport$class.handle(CookieSupport.scala:100)
    at com.ford.testbuilder.web.LoginServlet.org$scalatra$FlashMapSupport$$super$handle(LoginServlet.scala:10)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply$mcV$sp(flashMap.scala:101)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply(flashMap.scala:100)
    at org.scalatra.FlashMapSupport$$anonfun$handle$1.apply(flashMap.scala:100)
    at scala.util.DynamicVariable.withValue(DynamicVariable.scala:71)
    at org.scalatra.FlashMapSupport$class.handle(flashMap.scala:100)

Body:
I figured this out after trying a fresh checkout on someone else's machine (which was working fine) and comparing the classpaths. I found that I had both the scala-library-2.8.1.jar as well as the scala-library.jar in my classpath.

This was caused by the following line in my project file:

override def filterScalaJars = false

Wasted the better part of a day on this :(


问:
how to fix this java program
Create a class Employee with the following private member variables.

```<code>int employeeId
String employeeName
double salary
double netSalary
</code>```

Include appropriate getters and setters method in Employee class. Write the following method in the Employee class:

```<code>public void calculateNetSalary(int pfpercentage) // This method should take PF percentage as argument. Deduct the PF amount from the salary and set the netSalary.
</code>```

Create a Main class which has the main method which invokes the method to get the input and prints the details as shown in the sample.

Also write a method :

```<code>public static Employee getEmployeeDetails() // which gets the employee details and returns the employee object.

public static int getPFPercentage() // which gets the PF percentage and returns the same
</code>```

I have written this code. Output is correct but it's showing some error, how to fix it?

```<code>public class Employee {
    private int employeeId;
    private String employeeName;
    private double salary;
    private double netSalary;

    public static Employee instances= new Employee();

    public int getEmployeeId() {
        return employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public double getSalary() {
        return salary;
    }

    public double getNetSalary() {
        return netSalary;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void setNetSalary(double netSalary) {
        this.netSalary = netSalary;
    }
    public void calculateNetSalary(int pfpercentage) {
        instances.netSalary=(instances.salary)*(1-(((double)pfpercentage)/100));

    }
    public static Employee getEmployeeDetails(int id, String name,double salary) {

        instances.setEmployeeId(id);
        instances.setEmployeeName(name);
        instances.setSalary(salary);
        return instances;
    }

    public static int getPFPercentage(int pfpercentage)
    { instances.calculateNetSalary(pfpercentage);
    ' return pfpercentage;  '
    }
}'

public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter id");
        int id=sc.nextInt();
        System.out.println("Enter name");
        sc.nextLine();
        String name=sc.nextLine();
        System.out.println("Enter salary");
        double salary=sc.nextDouble();

        Employee e1= Employee.getEmployeeDetails( id, name, salary );
        System.out.println("Enter pfpercentage");
        Employee.getPFPercentage(sc.nextInt());

        System.out.println("Id :"+e1.getEmployeeId());
        System.out.println("name :"+e1.getEmployeeName());
        System.out.println("salary :"+e1.getSalary());
        System.out.println("Net salary :"+e1.getNetSalary());
    }

}
</code>```

FAIL-1:

check the availaibility of getEmployeeDetails() in main method or check wether the signature(returntype/argument/acessspecifier/methodname)of the of the method getEmployeeDetails is correct.
check the availaibility of getPFPercentage() in main method or check wether the signature(returntype/argument/acessspecifier/methodname)of the of the method getPFPercentage() is correct
FAIL-1: check the logic of calculateNetSalary
FAIL-2: check the method of getPFPercentage
FAIL-2: check the method of getEmployeeDetails
```

答:
Try this code.

```<code>class Employee {

     private int employeeId;
     private String employeeName;
     private double salary;
     private double netSalary;

     public Employee(int employeeId, String employeeName, double salary) {
         this.employeeId = employeeId;
         this.employeeName = employeeName;
         this.salary = salary;
     }

     public int getEmployeeId() {
         return employeeId;
     }

     public String getEmployeeName() {
         return employeeName;
     }

     public double getSalary() {
         return salary;
     }

     public double getNetSalary() {
         return netSalary;
     }

     public void setEmployeeId(int employeeId) {
         this.employeeId = employeeId;
     }

     public void setEmployeeName(String employeeName) {
         this.employeeName = employeeName;
     }

     public void setSalary(double salary) {
         this.salary = salary;
     }

     public void setNetSalary(double netSalary) {
         this.netSalary = netSalary;
     }

     public void calculateNetSalary(double pfpercentage) {
         this.netSalary = this.salary * (1 - (pfpercentage / 100));
     }
}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter id");
    int id = sc.nextInt();
    System.out.println("Enter name");
    sc.nextLine();
    String name = sc.nextLine();
    System.out.println("Enter salary");
    double salary = sc.nextDouble();

    Employee e1 = new  Employee(id, name, salary);
    System.out.println("Enter pfpercentage");
    e1.calculateNetSalary(sc.nextDouble());

    System.out.println("Id :" + e1.getEmployeeId());
    System.out.println("name :" + e1.getEmployeeName());
    System.out.println("salary :" + e1.getSalary());
    System.out.println("Net salary :" + e1.getNetSalary());
}
</code>```

In your code, you have declared a static Employee object and also you have the default constructor. It is not a good programming practice. The general purpose of a class is to create multiple objects. If you need one single object you should use the singleton design pattern.

https://www.javatpoint.com/singleton-design-pattern-in-java

```<code>public static Employee instance;

public static Employee getInstance(){
    if(instance != null){
        instance = new Employee();
    }
    return instance;
}

//private constructor
private Employee(){};
</code>```

I didn't understand the purpose of this method. Method name says getPFPercentage while your parameter is also pfpercentage.

```<code>public static int getPFPercentage(int pfpercentage)
{ instances.calculateNetSalary(pfpercentage);
    ' return pfpercentage;  '
}
</code>```

I think the above method is redundant. We can call calculateNetSalary method and retrieve calculated net salary through its getter.

Title: how to fix this java program

Body:
Create a class Employee with the following private member variables.

int employeeId
String employeeName
double salary
double netSalary

Include appropriate getters and setters method in Employee class. Write the following method in the Employee class:

public void calculateNetSalary(int pfpercentage) // This method should take PF percentage as argument. Deduct the PF amount from the salary and set the netSalary.

Create a Main class which has the main method which invokes the method to get the input and prints the details as shown in the sample.

Also write a method :

public static Employee getEmployeeDetails() // which gets the employee details and returns the employee object.

public static int getPFPercentage() // which gets the PF percentage and returns the same

I have written this code. Output is correct but it's showing some error, how to fix it?

public class Employee {
    private int employeeId;
    private String employeeName;
    private double salary;
    private double netSalary;

    public static Employee instances= new Employee();

    public int getEmployeeId() {
        return employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public double getSalary() {
        return salary;
    }

    public double getNetSalary() {
        return netSalary;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public void setNetSalary(double netSalary) {
        this.netSalary = netSalary;
    }
    public void calculateNetSalary(int pfpercentage) {
        instances.netSalary=(instances.salary)*(1-(((double)pfpercentage)/100));

    }
    public static Employee getEmployeeDetails(int id, String name,double salary) {

        instances.setEmployeeId(id);
        instances.setEmployeeName(name);
        instances.setSalary(salary);
        return instances;
    }

    public static int getPFPercentage(int pfpercentage)
    { instances.calculateNetSalary(pfpercentage);
    ' return pfpercentage;  '
    }
}'

public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter id");
        int id=sc.nextInt();
        System.out.println("Enter name");
        sc.nextLine();
        String name=sc.nextLine();
        System.out.println("Enter salary");
        double salary=sc.nextDouble();

        Employee e1= Employee.getEmployeeDetails( id, name, salary );
        System.out.println("Enter pfpercentage");
        Employee.getPFPercentage(sc.nextInt());

        System.out.println("Id :"+e1.getEmployeeId());
        System.out.println("name :"+e1.getEmployeeName());
        System.out.println("salary :"+e1.getSalary());
        System.out.println("Net salary :"+e1.getNetSalary());
    }

}

FAIL-1:

check the availaibility of getEmployeeDetails() in main method or check wether the signature(returntype/argument/acessspecifier/methodname)of the of the method getEmployeeDetails is correct.
check the availaibility of getPFPercentage() in main method or check wether the signature(returntype/argument/acessspecifier/methodname)of the of the method getPFPercentage() is correct
FAIL-1: check the logic of calculateNetSalary
FAIL-2: check the method of getPFPercentage
FAIL-2: check the method of getEmployeeDetails

Body:
Try this code.

class Employee {

     private int employeeId;
     private String employeeName;
     private double salary;
     private double netSalary;

     public Employee(int employeeId, String employeeName, double salary) {
         this.employeeId = employeeId;
         this.employeeName = employeeName;
         this.salary = salary;
     }

     public int getEmployeeId() {
         return employeeId;
     }

     public String getEmployeeName() {
         return employeeName;
     }

     public double getSalary() {
         return salary;
     }

     public double getNetSalary() {
         return netSalary;
     }

     public void setEmployeeId(int employeeId) {
         this.employeeId = employeeId;
     }

     public void setEmployeeName(String employeeName) {
         this.employeeName = employeeName;
     }

     public void setSalary(double salary) {
         this.salary = salary;
     }

     public void setNetSalary(double netSalary) {
         this.netSalary = netSalary;
     }

     public void calculateNetSalary(double pfpercentage) {
         this.netSalary = this.salary * (1 - (pfpercentage / 100));
     }
}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter id");
    int id = sc.nextInt();
    System.out.println("Enter name");
    sc.nextLine();
    String name = sc.nextLine();
    System.out.println("Enter salary");
    double salary = sc.nextDouble();

    Employee e1 = new  Employee(id, name, salary);
    System.out.println("Enter pfpercentage");
    e1.calculateNetSalary(sc.nextDouble());

    System.out.println("Id :" + e1.getEmployeeId());
    System.out.println("name :" + e1.getEmployeeName());
    System.out.println("salary :" + e1.getSalary());
    System.out.println("Net salary :" + e1.getNetSalary());
}

In your code, you have declared a static Employee object and also you have the default constructor. It is not a good programming practice. The general purpose of a class is to create multiple objects. If you need one single object you should use the singleton design pattern.

https://www.javatpoint.com/singleton-design-pattern-in-java

public static Employee instance;

public static Employee getInstance(){
    if(instance != null){
        instance = new Employee();
    }
    return instance;
}

//private constructor
private Employee(){};

I didn't understand the purpose of this method. Method name says getPFPercentage while your parameter is also pfpercentage.

public static int getPFPercentage(int pfpercentage)
{ instances.calculateNetSalary(pfpercentage);
    ' return pfpercentage;  '
}

I think the above method is redundant. We can call calculateNetSalary method and retrieve calculated net salary through its getter.