text:
Q: Upgrade php7.0 to php7.2 I have upgraded with success my ubuntu server from php7.0 to php7.2
I am using Nginx with php-fpm. Although php -v output is:

PHP 7.2.11-4+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Nov  4 2018 05:10:57) ( NTS )
  Copyright (c) 1997-2018 The PHP Group
  Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
      with the ionCube PHP Loader (enabled) + Intrusion Protection from ioncube24.com (unconfigured) v10.2.5, Copyright (c) 2002-2018, by ionCube Ltd.
      with Zend OPcache v7.2.11-4+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

I noticed that Nginx still runs with php-fpm7.0.
I checked and both php-fpm 7.0 & 7.2 are running.
My /etc/nginx/conf.d/mysite.com.conf doesn't include

location ~* .php$

line.
Output of

find / ( -iname "php.ini" -o -name "www.conf" )

is
/etc/php/7.0/apache2/php.ini
/etc/php/7.0/fpm/pool.d/www.conf
/etc/php/7.0/fpm/php.ini
/etc/php/7.0/cli/php.ini
/etc/php/7.2/fpm/pool.d/www.conf
/etc/php/7.2/fpm/php.ini
/etc/php/7.2/cli/php.ini

Also I don't have any /etc/nginx/conf.d/mysite.com.conf file
I only have global_locations_ssl.conf.inc inside /etc/nginx/conf.d/
Output of

ps -aux | grep nginx

is
root      3123  0.0  0.0  37944  4192 ?        Ss   Nov05   0:00               nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data  3124  0.0  0.0  37944  8416 ?        S    Nov05   0:54 nginx: worker process
www-data  3125  0.0  0.0  37944  8500 ?        S    Nov05   0:58 nginx: worker process
www-data  3126  0.0  0.0  37944  8552 ?        S    Nov05   2:04 nginx: worker process
www-data  3127  0.0  0.0  37944  8588 ?        S    Nov05   1:04 nginx: worker process
www-data  3128  0.0  0.0  37944  8668 ?        S    Nov05   1:10 nginx: worker process
www-data  3129  0.0  0.0  37944  8536 ?        S    Nov05   1:27 nginx: worker process
root     22931  0.0  0.0  13348   916 pts/0    R+   12:50   0:00 grep --color=auto nginx

So my Nginx master process runs as root.
What should I check to fix this?

A: you can find solution full solution in https://linode.com/docs/web-servers/nginx/serve-php-php-fpm-and-nginx/
Depending on your distribution and PHP version, the PHP configuration files will be stored in different locations. This guide is using PHP 7.0 from Ubuntu's repositories on Ubuntu 16.04 as an example, and the
`/etc/php/7.0/fpm/pool.d/www.conf and /etc/php/7.0/fpm/php.ini`

files are what we'll be modifying.

Find those full file paths using a find command:

`find / \( -iname "php.ini" -o -name "www.conf" \)`

The output should look similar to:

`root@localhost:~# find / \( -iname "php.ini" -o -name "www.conf" \)
/etc/php/7.0/fpm/php.ini
/etc/php/7.0/fpm/pool.d/www.conf
/etc/php/7.0/cli/php.ini
`

The listen.owner and listen.group variables are set to www-data by default, but they need to match the user and group NGINX is running as. If you installed NGINX using our Getting Started with NGINX series, then your setup will be using the nginx user and group. You can verify with:

`ps -aux | grep nginx`

The output should be similar to:

`
root@localhost:~# ps -aux | grep nginx
root      3448  0.0  0.0  32500  3516 ?        Ss   18:21   0:00 nginx: master process /        usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx     3603  0.0  0.0  32912  2560 ?        S    18:24   0:00 nginx: worker process
nginx     3604  0.0  0.0  32912  3212 ?        S    18:24   0:00 nginx: worker process
`
This shows the NGINX master process is running as root, and the worker processes are running as the nginx user and group. Change the listen variables to that:

`
sed -i 's/listen.owner = www-data/listen.owner = nginx/g' /etc/php/7.0/fpm/pool.d/www.conf
sed -i 's/listen.group = www-data/listen.group = nginx/g' /etc/php/7.0/fpm/pool.d/www.conf
`
When pairing NGINX with PHP-FPM, it's possible to return to NGINX a .php URI that does not actually exist in the site's directory structure. The PHP processor will process the URI, and execute the .php file, because its job is to process anything handed to it by NGINX. This of course presents a security problem.

It's important limit what NGINX passes to PHP-FPM so malicious scripts can't be injected into return streams to the server. Instead, the request is stopped, possibly then resulting in a 404. There are multiple ways to do this (see the NGINX wiki) but here we chose to specify the setting in PHP-FPM rather than in NGINX's configuration.

`sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' /etc/php/7.0/fpm/php.ini`

You'll notice that ;cgi.fix_pathinfo=1 is commented out by default. Setting it to 0 and uncommenting it will enforce the configuration should there be any upstream changes in the default value in the future.

Restart PHP-FPM to apply the changes:

`systemctl restart php7.0-fpm.service`

Configure the NGINX Server BlockPermalink
Again pulling from Part 1 of our NGINX series, we'll start with a basic Server Block for a static HTTP page being served from /var/www/example.com. Replace example.com with your site's domain or IP address, and the root directive with your site's root directory.

`/etc/nginx/conf.d/example.com.conf

`server {
    listen         80 default_server;
    listen         [::]:80 default_server;
    server_name    example.com www.example.com;
    root           /var/www/example.com;
    index          index.html;
}
`
To the Server Block above, add a location block containing the PHP directives. You should then have:

/etc/nginx/conf.d/example.com.conf

server {
    listen         80 default_server;
    listen         [::]:80 default_server;
    server_name    example.com www.example.com;
    root           /var/www/example.com;
    index          index.html;

  location ~* \.php$ {
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
  }
}
This is just a bare minimum to get PHP-FPM working and you will want to configure it further for your specific needs. Some further points about the configuration above:

The location ~* \.php$ means that NGINX will apply this configuration to all .php files (file names are not case sensitive) in your site's root directory, including any subdirectories containing PHP files.
The * in the ~* \.php$ location directive indicates that PHP file names are not case sensitive. This can be removed if you prefer to enforce letter case.
The fastcgi_pass location must match the listen = value in /etc/php/7.0/fpm/pool.d/www.conf. It is preferable for performance reasons for PHP-FPM to listen on a UNIX socket instead of a TCP address. Only change this if you require PHP-FPM use network connections.
Using $document_root in the SCRIPT_FILENAME parameter instead of an absolute path is preferred by NGINX's documentation.
Here's a variation of the location block above. This includes an if statement which disallows the FPM to process files in the /uploads/ directory. This is a security measure which prevents people from being able to upload .php files to your server or application which the FastCGI process manager would then execute.

This only applicable if you allow users to upload or submit files to your site. Change the name of the directory from uploads to whatever suits your need.

/etc/nginx/conf.d/example.com.conf

  location ~* \.php$ {
    if ($uri !~ "^/uploads/") {
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
  }
Reload NGINX:

nginx -s reload

A: I found the solution.
In my /etc/nginx/sites-enabled/my-site.conf had a line
upstream fastcgi_backend {
server   127.0.0.1:9000;
}

Nginx was configure without the

location ~* .php$

line.
So you don't have to change configuration every time you change php versions.
My problem was that I didn't checked that php-fpm7.0 was running at socket 9000.
The solution was to change in php.ini inside php-fpm7.2 to run at socket 9000


text:
Q: Sharepoint Custom SPFieldLookup save just one value I have write a custom field that extends SPFieldLookup. I set AllowMultipleValues = true;
Here is Field Control Value:
public override object Value
    {
        get
        {
            EnsureChildControls();
            SPFieldLookupValueCollection vals = new SPFieldLookupValueCollection();
            ICollection s = TinBaiLienQuanPicker.SelectedIds;
            if (s != null && s.Count > 0)
            {
                foreach (var i in s)
                {
                    ListItem z = availableItems.Find(x => (x.Value == i.ToString()));
                    if (z != null)
                    {
                        vals.Add(new SPFieldLookupValue(int.Parse(z.Value), z.Text));
                    }
                }
            }
            return vals;
        }
        set
        {
            EnsureChildControls();
            base.Value = value as SPFieldLookupValueCollection;
        }
    }

When control save field data, I see it return a collection which have multiple value.
But when I retrieve data again, I receive only the first value. I get value from Control Field ' ListItemFieldValue property.
Please give me a tip. Thank you very much.

A: Data storage logic is different in the database for lookup field with one value compared to multiple values. Check that in the field type definition xml ParentType is set to LookupMulti instead of Lookup.

A: You have to inherit the field control class from MultipleLookupField not from LookupField. Are you sure you are doing this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check the sequence of independent random variables satisfy Lindeberg condition? The sequence of independent random variables has the following distribution.
$$
\alpha>0\,, \quad P(X_n=n)=P(X_n=-n)=\frac{1}{6n^{2(\alpha-1)}}\,,\quad P(X_n=0)=1-\frac{1}{3n^{2(\alpha-1)}}
$$
I need to prove that the Lindeberg condition holds if and only if $\alpha<\frac{3}{2}$.
In the case of above distribution, I turn the problem into proving
$$
\frac{\sum_{k=\min\left(a:a\geq \epsilon \sqrt{\sum_{i=1}^{n}\operatorname{Var}(X_i)}\right)}^{n}\frac{1}{3}k^{4-2\alpha}}{\sum_{k=1}^{n}\frac{1}{3}k^{4-\alpha}} \rightarrow 0
$$
How to get the result?
Lindeberg condition:
$$
\{ X_n,n\ge1 \} \text{is a sequence of independent random variable.}\\EX_k=\mu_k \quad \operatorname{Var}X_k=\sigma_k^2 \quad
B_n=\sum_{k=1}^{n} \sigma_k^2 \\ \forall \epsilon > 0 \quad \frac{1}{B_n}\sum_{k=1}^{n}\int_{|x-\mu_k|>\epsilon\sqrt{B_n}}(x-\mu_k)^2dF_k(x) \rightarrow 0 \quad (n\rightarrow \infty)
$$

A: We have to check that $$R_n:=\frac{\sum_{k=\min\left(a:a\geq \epsilon \sqrt{\sum_{i=1}^{n}\operatorname{Var}(X_i)}\right)}^{n} k^{4-2\alpha}}{\sum_{k=1}^{n} k^{4-2\alpha}} \rightarrow 0.$$
Let $B_n=\sum_{i=1}^{n}\operatorname{Var}(X_i)$. If $\alpha\gt 5/2$, then $B_n$ converges to a positive number and $R_n$ will converge to $1$.
If $\alpha =5/2$, then $R_n$ behaves as
$$
R'_n:=\frac 1{\log n}\sum_{k=\lfloor c \log n\rfloor }^nk^{-1}
$$
which goes also to $1$.
Now, assume that $\alpha\lt 5/2.$ Then one can find  constants $c_1$ and $c_2$ depending only on $\alpha$ such that $c_1n^{5-2\alpha}\leqslant B_n\leqslant c_2n^{5-2\alpha}$ and a similar bound holds for $B_n$.
As a consequence, the summation set in the denominator is empty for $n$ large enough in the case $\alpha\lt 3/2$.
If $\alpha \gt 3/2$, one gets
$$
\sum_{k=\min\left(a:a\geq \epsilon \sqrt{\sum_{i=1}^{n}\operatorname{Var}(X_i)}\right)}^{n} k^{4-2\alpha}\geqslant \sum_{k=\lfloor Kn\rfloor}^nk^{4-2\alpha}\geqslant K'n^{5-2\alpha}
$$
for some positive $K'$ hence $R_n$ does not go to zero.


text:
Q: System.ArgumentException: Illegal characters in path. error I`m getting an ArgumentException from the following code:
string strPath="C:\somename.xls";
startPath=System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
filePath = System.IO.Path.Combine(startPath, strPath);

