问:
.net Core 3 identity 'AccessFailedCount' not incrementing
I'm having a problem with a asp.net Core 3 identity project. I have created custom UserStore and RoleStore to use Dapper instead of Entity Framework. Most appears to be working, except upon a failed login attempt, the AccessFailedCount in the database is not being incremented. I have stepped through the code, and located where the logic is failing. It is in the SignInManager method named CheckPasswordSignInAsync, in this block:

```<code>if (UserManager.SupportsUserLockout && lockoutOnFailure)
{
    // If lockout is requested, increment access failed count which might lock out the user
    await UserManager.AccessFailedAsync(user);
    if (await UserManager.IsLockedOutAsync(user))
    {
        return await LockedOut(user);
    }
}
</code>```

The value for UserManager.SupportsUserLockout is false, so it never hits the AccessFailedAsync method. But I'm not sure where this value comes from. The code block from UserManager.SupportsUserLockout in UserManager is:

```<code>public virtual bool SupportsUserLockout
{
  get
  {
    this.ThrowIfDisposed();
    return this.Store is IUserLockoutStore<TUser>;
  }
}
</code>```

But I can't figure out what here sets it to false? Where does this value come from?

答:
I think I got your problem, you haven't implemented IUserLockoutStore<TUser> interface. As you are not using the Entity framework so you need to implement all necessary stores your self. Below are the functions which you need to implement.

```<code>Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken);
Task<DateTimeOffset?> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken);
Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken);
Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken);
</code>```

Once you implement IUserLockoutStore<TUser> interface you have to enable Lockout functionality for an individual user, in order to achieve that you just need to set User.LockoutEnabled = 1 (true) in AspNetUsers table.

I hope this will resolve your issue!

Body:
I'm having a problem with a asp.net Core 3 identity project. I have created custom UserStore and RoleStore to use Dapper instead of Entity Framework. Most appears to be working, except upon a failed login attempt, the AccessFailedCount in the database is not being incremented. I have stepped through the code, and located where the logic is failing. It is in the SignInManager method named CheckPasswordSignInAsync, in this block:

if (UserManager.SupportsUserLockout && lockoutOnFailure)
{
    // If lockout is requested, increment access failed count which might lock out the user
    await UserManager.AccessFailedAsync(user);
    if (await UserManager.IsLockedOutAsync(user))
    {
        return await LockedOut(user);
    }
}

The value for UserManager.SupportsUserLockout is false, so it never hits the AccessFailedAsync method. But I'm not sure where this value comes from. The code block from UserManager.SupportsUserLockout in UserManager is:

public virtual bool SupportsUserLockout
{
  get
  {
    this.ThrowIfDisposed();
    return this.Store is IUserLockoutStore<TUser>;
  }
}

But I can't figure out what here sets it to false? Where does this value come from?

Body:
I think I got your problem, you haven't implemented IUserLockoutStore<TUser> interface. As you are not using the Entity framework so you need to implement all necessary stores your self. Below are the functions which you need to implement.

Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken);
Task<DateTimeOffset?> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken);
Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken);
Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken);
Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken);

Once you implement IUserLockoutStore<TUser> interface you have to enable Lockout functionality for an individual user, in order to achieve that you just need to set User.LockoutEnabled = 1 (true) in AspNetUsers table.

I hope this will resolve your issue!


来源: stackexchange

问:
UIDocumentPickerViewController doesn't show any contents on Mac Catalyst
UIDocumentPickerViewController works on iOS but not on Mac Catalyst. Is there any alternatives to workaround this issue? BTW, NSOpenPanel is unavailable on Mac Catalyst.

答:
After many attempts, I managed to find the code below that works well with Xcode 11.3.1 on Mac Catalyst.

```<code>import SwiftUI

    final class DocumentPicker: NSObject, UIViewControllerRepresentable, ObservableObject {
        typealias UIViewControllerType = UIDocumentPickerViewController
        @Published var urlsPicked = [URL]()

        lazy var viewController:UIDocumentPickerViewController = {
            // For picked only folder
            let vc = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open)
            // For picked every document
    //        let vc = UIDocumentPickerViewController(documentTypes: ["public.data"], in: .open)
            // For picked only images
    //        let vc = UIDocumentPickerViewController(documentTypes: ["public.image"], in: .open)
            vc.allowsMultipleSelection = false
    //        vc.accessibilityElements = [kFolderActionCode]
    //        vc.shouldShowFileExtensions = true
            vc.delegate = self
            return vc
        }()

        func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
            viewController.delegate = self
            return viewController
        }

        func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) {
        }
    }

    extension DocumentPicker: UIDocumentPickerDelegate {
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            urlsPicked = urls
            print("DocumentPicker geoFolder.geoFolderPath: \(urlsPicked[0].path)")
        }

    //    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    //        controller.dismiss(animated: true) {
    //        }
    //    }
    }
</code>```

and I use the code above, for example with:

```<code>import SwiftUI

    struct ContentView: View {
        @ObservedObject var picker = DocumentPicker()
        @State private var urlPick = ""

        var body: some View {
                HStack {
                    urlPickedFoRTextField()
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    Spacer()
                    Button(action: {
                        #if targetEnvironment(macCatalyst)
                        let viewController = UIApplication.shared.windows[0].rootViewController!
                        viewController.present(self.picker.viewController, animated: true)
                        self.picker.objectWillChange.send()
                        #endif
                        print("Hai premuto il pulsante per determinare il path della GeoFolder")
                    }) {
                        Image(systemName: "square.and.arrow.up")
                    }
                }
                .padding()
        }

        private func urlPickedFoRTextField() -> some View {
            if picker.urlsPicked.count > 0 {
                DispatchQueue.main.async {
                    self.urlPick = self.picker.urlsPicked[0].path
                }
            }
            return TextField("", text: $urlPick)
        }
    }
</code>```

I hope I was helpful.

ContentLicense: CC BY-SA 4.0

Body:
After many attempts, I managed to find the code below that works well with Xcode 11.3.1 on Mac Catalyst.

import SwiftUI

    final class DocumentPicker: NSObject, UIViewControllerRepresentable, ObservableObject {
        typealias UIViewControllerType = UIDocumentPickerViewController
        @Published var urlsPicked = [URL]()

        lazy var viewController:UIDocumentPickerViewController = {
            // For picked only folder
            let vc = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open)
            // For picked every document
    //        let vc = UIDocumentPickerViewController(documentTypes: ["public.data"], in: .open)
            // For picked only images
    //        let vc = UIDocumentPickerViewController(documentTypes: ["public.image"], in: .open)
            vc.allowsMultipleSelection = false
    //        vc.accessibilityElements = [kFolderActionCode]
    //        vc.shouldShowFileExtensions = true
            vc.delegate = self
            return vc
        }()

        func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
            viewController.delegate = self
            return viewController
        }

        func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: UIViewControllerRepresentableContext<DocumentPicker>) {
        }
    }

    extension DocumentPicker: UIDocumentPickerDelegate {
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            urlsPicked = urls
            print("DocumentPicker geoFolder.geoFolderPath: \(urlsPicked[0].path)")
        }

    //    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    //        controller.dismiss(animated: true) {
    //        }
    //    }
    }

and I use the code above, for example with:

import SwiftUI

    struct ContentView: View {
        @ObservedObject var picker = DocumentPicker()
        @State private var urlPick = ""

        var body: some View {
                HStack {
                    urlPickedFoRTextField()
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    Spacer()
                    Button(action: {
                        #if targetEnvironment(macCatalyst)
                        let viewController = UIApplication.shared.windows[0].rootViewController!
                        viewController.present(self.picker.viewController, animated: true)
                        self.picker.objectWillChange.send()
                        #endif
                        print("Hai premuto il pulsante per determinare il path della GeoFolder")
                    }) {
                        Image(systemName: "square.and.arrow.up")
                    }
                }
                .padding()
        }

        private func urlPickedFoRTextField() -> some View {
            if picker.urlsPicked.count > 0 {
                DispatchQueue.main.async {
                    self.urlPick = self.picker.urlsPicked[0].path
                }
            }
            return TextField("", text: $urlPick)
        }
    }

I hope I was helpful.


问:
Stop Excel from automatically converting certain text values to dates
Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?

I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date.  I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.

答:
Working off of Jarod's solution and the issue brought up by Jeffiekins, you could modify

```<code>"May 16, 2011"
</code>```

to

```<code>"=""May 16, 2011"""
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Working off of Jarod's solution and the issue brought up by Jeffiekins, you could modify

"May 16, 2011"

to

"=""May 16, 2011"""


问:
How to select positive square root expression in SymPy solve?
I'm calculating an expression for a variable (p2) in terms of other variables (q1,q2,p1) by solving an expression (hamiltonian=energy). The solve method returns two solutions (positive and negative) corresponding to the same square root. Below is the sample code:

```<code>state_symbols = ['q1', 'q2','p1','p2']
sympy_symbols = sp.symbols([tuple(state_symbols)])

