问:
What is this JAVA thread error?
I'm having this error and I'm can't fix, I don't know what is wrong. I'm stuck in this.

What this error means? com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager

This is the full stacktrace:

```<code>    org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:587
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
    at org.apache.commons.mail.Email.send(Email.java:1267)
    at com.wealthsystems.sim3g.modulo.email.impl.EnviaEmailsThread.process(EnviaEmailsThread.java:123)
    at com.wealthsystems.dao.hibernate.api.service.WsThreadService.run(WsThreadService.java:55)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager
    at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:800)
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:112)
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:65)
    at com.google.appengine.api.mail.MailServiceImpl.doSend(MailServiceImpl.java:101)
    at com.google.appengine.api.mail.MailServiceImpl.send(MailServiceImpl.java:34)
    at com.google.appengine.api.mail.stdimpl.GMTransport.sendMessage(GMTransport.java:223)
    at javax.mail.Transport.send(Transport.java:95)
    at javax.mail.Transport.send(Transport.java:48)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
    ... 10 more
</code>```

This is my code that generate this error:

```<code>   public static void sendMailApache(String protocol, String host, String port, String userName, String password,
           String subject, byte[] content, String para, String cc, String co) {
       try {
           final Email email = new SimpleEmail();
           email.setHostName(host);
           email.setSmtpPort(Integer.parseInt(port));
           email.setTLS(true);
           email.setSSL(false);
           email.setAuthenticator(new DefaultAuthenticator(userName, password));
           email.setFrom(userName);
           email.setSubject(subject);
           email.setCharset(org.apache.commons.mail.Email.ISO_8859_1);

           for (String str: para.split(";")) {
               email.addTo(str);
           }
           for (String str: cc.split(";")) {
               email.addCc(str);
           }
           for (String str: co.split(";")) {
               email.addBcc(str);
           }
           email.setMsg(content.toString());
           email.send();
       } catch (EmailException e) {
           throw new RuntimeException(e);
       }
    }
</code>```

What this error means? What I'm doing wrong?

答:
It means you can't use an threads that are not created by ThreadManager. In your case you're trying to use a ScheduledThreadPoolExecutor which by default would use "illegal" threads.

You'll need to supply a ThreadFactory from the ThreadManager (most likely the backgroundThreadFactory()), so the threads created are "proper" threads and GAE doesn't complain.

Title: What is this JAVA thread error?

Body:
I'm having this error and I'm can't fix, I don't know what is wrong. I'm stuck in this.

What this error means? com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager

This is the full stacktrace:

    org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:587
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1242)
    at org.apache.commons.mail.Email.send(Email.java:1267)
    at com.wealthsystems.sim3g.modulo.email.impl.EnviaEmailsThread.process(EnviaEmailsThread.java:123)
    at com.wealthsystems.dao.hibernate.api.service.WsThreadService.run(WsThreadService.java:55)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call mail.Send in a thread that is neither the original request thread nor a thread created by ThreadManager
    at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:800)
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:112)
    at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:65)
    at com.google.appengine.api.mail.MailServiceImpl.doSend(MailServiceImpl.java:101)
    at com.google.appengine.api.mail.MailServiceImpl.send(MailServiceImpl.java:34)
    at com.google.appengine.api.mail.stdimpl.GMTransport.sendMessage(GMTransport.java:223)
    at javax.mail.Transport.send(Transport.java:95)
    at javax.mail.Transport.send(Transport.java:48)
    at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1232)
    ... 10 more

This is my code that generate this error:

   public static void sendMailApache(String protocol, String host, String port, String userName, String password,
           String subject, byte[] content, String para, String cc, String co) {
       try {
           final Email email = new SimpleEmail();
           email.setHostName(host);
           email.setSmtpPort(Integer.parseInt(port));
           email.setTLS(true);
           email.setSSL(false);
           email.setAuthenticator(new DefaultAuthenticator(userName, password));
           email.setFrom(userName);
           email.setSubject(subject);
           email.setCharset(org.apache.commons.mail.Email.ISO_8859_1);

           for (String str: para.split(";")) {
               email.addTo(str);
           }
           for (String str: cc.split(";")) {
               email.addCc(str);
           }
           for (String str: co.split(";")) {
               email.addBcc(str);
           }
           email.setMsg(content.toString());
           email.send();
       } catch (EmailException e) {
           throw new RuntimeException(e);
       }
    }

What this error means? What I'm doing wrong?


来源: stackexchange

问:
Vapor: Handle HTTPS requests?
I have a VPS (Ubuntu 14.04) with Apache2, Swift 3.1.1 and Vapor installed. I want to receive client side requests to my Vapor-Built-Service via HTTPS protocol (on port 8443 for example). I didn't find any newbie helper document to do this, so please help me.

Thanks.

答:
After a lot of searching I found the answer:

1. You need to install Apache or Nginx on your VPS. Here I assume that the reader uses Apache. But for more info on installing Apache server on Ubuntu 14.04 you can take a look at here.

2. The next thing you need to do is to make Apache work with SSL (or HTTPS protocol). You can find a complete guide here.

3. Now it's time to set the Apache server as a reverse proxy server. You can find a good guide to do that here and here. don't forget to put the reverse-proxy-config-code at port 443 related part.

Update:

There is also another way which you can configure the Vapor directly. Take a look at here.

ContentLicense: CC BY-SA 3.0

Title: Vapor: Handle HTTPS requests?


问:
How to make an android apk file in android studio that runs in all mobiles for testing purpose only
I'm new to android, When i'm installing android app via USB cable manually it's running but i want to share it and run in another mobile phones for testing purpose for that what i've to do?</p>

答:
Go to Build menu, then click on Build APK. A pop-up appears having title Build APK
APK(s) generated successfully.
Show in Explorer. Then click on Show in Explorer and your APK file is ready to share.

ContentLicense: CC BY-SA 4.0


问:
Place holder in C#
```<code>   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }
</code>```

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

答:
Simply put, you can't provide a formatted specifier for a value that doesn't exist. For example:

```<code>Console.WriteLine("{1}", "test");
</code>```

Would throw a FormatException because only one parameter is provided (arrays being 0-based).

Title: Place holder in C#

Body:
   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

Body:
Simply put, you can't provide a formatted specifier for a value that doesn't exist. For example:

Console.WriteLine("{1}", "test");

Would throw a FormatException because only one parameter is provided (arrays being 0-based).


问:
Watson Discovery Passage Length
I am finding that the passages returned by Discovery are generally very good choices... but they are too short and truncated at odd points... even mid sentence. A couple of questions:

Is there a way to control the passage length returned?

Is there a way to bring the user directly to the passage within the full document?

答: This is a problem with Watson Discovery. The answer seems to be if you need longer answers, to divide your documents into short sub-documents and make those part of your collection. For instance, I use discovery with my syllabus to help students who have questions about class and university policies. I divide each sub-section into its own document. Discovery can then produce the entire document (which is not more than a paragraph). </p>

Title: Watson Discovery Passage Length


问:
Error while compiling with cmake: cannot find -ldwmapi
Edit: Im using MinGW-x86_64 on windows

When Im trying to compile a gtk+ 3 c project with cmake, I have this error message on the log:

```<code>"C:\Program Files\JetBrains\CLion 2017.1.3\bin\cmake\bin\cmake.exe" --build C:\Users\Jonas\ClionProjects\tutorial\cmake-build-debug --target tutorial -- -j 4
[ 50%] Linking C executable tutorial.exe
c:/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -ldwmapi
collect2.exe: error: ld returned 1 exit status
CMakeFiles\tutorial.dir\build.make:96: recipe for target 'tutorial.exe' failed
mingw32-make.exe[3]: *** [tutorial.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/tutorial.dir/all] Error 2
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/tutorial.dir/all' failed
CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/tutorial.dir/rule' failed
mingw32-make.exe[1]: *** [CMakeFiles/tutorial.dir/rule] Error 2
mingw32-make.exe: *** [tutorial] Error 2
Makefile:117: recipe for target 'tutorial' failed
</code>```

This is my CMakeLists.txt, in there I added gtk3 and its libraries, but when Im trying to compile, it has the errors mentioned before.

```<code>cmake_minimum_required(VERSION 3.7)
project(tutorial)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)

set(PKG_CONFIG_EXECUTABLE "C:/msys64/mingw64/bin/pkg-config.exe")

FIND_PACKAGE(PkgConfig REQUIRED)
PKG_CHECK_MODULES(GTK3 REQUIRED gtk+-3.0)

INCLUDE_DIRECTORIES(${GTK3_INCLUDE_DIRS})
LINK_DIRECTORIES(${GTK3_LIBRARY_DIRS})

add_executable(tutorial ${SOURCE_FILES})

ADD_DEFINITIONS(${GTK3_CFLAGS_OTHER})

TARGET_LINK_LIBRARIES(tutorial ${GTK3_LIBRARIES})
</code>```

答:
dwmapi.dll is provided only for Vista. So I guess that it is a bug of package of gtk+-3.0. And -ldwmapi is not required for your OS. Below is a workaround to fix this issue. I don't make sure this will solve your issue. Note that this is self-responsibility.