I found this code on Stack Overflow.
Link:
C#:Copy protected worksheet to another excel file
 I don't exactly know what it is. Please tell me what it is. This code I'm building into an exe.
Lastly, I need to Copy one worksheet to another file.
What`s wrong am I doing? I deploy this in server.

A: Your code should be:
string filePath = "C:\\somename.xls"

You need double backslashes.

A: what that code appears to do, is it gets your working directory(wherever the exe associated with your code is), and combines it with "C:\\somename.xls"(which doesn't make sense.)
I think you might have intended something like
string strPath=@"somename.xls";

so assume you're running your application from
"C:\Users\owner\documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug"

what that code would do is set filePath to
"C:\Users\owner\documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\somename.xls"

the first thing I saw was
string filePath="C:\somename.xls";

\ is a special character, for determining other characters.  for instance '\n' is a  newline.  '\\' is the actual backslash.
so, you want to escape your \ with another \
string filePath="C:\\somename.xls";

or make it a literal string by putting a @ in front of it.
string filePath=@"C:\somename.xls";

A: Two problems with the code,
First
string filePath="C:\somename.xls";

\ is a special character, for determining other characters.  for instance '\n' is a  newline.  '\\' is the actual backslash.
Second
filePath contains a root path, C:\\.  Path.Combine will just return filePath then, it cannot be combined.

A: Your main problem is in startPath parameter.
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

If you trace your code, in FileName you will see a bad symbol character witch is illegal


text:
Q: How the determine the number of real positive roots of a polynomial? The Problem

For a polynomial (of degree 3 or 4) with real coefficients how can we determine the number of real positive roots?

or phrased a different way

What conditions enure that a polynomial (of degree 3 or 4) with real coefficients has 0,1,2,3,or 4 positive real roots?

Context
I have a set of polynomials which have complicated coefficients which consists of several constants. I can determine the conditions when these coefficients are positive or negative. I am interested in only the positive real roots of these polynomials.
Possible Theorems to Use
Use a combination of Descartes' rule of signs, and Rolle's theorem?
Notes

*

*These posts with similar titles Number of real positive roots of a polynomial? Number of real positive roots of a polynomial? as the polynomials in these questions have numbers as their coefficients (rather than unknown constants) or have a specific structure.

*I am not interested in finding the explicit roots to these polynomials. I can solve them using Mathematica and other computer algebra systems. Determining when the roots are positive and real is the real problem.

*I am not sure what tags to use for this post, suggestions and edits are welcome.

A: What you want is
Sturm's theorem:
https://en.wikipedia.org/wiki/Sturm%27s_theorem
This gives a method
of computing
the number of real roots
of a polynomial
in any interval
of the real line.


text:
Q: Load Balancing over multiple ISP connections I have been trying to implement load balance and fail over on a linux machine having multiple interfaces.
Currently I am using two ISP lines and I wish to split the network traffic such that both of them are used. For this I have made changes to the IP tables and the rules that apply to them.
Following is the Linux Advances Routing and Traffic Control (LARTC) link I am referring http://lartc.org/howto/lartc.rpdb.multiple-links.html
Connections do get distributed on both ISP lines. However, it is observed that once a connection is routed over a particular interace, it follows the same route each time.
This is because of the entry that gets made in the routing cache. Load balancing is severely affected due to this phenomenon. I have been clearing the cache at regular intervals which has not made the situation any better.


text:
Q: Aggregating an array of values in MongoDB I have an array of values I want to group by the id of, and get the sum of all the values. Currently I'm trying:
db.entries.aggregate(
[
    { $match: {"user": "John" } },
    { "$unwind": '$games'},
    { $group: {
        "_id": "$games.id",
        "score": { "$sum": "$games.score"} }},
])

The data looks like:
{
   "user":"john",
   "games":[
      {
         "id":123,
         "score":123
      }
   ]
},
{
   "user":"john",
   "games":[
      {
         "id":123,
         "score":123
      }
   ]
},
{
   "user":"john",
   "games":[
      {
         "id":256,
         "score":256
      }
   ]
}

In this example, for "John" I would like to get the total of all the unique game scores. I should get (123 + 256) in this example.
However, right now I'm getting the sum of individual games, not all of them as a total.

A: I have here:
> db.entries.find();
{ "_id" : ObjectId("56a9610cca390d7e14a54486"), "user" : "john", "games" : [ { "id" : 123, "score" : 123 } ] }
{ "_id" : ObjectId("56a9610cca390d7e14a54487"), "user" : "john", "games" : [ { "id" : 123, "score" : 123 } ] }
{ "_id" : ObjectId("56a9610cca390d7e14a54488"), "user" : "john", "games" : [ { "id" : 256, "score" : 256 } ] }
> db.entries.aggregate([ {$match: {user: "john"}}, {$unwind: "$games"}, {$group: {_id: "$games.id", score: {$sum: "$games.score"}}} ]);
{ "_id" : 256, "score" : 256 }
{ "_id" : 123, "score" : 246 }

What's the problem?


text:
Q: php one page 2 result this is my code after success enter login and password
<?php session_start();
if(!isset($_SESSION['nik'])){ die("Anda belum login");}
if($_SESSION['level']!="admin"){
echo "
Welcome ".$_SESSION['nik']."
";
echo "panel user";
}
if($_SESSION['level']="admin"){
echo "panel admin";
}
?>
Log Out

the out put that i want is :
if login = admin then display "hello admin"
if login = user then display "hello user"
if not login then say "you must login"
any suggestion how to fix that ?

A: please find below code as per your requirements.
<?php
  session_start();
  if(!isset($_SESSION['nik'])){
      echo "You must login.";
      exit;
  }
  if($_SESSION['level']!="admin"){
              echo "
Welcome ".$_SESSION['level']."
";
              echo 'Log Out';
              exit;
  }
  else {
       echo "
Welcome ".$_SESSION['level']."
";
       echo 'Log Out';
  }
?>

Thanks.

A: i choose and use @Ghanshyam answer,
thank you to all member at stackoverflow.
this is very helpfull site

A: Use following statement to set session for username while login-

    session_start();
    //following statement will create a session store user name.You can use this variable to display particular output.
    $_SESSION["uname"] = $_GET['un'];
    //in above statement 'un' is text box from which we are accepting username.

After set session variable for user name you can use it on another page-
session_start();
if(isset($_SESSION["uname"]) )
{
   if($_SESSION["uname"] == 'admin')
   {
     echo 'hello admin';
   }
   else($_SESSION["uname"] == 'uname')
   {
      echo 'hello user';
   }
}
else
{
echo "you must login"
}

A: The problem is in your operator selection.
if($_SESSION['level']="admin"){
echo "panel admin";
}

should be
if($_SESSION['level'] == "admin"){
echo "panel admin";
}

= is an assignment operator. And you need to use == or ===


text:
Q: How to do an ng-repeat that doesn't duplicate the ng-repeat element I need to use ng-repeat to produce several elements but those elements cannot be each wrapped inside a div (this is for box layout purposes where the box layout only works on the immediate children).  For example, I need this result:

Head 1

Body 1

Head 2

Body 2

There is no wrapping element on the repeated sections. This structure is required to make use of flex-box style layouts. How can I do this with AngularJS?

A: As @Anders Bornholm said, it can't be done (fyi, in knockout.js this is easy).
Albiet its ugly, you can accomplish this via a directive, e.g.:

*

*AngularJS ng-repeat with no html element

*ng-repeat without HTML element (this time really without any)
JS:
directive('htmlAppend', function() {
    return {
        restrict: 'A',
            link: function(scope, element, attrs) {
                element.append(attrs.htmlRepeat);
        }
    };
})

HTML:

  Head

A: Short answer: can't be done. One of Angular's biggest drawbacks for me personally.
If directive templates would have allowed more than one root element you could have done it with a directive, but that doesn't work either.


text:
Q: Accessing app settings in Express 3 controllers I'm curious what people use for accessing Express 3 settings (from get/set) in controllers and models. I know that I can access it through the request but I am not sure what the best approach is to access it outside of the routes such as in a model. I currently use a combination of app.set and app.get as well as a static array called settings that I require here:
Here's what I have right now:
// conf/configuration.js
var settings;

module.exports = function(app, express) {
  app.set("root_dir", process.cwd() + "/");
  app.set("public_dir", process.cwd() + "/public");
  ...
};

settings = {
  foo: bar,
  ...

};

module.exports.settings = settings;

and in models I do
var settings = require("../conf/configuration").settings;

But I would like to do away with that settings array as I find the 2 methods a bit messy. Recommendation on how to access say 'root_dir' in a misc file?


text:
Q: Android percentage layout I would like to create a layout that has two LinearLayout(vertcal position).
First linearLayout has 80% from space and the other 20% (I used weightSum=10).
On second layout I have a textinput and when keyboard appears the screen size is reduced so the second linearlayout wich has 20% is too small.
I would like that my secondLayout to have minimum 100dp and the first layout to have the rest but I don't know how to implement this.
Thank you !

A: The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:weightSum:"10" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="8" >
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="0dip"
        android:layout_weight="2">
    </LinearLayout>

</LinearLayout>


text:
Q: Want to generate single extent report for multiple tests define in testng.xml file. I am getting multiple reports for multiple tests I am using Extent Report Version 2.41.2 to generate reports for two of my tests. I am working on selenium, java, TestNG, and maven project.
Here is my TestNG.xml file code, I am running using TestNG:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >

<suite name="TestNG Group Test">

        <listeners>
            <listener class-name="com.figbytes.Utilities.ReportUtils"></listener>
        </listeners>
        <parameter name="browserName" value="Chrome"></parameter>

   <test name="Figbytes-Login" preserve-order="true" group-by-instances="true">
       <groups>
            <define name = "SuperGrouop">
                <include name="CreateData"/>
                <include name="DeleteData"/>
            </define>

            <run>
                <include name="SuperGrouop"/>
            </run>
        </groups>

      <classes>
         <class name="com.figbytes.Test.LoginPageTest">
             <methods>
                 <include name = "loginTest"/>
             </methods>
         </class>
         </classes>
    </test>

    <test name="Figbytes-Create-Data" preserve-order="true" group-by-instances="true">
        <groups>
            <define name = "SuperGrouop">
                <include name="CreateData"/>
            </define>

            <run>
                <include name="SuperGrouop"/>
            </run>
        </groups>

      <classes>
          <class name="com.figbytes.Test.FacilityTest">
             <methods>
                <include name="hubCreation"/>
                <include name="facilityCreation"/>
                <include name="siteCreation"/>
             </methods>
          </class>
       </classes>
    </test>

    <test name="Figbytes-Delete-Data" preserve-order="true" group-by-instances="true">
            <groups>
                <define name = "SuperGrouop">
                    <include name="DeleteData"/>
                </define>

                <run>
                    <include name="SuperGrouop"/>
                </run>
            </groups>

          <classes>
                         <class name="com.figbytes.Test.FacilityTest">
                 <methods>
                    <include name="deleteSite"/>
                    <include name="deleteFacility"/>
                    <include name="deleteHub"/>
                 </methods>
              </class>

      </classes>
   </test>

  <test name="Figbytes-LogOut" preserve-order="true" group-by-instances="true">
       <groups>
            <define name = "SuperGrouop">
                <include name="CreateData"/>
                <include name="DeleteData"/>
            </define>

            <run>
                <include name="SuperGrouop"/>
            </run>
        </groups>

      <classes>
         <class name="com.figbytes.Test.LoginPageTest">
             <methods>
                 <include name = "test"/>
             </methods>
         </class>
         </classes>
    </test>

</suite>

Here is my ReportUtils class code:
package com.figbytes.Utilities;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.Parameters;
import org.testng.internal.Utils;

import com.figbytes.Test.BaseClass;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import com.relevantcodes.extentreports.view.ScreenshotHtml;

public class ReportUtils implements ITestListener {

    ExtentReports extent;
    ExtentTest test;
    String s;
    String sep = System.getProperty("file.separator");
    String basePath = System.getProperty("user.dir");
    String date;

    //String filename = Const.Extent_Report_Path+sep+date+".html";
    @Parameters("browserName")
    @Override
    public void onStart(ITestContext st) {

        // TODO Auto-generated method stub
        //ExtentReports extent = new ExtentReports(file-path, replaceExisting);

        //To make report name dynamically by date/time
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy__hh_mm_ssaa");
        date = df.format(new Date());
        Const.logger.info(date);
        //System.out.println(date);

            //extent = new ExtentReports(basePath+sep+"src"+sep+"main"+sep+"java"+sep+"com"+sep+"figbytes"+sep+"Reports"+sep+date+".html");

        //Save Report in HTML in local repository

        //extent = new ExtentReports(Const.Extent_Report_Path+sep+st.getName()+date+".html");
        //get latest report in email but create report with name of null
        //extent = new ExtentReports(filename);

        //getting report
        extent = new ExtentReports(Const.Extent_Report_Path+sep+st.getName()+date+".html");
        Const.logger.info(Const.Extent_Report_Path+sep+st.getName()+date+".html");

        extent.loadConfig(new File(basePath+"\\extent-config.xml"));

    }

    @Override
    public void onTestSuccess(ITestResult arg0) {
        // TODO Auto-generated method stub
        test.log(LogStatus.PASS, "Pass-Detail");
        extent.endTest(test);

    }

    @Override
    public void onTestFailure(ITestResult tr) {

        File file = ((TakesScreenshot)BaseClass.driver).getScreenshotAs(OutputType.FILE);
        try {
            //FileUtils.copyFile(file, new File(basePath+sep+"src"+sep+"main"+sep+"java"+sep+"com"+sep+"figbytes"+sep+"Reports"+sep+tr.getMethod().getMethodName()+date+".png"));
        //Save screenshot in local repository
            FileUtils.copyFile(file, new File(Const.Extent_Report_Path+sep+tr.getMethod().getMethodName()+date+".png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Throwable t = tr.getThrowable();
        String error = Utils.longStackTrace(t, true);
        //String error = Utils.stackTrace(t, true)[0];
        test.log(LogStatus.FAIL, "Fail-Detail");

        //test.log(LogStatus.FAIL, "Fail-Detail"+tr.getName());
        //test.log(LogStatus.FAIL, "Fail-Detail"+tr.getThrowable());

        //To take screenshot and save in report eclipse package folder
        //test.log(LogStatus.INFO, ScreenshotHtml.getSource(basePath+sep+"src"+sep+"main"+sep+"java"+sep+"com"+sep+"figbytes"+sep+"Reports"+sep+tr.getMethod().getMethodName()+date+".png"));

        //To take screenshot and save in report in local Respository
        test.log(LogStatus.INFO, ScreenshotHtml.getSource(Const.Extent_Report_Path+sep+tr.getMethod().getMethodName()+date+".png"));
        //To create logs and show in report
        test.log(LogStatus.ERROR, error);

        extent.endTest(test);
    }

    @Override
    public void onTestSkipped(ITestResult arg0) {
        // TODO Auto-generated method stub
        //test.log(LogStatus.SKIP, "Skip-Detail"+arg0.getName());
        test.log(LogStatus.SKIP, "Skip-Detail");
        extent.endTest(test);

    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTestStart(ITestResult tr) {
        // TODO Auto-generated method stub
        //ExtentTest test = extent.startTest("Test Name", "Sample description");

        //To give the class name with method name
        // test = extent.startTest(tr.getTestClass().getName()+"---"+tr.getMethod().getMethodName());
         test = extent.startTest(tr.getMethod().getMethodName());

    }

    @Override
    public void onFinish(ITestContext arg0) {

        extent.flush();

    }

}

Here is extent-config.xml file code:
<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
    <configuration>
        <!-- report theme -->
        <!-- standard, dark -->
        <theme>standard</theme>

        <!-- document encoding -->
        <!-- defaults to UTF-8 -->
        <encoding>UTF-8</encoding>

        <!-- protocol for script and stylesheets -->
        <!-- defaults to https -->
        <protocol>https</protocol>

        <!-- title of the document -->
        <documentTitle>Figbytes Project</documentTitle>

        <!-- report name - displayed at top-nav -->
        <reportName>Figbytes Report
        <![CDATA[
               <img src='C:/Users/vaishali.chaudhary/eclipse-workspace/FigbytesProject/Logo/FigbytesLogo.png'/>
            ]]>

        </reportName>

        <!-- location of charts in the test view -->
        <!-- top, bottom -->
        <testViewChartLocation>bottom</testViewChartLocation>

        <!-- custom javascript -->
        <scripts>
        <![CDATA[
       $(document).ready(function() {

            });
        ]]>
    </scripts>

        <!-- custom styles -->
        <styles>
            <![CDATA[
              .report-name { padding-left: 18px; } .report-name > img { float:
              left;height: 90%;margin-left: 30px; margin-top: 3px;width: auto;}
            ]]>
        </styles>
    </configuration>
</extentreports>

Want to generate a single extent report for multiple tests defined in the testng.xml file. I am getting multiple reports for multiple tests. Here is the defined testng.xml file:(Thanks in advance- Would be great if anyone can help)


text:
Q: Converting slow LEFT JOINs to UNIONs I had a query that was taking 5.5s.
SELECT *, chv_images.image_id FROM chv_images

LEFT JOIN chv_storages ON chv_images.image_storage_id = chv_storages.storage_id
LEFT JOIN chv_users ON chv_images.image_user_id = chv_users.user_id
LEFT JOIN chv_albums ON chv_images.image_album_id = chv_albums.album_id
LEFT JOIN chv_categories ON chv_images.image_category_id = chv_categories.category_id
LEFT JOIN chv_meta ON chv_images.image_id = chv_meta.image_id

WHERE chv_images.image_nsfw = 0 AND (chv_albums.album_privacy NOT IN ('private','private_but_link','custom') OR chv_albums.album_privacy IS NULL OR chv_albums.album_user_id IS NULL)
ORDER BY chv_images.image_id DESC
LIMIT 0,15

Optimized, the query takes 0.002 seconds. Great!
(
SELECT image_name, image_extension, image_date, image_date_gmt, image_nsfw, image_title, image_user_id, image_album_id, image_storage_mode, image_storage_id, image_views, image_category_id, image_chain, image_format, image_likes, image_center, image_zscore, image_enabled_zscore, image_update_cache, chv_images.image_id FROM chv_images
LEFT JOIN chv_albums ON chv_images.image_album_id = chv_albums.album_id WHERE chv_images.image_nsfw = 0 AND (chv_albums.album_user_id IS NULL)
ORDER BY chv_images.image_id DESC
LIMIT 0,15
)
UNION
DISTINCT
(
SELECT image_name, image_extension, image_date, image_date_gmt, image_nsfw, image_title, image_user_id, image_album_id, image_storage_mode, image_storage_id, image_views, image_category_id, image_chain, image_format, image_likes, image_center, image_zscore, image_enabled_zscore, image_update_cache, chv_images.image_id FROM chv_images
LEFT JOIN chv_albums ON chv_images.image_album_id = chv_albums.album_id WHERE chv_images.image_nsfw = 0 AND (chv_albums.album_privacy NOT IN ("private", "private_but_link", "custom") OR chv_albums.album_privacy IS NULL)
ORDER BY chv_images.image_id DESC
LIMIT 0,15
)
ORDER BY image_id DESC
LIMIT 0,15

The problem is, the new query only JOINS two tables. The output is missing columns that are needed. I did try adding more UNIONs for the other LEFT JOINs that are missing from the new query. I'd get close after fixing error after error (like matching column sizes), but no cigar.
See CREATE TABLE

UPDATE
Best query based on first query (no UNION) looks like this. 3.5 seconds.
SELECT * FROM (SELECT chv_images.image_id, chv_images.image_name, chv_images.image_extension, chv_images.image_date, chv_images.image_date_gmt, chv_images.image_nsfw, chv_images.image_title, chv_images.image_user_id, chv_images.image_album_id, chv_images.image_storage_mode, chv_images.image_storage_id, chv_images.image_views, chv_images.image_category_id, chv_images.image_chain, chv_images.image_format FROM chv_images

LEFT JOIN chv_storages ON chv_images.image_storage_id = chv_storages.storage_id
LEFT JOIN chv_users ON chv_images.image_user_id = chv_users.user_id
LEFT JOIN chv_albums ON chv_images.image_album_id = chv_albums.album_id
LEFT JOIN chv_categories ON chv_images.image_category_id = chv_categories.category_id
LEFT JOIN chv_meta ON chv_images.image_id = chv_meta.image_id

WHERE chv_images.image_nsfw = 0 AND (chv_albums.album_privacy NOT IN ('private','private_but_link','custom') OR chv_albums.album_privacy IS NULL OR chv_albums.album_user_id IS NULL)
               ) images, chv_storages
ORDER BY image_id DESC
LIMIT 0,15

UPDATE 2
Above query takes 2.6 seconds if "LEFT JOIN chv_meta ON chv_images.image_id = chv_meta.image_id" is removed.

A: Disclaimer: I'm not a mysql expert, so this is just general guidance here.
Looking at the EXPLAIN, it's probably related to your chv_images table since it's got 178K rows and all the other tables are joining to it.  A couple things to try:

*

*try removing parts of the query one-by-one to see what may be causing the delay:

*

*take out the ORDER BY (maybe the sort is taking forever)

*remove the LEFT JOINs one by one and see where performance degrades

*try using a window function instead of LIMIT
A couple links to look at:
EXPLAIN
LIMIT
I'd say to check the documentation for EXPLAIN and look at what the query plan's trying to do with your chv_images table.
Update
I checked all the tables you are joining and it looks like the joins are all done on unique keys (i.e. 1-1).  Since you want to order by the image_id field in the chv_images table, you should be able to do a sub-select for the rows you want from that table first before doing any of your joins.  Something like this:
SELECT
    chv_images.image_id,
    chv_images.image_name,
    chv_images.image_extension,
    chv_images.image_date,
    chv_images.image_date_gmt,
    chv_images.image_nsfw,
    chv_images.image_title,
    chv_images.image_user_id,
    chv_images.image_album_id,
    chv_images.image_storage_mode,
    chv_images.image_storage_id,
    chv_images.image_views,
    chv_images.image_category_id,
    chv_images.image_chain,
    chv_images.image_format
FROM (
    SELECT *
    FROM (
        SELECT
            img.*,
            ROW_NUMBER() OVER(ORDER BY img.image_id DESC) RowNum -- Assign a rank to each row, ordered by image_id
        FROM chv_images img
    ) src
    WHERE RowNum <= 15 -- Only return first 15 rows
) chv_images
--  FROM chv_images                                                                         -- Primary Key = image_id
LEFT JOIN chv_storages ON chv_images.image_storage_id = chv_storages.storage_id             -- Primary Key = NULL, Unique Key = storage_id
LEFT JOIN chv_users ON chv_images.image_user_id = chv_users.user_id                         -- Primary Key = user_id
LEFT JOIN chv_albums ON chv_images.image_album_id = chv_albums.album_id                     -- Primary Key = album_id
LEFT JOIN chv_categories ON chv_images.image_category_id = chv_categories.category_id       -- Primary Key = category_id
LEFT JOIN chv_meta ON chv_images.image_id = chv_meta.image_id                               -- Primary Key = id, Key = image_id
WHERE chv_images.image_nsfw = 0
AND (
    chv_albums.album_privacy NOT IN ('private','private_but_link','custom') OR
    chv_albums.album_privacy IS NULL OR
    chv_albums.album_user_id IS NULL
)
ORDER BY image_id DESC
-- LIMIT 0,15

This should be equivalent to doing the LIMIT at the end, since all your joins are being done on UNIQUE keys.  Keep in mind, if your query / DDL ever change so that the joins are not 1-1, then the behavior of this query may also change.  Give it a try and let me know.


text:
Q: Ошибка, Netbeans 8.2 не видит jdk при подключении модулей При попытке активировать модули в Netbeans возникает ошибка:

"Сбой при включении: Not all requested modules can be enabled:
  [StandardModule:org.netbeans.modules.spring.beans jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-spring-beans.jar,
  StandardModule:org.netbeans.modules.form.kit jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-form-kit.jar,
  StandardModule:org.netbeans.modules.hibernate jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-hibernate.jar,
  StandardModule:org.netbeans.modules.maven.kit jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-maven-kit.jar,
  StandardModule:org.netbeans.modules.j2ee.persistence.kit jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-j2ee-persistence-kit.jar,
  StandardModule:org.netbeans.modules.debugger.jpda.kit jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-debugger-jpda-kit.jar,
  StandardModule:org.netbeans.modules.java.kit jarFile:
  /home/ruben/netbeans-8.2/java/modules/org-netbeans-modules-java-kit.jar]"

A: В моем случаи решение было таково. Нужно было указать в файле netbeans.conf(/home/netbeans-8.2/etc) значение переменой java_home. Узнать значение переменной можно с помощью команды echo $JAVA_HOME.


text:
Q: Creating a More Attractive DataGridView My form looks like this with a DataGridView:

I would like to make it look more professional. Can someone recommend a "makeover" for it? Perhaps there is a more attractive way to display this data.

A: I have been using a free grid control from Component Factory, it has all the same features as the standard DataGridView. The grid allows customization for pretty much all UI elements.

A: This looks quite nice already. What you might want to do is set the Dock to Fill with the Properties panel to make it fill the whole form.

A: Personally, I'd recommend softening those colors a bit.  Use pastel-versions of the same color perhaps.
Also, like person-b suggests: Dock->Fill.
I'm not a big fan of unnecessary row/record-selector columns. If you don't need it, I'd recommend getting rid of it.
One last thing, Normally I'd recommend not paining your UI with a crayon, instead letting the colors default to whatever the user has specified as their Windows theme.  However, I see the point of coloring the columns in your case.  I would suggest that you allow the user to modify the colors.  I'm not color-blind, but it's possible your colors may be unreadable to someone who is.

A: My first thoughts are on the column colors, does the color mean something, if you are try to differentiate to columns I would use two subtle colors. Large color shifts should have a meaning (Errors are bold and Red). The Font should use the System font styles and basic colors should also you the system colors. Colors and font styles may work for you but not everyone, some people are color blind, some people need larger fonts.


text:
Q: iPhone - UITableView to show two different custom cell views In my UITableView, I want to show loading indicator in the last cell.
For remaining cells, I created a custom table view cell which is working fine. But when I scroll to the end, its crashing and not able to load loading indictor (which is a different custom cell view). Here's my code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"HomeViewCell";

    UITableViewCell* cellToReturn = nil;

    // Configure the cell.
    NSInteger row = [indexPath row];
    if (row < [jokesTableArray count])
    {
        CustomTableCell* cell = (CustomTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[[CustomTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        NSDictionary* dict = [jokesTableArray objectAtIndex:indexPath.row];
        NSNumber* rating = [[ServerCommunicator getInstance] getCurrentUserJokeRating:[dict objectForKey:@"id"]];
        cell.userRatedTheJoke = rating != nil ? YES : NO;
        cell.titleLabel.text = [dict objectForKey:@"title"];
        cell.descriptionLabel.text = [dict objectForKey:@"text"];
        cell.upVotes.text = [NSString stringWithFormat:@"%2.2f",[[dict objectForKey:@"rating_count"] floatValue]];
        [cell setRating:rating != nil ? [rating intValue] : [[dict objectForKey:@"rating_count"] intValue]];
        NSString* authorName = [dict objectForKey:@"author"];
        if (authorName != nil && ![authorName isEqual:[NSNull null]])
        {
            cell.author.text = [NSString stringWithFormat:@"By:%@",authorName];
        }
        cellToReturn = cell;
    }
    else
    {
        KMLoadingIndicatorCell* cell = (KMLoadingIndicatorCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            KMLoadingIndicatorCell* cell = [[[KMLoadingIndicatorCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell.loadingLabel.text = @"Loading...";
            cellToReturn = cell;
        }
    }

    return cellToReturn;
}

A: Since you are using the same reuseIdentifier, the line
KMLoadingIndicatorCell* cell = (KMLoadingIndicatorCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

is most likely setting cell to an instance of CustomTableCell that is now being reused, rather than the expected KMLoadingIndicatorCell. You should be using different identifiers for the two different types of cells.

A: You should use a different Cell Identifier for your custom cell.


text:
Q: Checking a string for punctuation using loops How do you check if a string has punctuation by using a loop. I was told to use the in operator
string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains  punctuation")
        break
    else:
        print("that string contains punctuation")
        break

A: Use string module's punctuation which handles all punctuations for you:
import string

if any(x in string.punctuation for x in s):
    print("that string contains punctuation")
else:
    print("that string contains no punctuation")

where s is your string.

A: You can use the for-else construct to print the message that the string does not contain punctuation if it finishes the loop without finding one:
string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains punctuation")
        break
else:
    print("that string does not contain punctuation")

A: That code is half right.
The if part is correct, because as soon as you find any punctuation, your goal is met and you don't need to keep looking, so you can correctly break out of the loop.
However the else part is wrong, because if the current character is not punctuation, you still have to keep looking -- the remainder of the string might have punctuation.    Also the message is wrong; it should say the string doesn't have punctuation.
You can restructure the code to take advantage of the for/else construct:
string = input("Enter a string")

for char in string:
    if char in "'.,;:?!":
        print("that string contains punctuation")
        break
else:
    print("that string does not contain punctuation")

The else will execute if the loop makes it all the way to the end of the string without calling break.

A: Or Check the other way round considering the string input would be longer than the punctuation string
string = input("Enter a string")

punch_string= "'.,;:?!"
for char in punch_string:
    if char in string:
        print("that string contains punctuation")
        break
else:
    print("that string does not contain punctuation")

A shorter version using set intersection
    if set(string).intersection(set("'.,;:?!" )):
        print("that string contains punctuation")
else:
    print("that string does not contain punctuation")


text:
Q: JSF Link Parameter get null I have a page with link http://localhost:8080/Test/Page.faces?id=asdasdasd
The page got 2 text field and one button, after user key in the details and click submit, it works well when you first time click the submit button, the id will return me the exact value, but if the user never enter the value and click submit the validation will be invoked and next click the button again the id return null? How to solve this problem anyone can help?

A: Yes, when the user clicks on the button, the browser does a new request to the server.  That new request doesn't have the ?id=asdasdasd as part of it.  The easiest solution I can think of is to store that value into a hidden text field on the page.  You can use some javascript to populate the value.
So, if you have a <h:hidden id="idHidden" value="#{mybean.idHidden}"/> on your JSP, maybe some javascript like this:
<script type='text/javascript'>
  function gup( name )
  {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }

  if(gup('id') != "") {
     document.forms[0].idHidden.value = gup('id');
  }

</script>

I haven't checked this code for errors, but the idea is the first time the page loads, the value of 'id' is stored in a hidden input field.  That field is bound to your managed bean so the value is persisted across page refreshes.  Just reference the id value stored on the bean (as idHidden in the example above) instead of the request parameter.
BTW: I stole the GUP function from http://www.netlobo.com/url_query_string_javascript.html
Nick


text:
Q: Fibonacci Function in RISC V Implementing the fibonacci function using RISC - V, so that f(0) = 0 ,
f(1) = 1, ..., up to f(47).
My output matches everything up to 46. But when i try to calculate f(47) i get: -1323752223.
Here's the output:Output from Code below with n=47
Is there some sort of Overflow because i get a negative Integer value? Where should i look into to try and fix the error?
.data
    n:  .word 47
.text
.globl main

main:

            li x2, 0                # Used to determine if n (x7) equals 0
            li x3, 1                # Used to determine if n (x7) equals 1
            li x5, 0                # First number
            li x6, 1                # Second number
            lw x7, n                # Limit
            li x8, 1                # Counter
            beq x7, x2, DO          # If n == 0 then jump to DO (Which shoud print 0). Implements f(0) = 0
            beq x7, x3, WRITE       # if n == 1 then jump to WRITE (Which should print 1). Implements f(1) = 1

    LOOP:   beq x8, x7, EXIT        # Comparse the counter x8 which starts with 1 to n (limit). If x8 == x7 jump to EXIT
            add x4, x5, x6          # Add x5 to x6 and store in x4
            ori x5, x6, 0           # Assign the second number to my first number
            ori x6, x4, 0           # Assign the sum of x5 and x6 to my second number
            addi x8, x8, 1          # Add 1 to my counter
            j LOOP                  # Jump to loop

    EXIT:
            li x17, 1               # Load constant 1 to x17
            add x10,x4,x0           # Add x4 (which contains the result after the above coe) to x10
            ecall                   # Issue an SystemCall which prints an integer (Because of the 1 in x17)
            li x17, 5
            ecall
            li x17, 10
            ecall                   # Reads an int from input console (Because of the 10 in x17)
    DO:
            li x4, 0                # load 0 in x10 (x10 will be used by the SysCall to print) and print
            add x10,x4,x0
            li x17, 1
            ecall
            li x17, 5
            ecall
            li x17, 10
            ecall

    WRITE:  li x4, 1                # load 1 in x10 and print
            add x10,x4,x0
            li x17,1
            ecall
            li x17, 5
            ecall
            li x17, 10
            ecall

A: Yes, you have found the boundary of what signed 32-bit integers can hold.

*

*fib(47) = 2971215073 won't fit in 32-bit integers as signed, but will fit as unsigned — however, RARS does not have an "unsigned int" print function.

*fib(48) = 4807526976 won't fit in 32-bit form, even as unsigned.
List of fibonacci numbers:
https://www.math.net/list-of-fibonacci-numbers

If you want to represent larger numbers, you will need a strategy.

*

*if precision is not important, you can switch to floating point, where the results with such large numbers will be inexact.

*use two integers together for 64-bit arithmetic — you'll be good up to fib(92) = 7540113804746346429.

*use variable length integers for precision limited only by computer memory and compute time

*a complex combination of the above

And finally, you can detect and issue an error on overflow of your chosen arithmetic data type.  Overflow detection on RISC V is somewhat simple but not really obvious.
Technically, addition of 2 arbitrary 32-bit numbers results in a 33 bit answer — but no more than 33 bits, so we can use that knowledge of math in detecting overflow.
First, in a 32-bit number the top bit is either the sign bit (when signed data type), or the magnitude bit (when unsigned data type).
If you add two positive numbers (as is the case with fib) and the sign bit is set, you have signed overflow — but a proper bit pattern, if interpreted as unsigned.  However, you won't be able to print the number properly using the ecall #1, because it will print the number as signed and interpret as negative.  You can write your own unsigned number print; you can also look for this case and simply stop the program from printing and issue an error instead.
Going beyond that you can check for overflow in 32-bit unsigned addition by seeing if the resulting value is less than one of the input operands.
The last approach is also used in multiword addition to make a carry from the lower word(s) to higher word(s).


text:
Q: datatable won't update I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["user"] == null)
            Response.Redirect("~/default.aspx");

        if (Request .QueryString ["action"]=="edit")
        {
            Panel1.Visible = true;
        }

        if (Request.QueryString["edit"] != null)
        {

            Panel1.Visible = true;
            SqlConnection con2 = new SqlConnection();
            con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
            DataTable dt3 = new DataTable();
            con2.Open();
            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
            myReader = myCommand.ExecuteReader();

            while (myReader.Read())
            {
                title_txt.Text=myReader ["Title"].ToString ();
                bodytxt.Text = myReader["Body"].ToString();
            }
            con2.Close();
        }
protected void btn_addpost_Click(object sender, EventArgs e)
    {
string title= title_txt .Text ;
string body=bodytxt .Text ;

if (Request.QueryString["edit"] != null)
{
    string message;

    string filename = thumb_uploader.FileName;
    string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
    string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
    string[] ext = { ".jpg", ".png", ".jpeg" };
    if (Array.IndexOf(ext, exup) < 0)
    {
        message = "not correct.";
    }

    if (thumb_uploader.FileBytes.Length / 1024 > 400)
    {
        message = "not currect.";
    }

    while (System.IO.File.Exists(path + "\\" + filename + exup))
    {
        filename += "1";
    }

    savepath = path + "\\" + filename;

    if (thumb_uploader.HasFile)
    {
        thumb_uploader.SaveAs(savepath);

        thumb = thumb_uploader.FileName;
        SqlCommand command;
        SqlDataAdapter da;
        SqlConnection con3 = new SqlConnection();

        con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
        command = new SqlCommand();
        command.Connection = con3;
        da = new SqlDataAdapter();
        da.SelectCommand = command;

        command.CommandText = "UPDATE tbl_post SET Title=@title ,Body=@body ,Thumb=@thu Where Postid=" + Request.QueryString["edit"].ToString();
        con3.Open();
        command.Parameters.AddWithValue("@title", title );
        command.Parameters.AddWithValue("@body", body );
        command.Parameters.AddWithValue("@thu", thumb_uploader .FileName);

        command.ExecuteNonQuery();
        con3.Close();
        message = "its ok.";
        lbl_result.Text = message;
   }
   else
   {
        using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
        {
            string sql = "update tbl_post SET Title=@title ,Body=@body  Where Postid=@postid" ;
            using (SqlCommand command = new SqlCommand(sql, con3))
            {
                con3.Open();

                command.Parameters.AddWithValue("@title", title);
                command.Parameters.AddWithValue("@body", body);
                command.Parameters.AddWithValue("@postid",  Request.QueryString["edit"].ToString());

                command.ExecuteNonQuery();
                con3.Close();
                message = "its ok.";
                lbl_result.Text = message;
            }
        }
   }
}

A: I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
 if (!Page.IsPostBack)
        {
            if (Request.QueryString["edit"] != null)
            {

                Panel1.Visible = true;
                SqlConnection con2 = new SqlConnection();
                con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
                DataTable dt3 = new DataTable();
                con2.Open();
                SqlDataReader myReader = null;
                SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
                myReader = myCommand.ExecuteReader();

                while (myReader.Read())
                {
                    title_txt.Text = myReader["Title"].ToString();
                    bodytxt.Text = myReader["Body"].ToString();
                }
                con2.Close();
            }
        }


text:
Q: Auto-condition transitions in Jira Workflow At the moment I'm working on development of new WorkFlow in Jira and have a case, that I don't know how to implement.
We have several statuses in our dev cycle, - such as "Waiting for reproduce" and "Developemnt", - mostly it depends on the current assignee of the bug, - if it the QA - status is "Waiting for reproduce", if developer - "Development".
At the moment when creating a bug it can be assigned on the creation step to qa, or developer, or pm. So I need to make a condition like this:
if assignee in group "Developers":
  status = "Development";
elif assignee in group "QA
  status = "Waiting for reproduce"
else:
  status = "Open"

I need to make this condition transition on "create" step and on other steps... Can you advice me some tricks or links, that can help me to handle this case?
Best regards, Alexander.

A: this can easily be done using Jira Scripting Suite:
# get the current assignee
assignee = issue.getAssignee()
if assignee.inGroup('Developers'):
    # set new status
    issue.setStatus(stateNumber.toString()) # status number as string, i.e. "6"
else:
    .....

A: I would recommend the Groovy ScriptRunner Plugin.
You can achieve your goal by introducing a new status directly after creation. From this new status create transitions to all statuses you need (e.g. "Waiting for reproduce" and "Developemnt").
In the "Create" transition you then use several Fast-track transition an issue post-functions - each for one condition you need. The condition would look like something like this:
groupManager.isUserInGroup(issue.assignee, "QA")


text:
Q: Request more permission from Facebook Session returns an error I use this in my onSessionStateChange
session.requestNewReadPermissions(new NewPermissionsRequest(this, Arrays.asList("user_photos")));

and i get this error:

java.lang.UnsupportedOperationException: Session: an attempt was made
  to request new permissions for a session that has a pending request.

here is the full code of the onSessionStateChange callback.
private void onSessionStateChange(Session session, SessionState state, Exception exception)
    {
        if (state.isOpened())
        {
            Log.i(TAG, "Logged in...");
            m_lblWelcome.setText("You are logged in :)");
            session.requestNewReadPermissions(new NewPermissionsRequest(this, Arrays.asList("user_photos")));

            //Request.executeMeRequestAsync(session, getCurrentLoggedInUser);

        }
        else if (state.isClosed())
        {
            Log.i(TAG, "Logged out...");
            m_lblWelcome.setText("Why did you leave :(");
        }
    }

What am i doing wrong here ?

A: You need to call the onActivityResult() method on your current Session when asking for more permissions:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data);
}


text:
Q: Clean Code adding Images I am trying to give styles to the transport links Li, i have done it, but i have the feeling it could be a cleaner code and i am not completely sure if using absolute position is the best approach here, perhaps i should use before pseudoclass.
Could you please point me out what it the best and clean way to achieve this.
Here is the link
Many Thanks
enter image description here
[https://dl.dropboxusercontent.com/u/14407746/move_bubble_master/index.html][2]
              #main .descript strong {
          font-family: 'proxima_nova_altbold';
          display: block;
          font-weight: 700;
          padding: 20px 0px 16px 0px;
          color: #000;
          font-size: 14px;
          border-bottom: solid 1px #e0e0e0;
          }
          /* line 226, ../sass/main.scss */
          #main .descript ol {
          list-style: none;
          padding: 0px;
          width: 100%;
          margin-bottom: 2px;
          }
          /* line 229, ../sass/main.scss */
          #main .descript ol li {
          width: 50%;
          float: left;
          height: 53px;
          border-bottom: solid 1px #e0e0e0;
          position: relative;
          color: #000;
          padding-left: 34px;
          font-size: 13px;
          -webkit-box-sizing: border-box;
          -moz-box-sizing: border-box;
          box-sizing: border-box;
          }
          /* line 236, ../sass/main.scss */
          #main .descript ol li img {
          float: left;
          position: absolute;
          left: 0px;
          top: 0px;
          }
          /* line 237, ../sass/main.scss */
          #main .descript ol li span {
          display: block;
          color: #9c9c9c;
          padding-bottom: 6px;
          }
          /* line 242, ../sass/main.scss */
          #main .descript ol li em {
          font-family: 'proxima_nova_altbold';
          position: absolute;
          top: 0px;
          right: 40px;
          line-height: 76px;
          color: #9c9c9c;
          font-style: normal;
          }
          /* line 250, ../sass/main.scss */
          #main .descript ol li.room {
          line-height: 53px;
          }
          /* line 252, ../sass/main.scss */
          #main .descript ol li.room img {
          width: 23px;
          height: auto;
          left: 3px;
          top: 15px;
          }
          /* line 254, ../sass/main.scss */
          #main .descript ol li.kitchen {
          line-height: 53px;
          }
          /* line 256, ../sass/main.scss */
          #main .descript ol li.kitchen img {
          width: 23px;
          height: auto;
          left: 3px;
          top: 15px;
          }
          /* line 258, ../sass/main.scss */
          #main .descript ol li.kilburn, #main .descript ol li.kilburnPark, #main .descript ol li.maida, #main .descript ol li.south {
          padding: 16px 0px 0px 34px;
          height: 64px;
          }
          /* line 260, ../sass/main.scss */
          #main .descript ol li.kilburn img, #main .descript ol li.kilburnPark img, #main .descript ol li.maida img, #main .descript ol li.south img {
          width: 19px;
          height: auto;
          left: 3px;
          top: 20px;
          }
          /* line 263, ../sass/main.scss */
          #main .descript ol:after {
          clear: both;
          content: "";
          display: table;
          }

A: For a start, I recommend you add some classes to some of the more deeply nested elements, and target those classes with your CSS instead of those big multi-tiered selectors you've got at the moment.
This would apply particularly to the bits of code that you've got duplicated; this duplication could be removed if you had the same class defined on all the target elements, rather than having to build a complex selector to each of them individually.


text:
Q: Matrix representation of Fractional Linear Transformation and the Identity Matrix? For $x \in \mathbb{R}$, define the fractional linear transformation of $x$ as $f(x)$ where:
$$f(x) = \frac{ax + b}{cx+d}$$
Then $f(x)$ has a matrix representation in $\mathbb{R}^2$ of $F$ where:
$$F = \begin{pmatrix} a & b \\ c & d \end{pmatrix}$$
Then the function $g(x)= \dfrac{1}{1-x}$ has the matrix representation of:
$$G = \begin{pmatrix} 0 & 1 \\ -1 & 1 \end{pmatrix}$$
Observe that $g(g(g(x)))=x$. Then why isn't $G^3=I$ ? In fact:
$$G^3 = \begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix} = -I$$
How does that make sense where $g^3(x)=x$ and not $-x$ ? Shouldn't the vector
$$ v=\begin{pmatrix} x \\ y \end{pmatrix}$$ get mapped back to itself after 3 iterations of multiplying by $G$ ? What am I missing?

A: Hint:
For which matrices $M = \pmatrix{a & b\\ c & d}$ is $f_M(x) = \frac{ax + b}{cx+d}$ the identity function? You know that it is when $M = I$, but is that the only matrix? No. For instance, $M = 2I$ also produces a function $f_{2I}$ that's the identify function. The mapping $M \mapsto f_M$ from matrices to fractional linear transformations is not injective.


text:
Q: cocos2D CCLayer or CCLayerColor setOpacity I'm trying to animate the opacity of a CCLayerColor and its not working. Here are my efforts so far. I've defined retryMenuLayer in .h like
CCLayerColor *retryMenuLayer;

and in .m file
retryMenuLayer = [CCLayerColor node];
[self addChild:retryMenuLayer z:5];

retryMenuLayer.scale = 0.5;
[retryMenuLayer setOpacity:0];

and in appearing method, I'm calling this.
[retryMenuLayer runAction:[CCFadeIn actionWithDuration:1]];

//OR

[retryMenuLayer setOpacity:255];

What happens is the background of retryMenuLayer animates from transparent to solid black but the contents inside (its children - a Menu with buttons) doesn't animate. In fact I have to use visibility property to at least disappear until the method is called.
retryMenuLayer.visible = NO; // When initiating.
retryMenuLayer.visible = YES; // When need to appear the layer.

A: For transparency in CCLayerColor, I use
    CCLayerColor *_shadowLayer = [CCLayerColor layerWithColor: ccc4(0,0,0, 100)];

for a transparent black color.
To make it FadeIn, this should work:
CCLayerColor _shadowLayer = [CCLayerColor layerWithColor: ccc4(0,0,0, 0)];
[_shadowLayer setContentSize: CGSizeMake(_winSize.width, _winSize.height)];
_shadowLayer.anchorPoint = ccp(0.0f, 0.0f);
_shadowLayer.position = ccp(0, 0);

[self addChild: _shadowLayer];

[_shadowLayer runAction: [CCFadeTo actionWithDuration:1.5f opacity:100]];

Note here that I added the shadow layer to self, that is my own customized layer. If I would add it to a sprite that is faded in, the opacity does not pull through to the shadow layer. There seems to be a workaround on that by user "aerostat" in the link in qklxtlx's answer, though.

A: CCLayer doesn't have opacity. Please refer to this http://www.cocos2d-iphone.org/forum/topic/5088


text:
Q: The import org.apache.olingo.commons.api.format.ODataFormat cannot be resolved I have tried to run java project using OData Service in Apache Olingo API.
But I'm getting "import org.apache.olingo.commons.api.format.ODataFormat cannot be resolved" Error.
I know to import API path for corresponding Java file to solve this issue. But I couldn't found right one. Anyone helps to solve this issue.
The example file path: https://apache.googlesource.com/olingo-odata4/+/Tutorial_P4_Navigation/samples/tutorials/p1_read?autodive=0%2F%2F

A: Tutorial linked by you is based on 4.0.0-beta-03 version of Olingo. ODataFormat is not needed anymore.
Instead
ODataFormat format = ODataFormat.fromContentType(responseFormat);
ODataSerializer serializer = odata.createSerializer(format);

You can just go with
ODataSerializer serializer = odata.createSerializer(responseFormat);

responseFormat is of type ContentType in both cases.
Code presented in the official tutorial is more up-to-date: https://olingo.apache.org/doc/odata4/index.html


text:
Q: ini file section to stringgrid Could someone know / give me an example of how to read a section from an ini file into a stringGrid? As I am struggling to figure out how to do it.
thanks
Colin

A: You are better to use TValueListEditor to show a section of an ini-file.
Here is a simple demo code:
procedure TForm1.Button1Click(Sender: TObject);
var
  SL: TStrings;
  IniFile: TMemIniFile;
begin
  SL:= TStringList.Create;
  try
    IniFile:= TMemIniFile.Create('test.ini');
    try
      IniFile.ReadSectionValues('FOLDERS', SL);
      ValueListEditor1.Strings.Assign(SL);
    finally
      IniFile.Free;
    end;
  finally
    SL.Free;
  end;
end;

A: OTOMH:
procedure ReadIntoGrid(const aIniFileName, aSection: string; const aGrid: TStringGrid);
var
  Ini: TIniFile;
  SL: TStringList;
  i: Integer;
begin
  SL := TStringList.Create;
  try
    Ini := TIniFile.Create(aIniFileName);
    try
      aGrid.ColCount := 2;
      Ini.ReadSectionValues(aSection, SL);
      aGrid.RowCount := SL.Count;
      for i := 0 to SL.Count - 1 do
      begin
        aGrid.Cells[0,i] := SL.Names[i];
        aGrid.Cells[1,i] := SL.ValueFromIndex[i];
      end;
    finally
      Ini.Free;
    end;
  finally
    SL.Free;
  end;
end;

EDIT
The other way round:
procedure SaveFromGrid(const aIniFileName, aSection: string; const aGrid: TStringGrid);
var
  Ini: TIniFile;
  i: Integer;
begin
  Ini := TIniFile.Create(aIniFileName);
  try
    for i := 0 to aGrid.RowCount - 1 do
      Ini.WriteString(aSection, aGrid.Cells[0,i], aGrid.Cells[1,i]);
  finally
    Ini.Free;
  end;
end;


text:
Q: How to identify software used to create an old 90's .PCB file? I have a .pcb file from the 90's. It was created as a student project, and because it was 30 years ago, I simply can't remember what software was used to create it.
Any ideas on how I might be able to identify the software? Or, is there software I might be able to use that can open a vast number of different kinds of formats? Any other suggestions?


text:
Q: How to send referer using Meta refresh on all browers? I want to redirect a webpage to a destiation WITH a referer. The straight forward solution is:
<meta http-equiv="refresh" content="0; url=example.com" />

The problem is, this works in Chrome, Safari, but does not work in IE and FF because these browsers don't send referer. What can I do to accomplish the task, because the destination require an referer in order to process.

A: You could try using a javascript redirect based on automatic form submission.

    <form id="redirect" action="//example.com" method="get"></form>


text:
Q: A range with steps bigger than one in freemarker? Question
I want to know if you can specify a step size in a numeric range.
For example, exist something like 50..100 in 10 that resolve to [50, 60, 70, 80, 90, 100]?
or if not exist can I make something like 5..10 * 10 and the same result?

Explanation
Here an explanation about my problem (if you like to know more). I have a configuration file with two blocks, the second related with the first.
Something like:

This will configure the application to do first A with parameter 100 and then do B with parameter 200. A will be a easy algorithm than B but less powerfull, but B will also try what A do if it's parameter is lower.
Now I want to launch a test with multiple values to know what is the better combination so I made the next template with freemarker.
<#list [50, 100, 200] as A>
<#list [100, 200, 500] as B>

<doA param1="${A}" />
<doB param1="${B}" />

</#list>
</#list>

The problem will be the combination of A=200 and B=100, because I already know that B will test A=200 so it is a waste of time to test.
I can solve this with an if, so if A is bigger than B, don't do nothing.
Now the problem have became bigger, and I need to check more values so I want to switch to a range of values, something like:
<#list 50..300 as A>
<#list 100..10000 as B>

<#if A < B >

<doA param1="${A}" />
<doB param1="${B}" />

</#if>

</#list>
</#list>

But an step of 1 is too small.
Also I think that with this I can do:
<#list 50..300 as A>
<#list A..10000 as B>

<doA param1="${A}" />
<doB param1="${B}" />

</#list>
</#list>

But I haven't test it. First I need to know that if I can make a big step.
P.D. I have search in freemarker documentation but I don't found nothing about this.

A: No, you can't specify a step. You can't multiply a whole range at once either. But of course you can do something like ${A*10} that is similar to having step 10.


text:
Q: Controlling which script is logged in system logs based on verbosity level in service now The organisation I work in uses service Now ,I just joined the team, My team wants me to do some research on logging in Service now.
All they want is to control the logging of scripts when they write a script on the server based on the verbosity level of the script
My understanding on logging  is it the type of  process that takes place on the server  i.e
•if a script is not of a proper syntax it logs as a WARNING stating the compile error in the message of the log
•If something runs successfully or a process is completed, it logs as INFO with the message of what happened
•Similar logging for debug takes place, (I may be wrong about this though)
I tried searching on service now wiki,one method I found was gs.log()
I tried running some test script to log info in  System Definition > Scripts - Background
Some of the various scripts I tried where
var gl = new GSLog("com.snc.sla.tasksla.log", "TaskSLA");
gl.logErr("This is an error message");

var gl = new GSLog("com.snc.sla.tasksla.log", "TaskSLA");
gl.logWarning("This is a warning message");

gs.info("This is an info log");
gs.debug("This is a debug log");

And then searched in the logs table   System Logs > System Log > All
all is saw was the scripts I ran were logged  as whole with INFO as the level , if the scripts had a syntax error it logged the same with WARNING level
Why doesn't it log the script line by line?
Also is there a way where I can tell Service now what script it should log based on the verbosity level?

A: If you're on the Fuji release or newer (which is still pretty new, so you may not be), there's actually a whole new logging api that's a bit more intuitive, and it's application-based. What follows is the documentation for that API:
Verbosity
There are 4 levels of verbosity, in order from least verbose to most verbose, they are:
error (gs.error)
warn (gs.warn)
info (gs.info)
debug (gs.debug)

...this means that setting log-level for a particular app to "info" will give you info+warn+error, but NOT debug.
...Session debugging verbosity is debug, so any level of log verbosity will be included in Session debug output, for JUST the app being debugged IN the session with session debugging activated.
The property for logging verbosity is (replacing  with your app name):
<APP_NAME>.logging.verbosity // off -> error -> warn -> info -> debug

Destination
Log destination of "db" will route log messages within desired logging verbosity to the table "syslog_app_scope", which extends syslog. This new table has added fields for the App/Scope issuing the log as well as a Source Script field that links to the script that called into the logging API (when we can figure it out, currently just for Business Rules and Script Includes). When Destination is set to "db", logs will ALSO go to file system.
Log destination of "file" will log to the node's file system log without broadcasting to log listeners (except in the case of Scripts-Background)
The property for destination is:
<APP_NAME>.logging.destination // none -> file -> db (implies file also)

Usage Examples
Consumers of this API (from JavaScript) should be able to just do:
gs.debug(message [, parameters])
-emit log message at debug level verbosity
gs.info(message [, parameters])
-emit log message at info level verbosity
gs.warn(message [, parameters])
-emit log message at warn level verbosity
gs.error(message [, parameters])
-emit log message at error level verbosity
This logging API supports the java MessageFormat placeholder replacement pattern
Currently there is support for up to 5 "varargs" placeholder arguments, any more than 5 need to be specified as a single javascript array argument
All of these are legal calls:
gs.info("Here's a log message from me"); // no params
gs.info("Here's a log message from {0}", myName); // single non array param
gs.info("Here's a log message from {0}.{1}", myFirstName, myLastName); // multiple "varargs" params (up to 5!)
gs.info("Here's a log message from {0}.{1}", [myFirstName, myLastName]); // array of n-number of params (no upper bounds)


text:
Q: What do you mean by instance in Javascript I am having tough time understanding the meaning of Instance properties
For example in Firefox ES6 Class document it says
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
Instance properties
Instance properties must be defined inside of class methods
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

I just see this as a class with constructor, so what do they mean by instance properties?

A: The instance properties there are height and width:
class Rectangle {
  constructor(height, width) {
    this.height = height;
//  -----^^^^^^
    this.width = width;
//  -----^^^^^
  }
}

An "instance" is an object. One tends to use "instance" in relation to code using class-like syntax, but it just means object (though often the implication is "object of a particular class").
Contrast with "static" or "class" properties:
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Rectangle.FOUR_BY_FOUR = new Rectangle(4,4);

There, FOUR_BY_FOUR is a "class/static" property. Or using the syntax proposed by the static class features proposal (currently Stage 3):
class Rectangle {
  static FOUR_BY_FOUR = new Rectangle(4,4);

  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

A: That means each instance of a Rectangle will have the properties height and width.
Later, they show how to create an instance.
const square = new Rectangle(10, 10);

Here, square is an instance of a Rectangle whose height and width properties are both initialized to 10.

A: You can picture class as a blueprint or modelling. Using the class that you've defined in your question for explanation
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

We have a class named Rectangle as a "blueprint" or design. Now we can create many individual instance/object by defining their own instance properties, base on this "blueprint"/Rectangle
let bigRectangle = new Rectangle(300,300);
let smallRectangle = new Rectangle(50,50);


text:
Q: Vim omnicompletion for Java I've read heaps of blogs on Vim's supposedly great omnicompletion, and yet no matter what I do I can't get it to work satisfactorily. It took me ages to figure discover that the version of ctags that is preinstalled on my system was the emacs one, and didn't have the --recurse option, but now that I've run ctags-exuberant on my copy of the OpenJDK sources to attempt to get some kind of code completion going, Vim hangs whenever I try to invoke it with [C-n] or [C-p].
All I really want is something that works like the code completion in Eclipse; I like Vim as an editor, but Eclipse just has those extra features out-of-the-box which Vim seems to fail with. Eclipse with a vi-mode plugin wasn't particularly useful to me, and it is too much of a memory and CPU hog to be of any use; eclim doesn't quite like me either.
Can anyone suggest a simpler way to get some kind of code completion working in Vim that actually works?

A: Here is a "JDE" feature for vim: http://www.vim.org/scripts/script.php?script_id=1213  One of the listed features is "Code completion ( working for java and jsp,taglib,html,xml,xsl,xsd) (VIM 7.0 required) "
And here is a Java autocompletion script: http://vim.sourceforge.net/scripts/script.php?script_id=1785
This one isn't Java, but I found it to be quite clear and understandable; perhaps it might be worth reading.  Here is a recipe on setting up autocompletion for Drupal.  A custom AWK script builds an autocompletion dictionary for vim.  http://www.thingy-ma-jig.co.uk/blog/18-08-2009/drupal-autocomplete-vim
Good luck.

A: I had a go with eclim:
http://eclim.sourceforge.net/
A while ago, it basically runs eclipse in the background and then provides a vim plugin which lets you get at all the functionality of eclipse inside vim.  So you can do refactoring, completion etc.  It seems to work quite well if you don't mind running a huge eclipse process in the background on your system.
I've got completion working quite well in C++ (Better than Vis stud anyway) but never had much luck with java.  These days I tend to use eclipse most of the time but I have gvim --remote set up as an external command in eclipse so that I can just wip the current buffer into vim anytime I want.

A: Had the same desire, got it fulfilled by using eclim. Works really really well.

A: I have looked for this as well as I am considering moving from eclipse to vim.  The best solution I have found so far is to bring vim to eclipse with the vrapper( http://vrapper.sourceforge.net/ ).  It brings a lot of the features of vim to the eclipse editor and you can still use autocompletion and all the other features of Eclipse.
I am still interested in moving completely, but it seems difficult to beat eclipse for a java development environment. (just hate the overhead for eclipse!)


text:
Q: How can a process handle multiple requests on a web server using sockets?TCP I know that you utilize a port to address a process and that you have to use sockets for handling multiple requests on web server, but how does it work? Is the process creating multiple socket threads for each connection? Is threading the answer?

A: Overview
This is a great question, and one that will take a bit to explain fully. I will step through different parts of this topic below. I personally learned multi-threading in Java, which has quite an extensive concurrency library. Although my examples will be in Java, the concepts will stand between languages.
Is threading valid?
In short, yes this is a perfect use case for multi-threading, although single-threaded is fine for simple scenarios as well. However, there does exist better designs that may yield better performance and safer code. The great thing is there are loads of examples on how to do this on the internet!

Multi-Threading
Lets investigate sample code from this article, seen below.
public class Server
{
    public static void main(String[] args) throws IOException
    {
        // server is listening on port 5056
        ServerSocket ss = new ServerSocket(5056);

        // running infinite loop for getting
        // client request
        while (true)
        {
            Socket s = null;

            try
            {
                // socket object to receive incoming client requests
                s = ss.accept();

                System.out.println("A new client is connected : " + s);

                // obtaining input and out streams
                DataInputStream dis = new DataInputStream(s.getInputStream());
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());

                System.out.println("Assigning new thread for this client");

                // create a new thread object
                Thread t = new ClientHandler(s, dis, dos);

                // Invoking the start() method
                t.start();

            }
            catch (Exception e){
                s.close();
                e.printStackTrace();
            }
        }
    }
}

The Server code is actually quite basic but still does the job well. Lets step through all the logic seen here:

*

*The Server sets up on Socket 5056

*The Server begins its infinite loop

*The client blocks on ss.accept() until a client request is received on part 5056

*The Server does relatively minimal operations (i.e. System.out logging, set up IO streams)

*A Thread is created and assigned to this request

*The Thread is started

*The loop repeats

The mentality here is that the server acts as a dispatcher. Requests enter the server, and the server allocates workers (Threads) to complete the operations in parallel so that the server can wait for and assist the next, incoming request.
Pros

*

*Simple, readable code

*Operations in parallel allows for increased performance with proper synchronization

Cons

*

*The dangers of multi-threading

*The creation of threads is quite cumbersome and resource intensive, thus should not be a frequent operation

*No re-use of threads

*Must manually limit threads

Thread Pool
Lets investigate sample code from this article, seen below.
while(! isStopped()){
    Socket clientSocket = null;
    try {
        clientSocket = this.serverSocket.accept();
    } catch (IOException e) {
        if(isStopped()) {
            System.out.println("Server Stopped.") ;
            break;
        }
        throw new RuntimeException("Error accepting client connection", e);
    }
    this.threadPool.execute(new WorkerRunnable(clientSocket,"Thread Pooled Server"));
}

Note, I excluded the setup because it is rather similar to the Multi-Threaded example. Lets step through the logic in this example.

*

*The server waits for a request to arrive on its alloted port

*The server sends the request to a handler that is given to the ThreadPool to run

*The ThreadPool receives Runnable code, allocated a worker, and begin code execution in parallel

*The loop repeats

The server again acts as a dispatcher; it listens for the request, receives one, and ships it to a ThreadPool. The ThreadPool abstracts the complex resource management from the developer and executes the code optimized fully. This is very similar to the multi-thread example, but all resource management is packaged into the ThreadPool. The code is reduced further from the above example, and it is much safer for non-multi-threading professionals. Note, the WorkerRunnable is only a Runnable, not a raw Thread, whilst the ClientHandler in the Multi-Thread example was a raw Thread.
Pros

*

*Threads are managed and re-used by the pool

*Further simplify code base

*Inherits all benefits from the Multi-Threaded example

Cons

*

*There is a learning curve to fully understanding pooling and different configurations of them

Notes
In Java, there exists another implementation called RMI, that attempts to abstract away the network, thus allowing the communication of Client-Server to happen as though it is on one JVM, even if it is on many. Although this as well can use multi-threading, it is another approach to the issue instead of sockets.


text:
Q: Разбить с помощью метода split() строку с двоичным числом на октеты? Есть двоичное число:
String s = "10000000001000000000101000000001"

Можно ли с помощью метода split() разбить его на октеты?

A:

console.log("10000000001000000000101000000001".split(/(?!^)(?=(?:.{8})+$)/))

A: Сплит тут подходит плохо... Регулярка по факту не очень быстрая.
Почему не написать простой метод? Что-то типа этого:
private String[] divideBy (String numb, int digitNumb){
    final String[]result = new String[numb.length()/digitNumb];
    for (int i = 0; i < numb.length()/digitNumb; i++) {
        result[i] = numb.substring(i*digitNumb, i*digitNumb+digitNumb);
    }
    return result;
}

Передаете первым аргументом свое число в стринге, а во втором количество цифр, на которое нужно поделить (по условию это 8, но можно поделить на любое количество) и получаете обычный массив.

A: Используйте
String s = "10000000001000000000101000000001";
String[] octets = s.split("(?<=\\G.{8})");
System.out.println(Arrays.toString(octets));
// = [10000000, 00100000, 00001010, 00000001]

См. демо онлайн.
Шаблон (?<=\G.{8}) представляет собой блок предварительного просмотра назад и находит позицию после любых первых восьми символов, а потом ещё после восьми и так далее.


text:
Q: spl_autoload_register and sub-classes I have got a class which is called "BaseCore" which just runs all the spl_autoload_registers(); which are in that file.
class BaseCore{

public function __construct(){
    spl_autoload_register( 'loadClasses' );
    spl_autoload_register( 'loadConfig' );
    spl_autoload_register( 'loadFMAPI' );
}

My second class extends BaseCore which on every new class that I want to extend the BaseCore, I have to require/include the BaseCore class.
require_once( 'classes/baseCore.class.php' );

class SchedulerDND extends BaseCore {

However, this seems very obsolete and an old way to do this.
So I guess my question is, how would I include the BaseCore into my child-class without having to write require_once(); on every child-class?
Thanks!

A: All you spl_autoload_register classes should be in some type of bootstrap file
For example create bootstrap.php and put all your autoload calls there.
Then you would make sure you always include your bootstrap file
For example, require 'bootstrap.php' in your index.php
That's all there is to it.
You bootstrap.php is loaded only once then you able to rely on autoloader to load all your classes, no need to have require or require_once in any of your classes.


text:
Q: Move files of particular pattern in batch to another folder I am trying to write a Windows batch file with commands for moving files with a pattern the file name from one folder to another folder, and others to others.
For example: vision.xls should go to a particular ~\vision folder. Any help is appreciated.

A:
Move files of particular pattern in batch to another folder
I am trying to write a Windows batch file with commands for moving
  files with a pattern the file name from one folder to another folder,
  and others to others.
For example: vision.xls should go to a particular ~\vision folder.

The below examples should work just as you explain for your need. Just plug in your paths for the source directory and the copy folder, and also put in your file pattern string as well. I tested and confirmed it works just as expected and as you described.
One example does a delete after the copy and the other does not and just does the copy. If you are expecting to copy the files to the new folder and then delete from the old folder, then you will want to use the one WITH DELETE.
As usual, you should test this to confirm it works for your particular needs before running against any critical files just in case.
EXAMPLE BATCH SCRIPT NO DELETE
@ECHO ON
SET SourceDir=C:\Path\Source
SET CopyDir=C:\Path\Vision
SET FilePatterName=*vision*.xls

FOR %%A IN ("%SourceDir%\%FilePatterName%") DO ECHO F | XCOPY /Y /F "%%~A" "%CopyDir%\"
GOTO EOF

EXAMPLE BATCH SCRIPT WITH DELETE
@ECHO ON
SET SourceDir=C:\Path\Source
SET CopyDir=C:\Path\Vision
SET FilePatterName=*vision*.xls

FOR %%A IN ("%SourceDir%\%FilePatterName%") DO (
    ECHO F | XCOPY /Y /F "%%~A" "%CopyDir%\"
    DEL /Q /F "%%~A"
)
GOTO EOF