hamiltonian = "(q1**2+q2**2+p1**2+p2**2)/(2)+ (q1**2*q2 - (q2**3)/(3))"
sys_fn = sp.sympify(sys_hamiltonian, evaluate=False)

sym_energy = sp.Symbol('energy')

expr_p2 = sp.solve(
            sys_fn - sym_energy, sympy_symbols[0][-1])
</code>```

Now this expr_p2 is a list of two solutions one of which is positive square root. How do I assert that the one I pick is always a positive square?

答:
The simplest sure way is to write a,b=expr_p2; Piecewise((a, Gt(a, b)), (b, True)). When symbols are involved SymPy should be canonical but the canonical answer may not place the positive answer 2nd:

```<code>>>> solve(a*x**2+b*x+c,x)
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
>>> solve(-a*x**2+b*x+c,x)
[(b - sqrt(4*a*c + b**2))/(2*a), (b + sqrt(4*a*c + b**2))/(2*a)]
</code>```

In the former, the greater root is first if a is positive while in the latter it is second if a is positive.

Body:
I'm calculating an expression for a variable (p2) in terms of other variables (q1,q2,p1) by solving an expression (hamiltonian=energy). The solve method returns two solutions (positive and negative) corresponding to the same square root. Below is the sample code:

state_symbols = ['q1', 'q2','p1','p2']
sympy_symbols = sp.symbols([tuple(state_symbols)])

hamiltonian = "(q1**2+q2**2+p1**2+p2**2)/(2)+ (q1**2*q2 - (q2**3)/(3))"
sys_fn = sp.sympify(sys_hamiltonian, evaluate=False)

sym_energy = sp.Symbol('energy')

expr_p2 = sp.solve(
            sys_fn - sym_energy, sympy_symbols[0][-1])

Now this expr_p2 is a list of two solutions one of which is positive square root. How do I assert that the one I pick is always a positive square?

Body:
The simplest sure way is to write a,b=expr_p2; Piecewise((a, Gt(a, b)), (b, True)). When symbols are involved SymPy should be canonical but the canonical answer may not place the positive answer 2nd:

>>> solve(a*x**2+b*x+c,x)
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
>>> solve(-a*x**2+b*x+c,x)
[(b - sqrt(4*a*c + b**2))/(2*a), (b + sqrt(4*a*c + b**2))/(2*a)]

In the former, the greater root is first if a is positive while in the latter it is second if a is positive.


问:
R function that makes several changes to multiple columns
Whenever I run a query on the data warehouse or receive data from colleagues I get data in the following format:

```<code>df <- structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c("100,1", "101,1",
"102,2", "103,3"), Revenue = c("100,1", "101,1", "102,2", "103,3"
)), row.names = c(NA, -4L), class = "data.frame")
</code>```

The first thing I must do is to replace "," with "." and the convert to numeric. So far I've done it like this:

```<code>df$Sales <- gsub(",", ".", df$Sales)
df$Sales <- as.numeric(df$Sales)
</code>```

This gets tiresome when there are multiple columns to convert and they have different names from case to case. So, after doing this for the nth time on the nth dataset I decided to write my first R function from scratch.
My initial attempt did this in two steps, and it worked!

```<code># Columns to convert
columns_names <- c("Revenue", "Sales")

# Function to convert "," to "."
convert_to_dot <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
  }
  df
}

# Function to convert to numeric
convert_to_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}
df <- convert_to_dot(df, columns_names)
df <- convert_to_numeric(df, columns_names)

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(100.1, 101.1, 102.2,
103.3), Revenue = c(100.1, 101.1, 102.2, 103.3)), row.names = c(NA,
-4L), class = "data.frame")
</code>```

However, when I try to combine them into one function nothing works. I have tried several versions of the following but they all tend to yield similar results where either the values in the columns are replaced with NAs or the whole data frame turns into a NULL value.

```<code># Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(NA_real_, NA_real_,
NA_real_, NA_real_), Revenue = c(NA_real_, NA_real_, NA_real_,
NA_real_)), row.names = c(NA, -4L), class = "data.frame")
</code>```

I'm guessing that for loops aren't the most efficient way of doing this, but can anyone give me a hint to how to do this?
Thanks in advance!

答:
You need to replace x[[i]] to df[[i]] as you already changed the comma with dot gsub using gsub. so your function should be:

Using OP approach(correcting the function):

```<code># Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
    for (i in column){
        df[[i]] <- gsub(",", ".", x[[i]])
        df[[i]] <- as.numeric(as.character(df[[i]]))
    }
    df
}

convert_dot_numeric(df,c('Sales', 'Revenue') )
</code>```

Using lapply:

You can use lapply to do it also like below:

```<code>df[,c('Sales', 'Revenue')] <- lapply(df[,c('Sales', 'Revenue')], function(x)as.numeric(gsub(',', '.', x)))
</code>```

lapply would iterate to all the necessary columns which you provide as input, then  gsub can replace the commas to dot iteratively. You can totally avoid for loop here (if you need to).

Ouput:

```<code>#  Year Company Sales Revenue
#1 1990       A 100.1   100.1
#2 1991       B 101.1   101.1
#3 1992       C 102.2   102.2
#4 1993       D 103.3   103.3
</code>```

I hope this helps

Body:
Whenever I run a query on the data warehouse or receive data from colleagues I get data in the following format:

df <- structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c("100,1", "101,1",
"102,2", "103,3"), Revenue = c("100,1", "101,1", "102,2", "103,3"
)), row.names = c(NA, -4L), class = "data.frame")

The first thing I must do is to replace "," with "." and the convert to numeric. So far I've done it like this:

df$Sales <- gsub(",", ".", df$Sales)
df$Sales <- as.numeric(df$Sales)

This gets tiresome when there are multiple columns to convert and they have different names from case to case. So, after doing this for the nth time on the nth dataset I decided to write my first R function from scratch.
My initial attempt did this in two steps, and it worked!

# Columns to convert
columns_names <- c("Revenue", "Sales")

# Function to convert "," to "."
convert_to_dot <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
  }
  df
}

# Function to convert to numeric
convert_to_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}
df <- convert_to_dot(df, columns_names)
df <- convert_to_numeric(df, columns_names)

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(100.1, 101.1, 102.2,
103.3), Revenue = c(100.1, 101.1, 102.2, 103.3)), row.names = c(NA,
-4L), class = "data.frame")

However, when I try to combine them into one function nothing works. I have tried several versions of the following but they all tend to yield similar results where either the values in the columns are replaced with NAs or the whole data frame turns into a NULL value.

# Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
  for (i in column){
    df[[i]] <- gsub(",", ".", x[[i]])
    df[[i]] <- as.numeric(as.character(x[[i]]))
  }
  df
}

structure(list(Year = c(1990, 1991, 1992, 1993), Company = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), Sales = c(NA_real_, NA_real_,
NA_real_, NA_real_), Revenue = c(NA_real_, NA_real_, NA_real_,
NA_real_)), row.names = c(NA, -4L), class = "data.frame")

I'm guessing that for loops aren't the most efficient way of doing this, but can anyone give me a hint to how to do this?
Thanks in advance!

Body:
You need to replace x[[i]] to df[[i]] as you already changed the comma with dot gsub using gsub. so your function should be:

Using OP approach(correcting the function):

# Function to replace "," with "." and convert to numeric
convert_dot_numeric <- function(x, column){
    for (i in column){
        df[[i]] <- gsub(",", ".", x[[i]])
        df[[i]] <- as.numeric(as.character(df[[i]]))
    }
    df
}

convert_dot_numeric(df,c('Sales', 'Revenue') )

Using lapply:

You can use lapply to do it also like below:

df[,c('Sales', 'Revenue')] <- lapply(df[,c('Sales', 'Revenue')], function(x)as.numeric(gsub(',', '.', x)))

lapply would iterate to all the necessary columns which you provide as input, then  gsub can replace the commas to dot iteratively. You can totally avoid for loop here (if you need to).

Ouput:

#  Year Company Sales Revenue
#1 1990       A 100.1   100.1
#2 1991       B 101.1   101.1
#3 1992       C 102.2   102.2
#4 1993       D 103.3   103.3

I hope this helps


问:
ORACLE SKEWNESS
In Oracle SQL Developer , how do we find the skewness of data in a table ?</p>

答:
Oracle 20c supports SKEWNESS aggregate functions:

New Analytical and Statistical Aggregate Functions

SKEWNESS functions SKEWNESS_POP and SKEWNESS_SAMP are measures of asymmetry in data. When skewness is positive this means data is skewed to right. When skewness is negative this means data is distributed to left.

SKEWNESS_POP

SKEWNESS_POP is an aggregate function that is primarily used to determine symmetry in a given distribution.

Title: ORACLE SKEWNESS


问:
cant access ubuntu localhost which hosts apache openmeeting from internet
I'm new and selflerner. I have configured a apache open meeting in ubuntu 18.04. Ubuntu has been installed as VM guest using windows server 2016. Open meeting is running on ubuntu local host properly. Both guest and host has two separate public IPs, x.x.x.155, x.x.x.157. I can ping those from internet. All the firewalls and virus guards has been disabled. If I try x.x.x.155/localhost, from internet I only get a error. Host and guest can ping each other but host cant access guest localhost. What am I doing wrong. Is there any place or script to configure. Any advice will be highly appreciated

I did not install Apache server. When I start the openmeeting from terminal, it shows tomcat has started. I do not have to edit NAT in router since I have public static ips.

答: Ok. I just found out that it should be done through editing hosts file.</p>


问:
First 4 li element's onClick work but everyone after doesn't - in FF 3.6 and Chrome
Sorry for the confusing title, but that's about the best I can describe it... So I have a TD element and when it's double clicked a jquery ajax function returns a ul from a PHP script.

New code (sorry for so much of it):

Here is the jQuery Ajax code:

```<code>    //Create PU:
    $('#DD_'+IDNum).append('<div class="popUp" id="PU_'+IDNum+'"></div>');

    //ajax:
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = '<img class="loading" id="LG_'+IDNum+'" src="../images/loading.gif" />';
    if(key==0)
        var term = '';
    else
        var term = $('#TC_'+IDNum).val();
    //load() functions
    var loadUrl = "./ddGet.php?Ele="+element+"&Client="+ClientID+"&vendorName="+vendorName+"&id="+IDNum+"&term="+term;
    $('#PU_'+IDNum+'').html(ajax_load).load(loadUrl);