make backup-copy of gdk-3.0.pc, gdk-broadway-3.0.pc, gdk-win32-3.0.pc in C:\msys64\mingw64\lib\pkgconfig

open those files in vim, remove -ldwmapi and :wq

UPDATE

Let's create libdwmapi.a

download def file from here

dlltool -d dwmapi.def -l libdwmapi.a

Body:
Edit: Im using MinGW-x86_64 on windows

When Im trying to compile a gtk+ 3 c project with cmake, I have this error message on the log:

"C:\Program Files\JetBrains\CLion 2017.1.3\bin\cmake\bin\cmake.exe" --build C:\Users\Jonas\ClionProjects\tutorial\cmake-build-debug --target tutorial -- -j 4
[ 50%] Linking C executable tutorial.exe
c:/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/ld.exe: cannot find -ldwmapi
collect2.exe: error: ld returned 1 exit status
CMakeFiles\tutorial.dir\build.make:96: recipe for target 'tutorial.exe' failed
mingw32-make.exe[3]: *** [tutorial.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/tutorial.dir/all] Error 2
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/tutorial.dir/all' failed
CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/tutorial.dir/rule' failed
mingw32-make.exe[1]: *** [CMakeFiles/tutorial.dir/rule] Error 2
mingw32-make.exe: *** [tutorial] Error 2
Makefile:117: recipe for target 'tutorial' failed

This is my CMakeLists.txt, in there I added gtk3 and its libraries, but when Im trying to compile, it has the errors mentioned before.

cmake_minimum_required(VERSION 3.7)
project(tutorial)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)

set(PKG_CONFIG_EXECUTABLE "C:/msys64/mingw64/bin/pkg-config.exe")

FIND_PACKAGE(PkgConfig REQUIRED)
PKG_CHECK_MODULES(GTK3 REQUIRED gtk+-3.0)

INCLUDE_DIRECTORIES(${GTK3_INCLUDE_DIRS})
LINK_DIRECTORIES(${GTK3_LIBRARY_DIRS})

add_executable(tutorial ${SOURCE_FILES})

ADD_DEFINITIONS(${GTK3_CFLAGS_OTHER})

TARGET_LINK_LIBRARIES(tutorial ${GTK3_LIBRARIES})


问:
Is there a way to write asp.net web service so they are easier to convert to WCF?
For example, I know that the WCF style web services don't rely so much on Session/Application/Request/Response as web services did. Are there any other gotchas I should keep in mind when writing web services today with the intention of making them WCF services as soon as my organization lets me use WCF?

I don't think I'm interested writing 2.0 webservices then using WCF's compatiblity mode, because that would be all the complexity without so much of the benefits of the new model.

答:
One suggestion that comes to my mind is to build your web services using Contract First Approach due to its conceptual similarities with wcf message/data contacts. Besides that MSDN has the following articles that are good guides to embark on a migration mission-

Easing into ASP.net WS to WCF
Migration

Migrating ASP.NET Web Services to WCF

Migrating WSE 3.0 Web Services to WCF

OwnerDisplayName: MatthewMartin

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Perpetualcoder


问:
SQL How to combine two tables into one
I'm getting the following error while trying to create a new table in SQL (Table3) using some columns from a current table (Table1) and combining with new columns from a second table (Table2): "Cannot find either column "a" or the user-defined function or aggregate "a.sum", or the name is ambiguous."

The code is the following:

```<code> select a. [Quarter]
  ,a. [Source Location]
  ,a. [Destination Location]
  ,a. sum([Total Volume]) as 'Total Volume'
  ,a. sum([Total Cost]) as 'Total Cost'
  ,b. [Source_City]
  ,b. [Source_State]
   Into [2016].[dbo].[Table3]
   FROM [2016].[dbo].[Table1] a
  ,[2016].[dbo].[Table2] b

  Where a. [Source Location]  = b. [Source_Location]

  Group By a. [Quarter]
  ,a. [Source Location]
  ,a. [Destination Location]
  ,b. [Source_City]
  ,b. [Source_State]
</code>```

The error is in reference to [Quarter]; however, [Quarter] is a defined column in Table 1. In addition [Source_Location] is a defined column in Table2.

Can anyone assist with how to resolve this problem and successfully combine these two tables into a third one?

Thank you for your help!

GK

答:
I'm not going to comment on other aspects of the formatting, but the issue is your use of sum().  You have:

```<code> a.sum([Total Volume]) as 'Total Volume',
 a.sum([Total Cost]) as 'Total Cost'
</code>```

The correct syntax is:

```<code> sum(a.[Total Volume]) as [Total Volume],
 sum(a.[Total Cost]) as [Total Cost]
</code>```

Title: SQL How to combine two tables into one

Body:
I'm getting the following error while trying to create a new table in SQL (Table3) using some columns from a current table (Table1) and combining with new columns from a second table (Table2): "Cannot find either column "a" or the user-defined function or aggregate "a.sum", or the name is ambiguous."

The code is the following:

 select a. [Quarter]
  ,a. [Source Location]
  ,a. [Destination Location]
  ,a. sum([Total Volume]) as 'Total Volume'
  ,a. sum([Total Cost]) as 'Total Cost'
  ,b. [Source_City]
  ,b. [Source_State]
   Into [2016].[dbo].[Table3]
   FROM [2016].[dbo].[Table1] a
  ,[2016].[dbo].[Table2] b

  Where a. [Source Location]  = b. [Source_Location]

  Group By a. [Quarter]
  ,a. [Source Location]
  ,a. [Destination Location]
  ,b. [Source_City]
  ,b. [Source_State]

The error is in reference to [Quarter]; however, [Quarter] is a defined column in Table 1. In addition [Source_Location] is a defined column in Table2.

Can anyone assist with how to resolve this problem and successfully combine these two tables into a third one?

Thank you for your help!

GK

Body:
I'm not going to comment on other aspects of the formatting, but the issue is your use of sum().  You have:

 a.sum([Total Volume]) as 'Total Volume',
 a.sum([Total Cost]) as 'Total Cost'

The correct syntax is:

 sum(a.[Total Volume]) as [Total Volume],
 sum(a.[Total Cost]) as [Total Cost]


问:
Using GPU to speed up BigInteger calculations
I am almost done with an algorithm that processes some very large integers (around the order of 2 raised to the power 100,000,000). This takes a couple of hours of highly-parallel code on a 16 core server with more than adequate memory since the algorithm is not memory intensive. I make use of the BigInteger class in .NET 4.

The specifics of the algorithm are not important but for context, following is a pretty exhaustive list of operations performed on these integers and some salient features of the algorithm:

Addition / Subtraction.

Multiplication of large numbers by small numbers.

Division of large numbers by very small numbers (e.g. 2).

Base 2 Log.

Base 2 Power.

Comparison of two or more large numbers (Min/Max).

No involvement whatsoever of prime numbers.

The algorithm is specifically designed not to be memory intensive since the performance hit of memory access is more than that of some smart on-the-fly calculations. Nevertheless, if memory access were to improve, the algorithm could benefit reasonably.

I have optimized the code as much as possible and profiling now shows only two bottlenecks:

Calculating base 2 Log for such large numbers.

Checking for pre-defined patterns of binary digits in these numbers. This is because the only way to access the BigInteger underlying data is by first using ToByteArray rather than in-place operations. Also, operating on byte-sized chunks does not help performance.

Considering memory access and Log operations, I started thinking about GPUs and whether I could offload some of the work effectively. I know very little about GPUs except that they are optimized for floating point operations.

My question is, using a library like GPU .NET, how can I process such large numbers on the GPU? Can I somehow make use of the floating point optimizations to calculate Log for such large numbers?

Looking for a starting point to form a strategy.

答:
If anyone finds it helpful, here is a Log Base 2 implementation for BigInteger that is much faster than using built in functions.</p>

```<code>private static BigInteger LogBase2(BigInteger num) {
    if (num <= Zero)
        return MinusOne; //does not support negative values.
    BigInteger i = Zero;
    while (!(num >>= 1).IsZero)
        i++;
    return i;
}
</code>```

Body:
If anyone finds it helpful, here is a Log Base 2 implementation for BigInteger that is much faster than using built in functions.

private static BigInteger LogBase2(BigInteger num) {
    if (num <= Zero)
        return MinusOne; //does not support negative values.
    BigInteger i = Zero;
    while (!(num >>= 1).IsZero)
        i++;
    return i;
}


问:
Generics with optional multiple bounds, e.g. List<? extends Integer OR String>
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

```<code>map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error
</code>```

It is not possible to declare a Map as below (to enforce compile time check).

```<code>void setProperties(Map<String, ? extends Integer || String> properties)
</code>```

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

```<code>void setProperties(Map<String, ?> properties)
</code>```

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

答:
You can’t declare a type variable to be either of two types. But you can create a helper class to encapsulate values not having a public constructor but factory methods for dedicated types:

```<code>public static final class Value {
    private final Object value;
    private Value(Object o) { value=o; }
}
public static Value value(int i) {
    // you could verify the range here
    return new Value(i);
}
public static Value value(String s) {
    // could reject null or invalid string contents here
    return new Value(s);
}
// these helper methods may be superseded by Java 9’s Map.of(...) methods
public static <K,V> Map<K,V> map(K k, V v) { return Collections.singletonMap(k, v); }
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2) {
    final HashMap<K, V> m = new HashMap<>();
    m.put(k1, v1);
    m.put(k2, v2);
    return m;
}
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2, K k3, V v3) {
    final Map<K, V> m = map(k1, v1, k2, v2);
    m.put(k3, v3);
    return m;
}
public void setProperties(Map<String, Value> properties) {
    Map<String,Object> actual;
    if(properties.isEmpty()) actual = Collections.emptyMap();
    else {
        actual = new HashMap<>(properties.size());
        for(Map.Entry<String, Value> e: properties.entrySet())
            actual.put(e.getKey(), e.getValue().value);
    }
    // proceed with actual map

}
</code>```

If you are using 3rd party libraries with map builders, you don’t need the map methods, they’re convenient for short maps only. With this pattern, you may call the method like

```<code>setProperties(map("mapLength", value(2), "timezone", value("UTC")));
</code>```

Since there are only the two Value factory methods for int and String, no other type can be passed to the map. Note that this also allows using int as parameter type, so widening of byte, short etc. to int is possible here.

Body:
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error

It is not possible to declare a Map as below (to enforce compile time check).

void setProperties(Map<String, ? extends Integer || String> properties)

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

void setProperties(Map<String, ?> properties)

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

Body:
You can’t declare a type variable to be either of two types. But you can create a helper class to encapsulate values not having a public constructor but factory methods for dedicated types:

public static final class Value {
    private final Object value;
    private Value(Object o) { value=o; }
}
public static Value value(int i) {
    // you could verify the range here
    return new Value(i);
}
public static Value value(String s) {
    // could reject null or invalid string contents here
    return new Value(s);
}
// these helper methods may be superseded by Java 9’s Map.of(...) methods
public static <K,V> Map<K,V> map(K k, V v) { return Collections.singletonMap(k, v); }
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2) {
    final HashMap<K, V> m = new HashMap<>();
    m.put(k1, v1);
    m.put(k2, v2);
    return m;
}
public static <K,V> Map<K,V> map(K k1, V v1, K k2, V v2, K k3, V v3) {
    final Map<K, V> m = map(k1, v1, k2, v2);
    m.put(k3, v3);
    return m;
}
public void setProperties(Map<String, Value> properties) {
    Map<String,Object> actual;
    if(properties.isEmpty()) actual = Collections.emptyMap();
    else {
        actual = new HashMap<>(properties.size());
        for(Map.Entry<String, Value> e: properties.entrySet())
            actual.put(e.getKey(), e.getValue().value);
    }
    // proceed with actual map

}

If you are using 3rd party libraries with map builders, you don’t need the map methods, they’re convenient for short maps only. With this pattern, you may call the method like

setProperties(map("mapLength", value(2), "timezone", value("UTC")));

Since there are only the two Value factory methods for int and String, no other type can be passed to the map. Note that this also allows using int as parameter type, so widening of byte, short etc. to int is possible here.


问:
pandas data and scikit learn
I have a pandas dataset with more than 300 predictors which are both continuous and categorical. The target variable is categorical and has values 0 or 1. I am going to perform logistic regression and I want to use the recursive feature selection from scikit learn module to obtain a shortlist of predictors. I know how to assign the target variable in the rfe.fit(x,y) function. How do I allocate all the other variables to x matrix?

thanks!

答:
You said that you want to use scikit-learn feature selector.

You pass your input matrix to a feature selector (e.g. SelectKBest) and then you can use the new features in the classifier.

```<code># X, y = your features and labels
sel = SelectKBest(chi2, k=2) # or any other feature selector
X_new = sel.fit_transform(X, y)

# clf = classifier of your choice
clf.fit(X_new, y)
</code>```

Title: pandas data and scikit learn

Body:
You said that you want to use scikit-learn feature selector.

You pass your input matrix to a feature selector (e.g. SelectKBest) and then you can use the new features in the classifier.

# X, y = your features and labels
sel = SelectKBest(chi2, k=2) # or any other feature selector
X_new = sel.fit_transform(X, y)

# clf = classifier of your choice
clf.fit(X_new, y)


问:
How can I generate this type pdf file by itextsharp?
I get a pdf  generate by itextsharp. In this pdf,all text cannot be selected, and when display, we don't need other fonts.  How can I generate this type pdf file? thks！

this file link: demo file

答:
I try following code,but in the pdf ,the "sample text" still can be selected. How I improve my code,thk.

string fileName = DateTime.Now.ToString();

```<code>    MemoryStream outputStream = new MemoryStream();//
    Document doc = new Document((PageSize.A5.Rotate()));//
    PdfDestination pdfDest = new PdfDestination(PdfDestination.FIT);
    PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
    doc.Open();

    PdfContentByte cb = writer.DirectContent;
    cb.BeginText();
    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 10f);
    cb.SetTextMatrix(1.2f, 9.5f);
    cb.ShowText("Sample text");
    cb.EndText();
    doc.Close();

    outputStream.Close();
    Response.ContentType = "application/pdf";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.OutputStream.Close();
</code>```

Body:
I try following code,but in the pdf ,the "sample text" still can be selected. How I improve my code,thk.

