问:
Sending JSON through JQuery to Java
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

```<code><script>
$.post("https://login-url",{"username":"user","password":"1234567890"},
function(data){
     alert("Data Loaded: " + data);
   }, "JSON" );
</script>
</code>```

UPDATE:

After following DavidDorward's comment my code looks like this:

```<code><script>
$.ajax({
    url: 'https://loginurl',
    type: 'POST',
    data: '{"username":"user","password":"1234567890"}',
    contentType: 'application/json',
    dataType: 'text',
    success: function(msg){
     alert("Data Loaded win: " + msg);}
</code>```

});

```<code></script>
</code>```

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype

答:
Your data wont be sent as JSON this way.

'dataType: The type of data expected from the server.'
http://api.jquery.com/jQuery.post/

Try:

{"json": '{"username":"user","password":"1234567890"}'}

Title: Sending JSON through JQuery to Java

Body:
I have a URL that accepts JSON through a post method. It should return a cookie and status.

When I try the following, (the username and password should be the JSON I'm trying to send) , I get no response, any ideas?

UPDATE:

After following DavidDorward's comment my code looks like this:

To describe my error a little better, a status should be returned, and a cookie. When I load this page firefox, and watch using firebug, there is no response, and no cookie information loaded in the header. Although it does seem to hit the URL, this makes me think its still a problem with the data. Although if the username and password are incorrect it should return an error, which is doesn't. It just consistently returns "null".

And to answer mattb's question, the login URL is only expecting "username" and "password" in JSON format and string datatype


来源: stackexchange

问:
Run Batch File In postgresql in single click
Hello Experts I have made batch file to run query in postgresql it works fine after pressing enter key 4 times without typing. 1-server, 2 database, 3 port and 4 for password. I need this same result with single click.
`

```<code>@echo off
REM Copyright (c) 2012-2016, EnterpriseDB Corporation.  All rights reserved

REM PostgreSQL server psql runner script for Windows

cmd.exe /c chcp 1252

SET server=localhost
SET /P server="Server [%server%]: "

SET database=naari
SET /P database="Database [%database%]: "
SET Password=pes

SET port=5432
SET /P port="Port [%port%]: "

SET username=postgres
SET /P username="Username [%username%]: "

for /f "delims=" %%a in ('chcp ^|find /c "932"') do @ SET CLIENTENCODING_JP=%%a
if "%CLIENTENCODING_JP%"=="1" SET PGCLIENTENCODING=SJIS
if "%CLIENTENCODING_JP%"=="1" SET /P PGCLIENTENCODING="Client Encoding [%PGCLIENTENCODING%]: "
REM Run psql
"C:\Program Files\PostgreSQL\10\bin\psql.exe" -h %server% -U %username% -d %database% -p %port% -f e:\DELETE.sql
pause
</code>```

`

答:
Now I have a solutions.</p>

```<code>@echo off
REM Copyright (c) 2012-2016, EnterpriseDB Corporation.  All rights reserved

REM PostgreSQL server psql runner script for Windows

cmd.exe /c chcp 1252

REM Run psql
"C:\Program Files\PostgreSQL\10\bin\psql.exe" -h localhost -U postgres -d naari -p 5432 -f e:\script.sql

pause
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hello Experts I have made batch file to run query in postgresql it works fine after pressing enter key 4 times without typing. 1-server, 2 database, 3 port and 4 for password. I need this same result with single click.
`

@echo off
REM Copyright (c) 2012-2016, EnterpriseDB Corporation.  All rights reserved

REM PostgreSQL server psql runner script for Windows

cmd.exe /c chcp 1252

SET server=localhost
SET /P server="Server [%server%]: "

SET database=naari
SET /P database="Database [%database%]: "
SET Password=pes

SET port=5432
SET /P port="Port [%port%]: "

SET username=postgres
SET /P username="Username [%username%]: "

for /f "delims=" %%a in ('chcp ^|find /c "932"') do @ SET CLIENTENCODING_JP=%%a
if "%CLIENTENCODING_JP%"=="1" SET PGCLIENTENCODING=SJIS
if "%CLIENTENCODING_JP%"=="1" SET /P PGCLIENTENCODING="Client Encoding [%PGCLIENTENCODING%]: "
REM Run psql
"C:\Program Files\PostgreSQL\10\bin\psql.exe" -h %server% -U %username% -d %database% -p %port% -f e:\DELETE.sql
pause

`

Body:
Now I have a solutions.

@echo off
REM Copyright (c) 2012-2016, EnterpriseDB Corporation.  All rights reserved

REM PostgreSQL server psql runner script for Windows

cmd.exe /c chcp 1252

REM Run psql
"C:\Program Files\PostgreSQL\10\bin\psql.exe" -h localhost -U postgres -d naari -p 5432 -f e:\script.sql

pause


问:
Responsive Images in Rails
What is the best method for implementing responsive images in Rails when using asset pipeline and the image_path helper?

Doing it purely through CSS is sadly a no-go for me, since that causes issues in IE with scaling.

答:
Use carrierwave gem and upload images using versions like:

```<code>class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  process resize_to_fit: [800, 800]

  version :thumb do
    process resize_to_fill: [200,200]
  end

  version :large do
    process resize_to_fill: [600,600]
  end

end
</code>```

Use different versions for different screen size.

```<code>uploader.url # => '/url/to/my_file.png'               # size: 800x800
uploader.thumb.url # => '/url/to/thumb_my_file.png'   # size: 200x200
uploader.large.url # => '/url/to/large_my_file.png'   # size: 600x600
</code>```

Title: Responsive Images in Rails

Body:
Use carrierwave gem and upload images using versions like:

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  process resize_to_fit: [800, 800]

  version :thumb do
    process resize_to_fill: [200,200]
  end

  version :large do
    process resize_to_fill: [600,600]
  end

end

Use different versions for different screen size.

uploader.url # => '/url/to/my_file.png'               # size: 800x800
uploader.thumb.url # => '/url/to/thumb_my_file.png'   # size: 200x200
uploader.large.url # => '/url/to/large_my_file.png'   # size: 600x600


问:
Why GetServiceDisplayNameW() and GetServiceDisplayNameA() returns different required buffer sizes in character?
Here is a sample code (only sample code to understand it easily, no error handling, no close handles, and so on):

```<code>SC_HANDLE hSCManager = ::OpenSCManager(nullptr, nullptr, 0);

DWORD buffSize = 0;
::GetServiceDisplayName(hSCManager, m_serviceName, nullptr, &buffSize);

LPTSTR buff = new TCHAR[++buffSize];
VERIFY(::GetServiceDisplayName(hSCManager, m_serviceName, buff, &buffSize));
</code>```

My sample service has the display name of "notepad starter" (15 characters).

Switching between build configuations, GetServiceDisplayName() returns a buffer size of 30 under ANSI (GetServiceDisplayNameA), and 15 under UNICODE (GetServiceDisplayNameW).

Documentation for this API says it returns the buffer size in characters excluding the null terminator (not well documented, but I'm expecting the buffer size to include the null terminator in the second call).

Why is it returning different buffer sizes in different build configurations?

答:
at first GetServiceDisplayName take handle to the service control manager database ( hSCManager) as first parameter, but not handle to service (hService) - so you not need open service for this task. and you not need SC_MANAGER_ALL_ACCESS here, but 0 is enough.

however your main error in next. you allocate buffer new TCHAR[buffSize + 1] - so buffSize + 1 in character - and this is correct because GetServiceDisplayName return size of the service's display name, excluding the null-terminating character - so we need extra one character space for terminating 0;

but in next line error - &buffSize - last parameter lpcchBuffer must containing size of the buffer in characters. so exactly buffer size which you allocated. but you allocate  buffSize + 1 space, not buffSize. so code must be next:

```<code>if (SC_HANDLE hSCManager = OpenSCManagerW(nullptr, nullptr, 0))
{
    DWORD cch = 0;
    if (!GetServiceDisplayNameW(hSCManager, m_serviceName, nullptr, &cch))
    {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            PWSTR buff =(PWSTR)alloca(++cch*sizeof(WCHAR));
            if (GetServiceDisplayNameW(hSCManager, m_serviceName, buff, &cch))
            {
                DbgPrint("%S\n", buff);
            }
        }
    }
    CloseServiceHandle(hSCManager);
}
</code>```

so you in your code must replace buffSize + 1 to ++buffSize

about ansi version - GetServiceDisplayNameA - here really error in api implementation - if buffer size in characters not big enough - it return how many bytes require unicode service name excluding the null-terminating symbol. if buffer is big enough it at all not update lpcchBuffer. this yet else one argument never use A versions of api, but always W

Body:
Here is a sample code (only sample code to understand it easily, no error handling, no close handles, and so on):

SC_HANDLE hSCManager = ::OpenSCManager(nullptr, nullptr, 0);

DWORD buffSize = 0;
::GetServiceDisplayName(hSCManager, m_serviceName, nullptr, &buffSize);

LPTSTR buff = new TCHAR[++buffSize];
VERIFY(::GetServiceDisplayName(hSCManager, m_serviceName, buff, &buffSize));

My sample service has the display name of "notepad starter" (15 characters).

Switching between build configuations, GetServiceDisplayName() returns a buffer size of 30 under ANSI (GetServiceDisplayNameA), and 15 under UNICODE (GetServiceDisplayNameW).

Documentation for this API says it returns the buffer size in characters excluding the null terminator (not well documented, but I'm expecting the buffer size to include the null terminator in the second call).

Why is it returning different buffer sizes in different build configurations?

Body:
at first GetServiceDisplayName take handle to the service control manager database ( hSCManager) as first parameter, but not handle to service (hService) - so you not need open service for this task. and you not need SC_MANAGER_ALL_ACCESS here, but 0 is enough.

however your main error in next. you allocate buffer new TCHAR[buffSize + 1] - so buffSize + 1 in character - and this is correct because GetServiceDisplayName return size of the service's display name, excluding the null-terminating character - so we need extra one character space for terminating 0;

but in next line error - &buffSize - last parameter lpcchBuffer must containing size of the buffer in characters. so exactly buffer size which you allocated. but you allocate  buffSize + 1 space, not buffSize. so code must be next:

if (SC_HANDLE hSCManager = OpenSCManagerW(nullptr, nullptr, 0))
{
    DWORD cch = 0;
    if (!GetServiceDisplayNameW(hSCManager, m_serviceName, nullptr, &cch))
    {
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            PWSTR buff =(PWSTR)alloca(++cch*sizeof(WCHAR));
            if (GetServiceDisplayNameW(hSCManager, m_serviceName, buff, &cch))
            {
                DbgPrint("%S\n", buff);
            }
        }
    }
    CloseServiceHandle(hSCManager);
}

so you in your code must replace buffSize + 1 to ++buffSize

about ansi version - GetServiceDisplayNameA - here really error in api implementation - if buffer size in characters not big enough - it return how many bytes require unicode service name excluding the null-terminating symbol. if buffer is big enough it at all not update lpcchBuffer. this yet else one argument never use A versions of api, but always W


问:
How can I obtain the case-sensitive path on Windows?
I need to know which is the real path of a given path.

For example:

The real path is: d:\src\File.txt

And the user give me: D:\src\file.txt

I need as a result: d:\src\File.txt

答:
You can use this function:</p>

```<code>[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint GetLongPathName(string ShortPath, StringBuilder sb, int buffer);

[DllImport("kernel32.dll")]
static extern uint GetShortPathName(string longpath, StringBuilder sb, int buffer);

protected static string GetWindowsPhysicalPath(string path)
{
        StringBuilder builder = new StringBuilder(255);

        // names with long extension can cause the short name to be actually larger than
        // the long name.
        GetShortPathName(path, builder, builder.Capacity);

        path = builder.ToString();

        uint result = GetLongPathName(path, builder, builder.Capacity);

        if (result > 0 && result < builder.Capacity)
        {
            //Success retrieved long file name
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        if (result > 0)
        {
            //Need more capacity in the buffer
            //specified in the result variable
            builder = new StringBuilder((int)result);
            result = GetLongPathName(path, builder, builder.Capacity);
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        return null;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can use this function:

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint GetLongPathName(string ShortPath, StringBuilder sb, int buffer);

[DllImport("kernel32.dll")]
static extern uint GetShortPathName(string longpath, StringBuilder sb, int buffer);

protected static string GetWindowsPhysicalPath(string path)
{
        StringBuilder builder = new StringBuilder(255);

        // names with long extension can cause the short name to be actually larger than
        // the long name.
        GetShortPathName(path, builder, builder.Capacity);

        path = builder.ToString();

        uint result = GetLongPathName(path, builder, builder.Capacity);

        if (result > 0 && result < builder.Capacity)
        {
            //Success retrieved long file name
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        if (result > 0)
        {
            //Need more capacity in the buffer
            //specified in the result variable
            builder = new StringBuilder((int)result);
            result = GetLongPathName(path, builder, builder.Capacity);
            builder[0] = char.ToLower(builder[0]);
            return builder.ToString(0, (int)result);
        }

        return null;
}


问:
T-SQL Problems with query and multiple comparison
Suppose to have this table:

```
|ORDER_NUMBER|CREATION_DATE|   STATUS   |
|201700014587|  2017-08-01 |STATUS1     |
|201700014587|  2017-08-03 |STATUS2     |
|201700013131|  2017-08-07 |STATUS1     |
|201700013131|  2017-08-11 |STATUS2     |
|201700014587|  2017-08-13 |STATUS3     |
|201700013131|  2017-08-14 |STATUS4     |
```

How can I select all orders:

on STATUS1,STATUS2 and STATUS4

between 2017-08-01 and 2017-08-15

without any rows on STATUS3

In this example, I would extract only order n. 201700013131.
Thanks.

答:
You can achieve this with NOT EXISTS like this:

```<code>SELECT DISTINCT ORDER_NUMBER
    FROM YourTable T
    WHERE STATUS IN('STATUS1', 'STATUS2', 'STATUS4')
        AND CREATION_DATE BETWEEN '20170801' AND '20170815'
        AND NOT EXISTS
            (
               SELECT * FROM YourTable
                   WHERE ORDER_NUMBER = T.ORDER_NUMBER
                      AND STATUS = 'STATUS3'
            );
</code>```

Body:
Suppose to have this table:

|ORDER_NUMBER|CREATION_DATE|   STATUS   |
|201700014587|  2017-08-01 |STATUS1     |
|201700014587|  2017-08-03 |STATUS2     |
|201700013131|  2017-08-07 |STATUS1     |
|201700013131|  2017-08-11 |STATUS2     |
|201700014587|  2017-08-13 |STATUS3     |
|201700013131|  2017-08-14 |STATUS4     |

How can I select all orders:

on STATUS1,STATUS2 and STATUS4

between 2017-08-01 and 2017-08-15

without any rows on STATUS3

In this example, I would extract only order n. 201700013131.
Thanks.

Body:
You can achieve this with NOT EXISTS like this:

SELECT DISTINCT ORDER_NUMBER
    FROM YourTable T
    WHERE STATUS IN('STATUS1', 'STATUS2', 'STATUS4')
        AND CREATION_DATE BETWEEN '20170801' AND '20170815'
        AND NOT EXISTS
            (
               SELECT * FROM YourTable
                   WHERE ORDER_NUMBER = T.ORDER_NUMBER
                      AND STATUS = 'STATUS3'
            );


问:
What is the difference between !empty($data['name']) and $data['name'] != '' in PHP?
Can anybody please me what is the difference between these two statements in PHP?

```<code>if ($data['name'] != '')
{
  ...
}
</code>```

and

```<code>if (!empty($data['name']))
{
  ...
}
</code>```

When I replaced the first statement with second it fixes the undefined array element error.

Thanks in advance.

答:
If you try to access a variable or array index which does not exists, PHP will warn you about this potential typo or incorrect logic with a Notice. If it's legitimate that you don't know whether the variable/index exists and you're trying to check precisely that, then use empty to suppress that notice.

empty is the same as == false, but does not raise notices in case of undefined variables/indices. Also see The Definitive Guide To PHP's isset And empty.

Beyond that, look at the comparison tables for what comparison will yield what for the nuances between == false and != '': http://php.net/manual/en/types.comparisons.php. The result will be different if $data['name'] contains a "0" or array(). Those will be considered empty (false), but they don't equal ''.

Body:
Can anybody please me what is the difference between these two statements in PHP?

if ($data['name'] != '')
{
  ...
}

and

if (!empty($data['name']))
{
  ...
}

When I replaced the first statement with second it fixes the undefined array element error.

Thanks in advance.


问:
Decrease row height on click on searchbar
I have some tableviewcells loaded on my tableview. Each of those cells has an arrow button at the top right on the click of which the height of the row is increased and some more buttons are exposed. Clicking on the button again hides the button & the height is decreased as before. The code for that is given like so...

```<code>func moreOptionsBtnTapped(cell: CustomersTableViewCell) {

    if i == 0 {
        if let indexPath = tableView?.indexPath(for: cell) {

            selectedIndex = indexPath as NSIndexPath
            tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
        }
        i += 1
    } else {
        if let indexPath = tableView?.indexPath(for: cell) {
            selectedIndex = indexPath as NSIndexPath
            tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
        }

        i = 0
    }
}
</code>```

The heightForRowAtIndexPath is given as:

```<code>   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if indexPath == selectedIndex as IndexPath {
        if i == 0 {
            return 92
        } else {
            return 66
        }
    }
return 66
</code>```

}

Now the issue is I also have a search bar on top and on click of that searchbar, if the additional buttons are exposed on the tableview cell then I want them to be minimised. Mere hiding them doesn't work. That has been tried.

Hope somebody can help...

答:
When you are clicking on search bar you will get the call back on UISearchBarDelegate methods like

```<code>optional public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool // return NO to not become first responder
</code>```

in this method you can change the i value and reload the table view. and in this method you are not getting the indexPath for rows , thats why you use this...

```<code> self.tableview.relaodData()
</code>```

Body:
I have some tableviewcells loaded on my tableview. Each of those cells has an arrow button at the top right on the click of which the height of the row is increased and some more buttons are exposed. Clicking on the button again hides the button & the height is decreased as before. The code for that is given like so...

func moreOptionsBtnTapped(cell: CustomersTableViewCell) {

    if i == 0 {
        if let indexPath = tableView?.indexPath(for: cell) {

            selectedIndex = indexPath as NSIndexPath
            tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
        }
        i += 1
    } else {
        if let indexPath = tableView?.indexPath(for: cell) {
            selectedIndex = indexPath as NSIndexPath
            tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
        }

        i = 0
    }
}

The heightForRowAtIndexPath is given as:

   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if indexPath == selectedIndex as IndexPath {
        if i == 0 {
            return 92
        } else {
            return 66
        }
    }
return 66

}

Now the issue is I also have a search bar on top and on click of that searchbar, if the additional buttons are exposed on the tableview cell then I want them to be minimised. Mere hiding them doesn't work. That has been tried.

Hope somebody can help...

Body:
When you are clicking on search bar you will get the call back on UISearchBarDelegate methods like

optional public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool // return NO to not become first responder

in this method you can change the i value and reload the table view. and in this method you are not getting the indexPath for rows , thats why you use this...

 self.tableview.relaodData()


问:
Reference types live on the heap, value types live on the stack
While reading "C# in Depth" I was going through the section titled "Reference types live on the heap, value types live on the stack."

Now what I could understand is (mainly for ref type):

```<code>class Program
{
    int a = 5;  // stored in heap

    public void Add(int x, int y) // x,y stored in stack
    {
        int c = x + y;  // c  stored in stack
    }
}
</code>```

Just want to clarify if my assumptions are right. Thanks.

EDIT:
I should have used diff variables, as I think what I had initially created confusion. So I have modified the code.

EDIT:
Yes, as Jon mentioned - it's a myth. I should have mentioned that. My apologies.

答:
Quoting Jon Skeet from his famous blog about how and where reference and value types are stored in a .NET application:

The memory slot for a variable is stored on either the stack or the
heap. It depends on the context in which it is declared:

Each local variable (ie one declared in a method) is stored on the stack. That includes reference type variables - the variable itself is
on the stack, but remember that the value of a reference type variable
is only a reference (or null), not the object itself. Method
parameters count as local variables too, but if they are declared with
the ref modifier, they don't get their own slot, but share a slot with
the variable used in the calling code. See my article on parameter
passing for more details.

Instance variables for a reference type are always on the heap. That's where the object itself "lives".

Instance variables for a value type are stored in the same context as the variable that declares the value type. The memory slot for the
instance effectively contains the slots for each field within the
instance. That means (given the previous two points) that a struct
variable declared within a method will always be on the stack, whereas
a struct variable which is an instance field of a class will be on the
heap.

Every static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. There is only
one slot in total no matter how many instances are created. (There
don't need to be any instances created for that one slot to exist
though.) The details of exactly which heap the variables live on are
complicated, but explained in detail in an MSDN article on the
subject.

ContentLicense: CC BY-SA 4.0

Body:
While reading "C# in Depth" I was going through the section titled "Reference types live on the heap, value types live on the stack."

Now what I could understand is (mainly for ref type):

class Program
{
    int a = 5;  // stored in heap

    public void Add(int x, int y) // x,y stored in stack
    {
        int c = x + y;  // c  stored in stack
    }
}

Just want to clarify if my assumptions are right. Thanks.

EDIT:
I should have used diff variables, as I think what I had initially created confusion. So I have modified the code.

EDIT:
Yes, as Jon mentioned - it's a myth. I should have mentioned that. My apologies.


问:
Get dates between 2 dates with equal intervals
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

```<code>Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017
</code>```

Please help!!

答:
```<code>DECLARE @StartDate  DATETIME,
    @EndDate        DATETIME

SELECT @StartDate = '2017-04-01',
    @EndDate = '2017-04-30'

SELECT DATEADD(DAY, number*7, @StartDate)
FROM master.dbo.spt_values
WHERE type='P'
    AND  @EndDate >= DATEADD(DAY, number*7, @StartDate)
</code>```

Body:
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017

Please help!!


问:
What is the correct way to add space to an HTML table?

I'm trying to adjust the spacing of a table in a webapp I'm building. I found various properties controlling space inside a table: cellspacing, cellpadding, border-spacing, and of course - margin and padding. What is the difference between those? Should I just use margin and padding which I know and understand, or is it more suitable and correct to use the table specific properties?  </p>

答:
I think the better solution is read something about that properties and decide what do you really need:

https://www.w3schools.com/tags/att_table_border.asp

https://www.w3schools.com/tags/att_table_cellpadding.asp

https://www.w3schools.com/tags/att_table_cellspacing.asp


答:
empty($data['name'] checks to see if a variable is empty. Empty is
interpreted as: "" (an empty string), 0 (integer), 0.0 (float)`, "0"
(string), NULL, FALSE, array() (an empty array), and "$var;" (a
variable declared, but without a value in a class.

$data['name'] != '' only checks if the respective data is not an
empty string.

Title: What is the difference between !empty($data['name']) and $data['name'] != '' in PHP?


答:
```<code>Declare @StartDate DATE=CONVERT(DATE,'01/04/2017',104),@EndDate DATE=CONVERT(DATE,'01/12/2017',104)
Declare @String NVARCHAR(MAX)=''

WHILE (@StartDate<=@EndDate AND DATEDIFF(wk,@StartDate,@EndDate)>=0)
BEGIN

SET @String=@String+CONVERT(NVARCHAR(100),@StartDate)+CHAR(10)+CHAR(13)

SET @StartDate=DATEADD(d,7,@StartDate)

END
PRINT  @String
GO
</code>```

Title: Get dates between 2 dates with equal intervals


问:
Shell script invocation error command /bin/sh failed with exit code 1
I'm getting shell script invocation error command /bin/sh failed with exit code 1 error in Xcode 9.1.

Precisely it's working fine, but it's getting error...
I tried to delete derived data, but after that also it's getting error.
Can any one help me to solve this error...

```<code>mkdir -p /Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/IQKeyboardManager/IQKeyboardManager.framework" "/Users/developement/Library/Developer/Xcode/DerivedData/elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks"
building file list ... done
IQKeyboardManager.framework/
IQKeyboardManager.framework/IQKeyboardManager
IQKeyboardManager.framework/Info.plist
IQKeyboardManager.framework/IQKeyboardManager.bundle/
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowDown@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowDown@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowLeft@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowLeft@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowRight@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowRight@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowUp@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowUp@3x.png

sent 631432 bytes  received 252 bytes  1263368.00 bytes/sec
total size is 630553  speedup is 1.00

Code Signing /Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework with Identity iPhone Developer: Developer ID
/usr/bin/codesign --force --sign 4A6D63EB1880BC5B617BFF614E2D009066DF1E  --preserve-metadata=identifier,entitlements '/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework'
/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework: unknown error -1=ffffffffffffffff
Command /bin/sh failed with exit code 1
</code>```

I'm getting this error only when I run in device. If i run in simulator it's working fine.

答:
In my case:

Clean Product

Clean Build Folder

Open derived data folder from Xcode

Quit XCode

Delete Derived data

Delete derived data from Trash as well

Open Xcode

Run your app

If this doesn't solve your problem, remove your account and add it again using below steps:

Open Preferences from XCode menu

Goto Accounts

Select your developer account under Apple IDs

Remove that account

Add your account back

This should solve your problem.

Body:
I'm getting shell script invocation error command /bin/sh failed with exit code 1 error in Xcode 9.1.

Precisely it's working fine, but it's getting error...
I tried to delete derived data, but after that also it's getting error.
Can any one help me to solve this error...

mkdir -p /Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/IQKeyboardManager/IQKeyboardManager.framework" "/Users/developement/Library/Developer/Xcode/DerivedData/elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks"
building file list ... done
IQKeyboardManager.framework/
IQKeyboardManager.framework/IQKeyboardManager
IQKeyboardManager.framework/Info.plist
IQKeyboardManager.framework/IQKeyboardManager.bundle/
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowDown@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowDown@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowLeft@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowLeft@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowRight@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowRight@3x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowUp@2x.png
IQKeyboardManager.framework/IQKeyboardManager.bundle/IQButtonBarArrowUp@3x.png

sent 631432 bytes  received 252 bytes  1263368.00 bytes/sec
total size is 630553  speedup is 1.00

Code Signing /Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework with Identity iPhone Developer: Developer ID
/usr/bin/codesign --force --sign 4A6D63EB1880BC5B617BFF614E2D009066DF1E  --preserve-metadata=identifier,entitlements '/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework'
/Users/developement/Library/Developer/Xcode/DerivedData/App Name-elbnnhecajvuocajithvpcwntcof/Build/Products/Release-iphoneos/App Name.app/Frameworks/IQKeyboardManager.framework: unknown error -1=ffffffffffffffff
Command /bin/sh failed with exit code 1

I'm getting this error only when I run in device. If i run in simulator it's working fine.


问:
Calcite doing full table scan
I'm using Calcite to query from both MySql and Vertica.

When running this query:

```<code>statement.executeQuery(
        "SELECT a.name, b.name " +
        "FROM mysqlschema.tableA as a " +
        "INNER JOIN verticaschema.tableB as b ON a.id = b.id " +
        "WHERE a.id = 1 AND b.id = 1 "));
</code>```

For some reason, I see that Calcite is properly accesing tableA whith the correct predicate but it's doing SELECT * FROM verticaschema.tableB for some reason over the second table.

Is there a way of optimizing it so Calcite will run the predicate b.id=1 over tableB too?

Thanks

答:
Apache Calcite has some limitations:

Current limitations: The JDBC adapter currently only pushes down table scan operations; all other processing (filtering, joins, aggregations and so forth) occurs within Calcite. Our goal is to push down as much processing as possible to the source system, translating syntax, data types and built-in functions as we go. If a Calcite query is based on tables from a single JDBC database, in principle the whole query should go to that database. If tables are from multiple JDBC sources, or a mixture of JDBC and non-JDBC, Calcite will use the most efficient distributed query approach that it can.

You should implement it yourself.

Title: Calcite doing full table scan

Body:
I'm using Calcite to query from both MySql and Vertica.

When running this query:

statement.executeQuery(
        "SELECT a.name, b.name " +
        "FROM mysqlschema.tableA as a " +
        "INNER JOIN verticaschema.tableB as b ON a.id = b.id " +
        "WHERE a.id = 1 AND b.id = 1 "));

For some reason, I see that Calcite is properly accesing tableA whith the correct predicate but it's doing SELECT * FROM verticaschema.tableB for some reason over the second table.

Is there a way of optimizing it so Calcite will run the predicate b.id=1 over tableB too?

Thanks


问:
MVC 2 AreaRegistration Routes Order
I noticed that in MVC 2 Preview 2, AreaRegistration is loading the routes for each area in an arbitrary order. Is there a good way to get one before the other?

For example, I have two areas - "Site" and "Admin". Both have a "Blog" controller.

I would like the following:

```<code>/admin/ --> go to Admin's Blog controller
/       --> go to Site's Blog controller.
</code>```

The problem is that it is loading the site's route first, so it is matching {controller}/{action}/{id} instead of admin/{controller}/{action}/{id} when I go to the url "/admin/". I then get a 404, because there is no Admin controller in the "Site" area.

Both areas default to the "Blog" controller. I realize I could simply put site/{controller}/... as the url, but I would rather have it at the root if possible. I also tried keeping the default route in the global RegisterRoutes function, however, it is then not sent to the "Sites" area.

Thanks in advance!

答:
I make this solution:

AreaUtils.cs

```<code>    using System;
    using System.Web.Mvc;
    using System.Web.Routing;

    namespace SledgeHammer.Mvc.Site
    {
        public static class Utils
        {
                public static void RegisterArea<T>(RouteCollection routes,
    object state) where T : AreaRegistration

            {
                 AreaRegistration registration =
     (AreaRegistration)Activator.CreateInstance(typeof(T));

                    AreaRegistrationContext context =
     new AreaRegistrationContext(registration.AreaName, routes, state);

                    string tNamespace = registration.GetType().Namespace;
                    if (tNamespace != null)
                {
                    context.Namespaces.Add(tNamespace + ".*");
                }

                registration.RegisterArea(context);
            }
        }

    }
</code>```

In global.asax:

```<code>Utils.RegisterArea<SystemAreaRegistration>(RouteTable.Routes, null);
Utils.RegisterArea<ClientSitesAreaRegistration>(RouteTable.Routes, null);

//AreaRegistration.RegisterAllAreas(); do not dublicate register areas
</code>```

No requred changes to generated area registration code.
I also use custom constrant in routes to filter routes by type of domain in request (system domain or user site).

This is my area registrations as example:

```<code>namespace SledgeHammer.MVC.Site.Areas.System
{
    public class SystemAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get { return "System"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "System_Feedback",
                "Feedback",
                new { controller = "Feedback", action = "Index" }
            );
            context.MapRoute(
                "System_Information",
                "Information/{action}/{id}",
                new { controller = "Information", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

namespace SledgeHammer.MVC.Site.Areas.ClientSites
{
    public class ClientSitesAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get { return "ClientSites"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "ClientSites_default",
                "{controller}/{action}/{id}",
                new { controller = "Site", action = "Index", id = UrlParameter.Optional },
                new { Host = new SiteInGroups("clients") }
            );
        }
    }
}
</code>```

Title: MVC 2 AreaRegistration Routes Order

Body:
I noticed that in MVC 2 Preview 2, AreaRegistration is loading the routes for each area in an arbitrary order. Is there a good way to get one before the other?

For example, I have two areas - "Site" and "Admin". Both have a "Blog" controller.

I would like the following:

/admin/ --> go to Admin's Blog controller
/       --> go to Site's Blog controller.

The problem is that it is loading the site's route first, so it is matching {controller}/{action}/{id} instead of admin/{controller}/{action}/{id} when I go to the url "/admin/". I then get a 404, because there is no Admin controller in the "Site" area.

Both areas default to the "Blog" controller. I realize I could simply put site/{controller}/... as the url, but I would rather have it at the root if possible. I also tried keeping the default route in the global RegisterRoutes function, however, it is then not sent to the "Sites" area.

Thanks in advance!

Body:
I make this solution:

AreaUtils.cs

    using System;
    using System.Web.Mvc;
    using System.Web.Routing;

    namespace SledgeHammer.Mvc.Site
    {
        public static class Utils
        {
                public static void RegisterArea<T>(RouteCollection routes,
    object state) where T : AreaRegistration

            {
                 AreaRegistration registration =
     (AreaRegistration)Activator.CreateInstance(typeof(T));

                    AreaRegistrationContext context =
     new AreaRegistrationContext(registration.AreaName, routes, state);

                    string tNamespace = registration.GetType().Namespace;
                    if (tNamespace != null)
                {
                    context.Namespaces.Add(tNamespace + ".*");
                }

                registration.RegisterArea(context);
            }
        }

    }

In global.asax:

Utils.RegisterArea<SystemAreaRegistration>(RouteTable.Routes, null);
Utils.RegisterArea<ClientSitesAreaRegistration>(RouteTable.Routes, null);

//AreaRegistration.RegisterAllAreas(); do not dublicate register areas

No requred changes to generated area registration code.
I also use custom constrant in routes to filter routes by type of domain in request (system domain or user site).

This is my area registrations as example:

namespace SledgeHammer.MVC.Site.Areas.System
{
    public class SystemAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get { return "System"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "System_Feedback",
                "Feedback",
                new { controller = "Feedback", action = "Index" }
            );
            context.MapRoute(
                "System_Information",
                "Information/{action}/{id}",
                new { controller = "Information", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

namespace SledgeHammer.MVC.Site.Areas.ClientSites
{
    public class ClientSitesAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get { return "ClientSites"; }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "ClientSites_default",
                "{controller}/{action}/{id}",
                new { controller = "Site", action = "Index", id = UrlParameter.Optional },
                new { Host = new SiteInGroups("clients") }
            );
        }
    }
}


问:
Divisions between large numbers with long integers: how to bypass float conversion?
I need to calculate a ratio between very large numbers as shown in the code:

```<code>import scipy.special

x=2000
n=range(8,x+1)
q=[]

for i in range(0,len(n)):

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.binom(n[i]//7+n[i]%7,n[i]//7))*(26**n[i])**(-1))
</code>```

I get errors since numbers are too large:

```<code>OverflowError: long int too large to convert to float
</code>```

how can I handle such large numbers?

Body:
I need to calculate a ratio between very large numbers as shown in the code:

import scipy.special

x=2000
n=range(8,x+1)
q=[]

for i in range(0,len(n)):

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.binom(n[i]//7+n[i]%7,n[i]//7))*(26**n[i])**(-1))

I get errors since numbers are too large:

OverflowError: long int too large to convert to float

how can I handle such large numbers?

Body:
You can use scipy.special.comb with the exact kwd and replace *large^(-1) with /large:

import scipy.special

x=2000
n=range(8,x+1)
q=[]

for i in range(0,len(n)):

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.comb(n[i]//7+n[i]%7,n[i]//7, exact=True))/(26**n[i]))

print(q[-10:])

# [2.4714229501232675e-07, 2.4726679994684175e-07, 2.473913048813568e-07, 2.4751580981587185e-07, 2.4764031475038685e-07, 2.477648196849019e-07, 2.478893246194169e-07, 2.4801382955393194e-07, 2.4813833448844694e-07, 2.48262839422962e-07]

Division itself doesn't seem to be a problem:

(3**100)/(4**88)
# 5.380792381981753e-06

Note: The above appplies to Python3. On Python2 division between ints defaults to return an int. You can either use __truediv__

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.comb(n[i]//7+n[i]%7,n[i]//7, exact=True)).__truediv__((26**n[i])))

or use a future import

from __future__ import division


问:
Integrate flask with legacy Database
I am new with flask, I am trying to create model classes from existing database tables ,in Django to achieve that we can use python manage.py inspectdb it will create a model classes.

Is there any slimier option in flask ?

I searched it and found some options like SQLAlchemy's autoload, it does not creates models classes on the fly.
Please suggest..

答:
flask is micro what-does-micro-mean

The “micro” in microframework means Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what database to use

so you should understand many options that django has in box not in flask, for many solution you need to find extension, which is better for your project. And if you whant to use SQLAlchemy you can try sqlacodegen
for details:

```<code>sqlacodegen --help
</code>```

Title: Integrate flask with legacy Database

Body:
flask is micro what-does-micro-mean

The “micro” in microframework means Flask aims to keep the core simple but extensible. Flask won’t make many decisions for you, such as what database to use

so you should understand many options that django has in box not in flask, for many solution you need to find extension, which is better for your project. And if you whant to use SQLAlchemy you can try sqlacodegen
for details:

sqlacodegen --help


问:
How to update ListView without freezing the program
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}
</code>```

答:
I think if you are open to use a open source project ,then my suggestion will be use RX-JAVA.Which is based in reactive and push based model.

link for rx-java.

rx-java example.

Body:
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}


问:
How can I switch to another branch in git?
Which one of these lines is correct?

```<code>git checkout 'another_branch'
</code>```

or

```<code>git checkout origin 'another_branch'
</code>```

or

```<code>git checkout origin/'another_branch'
</code>```

And what is the difference between them?

答:
[git checkout "branch_name"]

is another way to say:

[git checkout -b branch_name origin/branch_name]

in case "branch_name" exists only remotely.

[git checkout -b branch_name origin/branch_name] is useful in case you have multiple remotes.

Regarding [git checkout origin 'another_branch'] I'm not sure this is possible, AFAK you can do this using "fetch" command
-- [git fetch origin 'another_branch']

Body:
Which one of these lines is correct?

git checkout 'another_branch'

or

git checkout origin 'another_branch'

or

git checkout origin/'another_branch'

And what is the difference between them?


问:
Order object by enum in custom order
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

```<code>public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }
</code>```

My Animal class:

```<code>public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }
</code>```

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

答:
You can check if any of them are Medium before comparing (not tested) :

```<code>public int CompareTo(Animal other)
{
    if (this.Size == other.Size) return 0;
    if (this.Size == AnimalSize.Medium) return -1;
    if (other.Size == AnimalSize.Medium) return 1;

    return this.Size.CompareTo(other.Size);
}
</code>```

A bit more efficient without branch misprediction (3 becomes 1, 5 ⇒ 3, and 1 ⇒ 7) :

```<code>public int CompareTo(Animal other) => ((int)this.Size + 2 ^ 4) - ((int)other.Size + 2 ^ 4);
</code>```

or lookup array (3 ⇒ 1, 5 ⇒ 2, and 1 ⇒ 3) :

```<code>byte[] order = { 0, 3, 0, 1, 0, 2 };

public int CompareTo(Animal other) => order[(byte)this.Size] - order[(byte)other.Size];
</code>```

Title: Order object by enum in custom order

Body:
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }

My Animal class:

public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

Body:
You can check if any of them are Medium before comparing (not tested) :

public int CompareTo(Animal other)
{
    if (this.Size == other.Size) return 0;
    if (this.Size == AnimalSize.Medium) return -1;
    if (other.Size == AnimalSize.Medium) return 1;

    return this.Size.CompareTo(other.Size);
}

A bit more efficient without branch misprediction (3 becomes 1, 5 ⇒ 3, and 1 ⇒ 7) :

public int CompareTo(Animal other) => ((int)this.Size + 2 ^ 4) - ((int)other.Size + 2 ^ 4);

or lookup array (3 ⇒ 1, 5 ⇒ 2, and 1 ⇒ 3) :

byte[] order = { 0, 3, 0, 1, 0, 2 };

public int CompareTo(Animal other) => order[(byte)this.Size] - order[(byte)other.Size];


问:
Simple programming practice (using modulus op)
First question, I'm trying to do a practice where I am asked to return true if the given non-negative number is a multiple of 3 or 5, but not both. Examples are;

old35(3) → true

old35(10) → true

old35(15) → false

So 3 would be true, as it's a multiple of 3, but I can't currently make my code work for all instances. Code below;

```<code>public boolean old35(int n) {
     if ((35 % n == 3) || (35 % n == 5))
        return true;
     return false;
}
</code>```

How could I edit this to fit the criteria of what the practice is telling me to do?
>

答:
I will throw a detailed explanation. First, you use the remainder sign to check the condition where remainder is zero;

```<code>n % 3 == 0
</code>```

and

```<code>n % 5 == 0
</code>```

Then for a one to one translation for your conditions, put them together as:

```<code>((n % 3 == 0) || (n % 5 == 0)) // Multiple of 3 or 5

!((n % 3 == 0) && (n % 5 == 0)) // But not both
</code>```

Add (and) them together;

```<code>public static boolean old35(int n) {
  return(((n % 3 == 0) || (n % 5 == 0)) && !((n % 3 == 0) && (n % 5 == 0)));
}
</code>```

But simply, what you are doing is the XOR (^) operation, the following code is valid and simple:

```<code>public static boolean old35(int n) {
  return((n % 3 == 0) ^ (n % 5 == 0));
}
</code>```

Body:
First question, I'm trying to do a practice where I am asked to return true if the given non-negative number is a multiple of 3 or 5, but not both. Examples are;

old35(3) → true

old35(10) → true

old35(15) → false

So 3 would be true, as it's a multiple of 3, but I can't currently make my code work for all instances. Code below;

public boolean old35(int n) {
     if ((35 % n == 3) || (35 % n == 5))
        return true;
     return false;
}

How could I edit this to fit the criteria of what the practice is telling me to do?
>

Body:
I will throw a detailed explanation. First, you use the remainder sign to check the condition where remainder is zero;

n % 3 == 0

and

n % 5 == 0

Then for a one to one translation for your conditions, put them together as:

((n % 3 == 0) || (n % 5 == 0)) // Multiple of 3 or 5

!((n % 3 == 0) && (n % 5 == 0)) // But not both

Add (and) them together;

public static boolean old35(int n) {
  return(((n % 3 == 0) || (n % 5 == 0)) && !((n % 3 == 0) && (n % 5 == 0)));
}

But simply, what you are doing is the XOR (^) operation, the following code is valid and simple:

public static boolean old35(int n) {
  return((n % 3 == 0) ^ (n % 5 == 0));
}


问:
PHP Web App - local and online synced versions
I developed a PHP driven Web App with a MySQL backend. New requirement is to have it available offline too at a client's office, once there is an lnternet connection, the two should sync so that both local and online versions are the same. Any advice on how best to implement this?</p>

答:
I found MySQL database Master-Master Replication helpful.

https://www.linode.com/docs/databases/mysql/configure-master-master-mysql-database-replication

no need to write code


问:
How to get all possible latitude and longitude based specific distance from location
I want to restrict map to specific distance as example 15 km from my current location to restrict user navigate to another locations.

I can calculate the distance between 2 points correctly based on the following function

```<code>public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 6371.0; // earth radius in km
    double dLat = Math.toRadians(lat2 - lat1);
    double dLng = Math.toRadians(lng2 - lng1);
    double sindLat = Math.sin(dLat / 2);
    double sindLng = Math.sin(dLng / 2);
    double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
            * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double dist = earthRadius * c;

    return dist;
}
</code>```

but cannot get possible latitude and longitude from my location in all sides based on specific distance because user can navigate in any side in map.

I tried this example but not give my accurate result.

答:
Check this answer here:
https://stackoverflow.com/a/7478827/1397821

Now put all angles 0-360 in the equations mentioned in the above answer to get all the Lat Longs.

Hope this helps

Body:
I want to restrict map to specific distance as example 15 km from my current location to restrict user navigate to another locations.

I can calculate the distance between 2 points correctly based on the following function

public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 6371.0; // earth radius in km
    double dLat = Math.toRadians(lat2 - lat1);
    double dLng = Math.toRadians(lng2 - lng1);
    double sindLat = Math.sin(dLat / 2);
    double sindLng = Math.sin(dLng / 2);
    double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
            * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double dist = earthRadius * c;

    return dist;
}

but cannot get possible latitude and longitude from my location in all sides based on specific distance because user can navigate in any side in map.

I tried this example but not give my accurate result.


问:
How to create methods in Jenkins Declarative pipeline?
In Jenkins scripted pipeline we are able to create methods and can call them.

Is it possible also in the Jenkins declarative pipeline? And how?

答:
You can create a groovy function like this and save it in your git which should be configured as managed library (Configure it in jenkins too):

```<code>/path/to/repo-shared-library/vars/sayHello.groovy:
</code>```

Content:

```<code>def call(String name = 'human') {
    echo "Hello, ${name}."
}
</code>```

You can just call this method in your pipeline using:

```<code>@Library('name-of-shared-library')_
pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                sayHello 'Joe'
            }
        }
    }
}
</code>```

Output:

```<code>[Pipeline] echo
Hello, Joe.
</code>```

You can reuse existing functions which you keep in your library.

Body:
You can create a groovy function like this and save it in your git which should be configured as managed library (Configure it in jenkins too):

/path/to/repo-shared-library/vars/sayHello.groovy:

Content:

def call(String name = 'human') {
    echo "Hello, ${name}."
}

You can just call this method in your pipeline using:

@Library('name-of-shared-library')_
pipeline {
    agent any
    stages {
        stage('test') {
            steps {
                sayHello 'Joe'
            }
        }
    }
}

Output:

[Pipeline] echo
Hello, Joe.

You can reuse existing functions which you keep in your library.


问:
Syntax error in SQL query: unexpected 'SUM' (sum)

I am trying to run the following query and I am getting the following error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'sum(sl.duration) as duration, sum(sl.quantity_loss) as
  quantity_loss'

```<code>SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(sl.duration * b.marginal_value_downtime) AS value_loss where en.state = 'downtime',
   SUM(sl.quantity_loss * p.marginal_value) as value_loss where en.state != 'downtime',
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM
    sub_losses AS sl
</code>```

Any idea why is this syntax error occurring?

答:
TRY THIS: Except above comments it is not allowed to use same ALIAS or COLUMN NAME more than once in a single block of query so I have given value_loss1 to make is unique.

```<code>SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(CASE WHEN en.state = 'downtime' THEN (sl.duration * b.marginal_value_downtime) ELSE 0 END) AS value_loss,
   SUM(CASE WHEN en.state != 'downtime' THEN (sl.quantity_loss * p.marginal_value) ELSE 0 END) AS value_loss1,
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM sub_losses AS sl
GROUP BY lr.uid,
         gl.uid,
         lt.uid
</code>```

Body:
I am trying to run the following query and I am getting the following error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'sum(sl.duration) as duration, sum(sl.quantity_loss) as
  quantity_loss'

SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(sl.duration * b.marginal_value_downtime) AS value_loss where en.state = 'downtime',
   SUM(sl.quantity_loss * p.marginal_value) as value_loss where en.state != 'downtime',
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM
    sub_losses AS sl

Any idea why is this syntax error occurring?

Body:
TRY THIS: Except above comments it is not allowed to use same ALIAS or COLUMN NAME more than once in a single block of query so I have given value_loss1 to make is unique.

SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(CASE WHEN en.state = 'downtime' THEN (sl.duration * b.marginal_value_downtime) ELSE 0 END) AS value_loss,
   SUM(CASE WHEN en.state != 'downtime' THEN (sl.quantity_loss * p.marginal_value) ELSE 0 END) AS value_loss1,
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM sub_losses AS sl
GROUP BY lr.uid,
         gl.uid,
         lt.uid


问:
Xcode 9 error: "iPhone has denied the launch request"
Using Xcode beta 9 (v4), I'm trying to launch the app by clicking on the "play" button. I get a "build succeeded" but right before launching, a popup message appears in Xcode:

"iPhone has denied the launch request."

It used to work yesterday. It does work on the simulator. I've rebooted my computer, the iPhone, uninstall the app, cleaned the build. Running out of ideas.

答: I had the same issue . Its a bug in Xcode 9.1. There is a trick to make it work for now. Lock your phone. Run the code. Xcode will ask to unlock the iPhone. </p>


问:
The currently selected JAXB library provider is invalid
I'm using Elipse Neon with JDK 1.8 and run time environment GlassFish 4.1. I have tried to add to my project facet configuration JAXB 2.2 however I'm getting the error: The currently selected JAXB library provider is invalid.

What I can do, or what library I should use in order to use JAXB configuration. Additionally I mention that I'm using JAXB for a JAX-RS project with Jersey implementation (natively build into Glassfish)

Regards,

答:
JAXB is present in GlassFish, you do not need to add it. For GlassFish 4.1, just add the Java EE 7.0 full profile as a provided dependency so that you can develop with all the APIs, knowing they will be there when you deploy your WAR:

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>
</code>```

Body:
JAXB is present in GlassFish, you do not need to add it. For GlassFish 4.1, just add the Java EE 7.0 full profile as a provided dependency so that you can develop with all the APIs, knowing they will be there when you deploy your WAR:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
</dependency>


问:
FFMPEG RTP MpegTS Muxrate
I am needing an application that takes an input rtp MpegTS stream and re-muxes it, remaps the PIDs and then sends it out as an RTP MpegTS multicast. I understand FFMPEG in its current form cannot do this as the rtp_mpegts does not pick up the options from the command line.

I have started to look at the FFMPEG source to find a way to add it into to have these options. I am slightly confused by the way FFMPEG uses the AVFormatContext to pass around information. I have added a new priv_class to the rtp_mepgts which points to a class with options in it (identical to the mpegtsenc.c class) so that the options will actually be added to that context. However, it is now failing when trying to do a realloc somewhere.

Before going down the line too far - is this the correct approach to take? Is this how to add the options correctly to FFMPEG or is there another way completely I should be looking?

答:
Remmaping of PIDs can be done in ffmpeg.

fmpeg -i input -c copy -f mpegts \

 -mpegts_original_network_id 0x1122 \

 -mpegts_transport_stream_id 0x3344 \

 -mpegts_service_id 0x5566 \

 -mpegts_service_type 0x1 \

 -mpegts_pmt_start_pid 0x1500 \

 -mpegts_start_pid 0x150 \

 -metadata service_provider="Some provider" \

 -metadata service_name="Some Channel" \

 -tables_version 5 \

 sample.ts

Remuxing can be done via ffmpeg using [muxrate] parameter

Changing RTP to UDP and to RTP can be done using multicat tool
https://www.videolan.org/projects/multicat.html

Title: FFMPEG RTP MpegTS Muxrate


问:
Explicit constructors and nested initializer lists
The following code successfully compiles with most modern C++11 compatible compilers (GCC >= 5.x, Clang, ICC, MSVC).

```<code>#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1({{{"test"}}});
}
</code>```

But why does it compile in the first place, and how are the listed compilers interpreting that code?

Why is MSVC able to compile this without B(B &) = delete;, but the other 3 compilers all need it?

And why does it fail in all compilers except MSVC when I delete a different signature of the copy constructor, e.g. B(const B &) = delete;?

Are the compilers even all choosing the same constructors?

Why does Clang emit the following warning?

```<code>17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1({{{"test"}}});
</code>```

答:
(Edited, thanks @dyp)

Here's a partial answer and speculative, explaining how I've gone about interpreting what happens, not being a compilation expert and not much of a C++ Guru.

First I'll go with some intuition and common sense. Obviously the last thing to happen is a B::B(A), since that's the only constructor available for B b1 (apparently it can't be a B::B(B&&) because there's at least one copy constructor defined, so B::B(B&&) is not implicitly defined for us). Also, the first construction of an A or a B to happen can't be an A::A(const char*) because that one's explicit, so there must be some use of A::A(std::string). Also, the innermost quoted text is a const char[5]. So I'll guess the first, innermost, construction is a const char*; and then a string construction: std::string::string(const char *). There's one more curly-bracket construction, and I would guess it's A::A(A&&) (or maybe A::A(A&)?). So, to summarize my intuitive guess, the order of constructions should be:

A const char*

An std::string (which is really std::basic_string<whatever>)

an A

a B

Then I put this on GodBolt, with GCC as the first example. (Alternatively, you could just compile it yourself while keeping the assembly language output, and pass that through c++filt to make it more readable). Here are all the lines specifically mentioning C++ code:

```<code>call   4006a0 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@plt>
call   400858 <A::A(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)>
call   400868 <B::B(A)>
call   400680 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@plt>
call   400690 <std::allocator<char>::~allocator()@plt>
call   400690 <std::allocator<char>::~allocator()@plt>
</code>```

So it seems the order of proper actionable constructions we see is:

(not seeing 1.)
2. std::basic_string::basic_string(const char* /* ignoring the allocator */)
3. A::A(std::string)
4. B::B(A)

With clang 5.0.0, results are similar IIANM, and as for MSVC - who knows? Maybe it's a bug? They have been known to be a bit dodgy sometimes on properly supporting the language standard all the way. Sorry, like I said - partial answer.

Body:
The following code successfully compiles with most modern C++11 compatible compilers (GCC >= 5.x, Clang, ICC, MSVC).

#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1({{{"test"}}});
}

But why does it compile in the first place, and how are the listed compilers interpreting that code?

Why is MSVC able to compile this without B(B &) = delete;, but the other 3 compilers all need it?

And why does it fail in all compilers except MSVC when I delete a different signature of the copy constructor, e.g. B(const B &) = delete;?

Are the compilers even all choosing the same constructors?

Why does Clang emit the following warning?

17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1({{{"test"}}});

Body:
(Edited, thanks @dyp)

Here's a partial answer and speculative, explaining how I've gone about interpreting what happens, not being a compilation expert and not much of a C++ Guru.

First I'll go with some intuition and common sense. Obviously the last thing to happen is a B::B(A), since that's the only constructor available for B b1 (apparently it can't be a B::B(B&&) because there's at least one copy constructor defined, so B::B(B&&) is not implicitly defined for us). Also, the first construction of an A or a B to happen can't be an A::A(const char*) because that one's explicit, so there must be some use of A::A(std::string). Also, the innermost quoted text is a const char[5]. So I'll guess the first, innermost, construction is a const char*; and then a string construction: std::string::string(const char *). There's one more curly-bracket construction, and I would guess it's A::A(A&&) (or maybe A::A(A&)?). So, to summarize my intuitive guess, the order of constructions should be:

A const char*

An std::string (which is really std::basic_string<whatever>)

an A

a B

Then I put this on GodBolt, with GCC as the first example. (Alternatively, you could just compile it yourself while keeping the assembly language output, and pass that through c++filt to make it more readable). Here are all the lines specifically mentioning C++ code:

call   4006a0 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)@plt>
call   400858 <A::A(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)>
call   400868 <B::B(A)>
call   400680 <std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()@plt>
call   400690 <std::allocator<char>::~allocator()@plt>
call   400690 <std::allocator<char>::~allocator()@plt>

So it seems the order of proper actionable constructions we see is:

(not seeing 1.)
2. std::basic_string::basic_string(const char* /* ignoring the allocator */)
3. A::A(std::string)
4. B::B(A)

With clang 5.0.0, results are similar IIANM, and as for MSVC - who knows? Maybe it's a bug? They have been known to be a bit dodgy sometimes on properly supporting the language standard all the way. Sorry, like I said - partial answer.


问:
Script to go to every subdirectory of a folder and run command
I am trying to write a script that performs the following steps:
1. Go to every folder in a directory which was given as parameter when running the script.
2. Make a folder in each subdirectory called "Histogram"
3. Read out every file with the Ending *.jpg
4. Convert a picture into a txt-file by the command "Convert XY -format %c histogram:info:XY.txt
5. Move txt-file to folder "Histogram"
6. Go back to start directory and continue with next folder

This is what I got so far:

```<code>pfad="${1:-.}"
cd "$pfad/"
mkdir Histogram
for i in 'ls -1 *.jpg'
do
cat $1 |
convert $i -format %c histogram:info:"Histogram_$1'.txt"|
mv "Histogram_$i'.txt" Histogram/
</code>```

It is still missing, that the script executes the command for each subdirectory, also the making of the folder and the moving of the txt-file in the folder does not work.

答:
create a script which takes a list of absolute file name and creates Histrogram folder if not exists and creates txt file

```<code>#!/usr/bin/bash
for absfile in "$@"; do
    dir=${absfile%/*}/Histogram
    file=${absfile##*/}
    mkdir -p "$dir" || exit 1
    convert "$absfile" -format %c histogram:info:"$dir/Histogram_$file.txt" || exit 1
done
</code>```

call this script in  find command

```<code>find root_path -name '*.jpg' -exec ./script.sh {} +
</code>```

Body:
I am trying to write a script that performs the following steps:
1. Go to every folder in a directory which was given as parameter when running the script.
2. Make a folder in each subdirectory called "Histogram"
3. Read out every file with the Ending *.jpg
4. Convert a picture into a txt-file by the command "Convert XY -format %c histogram:info:XY.txt
5. Move txt-file to folder "Histogram"
6. Go back to start directory and continue with next folder

This is what I got so far:

pfad="${1:-.}"
cd "$pfad/"
mkdir Histogram
for i in 'ls -1 *.jpg'
do
cat $1 |
convert $i -format %c histogram:info:"Histogram_$1'.txt"|
mv "Histogram_$i'.txt" Histogram/

It is still missing, that the script executes the command for each subdirectory, also the making of the folder and the moving of the txt-file in the folder does not work.

Body:
create a script which takes a list of absolute file name and creates Histrogram folder if not exists and creates txt file

#!/usr/bin/bash
for absfile in "$@"; do
    dir=${absfile%/*}/Histogram
    file=${absfile##*/}
    mkdir -p "$dir" || exit 1
    convert "$absfile" -format %c histogram:info:"$dir/Histogram_$file.txt" || exit 1
done

call this script in  find command

find root_path -name '*.jpg' -exec ./script.sh {} +


问:
How to hide discount field in Invoice form? Odoo
I have try to hide discount field in invoice form by xpath. However it doesn't work.

The following is my code :

<odoo>
  <data>
    <record model="ir.ui.view" id="hidden_discount">
      <field name="name">account.invoice.hidden.discount</field>
      <field name="model">account.invoice</field>
      <field name="inherit_id" ref="account.invoice_form"/>
      <field name="arch" type="xml">
        <xpath expr="//field[@name='discount']" position="attributes">
            <attribute name="invisible">True</attribute>
        </xpath>
      </field>
    </record>
  </data>
</odoo>
```

Do you have any solution or suggestion?

答:
There is no direct form view design for One2many field. So we need to upgrade account.invoice.line form view directly.

Try with following code.

<record model="ir.ui.view" id="hidden_discount">
    <field name="name">account.invoice.line.hidden.discount</field>
    <field name="model">account.invoice.line</field>
    <field name="inherit_id" ref="account.view_invoice_line_form"/>
    <field name="arch" type="xml">
        <field name="discount" position="attributes">
            <attribute name="invisible">1</attribute>
        </field>
    </field>
</record>
```

Body:
I have try to hide discount field in invoice form by xpath. However it doesn't work.

The following is my code :

<odoo>
  <data>
    <record model="ir.ui.view" id="hidden_discount">
      <field name="name">account.invoice.hidden.discount</field>
      <field name="model">account.invoice</field>
      <field name="inherit_id" ref="account.invoice_form"/>
      <field name="arch" type="xml">
        <xpath expr="//field[@name='discount']" position="attributes">
            <attribute name="invisible">True</attribute>
        </xpath>
      </field>
    </record>
  </data>
</odoo>

Do you have any solution or suggestion?


问:
if statement won't check through my array list
I was trying not to resort to posting on the forums but everything I've done will not make this work. What I'm trying to do is if an ArrayList doesn't contain a players name then it will add them to the ArrayList, but it's skipping over that and just removing them from the list they were never added to. Ultimate goal out of this plugin is if they are in god mode they can't be hurt.
Command Class:

```<code>    public static List<String> playerList = new ArrayList<String>();

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
        Player player = (Player) sender;
        String p = player.getName();
        List<String> isGod = new ArrayList<String>();

        if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
            if (!isGod.contains(p)) {
                isGod.add(p);
                playerList.add(p);
                player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
                return true;
            } else {
                isGod.remove(p);
                playerList.remove(p);
                player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
                return true;
            }
        }
        return true;
    }
}
</code>```

Listener Class:

```<code>    @EventHandler
    public void isDamaged(EntityDamageEvent e) {
        String player = e.getEntity().getName();
        if (playerList.contains(player)) {
            e.setCancelled(true);
        }
    }
}
</code>```

答:
As dly said yes, you create new empty list every time command is executed. You must init your list as global static in your class in order to make sure that this is only one list for all operations.

```<code>public static List<String> isGod = new ArrayList<>();             // <== HERE
public static List<String> playerList = new ArrayList<String>();

@Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
    Player player = (Player) sender;
    String p = player.getName();

    if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
        if (!isGod.contains(p)) {
            isGod.add(p);
            playerList.add(p);
            player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
            return true;
        } else {
            isGod.remove(p);
            playerList.remove(p);
            player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
            return true;
        }
    }
    return true;
}
</code>```

Body:
I was trying not to resort to posting on the forums but everything I've done will not make this work. What I'm trying to do is if an ArrayList doesn't contain a players name then it will add them to the ArrayList, but it's skipping over that and just removing them from the list they were never added to. Ultimate goal out of this plugin is if they are in god mode they can't be hurt.
Command Class:

    public static List<String> playerList = new ArrayList<String>();

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
        Player player = (Player) sender;
        String p = player.getName();
        List<String> isGod = new ArrayList<String>();

        if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
            if (!isGod.contains(p)) {
                isGod.add(p);
                playerList.add(p);
                player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
                return true;
            } else {
                isGod.remove(p);
                playerList.remove(p);
                player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
                return true;
            }
        }
        return true;
    }
}

Listener Class:

    @EventHandler
    public void isDamaged(EntityDamageEvent e) {
        String player = e.getEntity().getName();
        if (playerList.contains(player)) {
            e.setCancelled(true);
        }
    }
}

Body:
As dly said yes, you create new empty list every time command is executed. You must init your list as global static in your class in order to make sure that this is only one list for all operations.

public static List<String> isGod = new ArrayList<>();             // <== HERE
public static List<String> playerList = new ArrayList<String>();

@Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
    Player player = (Player) sender;
    String p = player.getName();

    if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
        if (!isGod.contains(p)) {
            isGod.add(p);
            playerList.add(p);
            player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
            return true;
        } else {
            isGod.remove(p);
            playerList.remove(p);
            player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
            return true;
        }
    }
    return true;
}


问:
Progress bar overflow div
I'm doing progress bar I added div inside bar but at 0% and 100% value is overflow and while moving also looks like a doubt after reached the point then shows full width.

Expected output:

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});
```