</code>```

Here is a snippet of the PHP:

```<code>$result = mysql_query($query) or die(mysql_error());
$response= '<ul id="DD_UL">';
$resultArray = array();
$class = "li-odd";
$i = 1;
while($row = mysql_fetch_array($result))
{
    if(!in_array($row[0], $resultArray)){
    $resultArray[]=$row[0];
    if(isset($row[1]))
        $roW1 = ' - '.$row[1];
    else
        $roW1 = '';
    $response .= "\n".'<li id="LI_'.$id.'_'.$i.'" class="'.$class.'">'.$row[0].$roW1.'</li>';
    //selectLI(\'LI_'.$id.'_'.$i.'\')
    if($class == "li-odd")
        $class = "li-even";
    else
        $class = "li-odd";
    $i++;
    }
}
$response .= '</ul>';
echo $response;
</code>```

Here is the response text:

```<code><ul id="DD_UL">
<li id="LI_1_1_1" class="li-odd">E02_02</li>
<li id="LI_1_1_2" class="li-even">E02_03</li>
<li id="LI_1_1_3" class="li-odd">E02_04</li>
<li id="LI_1_1_4" class="li-even">E02_05</li>
<li id="LI_1_1_5" class="li-odd">E02_06</li>
<li id="LI_1_1_6" class="li-even">E02_07</li>
<li id="LI_1_1_7" class="li-odd">E02_08</li>
<li id="LI_1_1_8" class="li-even">E02_09</li>
<li id="LI_1_1_9" class="li-odd">E02_10</li>
<li id="LI_1_1_10" class="li-even">E02_11</li>
<li id="LI_1_1_11" class="li-odd">E02_13</li>
<li id="LI_1_1_12" class="li-even">E02_14</li>
<li id="LI_1_1_13" class="li-odd">E02_20</li>
</ul>
</code>```

And finally the new function that is called after the UL is displayed that assigns the .live:

```<code>function selectLI(){
        $('#DD_UL').live('click',function(e){
        var id = e.target
        id = $(id).attr('id');
        var IDNum = id.substr(3);
        IDNum = IDNum.substring(0,IDNum.lastIndexOf("_"));
        var newVal = $('#'+id).html();
        if(newVal.indexOf(" - ")>0)
            newVal = newVal.substring(0, newVal.indexOf(" - "));
        $('#TC_'+IDNum).val(newVal);
        });
    }
</code>```

Not so simple anymore, huh?  Well first I noticed that in Chrome the onclick would only work if it was like one of the first 4 li's or so clicked.  After the first four (or so) nothing would happen.  I then noticed that FF 3.6 was doing the same thing.  I check IE (although the page is not meant to be run in IE) and it worked.  Finally FF 4 works fine as well.

I say "or so" because sometimes it's the first 4,5,6,7...  Sometimes there appears to be a pattern but I can't figure it out.  I would post more code, however there is a lot of it and I don't see the point since the issue is basically occurring with the above response text.

I have no idea what to do next.

答:
Hm.. I don't seem to be able to replicate your problem (though I don't have Firefox 3.6 to test it in).

Can you test it here on JSFiddle:
http://jsfiddle.net/rQYFW/

I've gotten it to work fine in Firefox 4, Chrome 11, IE 9.

Body:
Sorry for the confusing title, but that's about the best I can describe it... So I have a TD element and when it's double clicked a jquery ajax function returns a ul from a PHP script.

New code (sorry for so much of it):

Here is the jQuery Ajax code:

    //Create PU:
    $('#DD_'+IDNum).append('

');

    //ajax:
    $.ajaxSetup ({
        cache: false
    });
    var ajax_load = '';
    if(key==0)
        var term = '';
    else
        var term = $('#TC_'+IDNum).val();
    //load() functions
    var loadUrl = "./ddGet.php?Ele="+element+"&Client="+ClientID+"&vendorName="+vendorName+"&id="+IDNum+"&term="+term;
    $('#PU_'+IDNum+'').html(ajax_load).load(loadUrl);

Here is a snippet of the PHP:

$result = mysql_query($query) or die(mysql_error());
$response= '
';
$resultArray = array();
$class = "li-odd";
$i = 1;
while($row = mysql_fetch_array($result))
{
    if(!in_array($row[0], $resultArray)){
    $resultArray[]=$row[0];
    if(isset($row[1]))
        $roW1 = ' - '.$row[1];
    else
        $roW1 = '';
    $response .= "\n".'
'.$row[0].$roW1.'
';
    //selectLI(\'LI_'.$id.'_'.$i.'\')
    if($class == "li-odd")
        $class = "li-even";
    else
        $class = "li-odd";
    $i++;
    }
}
$response .= '
';
echo $response;

Here is the response text:

E02_02

E02_03

E02_04

E02_05

E02_06

E02_07

E02_08

E02_09

E02_10

E02_11

E02_13

E02_14

E02_20

And finally the new function that is called after the UL is displayed that assigns the .live:

function selectLI(){
        $('#DD_UL').live('click',function(e){
        var id = e.target
        id = $(id).attr('id');
        var IDNum = id.substr(3);
        IDNum = IDNum.substring(0,IDNum.lastIndexOf("_"));
        var newVal = $('#'+id).html();
        if(newVal.indexOf(" - ")>0)
            newVal = newVal.substring(0, newVal.indexOf(" - "));
        $('#TC_'+IDNum).val(newVal);
        });
    }

Not so simple anymore, huh?  Well first I noticed that in Chrome the onclick would only work if it was like one of the first 4 li's or so clicked.  After the first four (or so) nothing would happen.  I then noticed that FF 3.6 was doing the same thing.  I check IE (although the page is not meant to be run in IE) and it worked.  Finally FF 4 works fine as well.

I say "or so" because sometimes it's the first 4,5,6,7...  Sometimes there appears to be a pattern but I can't figure it out.  I would post more code, however there is a lot of it and I don't see the point since the issue is basically occurring with the above response text.

I have no idea what to do next.


问:
I get an implementation of a PopUp using an interface. Is there a way I could hard code in some parameters?
I have code that calls a dependency service to get access to a PopUp implementation in iOS and Android. It does it this way:

```<code>DependencyService.Get<IPopUp>().Popup("XYZ", "ABC",
            (Color)Application.Current.Resources["PopUpTitleColor"],
            (Color)Application.Current.Resources["PopUpMessageColor"],
            (Color)Application.Current.Resources["PopUpBackgroundColor"],
            (Color)Application.Current.Resources["PopUpSeparatorColor"],
            (sen, args) => {
                DidShowFirstMessage = true;
            });

public interface IPopUp
{
    void Popup(string title,
        string message,
        Color titleColor,
        Color messageColor,
        Color popUpBackgroundColor,
        Color popUpSeparatorColor,
        EventHandler handler);
}