string fileName = DateTime.Now.ToString();

    MemoryStream outputStream = new MemoryStream();//
    Document doc = new Document((PageSize.A5.Rotate()));//
    PdfDestination pdfDest = new PdfDestination(PdfDestination.FIT);
    PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
    doc.Open();

    PdfContentByte cb = writer.DirectContent;
    cb.BeginText();
    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 10f);
    cb.SetTextMatrix(1.2f, 9.5f);
    cb.ShowText("Sample text");
    cb.EndText();
    doc.Close();

    outputStream.Close();
    Response.ContentType = "application/pdf";
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.OutputStream.Write(outputStream.GetBuffer(), 0, outputStream.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.OutputStream.Close();


问:
In Postgres, how do you extract the month (according to specific timezone) from a given TIMESTAMP WITH TIME ZONE column?
I have a column called login_timestamp, which is of type TIMESTAMP WITH TIME ZONE.

To retrieve the month for this timestamp, I would do: EXTRACT(MONTH FROM login_timestamp).

However, I would like to retrieve the month for a specific time zone (in my case, Pakistan), but can't figure out how to do that.

答:
Use the AT TIME ZONE construct:

```<code>SELECT EXTRACT(MONTH FROM login_timestamp AT TIME ZONE '-5');
</code>```

-5 is the constant offset for Pakistan.

Details:

Ignoring timezones altogether in Rails and PostgreSQL

Body:
Use the AT TIME ZONE construct:

SELECT EXTRACT(MONTH FROM login_timestamp AT TIME ZONE '-5');

-5 is the constant offset for Pakistan.

Details:

Ignoring timezones altogether in Rails and PostgreSQL


问:
How to upload .txt files into a database?
There is my database:

```<code>CREATE TABLE Persons (
ID int AUTO_INCREMENT,
Father varchar(255) NOT NULL,
Text varchar(255),
PRIMARY KEY (ID));
</code>```

And there is my .txt file:
(NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text')...

Ok this works for me now:

```<code>    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$text_file = file_get_contents('newfile.txt');
    $sql = "INSERT INTO `Persons` (`ID`, `Father`, `Text`) VALUES".$text_file;
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>
</code>```

And now how do i upload multiple txt files, like from multiple folders, or just one folder?

答:
Try it like this:

```<code>$text_file = file_get_contents('myTextFile.txt');
$sql = "INSERT INTO Persons (ID,Father,Text)VALUES".$text_file;
</code>```

This goes only if your textfile has only this content you posted (NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text').

Take care for SQL injection.

Body:
There is my database:

CREATE TABLE Persons (
ID int AUTO_INCREMENT,
Father varchar(255) NOT NULL,
Text varchar(255),
PRIMARY KEY (ID));

And there is my .txt file:
(NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text')...

Ok this works for me now:

    <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$text_file = file_get_contents('newfile.txt');
    $sql = "INSERT INTO `Persons` (`ID`, `Father`, `Text`) VALUES".$text_file;
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }

$conn = null;
?>

And now how do i upload multiple txt files, like from multiple folders, or just one folder?

Body:
Try it like this:

$text_file = file_get_contents('myTextFile.txt');
$sql = "INSERT INTO Persons (ID,Father,Text)VALUES".$text_file;

This goes only if your textfile has only this content you posted (NULL, '1', 'text'),(NULL, '2', 'text'),(NULL, '3', 'text').

Take care for SQL injection.


问:
CSS Selector for first-child after a page break
How can I style the first-child AFTER a page break has occurred?

The ultimate situation I'm facing is that I would like to style the first row of a table differently, and when printing the table spans multiple pages. I successfully used :first-child to style the first row. I also successfully avoided page breaks inside rows. I can not figure out how to style the first row on the second page of the table, though.

I'm familiar with the css pseudo class first-child (http://www.w3schools.com/cssref/sel_firstchild.asp), and I'm also familiar with the css print property page-break-inside (http://www.w3schools.com/cssref/pr_print_pagebi.asp). I'm unable to get them to play nicely together?

EDIT:
Adding code sample

```<code>HTML:
<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>

CSS:
table tr:first-child td { border-top: solid red 2px; }
table tr { page-break-inside: avoid }
</code>```

答:
I was also looking for a way to apply styles to only the first and last rows of a table over a page break, but maybe for a different use case.

I needed to give my whole table a border, but not on the table rows, just the outside. The easy way is to add a border to the table, but when a page break occurs, the borders aren't redrawn at the break.

My solution was to use a thead and tfoot, as these elements are repeated at every break. This gave me a full border around the table that obeyed page breaks.

You can modify this technique for your circumstances. Say if you wanted to change the styles of just the first row (and have it be consistent across page breaks), you just put that row in the thead or the tfoot depending on if you want the first or last row. You can even do this with an existing thead. Just give each thead tr a class so you know which is the main header, and which is a styled row.

There were a few caveats. The table footer had to have something within its tds otherwise it won't render. I added a   (which means "no breaking space") to the first td and then set the font-size on the td to 1px (Otherwise there will be a noticeable gap at the bottom of your table). The font size has to be applied directly to the td. A font size of 0 will not work either. It has to be non-zero.

Example

This example is for my use case, but you can modify it. You can also use as many columns as you want. I used one for simplicity. The thead and tfoot must have the same number of columns though.

```<code>.my-table tr {border-left: 1px; border-right: 1px;}
.my-table thead {border-top: 1px;}
.my-table tfoot {border-bottom: 1px;}

// must be applied to the td!!!
.my-table tfoot td {font-size: 1px;}

<table class="my-table">
  <thead><td></td></thead>
  <tbody>
    <tr><td>data</td></tr>
    <tr><td>data</td></tr>
  </tbody>
  <tfoot><td> </td></tfoot>
</table>
</code>```

Body:
How can I style the first-child AFTER a page break has occurred?

The ultimate situation I'm facing is that I would like to style the first row of a table differently, and when printing the table spans multiple pages. I successfully used :first-child to style the first row. I also successfully avoided page breaks inside rows. I can not figure out how to style the first row on the second page of the table, though.

I'm familiar with the css pseudo class first-child (http://www.w3schools.com/cssref/sel_firstchild.asp), and I'm also familiar with the css print property page-break-inside (http://www.w3schools.com/cssref/pr_print_pagebi.asp). I'm unable to get them to play nicely together?

EDIT:
Adding code sample

HTML:

CSS:
table tr:first-child td { border-top: solid red 2px; }
table tr { page-break-inside: avoid }

Body:
I was also looking for a way to apply styles to only the first and last rows of a table over a page break, but maybe for a different use case.

I needed to give my whole table a border, but not on the table rows, just the outside. The easy way is to add a border to the table, but when a page break occurs, the borders aren't redrawn at the break.

My solution was to use a thead and tfoot, as these elements are repeated at every break. This gave me a full border around the table that obeyed page breaks.

You can modify this technique for your circumstances. Say if you wanted to change the styles of just the first row (and have it be consistent across page breaks), you just put that row in the thead or the tfoot depending on if you want the first or last row. You can even do this with an existing thead. Just give each thead tr a class so you know which is the main header, and which is a styled row.

There were a few caveats. The table footer had to have something within its tds otherwise it won't render. I added a &nbsp; (which means "no breaking space") to the first td and then set the font-size on the td to 1px (Otherwise there will be a noticeable gap at the bottom of your table). The font size has to be applied directly to the td. A font size of 0 will not work either. It has to be non-zero.

Example

This example is for my use case, but you can modify it. You can also use as many columns as you want. I used one for simplicity. The thead and tfoot must have the same number of columns though.

.my-table tr {border-left: 1px; border-right: 1px;}
.my-table thead {border-top: 1px;}
.my-table tfoot {border-bottom: 1px;}

// must be applied to the td!!!
.my-table tfoot td {font-size: 1px;}

<table class="my-table">
  <thead><td></td></thead>
  <tbody>
    <tr><td>data</td></tr>
    <tr><td>data</td></tr>
  </tbody>
  <tfoot><td>&nbsp;</td></tfoot>
</table>


答:
Try applying AT TIME ZONE. Demo

```<code>select extract(month from cast ('2017-07-01 01:00+03' as TIMESTAMP WITH TIME ZONE) AT TIME ZONE '+08') as monthNo
</code>```

returns

```<code>    monthno
1   6
</code>```

Title: In Postgres, how do you extract the month (according to specific timezone) from a given TIMESTAMP WITH TIME ZONE column?

Body:
I have a column called login_timestamp, which is of type TIMESTAMP WITH TIME ZONE.

To retrieve the month for this timestamp, I would do: EXTRACT(MONTH FROM login_timestamp).

However, I would like to retrieve the month for a specific time zone (in my case, Pakistan), but can't figure out how to do that.

Body:
Try applying AT TIME ZONE. Demo

select extract(month from cast ('2017-07-01 01:00+03' as TIMESTAMP WITH TIME ZONE) AT TIME ZONE '+08') as monthNo

returns

    monthno
1   6


问:
Upon upgrade to chromedriver 2.30, error: cannot parse capability: chromeOptions/cannot parse mobileEmulation/'Apple iPhone 6' must be a valid device
In our Capybara/Rspec suite written in Ruby, we use a special driver to test touch interactions and mobile screen sizes.

This code works in Chromedriver 2.28

our setup in spec/spec_helper.rb

```<code>Capybara.register_driver :chrome_emulating_iphone_6 do |app|
  mobile_emulation = { "deviceName" => "Apple iPhone 6" }
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    'chromeOptions' => {
      'mobileEmulation' => mobile_emulation,
      'args' => [ ' --disable-web-security' ]
    }
  )
  Capybara::Selenium::Driver.new(app, :browser => :chrome,
                                 :desired_capabilities => caps)
end
</code>```

The above code worked in Chromedriver 2.28

checking exact version:

```<code>$ chromedriver -v
ChromeDriver 2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)
</code>```

Upon upgrading to Chromedriver 2.30, the code above breaks
the version after upgrading that seems to have broken the spec:

```<code>$ chromedriver -v
ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)
</code>```

the ruby spec fails with:

1) sister selector view Mobile Sister Selector should be on the page
     Failure/Error: visit "/products/boxer-briefs"

```<code> Selenium::WebDriver::Error::UnknownError:
   unknown error: cannot parse capability: chromeOptions
   from unknown error: cannot parse mobileEmulation
   from unknown error: 'Apple iPhone 6' must be a valid device
   from unknown error: must be a valid device
     (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)
</code>```

答: A full list of acceptable device names can be found here. Additional information about mobile device emulation can be found on the ChromeDriver web site at https://chromedriver.chromium.org/mobile-emulation.</p>

Body:
In our Capybara/Rspec suite written in Ruby, we use a special driver to test touch interactions and mobile screen sizes.

This code works in Chromedriver 2.28

our setup in spec/spec_helper.rb

Capybara.register_driver :chrome_emulating_iphone_6 do |app|
  mobile_emulation = { "deviceName" => "Apple iPhone 6" }
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    'chromeOptions' => {
      'mobileEmulation' => mobile_emulation,
      'args' => [ ' --disable-web-security' ]
    }
  )
  Capybara::Selenium::Driver.new(app, :browser => :chrome,
                                 :desired_capabilities => caps)
end

The above code worked in Chromedriver 2.28

checking exact version:

$ chromedriver -v
ChromeDriver 2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)

Upon upgrading to Chromedriver 2.30, the code above breaks
the version after upgrading that seems to have broken the spec:

$ chromedriver -v
ChromeDriver 2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262)

the ruby spec fails with:

1) sister selector view Mobile Sister Selector should be on the page
     Failure/Error: visit "/products/boxer-briefs"

 Selenium::WebDriver::Error::UnknownError:
   unknown error: cannot parse capability: chromeOptions
   from unknown error: cannot parse mobileEmulation
   from unknown error: 'Apple iPhone 6' must be a valid device
   from unknown error: must be a valid device
     (Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.11.6 x86_64)


问:
JQuery AutoComplete with ASP.Net
Below is my JavaScript

```<code>    <script>
    $(function () {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").attr("scrollTop", 0);
        }

        $("#city").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "getpostcodes.aspx",
                    dataType: "jsonp",
                    data: {
                        like: request.term
                    },
                    success: function (data) {
                        response($.map(data.RegionList, function (item) {
                                return {
                                label: item.Detail,
                                value: item.Detail
                            }
                        }));
                    }
                });
            },
            minLength: 2,
            select: function (event, ui) {
                log(ui.item ?
                "Selected: " + ui.item.label :
                "Nothing selected, input was " + this.value);
            },
            open: function () {
                $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            },
            close: function () {
                $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
            }
        });
    });
</script>
</code>```

