问:
Python beautifulsoup to remove all tags/content with specific tag and text following
I am using beautifulsoup in python and want to remove everything from a string that are enclosed in a certain tag and have a specific non-closing tag with specific text following it. In this example, I want to remove all the documents that have type tag inside it with text of DOCA.

Let's say I have something like this:

```<code><body>
    <document>
        <type>DOCA
            <sequence>1
            <filename>DOCA.htm
            <description>FORM DOCA
            <text>
                <title>Form DOCA</title>
                <h5 align="left"><a href="#toc">Table of Contents</a></h5>
    </document>
    <document>
        <type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
            <title>Form DOCB</title>
            <h5 align="left"><a href="#toc">Table of Contents</a></h5>
    </document>
<body>
</code>```

What I want to do is remove all <document> that have a <type> of DOCA. I have tried the following but it doesn't work:

```<code>>>print(soup.find('document').find('type', text = re.compile('DOCA.*')))
None
</code>```

答:
You can use a lambda in the find method to select an element, eg:

```<code>soup.find('document').find(lambda tag : tag.name == 'type' and 'DOCA' in tag.text)
</code>```

Then you can use extract or decompose to remove that element.

Edit:  use this expression to select all elements:

```<code>soup.find_all(lambda tag:tag.name == 'document'
    and tag.find(lambda t:t.name == 'type' and 'DOCA' in t.text))
</code>```

Body:
I am using beautifulsoup in python and want to remove everything from a string that are enclosed in a certain tag and have a specific non-closing tag with specific text following it. In this example, I want to remove all the documents that have type tag inside it with text of DOCA.

Let's say I have something like this:

    <document>
        <type>DOCA
            <sequence>1
            <filename>DOCA.htm
            <description>FORM DOCA
            <text>
                <title>Form DOCA</title>

Table of Contents

    </document>
    <document>
        <type>DOCB
        <sequence>1
        <filename>DOCB.htm
        <description>FORM DOCB
        <text>
            <title>Form DOCB</title>

Table of Contents

    </document>

What I want to do is remove all <document> that have a <type> of DOCA. I have tried the following but it doesn't work:

>>print(soup.find('document').find('type', text = re.compile('DOCA.*')))
None

Body:
You can use a lambda in the find method to select an element, eg:

soup.find('document').find(lambda tag : tag.name == 'type' and 'DOCA' in tag.text)

Then you can use extract or decompose to remove that element.

Edit:  use this expression to select all elements:

soup.find_all(lambda tag:tag.name == 'document'
    and tag.find(lambda t:t.name == 'type' and 'DOCA' in t.text))


来源: stackexchange

问:
I want to be able to print stack traces java style in c
Simple question, I want to be able to print stack traces java style in c. I have the signal handlers set up and I get the stack trace addresses but I want to translate the addresses to the function names. Therefore, I decided to implement reflection. Right now I have tables as follows: {"FOO", &FOO, "BAR", &BAR}. While this solution works for all platforms, it is really annoying to keep up to date. Is there another way to do this (one that wouldnt require manual upkeep?)</p>

答: You could use the conventions in GObject Introspection: http://live.gnome.org/GObjectIntrospection</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
MySQL group by get data from latest entry
I have a SQL table with AT&T wireless users ranging over a couple of months. I'm trying to see who has used the most data over those months, but some of the User Names on the Wireless Number accounts have changed, as well as their data plan. Here's the query I'm trying to run:

```<code>select Wireless_Number, User_Name, sum(Total_KB_Data_Usage / 1048576) as Total_GB_Usage, avg(Total_KB_Data_Usage / 1048576) as AVG_GB_Usage, Data_Pooling_Rate_Plan_Code
from att
group by Wireless_Number
order by Total_GB_Usage desc
limit 20;
</code>```

Here's a preview of what I get back (some data omitted for privacy)

```<code>| Wireless_Number | User_Name        | Total_GB_Usage | AVG_GB_Usage | Data_Pooling_Rate_Plan_Code |
|-----------------|------------------|----------------|--------------|-----------------------------|
| XXXXXX3330      | XXXX CRADLEPOINT | 1452.6883      | 181.58603750 | B
| XXXXXX4638      | XXXX CLARK       | 392.4903       | 49.06128750  | B
| XXXXXX1819      | XXXX RAMSEY      | 346.8210       | 43.35262500  | B
| XXXXXX0847      | XXXX WYNIA       | 265.9175       | 33.23968750  | B
</code>```

The problem is that 'Ramsey' is no longer the holder of that account, now it's 'Welch'

```<code>select monthname(Month) as Month, Wireless_Number, User_Name
from att
where Wireless_Number like 'XXXXXX1819';
</code>```

:

```<code>| Month    | Wireless_Number | User_Name   |
|----------|-----------------|-------------|
| October  | XXXXXX1819      | XXXX RAMSEY |
| November | XXXXXX1819      | XXXX WELCH  |
| December | XXXXXX1819      | XXXX WELCH  |
| January  | XXXXXX1819      | XXXX WELCH  |
| February | XXXXXX1819      | XXXX WELCH  |
</code>```

1819 is just one of the numbers that has changed so far. I want to select the last row in my initial query which used a group by, but I need to still query all of the months in order to get accurate sums and averages. How to I go about doing this?

Edit:
The Wireless_Number does not change, only the User_Name and Data_Pooling_Rate_Plan_Code may have.

```<code>| monthname(Month) | Wireless_Number | User_Name         | Data_Pooling_Rate_Plan_Code |
|------------------|-----------------|-------------------|-----------------------------|
| October          | XXXXXX3330      | XXXX CRADLEPOINT  | B
| November         | XXXXXX3330      | TEMP LTE INTERNET | BDP10GBO
| December         | XXXXXX3330      | TEMP LTE INTERNET | None
</code>```

Here's on that changes Plans, which is persistent from March on.

```<code>| Month    | Wireless_Number | User_Name  |  Data_Pooling_Rate_Plan_Code
|----------|-----------------|------------|---------------------|
| January  | XXXXXX1819      | XXXX WELCH | BDPIPJ5GB           |
| February | XXXXXX1819      | XXXX WELCH | Multiple Rate Plans |
| March    | XXXXXX1819      | XXXX WELCH | MBSL5GWTO           |
</code>```

I'm not going to disagree that that data is bad, but I feel like this is something I should be able to do.

Edit 2:
My primary key is the Wireless_Number.
Here's what I'd like to see from an ideal query:

```<code>| Wireless_Number | User_Name         | Total_GB_Usage | AVG_GB_Usage | Data_Pooling_Rate_Plan_Code |
|-----------------|-------------------|----------------|--------------|-----------------------------|
| XXXXXX3330      | TEMP LTE INTERNET | 1452.6883      | 181.5860375  | NONE
| XXXXXX4638      | XXXX CLARK        | 392.4903       | 49.0612875   | MBSL5GWTO                   |
| XXXXXX1819      | XXXX WELCH        | 346.821        | 43.352625    | MBSL5GWTO                   |
</code>```

答:
One solution is to simply extend your group by clause to include the User_Name. If you have line a that is shared between two users, that will produce a record for each of them.

```<code>select
  Wireless_Number
  , User_Name
  , Data_Pooling_Rate_Plan_Code
  , sum(Total_KB_Data_Usage / 1048576) as Total_GB_Usage
  , avg(Total_KB_Data_Usage / 1048576) as AVG_GB_Usage
from
  att
group by
  Wireless_Number
  , User_Name
  , Data_Pooling_Rate_Plan_Code
order by
  Total_GB_Usage desc
limit 20;
</code>```

You may want to introduce some additional logic to only select people who only currently have that number.

Body:
I have a SQL table with AT&T wireless users ranging over a couple of months. I'm trying to see who has used the most data over those months, but some of the User Names on the Wireless Number accounts have changed, as well as their data plan. Here's the query I'm trying to run:

select Wireless_Number, User_Name, sum(Total_KB_Data_Usage / 1048576) as Total_GB_Usage, avg(Total_KB_Data_Usage / 1048576) as AVG_GB_Usage, Data_Pooling_Rate_Plan_Code
from att
group by Wireless_Number
order by Total_GB_Usage desc
limit 20;

Here's a preview of what I get back (some data omitted for privacy)

| Wireless_Number | User_Name        | Total_GB_Usage | AVG_GB_Usage | Data_Pooling_Rate_Plan_Code |
|-----------------|------------------|----------------|--------------|-----------------------------|
| XXXXXX3330      | XXXX CRADLEPOINT | 1452.6883      | 181.58603750 | B
| XXXXXX4638      | XXXX CLARK       | 392.4903       | 49.06128750  | B
| XXXXXX1819      | XXXX RAMSEY      | 346.8210       | 43.35262500  | B
| XXXXXX0847      | XXXX WYNIA       | 265.9175       | 33.23968750  | B

The problem is that 'Ramsey' is no longer the holder of that account, now it's 'Welch'

select monthname(Month) as Month, Wireless_Number, User_Name
from att
where Wireless_Number like 'XXXXXX1819';

:

| Month    | Wireless_Number | User_Name   |
|----------|-----------------|-------------|
| October  | XXXXXX1819      | XXXX RAMSEY |
| November | XXXXXX1819      | XXXX WELCH  |
| December | XXXXXX1819      | XXXX WELCH  |
| January  | XXXXXX1819      | XXXX WELCH  |
| February | XXXXXX1819      | XXXX WELCH  |

1819 is just one of the numbers that has changed so far. I want to select the last row in my initial query which used a group by, but I need to still query all of the months in order to get accurate sums and averages. How to I go about doing this?

Edit:
The Wireless_Number does not change, only the User_Name and Data_Pooling_Rate_Plan_Code may have.