[assembly: Dependency(typeof(PopupImplemention))]
namespace Japanese.iOS.CustomRenderers
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title,
            string message,
            Color titleColor,
            Color messageColor,
            Color popUpBackgroundColor,
            Color popUpSeparatorColor,
            EventHandler handler)
        {
</code>```

Every time the PopUp is called it uses the same Color parameters. Is there a way without changing the PopupImplemention that I could call Popup like this:

```<code>DependencyService.Get<IPopUp>().Popup("XYZ", "ABC", (sen, args) => {
            DidShowFirstMessage = true;
});
</code>```

As it's an interface I don't think I can hard code parameters so wondering how I could do this.

答:
You can create an extension method:

public static void Popup(this IPopUp popup, string title, string message, EventHandler handler)
{
    popup.Popup(
        title,
        message,
        (Color)Application.Current.Resources["PopUpTitleColor"],
        (Color)Application.Current.Resources["PopUpMessageColor"],
        (Color)Application.Current.Resources["PopUpBackgroundColor"],
        (Color)Application.Current.Resources["PopUpSeparatorColor"],
        handler
    );
}
```

Body:
I have code that calls a dependency service to get access to a PopUp implementation in iOS and Android. It does it this way:

DependencyService.Get<IPopUp>().Popup("XYZ", "ABC",
            (Color)Application.Current.Resources["PopUpTitleColor"],
            (Color)Application.Current.Resources["PopUpMessageColor"],
            (Color)Application.Current.Resources["PopUpBackgroundColor"],
            (Color)Application.Current.Resources["PopUpSeparatorColor"],
            (sen, args) => {
                DidShowFirstMessage = true;
            });

public interface IPopUp
{
    void Popup(string title,
        string message,
        Color titleColor,
        Color messageColor,
        Color popUpBackgroundColor,
        Color popUpSeparatorColor,
        EventHandler handler);
}

[assembly: Dependency(typeof(PopupImplemention))]
namespace Japanese.iOS.CustomRenderers
{
    public class PopupImplemention : IPopUp
    {
        public void Popup(string title,
            string message,
            Color titleColor,
            Color messageColor,
            Color popUpBackgroundColor,
            Color popUpSeparatorColor,
            EventHandler handler)
        {

Every time the PopUp is called it uses the same Color parameters. Is there a way without changing the PopupImplemention that I could call Popup like this:

DependencyService.Get<IPopUp>().Popup("XYZ", "ABC", (sen, args) => {
            DidShowFirstMessage = true;
});

As it's an interface I don't think I can hard code parameters so wondering how I could do this.


问:
1. Why do we need to override the method public boolean equals(Object ob) in any class?

Why do we need to override the method public boolean equals(Object ob) in any class?

Is public boolean equals(Object ob) is same as public boolean equals(Circle ob)?

答:
You don't have to.

No, it is not.

Body:
You don't have to.

No, it is not.


问:
Displaying array elements in a TextView
****I am very new to Java and android studio and am trying to  display an individual element of my array into my textView wordTextView with every click of a button. When I click the button on the emulator nothing is being displayed. I have also tried to use a for loop yet I cannot seem to get that to work either. Any help would be greatly appreciated****

```<code>public class MainActivity extends AppCompatActivity {

    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
    }

    public void getNextWord(String string) {
        String [] array = {"Noun", "Adjective", "Proper Noun", "Name"};
        TextView wordTextView = findViewById(R.id.wordTextView);
        wordTextView.setText(array[i]);
    }
}
</code>```

Here is the .xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="nextWord"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/wordTextView"
        android:layout_width="155dp"
        android:layout_height="153dp"
        android:layout_marginTop="84dp"
        android:gravity="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/enterEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="280dp"
        android:ems="10"
        android:hint="Something"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/wordTextView" />

    <Button
        android:id="@+id/nextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:onClick="nextWord"
        android:text="Next"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/enterEditText"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Call your getNextWord() method in nextWord()

```<code>public void nextWord(View view) { //nextWord is the onclick of the button
    i = i++;
getNextWord();
}
</code>```

And remove parameter from getNextWord().

Title: Displaying array elements in a TextView

Body:
****I am very new to Java and android studio and am trying to  display an individual element of my array into my textView wordTextView with every click of a button. When I click the button on the emulator nothing is being displayed. I have also tried to use a for loop yet I cannot seem to get that to work either. Any help would be greatly appreciated****

public class MainActivity extends AppCompatActivity {

    int i = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void nextWord(View view) { //nextWord is the onclick of the button
        i = i++;
    }

    public void getNextWord(String string) {
        String [] array = {"Noun", "Adjective", "Proper Noun", "Name"};
        TextView wordTextView = findViewById(R.id.wordTextView);
        wordTextView.setText(array[i]);
    }
}

Here is the .xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="nextWord"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/wordTextView"
        android:layout_width="155dp"
        android:layout_height="153dp"
        android:layout_marginTop="84dp"
        android:gravity="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/enterEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="280dp"
        android:ems="10"
        android:hint="Something"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/wordTextView" />

    <Button
        android:id="@+id/nextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:onClick="nextWord"
        android:text="Next"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/enterEditText"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Call your getNextWord() method in nextWord()

public void nextWord(View view) { //nextWord is the onclick of the button
    i = i++;
getNextWord();
}

And remove parameter from getNextWord().


问:
How to handle the error 'Page reload detected during async script' using Selenium
How to handle the error  Page reload detected during async script using Selenium and InternetExplorerDriver?

Error stack trace:

```<code>org.openqa.selenium.JavascriptException: Page reload detected during async script
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.edgechromium: false, ie.edgepath: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: http://localhost:24135/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: f8538187-14df-4144-8bd0-605ce398395e
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:506)
    at stepdefinition.Steps.I_selected_the_Client(Steps.java:60)
</code>```

答: issue got resolved by using the CSS locator instead of AsynScript to perform click action on webelement. Thank You</p>

Body:
How to handle the error  Page reload detected during async script using Selenium and InternetExplorerDriver?

Error stack trace:

org.openqa.selenium.JavascriptException: Page reload detected during async script
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_221'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.edgechromium: false, ie.edgepath: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: http://localhost:24135/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: f8538187-14df-4144-8bd0-605ce398395e
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.executeAsyncScript(RemoteWebDriver.java:506)
    at stepdefinition.Steps.I_selected_the_Client(Steps.java:60)


问:
Change Button text in html and angular 2
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

```<code> <div>
                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

</div>
</code>```

答:
in yourComponent.html

```<code><div>
                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                       {{buttonTitle}}
                    </button>

</div>
</code>```

In .ts

Create a new boolean variabile isClickedOnYes and inizialize it to false.

```<code>isClickedOnYes: boolean = false;
titleButton: string = 'YES'
</code>```

When you click on button it became true and title became NO, when you click another time,
it became false and title became YES;

In sayYes()  function  you can implement a logic like this:

```<code>sayYes() {
  if(this.isClickedOnYes == false){
    this.titleButton= 'NO'
    this.isClickedOnYes = true;
  }
  else {
    this.titleButton= 'YES'
    this.isClickedOnYes = false;
 }

 }
</code>```

Body:
I want to change the button text once it is selected, logically it is working fine, initially YES button is highlighting once i click on it sightly change then if i hover disable symbol will show
first image : before click
second image : after click
So what i want is , when i click on yes it should change it to NO and if i hover disable symbol has to show
here is my HTML code

                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                        YES
                    </button>

Body:
in yourComponent.html

<div>
                    <button type="button" class="confirm"
                            [disabled]="(isConfirmed && agree) || (isConfirmed && nutral)"
                            style="color: blue;"
                            (click)="sayYes()">
                       {{buttonTitle}}
                    </button>

</div>

In .ts

Create a new boolean variabile isClickedOnYes and inizialize it to false.

isClickedOnYes: boolean = false;
titleButton: string = 'YES'

When you click on button it became true and title became NO, when you click another time,
it became false and title became YES;

In sayYes()  function  you can implement a logic like this:

sayYes() {
  if(this.isClickedOnYes == false){
    this.titleButton= 'NO'
    this.isClickedOnYes = true;
  }
  else {
    this.titleButton= 'YES'
    this.isClickedOnYes = false;
 }

 }


问:
float output from php function
I have a simple php replace function, that I need to return a "0" (for resale) and a "1" (for newbuilt)

```<code>. function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}
</code>```

In my output I get "1", but not "0". I figured out that I have to convert the zero to a float value to be returned. I tried a few things with the floatval() function, but can not get it to work.

Anyone who can set me in the right direction?

Kind, regards.

答:
Your code works perfectly :

```<code>function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}

$t = 'Hello i am newbuilt and not resale, bye';
var_dump(multi_rep2($t));
// string(27) "Hello i am 1 and not 0, bye"
</code>```

Are you sure "resale" is in your string ?

Title: float output from php function

Body:
I have a simple php replace function, that I need to return a "0" (for resale) and a "1" (for newbuilt)

. function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}

In my output I get "1", but not "0". I figured out that I have to convert the zero to a float value to be returned. I tried a few things with the floatval() function, but can not get it to work.

Anyone who can set me in the right direction?

Kind, regards.

Body:
Your code works perfectly :

function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}

$t = 'Hello i am newbuilt and not resale, bye';
var_dump(multi_rep2($t));
// string(27) "Hello i am 1 and not 0, bye"

Are you sure "resale" is in your string ?


问:
Neo4J: Pods logs Neo4j Invalid Username
Has anyone deployed a Neo4J graph DB or any stateful application to Kubernetes using Helm Charts? I have this task that requires me to deploy a Neo4J graph DB to Kubernetes.

Issue: The Pod keeps on crashing as it cannot get the username provided, and throws the following logs even when the username is provided:
Invalid username, it must be neo4j when you run kubectl logs neo4j-chart-0  command. What am I doing wrong?

```<code>command:
      - "/bin/bash"
      - "-c"
      - |
        export NEO4J_dbms_connectors_default__advertised__address=$(hostname -f)
        export NEO4J_causal__clustering_discovery__advertised__address=$(hostname -f):5000
        export NEO4J_causal__clustering_transaction__advertised__address=$(hostname -f):6000
        export NEO4J_causal__clustering_raft__advertised__address=$(hostname -f):7000

        if [ "${AUTH_ENABLED:-}" == "true" ]; then
          export NEO4J_AUTH=“neo4j/${NEO4J_SECRETS_PASSWORD}”
        else
          export NEO4J_AUTH=“none”
        fi

        exec /docker-entrypoint.sh "neo4j"
</code>```

答:
I found out I had mismatched quotes:

“neo4j/${NEO4J_SECRETS_PASSWORD}”

Which is different from this "neo4j/${NEO4J_SECRETS_PASSWORD".

Title: Neo4J: Pods logs Neo4j Invalid Username

Body:
Has anyone deployed a Neo4J graph DB or any stateful application to Kubernetes using Helm Charts? I have this task that requires me to deploy a Neo4J graph DB to Kubernetes.

Issue: The Pod keeps on crashing as it cannot get the username provided, and throws the following logs even when the username is provided:
Invalid username, it must be neo4j when you run kubectl logs neo4j-chart-0  command. What am I doing wrong?

command:
      - "/bin/bash"
      - "-c"
      - |
        export NEO4J_dbms_connectors_default__advertised__address=$(hostname -f)
        export NEO4J_causal__clustering_discovery__advertised__address=$(hostname -f):5000
        export NEO4J_causal__clustering_transaction__advertised__address=$(hostname -f):6000
        export NEO4J_causal__clustering_raft__advertised__address=$(hostname -f):7000

        if [ "${AUTH_ENABLED:-}" == "true" ]; then
          export NEO4J_AUTH=“neo4j/${NEO4J_SECRETS_PASSWORD}”
        else
          export NEO4J_AUTH=“none”
        fi

        exec /docker-entrypoint.sh "neo4j"


问:
How to make drop down box bring above and in fron to the all content in pure css?
I have created custom drop down like div's. But the problem I am facing is with display the ul.

Code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drop Downn</title>
</head>

<style>

    .content{
        height: 400px;
        width: 100%;
        background-color: aliceblue;
    }
    .combo-box{

        border: 1px solid rgba(0, 0, 0, 0.089);
        background-color: #ffffff;
        width: 200px;
        height: 40px;

        font-size: 18px;

        cursor: pointer;

        align-items: center;
        display: flex;
    }

    .selections{

        background-color: beige;
    }

    ul{

    padding: 0;
    margin: 0;

    background-color: white;

    border: 1px solid rgba(97, 97, 97, 0.164);
    box-shadow: 0 1px 6px -2px #00000036;

    width: 200px;
    max-height: 300px;
    overflow: auto;

    display: none;
  }

  li{

    list-style: none;
    cursor: pointer;
    padding: 0px 14px;
    height: 32px;

    line-height: 34px;

  }

 li:hover{

    background-color: rgb(216, 9, 95);
    color: white;
 }

</style>

<script>

    function display(tag){

        let div = document.getElementsByTagName(tag)[0]
        div.style.display = div.style.display != 'block' ? 'block' : 'none'
    }
</script>
<body>

    <div class="content">
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?</p>
    </div>
    <div class="selections">
        <h4>Select your pet</h4>

    <div class="combo-box" onclick="display('ul')">
        <a>Tiger</a>
    </div>

    <ul>
        <li>Cat</li>
        <li>Dog</li>
        <li>Tiger</li>
        <li>Lion</li>
        <li>Parrot</li>
        <li>Peacock</li>
        <li>Rabbit</li>
        <li>Raino</li>
        <li>Kola</li>
        <li>Sea Lion</li>
        <li>Otter</li>
        <li>Turtle</li>
        <li>Rat</li>
        <li>Cow</li>
        <li>Goat</li>
        <li>Pig</li>
        <li>Fish (Fish food)</li>
        <li>Owl</li>
        <li>Squirrel</li>
    </ul>
    </div>
</body>
</html>
</code>```

From above picture, I want to show ul list over all div's & above the box Tiger and I don't want to expand the div selections. How can I make it work like that? Thank you all.

Update:
  I want to show the drop down above the .combo-box. Please refer below code and screenshot.

```<code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drop Downn</title>
  </head>

  <style>
    .content {
      height: 400px;
      width: 100%;
      background-color: aliceblue;
    }

    .combo-box {
      position: relative;   /* <-- Relative position here */

      border: 1px solid rgba(0, 0, 0, 0.089);
      background-color: #ffffff;
      width: 200px;
      height: 40px;

      font-size: 18px;

      cursor: pointer;

      align-items: center;
      display: flex;
    }

    .selections {
      background-color: beige;
    }

    ul {
      padding: 0;
      margin: 0;
      background-color: white;

      border: 1px solid rgba(97, 97, 97, 0.164);
      box-shadow: 0 1px 6px -2px #00000036;

      width: 200px;
      max-height: 300px;
      overflow: auto;

      display: none;
    }

    li {

      list-style: none;
      cursor: pointer;
      padding: 0px 14px;
      height: 32px;

      line-height: 34px;

    }

    li:hover {

      background-color: rgb(216, 9, 95);
      color: white;
    }

  </style>

  <script>
    function display(tag) {

      let div = document.getElementsByTagName(tag)[0]
      div.style.display = div.style.display != 'block' ? 'block' : 'none'
    }

  </script>

  <body>

    <div class="content">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?</p>
    </div>
    <div class="selections">
      <h4>Select your pet</h4>

      <ul>
        <li>Cat</li>
        <li>Dog</li>
        <li>Tiger</li>
        <li>Lion</li>
        <li>Parrot</li>
        <li>Peacock</li>
        <li>Rabbit</li>
        <li>Raino</li>
        <li>Kola</li>
        <li>Sea Lion</li>
        <li>Otter</li>
        <li>Turtle</li>
        <li>Rat</li>
        <li>Cow</li>
        <li>Goat</li>
        <li>Pig</li>
        <li>Fish (Fish food)</li>
        <li>Owl</li>
        <li>Squirrel</li>
      </ul>

      <div class="combo-box" onclick="display('ul')">
        <a>Tiger</a>
      </div>

    </div>
  </body>

</html>
</code>```

Output I want like below image, but I don't want to expand that div.

答:
By reviewing the structure of your html and using the property position: absolute you can achieve something like this:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drop Downn</title>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?

Select your pet

      Tiger

Cat

Dog

Tiger

Lion

Parrot

Peacock

Rabbit

Raino

Kola

Sea Lion

Otter

Turtle

Rat

Cow

Goat

Pig

Fish (Fish food)

Owl

Squirrel

```

Body:
I have created custom drop down like div's. But the problem I am facing is with display the ul.

Code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drop Downn</title>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?

Select your pet

        Tiger

Cat

Dog

Tiger

Lion

Parrot

Peacock

Rabbit

Raino

Kola

Sea Lion

Otter

Turtle

Rat

Cow

Goat

Pig

Fish (Fish food)

Owl

Squirrel

From above picture, I want to show ul list over all div's & above the box Tiger and I don't want to expand the div selections. How can I make it work like that? Thank you all.

Update:
  I want to show the drop down above the .combo-box. Please refer below code and screenshot.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drop Downn</title>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?

Select your pet

Cat

Dog

Tiger

Lion

Parrot

Peacock

Rabbit

Raino

Kola

Sea Lion

Otter

Turtle

Rat

Cow

Goat

Pig

Fish (Fish food)

Owl

Squirrel

        Tiger

Output I want like below image, but I don't want to expand that div.

Body:
By reviewing the structure of your html and using the property position: absolute you can achieve something like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drop Downn</title>
</head>

<style>
  .content {
    height: 400px;
    width: 100%;
    background-color: aliceblue;
  }

  .combo-box {
    position: relative;
    /* <-- Relative position here */
    border: 1px solid rgba(0, 0, 0, 0.089);
    background-color: #ffffff;
    width: 200px;
    height: 40px;
    font-size: 18px;
    cursor: pointer;
    align-items: center;
    display: flex;
  }

  .selections {
    background-color: beige;
  }

  ul {
    position: absolute;
    /* <-- Absolute position here */
    bottom: 100%;
    /* <-- Fix it to bottom */
    padding: 0;
    margin: 0;
    background-color: white;
    border: 1px solid rgba(97, 97, 97, 0.164);
    box-shadow: 0 1px 6px -2px #00000036;
    width: 200px;
    max-height: 300px;
    overflow: auto;
    display: none;
  }

  li {
    list-style: none;
    cursor: pointer;
    padding: 0px 14px;
    height: 32px;
    line-height: 34px;
  }

  li:hover {
    background-color: rgb(216, 9, 95);
    color: white;
  }
</style>

<script>
  function display(tag) {

    let div = document.getElementsByTagName(tag)[0]
    div.style.display = div.style.display != 'block' ? 'block' : 'none'
  }
</script>

<body>

  <div class="content">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam laudantium possimus nulla officia tempore earum ea perspiciatis quia fugit asperiores laborum ab voluptas, dolore doloremque illo? Saepe, ex? Molestiae, doloremque?</p>
  </div>
  <div class="selections">
    <h4>Select your pet</h4>

    <div class="combo-box" onclick="display('ul')">
      <a>Tiger</a>

      <!-- Move ul in .combo-box -->
      <ul>
        <li>Cat</li>
        <li>Dog</li>
        <li>Tiger</li>
        <li>Lion</li>
        <li>Parrot</li>
        <li>Peacock</li>
        <li>Rabbit</li>
        <li>Raino</li>
        <li>Kola</li>
        <li>Sea Lion</li>
        <li>Otter</li>
        <li>Turtle</li>
        <li>Rat</li>
        <li>Cow</li>
        <li>Goat</li>
        <li>Pig</li>
        <li>Fish (Fish food)</li>
        <li>Owl</li>
        <li>Squirrel</li>
      </ul>
    </div>

  </div>
</body>

</html>


问:
How to know if url is already bookmarked
I am adding bookmark from code. Now in Firefox if user already added the url as bookmark he should not be able to bookmark it again. How can I do it? For now every time a new bookmark is getting created.</p>

答:
Obviously, you cannot, except for the above two good suggestions: use cookies. Or user information (although if they registered, they probably already bookmarked the site!).
Cookie solution is brittle, though, as user can erase them.

Why you cannot: that would be an obvious security breach if a JavaScript program could read the list of bookmarks of the user: beside privacy concerns, one can have some sensible information in the URL parameters...

Side note: adding a bookmark is done on user action (or should be!). So users should know if they added the bookmark already, no?

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: PhiLho


问:
Is there a way in Visual Studio 2010 to have code/project/folder structure mapped from TFS to mutiple machines?
I am currently working on several applications and in n some of these apps the solutions contain projects from multiple work spaces in Visual Studio 2010.

This causes an issue when others attempt to work on the code for a certain application or simply download the code and run the app. I have my work spaces for my computer defined, but others do not.

What I want to do is have a way to set up a work space or sort of work space template where anyone can download the code from the server, while on any machine and with the required folder structure, and the application will run.

For instance, if I had the following server structure:

```<code>$/
  $/SolutionFiles/

  $/SubFolder1/
    $/SubFolder1/ProjectA/
    $/SubFolder1/ProjectB/

  $/SubFolder2/
    $/SubFolder2/Project1/
    $/SubFolder2/Project2/
</code>```

...and I had a solution $/SolutionFiles/MyAppSolution that contains code from $/SubFolder/ProjectA/ and $/SubFolder2/Project1/, I want to have a separate workspace or something, possibly named "MyAppSolution_Workspace" or something like that, that will map the solution folder and the related project folders to a generic path. This would need to work and be accessible from all other separate computers and would need to keep the same directory structure from the server and have the same folder names and everything as is expected by the solution/project files.

From what it looks like Shared work spaces in VS2010 would work, but it seems to only apply to one machine and is not entirely generic.

Are there any suggestions for how to accomplish this?

答:
You probably won't like this answer but here is what we do:

Keep your workspace mapping as simple as possible.  Never move folders or rename folders or files using the workspace mapping.  Then all users need to do is map from the top and everything works.  They may get more files than they want but it will work.

Advanced users can use the folder cloaking ability to block getting folders they aren't interested in or can map just the folders they want. The key being that when they map specific folders instead of the root they leave the paths the same as they would be if the root was mapped.

In our system we then have our version and release branching structure above the folders of your example.  So everything you've listed would be duplicated inside a MAIN folder and inside a Release_1 folder.

Body:
I am currently working on several applications and in n some of these apps the solutions contain projects from multiple work spaces in Visual Studio 2010.

This causes an issue when others attempt to work on the code for a certain application or simply download the code and run the app. I have my work spaces for my computer defined, but others do not.

What I want to do is have a way to set up a work space or sort of work space template where anyone can download the code from the server, while on any machine and with the required folder structure, and the application will run.

For instance, if I had the following server structure:

$/
  $/SolutionFiles/

  $/SubFolder1/
    $/SubFolder1/ProjectA/
    $/SubFolder1/ProjectB/

  $/SubFolder2/
    $/SubFolder2/Project1/
    $/SubFolder2/Project2/

...and I had a solution $/SolutionFiles/MyAppSolution that contains code from $/SubFolder/ProjectA/ and $/SubFolder2/Project1/, I want to have a separate workspace or something, possibly named "MyAppSolution_Workspace" or something like that, that will map the solution folder and the related project folders to a generic path. This would need to work and be accessible from all other separate computers and would need to keep the same directory structure from the server and have the same folder names and everything as is expected by the solution/project files.

From what it looks like Shared work spaces in VS2010 would work, but it seems to only apply to one machine and is not entirely generic.

Are there any suggestions for how to accomplish this?


问:
Respect to image's position, I need to center an image. I'm using react and css
I want to center my image but I don't know how. This is my code.

```<code>        text ={

           fontWeight: 'bold'

         }

        screenColor ={
         background: 'lightblue',
         height: 800,
         weight: 500
       }
        render() {
           return(
               <nav className="nav" style={{
                background: 'lightblue',
                height:800,
                weight:600,
                margin: '20 20 0 10',
                padding: '10 10 0 10'
                 }}  >
              <div className="container" style={this.screenColor}>

              <div style={this.text}>Welcome - Programming 3 2019 </div>

              <br></br>

           <img  src={net} style={{
            justifyContent: 'center',
            alignItems: 'center'}}   //These lines from img tag didn't work except src and alt.
             alt="fireSpot"/>

             </div>;
             </nav>
                 )
                   }
                   }
</code>```

How can I center an image?, I need to solve this. I want to center an image. I'm using react but I need to center the image respect to position.

By other way I want to getting image to lower height.

答:
add ClassName in Div tag. and define class in style.</p>

```<code><div className="imgStyle">
  <img  src={net} style={{
            justifyContent: 'center',

            alignItems: 'center'}}
             alt="fireSpot"/>
</div>

.imgStyle{
Display: flex;
Height: 100vh;
Width: 100vw;
Align-Items: center;
Justify-Content: centre;
}

</code>```

Body:
I want to center my image but I don't know how. This is my code.

        text ={

           fontWeight: 'bold'

         }

        screenColor ={
         background: 'lightblue',
         height: 800,
         weight: 500
       }
        render() {
           return(

Welcome - Programming 3 2019

;

                 )
                   }
                   }

How can I center an image?, I need to solve this. I want to center an image. I'm using react but I need to center the image respect to position.

By other way I want to getting image to lower height.

Body:
add ClassName in Div tag. and define class in style.

<div className="imgStyle">
  <img  src={net} style={{
            justifyContent: 'center',

            alignItems: 'center'}}
             alt="fireSpot"/>
</div>

.imgStyle{
Display: flex;
Height: 100vh;
Width: 100vw;
Align-Items: center;
Justify-Content: centre;
}


问:
How to show large scrollbar in Kivy's RecycleView
I wrote the following code in Kivy in Python.

It is a GUI with only five buttons that can be scrolled.

I am running the following in an Anacond environment.

```<code>#-*- coding: utf-8 -*-

from kivy.lang import Builder
Builder.load_string("""
<TextWidget>:
    BoxLayout:
        size: root.size
        orientation: 'vertical'

        RecycleView:
            size_hint: 1.0,1.0

            BoxLayout:
                orientation: 'vertical'
                size_hint_y: 5

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST1'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST2'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST3'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST4'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST5'
""")

from kivy.app import App
from kivy.uix.widget import Widget

from kivy.properties import StringProperty

class TextWidget(Widget):
    text = StringProperty()

    def __init__(self, **kwargs):
        super(TextWidget, self).__init__(**kwargs)

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.title = 'test'

    def build(self):
        return TextWidget()

if __name__ == '__main__':
    TestApp().run()
</code>```

A scroll bar appears but is too small to touch.

So I have to scroll with the middle mouse wheel button.

Is there a way to display a large scrollbar?

答:
You can use the bar_width attribute:

        RecycleView:
            size_hint: 1.0,1.0
            bar_width: dp(10)
            scroll_type: ["bars", "content"]
```

Body:
I wrote the following code in Kivy in Python.

It is a GUI with only five buttons that can be scrolled.

I am running the following in an Anacond environment.

#-*- coding: utf-8 -*-

from kivy.lang import Builder
Builder.load_string("""
<TextWidget>:
    BoxLayout:
        size: root.size
        orientation: 'vertical'

        RecycleView:
            size_hint: 1.0,1.0

            BoxLayout:
                orientation: 'vertical'
                size_hint_y: 5

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST1'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST2'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST3'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST4'

                Button:
                    halign: 'center'
                    valign: 'center'
                    text: 'TEST5'
""")

from kivy.app import App
from kivy.uix.widget import Widget

from kivy.properties import StringProperty

class TextWidget(Widget):
    text = StringProperty()

    def __init__(self, **kwargs):
        super(TextWidget, self).__init__(**kwargs)

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.title = 'test'

    def build(self):
        return TextWidget()

if __name__ == '__main__':
    TestApp().run()

A scroll bar appears but is too small to touch.

So I have to scroll with the middle mouse wheel button.

Is there a way to display a large scrollbar?


问:
Python List Multiplication
I am currently trying to run the following code

```<code>from PIL import Image

img = Image.open('C:/Users/j.png')

WIDTH, HEIGHT = img.size

imgData = list(img.getdata())  =
imgData = [imgData[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

def function_sum2_x():
    sum2_x = 0
    for i in range(0, HEIGHT - 1):
        for j in range(0, WIDTH - 1):
            sum2_x += imgData[i][j] * imgData[i][j]

    return sum2_x

print(function_sum2_x())
</code>```

Although I am getting the following error:
line 25, in function_sum2_x
    sum2_x += imgData[i][j] * imgData[i][j]
TypeError: can't multiply sequence by non-int of type 'tuple'

The purpose of this code is for a mathematical formula for comparing 2 images.  For context, my image is black and white binary. I originally thought the issue would be due to multiplying the 0 values by eachother in "imgData" but after converting all 0s to 1s I am getting the same issue.

After some research online I found some issues with list multiplication so now I think this may be the issue. I found some sources saying to use the line

```<code>newarr= map(lambda x: i*x, imgData)
</code>```

However I am not sure how to implement this and if it is actually useful to resolving this error

答: I guess you have a colored image, use Image.convert() to convert it to a grayscale image. Even though your image is black and white in your image viewer, it does not mean that it's saved that way internally.

Title: Python List Multiplication

Body:
I am currently trying to run the following code

from PIL import Image

img = Image.open('C:/Users/j.png')

WIDTH, HEIGHT = img.size

imgData = list(img.getdata())  =
imgData = [imgData[offset:offset + WIDTH] for offset in range(0, WIDTH * HEIGHT, WIDTH)]

def function_sum2_x():
    sum2_x = 0
    for i in range(0, HEIGHT - 1):
        for j in range(0, WIDTH - 1):
            sum2_x += imgData[i][j] * imgData[i][j]

    return sum2_x

print(function_sum2_x())

Although I am getting the following error:
line 25, in function_sum2_x
    sum2_x += imgData[i][j] * imgData[i][j]
TypeError: can't multiply sequence by non-int of type 'tuple'

The purpose of this code is for a mathematical formula for comparing 2 images.  For context, my image is black and white binary. I originally thought the issue would be due to multiplying the 0 values by eachother in "imgData" but after converting all 0s to 1s I am getting the same issue.

After some research online I found some issues with list multiplication so now I think this may be the issue. I found some sources saying to use the line

newarr= map(lambda x: i*x, imgData)

However I am not sure how to implement this and if it is actually useful to resolving this error


问:
Not able to load local .xml file through Jquery ajax call
I am making a sample web application on my local machine. I want to make ajax call to an .xml file which is on my local machine.

It is not working in any browsers at all.
When i try to see in the Network tab of Chrome it display that XMLHttpRequest cannot load file:///D:/somefolder/finishers.xml?_=1392713504397. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

May be this is possible duplicate question, but I am new to Jquery.
Below is my code.

```<code>$.ajax({
    url: "finishers.xml",
    cache: false,
    dataType: "xml",
    success: function(xml){}
});
</code>```

Please help me how to resolve this.
Thanks in advance.

答:
This error is a result of a request being made from your client code to a non-existent server. Your first option is to deploy your website to a hosting platform. This is, however, a production activity and would not be necessary to quickly confirm the feature you have implemented.

A quick fix is to run a webserver on your local machine by installing python, navigating to the root of the project directory in terminal and running this command.

```<code>python -m http.server
</code>```

You can then navigate to the appropriate localhost port and enter your web application via the index.html file

Body:
I am making a sample web application on my local machine. I want to make ajax call to an .xml file which is on my local machine.

It is not working in any browsers at all.
When i try to see in the Network tab of Chrome it display that XMLHttpRequest cannot load file:///D:/somefolder/finishers.xml?_=1392713504397. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

May be this is possible duplicate question, but I am new to Jquery.
Below is my code.

$.ajax({
    url: "finishers.xml",
    cache: false,
    dataType: "xml",
    success: function(xml){}
});

Please help me how to resolve this.
Thanks in advance.

Body:
This error is a result of a request being made from your client code to a non-existent server. Your first option is to deploy your website to a hosting platform. This is, however, a production activity and would not be necessary to quickly confirm the feature you have implemented.

A quick fix is to run a webserver on your local machine by installing python, navigating to the root of the project directory in terminal and running this command.

python -m http.server

You can then navigate to the appropriate localhost port and enter your web application via the index.html file


问:
Is signed integer overflow in safe Rust in release mode considered as undefined behavior?
Rust treats signed integer overflow differently in debug and release mode. When it happens, Rust panics in debug mode while silently performs two's complement wrapping in release mode.

As far as I know, C/C++ treats signed integer overflow as undefined behavior partly because:

At that time of C's standardization, different underlying architecture of representing signed integers, such as one's complement, might still be in use somewhere. Compilers cannot make assumptions of how overflow is handled in the hardware.

Later compilers thus making assumptions such as the sum of two positive integers must also be positive to generate optimized machine code.

So if Rust compilers do perform the same kind of optimization as C/C++ compilers regarding signed integers, why does The Rustonomicon states:

No matter what, Safe Rust can't cause Undefined Behavior.

Or even if Rust compilers do not perform such optimization, Rust programmers still do not anticipate seeing a signed integer wrapping around. Can't it be called "undefined behavior"?

答:
Q: So if Rust compilers do perform the same kind of optimization as C/C++ compilers regarding signed integers

Rust does not. Because, as you noticed, it cannot perform these optimizations as integer overflows are well defined.

For an addition in release mode, Rust will emit the following LLVM instruction (you can check on Playground):

add i32 %b, %a
```

<p>On the other hand, clang will emit the following LLVM instruction (you can check via <code>clang -S -emit-llvm add.c</code>):</p>

<pre class="lang-none prettyprint-override"><code>add nsw i32 %6, %8
</code>```

The difference is the nsw (no signed wrap) flag. As specified in the LLVM reference about add:

If the sum has unsigned overflow, the result returned is the mathematical result modulo 2n, where n is the bit width of the result.

Because LLVM integers use a two’s complement representation, this instruction is appropriate for both signed and unsigned integers.

nuw and nsw stand for “No Unsigned Wrap” and “No Signed Wrap”, respectively. If the nuw and/or nsw keywords are present, the result value of the add is a poison value if unsigned and/or signed overflow, respectively, occurs.

The poison value is what leads to undefined behavior. If the flags are not present, the result is well defined as 2's complement wrapping.

Q: Or even if Rust compilers do not perform such optimization, Rust programmers still do not anticipate seeing a signed integer wrapping around. Can't it be called "undefined behavior"?

"Undefined behavior" as used in this context has a very specific meaning that is different from the intuitive English meaning of the two words. UB here specifically means that the compiler can assume an overflow will never happen and that if an overflow will happen, any program behavior is allowed. That's not what Rust specifies.

However, an integer overflow via the arithmetic operators is considered a bug in Rust. That's because, as you said, it is usually not anticipated. If you intentionally want the wrapping behavior, there are methods such as i32::wrapping_add.

Some additional resources:

RFC 560 specifies everything about integer overflows in Rust. In short: panic in debug mode, 2's complement wrap in release mode.

Myths and Legends about Integer Overflow in Rust. Nice blog post about this topic.

Body:
Q: So if Rust compilers do perform the same kind of optimization as C/C++ compilers regarding signed integers

Rust does not. Because, as you noticed, it cannot perform these optimizations as integer overflows are well defined.

For an addition in release mode, Rust will emit the following LLVM instruction (you can check on Playground):

add i32 %b, %a

On the other hand, clang will emit the following LLVM instruction (you can check via clang -S -emit-llvm add.c):

add nsw i32 %6, %8

The difference is the nsw (no signed wrap) flag. As specified in the LLVM reference about add:

If the sum has unsigned overflow, the result returned is the mathematical result modulo 2n, where n is the bit width of the result.

Because LLVM integers use a two’s complement representation, this instruction is appropriate for both signed and unsigned integers.

nuw and nsw stand for “No Unsigned Wrap” and “No Signed Wrap”, respectively. If the nuw and/or nsw keywords are present, the result value of the add is a poison value if unsigned and/or signed overflow, respectively, occurs.

The poison value is what leads to undefined behavior. If the flags are not present, the result is well defined as 2's complement wrapping.

Q: Or even if Rust compilers do not perform such optimization, Rust programmers still do not anticipate seeing a signed integer wrapping around. Can't it be called "undefined behavior"?

"Undefined behavior" as used in this context has a very specific meaning that is different from the intuitive English meaning of the two words. UB here specifically means that the compiler can assume an overflow will never happen and that if an overflow will happen, any program behavior is allowed. That's not what Rust specifies.

However, an integer overflow via the arithmetic operators is considered a bug in Rust. That's because, as you said, it is usually not anticipated. If you intentionally want the wrapping behavior, there are methods such as i32::wrapping_add.

Some additional resources:

RFC 560 specifies everything about integer overflows in Rust. In short: panic in debug mode, 2's complement wrap in release mode.

Myths and Legends about Integer Overflow in Rust. Nice blog post about this topic.


问:
how in python remove all folder inside path
How can I list all folders of a directory in Python and remove them ?

```<code>for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
    print(root)
    print(dirs)
    print(files)
</code>```

i run this code in Centos7 but i just need list folder for delete times

答:
```<code>import os
import shutil

dirs= next(os.walk(r'/home/m110/public_html/ts/'))[1]
for name in dirs:
    print name
    shutil.rmtree(name)
</code>```

Body:
How can I list all folders of a directory in Python and remove them ?

for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
    print(root)
    print(dirs)
    print(files)

i run this code in Centos7 but i just need list folder for delete times


问:
Desired capabilities depreciated, how to get it appium working with Android driver?
I'm currently trying to start a automation project with Appium/Selenium and noticed that DesiredCapabilities are depreciated. Does anyone have a working example of a workaround or new implementation of this?

```<code>using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Remote;

namespace LeaflyAutomation
{
    public class TC1
    {

        public AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL(sc_url), caps);

        public void InitDriver()
        {
            //No longer valid, need new driver setup
            DesiredCapabilities caps = new DesiredCapabilities();

            caps.SetCapability("PlatformName", "Android");
            caps.SetCapability("appPackage"), "myapp file path");
            caps.SetCapability("appActivity", "com.demo.demofolder.activities.MainActivity");

        }
    }
}
</code>```

答:
```<code>DesiredCapabilities are depreciated in latest version , we can use AppiumOptions to pass device detail instead of DesiredCapabilities.

                  AppiumOptions capabilities = new AppiumOptions();
                  capabilities.AddAdditionalCapability("platformName", "Android");
                  capabilities.AddAdditionalCapability("app", "APK_Path");
                  capabilities.AddAdditionalCapability("udid", "Device_ID");
                  capabilities.AddAdditionalCapability("deviceName", "Android");
                  capabilities.AddAdditionalCapability("noReset", false);
                  driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities);