And below is my JSON Returned by the server

```<code>{"RegionList":[{"Detail":"2250, GOSFORD"}]}
</code>```

But my auto complete doesn't show up the result? am i doing anything wrong?

答: What is the HTTP Status code response? I had problemas sometimes because I received the answer, but the status code was 500</p>

Title: JQuery AutoComplete with ASP.Net

Body:
Below is my JavaScript

And below is my JSON Returned by the server

{"RegionList":[{"Detail":"2250, GOSFORD"}]}

But my auto complete doesn't show up the result? am i doing anything wrong?


问:
Trying to create custom array adapter
So here im trying to create an custom array adapter , that can change images too, but when I do this it gives me error:

```<code>    public class CustomAdapter extends ArrayAdapter {
public CustomAdapter(@NonNull Context context, String [] food_text,int [] food_image) {
    super(context,R.layout.custom_row,food_text,food_image);
}
</code>```

But if I do this, it doesn't :

```<code>    public class CustomAdapter extends ArrayAdapter {
public CustomAdapter(@NonNull Context context, String [] food_text) {
    super(context,R.layout.custom_row,food_text);
}
</code>```

Here is my full code for custom adaptor:

```<code>public class CustomAdapter extends ArrayAdapter {

int[] food_image;

public CustomAdapter(@NonNull Context context, String [] food_text, int[] food_image) {
    super(context,R.layout.custom_row,food_text);
    this.food_image=food_image;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View foodView = inflater.inflate(R.layout.custom_row,parent,false);

    String singleFoodItem = (String) getItem(position);
    int SingleFoodImage = (int) getItem(position);
    TextView Food_text = (TextView) foodView.findViewById(R.id.Food_text);
    ImageView food_image = (ImageView) foodView.findViewById(R.id.food_image);

    Food_text.setText(singleFoodItem);
    food_image.setImageResource(SingleFoodImage);

    return foodView;
}
</code>```

}

And I get this error: java.lang.String cannot be cast to java.lang.Integer

答:
ArrayAdapter has specific constructors who's signature is defied in docs

```<code>ArrayAdapter(Context context, int resource)
ArrayAdapter(Context context, int resource, int textViewResourceId)
ArrayAdapter(Context context, int resource, T[] objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
ArrayAdapter(Context context, int resource, List<T> objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)
</code>```

since your constructor has no match against any of above , hence the error

so if you want some extra reference then use

```<code> public class CustomAdapter extends ArrayAdapter {
     int [] food_image;

    public CustomAdapter(@NonNull Context context, String [] food_text,int [] food_image) {
        super(context,R.layout.custom_row,food_text);
        this.food_image=food_image;
      }
  }
</code>```

We passed the String array String [] food_text and you cannot convert it to int here

```<code>int SingleFoodImage = (int) getItem(position); // error, string can't be converted to int
</code>```

So use this

```<code>int SingleFoodImage = food_image[position];
//  use the food_image

food_image.setImageResource(SingleFoodImage);
</code>```

Update : if you are planning to apply filtering soon or later then you will face issues with images position array mismatch so we need to create a POJO class

1.) Create a class

```<code>class Food{
    private int imageID;
    private String text;
    public Food(){}
    public Food(String oText ,int oImage ){ text=oText; imageID=oImage;}
    // getters and setters
    public int getImageID(){ return imageID;}
    public String getText(){ return text;}
}
</code>```

2.) Create a list of POJO objects and use this adapter

```<code>public class CustomAdapter extends ArrayAdapter<Food> {

   public CustomAdapter(@NonNull Context context, List<Food> items) {
        super(context,R.layout.custom_row,items);
      }

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View foodView = inflater.inflate(R.layout.custom_row,parent,false);

    Food singleFoodItem = getItem(position);
    TextView Food_text = (TextView) foodView.findViewById(R.id.Food_text);
    ImageView food_image = (ImageView) foodView.findViewById(R.id.food_image);

    Food_text.setText(singleFoodItem.getText());
    food_image.setImageResource(singleFoodItem.getImageID());
    return foodView;
}}
</code>```

example to create list

```<code>List<Food> foods = new ArrayList<>();
foods.add(new Food("Mango",R.drawable.image1));
</code>```

Title: Trying to create custom array adapter

Body:
So here im trying to create an custom array adapter , that can change images too, but when I do this it gives me error:

    public class CustomAdapter extends ArrayAdapter {
public CustomAdapter(@NonNull Context context, String [] food_text,int [] food_image) {
    super(context,R.layout.custom_row,food_text,food_image);
}

But if I do this, it doesn't :

    public class CustomAdapter extends ArrayAdapter {
public CustomAdapter(@NonNull Context context, String [] food_text) {
    super(context,R.layout.custom_row,food_text);
}

Here is my full code for custom adaptor:

public class CustomAdapter extends ArrayAdapter {

int[] food_image;

public CustomAdapter(@NonNull Context context, String [] food_text, int[] food_image) {
    super(context,R.layout.custom_row,food_text);
    this.food_image=food_image;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View foodView = inflater.inflate(R.layout.custom_row,parent,false);

    String singleFoodItem = (String) getItem(position);
    int SingleFoodImage = (int) getItem(position);
    TextView Food_text = (TextView) foodView.findViewById(R.id.Food_text);
    ImageView food_image = (ImageView) foodView.findViewById(R.id.food_image);

    Food_text.setText(singleFoodItem);
    food_image.setImageResource(SingleFoodImage);

    return foodView;
}

}

And I get this error: java.lang.String cannot be cast to java.lang.Integer

Body:
ArrayAdapter has specific constructors who's signature is defied in docs

ArrayAdapter(Context context, int resource)
ArrayAdapter(Context context, int resource, int textViewResourceId)
ArrayAdapter(Context context, int resource, T[] objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
ArrayAdapter(Context context, int resource, List<T> objects)
ArrayAdapter(Context context, int resource, int textViewResourceId, List<T> objects)

since your constructor has no match against any of above , hence the error

so if you want some extra reference then use

 public class CustomAdapter extends ArrayAdapter {
     int [] food_image;

    public CustomAdapter(@NonNull Context context, String [] food_text,int [] food_image) {
        super(context,R.layout.custom_row,food_text);
        this.food_image=food_image;
      }
  }

We passed the String array String [] food_text and you cannot convert it to int here

int SingleFoodImage = (int) getItem(position); // error, string can't be converted to int

So use this

int SingleFoodImage = food_image[position];
//  use the food_image

food_image.setImageResource(SingleFoodImage);

Update : if you are planning to apply filtering soon or later then you will face issues with images position array mismatch so we need to create a POJO class

1.) Create a class

class Food{
    private int imageID;
    private String text;
    public Food(){}
    public Food(String oText ,int oImage ){ text=oText; imageID=oImage;}
    // getters and setters
    public int getImageID(){ return imageID;}
    public String getText(){ return text;}
}

2.) Create a list of POJO objects and use this adapter

public class CustomAdapter extends ArrayAdapter<Food> {

   public CustomAdapter(@NonNull Context context, List<Food> items) {
        super(context,R.layout.custom_row,items);
      }

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(getContext());
    View foodView = inflater.inflate(R.layout.custom_row,parent,false);

    Food singleFoodItem = getItem(position);
    TextView Food_text = (TextView) foodView.findViewById(R.id.Food_text);
    ImageView food_image = (ImageView) foodView.findViewById(R.id.food_image);

    Food_text.setText(singleFoodItem.getText());
    food_image.setImageResource(singleFoodItem.getImageID());
    return foodView;
}}

example to create list

List<Food> foods = new ArrayList<>();
foods.add(new Food("Mango",R.drawable.image1));


问:
Junos creates console object instead of device object
I'm working on a zero-day configuration tool and I'm trying to deploy a configuration to a EX2200 switch. I'm using the PyEZ framework to connect to the device:

```<code>dev = Device(mode='serial', port='/dev/ttyUSB0',user="user",
               password="password", gather_facts=True)
dev.open()
</code>```

The object dev should be an instance of the class Device, but when I check its class with dev._ class _ it says class 'jnpr.junos.console.Console'.
I want to pass dev a configuration through a jinja2 template,

```<code>cu = Config(dev)
rsp=cu.load(template_path=template_path,
template_vars=config_data,merge=True)
</code>```

but it gives me the following error when loading the configuration:

```<code>Error loading config: 'Console' object has no attribute '_j2ldr'
</code>```

Any help would be greatly appreciated. Thanks!

答: This was a PyEZ bug which has been addressed by #753</p>

Body:
I'm working on a zero-day configuration tool and I'm trying to deploy a configuration to a EX2200 switch. I'm using the PyEZ framework to connect to the device:

dev = Device(mode='serial', port='/dev/ttyUSB0',user="user",
               password="password", gather_facts=True)
dev.open()