| monthname(Month) | Wireless_Number | User_Name         | Data_Pooling_Rate_Plan_Code |
|------------------|-----------------|-------------------|-----------------------------|
| October          | XXXXXX3330      | XXXX CRADLEPOINT  | B
| November         | XXXXXX3330      | TEMP LTE INTERNET | BDP10GBO
| December         | XXXXXX3330      | TEMP LTE INTERNET | None

Here's on that changes Plans, which is persistent from March on.

| Month    | Wireless_Number | User_Name  |  Data_Pooling_Rate_Plan_Code
|----------|-----------------|------------|---------------------|
| January  | XXXXXX1819      | XXXX WELCH | BDPIPJ5GB           |
| February | XXXXXX1819      | XXXX WELCH | Multiple Rate Plans |
| March    | XXXXXX1819      | XXXX WELCH | MBSL5GWTO           |

I'm not going to disagree that that data is bad, but I feel like this is something I should be able to do.

Edit 2:
My primary key is the Wireless_Number.
Here's what I'd like to see from an ideal query:

| Wireless_Number | User_Name         | Total_GB_Usage | AVG_GB_Usage | Data_Pooling_Rate_Plan_Code |
|-----------------|-------------------|----------------|--------------|-----------------------------|
| XXXXXX3330      | TEMP LTE INTERNET | 1452.6883      | 181.5860375  | NONE
| XXXXXX4638      | XXXX CLARK        | 392.4903       | 49.0612875   | MBSL5GWTO                   |
| XXXXXX1819      | XXXX WELCH        | 346.821        | 43.352625    | MBSL5GWTO                   |

Body:
One solution is to simply extend your group by clause to include the User_Name. If you have line a that is shared between two users, that will produce a record for each of them.

select
  Wireless_Number
  , User_Name
  , Data_Pooling_Rate_Plan_Code
  , sum(Total_KB_Data_Usage / 1048576) as Total_GB_Usage
  , avg(Total_KB_Data_Usage / 1048576) as AVG_GB_Usage
from
  att
group by
  Wireless_Number
  , User_Name
  , Data_Pooling_Rate_Plan_Code
order by
  Total_GB_Usage desc
limit 20;

You may want to introduce some additional logic to only select people who only currently have that number.


问:
Android Studio - No USB devices detected
I tried to play Android Studio 2.0 with my mobile without success, what I did are:

In my mobile, Apps/gear icon/Settings/SYSTEM/{} Developer options/ Android debugging/, enable the Android Debug Bridge(adb) interface (set tick).

After plug in my mobile to my PC with a USB cable, I found A0001 in my Computer folder. Within A0001, I can see the files in my mobile.

In my PC, run Android Studio/bin/studio.exe, "Select Deployment Target" window shows with message "No USB devices or running emulators detected"

I have tried two different USB drivers but got no lucky.

Perhaps I should tell Android Studio where is my USB driver? But, how?
Can you help?

答:
Finally found the solution : )</p>

```<code> 1. Install device’s required driver. (for me it was motorola device
    manager)
 2. Download Google Usb Driver from SDK Manager
 3. Open your phone's setting->developer options and turn on USB debugging.
 4. connect your device to computer
 5. Go to Device Manager from Start Menu and try to find if there is ADB Interface with an error symbol on it.
 5.1. If yes, then right click on the ADB interface->Update driver
    software->Browse my computer for driver software-> Let me pick from
    a list of device drivers on my computer->Select Motorola ADB interface
 5.2. Now one confirmation will pop up in your mobile, accept it
 5.3. Now you should see no error mark beside the ADB interface in your
    device manager
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Finally found the solution : )

 1. Install device’s required driver. (for me it was motorola device
    manager)
 2. Download Google Usb Driver from SDK Manager
 3. Open your phone's setting->developer options and turn on USB debugging.
 4. connect your device to computer
 5. Go to Device Manager from Start Menu and try to find if there is ADB Interface with an error symbol on it.
 5.1. If yes, then right click on the ADB interface->Update driver
    software->Browse my computer for driver software-> Let me pick from
    a list of device drivers on my computer->Select Motorola ADB interface
 5.2. Now one confirmation will pop up in your mobile, accept it
 5.3. Now you should see no error mark beside the ADB interface in your
    device manager


问:
Analyze methods count of an android library
I recently in my project get 65536 error message about dex size and blahblah.<br>
and now I'm trying to reduce my dex size but I don't know exactly wich of my  libraries is adding more size to dex file I just can see hole dex file size in apk analyzer is there a tool or way to analyze dex file and getting information about how many methods this library has and how much adding to my dex file?    </p>

答:
You should use this gradle plugin

https://github.com/KeepSafe/dexcount-gradle-plugin

It's the best to find the number of methods of your app in total or per library

Body:
I recently in my project get 65536 error message about dex size and blahblah.

and now I'm trying to reduce my dex size but I don't know exactly wich of my  libraries is adding more size to dex file I just can see hole dex file size in apk analyzer is there a tool or way to analyze dex file and getting information about how many methods this library has and how much adding to my dex file?


问:
R Text Mining - Converting Term Document Matrix
I created a list of bigrams using:

```<code>BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))
tdm_a.bigram = TermDocumentMatrix(docs_a,
                                control = list(tokenize = BigramTokenizer))
</code>```

I am trying to get a count of documents each bigram is appearing in. If I understand correctly Term Document Matrix will give how many times each bigram occurs within a document. But I just need
'1'-present in a document and
'0'-not there.

How do I convert Term Document Matrix into dataframe or matrix to be able to get such count?

答:
A TDM is a simple_triplet_matrix from the slam package. Which has some fucntions for common operations line row/colSums.

slam::row_sums(tdm_a.bigram>=1)

This should tell you how many documents contained each bigram.

Body:
I created a list of bigrams using:

BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))
tdm_a.bigram = TermDocumentMatrix(docs_a,
                                control = list(tokenize = BigramTokenizer))

I am trying to get a count of documents each bigram is appearing in. If I understand correctly Term Document Matrix will give how many times each bigram occurs within a document. But I just need
'1'-present in a document and
'0'-not there.

How do I convert Term Document Matrix into dataframe or matrix to be able to get such count?


问:
How to run/view the existing project powered by KeystoneJS on the browser?
I need to upgrade a website and the website is powered by KeystoneJS. I've given a folder of the website containing all the folders (models, node_modules, public, ...) and the problem is how do I run/view the existing project on the browser? Help me please... :(</p>

答:
You should have a keystone.js or maybe index.js as the entry point. Look in this file.

Inside you should find the keystone init call. Change the host and port properties in it by respectively 'localhost' and 80.

```<code>keystone.init({
    // Bunch of other options
    host: 'localhost',
    port: 80,
});
</code>```

Then run node yourentrypoint.js.

Now the website should be accessible in your browser on default HTTP.

It's assuming that you are running this on local and that no other program uses the port 80.

If you are on a web server, then replace 'localhost' by the IP of the server, as a string.

If another program already uses port 80, change it, but note that if you want the website to be available as default HTTP, you should either cancel this other program, or use a reverse proxy such as ngix.

Body:
You should have a keystone.js or maybe index.js as the entry point. Look in this file.

Inside you should find the keystone init call. Change the host and port properties in it by respectively 'localhost' and 80.

keystone.init({
    // Bunch of other options
    host: 'localhost',
    port: 80,
});

Then run node yourentrypoint.js.

Now the website should be accessible in your browser on default HTTP.

It's assuming that you are running this on local and that no other program uses the port 80.

If you are on a web server, then replace 'localhost' by the IP of the server, as a string.

If another program already uses port 80, change it, but note that if you want the website to be available as default HTTP, you should either cancel this other program, or use a reverse proxy such as ngix.


问:
Reverse Dependency Service
I have a Xamarin Forms Project. I have used Dependency Service to call the Platform specific method to fire a local notification on Android and a Alert on iOS.

My problem is now, how to handle an action on both notification(android) and alert(iOS). Is it possible to call a method of the shared project from the android or iOS project?

Do I need another approach? Does someone know what I have to do?

Just for clarification, I know how the ordinary dependency services works i.e. Call a method on android or iOS from the shared project!

答:
I believe I had a similar scenario on my app. If you want to push something from your platform methods to your PCL you would need to make use of call backs and event delegates.

In Interface PCL:

```<code>    event OnMessageHandlerCallback OnMessageEvent;
    event OnErrorHandlerCallBack OnErrorEvent;
</code>```

In Platform specific Class inheriting interface:

```<code> private OnMessageHandlerCallback callback = null;
    private OnErrorHandlerCallBack errorCallBack = null;

    public event OnMessageHandlerCallback OnMessageEvent;

    public event OnErrorHandlerCallBack OnErrorEvent;