</code>```

Body:
I'm currently trying to start a automation project with Appium/Selenium and noticed that DesiredCapabilities are depreciated. Does anyone have a working example of a workaround or new implementation of this?

using System;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Remote;

namespace LeaflyAutomation
{
    public class TC1
    {

        public AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL(sc_url), caps);

        public void InitDriver()
        {
            //No longer valid, need new driver setup
            DesiredCapabilities caps = new DesiredCapabilities();

            caps.SetCapability("PlatformName", "Android");
            caps.SetCapability("appPackage"), "myapp file path");
            caps.SetCapability("appActivity", "com.demo.demofolder.activities.MainActivity");

        }
    }
}


问:
Pandas: Calculating a Z-score to avoid "look ahead" bias
I have time series data in dataframe named "df", and, my code for calculating the z-score is given below:

```<code>mean = df.mean()
standard_dev = df.std()
z_score = (df - mean) / standard_dev
</code>```

I would like to calculate the z-score for each observation using the respective observation and data that was known at the point of recording the observation. i.e. I do not want to use a standard deviation and mean that incorporates data that occurs after a specific point in time. I just want to use data from time t, t-1, t-2....

How do I do this?

答:
You could assign two new columns, containing the mean and std of previous items. I here assume, that your time series data is in the column 'time_series_data':

```<code>len_ = len(df)
df['mean_past'] = [np.mean(df['time_series_data'][0:lv+1]) for lv in range(len_)]
df['std_past'] = [np.std(df['time_series_data'][0:lv+1]) for lv in range(len_)]
df['z_score'] = (df['time_series_data'] - df['mean_past']) / df['std_past']
</code>```

Edit: if you want to z-score all columns, you could define a function, that computes the z-score and apply it on all columns of your dataframe:

```<code>def z_score_column(column):
    len_ = len(column)
    mean = [np.mean(column[0:lv+1]) for lv in range(0,len_)]
    std =  [np.std(column[0:lv+1]) for lv in range(0,len_)]
    return [(c-m)/s for c,m,s in zip(column, mean, std)]