The object dev should be an instance of the class Device, but when I check its class with dev._ class _ it says class 'jnpr.junos.console.Console'.
I want to pass dev a configuration through a jinja2 template,

cu = Config(dev)
rsp=cu.load(template_path=template_path,
template_vars=config_data,merge=True)

but it gives me the following error when loading the configuration:

Error loading config: 'Console' object has no attribute '_j2ldr'

Any help would be greatly appreciated. Thanks!


答:
Documentation for this is under Date/Time Functions and Operators. Search that page for "at time zone".

```<code>select extract(month from login_timestamp at time zone 'Asia/Karachi');
</code>```

You can change the time zone for a single session or for a single transaction with set session... or set local.... For example, this changes the time zone for the current session.

```<code>set session time zone 'Asia/Karachi';
</code>```

Body:
Documentation for this is under Date/Time Functions and Operators. Search that page for "at time zone".

select extract(month from login_timestamp at time zone 'Asia/Karachi');

You can change the time zone for a single session or for a single transaction with set session... or set local.... For example, this changes the time zone for the current session.

set session time zone 'Asia/Karachi';


问:
Vector erase elements from range
Why programm stopped? That programm compile, but if i run, that he break, and give some message about iterator vector not incrementable.
What is wrong?</p>

```<code>int main()
{
    std::vector<int> vec;
    for (int i = 1; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.begin() + 5; itr < vec.end() - 5; ++itr)
        vec.erase(itr);
    for (const auto& itr : vec)
            std::cout << itr << std::endl;
    return 0;
}
</code>```

答:
You are wrong, because function erase don't anull iterators.
So you can do like that:

```<code>auto itr = vec.begin() + 5;
while (itr != vec.end() - 5) {
itr = vec.erase(itr);
}
</code>```

or more flexible ( without loop )

```<code>vec.erase(vec.begin() + 5, vec.end() - 5);
</code>```

Title: Vector erase elements from range

Body:
Why programm stopped? That programm compile, but if i run, that he break, and give some message about iterator vector not incrementable.
What is wrong?

int main()
{
    std::vector<int> vec;
    for (int i = 1; i <= 100; ++i)
        vec.push_back(i);
    for (auto itr = vec.begin() + 5; itr < vec.end() - 5; ++itr)
        vec.erase(itr);
    for (const auto& itr : vec)
            std::cout << itr << std::endl;
    return 0;
}

Body:
You are wrong, because function erase don't anull iterators.
So you can do like that:

auto itr = vec.begin() + 5;
while (itr != vec.end() - 5) {
itr = vec.erase(itr);
}

or more flexible ( without loop )

vec.erase(vec.begin() + 5, vec.end() - 5);


问:
Place holder in C#
```<code>   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }
</code>```

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

答:
```<code>Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
</code>```

Let me explain what everything means here:

```<code>Console.WriteLine(string text, params object[] obj);
</code>```

This is the method without values.
As you can see, you give it a string to print and a list of parameters.

When you run this method, it will be filled with the following values:

```<code>text = "your Add result  {0} + {1} is {2}";
obj  = new object[3];
obj[0] = num1;
obj[1] = num2;
obj[2] = num1+num2;
</code>```

Now what the formatter does is place the values of the objects that are returned by the ToString()-method at the given indexes.

Lets just assume that num1 is 4 and num2 is 5.

```<code>"your Add result  {0} + {1} is {2}"
</code>```

will be filled like this

```<code>"your Add result  4 + 5 is 9"
</code>```

But if you change the indexes to lets say

```<code>"your Add result  {2} + {0} is {1}"
</code>```

it will turn out like this

```<code>"your Add result  9 + 4 is 5"
</code>```

If you give the string indexes that do not exist in the array (like e.g. {7}) the application will crash, stating that the requested index, in this case 7, is null. This will be a System.FormatException.

It would be the same if you are trying to get the value of index 7 in an array with a size of 4 elements.

Title: Place holder in C#

Body:
   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace switch_calculator
    {
        class Program
        {
            static void Main(string[] args)
            {
                double num1, num2;
                char opt;

                Console.WriteLine("Enter num1");
                num1 = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter num2");
                num2 = Convert.ToInt32(Console.ReadLine());

       Console.WriteLine("Select the operation you would like to perform" );
       Console.WriteLine("Press \n 'A' for Add \n 'S' for subtraction
\n 'D' for Division \n 'M' for multiplicatiion \n 'R' for Remainder");

                opt = Convert.ToChar(Console.ReadLine());
                switch(opt)
                {
                    case 'A':

                        Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);
                        break;
                }

                Console.ReadLine();

            }
        }
    }

Here it's my C# code , I'm very new to programming I was just
wondering can I assign place holder value to other number like
{0},{7} or {1},{3} instead of {0},{1} in the switch case statement
case A ?? can someone pls explain the place holder concept here ?

Body:
Console.WriteLine("your Add result  {0} + {1} is {2}", num1, num2, num1+num2);

Let me explain what everything means here:

Console.WriteLine(string text, params object[] obj);

This is the method without values.
As you can see, you give it a string to print and a list of parameters.

When you run this method, it will be filled with the following values:

text = "your Add result  {0} + {1} is {2}";
obj  = new object[3];
obj[0] = num1;
obj[1] = num2;
obj[2] = num1+num2;

Now what the formatter does is place the values of the objects that are returned by the ToString()-method at the given indexes.

Lets just assume that num1 is 4 and num2 is 5.

"your Add result  {0} + {1} is {2}"

will be filled like this

"your Add result  4 + 5 is 9"

But if you change the indexes to lets say

"your Add result  {2} + {0} is {1}"

it will turn out like this

"your Add result  9 + 4 is 5"

If you give the string indexes that do not exist in the array (like e.g. {7}) the application will crash, stating that the requested index, in this case 7, is null. This will be a System.FormatException.

It would be the same if you are trying to get the value of index 7 in an array with a size of 4 elements.


问:
BeanNotOfRequiredTypeException due to autowired fields
I'm still new to Spring MVC and while building my test project, I got this message from Tomcat logs:

```<code>SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'divisionController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    ...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:360)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
</code>```

I have two rolle services for user and admin with there interfaces:

```<code>package employee.service;

import employee.model.EmployeeDiv;
import employee.model.EmployeeInfo;
import employee.model.UserInfo;

import java.util.List;

/**
 *
 * @author serge
 */

public interface AdminService extends UserService {

     //  !!!! for register & udate of Employee use String type birthday !!!!

    /*
     * Employee
     */
    public EmployeeInfo registerEmployee(EmployeeInfo employeeInfo);

    public EmployeeInfo updateEmployee(EmployeeInfo employeeInfo);

    public EmployeeInfo findEmployeeByID(Integer id);

    /*
     * Division
     */
    public EmployeeDiv registerDivision(EmployeeDiv division);

    public EmployeeDiv updateDivision(EmployeeDiv division);

    public List<EmployeeDiv> findAllDivisions();

    public List<EmployeeDiv> findDivisionsByName(EmployeeDiv division);

    public EmployeeDiv findDivisionsById(Integer id);

    /*
     * Login
     */
    public UserInfo registerUser(UserInfo user);

    public UserInfo updateUser(UserInfo user);

    public List<UserInfo> findAllUsesrs();

    public List<UserInfo> findUsesrByLogin(UserInfo user);

    public UserInfo findUsesrById(Integer id);
}
</code>```

This is AdminServiceImpl:

```<code>package employee.service.impl;

import employee.DAO.EmployeeDivDAO;
import employee.DAO.EmployeeInfoDAO;
import employee.DAO.UserDAO;
import employee.model.EmployeeDiv;
import employee.model.EmployeeInfo;
import employee.model.UserInfo;
import employee.service.AdminService;
import employee.validation.ParsingDate;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author serge
 *
 * Admin level
 *
 * Service for processing employee, divisions, userslogin
 */

//@Repository("adminService")
@Service("adminService")
@Transactional
public class AdminServiceImpl extends UserServiceImpl implements AdminService {

    protected static Logger adminLogger = Logger.getLogger("service");
    private EmployeeDivDAO emplDivDAO;
    private UserDAO userDAO;
    private EmployeeInfoDAO emplInfoDAO;

    @Autowired
    @Override
    public void setEmployeeDao(EmployeeInfoDAO emplInfoDAO) {
        this.emplInfoDAO = emplInfoDAO;
    }

    @Autowired
    public void setEmployeeDao(EmployeeDivDAO emplDivDAO) {
        this.emplDivDAO = emplDivDAO;
    }

    @Autowired
    public void setUserDao(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public AdminServiceImpl() {

        initTestEmployee();
    }

    /**
     * Initialize EmployeeInfo test
     */
    @Transactional
    @Secured("ROLE_ADMIN")
    private EmployeeInfo initTestEmployee() {

        adminLogger.debug("saving testEmployee");

        EmployeeInfo employeeInfo = new EmployeeInfo();
        ParsingDate date = new ParsingDate();
        employeeInfo.setFirstName("Petr");
        employeeInfo.setLastName("Ivanenko");
        employeeInfo.setEmpDiv("second");
        employeeInfo.setBirthdate(date.parseDate("1981-10-03"));
        employeeInfo.setSalary(3500);
        employeeInfo.setActive(true);

        return employeeInfo;
    }

    /**
     * registrating new Employee Information
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo registerEmployee(EmployeeInfo employeeInfo) {

        adminLogger.debug("registrating new Employee");

        try {

            emplInfoDAO.save(employeeInfo);

        } catch (NullPointerException e) {
        }
        return employeeInfo;
    }

    /**
     * updating Employee Information
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo updateEmployee(EmployeeInfo employeeInfo) {

        adminLogger.debug("updating Employee with id: " + employeeInfo.getId());
        try {

            emplInfoDAO.update(employeeInfo);

        } catch (NullPointerException e) {
        }
        return employeeInfo;
    }

    /**
     * Retrieving Employee Information by id
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo findEmployeeByID(Integer id) {

        adminLogger.debug("Retrieving Employee with id= " + id);
        EmployeeInfo employeeInfo = new EmployeeInfo();
        employeeInfo.setId(id);
        emplInfoDAO.find(employeeInfo);
        return employeeInfo;
    }

    /**
     * registrating new Employee Division
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv registerDivision(EmployeeDiv division) {

        adminLogger.debug("registrating new Division");
        try {

            emplDivDAO.save(division);

        } catch (NullPointerException e) {
        }
        return division;
    }

    /**
     * updating Employee Division
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv updateDivision(EmployeeDiv division) {

        adminLogger.debug("updating Division with id: " + division.getId());
        try {

            emplDivDAO.update(division);

        } catch (NullPointerException e) {
        }
        return division;
    }

    /**
     * Retrieving all Employee Divisions
     *
     * @return List of EmployeeDiv objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<EmployeeDiv> findAllDivisions() {

        adminLogger.debug("Retrieving all divisions");
        return emplDivDAO.findAll();
    }

    /**
     * Retrieving all Employee Divisions by name
     *
     * @return List of EmployeeDiv objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<EmployeeDiv> findDivisionsByName(EmployeeDiv division) {
        String empDiv = "empDiv";

        adminLogger.debug("Retrieving Divisions by name: " + division.getEmpDiv());
        return emplDivDAO.findAllByParam(empDiv, division.getEmpDiv());
    }

     /**
     * Retrieving Employee Divisions by id
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv findDivisionsById(Integer id) {

        adminLogger.debug("Retrieving Division with id= " + id);
        EmployeeDiv employeeDiv = new EmployeeDiv();
        employeeDiv.setId(id);
        emplInfoDAO.find(employeeDiv);
        return employeeDiv;
    }

    /**
     * registrating new User Information
     *
     * @return UserInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo registerUser(UserInfo user) {

        adminLogger.debug("registrating new User");
        try {

            userDAO.save(user);

        } catch (NullPointerException e) {
        }
        return user;
    }

    /**
     * updating new User Information
     *
     * @return UserInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo updateUser(UserInfo user) {

        adminLogger.debug("updating User with id: " + user.getId());
        try {

            userDAO.update(user);

        } catch (NullPointerException e) {
        }
        return user;
    }

    /**
     * retriviting all Users
     *
     * @return List of UserInfo objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<UserInfo> findAllUsesrs() {

        adminLogger.debug("Retrieving all Users");
        return userDAO.findAll();
    }

    /**
     * retriving all Users by login
     *
     * @return List of UserInfo objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<UserInfo> findUsesrByLogin(UserInfo user) {
        String login = "login";

        adminLogger.debug("Retrieving User with login: " + login);
        return userDAO.findAllByParam(login, user.getLogin());
    }

    /**
     * Retrieving Employee Divisions by id
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo findUsesrById(Integer id) {

        adminLogger.debug("Retrieving Division with id= " + id);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        emplInfoDAO.find(userInfo);
        return userInfo;
    }
}
</code>```

This is applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!-- Activates annotations -->

    <context:annotation-config />

    <!-- Scans for annotated components in base-package-->

    <context:component-scan base-package="employee" />

    <bean class="employee.service.impl.AdminServiceImpl"/>
    <bean class="employee.service.impl.UserServiceImpl"/>
    <!--bean class="employee.DAO.impl.EmployeeInfoDAOImpl"/>
    <bean class="employee.DAO.impl.EmployeeDivDAOImpl"/>
    <bean class="employee.DAO.impl.UserDAOImpl"/-->

    <!-- for Spring Jackson JSON support  -->

    <mvc:annotation-driven/>

    <!-- Shared Hibernate SessionFactory in a Spring application context. -->

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <!--property name="dataSource">
            <ref bean="dataSource"/>
        </property-->

        <property name="annotatedClasses">
            <list>
                <value>employee.model.UserInfo</value>
                <value>employee.model.EmployeeInfo</value>
                <value>employee.model.EmployeeDiv</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <!-- for database, imports the properties from database.properties -->

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:database.properties"/>
    </bean>
</beans>
</code>```

Please tell me what is the problem with this bean name, I understand that is AOP problem:

```<code>Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]
</code>```

how I can fix it?

I use AdminServiceImpl in Controllers:

```<code>package employee.controller;

import employee.model.EmployeeDiv;
import employee.service.impl.AdminServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

/**
 * @author serge
 *
 * Handles and retrieves division related requests
 */
@Controller
@RequestMapping("/division")
public class DivisionController {

    protected static Logger logger = Logger.getLogger("controller");
    @Resource(name = "adminService")
    private AdminServiceImpl adminService;