</code>```

Title: Reverse Dependency Service

Body:
I believe I had a similar scenario on my app. If you want to push something from your platform methods to your PCL you would need to make use of call backs and event delegates.

In Interface PCL:

    event OnMessageHandlerCallback OnMessageEvent;
    event OnErrorHandlerCallBack OnErrorEvent;

In Platform specific Class inheriting interface:

 private OnMessageHandlerCallback callback = null;
    private OnErrorHandlerCallBack errorCallBack = null;

    public event OnMessageHandlerCallback OnMessageEvent;

    public event OnErrorHandlerCallBack OnErrorEvent;


问:
SonarQube WS API call on ceTaskUrl not returning anything
I am using curl to GET from the url. I am trying to fail a build if the quality gate does not pass, but I don't get anything back. I am on mac and in terminal I try "curl ceTaskUrl" (can't put real url) and see no response. Any ideas?  </p>

答: It turned out that I was not supplying the login information for the website. The command needs to be structured like this curl -u username:password URL.</p>


问:
Update only edited/changed fields
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

```<code>$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");
</code>```

Appreciate the help here.....

答:
Here is a suggestion:

```<code>$res= mysqli_query("SELECT * from table where id ='$id'");
</code>```

Fetch the result to array.
After selecting that data you need to compare them with your POST data
if your db fetched data and your posted data is not same then you will set new value.

```<code>if($_POST['name'] == $res['name']){
    $name = $res['name'];
}
else{
$name = $_POST['name'];
}
</code>```

Title: Update only edited/changed fields

Body:
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");

Appreciate the help here.....

Body:
Here is a suggestion:

$res= mysqli_query("SELECT * from table where id ='$id'");

Fetch the result to array.
After selecting that data you need to compare them with your POST data
if your db fetched data and your posted data is not same then you will set new value.

if($_POST['name'] == $res['name']){
    $name = $res['name'];
}
else{
$name = $_POST['name'];
}


问:
Newtonsoft.JSON v9.01 + FileNotFoundException (.NET Core Class library)
(VS2015 Update 3 + Patch)

I have a plain .NET console application (.NET 4.6) and reference a .NET core class library that targets NetStandard v1.3.
The class library has a reference to Newtonsoft.JSON.

```<code>{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Newtonsoft.Json": "9.0.1"
  },
  "buildOptions": { "platform": "anycpu" },

  "frameworks": {
    "netstandard1.3": {
      "imports": "dnxcore50"
    }
  }
}
</code>```

The referenced NewtonSoft.JSON package is deployed here:

C:\Users\UserAccount\.nuget\packages\Newtonsoft.Json\9.0.1

The Exception:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in DotNetConsoleApplication.exe

Additional information: Could not load file or assembly
  'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral,
  PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
  system cannot find the file specified.

I guess the .net core lib would reference the dll from the netstandard1.0 folder.

答:
As a workaround solution, In visual studio 2017, you can modify the the NetStandard project .csproj as multi-target:

```<code>           <TargetFrameworks>netstandard1.3;net461</TargetFrameworks>
</code>```

Rebuild the solution and the referenced dll (NewtonSoft.JSON) will be  copied to bin folder of the console project.

Have a look to my implementation in :Workaround Solution

Body:
(VS2015 Update 3 + Patch)

I have a plain .NET console application (.NET 4.6) and reference a .NET core class library that targets NetStandard v1.3.
The class library has a reference to Newtonsoft.JSON.

{
  "version": "1.0.0-*",

  "dependencies": {
    "NETStandard.Library": "1.6.0",
    "Newtonsoft.Json": "9.0.1"
  },
  "buildOptions": { "platform": "anycpu" },

  "frameworks": {
    "netstandard1.3": {
      "imports": "dnxcore50"
    }
  }
}

The referenced NewtonSoft.JSON package is deployed here:

C:\Users\UserAccount\.nuget\packages\Newtonsoft.Json\9.0.1

The Exception:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in DotNetConsoleApplication.exe

Additional information: Could not load file or assembly
  'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral,
  PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The
  system cannot find the file specified.

I guess the .net core lib would reference the dll from the netstandard1.0 folder.

Body:
As a workaround solution, In visual studio 2017, you can modify the the NetStandard project .csproj as multi-target:

           <TargetFrameworks>netstandard1.3;net461</TargetFrameworks>

Rebuild the solution and the referenced dll (NewtonSoft.JSON) will be  copied to bin folder of the console project.

Have a look to my implementation in :Workaround Solution


问:
AbstractMethodError when running standalone jar built with SBT and ProGuard
I've written a simple Scala application that I'd like to distribute in the form of a standalone, executable jar to servers without the Scala runtime.  Everything works fine when invoked through SBT run, but not java -jar.

When I run the jar through java, I get the following unhandled exception:

```<code>Exception in thread "main" java.lang.AbstractMethodError: java.util.logging.Handler.publish(Ljava/util/logging/LogRecord;)V
    at java.util.logging.Logger.log(Logger.java:458)
    at net.lag.logging.Logger.log(Logger.scala:108)
    at net.lag.logging.Logger.log(Logger.scala:91)
    at net.lag.logging.Logger.info(Logger.scala:121)
    at com.rentawebgeek.sitewiki.SiteWiki$.main(SiteWiki.scala:29)
    at com.rentawebgeek.sitewiki.SiteWiki.main(SiteWiki.scala)
Exception in thread "Thread-0" java.lang.AbstractMethodError: java.util.logging.Handler.close()V
    at java.util.logging.LogManager.resetLogger(LogManager.java:682)
    at java.util.logging.LogManager.reset(LogManager.java:665)
    at java.util.logging.LogManager$Cleaner.run(LogManager.java:223)
</code>```

I'm using Configgy and it's Logger, and, per the javadocs for AbstractMethodError, thought it might be related to Scala/SBT using a different Java version than what I'm invoking from my shell.  However, java -version and $JAVA_HOME/bin/java -version (what /usr/local/bin/scala uses) both match up as 1.6.0_22.

My ProGuard options are:

```<code>//program entry point
override def mainClass: Option[String] = Some("com.rentawebgeek.sitewiki.SiteWiki")

//proguard
override def proguardOptions = List(
    "-keepclasseswithmembers public class * { public static void main(java.lang.String[]); }",
    "-dontoptimize",
    "-dontobfuscate",
    "-keep class *",
    proguardKeepLimitedSerializability,
    proguardKeepAllScala,
    "-keep interface scala.ScalaObject"
)

override def proguardInJars = Path.fromFile(scalaLibraryJar) +++ super.proguardInJars
</code>```

How can I resolve this error?  Or find another way to build an executable jar from an SBT project for a Scala-less deployment?

答:
Check out what call you are making at line 29 in SiteWiki.scala; that is the offending call. You're probably calling a trait/class there with an abstract method. Most probably the method that should implement the abstract method is ripped away by proguard (or there the Scala override doesn't match up (I've seen that happen)).

If the line is long to find the offending call; try to decompose over multiple lines.

Body:
I've written a simple Scala application that I'd like to distribute in the form of a standalone, executable jar to servers without the Scala runtime.  Everything works fine when invoked through SBT run, but not java -jar.

When I run the jar through java, I get the following unhandled exception:

Exception in thread "main" java.lang.AbstractMethodError: java.util.logging.Handler.publish(Ljava/util/logging/LogRecord;)V
    at java.util.logging.Logger.log(Logger.java:458)
    at net.lag.logging.Logger.log(Logger.scala:108)
    at net.lag.logging.Logger.log(Logger.scala:91)
    at net.lag.logging.Logger.info(Logger.scala:121)
    at com.rentawebgeek.sitewiki.SiteWiki$.main(SiteWiki.scala:29)
    at com.rentawebgeek.sitewiki.SiteWiki.main(SiteWiki.scala)
Exception in thread "Thread-0" java.lang.AbstractMethodError: java.util.logging.Handler.close()V
    at java.util.logging.LogManager.resetLogger(LogManager.java:682)
    at java.util.logging.LogManager.reset(LogManager.java:665)
    at java.util.logging.LogManager$Cleaner.run(LogManager.java:223)

I'm using Configgy and it's Logger, and, per the javadocs for AbstractMethodError, thought it might be related to Scala/SBT using a different Java version than what I'm invoking from my shell.  However, java -version and $JAVA_HOME/bin/java -version (what /usr/local/bin/scala uses) both match up as 1.6.0_22.

My ProGuard options are:

//program entry point
override def mainClass: Option[String] = Some("com.rentawebgeek.sitewiki.SiteWiki")

//proguard
override def proguardOptions = List(
    "-keepclasseswithmembers public class * { public static void main(java.lang.String[]); }",
    "-dontoptimize",
    "-dontobfuscate",
    "-keep class *",
    proguardKeepLimitedSerializability,
    proguardKeepAllScala,
    "-keep interface scala.ScalaObject"
)

override def proguardInJars = Path.fromFile(scalaLibraryJar) +++ super.proguardInJars

How can I resolve this error?  Or find another way to build an executable jar from an SBT project for a Scala-less deployment?


问:
Apache rewrite rules for running a Symfony application in a sub-directory when rewrite rules already exist for legacy application
Version Information: Apache v2.4.18 on Ubuntu, PHP version 7.1,Symfony v3.2

I've been trying to get this working for a couple of days now and keep hitting problems, I have an existing PHP application using a custom built framework with the following Apache VirtualHost configuration:

```<code><VirtualHost *:80>
    ServerName dvlp.mydomain.com
    DocumentRoot /var/www/my-site/com

    RewriteEngine   On

    # Do nothing for the Home page ('^/$'), specific directories, static files.
    RewriteRule ^/(?:$|shared|asset)|\.(?:php|ico|txt|xml) - [L]

    # Search engine friendly request URIs (most, but not all, without a query string).
    RewriteRule ^/([a-z0-9-]+/?)$                 /index.php?param1=$1 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$  /index.php?param1=$1&param2=$2 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]

    <Directory />
            Options FollowSymLinks
            AllowOverride None
            ErrorDocument 404 /404.php
    </Directory>
</VirtualHost>
</code>```

What I am trying to do is install a Symfony application to work within a sub-directory. I've created my Symfony application in /var/www/symfony-app and created a symbolic link /var/www/my-site/com/my-symfony which points to /var/www/symfony-app/web.

I then tried the following on line 6 of my VirtualHost file:

```<code>RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]
</code>```

Visiting dvlp.mydomain.com/my-symfony in the browser takes me to the directory listings for the /var/www/symfony-app/web folder. I tried adding an index.php file to /var/www/symfony-app/web which simply includes app_dev.php and it loaded the home page, but I I tried visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the 404 error page from my existing application.

I realised now that I need separate rewrite rules for this sub-directory, for Symfony this is usually written as the following:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]
</code>```

So I undid the change I made to line 6 of the VirtualHost file and added a new line as follows:

```<code>RewriteRule ^/my-symfony(.*)$ /my-symfony/index.php [L,QSA]
</code>```

This results in a 404 error:

```<code>No route found for "GET /my-symfony/" (from "http://dvlp.mydomain.com/")
</code>```

And if I try visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the same 404 error:

```<code>No route found for "GET /my-symfony/edit-personal-details" (from "http://dvlp.mydomain.com/")
</code>```

The last thing I have tried is adding a prefix to my Symfony routing.yml:

```<code>my_symfony:
    resource: "@MySymfonyBundle/Controller/"
    type:     annotation
    prefix:   /my-symfony
</code>```

This then loads the pages correctly but with no images or stylesheets because they are trying to load from the DocumentRoot (e.g dvlp.mydomain.com/css instead of dvlp.mydomain.com/my-symfony/css).

I would appreciate any input as to where I am going wrong. Thanks.

答:
I finally managed to get this working as intended by adding a "Location" tag containing specific RewriteRules and a RewriteBase for the Symbolic link. For information, final VirtualHost config below:</p>

```<code><VirtualHost *:80>
    ServerName dvlp.my-domain.com
    DocumentRoot /var/www/my-site/com

    RewriteEngine On

    <Location /my-symfony>
        RewriteBase /my-symfony
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ app_dev.php [QSA,L]
    </Location>

    # Do nothing for the Home page ('^/$'), specific directories, static files.
    RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]

    # Search engine friendly request URIs (most, but not all, without a query string).
    RewriteRule ^/([a-z0-9-]+/?)$                 /index.php?param1=$1 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$  /index.php?param1=$1&param2=$2 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]

    <Directory />
        Options FollowSymLinks
        AllowOverride None
        ErrorDocument 404 /404.php
    </Directory>
</VirtualHost>
</code>```

Body:
Version Information: Apache v2.4.18 on Ubuntu, PHP version 7.1,Symfony v3.2

I've been trying to get this working for a couple of days now and keep hitting problems, I have an existing PHP application using a custom built framework with the following Apache VirtualHost configuration:

<VirtualHost *:80>
    ServerName dvlp.mydomain.com
    DocumentRoot /var/www/my-site/com

    RewriteEngine   On

    # Do nothing for the Home page ('^/$'), specific directories, static files.
    RewriteRule ^/(?:$|shared|asset)|\.(?:php|ico|txt|xml) - [L]

    # Search engine friendly request URIs (most, but not all, without a query string).
    RewriteRule ^/([a-z0-9-]+/?)$                 /index.php?param1=$1 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$  /index.php?param1=$1&param2=$2 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]

    <Directory />
            Options FollowSymLinks
            AllowOverride None
            ErrorDocument 404 /404.php
    </Directory>
</VirtualHost>

What I am trying to do is install a Symfony application to work within a sub-directory. I've created my Symfony application in /var/www/symfony-app and created a symbolic link /var/www/my-site/com/my-symfony which points to /var/www/symfony-app/web.

I then tried the following on line 6 of my VirtualHost file:

RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]

Visiting dvlp.mydomain.com/my-symfony in the browser takes me to the directory listings for the /var/www/symfony-app/web folder. I tried adding an index.php file to /var/www/symfony-app/web which simply includes app_dev.php and it loaded the home page, but I I tried visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the 404 error page from my existing application.

I realised now that I need separate rewrite rules for this sub-directory, for Symfony this is usually written as the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ app.php [QSA,L]

So I undid the change I made to line 6 of the VirtualHost file and added a new line as follows:

RewriteRule ^/my-symfony(.*)$ /my-symfony/index.php [L,QSA]

This results in a 404 error:

No route found for "GET /my-symfony/" (from "http://dvlp.mydomain.com/")

And if I try visiting dvlp.mydomain.com/my-symfony/edit-personal-details I get the same 404 error:

No route found for "GET /my-symfony/edit-personal-details" (from "http://dvlp.mydomain.com/")

The last thing I have tried is adding a prefix to my Symfony routing.yml:

my_symfony:
    resource: "@MySymfonyBundle/Controller/"
    type:     annotation
    prefix:   /my-symfony

This then loads the pages correctly but with no images or stylesheets because they are trying to load from the DocumentRoot (e.g dvlp.mydomain.com/css instead of dvlp.mydomain.com/my-symfony/css).

I would appreciate any input as to where I am going wrong. Thanks.

Body:
I finally managed to get this working as intended by adding a "Location" tag containing specific RewriteRules and a RewriteBase for the Symbolic link. For information, final VirtualHost config below:

<VirtualHost *:80>
    ServerName dvlp.my-domain.com
    DocumentRoot /var/www/my-site/com

    RewriteEngine On

    <Location /my-symfony>
        RewriteBase /my-symfony
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^(.*)$ app_dev.php [QSA,L]
    </Location>

    # Do nothing for the Home page ('^/$'), specific directories, static files.
    RewriteRule ^/(?:$|my-symfony|shared|asset)|\.(?:php|ico|txt|xml) - [L]

    # Search engine friendly request URIs (most, but not all, without a query string).
    RewriteRule ^/([a-z0-9-]+/?)$                 /index.php?param1=$1 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-\.]+/?)$  /index.php?param1=$1&param2=$2 [L,QSA]
    RewriteRule ^/([a-z0-9-]+)/([a-z0-9-]+)/(.+)$ /index.php?param1=$1&param2=$2&param3=$3 [QSA]

    <Directory />
        Options FollowSymLinks
        AllowOverride None
        ErrorDocument 404 /404.php
    </Directory>
</VirtualHost>


问:
What does a code np.mean(array_1 == array_2) do?
What does the following code do?

```<code>import numpy as np
np.mean(array_1 == array_2)
</code>```

Here array_1 and array_2 are same shaped arrays of type int.

答:
This gives the average similarity between the two arrays, that is the number of elements that were identical divided by the length of the arrays.

Note that if the arrays are different lengths, the == will evaluate to False and the returned mean will be 0.0

```<code>>>> import numpy as np
>>> array_1 = np.arange(4)
>>> array_2 = np.arange(4) % 3
>>> array_1
array([0, 1, 2, 3])
>>> array_2
array([0, 1, 2, 0])
>>> np.mean(array_1 == array_2)
0.75
</code>```

Body:
What does the following code do?

import numpy as np
np.mean(array_1 == array_2)

Here array_1 and array_2 are same shaped arrays of type int.

Body:
This gives the average similarity between the two arrays, that is the number of elements that were identical divided by the length of the arrays.

Note that if the arrays are different lengths, the == will evaluate to False and the returned mean will be 0.0

>>> import numpy as np
>>> array_1 = np.arange(4)
>>> array_2 = np.arange(4) % 3
>>> array_1
array([0, 1, 2, 3])
>>> array_2
array([0, 1, 2, 0])
>>> np.mean(array_1 == array_2)
0.75


问:
How to configure logstash to create an elasticsearch index?
elasticsearch version: elasticsearch-2.2.0.rpm
logstash version: logstash-2.2.2-1.noarch.rpm

I start elasticsearch, then logstash with /etc/logstash/conf.d/logstash.conf having a basic stdin/stdout, but no elasticsearch index is created. If I add the following to my logstash output configuration I get an index that indicates a yellow status:

action => "create"
index => "main_index"

The reason it's yellow, and not usable, is because the number of shards is 5 and replicas is 3. If I run:

curl -XPUT 'http://localhost:9200/index2/' -d '
index :
   number_of_shards : 1
   number_of_replicas : 0
'

"index2" is green and usable. How do I tell either logstash and/or elasticsearch that I want my index to have 1 shard with 0 replicas without issuing a curl command?

Thanks.

答:
In order to complete Val´s answer, here is an update for ES version 5.x:

Solution 3 would not work as index level configurations are disabled from config files: "Since elasticsearch 5.x index level settings can NOT be set on the nodes configuration like the elasticsearch.yaml"

Solution 1 does work, and below is an example:

Download and edit the base template for ES 5.x from here.

Change template name to match your index name pattern, and add the index settings you wanted to update in the first place:

```<code>{
  "template" : "syslog*",
  "version" : 50001,
  "settings" : {
   "index.refresh_interval" : "5s",
   "index.number_of_replicas" : 0,
   "index.number_of_shards" : 1
  },
...
}
</code>```

Update the logstash configuration so the output uses the created template:

```<code>output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "syslog%{+YYYY.MM.dd}"
    template => "path_to_your_template.json"
    template_name => "syslog*"
    template_overwrite => true
  }
}
</code>```

Restart the service

Body:
In order to complete Val´s answer, here is an update for ES version 5.x:

Solution 3 would not work as index level configurations are disabled from config files: "Since elasticsearch 5.x index level settings can NOT be set on the nodes configuration like the elasticsearch.yaml"

Solution 1 does work, and below is an example:

Download and edit the base template for ES 5.x from here.

Change template name to match your index name pattern, and add the index settings you wanted to update in the first place:

{
  "template" : "syslog*",
  "version" : 50001,
  "settings" : {
   "index.refresh_interval" : "5s",
   "index.number_of_replicas" : 0,
   "index.number_of_shards" : 1
  },
...
}

Update the logstash configuration so the output uses the created template:

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "syslog%{+YYYY.MM.dd}"
    template => "path_to_your_template.json"
    template_name => "syslog*"
    template_overwrite => true
  }
}

Restart the service


问:
Json to CLOB in java
I have created a spring boot application for fetching json messages from Kafka and I need to save the messages using Oracle function. For calling the function I need to convert json to CLOB. Can we do the conversion of Json to CLOB in java?</p>

答: JSON is stored as CLOB.. What is the issue.</p>

Title: Json to CLOB in java