<pre class="lang-css prettyprint-override"><code>/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
    position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
}
.testimonial_block2 .percentage {
    display: flex;
    position: absolute;
    padding: 5px;
    top: 6px;
    right: 0;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}
</code>```

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

```

答:
You can create a function who calculate the width of your element percentage and make the left with this percent.

i have create this. you can modify this:

```<code>if(percent >= 88){
  perce = 100 - percent
  $(this).find(".percentage").css({left:(88-perce) + "%"})
}else{
  $(this).find(".percentage").css({left:(percent) + "%"})
}
</code>```

Full code

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            if(percent >= 88){
              perce = 100 - percent
              $(this).find(".percentage").css({left:(88-perce) + "%"})
            }else{
              $(this).find(".percentage").css({left:(percent) + "%"})
            }

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);

        });
    }

    progressbar();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
 position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
    overflow: visible !important;
}
.testimonial_block2 .percentage {
 display: flex;
 position: absolute;
    padding: 5px;
    top: 6px;

    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}</code>```

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

```

Title: Progress bar overflow div

Body:
I'm doing progress bar I added div inside bar but at 0% and 100% value is overflow and while moving also looks like a doubt after reached the point then shows full width.

Expected output:

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);
        });
    }

    progressbar();
});

/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
    position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
}
.testimonial_block2 .percentage {
    display: flex;
    position: absolute;
    padding: 5px;
    top: 6px;
    right: 0;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}