    /**
     * Handles and retrieves a /WEB-INF/jsp/divisionpage.jsp
     *
     * containing all division
     *
     * @return the name of the JSP page
     */
    @RequestMapping(method = RequestMethod.GET)
    public String getAllPage(Model model) {
        logger.debug("Received request to show all division page");

        // Retrieve all division and attach to model
        model.addAttribute("division", adminService.findAllDivisions());
        return "divisionpage";
    } ....
</code>```

答:
When your service class implements some interface, spring by default takes proxy by JDK, that's why you get that error, so you can solve that problem whether using @Autowired over the interface or enabling the CGLIB proxy.

I solved that problem enabling CGLIB proxy using proxy-target-class attribute in my spring  application context

```<code><tx:annotation-driven proxy-target-class="true"
        transaction-manager="transactionManager" />
</code>```

Body:
I'm still new to Spring MVC and while building my test project, I got this message from Tomcat logs:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'divisionController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    ...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:360)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)

I have two rolle services for user and admin with there interfaces:

package employee.service;

import employee.model.EmployeeDiv;
import employee.model.EmployeeInfo;
import employee.model.UserInfo;

import java.util.List;

/**
 *
 * @author serge
 */

public interface AdminService extends UserService {

     //  !!!! for register & udate of Employee use String type birthday !!!!

    /*
     * Employee
     */
    public EmployeeInfo registerEmployee(EmployeeInfo employeeInfo);

    public EmployeeInfo updateEmployee(EmployeeInfo employeeInfo);

    public EmployeeInfo findEmployeeByID(Integer id);

    /*
     * Division
     */
    public EmployeeDiv registerDivision(EmployeeDiv division);

    public EmployeeDiv updateDivision(EmployeeDiv division);

    public List<EmployeeDiv> findAllDivisions();

    public List<EmployeeDiv> findDivisionsByName(EmployeeDiv division);

    public EmployeeDiv findDivisionsById(Integer id);

    /*
     * Login
     */
    public UserInfo registerUser(UserInfo user);

    public UserInfo updateUser(UserInfo user);

    public List<UserInfo> findAllUsesrs();

    public List<UserInfo> findUsesrByLogin(UserInfo user);

    public UserInfo findUsesrById(Integer id);
}

This is AdminServiceImpl:

package employee.service.impl;

import employee.DAO.EmployeeDivDAO;
import employee.DAO.EmployeeInfoDAO;
import employee.DAO.UserDAO;
import employee.model.EmployeeDiv;
import employee.model.EmployeeInfo;
import employee.model.UserInfo;
import employee.service.AdminService;
import employee.validation.ParsingDate;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author serge
 *
 * Admin level
 *
 * Service for processing employee, divisions, userslogin
 */

//@Repository("adminService")
@Service("adminService")
@Transactional
public class AdminServiceImpl extends UserServiceImpl implements AdminService {

    protected static Logger adminLogger = Logger.getLogger("service");
    private EmployeeDivDAO emplDivDAO;
    private UserDAO userDAO;
    private EmployeeInfoDAO emplInfoDAO;

    @Autowired
    @Override
    public void setEmployeeDao(EmployeeInfoDAO emplInfoDAO) {
        this.emplInfoDAO = emplInfoDAO;
    }

    @Autowired
    public void setEmployeeDao(EmployeeDivDAO emplDivDAO) {
        this.emplDivDAO = emplDivDAO;
    }

    @Autowired
    public void setUserDao(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public AdminServiceImpl() {

        initTestEmployee();
    }

    /**
     * Initialize EmployeeInfo test
     */
    @Transactional
    @Secured("ROLE_ADMIN")
    private EmployeeInfo initTestEmployee() {

        adminLogger.debug("saving testEmployee");

        EmployeeInfo employeeInfo = new EmployeeInfo();
        ParsingDate date = new ParsingDate();
        employeeInfo.setFirstName("Petr");
        employeeInfo.setLastName("Ivanenko");
        employeeInfo.setEmpDiv("second");
        employeeInfo.setBirthdate(date.parseDate("1981-10-03"));
        employeeInfo.setSalary(3500);
        employeeInfo.setActive(true);

        return employeeInfo;
    }

    /**
     * registrating new Employee Information
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo registerEmployee(EmployeeInfo employeeInfo) {

        adminLogger.debug("registrating new Employee");

        try {

            emplInfoDAO.save(employeeInfo);

        } catch (NullPointerException e) {
        }
        return employeeInfo;
    }

    /**
     * updating Employee Information
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo updateEmployee(EmployeeInfo employeeInfo) {

        adminLogger.debug("updating Employee with id: " + employeeInfo.getId());
        try {

            emplInfoDAO.update(employeeInfo);

        } catch (NullPointerException e) {
        }
        return employeeInfo;
    }

    /**
     * Retrieving Employee Information by id
     *
     * @return EmployeeInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeInfo findEmployeeByID(Integer id) {

        adminLogger.debug("Retrieving Employee with id= " + id);
        EmployeeInfo employeeInfo = new EmployeeInfo();
        employeeInfo.setId(id);
        emplInfoDAO.find(employeeInfo);
        return employeeInfo;
    }

    /**
     * registrating new Employee Division
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv registerDivision(EmployeeDiv division) {

        adminLogger.debug("registrating new Division");
        try {

            emplDivDAO.save(division);

        } catch (NullPointerException e) {
        }
        return division;
    }

    /**
     * updating Employee Division
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv updateDivision(EmployeeDiv division) {

        adminLogger.debug("updating Division with id: " + division.getId());
        try {

            emplDivDAO.update(division);

        } catch (NullPointerException e) {
        }
        return division;
    }

    /**
     * Retrieving all Employee Divisions
     *
     * @return List of EmployeeDiv objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<EmployeeDiv> findAllDivisions() {

        adminLogger.debug("Retrieving all divisions");
        return emplDivDAO.findAll();
    }

    /**
     * Retrieving all Employee Divisions by name
     *
     * @return List of EmployeeDiv objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<EmployeeDiv> findDivisionsByName(EmployeeDiv division) {
        String empDiv = "empDiv";

        adminLogger.debug("Retrieving Divisions by name: " + division.getEmpDiv());
        return emplDivDAO.findAllByParam(empDiv, division.getEmpDiv());
    }

     /**
     * Retrieving Employee Divisions by id
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public EmployeeDiv findDivisionsById(Integer id) {

        adminLogger.debug("Retrieving Division with id= " + id);
        EmployeeDiv employeeDiv = new EmployeeDiv();
        employeeDiv.setId(id);
        emplInfoDAO.find(employeeDiv);
        return employeeDiv;
    }

    /**
     * registrating new User Information
     *
     * @return UserInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo registerUser(UserInfo user) {

        adminLogger.debug("registrating new User");
        try {

            userDAO.save(user);

        } catch (NullPointerException e) {
        }
        return user;
    }

    /**
     * updating new User Information
     *
     * @return UserInfo object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo updateUser(UserInfo user) {

        adminLogger.debug("updating User with id: " + user.getId());
        try {

            userDAO.update(user);

        } catch (NullPointerException e) {
        }
        return user;
    }

    /**
     * retriviting all Users
     *
     * @return List of UserInfo objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<UserInfo> findAllUsesrs() {

        adminLogger.debug("Retrieving all Users");
        return userDAO.findAll();
    }

    /**
     * retriving all Users by login
     *
     * @return List of UserInfo objects
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public List<UserInfo> findUsesrByLogin(UserInfo user) {
        String login = "login";

        adminLogger.debug("Retrieving User with login: " + login);
        return userDAO.findAllByParam(login, user.getLogin());
    }

    /**
     * Retrieving Employee Divisions by id
     *
     * @return EmployeeDiv object
     */
    @Override
    @Transactional
    @Secured("ROLE_ADMIN")
    public UserInfo findUsesrById(Integer id) {

        adminLogger.debug("Retrieving Division with id= " + id);
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        emplInfoDAO.find(userInfo);
        return userInfo;
    }
}

This is applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <context:annotation-config />

    <context:component-scan base-package="employee" />

    <bean class="employee.service.impl.AdminServiceImpl"/>
    <bean class="employee.service.impl.UserServiceImpl"/>

    <mvc:annotation-driven/>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <property name="annotatedClasses">
            <list>
                <value>employee.model.UserInfo</value>
                <value>employee.model.EmployeeInfo</value>
                <value>employee.model.EmployeeDiv</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:database.properties"/>
    </bean>
</beans>

Please tell me what is the problem with this bean name, I understand that is AOP problem:

Bean named 'adminService' must be of type [employee.service.impl.AdminServiceImpl], but was actually of type [$Proxy52]

how I can fix it?

I use AdminServiceImpl in Controllers:

package employee.controller;

import employee.model.EmployeeDiv;
import employee.service.impl.AdminServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;

/**
 * @author serge
 *
 * Handles and retrieves division related requests
 */
@Controller
@RequestMapping("/division")
public class DivisionController {

    protected static Logger logger = Logger.getLogger("controller");
    @Resource(name = "adminService")
    private AdminServiceImpl adminService;

    /**
     * Handles and retrieves a /WEB-INF/jsp/divisionpage.jsp
     *
     * containing all division
     *
     * @return the name of the JSP page
     */
    @RequestMapping(method = RequestMethod.GET)
    public String getAllPage(Model model) {
        logger.debug("Received request to show all division page");

        // Retrieve all division and attach to model
        model.addAttribute("division", adminService.findAllDivisions());
        return "divisionpage";
    } ....

Body:
When your service class implements some interface, spring by default takes proxy by JDK, that's why you get that error, so you can solve that problem whether using @Autowired over the interface or enabling the CGLIB proxy.

I solved that problem enabling CGLIB proxy using proxy-target-class attribute in my spring  application context

<tx:annotation-driven proxy-target-class="true"
        transaction-manager="transactionManager" />


问:
Expressjs static javascript file not loading
I'm setting up express server with create-react-app.

AT console I'm getting

Uncaught SyntaxError: Unexpected token <                    bundle.js:1

When I click on error it shows me homepage html.
While using morgan logger its giving me 200 ok.

GET /static/js/bundle.js 304 1.145 ms - -

Also when i view source click on css link it shows me css while click on javascript link it shows me blank page(homepage html).

Here is the the server code.

```<code>var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require ('path');

var data = {};

express()
    .use(logger('dev'))
    .use(express.static(path.join(__dirname, 'flashcard-app/build')))

    .use(bodyParser.json())
    .get('/api/test', (req, res) => res.json("Great news every thing is working fine."))
    .get('/api/data', (req, res) => res.json(data))
    .post('/api/data', (req, res) => res.json(data = req.body))
    .get('*', function(req, res) {
        console.log('serving path:', path.join(__dirname+'/flashcard-app/build/index.html'));
         res.sendFile(path.join(__dirname, 'flashcard-app/build/index.html'));
    })
    .listen(3333, function(){
        console.log('server running at 3333');
    });
</code>```

Also this is custom server.js file not one that provided by express-generator. I'm running by node server_old.js instead of using ./bin/www

Help comment tips appreciated.

答:
You are trying to fetch /static/js/bundle.js, but there is no bundle.js in static/js.

I think you are trying to use index.html that tries to bundle.js while your webpack config builds main.[hash].js

Body:
I'm setting up express server with create-react-app.

AT console I'm getting

Uncaught SyntaxError: Unexpected token <                    bundle.js:1

When I click on error it shows me homepage html.
While using morgan logger its giving me 200 ok.

GET /static/js/bundle.js 304 1.145 ms - -

Also when i view source click on css link it shows me css while click on javascript link it shows me blank page(homepage html).

Here is the the server code.

var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require ('path');

var data = {};

express()
    .use(logger('dev'))
    .use(express.static(path.join(__dirname, 'flashcard-app/build')))

    .use(bodyParser.json())
    .get('/api/test', (req, res) => res.json("Great news every thing is working fine."))
    .get('/api/data', (req, res) => res.json(data))
    .post('/api/data', (req, res) => res.json(data = req.body))
    .get('*', function(req, res) {
        console.log('serving path:', path.join(__dirname+'/flashcard-app/build/index.html'));
         res.sendFile(path.join(__dirname, 'flashcard-app/build/index.html'));
    })
    .listen(3333, function(){
        console.log('server running at 3333');
    });

Also this is custom server.js file not one that provided by express-generator. I'm running by node server_old.js instead of using ./bin/www

Help comment tips appreciated.