问:
How do I get all pages to adopt the user-defined browser zoom level (css/html)?
I'm creating a website with multiple different pages (accessible through the nav bar).  When I zoom in on one of these pages (using ctrl +/-), the other pages don't necessarily adopt that zoom level.  So, for instance, if I make the "home" page 125% and then click onto the "contact" page, the "contact" page won't automatically be 125% as well.

How do I get all pages of my website to adopt whatever browser zoom level the user has chosen?

答:
I believe different browsers work differently when opening local files (using the file:// protocol).

I assume that since the browser believes it's opening 2 different HTML files which may not have any connection it will just set the zoom-level to the default one. Some browsers may remember this setting for all files opened in the future.

When you are on the same domain however using a website or local web server (google it, read up on xampp or Node.js to simulate a real website) which uses the http:// protocol the browser probably saves the zoom-level per domain (youtube.com, google.com etc.) so that it knows to set the zoom on all pages under that domain.


问:
Deployed heroku postgrest + database keeps crashing
I am trying to deploy postgrest v 0.4.2.0 app (https://github.com/begriffs/postgrest/releases/tag/v0.4.2.0) on heroku according to this instruction:

https://postgrest.com/en/v3.2/admin_deployment.html#heroku  (it's an older version, but viable in general instructions)

I already have a deployed database (via Heroku Postgres) with 1 table on my heroku account, so I keep trying to connect my DB with postgrest:

DB_URL: postgres://mpdwpnlqhwsosk:5abeb772ff431ef99e975be287970c3412174b331926b189d6485277f41d65d1@ec2-174-129-224-33.compute-1.amazonaws.com:5432/da5a8m1p77diab

And so, my app is just crashing (H10 error). I can't see table, etc. Although, I can successfully connect to this DB via pgAdmin

Is there I am doing something wrong, or is that some kind of nasty bug?

Logs:
2017-06-19T09:53:52.579013+00:00 heroku[web.1]: State changed from starting to crashed

2017-06-19T09:53:52.568134+00:00 heroku[web.1]: Process exited with status 1

2017-06-19T10:38:45.049215+00:00 heroku[web.1]: State changed from crashed to starting

2017-06-19T10:38:45.838847+00:00 heroku[web.1]: Starting process with command ./env-to-config ./postgrest postgrest.conf

2017-06-19T10:38:47.811334+00:00 heroku[web.1]: Process exited with status 1

2017-06-19T10:38:47.752947+00:00 app[web.1]: ConfigError {configErrorLocation = Key "" "secret-is-base64", configConversionError = Just [ConversionError {conversionErrorLoc = "boolValue", conversionErrorWhy = TypeError, conversionErrorVal = Just (String "false"), conversionErrorType = Just Bool, conversionErrorMsg = Nothing}]}

2017-06-19T10:38:47.822918+00:00 heroku[web.1]: State changed from starting to crashed

2017-06-19T11:04:22.519115+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=agile-mesa-95349.herokuapp.com request_id=7f7c6d70-c23b-400a-aec8-83758cb226cf fwd="109.184.214.45" dyno= connect= service= status=503 bytes= protocol=https

答:
By the way, this probably should not have been downvoted. It looks like a manifestation of a bug that was recently fixed in https://github.com/begriffs/postgrest/pull/897

The fix is not yet part of a release, but will be in the next release.


问:
Hibernate ManyToMany save
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.</p>

```<code>class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}
</code>```

答:
You are doing the audience save first but in relationship defined in your code:

Event will handle the persisting of the audience due to this:

```<code> @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
</code>```

So you first create the audiences, then create event, then attach audience list to event and save the event object in the end to database.

Title: Hibernate ManyToMany save

Body:
I have two classes with relation ManyToMany, I want create Audiences and later add them to events, but it throwing "detached" exception.

class Event {
    @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    @JoinTable(name = "UC_EVENT_AUDIENCE",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "audience_id"))
    private List<Audience> targetAudiences = new ArrayList<>();
}

clsas Audience {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "targetAudiences")
    private List<Event> events = new ArrayList<>();
}

public void run(ApplicationArguments args) throws Exception {
    //Generate audience data
    List<Audience> audiences = dataGenerator.createAudiences();
    //Save to db
    audienceRepository.save(audiences);

    Event event = new Event();
    event.setTargetAudiences(audiences);
    eventRepository.save(events);
}

Body:
You are doing the audience save first but in relationship defined in your code:

Event will handle the persisting of the audience due to this:

 @ManyToMany(
            fetch = FetchType.LAZY,
            targetEntity = Audience.class,
            cascade = {CascadeType.PERSIST, CascadeType.MERGE})

So you first create the audiences, then create event, then attach audience list to event and save the event object in the end to database.


问:
Replace Text/Image URL with CSS
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }```
</div>
</div>
</p>

<p>I tried to search before posting but I'm not finding anything that will work for what I need. </p>

<p>Thanks!</p>

<hr>

<p>Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:</p>

```

```

<p>And the script I have in tampermonkey:</p>

```    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });
```

<hr>

<p>Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:</p>

<p>Try 1:</p>

```var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });
```

<p>Try 2:</p>

```var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

<p>Try 3:</p>

```   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});
```

All of these attempts have returned the same error in console that .foreach is not a function.

答:
Try this? Add background: url(meta.eveonline.com/erika_mizune/90/2168_1.png) no-repeat !important; to your img CSS.

.topic-avatar img.avatar {
  height: 75px;
  width: 75px;
  border-radius: 0;
  background: url(meta.eveonline.com/erika_mizune/90/2168_1.png) no-repeat !important;
}

.topic-avatar {
  width: 75px !important;
}```

Title: Replace Text/Image URL with CSS

Body:
I am trying to make a custom style for the stylish plugin to use for the Eve Online forums.  I am attempting to resize the avatar image because it was too small for my liking. However it's using a low-quality image and it looks too grainy when resized, so I am trying to figure out how to use the larger image by replacing part of the text, or replacing the url (whatever is easier).  In the image, the only difference a piece of text that shows the size.

See:

meta.eveonline.com/erika_mizune/45/2168_1.png
meta.eveonline.com/erika_mizune/90/2168_1.png

So essentially the 45 (original) needs to be replaced with the 90 in order to look less grainy.

URL to Post: https://meta.eveonline.com/t/avatar-size-category-adjustment/9032

Stylish Plugin: https://userstyles.org/styles/144974/avatar-category-adjustment

My code to resize the image is this:

 .topic-avatar img.avatar
  {
    height: 75px;
    width: 75px;
    border-radius: 0;
  }

  .topic-avatar
  {
    width: 75px !important;
  }

I tried to search before posting but I'm not finding anything that will work for what I need.

Thanks!

Edit 1: I attempted to switch to tampermonkey to use JS as suggested but is not working.  Below is the origional code:

And the script I have in tampermonkey:

    var imagelist = document.getElementsByClassName("avatar");
    imagelist.foreach(function(element) {
        element.src = element.src.replace("/45/", "/90/");
    });

Edit 2: After trying to use debugging in the console I got the error that .foreach is not a function and attempted to try the following as well:

Try 1:

var imagelist = document.getElementsByTagName("img");
        imagelist.foreach(function(element) {
            element.src = element.src.replace("/45/", "/90/");
        });

Try 2:

var imagelist = Array.from(document.getElementsByClassName('avatar'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

Try 3:

   var imagelist = Array.from(document.getElementsByTagName('img'));
imagelist.foreach(function(element) {
    element.src = element.src.replace("/45/", "/90/");
});

All of these attempts have returned the same error in console that .foreach is not a function.


问:
Bootstrap Popover inside of a link in a table cell does not display
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

```<code><table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
 <tr style="background: transparent; border: 0; outline: 0;">
  <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
   <a href="#" id="lastBACommentCell" tabindex="0" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-template="<div class='mainViewPopover' role='tooltip'><div class='arrow'></div><div class='popover-content' style='color: #FFFFFF;'></div></div>" data-content="Here is my popover">
    Hover here for the popover to appear...
   </a>
  </td>
 </tr>
</table>
...
    <script type="text/javascript" language="javascript">
     $(document).ready(function() {
      $('#lastBACommentCell').popover();
     });
    </script>
</code>```

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

答:
I've included bootstrap and JQuery to the jsfiddle, The popover itself works, the problem is that you don't see it (because it is not styled) I've added a dummy text to see that the popover works -
 https://jsfiddle.net/km7pn81z/9/. You could also remove the data-template to see that it works.

Just add this CSS to make it more visible:

```<code>.mainViewPopover{
  background: black;
}
</code>```

Body:
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

    Hover here for the popover to appear...

...

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

Body:
I've included bootstrap and JQuery to the jsfiddle, The popover itself works, the problem is that you don't see it (because it is not styled) I've added a dummy text to see that the popover works -
 https://jsfiddle.net/km7pn81z/9/. You could also remove the data-template to see that it works.

Just add this CSS to make it more visible:

.mainViewPopover{
  background: black;
}


问:
T-SQL ORDER BY several clauses
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

```<code> ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |
</code>```

Demo Data Table ProjectData:

```<code> ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |
</code>```

My current result looks like this:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
</code>```

My current query looks like this:

```<code>SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt
</code>```

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

```<code> ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |
</code>```

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

答:
From the comments:

Q: Is 4 the only status that is out of order? or is there a later status that needs to be changed?

A: currently, 4 is the only one - but I assume in future there might emerge some others :)

So projects have a sort order. The natural thing would hence be to add a sortkey column to the project table. Then it's simply:

```<code>SELECT
  ROW_NUMBER() OVER (ORDER BY p.sortkey) as rn, -- if you want to show a row number
  p.ProjectId,
  p.Label,
  pd.StatusId,
  p.ProjectDataId
FROM MySchema.Project p
JOIN MySchema.ProjectData pd ON pd.ProjectDataId = p.ProjectDataId
ORDER BY p.sortkey;
</code>```