5 REVIEWS

4 REVIEWS

3 REVIEWS

2 REVIEWS

1 REVIEWS

Body:
You can create a function who calculate the width of your element percentage and make the left with this percent.

i have create this. you can modify this:

if(percent >= 88){
  perce = 100 - percent
  $(this).find(".percentage").css({left:(88-perce) + "%"})
}else{
  $(this).find(".percentage").css({left:(percent) + "%"})
}

Full code

$(document).ready(function(){
    function progressbar() {
        $('.iva_progress_bar').each(function() {

            var totalreviews = 1540;

            var percent = $(this).find('.bar_color').attr('data-width');

            if(percent >= 88){
              perce = 100 - percent
              $(this).find(".percentage").css({left:(88-perce) + "%"})
            }else{
              $(this).find(".percentage").css({left:(percent) + "%"})
            }

            $(this).find('.percentage').append(percent + '%');
            $(this).find('.bar_color').animate({
                  width: percent + '%'
             }, 1500);

            var a = $(this).find('.bar_color').attr('data-width');
            var ur = ( a/ 100 ) * totalreviews;

            var usersReview = Math.floor(ur);
            $(this).find('.users').append(usersReview);

        });
    }

    progressbar();
});

/* progress bar */
.testimonial_block2 .iva_progress_bar {
    display: flex;
    width: 100%;
    margin-bottom: 25px;
    flex-direction: row;
}
.testimonial_block2 .iva_progress_bar .bar_title {
    flex-basis: 15%;
    align-self: center;
    text-align: center;
    font-size: 18px;
}
.testimonial_block2 .iva_progress_bar .bar_wrap {
    flex-basis: 70%;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.09) inset;
    background-color: #ebebeb;
}
.testimonial_block2 .iva_progress_bar .bar_color {
 position: relative;
    padding: 18px 0;
    float: left;
    background-color: #3379b7;
    overflow: visible !important;
}
.testimonial_block2 .percentage {
 display: flex;
 position: absolute;
    padding: 5px;
    top: 6px;

    align-items: center;
    justify-content: center;
    border-radius: 5px;
    background: rgba(0,0,0,0.5);
    color: #ffffff;
}

.testimonial_block2 .users {
    flex-basis: 15%;
    align-self: center;
    font-size: 18px;
    color: #777777;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="testimonial_block2">

     <!-- progress bar -->

     <div class="iva_progress_bar">
      <div class="bar_title">5 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="0">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">4 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="100">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">3 REVIEWS</div>
      <div class="bar_wrap">
       <span  class="bar_color" data-width="3">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">2 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="6">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>

     <div class="iva_progress_bar">
      <div class="bar_title">1 REVIEWS</div>
      <div class="bar_wrap">
       <span class="bar_color" data-width="11">
        <div class="percentage"></div>
       </span>
      </div>
      <div class="users"></div>
     </div>
        </div>