df = pd.DataFrame(np.random.rand(10,5))
df.apply(z_score_column)
</code>```

Body:
I have time series data in dataframe named "df", and, my code for calculating the z-score is given below:

mean = df.mean()
standard_dev = df.std()
z_score = (df - mean) / standard_dev

I would like to calculate the z-score for each observation using the respective observation and data that was known at the point of recording the observation. i.e. I do not want to use a standard deviation and mean that incorporates data that occurs after a specific point in time. I just want to use data from time t, t-1, t-2....

How do I do this?

Body:
You could assign two new columns, containing the mean and std of previous items. I here assume, that your time series data is in the column 'time_series_data':

len_ = len(df)
df['mean_past'] = [np.mean(df['time_series_data'][0:lv+1]) for lv in range(len_)]
df['std_past'] = [np.std(df['time_series_data'][0:lv+1]) for lv in range(len_)]
df['z_score'] = (df['time_series_data'] - df['mean_past']) / df['std_past']

Edit: if you want to z-score all columns, you could define a function, that computes the z-score and apply it on all columns of your dataframe:

def z_score_column(column):
    len_ = len(column)
    mean = [np.mean(column[0:lv+1]) for lv in range(0,len_)]
    std =  [np.std(column[0:lv+1]) for lv in range(0,len_)]
    return [(c-m)/s for c,m,s in zip(column, mean, std)]

df = pd.DataFrame(np.random.rand(10,5))
df.apply(z_score_column)


问:
Unexpected $end in eval()'d code
I hate to ask such a specific question, but I'm getting an error I can't figure out. This is in a cron job which runs on the hour. I'm creating an array of tasks, each of which has a date check which is supposed to be eval()'d.

```<code>$todo = array();
$todo[] = array( "date('z')%3 == 0", "Task 1" );
$todo[] = array( "date('N') == 1", "Task 2" );
foreach( $todo as $task )
{
    if( eval($task[0]) ) {
        echo $task[1];
    }
}
</code>```

For some reason the eval() line is giving me this error. Note that I am getting this error for both tasks.

```<code>Parse error: syntax error, unexpected $end in /file.php(21) : eval()'d code on line 1
</code>```

Any suggestions? I tried searching for this but couldn't find anything. Thank you.

答:
You are missing ';' on end of string evaluation. Eval function able to process statements or expressions.

Example:

```<code>$value = 7;
eval("\$value+=2;");
echo $value;
</code>```

Title: Unexpected $end in eval()'d code

Body:
I hate to ask such a specific question, but I'm getting an error I can't figure out. This is in a cron job which runs on the hour. I'm creating an array of tasks, each of which has a date check which is supposed to be eval()'d.

$todo = array();
$todo[] = array( "date('z')%3 == 0", "Task 1" );
$todo[] = array( "date('N') == 1", "Task 2" );
foreach( $todo as $task )
{
    if( eval($task[0]) ) {
        echo $task[1];
    }
}

For some reason the eval() line is giving me this error. Note that I am getting this error for both tasks.

Parse error: syntax error, unexpected $end in /file.php(21) : eval()'d code on line 1

Any suggestions? I tried searching for this but couldn't find anything. Thank you.

Body:
You are missing ';' on end of string evaluation. Eval function able to process statements or expressions.

Example:

$value = 7;
eval("\$value+=2;");
echo $value;


问:
implementing captcha in ipad
I am new to iPhone development.
 how is captcha in iphone implemented.
Please tell me if anyone can shed some light on this.

Any help is appreciated.

Thanks in advance

答:
You really need captcha on iPhone when your client app have ability of registering new users on you server. Someone may crack your app and stole the registration protocol.

But I found the solution. Just use APN :

Client-app generates APN_id and sends it to server.

Server pushes notification with random string to client thru APN.

Client sends this string to server and server now may accept registrations from client.

Title: implementing captcha in ipad


答:
I'm confused to why you need to convert the zero to a float?
I tried this out in a PHP sandbox and it seems to work fine.

```<code>$oldVar = 'newbuilt and resale';
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array(1, 0);
    $rep = str_replace($searchVal2, $replaceVal2, $oldVar);
    echo $rep;
</code>```

This echoes "1 and 0" instead of "newbuilt and resale".

Title: float output from php function

Body:
I have a simple php replace function, that I need to return a "0" (for resale) and a "1" (for newbuilt)

. function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}

In my output I get "1", but not "0". I figured out that I have to convert the zero to a float value to be returned. I tried a few things with the floatval() function, but can not get it to work.

Anyone who can set me in the right direction?

Kind, regards.

Body:
I'm confused to why you need to convert the zero to a float?
I tried this out in a PHP sandbox and it seems to work fine.

$oldVar = 'newbuilt and resale';
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array(1, 0);
    $rep = str_replace($searchVal2, $replaceVal2, $oldVar);
    echo $rep;

This echoes "1 and 0" instead of "newbuilt and resale".