I've removed the DISTINCT Keyword, as there cannot be duplicates in the result when it contains ProjectDataId, I surmise.

Title: T-SQL ORDER BY several clauses

Body:
I'm currently working on a stored procedure in TSQL on SQL Server 2014. I need to write a query to order a list of Projects by different StatusIds.

Table Project:

ProjectId

Label

ProjectDataId

Table ProjectData:

ProjectDataId

StatusId

Table Project is linked to ProjectData via ProjectDataId.

Demo Data Table Project:

 ProjectId  | Label |  ProjectDataId |
------------+-------+----------------+
1           | Pro22 |      2         |
2           | Pro54 |      3         |
3           | Pro87 |      4         |
4           | Pro77 |      5         |
5           | Pro28 |      6         |

Demo Data Table ProjectData:

 ProjectDataId  |  StatusId   |
----------------+-------------+
2               |      1      |
3               |      2      |
4               |      3      |
5               |      4      |
6               |      4      |

My current result looks like this:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
3           | Pro87 |      3      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |

My current query looks like this:

SELECT ROW_NUMBER() OVER(ORDER BY StatusId ASC)  AS [RowNumber], *
FROM (SELECT DISTINCT
        [P].ProjectId
      , [P].Label
      , [PD].StatusId
      , [P].ProjectDataId
     FROM [MySchema].[Project] [P]
     INNER JOIN [MyProject].[ProjectData] [PD]
     ON [PD].ProjectDataId = [P].ProjectDataId) dt

This query works to order by statusId asc 1, 2, 3, 4 but not to bring it into the right order of statusId 1, 2, 4, 3.

Actually, the desired output should be:

 ProjectId  | Label |  StatusId   |
------------+-------+-------------+
1           | Pro22 |      1      |
2           | Pro54 |      2      |
4           | Pro77 |      4      |
5           | Pro28 |      4      |
3           | Pro87 |      3      |

Thus, I need to alter my sort query to achieve this.

My question, do you know how to solve this problem? To order by status more or less dynamically?

Thanks!

Body:
From the comments:

Q: Is 4 the only status that is out of order? or is there a later status that needs to be changed?

A: currently, 4 is the only one - but I assume in future there might emerge some others :)

So projects have a sort order. The natural thing would hence be to add a sortkey column to the project table. Then it's simply:

SELECT
  ROW_NUMBER() OVER (ORDER BY p.sortkey) as rn, -- if you want to show a row number
  p.ProjectId,
  p.Label,
  pd.StatusId,
  p.ProjectDataId
FROM MySchema.Project p
JOIN MySchema.ProjectData pd ON pd.ProjectDataId = p.ProjectDataId
ORDER BY p.sortkey;

I've removed the DISTINCT Keyword, as there cannot be duplicates in the result when it contains ProjectDataId, I surmise.


问:
How to create a circular progress bar over a image with only css?
I´m trying to create a circular progress bar over a image, like the image attached.

I´d like when 100%, hide progress. Any help?

答:
You can use CSS animation for this. This solution uses animated circle halves:

.circle {
  display: inline-flex;
  border-radius: 100%;
  background-image: url("https://i.stack.imgur.com/sRV6Q.jpg");
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div></code>```

Also if you want smooth circle hiding you can add animation for circle halves:

.circle {
  display: inline-flex;
  border-radius: 100%;
  background-image: url("https://i.stack.imgur.com/sRV6Q.jpg");
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
  animation-name: hide-smoothly;
  animation-duration: 2s;
  animation-delay: 4s;
  animation-fill-mode: forwards;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-fill-mode: forwards;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes hide-smoothly {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div></code>```

Body:
You can use CSS animation for this. This solution uses animated circle halves:

.circle {
  display: inline-flex;
  border-radius: 100%;
  background-image: url("https://i.stack.imgur.com/sRV6Q.jpg");
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

<div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div>

Also if you want smooth circle hiding you can add animation for circle halves:

.circle {
  display: inline-flex;
  border-radius: 100%;
  background-image: url("https://i.stack.imgur.com/sRV6Q.jpg");
  overflow: hidden;
}

.circle__half {
  height: 200px;
  width: 100px;
  position: relative;
  overflow: hidden;
  animation-name: hide-smoothly;
  animation-duration: 2s;
  animation-delay: 4s;
  animation-fill-mode: forwards;
}

.circle__half:before {
  height: inherit;
  width: inherit;
  position: absolute;
  content: "";
  border-radius: 100px 0 0 100px;
  background-color: lime;
  transform-origin: 100% 50%;
  /* hidden by default */
  transform: rotate(180deg);
  opacity: 0.65;
  animation-name: rotate-circle-half;
  animation-duration: 4s;
  animation-timing-function: linear;
  animation-fill-mode: forwards;
}

.circle__half--right {
  transform: scale(-1, -1);
}

.circle .circle__half--right:before {
  animation-name: rotate-circle-half--right;
}

/* show half of circle half of the time */
@keyframes rotate-circle-half {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes rotate-circle-half--right {
  0% {
    transform: rotate(180deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(0deg);
  }
}

@keyframes hide-smoothly {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

<div class="circle">
  <div class="circle__half"></div>
  <div class="circle__half circle__half--right"></div>
</div>


问:
AJAX call to servlet not working
I have a servlet that will insert form input fields into my database and it works when I set

```<code><form action="CreateUserServlet">
</code>```

but I wanted to try some form validation stuff and the ajax servlet call returns success but the data is not added to my database.

servlet:

```<code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String username = request.getParameter("usernameField");
    String password = request.getParameter("passwordField");

    if (MySqlCon.createUser(username, password)) {
        try (PrintWriter out = response.getWriter()) {
            out.println("<script type=\"text/javascript\">");
            out.println("alert('Account Successfully Created!');");
            out.println("</script>");
        }
    } else {
        try (PrintWriter out = response.getWriter()) {
            out.println("<script type=\"text/javascript\">");
            out.println("alert('Error in Creating Account!');");
            out.println("</script>");
        }
    }
}
</code>```

html form

```<code><div class="collapse" id="createAcc">
                <div class="create-wrapper">
                    <form method="post" id="create-ajax">
                        <h3> Enter your details </h3>
                        <div class="row">
                            <div class="col-md-12">
                                <input type="text" name="usernameField" placeholder="choose username" id="createUsername"/>
                                <p class="hideMsg" id="createUserError">bad username, try again</p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <input type="text" name="passwordField" placeholder="choose password" id="createPassword"/>
                                <p class="hideMsg" id="createPasswordError">bad password, try again</p>
                            </div>
                        </div>
                        <div class="row buttonRow">
                            <div class="col-md-12">
                                <input id="submitCreateAcc" type="submit" value="Create"/>
                                <p class="hideMsg" id="successMsg">Account created!</p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
</code>```

the javascript:

```<code>$(document).ready(function () {
var createForm = $('#create-ajax');

$(createForm).submit(function (event) {
    event.preventDefault();

    var username = $('#createUsername').val();
    var password = $('#createPassword').val();

    if (username.length < 6) {
        $('#createUserError').removeClass('hideMsg').addClass('showMsg');
    } else {
        $('#createUserError').removeClass('showMsg').addClass('hideMsg');
    }
    if (password.length < 8) {
        $('#createPasswordError').removeClass('hideMsg').addClass('showMsg');
    } else {
        $('#createPasswordError').removeClass('showMsg').addClass('hideMsg');
    }

    if (username.length >= 6 && password.length >= 8) {
        $.ajax({
            url: 'CreateUserServlet',
            method: 'POST',
            success: function () {
                $('#successMsg').removeClass('hideMsg').addClass('showMsg');
            }
        });
    }
})
});
</code>```

The sucessMsg is shown but the data did not get inserted. Any help is appreciated, thanks

答:
You need to provide the data to submit with the post request, it does not get bound automatically.

```<code>$.ajax({
  url: 'CreateUserServlet',
  method: 'POST',
  data: createForm.serialize(),
  success: function () {
    $('#successMsg').removeClass('hideMsg').addClass('showMsg');
  }
});
</code>```

And returning an alert from the server makes no sense in this case. You should return back a JSON object with the value you want to display to the user.

Title: AJAX call to servlet not working

Body:
I have a servlet that will insert form input fields into my database and it works when I set

<form action="CreateUserServlet">

but I wanted to try some form validation stuff and the ajax servlet call returns success but the data is not added to my database.

servlet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String username = request.getParameter("usernameField");
    String password = request.getParameter("passwordField");

    if (MySqlCon.createUser(username, password)) {
        try (PrintWriter out = response.getWriter()) {
            out.println("");
        }
    } else {
        try (PrintWriter out = response.getWriter()) {
            out.println("");
        }
    }
}

html form

                    <form method="post" id="create-ajax">

 Enter your details

                                <input type="text" name="usernameField" placeholder="choose username" id="createUsername"/>

bad username, try again

                                <input type="text" name="passwordField" placeholder="choose password" id="createPassword"/>

bad password, try again

                                <input id="submitCreateAcc" type="submit" value="Create"/>

Account created!

                    </form>

the javascript:

$(document).ready(function () {
var createForm = $('#create-ajax');

$(createForm).submit(function (event) {
    event.preventDefault();

    var username = $('#createUsername').val();
    var password = $('#createPassword').val();

    if (username.length < 6) {
        $('#createUserError').removeClass('hideMsg').addClass('showMsg');
    } else {
        $('#createUserError').removeClass('showMsg').addClass('hideMsg');
    }
    if (password.length < 8) {
        $('#createPasswordError').removeClass('hideMsg').addClass('showMsg');
    } else {
        $('#createPasswordError').removeClass('showMsg').addClass('hideMsg');
    }

    if (username.length >= 6 && password.length >= 8) {
        $.ajax({
            url: 'CreateUserServlet',
            method: 'POST',
            success: function () {
                $('#successMsg').removeClass('hideMsg').addClass('showMsg');
            }
        });
    }
})
});

The sucessMsg is shown but the data did not get inserted. Any help is appreciated, thanks

Body:
You need to provide the data to submit with the post request, it does not get bound automatically.

$.ajax({
  url: 'CreateUserServlet',
  method: 'POST',
  data: createForm.serialize(),
  success: function () {
    $('#successMsg').removeClass('hideMsg').addClass('showMsg');
  }
});

And returning an alert from the server makes no sense in this case. You should return back a JSON object with the value you want to display to the user.


问:
For each through List<string> returned from AJAX GET in JavaScript
The problem is as the title describes... I'm trying to loop through the values in a list of strings and alert them on the page.  Unfortunately, I keep getting an error of...

"Uncaught TypeError: response.forEach is not a function"

I've read a few other places on SO about for loops in javascript, but it seems that it works with arrays.  I'll state that I'm a novice when it comes to JavaScript... so is there an equivalent .ToArray() method in JavaScript?  I've written a simple application to show what it is I'm trying to accomplish.

Note: I'm unable to change the return type of the controller method "GetStringList". In the larger application, the method must return a list of strings.

Controller Method (C#)

```<code>    public List<string> GetStringList(){
        List<string> listOfStrings = new List<string>();

        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[SampleOrders] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                listOfStrings.Add((string)sqlDR["SalesOrder"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return listOfStrings;
    }
</code>```

View / JavaScript Function

```<code>    <script>
        $(document).ready(function () {
            $('#demoBtn').click(function () {
                $.ajax({
                    type: 'GET',
                    url: '/Home/GetStringList',
                    success: function (response) {
                        response.forEach(function (item) {
                            alert(item);
                        });
                    }
                });
            });
        });
    </script>
</code>```

Please let me know if any clarifications need made -- thanks!

答:
.forEach() is an array method. response is the XMLHttpRequest response string. Since there is no List<String> type in JavaScript, you just have a big string.

You should try parsing that string into an Array (if that's the structure you've received) with var myArray = JSON.parse(response) and then you'd be able to call .forEach() on myArray.

Have you actually logged response to see the exact syntax you are getting?

Body:
The problem is as the title describes... I'm trying to loop through the values in a list of strings and alert them on the page.  Unfortunately, I keep getting an error of...

"Uncaught TypeError: response.forEach is not a function"

I've read a few other places on SO about for loops in javascript, but it seems that it works with arrays.  I'll state that I'm a novice when it comes to JavaScript... so is there an equivalent .ToArray() method in JavaScript?  I've written a simple application to show what it is I'm trying to accomplish.

Note: I'm unable to change the return type of the controller method "GetStringList". In the larger application, the method must return a list of strings.

Controller Method (C#)

    public List<string> GetStringList(){
        List<string> listOfStrings = new List<string>();

        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[SampleOrders] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                listOfStrings.Add((string)sqlDR["SalesOrder"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return listOfStrings;
    }

View / JavaScript Function

Please let me know if any clarifications need made -- thanks!


问:
Is it possible to add custom attributes to a group in Azure AD B2C
I am trying to cater for a broad set of auth and identity management requirements, homogenizing this area of functionality across different legacy applications, and looking into Azure AD B2C as an option.

It seems as though there may be a need for maintaining contact information on a group. For example, we may need to group users according to their 'reseller,' and we may wish to have additional info about the reseller within Azure AD B2C.

Is this possible in AD B2C?

答:
It is possible to add custom attributes to a group in Azure AD B2C using the same mechanism that's available in regular Azure AD via the Azure AD Graph: Directory schema extensions.

Note that while you can use groups in Azure AD B2C, sending group claims in the token isn't yet supported, so you'll need to make a separate call to the Azure AD Graph to obtain a user's group membership and details about the group. You can always vote for this ask in the Azure AD B2C feedback forum: Get user membership groups in the claims with AD B2C


问:
detect is the last row in column is changed and fire event
I would like to trigger an event if the user starts to type anything in the last empty cell in column B.
I have the code bellow so far but have a mismatch for the range and not sure how to correct it.</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim LastNonEmptyRow, LastRow, LastEmptyRow, LastValue As Long

LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B

LastEmptyRow = LastNonEmptyRow + 1'
        If Not Intersect(Target, Range(LastEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range
        MsgBox "You entered something in last empty row in column B!"
        '...code to execute when data is entered in the last empty column

   End If
End Sub
</code>```

答:
You need to specify your range correctly.  Change from this:

```<code>Range(LastEmptyRow)
</code>```

To this:

```<code>Range("B" & LastEmptyRow)
</code>```

EDIT:

Taking the above into account along with your additional comments, the code ends up like this:

```<code>Private oldValue As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   oldValue = Target.Value
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim LastNonEmptyRow As Long
   Dim LastRow As Long
   Dim LastEmptyRow As Long
   Dim LastValue As Long

   If oldValue <> "" Then Exit Sub

   LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B
   LastEmptyRow = LastNonEmptyRow + 1

   If Not Intersect(Target, Range("B" & LastNonEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range
      MsgBox "You entered something in last empty row in column B - " & LastNonEmptyRow
      '...code to execute when data is entered in the last empty column
   End If
End Sub
</code>```

Body:
I would like to trigger an event if the user starts to type anything in the last empty cell in column B.
I have the code bellow so far but have a mismatch for the range and not sure how to correct it.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim LastNonEmptyRow, LastRow, LastEmptyRow, LastValue As Long

LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B

LastEmptyRow = LastNonEmptyRow + 1'
        If Not Intersect(Target, Range(LastEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range
        MsgBox "You entered something in last empty row in column B!"
        '...code to execute when data is entered in the last empty column

   End If
End Sub

Body:
You need to specify your range correctly.  Change from this:

Range(LastEmptyRow)

To this:

Range("B" & LastEmptyRow)

EDIT:

Taking the above into account along with your additional comments, the code ends up like this:

Private oldValue As String

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   oldValue = Target.Value
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim LastNonEmptyRow As Long
   Dim LastRow As Long
   Dim LastEmptyRow As Long
   Dim LastValue As Long

   If oldValue <> "" Then Exit Sub

   LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B
   LastEmptyRow = LastNonEmptyRow + 1

   If Not Intersect(Target, Range("B" & LastNonEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range
      MsgBox "You entered something in last empty row in column B - " & LastNonEmptyRow
      '...code to execute when data is entered in the last empty column
   End If
End Sub


问:
$_FILES[“image”][“tmp_name”] is empy with no data
I have written the following code. But I am getting empty $_FILES[“image”][“tmp_name”] with no value.

Php:

```<code>if ($_FILES) {
$imageFileType = strtolower(pathinfo("img/" . basename($_FILES["Image"]["name"]), PATHINFO_EXTENSION));

$target_file = "img/" . uniqid(rand()) . ".$imageFileType";
if (move_uploaded_file($_FILES["Image"]["tmp_name"], $target_file)) {
   $pic = $target_file;
} else {

    echo "Invalid File";
    }
}
</code>```

Html:

```<code><form action="product-add.php" method="post" enctype="multipart/form-data">
        <div class="products-form">
            <p> Image:</p> <input type="file" name="Image" >
            <input type="submit" value="ADD PRODUCT" class="btn">
        </div>
</form>
</code>```

答:
Well it appears to me this is not right:

```<code>$target_file = "img/" . uniqid(rand()) . ".$imageFileType";
</code>```

it should be

```<code>$target_file = "img/" . uniqid(rand()) . "." .$imageFileType;
</code>```

Body:
I have written the following code. But I am getting empty $_FILES[“image”][“tmp_name”] with no value.

Php:

if ($_FILES) {
$imageFileType = strtolower(pathinfo("img/" . basename($_FILES["Image"]["name"]), PATHINFO_EXTENSION));

$target_file = "img/" . uniqid(rand()) . ".$imageFileType";
if (move_uploaded_file($_FILES["Image"]["tmp_name"], $target_file)) {
   $pic = $target_file;
} else {

    echo "Invalid File";
    }
}

Html:

<form action="product-add.php" method="post" enctype="multipart/form-data">

 Image:
 <input type="file" name="Image" >
            <input type="submit" value="ADD PRODUCT" class="btn">

</form>

Body:
Well it appears to me this is not right:

$target_file = "img/" . uniqid(rand()) . ".$imageFileType";

it should be

$target_file = "img/" . uniqid(rand()) . "." .$imageFileType;


问:
How do I extract "last name" from my JSON response?
Can anyone tell me how to parse this JSON reponse? I need to extract "last name" from the services.</p>

```<code>{
   "Entity":{
      "ID":1,
      "UserTypeID":1,
      "Code":"lPEq",
      "Services":[
         {
            "ID":118,
            "Code":"1",
            "Parent_ID":null,
            "Name":"Alex",
            "lastName":"John"
         },
         {
            "ID":119,
            "Code":"2",
            "Parent_ID":null,
            "Name":"Christy",
            "lastName":"Noel"
         }
      ]
   }
}
</code>```

答:
Here's how you can do it. Don't forget to handle unwrap</p>

```<code>let str = "{ \"Entity\":{ \"ID\":1, \"UserTypeID\":1, \"Code\":\"lPEq\", \"Services\":[ { \"ID\":118, \"Code\":\"1\", \"Parent_ID\":null, \"Name\":\"Alex\", \"lastName\":\"John\" }, { \"ID\":119, \"Code\":\"2\", \"Parent_ID\":null, \"Name\":\"Christy\", \"lastName\":\"Noel\" } ] } }"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

    let entityDic = json?["Entity"] as? [String: Any]
    let servicesDic = entityDic?["Services"] as? [Any]
    let firstPerson = servicesDic?[0] as? [String: Any]
    dump(firstPerson?["lastName"])
}catch let error{

}
</code>```

Body:
Can anyone tell me how to parse this JSON reponse? I need to extract "last name" from the services.

{
   "Entity":{
      "ID":1,
      "UserTypeID":1,
      "Code":"lPEq",
      "Services":[
         {
            "ID":118,
            "Code":"1",
            "Parent_ID":null,
            "Name":"Alex",
            "lastName":"John"
         },
         {
            "ID":119,
            "Code":"2",
            "Parent_ID":null,
            "Name":"Christy",
            "lastName":"Noel"
         }
      ]
   }
}

Body:
Here's how you can do it. Don't forget to handle unwrap

let str = "{ \"Entity\":{ \"ID\":1, \"UserTypeID\":1, \"Code\":\"lPEq\", \"Services\":[ { \"ID\":118, \"Code\":\"1\", \"Parent_ID\":null, \"Name\":\"Alex\", \"lastName\":\"John\" }, { \"ID\":119, \"Code\":\"2\", \"Parent_ID\":null, \"Name\":\"Christy\", \"lastName\":\"Noel\" } ] } }"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

    let entityDic = json?["Entity"] as? [String: Any]
    let servicesDic = entityDic?["Services"] as? [Any]
    let firstPerson = servicesDic?[0] as? [String: Any]
    dump(firstPerson?["lastName"])
}catch let error{

}


问:
Update only edited/changed fields
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

```<code>$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");
</code>```

Appreciate the help here.....

答:
Another solution could be to set the value of all fields as what the current value is in the database. That way, they know what the current value is and would be easier for them to know what to change, and when the form is submitted, it'll just resubmit the info in the form whether it was changed or not.

For example:

```<code><input type="text" name="firstname" value="<?php echo $row['firstname']; ?>" required>
</code>```

when the form is submitted, it'll keep the same data that was currently there, or update it if the value was changed in the input field

Title: Update only edited/changed fields

Body:
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");

Appreciate the help here.....

Body:
Another solution could be to set the value of all fields as what the current value is in the database. That way, they know what the current value is and would be easier for them to know what to change, and when the form is submitted, it'll just resubmit the info in the form whether it was changed or not.

For example:

<input type="text" name="firstname" value="<?php echo $row['firstname']; ?>" required>

when the form is submitted, it'll keep the same data that was currently there, or update it if the value was changed in the input field


问:
How to resolve positional index error in python while solving a condition in python?
I have the following data and I am trying the following code:

```<code>Name    Sensex_index    Start_Date       End_Date
AAA        0.5           20/08/2016    25/09/2016
AAA        0.8           26/08/2016    29/08/2016
AAA        0.4           30/08/2016    31/08/2016
AAA        0.9           01/09/2016    05/09/2016
AAA        0.5           12/09/2016    22/09/2016
AAA        0.3           24/09/2016    29/09/2016
ABC        0.9           01/01/2017    15/01/2017
ABC        0.5           23/01/2017    30/01/2017
ABC        0.7           02/02/2017    15/03/2017
</code>```

so what i do is, If the sensex index of (with same name) increases from lower index and moves to higher index, then the Termination date is the previous value, for example, I am looking for the following output. To find the actual start and termination date from the above datatype.

```<code>Name   Sensex_index  Actual_Start      Termination_Date
AAA        0.5        20/08/2016          31/08/2016
AAA        0.8        20/08/2016          31/08/2016
AAA        0.4        20/08/2016          31/08/2016 [high to low; low to high,terminate]
AAA        0.9        01/09/2016          29/09/2016
AAA        0.5        01/09/2016          29/09/2016
AAA        0.3        01/09/2016          29/09/2016 [end of AAA]
ABC        0.9        01/01/2017          30/01/2017
ABC        0.5        01/01/2017          30/01/2017 [high to low; low to high,terminate]
ABC        0.7        02/02/2017          15/03/2017 [end of ABC]
</code>```

I use the following code which was working before but now i get index error,

```<code>#Find the rows where price change from high to low and then to high
df['change'] = df.groupby('Name')['Sensex_index'].apply(lambda x: x.rolling(3,center=True).apply(lambda y: True if (y[1]<y[0] and y[1]<y[2]) else False))
#Find the last row for each name
df.iloc[df.groupby('Name')['change'].tail(1).index, -1] = 1.0
#Set End_Date as Termination_Date for those changing points
df['Termination_Date'] = df.apply(lambda x: x.End_Date if x.change>0 else np.nan, axis=1)
#Set Actual_Start
df['Actual_Start'] = df.apply(lambda x: x.Start_Date if (x.name==0
                                                      or x.Name!=
df.iloc[x.name-1]['Name']
                                                      or df.iloc[x.name-1]['change']>0)
                                                 else np.nan, axis=1)
#back fill the Termination_Date for other rows.
df.Termination_Date.fillna(method='bfill', inplace=True)
#forward fill the Actual_Start for other rows.
df.Actual_Start.fillna(method='ffill', inplace=True)
print(df)
</code>```

I get the following error:

```<code> File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1554, in _is_valid_list_like
raise IndexError("positional indexers are out-of-bounds")
</code>```

Index Error!

```<code>IndexError: positional indexers are out-of-bounds
</code>```

Body:
I have the following data and I am trying the following code:

Name    Sensex_index    Start_Date       End_Date
AAA        0.5           20/08/2016    25/09/2016
AAA        0.8           26/08/2016    29/08/2016
AAA        0.4           30/08/2016    31/08/2016
AAA        0.9           01/09/2016    05/09/2016
AAA        0.5           12/09/2016    22/09/2016
AAA        0.3           24/09/2016    29/09/2016
ABC        0.9           01/01/2017    15/01/2017
ABC        0.5           23/01/2017    30/01/2017
ABC        0.7           02/02/2017    15/03/2017

so what i do is, If the sensex index of (with same name) increases from lower index and moves to higher index, then the Termination date is the previous value, for example, I am looking for the following output. To find the actual start and termination date from the above datatype.

Name   Sensex_index  Actual_Start      Termination_Date
AAA        0.5        20/08/2016          31/08/2016
AAA        0.8        20/08/2016          31/08/2016
AAA        0.4        20/08/2016          31/08/2016 [high to low; low to high,terminate]
AAA        0.9        01/09/2016          29/09/2016
AAA        0.5        01/09/2016          29/09/2016
AAA        0.3        01/09/2016          29/09/2016 [end of AAA]
ABC        0.9        01/01/2017          30/01/2017
ABC        0.5        01/01/2017          30/01/2017 [high to low; low to high,terminate]
ABC        0.7        02/02/2017          15/03/2017 [end of ABC]

I use the following code which was working before but now i get index error,

#Find the rows where price change from high to low and then to high
df['change'] = df.groupby('Name')['Sensex_index'].apply(lambda x: x.rolling(3,center=True).apply(lambda y: True if (y[1]<y[0] and y[1]<y[2]) else False))
#Find the last row for each name
df.iloc[df.groupby('Name')['change'].tail(1).index, -1] = 1.0
#Set End_Date as Termination_Date for those changing points
df['Termination_Date'] = df.apply(lambda x: x.End_Date if x.change>0 else np.nan, axis=1)
#Set Actual_Start
df['Actual_Start'] = df.apply(lambda x: x.Start_Date if (x.name==0
                                                      or x.Name!=
df.iloc[x.name-1]['Name']
                                                      or df.iloc[x.name-1]['change']>0)
                                                 else np.nan, axis=1)
#back fill the Termination_Date for other rows.
df.Termination_Date.fillna(method='bfill', inplace=True)
#forward fill the Actual_Start for other rows.
df.Actual_Start.fillna(method='ffill', inplace=True)
print(df)

I get the following error:

 File "/usr/local/lib/python2.7/dist-packages/pandas/core/indexing.py", line 1554, in _is_valid_list_like
raise IndexError("positional indexers are out-of-bounds")

Index Error!

IndexError: positional indexers are out-of-bounds

Body:
You probably overwritten your df somewhere:

tsv = """Name    Sensex_index    Start_Date       End_Date
AAA        0.5           20/08/2016    25/09/2016
AAA        0.8           26/08/2016    29/08/2016
AAA        0.4           30/08/2016    31/08/2016
AAA        0.9           01/09/2016    05/09/2016
AAA        0.5           12/09/2016    22/09/2016
AAA        0.3           24/09/2016    29/09/2016
ABC        0.9           01/01/2017    15/01/2017
ABC        0.5           23/01/2017    30/01/2017
ABC        0.7           02/02/2017    15/03/2017
"""

df=pd.read_table(io.StringIO(tsv), sep="\s+")

then I copy-pasted your code and received no error, but this df

  Name  Sensex_index  Start_Date    End_Date  change Termination_Date  \
0  AAA           0.5  20/08/2016  25/09/2016     NaN       31/08/2016
1  AAA           0.8  26/08/2016  29/08/2016     0.0       31/08/2016
2  AAA           0.4  30/08/2016  31/08/2016     1.0       31/08/2016
3  AAA           0.9  01/09/2016  05/09/2016     0.0       29/09/2016
4  AAA           0.5  12/09/2016  22/09/2016     0.0       29/09/2016
5  AAA           0.3  24/09/2016  29/09/2016     1.0       29/09/2016
6  ABC           0.9  01/01/2017  15/01/2017     NaN       30/01/2017
7  ABC           0.5  23/01/2017  30/01/2017     1.0       30/01/2017
8  ABC           0.7  02/02/2017  15/03/2017     1.0       15/03/2017

  Actual_Start
0   20/08/2016
1   20/08/2016
2   20/08/2016
3   01/09/2016
4   01/09/2016
5   01/09/2016
6   01/01/2017
7   01/01/2017
8   02/02/2017

Just recreate your dataframe and you should be good.