问:
javascript - functions and equations confusion
```<code> var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2
</code>```

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!

答:
If you want an equation :)

function sumOfNumbersDivisibleBy3Or5(n) {
   const by3 = Math.floor(n/3),
         by5 = Math.floor(n/5),
         by3And5 = Math.floor(n/3/5);

  return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}

console.log(sumOfNumbersDivisibleBy3Or5(17))```

Body:
 var number = prompt('Input a number!');
 var n = number;
   function getList() {

 for (var n = 1; n <= 17; n++) {

   if (n % 3 == 0 || n % 5 == 0)
     console.log (n);
   }
 }

console.log(getList());
console.log((n*(n+1))/2);

//equation for summation: (n*(n+1))/2

I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.

I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?

The answer is supposed to be 60. Any clue? Thanks!


来源: stackexchange

问:
select large table in laravel 5
I would like to know how to get very large number of rows in the controller, and dispay it to the view. my current code looks likes below.

this is the controller.

```<code>$users = \App\Models\User::select ('id','first_name','last_name','created_at')
            ->where('friend_id', '=', 0)
            ->orderBy('created_at')->get();

return view('layouts.users.friends', compact('users'));
</code>```

this is the view.

```<code>@if (!empty($users))
                    @foreach($users as $user)
                        <tr>
                            <?php $count++ ?>
                            <td>
                                {!! $user->id !!}
                            </td>
                            <td>{!! $user->first_name .'   ' .$user->last_name !!}</td>
                            <td> {!! $user->created_at->format("d-m-y") !!} </td>
                        </tr>
                    @endforeach
                @endif
</code>```

Now i have 40,000 rows in the table, and when try to get the view error code 500, outof memory. I have to get all the rows. Please advice me what should be done. here. I have heard about laravel 5 chunk. but dont know who to display it on the view. Please help.

答:
If you just need to show data then, you can use pagination. You can see official documentation for pagination here.

If you need other complex calculation and operations you need some loop optimization methods.

ContentLicense: CC BY-SA 3.0

Title: select large table in laravel 5

Body:
I would like to know how to get very large number of rows in the controller, and dispay it to the view. my current code looks likes below.

this is the controller.

$users = \App\Models\User::select ('id','first_name','last_name','created_at')
            ->where('friend_id', '=', 0)
            ->orderBy('created_at')->get();

return view('layouts.users.friends', compact('users'));

this is the view.

@if (!empty($users))
                    @foreach($users as $user)

                            <?php $count++ ?>

                                {!! $user->id !!}

                            {!! $user->first_name .'   ' .$user->last_name !!}
                             {!! $user->created_at->format("d-m-y") !!}

                    @endforeach
                @endif

Now i have 40,000 rows in the table, and when try to get the view error code 500, outof memory. I have to get all the rows. Please advice me what should be done. here. I have heard about laravel 5 chunk. but dont know who to display it on the view. Please help.


问:
How to build SOCI with PostgreSQL?
I'm trying to build the SOCI library to run with PostgreSQL. I followed these steps:

Install PostgreSQL in Ubutu 15.10

Download SOCI source code

Extract SOCI code

I then run the following commands:

```<code>mkdir build
cd build
cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_POSTGRESQL=ON -DPOSTGRESQL_INCLUDE_DIR=/usr/local/pgsql/include -DPOSTGRESQL_LIBRARIES=/usr/local/pgsql/lib ../soci
</code>```

At this point, CMake gave the following warnings:

```<code>WARNING: Target "soci_postgresql" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
</code>```

Persisting with the build, I then ran make, which fails with the following error:

```<code>[ 98%] Building CXX object tests/postgresql/CMakeFiles/soci_postgresql_test.dir/test-postgresql.cpp.o
Linking CXX executable ../../bin/soci_postgresql_test
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultStatus'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQgetvalue'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQclear'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQserverVersion'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultErrorMessage'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexec'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_lseek'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfsize'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQgetisnull'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQerrorMessage'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_open'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexecPrepared'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQftype'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_close'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexecParams'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfname'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQconnectdb'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQstatus'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQntuples'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultErrorField'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfformat'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_read'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfinish'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQprepare'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_write'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQcmdTuples'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQnfields'
collect2: error: ld returned 1 exit status
tests/postgresql/CMakeFiles/soci_postgresql_test.dir/build.make:89: recipe for target 'bin/soci_postgresql_test' failed
make[2]: *** [bin/soci_postgresql_test] Error 1
CMakeFiles/Makefile2:609: recipe for target 'tests/postgresql/CMakeFiles/soci_postgresql_test.dir/all' failed
make[1]: *** [tests/postgresql/CMakeFiles/soci_postgresql_test.dir/all] Error 2
Makefile:126: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

Any idea what the cause of the CMake warnings and build error might be?

答:
I got the right answer from the github, here is link.
The following reply is largely taken from there, but repeated here for convenience (with cleanup and clarification):

-DPOSTGRESQL_LIBRARIES=/usr/local/psql/lib should point to the libraries, not directories.

This is what the following warning already highlights:

WARNING: Target "soci_postgresql" requests linking to directory
  "/usr/local/postgresql/lib"

Try the following command instead (you may need to delete your CMakeCache.txt from the build directory first as well):

```<code>cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_POSTGRESQL=ON ../soci
</code>```

On Linux systems where "postgresql-devel.x86_64 : PostgreSQL development header files and libraries" is installed, this command should be enough.

Title: How to build SOCI with PostgreSQL?

Body:
I'm trying to build the SOCI library to run with PostgreSQL. I followed these steps:

Install PostgreSQL in Ubutu 15.10

Download SOCI source code

Extract SOCI code

I then run the following commands:

mkdir build
cd build
cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_POSTGRESQL=ON -DPOSTGRESQL_INCLUDE_DIR=/usr/local/pgsql/include -DPOSTGRESQL_LIBRARIES=/usr/local/pgsql/lib ../soci

At this point, CMake gave the following warnings:

WARNING: Target "soci_postgresql" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.
WARNING: Target "soci_postgresql_test_static" requests linking to directory "/usr/local/pgsql/lib".  Targets may link only to libraries.  CMake is dropping the item.

Persisting with the build, I then ran make, which fails with the following error:

[ 98%] Building CXX object tests/postgresql/CMakeFiles/soci_postgresql_test.dir/test-postgresql.cpp.o
Linking CXX executable ../../bin/soci_postgresql_test
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultStatus'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQgetvalue'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQclear'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQserverVersion'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultErrorMessage'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexec'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_lseek'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfsize'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQgetisnull'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQerrorMessage'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_open'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexecPrepared'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQftype'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_close'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQexecParams'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfname'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQconnectdb'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQstatus'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQntuples'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQresultErrorField'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfformat'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_read'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQfinish'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQprepare'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `lo_write'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQcmdTuples'
../../lib/libsoci_postgresql.so.4.0.0: undefined reference to `PQnfields'
collect2: error: ld returned 1 exit status
tests/postgresql/CMakeFiles/soci_postgresql_test.dir/build.make:89: recipe for target 'bin/soci_postgresql_test' failed
make[2]: *** [bin/soci_postgresql_test] Error 1
CMakeFiles/Makefile2:609: recipe for target 'tests/postgresql/CMakeFiles/soci_postgresql_test.dir/all' failed
make[1]: *** [tests/postgresql/CMakeFiles/soci_postgresql_test.dir/all] Error 2
Makefile:126: recipe for target 'all' failed
make: *** [all] Error 2

Any idea what the cause of the CMake warnings and build error might be?

Body:
I got the right answer from the github, here is link.
The following reply is largely taken from there, but repeated here for convenience (with cleanup and clarification):

-DPOSTGRESQL_LIBRARIES=/usr/local/psql/lib should point to the libraries, not directories.

This is what the following warning already highlights:

WARNING: Target "soci_postgresql" requests linking to directory
  "/usr/local/postgresql/lib"

Try the following command instead (you may need to delete your CMakeCache.txt from the build directory first as well):

cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_POSTGRESQL=ON ../soci

On Linux systems where "postgresql-devel.x86_64 : PostgreSQL development header files and libraries" is installed, this command should be enough.


问:
Extract a function name inside a macro
In C, we often have to run such code

```<code>if (! somefun(x, y, z)) {
    perror("somefun")
}
</code>```

Is it possible to create a macro which, used as follows:

```<code>#define chkerr ...
chkerr(somefun(x, y, z));
</code>```

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

```<code>chkerr(somefun, x, y, z)
</code>```

答:
Short variant (you spotted already):

```<code>#define chkErr(FUNCTION, ...)  \
    if(!FUNCTION(__VA_ARGS__)) \
    {                          \
        perror(#FUNCTION);     \
    }
</code>```

Be aware that this can impose big problems in nested if/else or similar constructs:

```<code>if(x)
    chkErr(f, 10, 12) //;
                      //^ semicolon forgotten!
else
    chkErr(f, 12, 10);
</code>```

would compile to code equivalent to the following:

```<code>if(x)
{
    if(!f(10, 12))
        perror("f");
    else if(!f, 12, 10))
        perror("f");
}
</code>```

Quite obviously not what was intended with the if/else written with the macros... So you really should prefer to let it look like a real function (requiring a semicolon):

```<code>#define chkErr(FUNCTION, ...)      \
    do                             \
    {                              \
        if(!FUNCTION(__VA_ARGS__)) \
        {                          \
            perror(#FUNCTION);     \
        }                          \
    }                              \
    while(0)
</code>```

You would call it like this:

```<code>chkErr(someFunction, 10, 12);
</code>```

In case of error, output would be:

```<code>someFunction: <error text>
</code>```

However, this hides the fact that a function actually gets called, making it more difficult to understand for "outsiders". Same output, not hiding the function call, but requiring one additional comma in between function and arguments (compared to a normal function call):

```<code>#define chkErr(FUNCTION, ARGUMENTS) \
do                                  \
{                                   \
    if(!FUNCTION ARGUMENTS)         \
    {                               \
        perror(#FUNCTION);          \
    }                               \
}                                   \
while(0)

chkErr(someFunction,(12, 10));
//                 ^ (!)
</code>```

Another variant with the charm of retaining the function call would print out this entire function call:

```<code>#define chkErr(FUNCTION_CALL)   \
do                              \
{                               \
    if(!FUNCTION_CALL)          \
    {                           \
        perror(#FUNCTION_CALL); \
    }                           \
}                               \
while(0)

chkErr(someFunction(10, 12));
</code>```

In case of error, output would be:

```<code>someFunction(10, 12): <error text>
</code>```

Addendum: If you really want exactly the output as shown in the question and still have the function call retained (without comma in between), you are a little in trouble. Actually, it is possible, but it requires some extra work:

Problem is how the preprocessor operates on macro arguments: Each argument is a token. It can easily combine tokens, but cannot split them.

Leaving out any commas results in the macro accepting one single token, just as in my second variant. Sure, you can stringify it, as I did, but you get the function arguments with. This is a string literal, and as the pre-processor cannot modify string literals, you have to operate on them at runtime.

Next problem then is, though, string literals are unmodifiable. So you need to modify a copy!

The following variant would do all this work for you:

```<code>#define chkErr(FUNCTION_CALL)                                 \
do                                                            \
{                                                             \
    if(!FUNCTION_CALL)                                        \
    {                                                         \
        char function_name[] = #FUNCTION_CALL;                \
        char* function_name_end = strchr(function_name, '('); \
        if(function_name_end)                                 \
            *function_name_end = 0;                           \
        perror(function_name);                                \
    }                                                         \
}                                                             \
while(0)
</code>```

Well, decide you if it is worth the effort...

By the way - whitespace between function name and opening parenthesis is not eliminated. If you want to be perfect:

```<code>unsigned char* end = (unsigned char*) function_name;
while(*end && *end != '(' && !isspace(*end))
    ++end;
*end = 0;
</code>```

Or, much nicer (thanks chqrlie for the hint):

```<code>function_name[strcspn(function_name, "( \t")] = 0;
</code>```

Anything else I can think of would require an additional pre-processing step:

```<code>#define CAT(X, Y) CAT_(X, Y)
#define CAT_(X, Y) X ## Y

#define chkErr(FUNCTION_CALL)                 \
do                                            \
{                                             \
    if(!FUNCTION_CALL)                        \
    {                                         \
        perror(CAT(CHK_ERR_TEXT_, __LINE__)); \
    }                                         \
}                                             \
while 0

chkErr(function(10, 12));
</code>```

Ah, huh, this would result in code like this:

```<code>if(!function(10, 12))
{
    perror(CHK_ERR_TEXT_42);
}
</code>```

And now, where to get these macros from? Well, the pre-processing, remember? Possibly a perl or python script, e. g. generating an additional header file you'd have to include. You would have to make sure this pre-processing is done every time before the compiler's pre-processor runs.

Well, all not impossible to solve, but I'll leave this to the masochists among us...

Title: Extract a function name inside a macro

Body:
In C, we often have to run such code

if (! somefun(x, y, z)) {
    perror("somefun")
}

Is it possible to create a macro which, used as follows:

#define chkerr ...
chkerr(somefun(x, y, z));

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

chkerr(somefun, x, y, z)

Body:
Short variant (you spotted already):

#define chkErr(FUNCTION, ...)  \
    if(!FUNCTION(__VA_ARGS__)) \
    {                          \
        perror(#FUNCTION);     \
    }

Be aware that this can impose big problems in nested if/else or similar constructs:

if(x)
    chkErr(f, 10, 12) //;
                      //^ semicolon forgotten!
else
    chkErr(f, 12, 10);

would compile to code equivalent to the following:

if(x)
{
    if(!f(10, 12))
        perror("f");
    else if(!f, 12, 10))
        perror("f");
}

Quite obviously not what was intended with the if/else written with the macros... So you really should prefer to let it look like a real function (requiring a semicolon):

#define chkErr(FUNCTION, ...)      \
    do                             \
    {                              \
        if(!FUNCTION(__VA_ARGS__)) \
        {                          \
            perror(#FUNCTION);     \
        }                          \
    }                              \
    while(0)

You would call it like this:

chkErr(someFunction, 10, 12);

In case of error, output would be:

someFunction: <error text>

However, this hides the fact that a function actually gets called, making it more difficult to understand for "outsiders". Same output, not hiding the function call, but requiring one additional comma in between function and arguments (compared to a normal function call):

#define chkErr(FUNCTION, ARGUMENTS) \
do                                  \
{                                   \
    if(!FUNCTION ARGUMENTS)         \
    {                               \
        perror(#FUNCTION);          \
    }                               \
}                                   \
while(0)

chkErr(someFunction,(12, 10));
//                 ^ (!)

Another variant with the charm of retaining the function call would print out this entire function call:

#define chkErr(FUNCTION_CALL)   \
do                              \
{                               \
    if(!FUNCTION_CALL)          \
    {                           \
        perror(#FUNCTION_CALL); \
    }                           \
}                               \
while(0)

chkErr(someFunction(10, 12));

In case of error, output would be:

someFunction(10, 12): <error text>

Addendum: If you really want exactly the output as shown in the question and still have the function call retained (without comma in between), you are a little in trouble. Actually, it is possible, but it requires some extra work:

Problem is how the preprocessor operates on macro arguments: Each argument is a token. It can easily combine tokens, but cannot split them.

Leaving out any commas results in the macro accepting one single token, just as in my second variant. Sure, you can stringify it, as I did, but you get the function arguments with. This is a string literal, and as the pre-processor cannot modify string literals, you have to operate on them at runtime.

Next problem then is, though, string literals are unmodifiable. So you need to modify a copy!

The following variant would do all this work for you:

#define chkErr(FUNCTION_CALL)                                 \
do                                                            \
{                                                             \
    if(!FUNCTION_CALL)                                        \
    {                                                         \
        char function_name[] = #FUNCTION_CALL;                \
        char* function_name_end = strchr(function_name, '('); \
        if(function_name_end)                                 \
            *function_name_end = 0;                           \
        perror(function_name);                                \
    }                                                         \
}                                                             \
while(0)

Well, decide you if it is worth the effort...

By the way - whitespace between function name and opening parenthesis is not eliminated. If you want to be perfect:

unsigned char* end = (unsigned char*) function_name;
while(*end && *end != '(' && !isspace(*end))
    ++end;
*end = 0;

Or, much nicer (thanks chqrlie for the hint):

function_name[strcspn(function_name, "( \t")] = 0;

Anything else I can think of would require an additional pre-processing step:

#define CAT(X, Y) CAT_(X, Y)
#define CAT_(X, Y) X ## Y

#define chkErr(FUNCTION_CALL)                 \
do                                            \
{                                             \
    if(!FUNCTION_CALL)                        \
    {                                         \
        perror(CAT(CHK_ERR_TEXT_, __LINE__)); \
    }                                         \
}                                             \
while 0

chkErr(function(10, 12));

Ah, huh, this would result in code like this:

if(!function(10, 12))
{
    perror(CHK_ERR_TEXT_42);
}

And now, where to get these macros from? Well, the pre-processing, remember? Possibly a perl or python script, e. g. generating an additional header file you'd have to include. You would have to make sure this pre-processing is done every time before the compiler's pre-processor runs.

Well, all not impossible to solve, but I'll leave this to the masochists among us...

ContentLicense: CC BY-SA 4.0


问:
Android Multiple dex files define Lcom/google/android/gms/common/api/zza
Building project and deploying app to the emulator with API level 22 or 25 goes ok, but when i try to build APK or deploy app to my real device with API level 16 i get the following error:

```<code>Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/common/api/zza;
</code>```

My project build.gradle file:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'me.tatarka:gradle-retrolambda:3.3.0-beta4'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app build.gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "<aplication id here>"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {

    final SUPPORT_LIBRARY_VERSION = '25.0.1'
    final DAGGER_VERSION = '2.4'
    final BUTTERKNIFE_VERSION = '8.0.1'
    final TIMBER_VERISON = '4.3.0'
    final LEAKCANARY_VERSION = '1.4'
    final FIREBASE_VERSION = '10.0.0'
    final FIREBASE_UI_VERSION = '1.0.0'

    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:cardview-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:support-vector-drawable:$SUPPORT_LIBRARY_VERSION"

    compile "com.google.dagger:dagger:$DAGGER_VERSION"
    apt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"

    compile "com.google.firebase:firebase-database:$FIREBASE_VERSION"
    compile "com.firebaseui:firebase-ui-database:$FIREBASE_UI_VERSION"

    compile "com.jakewharton:butterknife:$BUTTERKNIFE_VERSION"
    apt "com.jakewharton:butterknife-compiler:$BUTTERKNIFE_VERSION"

    compile "com.jakewharton.timber:timber:$TIMBER_VERISON"

    debugCompile "com.squareup.leakcanary:leakcanary-android:$LEAKCANARY_VERSION"

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    testCompile 'junit:junit:4.12'
}
</code>```

Note: if i add the "multiDexEnabled true" line to my defaultConfig i'll get the following error:

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/common/api/zza.class
</code>```

答:
Although I had the same error but the above solution did not work for me. I managed to solve the error by downgrading my firebase-ui library version from 2.0.0 to 1.2.0 and added the following to Project level build.gradle file:</p>

```<code>allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}
</code>```

Body:
Building project and deploying app to the emulator with API level 22 or 25 goes ok, but when i try to build APK or deploy app to my real device with API level 16 i get the following error:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/common/api/zza;

My project build.gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath 'me.tatarka:gradle-retrolambda:3.3.0-beta4'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "<aplication id here>"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

}

dependencies {

    final SUPPORT_LIBRARY_VERSION = '25.0.1'
    final DAGGER_VERSION = '2.4'
    final BUTTERKNIFE_VERSION = '8.0.1'
    final TIMBER_VERISON = '4.3.0'
    final LEAKCANARY_VERSION = '1.4'
    final FIREBASE_VERSION = '10.0.0'
    final FIREBASE_UI_VERSION = '1.0.0'

    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile "com.android.support:appcompat-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:recyclerview-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:cardview-v7:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:support-v4:$SUPPORT_LIBRARY_VERSION"
    compile "com.android.support:support-vector-drawable:$SUPPORT_LIBRARY_VERSION"

    compile "com.google.dagger:dagger:$DAGGER_VERSION"
    apt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"

    compile "com.google.firebase:firebase-database:$FIREBASE_VERSION"
    compile "com.firebaseui:firebase-ui-database:$FIREBASE_UI_VERSION"

    compile "com.jakewharton:butterknife:$BUTTERKNIFE_VERSION"
    apt "com.jakewharton:butterknife-compiler:$BUTTERKNIFE_VERSION"

    compile "com.jakewharton.timber:timber:$TIMBER_VERISON"

    debugCompile "com.squareup.leakcanary:leakcanary-android:$LEAKCANARY_VERSION"

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    testCompile 'junit:junit:4.12'
}

Note: if i add the "multiDexEnabled true" line to my defaultConfig i'll get the following error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/common/api/zza.class

Body:
Although I had the same error but the above solution did not work for me. I managed to solve the error by downgrading my firebase-ui library version from 2.0.0 to 1.2.0 and added the following to Project level build.gradle file:

allprojects {
    repositories {
        jcenter()

        // Add the following
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}


问:
jquery price not updating on delete
I want to update price on delete button click. When I am clicking on add button it adding the field and updating the price. But on delete button it is only deleting field and price is not updating.      </p>

```<code>$(document).ready(function() {
  $('#add').on('click', function() {

     var maxfld=$('.acmp').length;
     var pricedl=500;

     if(maxfld<10)
     {
     $('#new_ac').append('<div id="" class="acmp">'+(++maxfld)+'  <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
     }
     if(maxfld>9)
     {
        alert("Cannot add more accompany");

     }
     var totalp=(pricedl*maxfld);
       $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
      $('.price').html(newp);

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

答:
You need tot make your variables(totalp,maxfld) global. Now they are out of the scope of the second click function and it will return undefined. Your code should look like this:

```<code>$(document).ready(function() {
var maxfld = '';
var pricedl = '';
  $('#add').on('click', function() {

     maxfld = $('.acmp').length;
     pricedl = 500;

    if (maxfld < 10) {
      $('#new_ac').append('<div id="" class="acmp">' + (++maxfld) + '  <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
    }
    if (maxfld > 9) {
      alert("Cannot add more accompany");

    }
    var totalp = (pricedl * maxfld);
    $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp = totalp / maxfld;
    $('.price').html(newp);

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

Title: jquery price not updating on delete

Body:
I want to update price on delete button click. When I am clicking on add button it adding the field and updating the price. But on delete button it is only deleting field and price is not updating.

$(document).ready(function() {
  $('#add').on('click', function() {

     var maxfld=$('.acmp').length;
     var pricedl=500;

     if(maxfld<10)
     {
     $('#new_ac').append('
'+(++maxfld)+'
ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)
<input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required />
Gender
<input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female
');
     }
     if(maxfld>9)
     {
        alert("Cannot add more accompany");

     }
     var totalp=(pricedl*maxfld);
       $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
      $('.price').html(newp);

  });
});

Body:
You need tot make your variables(totalp,maxfld) global. Now they are out of the scope of the second click function and it will return undefined. Your code should look like this:

$(document).ready(function() {
var maxfld = '';
var pricedl = '';
  $('#add').on('click', function() {

     maxfld = $('.acmp').length;
     pricedl = 500;

    if (maxfld < 10) {
      $('#new_ac').append('<div id="" class="acmp">' + (++maxfld) + '  <p>ACCOMPANYING PERSON DETAILS (No access to Scientific Halls)</p><input type="text" name="name" placeholder="Accompany Full Name" required /><input type="text" name="mob" placeholder="Accompany Mobile Number" required /><br />Gender<br /><input name="gender" type="radio" value="male" required="required" /> Male<input name="gender" type="radio" value="female" required="required" /> Female</div>');
    }
    if (maxfld > 9) {
      alert("Cannot add more accompany");

    }
    var totalp = (pricedl * maxfld);
    $('#amount').html(totalp);

  });

  $('#del').on('click', function() {
    $('.acmp:last-child').remove();
    var newp = totalp / maxfld;
    $('.price').html(newp);

  });
});


问:
Ruby query need to update
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

```<code>User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}
</code>```

Results as below:

```<code> [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]
</code>```

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

答:
With the same associations you have on the models, you could do (assuming that user passes status they wants to see:

```<code>user_ids = User.where(primary_partner_id: 2).pluck(:id)
Sima.where(user_id: user_ids, status: params[:status])
</code>```

The above will hit the database twice but that's totally fine. You could use includes and map but I don't think that will be a huge performance benefit depending on the number of users on a account you have. Eitherways, here it is:

```<code>User.includes(:sima)
  .references(:sima) # you need this if you use Rails 4 +
  .where(users: { primary_partner_id: 2 })
  .where(simas: { status: params[:status] })
  .map(&:sima)
</code>```

However, I suggest you update Account model with has_many through associations.

```<code>class Account
  has_many :users
  has_many :simas, through: :users
end

# To get sima of a particular status
Account.find(2).simas.where(status: param[:status])
</code>```

This way, you can just do account.simas to get simas from all the users that belong to that account.

Title: Ruby query need to update

Body:
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}

Results as below:

 [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

Body:
With the same associations you have on the models, you could do (assuming that user passes status they wants to see:

user_ids = User.where(primary_partner_id: 2).pluck(:id)
Sima.where(user_id: user_ids, status: params[:status])

The above will hit the database twice but that's totally fine. You could use includes and map but I don't think that will be a huge performance benefit depending on the number of users on a account you have. Eitherways, here it is:

User.includes(:sima)
  .references(:sima) # you need this if you use Rails 4 +
  .where(users: { primary_partner_id: 2 })
  .where(simas: { status: params[:status] })
  .map(&:sima)

However, I suggest you update Account model with has_many through associations.

class Account
  has_many :users
  has_many :simas, through: :users
end

# To get sima of a particular status
Account.find(2).simas.where(status: param[:status])

This way, you can just do account.simas to get simas from all the users that belong to that account.


答:
Two things:

Just return the sum from your getList function

Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong

var number = parseInt(prompt('Input a number!'));
var n = number;

function getList() {
  var sum = 0;

  for (var n = 1; n <= 17; n++) {
    if (n % 3 == 0 || n % 5 == 0) {
      console.log (n);
      sum += n;
    }
  }

  return sum;
}

console.log(getList());
console.log(n, (n*(n+1))/2);```

Title: javascript - functions and equations confusion


问:
Remove the cells below the selected one from the UITableView Swift 3
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

```<code>var myArray = ["rahul","rahib","suhail","alex","siya"]
</code>```

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

```<code>var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)
</code>```

Thanks in advance!

答:
Try this to remove </p>

```<code>    var myArray = ["rahul","rahib","suhail","alex","siya"]
    print(myArray)

    let selectedIndex = 2
    myArray.removeSubrange(selectedIndex..<myArray.count)

    print(myArray)
</code>```

Body:
Here I am trying to remove the remaining objects after the selected one of an array when a particular row is selected from the UITableView.

Here is my sample array:

var myArray = ["rahul","rahib","suhail","alex","siya"]

If I select myArray[2] the remaining elements after "suhail" should be deleted and the final array have to be ["rahul","rahib","suhail"].

Here is my try but it only remove one object:

var selectedIndex = indexPath.row
myArray.remove(at: selectedIndex+1)

Thanks in advance!

Body:
Try this to remove

    var myArray = ["rahul","rahib","suhail","alex","siya"]
    print(myArray)

    let selectedIndex = 2
    myArray.removeSubrange(selectedIndex..<myArray.count)

    print(myArray)


问:
How to get String output as in single quote in javascript
Advance thanks, Question looks like simple but i could not able to find the solution.

```<code>function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3
</code>```

Expected output

```<code>sumStrings('1','2') // => '3'
</code>```

答:
With the new template literal you can try this:</p>

```<code>a=`'5'`;
console.log(a);
</code>```

Body:
Advance thanks, Question looks like simple but i could not able to find the solution.

function sumStrings(a, b)
{
return  +a + +b;
}
sumStrings('1','2') //=>3

Expected output

sumStrings('1','2') // => '3'

Body:
With the new template literal you can try this:

a=`'5'`;
console.log(a);


问:
Configuration for vue-resource root and authorization
I'm looking at the following documentation for vue-resource that describes how to set up configuration:  https://github.com/vuejs/vue-resource/blob/master/docs/config.md

It says to set your headers with a common authorization value:

```<code> Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
</code>```

I am guessing this "Basic YXBpOnBhc3N3b3Jk" value is just an example, but what is this value for, and what should one use instead of it?

On the same page, I also see a setting for "root":

```<code> Vue.http.options.root = '/root';
</code>```

I understand this to mean the web URL for the web app.  However, why does vue-resource need me to tell it this value?  What does it use it for?

答:
If you want set header auth in global way use the inceptor

```<code>Vue.http.interceptors.push(function(request, next) {

    request.headers['Authorization'] = 'Basic abcd' //Base64
    request.headers['Accept'] = 'application/json'
    next()
});
</code>```

and use option credentials:

```<code>Vue.http.options.credentials = true;
</code>```

Body:
I'm looking at the following documentation for vue-resource that describes how to set up configuration:  https://github.com/vuejs/vue-resource/blob/master/docs/config.md

It says to set your headers with a common authorization value:

 Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';

I am guessing this "Basic YXBpOnBhc3N3b3Jk" value is just an example, but what is this value for, and what should one use instead of it?

On the same page, I also see a setting for "root":

 Vue.http.options.root = '/root';

I understand this to mean the web URL for the web app.  However, why does vue-resource need me to tell it this value?  What does it use it for?

Body:
If you want set header auth in global way use the inceptor

Vue.http.interceptors.push(function(request, next) {

    request.headers['Authorization'] = 'Basic abcd' //Base64
    request.headers['Accept'] = 'application/json'
    next()
});

and use option credentials:

Vue.http.options.credentials = true;


问:
Jenkins - Publish HTML report to custom URL
One of my jobs in Jenkins generates an html report and uses the HTML Publisher Plugin to link to it from respective build. In such case, if I want to get to this HTML page directly (assume no security enabled so no log in required), I need to follow a link that has the following form:

http://hostname:port/job/Some%20Job%20Name/buildNumber/Functional_Test_Report/

And for each subsequent build, the URL is going to change based on buildNumber. I would like to have a "pretty" URL that will just display the last report all the time. Say something like this:

http://hostname:port/testReport

The actual report HTML will then be automatically pushed into this location every time the build is finished and will eliminate the need of going through Jenkins each time to see the report.

Is there a way to accomplish this?

答: Just posting my own solution here. Perhaps not the most elegant but one way to do it is by deploying an HTTP server on the same machine where Jenkins runs and add a "post build step" in relevant Jenkins job to copy the HTML report files to HTTP server overwriting the existing files if there are any. Then, the report will be available on whatever port the HTTP server is running on.</p>


问:
Android installation - sdk manager.exe does not work
I installed the android SDK from developer.android.com for Windows (installer_r08-windows.exe).  I installed to the default location, C:\Program Files\Android\android-sdk-windows.  When I try to run SDK Manager.exe, a console window briefly pops up, but disappears.. nothing else happens.  If I try to run this from the command line, nothing happens, either (and no output).

I have JDK 1.6.0_20 installed, and JAVA_HOME environment variable points to this folder (C:\Program Files\Java\jdk1.6.0_20)

Help?

答:
I Had the same problem.
I had installed Java SDK 1.4 (which is not compatible) so I installed 1.6 and add dir to PATH variable and everything works.</p>

ContentLicense: CC BY-SA 2.5


问:
webpack DefinePlugin use external config.js
I am new in webpack
I have this code in webpack.config.js

```<code>var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
var myconfig = require('./webpack.myconfig.js');

// bundle dependencies in separate vendor bundle
var dependencies = Object.keys(pkg.dependencies).filter(function (el) {
  //exclude font packages from vendor bundle & css-toggle-switch
  if (el.indexOf('font') !== -1 || el.indexOf('css-toggle-switch') !== -1) {
    return false;
  }
  else return true;
});

module.exports = {
  entry: {
      libs: dependencies,
      main: './src/index'
  },
  output: {
    path: path.join(__dirname, myconfig.buildPath),
    publicPath: myconfig.uiURL,
    filename: 'dist/js/[name].js',
    chunkFilename: '[id].[name].js'
  },
  plugins: [
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],
};
</code>```

and this is myconfig.js

```<code>myconfig = {
  uiURL: 'http://example.com/',
  apiUrl: 'http://api.example.com/api/'
};

module.exports = myconfig;
</code>```

and if I run this syntax

```<code>webpack -p --config webpack.config.js --progress --colors
</code>```

I will get the result like

```<code>/dist/js/libs.js
/dist/js/main.js
</code>```

but I want the result not like this, I want the result to be:

```<code>/dist/js/myconfig.js
/dist/js/libs.js
/dist/js/main.js
</code>```

What really I want is,
I want in main.js file, it will use myconfig.apiUrl as depedencies,
so when I deployed to production or qserver, I just change myconfig.js.

Thank you

答:
webpack.myconfig.js is used in webpack config file so you have to rebuild every time when webpack.myconfig.js is changed.

You could use myconfig.json and send http request to get it dynamically.

Body:
I am new in webpack
I have this code in webpack.config.js

var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
var myconfig = require('./webpack.myconfig.js');

// bundle dependencies in separate vendor bundle
var dependencies = Object.keys(pkg.dependencies).filter(function (el) {
  //exclude font packages from vendor bundle & css-toggle-switch
  if (el.indexOf('font') !== -1 || el.indexOf('css-toggle-switch') !== -1) {
    return false;
  }
  else return true;
});

module.exports = {
  entry: {
      libs: dependencies,
      main: './src/index'
  },
  output: {
    path: path.join(__dirname, myconfig.buildPath),
    publicPath: myconfig.uiURL,
    filename: 'dist/js/[name].js',
    chunkFilename: '[id].[name].js'
  },
  plugins: [
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],
};

and this is myconfig.js

myconfig = {
  uiURL: 'http://example.com/',
  apiUrl: 'http://api.example.com/api/'
};

module.exports = myconfig;

and if I run this syntax

webpack -p --config webpack.config.js --progress --colors

I will get the result like

/dist/js/libs.js
/dist/js/main.js

but I want the result not like this, I want the result to be:

/dist/js/myconfig.js
/dist/js/libs.js
/dist/js/main.js

What really I want is,
I want in main.js file, it will use myconfig.apiUrl as depedencies,
so when I deployed to production or qserver, I just change myconfig.js.

Thank you


问:
IDEA Groovy test class already exists
IDEA is giving my groovy class the warning `class "MyClassTest" already exists in "my.class.package". It also doesn't seem to be doing a very good job of keeping the class updated when I run the test. I'll add an assertion guaranteed to fail, or succeed and it won't recognize it until later (later so far seems arbitrary). Given that I have maven tests passing and running correctly I suspect this is simply an IDEA configuration problem

here's my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
 <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xenoterracide</groupId>
<artifactId>rpf</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.9.RELEASE</version>
</parent>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>addSources</goal>
                        <goal>addTestSources</goal>
                        <goal>generateStubs</goal>
                        <goal>compile</goal>
                        <goal>testGenerateStubs</goal>
                        <goal>testCompile</goal>
                        <goal>removeStubs</goal>
                        <goal>removeTestStubs</goal>
                    </goals>
                </execution>

            </executions>
            <configuration>
                <testSources>
                    <testSource>
                        <directory>${project.basedir}/src/test/groovy</directory>
                        <includes>
                            <include>**/*.groovy</include>
                        </includes>
                    </testSource>
                </testSources>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.8.0.DATAJPA-622-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <!--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.3.7</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<properties>
    <!-- use UTF-8 for everything -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <start-class>com.xenoterracide.rpf.Application</start-class>
    <java.version>1.8</java.version>
</properties>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

</project>
</code>```

答:
This is because of IntelliJ knows groovy by nature, the only thing you have to do is DO NOT activate gmaveplus-plugin in IntelliJ:

<profiles>
    <profile>
        <id>groovy-integration</id>

        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.gmavenplus</groupId>
                    <artifactId>gmavenplus-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>addSources</goal>
                                <goal>addTestSources</goal>
                                <goal>generateStubs</goal>
                                <goal>compile</goal>
                                <goal>testGenerateStubs</goal>
                                <goal>testCompile</goal>
                                <goal>removeStubs</goal>
                                <goal>removeTestStubs</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>

    <profile>
        <id>development-in-idea</id>

        <activation>
            <property>
                <name>idea.version</name>
            </property>
        </activation>
    </profile>
</profiles>
```

One down side is that when you run maven goal from IntelliJ IDEA's Maven Projects tool window directly, the groovy-integration profile will not be activated as usual.

However, you can always navigate to the test folder, click "Run 'Tests in '...''" and have all the benefits brought to you by IntelliJ.

Exclude gmavenplus-plugin within IntelliJ IDEA takes one more advantage, IntelliJ IDEA sometimes add the generated test stubs as Sources instead of Test Sources, and unable to compile them due to lack of test-scoped dependencies.

Title: IDEA Groovy test class already exists

Body:
IDEA is giving my groovy class the warning `class "MyClassTest" already exists in "my.class.package". It also doesn't seem to be doing a very good job of keeping the class updated when I run the test. I'll add an assertion guaranteed to fail, or succeed and it won't recognize it until later (later so far seems arbitrary). Given that I have maven tests passing and running correctly I suspect this is simply an IDEA configuration problem

here's my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://maven.apache.org/POM/4.0.0"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.xenoterracide</groupId>
<artifactId>rpf</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.9.RELEASE</version>
</parent>

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.gmavenplus</groupId>
            <artifactId>gmavenplus-plugin</artifactId>
            <version>1.2</version>
            <executions>
                <execution>
                    <goals>
                        <goal>addSources</goal>
                        <goal>addTestSources</goal>
                        <goal>generateStubs</goal>
                        <goal>compile</goal>
                        <goal>testGenerateStubs</goal>
                        <goal>testCompile</goal>
                        <goal>removeStubs</goal>
                        <goal>removeTestStubs</goal>
                    </goals>
                </execution>

            </executions>
            <configuration>
                <testSources>
                    <testSource>
                        <directory>${project.basedir}/src/test/groovy</directory>
                        <includes>
                            <include>**/*.groovy</include>
                        </includes>
                    </testSource>
                </testSources>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.8.0.DATAJPA-622-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>javax.enterprise</groupId>
        <artifactId>cdi-api</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.3.7</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <start-class>com.xenoterracide.rpf.Application</start-class>
    <java.version>1.8</java.version>
</properties>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>http://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

</project>

Body:
This is because of IntelliJ knows groovy by nature, the only thing you have to do is DO NOT activate gmaveplus-plugin in IntelliJ:

<profiles>
    <profile>
        <id>groovy-integration</id>
        <!-- profile to incorporate gmaveplus in normal build -->
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.gmavenplus</groupId>
                    <artifactId>gmavenplus-plugin</artifactId>
                    <version>1.5</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>addSources</goal>
                                <goal>addTestSources</goal>
                                <goal>generateStubs</goal>
                                <goal>compile</goal>
                                <goal>testGenerateStubs</goal>
                                <goal>testCompile</goal>
                                <goal>removeStubs</goal>
                                <goal>removeTestStubs</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>

    <profile>
        <id>development-in-idea</id>
        <!-- suppress `groovy-integration` profile by default in IntelliJ -->
        <activation>
            <property>
                <name>idea.version</name>
            </property>
        </activation>
    </profile>
</profiles>

One down side is that when you run maven goal from IntelliJ IDEA's Maven Projects tool window directly, the groovy-integration profile will not be activated as usual.

However, you can always navigate to the test folder, click "Run 'Tests in '...''" and have all the benefits brought to you by IntelliJ.

Exclude gmavenplus-plugin within IntelliJ IDEA takes one more advantage, IntelliJ IDEA sometimes add the generated test stubs as Sources instead of Test Sources, and unable to compile them due to lack of test-scoped dependencies.


问:
Twitter widget timeline using publish.twitter.com script is not loading in webview
When we use https://publish.twitter.com/# to get the script for Twitter timeline and use it in Webview at mobile app, the script simply showing "Tweets by " as a link instead of showing timeline.

Can anyone suggest what is missing here?

答:
I just get an answer from Twitter staff. We need to add https: to the widgets.js and its working fine for me.

```<code><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</code>```

Body:
I just get an answer from Twitter staff. We need to add https: to the widgets.js and its working fine for me.

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>


答:
```<code>library(hydroTSM)

dm2seasonal(df, FUN=sum, season="DJF")
</code>```

I've used the package hydroTSM. The package can also be used for other seasons (MAM, JJA, SON) and with other functions (e.g. mean). You can compute the yearly seasonal sums for every column in your matrix (df). seas does the same for every column, but you have to write your own loop to get yearly seasonal sums I guess. mkseas() from seas will compute the sum over all winter months in your timeseries.

Title: Yearly seasonal sums for DJF

Body:
I want to create sums for the meteorological nomenclature of DJF, that means December values are from the year x-1.

There is already a suggestion, using the packages seas and zoo for my kind of problem: Link to the reference. Can I use a loop regarding the time index of my zoo-object, to get the winter sums for each year and different columns? There are already only the winter months in my sample data:

structure(c(0.335767631885527, 0.329964137686826, 0.324867678295622,
0.346234032749876, 0.315486588076342, 0.373440783616547, 0.393108355980974,
0.310526442402042, 0.955068399718777, 0.959654624426492, 0.293930575800507,
0.350949140946517, 0.657761387039141, 0.53822087533681, 0.296938223280703,
0.318325593619261, 0.827528522109129, 0.914084376992577, 0.914209302937996,
0.913163846516007, 0.776698687524975, 0.597284692104539, 0.91488961230643,
0.28945161773974, 0.282895617679457, 0.28492139335934, 0.928492227792593,
0.287740157404564, 0.93011080075256, 0.32787462005944, 0.809245564874419,
0.299095322129539, 0.302473955104931, 0.453458703894119, 0.331724139938735,
0.314265997270211, 0.378968117507553, 0.344955599135117, 0.961200295699775,
1.07300929383762, 0.339365254133058, 0.421999171190298, 0.351276824906379,
0.36810350819186, 0.364237601690115, 0.425751222495895, 1.2000504740503,
0.401585883450189, 0.393244206959102, 0.412013522316855, 1.40622761554481,
1.43010692801434, 1.45452312391606, 1.44102848262452, 0.583854512560274,
0.453530324821785, 0.836929179095723, 0.485649439571136, 1.45323622566975,
1.42066532567401, 1.55192692063172, 1.69545734226667, 1.59084952877426,
0.536277991651981, 0.878100994910164, 1.80588869793109, 0.612726668114702,
1.49557275883036, 1.83080789724595, 0.859368961826519, 1.3537163175202,
0.795003445956722, 1.68510799767645, 1.94219078558463, 0.678911636490617,
1.98538116097216, 1.39431924099171, 0.716178198907659, 0.897864731079577,
0.739754008960108, 1.32647638785145, 1.27550346512974, 1.57782298324095,
1.17541538713537, 1.08141388070016, 2.81373485339402, 0.841584582588819,
2.98872530454666, 1.93484656658214, 3.01625884992721, 0.902448663673698,
0.361944635028181, 1.03795562218241, 0.961881521906292, 0.704732279822006,
0.894256898010956, 0.307197052425753, 0.620230669033494, 0.900835004143219,
0.336503062729966, 0.376726235662507, 0.323019953443342, 0.291097473211189,
0.583926906347703, 0.540940525007957, 0.906358816314195, 0.372788957369332,
0.335375002309946, 0.914209302937996, 0.328320596067713, 0.659589829678685,
0.68859386616471, 0.91488961230643, 0.902977019532625, 0.739324647975471,
0.603576498397486, 0.690375139214112, 0.603004583921208, 0.659868379563069,
0.292376232645021, 0.562401086780579, 0.298131207627614, 0.299095322129539,
0.302473955104931, 0.705840069893102, 0.993644273952054, 0.425326528868129,
0.400345928302124, 0.361221494378293, 0.328750601711733, 0.55820945179875,
0.748093576785292, 0.345188978576, 0.351315165819748, 0.357626992140137,
0.517538802067647, 1.04751086637289, 0.385695811626645, 0.385612146149294,
0.397271280188057, 0.550298801906058, 1.28131889629393, 0.82396230266283,
1.03189532043667, 0.502923809446499, 1.13388533378536, 0.821249922028902,
0.496130920693478, 0.491056299113018, 0.861144623672965, 0.498763665924562,
0.912165347541201, 0.64869230436972, 1.32528603957948, 1.75339437114229,
1.78285803283739, 1.11217610098546, 0.597795159831033, 1.00740416004752,
0.739549658487185, 0.607139331936484, 1.35734916834937, 1.43608105985186,
1.80042779869959, 1.18905308118327, 1.70456429994882, 0.905541925940458,
2.22398340066076, 2.16944665030202, 2.29546486372867, 1.85605245367111,
1.1239234690604, 2.50480944519147, 1.02954245959557, 0.975126362552554,
2.14223132835323, 2.91282474285556, 2.66863827732602, 0.933593864631134,
2.70815814163342, 2.87351062547491, 0.335329222971355, 0.934907402460015,
0.57591904762801, 0.907224647738403, 0.320417497402957, 0.766767831651282,
0.861903342837008, 0.303464733511709, 0.709698376015027, 0.308598232977547,
0.293930575800507, 0.29130992351097, 0.28896933229556, 0.45769807141885,
0.468340431926149, 0.830040974016766, 0.282420179745874, 0.477428977916008,
0.733418492651481, 0.822348309121175, 0.280392410026905, 0.542239475756514,
0.281077879631808, 0.281845318148658, 0.42849080424256, 0.295089908538224,
0.747925637213591, 0.929814463524078, 0.310954657683433, 0.292376232645021,
0.64500798819687, 0.690255336889303, 0.364309565584761, 0.306129346468766,
0.311371964852598, 0.915461004824963, 0.397063771122394, 1.0404933625801,
0.483845551843616, 0.333807374425717, 0.402255447456447, 0.453946781602374,
0.394538152500142, 0.357626992140137, 0.364237601690115, 0.372020526598045,
0.37823224873185, 0.389581791596903, 0.393244206959102, 0.401126173348066,
0.563948059226945, 0.625538021242673, 0.80823517471131, 0.440809452269821,
0.753920921570439, 0.571583127323145, 0.463092290982252, 0.576935449307388,
0.482901053437729, 1.40965077473646, 1.25183016539419, 0.856169846501004,
1.72377824975207, 0.536277991651981, 1.13652692119597, 1.24290457699823,
1.64437171023011, 1.87302947654355, 0.594841647571458, 2.04410190051534,
1.62571002130845, 1.13052139459963, 0.836130011762252, 1.85233449007414,
2.38839794838805, 1.09920265799031, 1.94766079436355, 1.66770758466983,
1.27453119791191, 2.57917818578189, 1.13896219096471, 2.74804359878488,
1.69823856330245, 0.935150681359782, 1.74656095016161, 0.835168244061429,
0.841584582588819, 0.856635868155615, 0.972724285567558, 2.42939239419398,
0.96325679668782, 0.640892567004161, 1.03795562218241, 0.949309568900219,
0.316910844084317, 0.311204732481577, 0.307197052425753, 0.303464733511709,
0.779574150582344, 0.296830513889512, 0.335960010735195, 0.4390886067335,
0.28896933229556, 0.306902835898889, 0.926150657204963, 0.388532344331494,
0.495283643343666, 0.916064063737401, 0.281013296117892, 0.913163846516007,
0.912928724576721, 0.438926937515807, 0.59117658733228, 0.517844090756594,
0.704234100156676, 0.913848110190877, 0.423829975580762, 0.795497269555325,
0.289917958593354, 0.292376232645021, 0.295114252321699, 0.345353147959634,
0.854886103409894, 0.62965115658928, 0.776701146370991, 0.446059142229343,
0.326457042618417, 0.568752212327844, 0.325374322793979, 0.374762702815228,
0.333807374425717, 0.420206697512664, 0.399408381034396, 0.456977698650331,
0.357626992140137, 0.596680957599271, 1.29550961397828, 1.24265117031916,
0.580164026815441, 0.393244206959102, 0.401126173348066, 0.443462006528755,
0.417630422649225, 0.426247823064678, 0.505363855323395, 0.494595916530596,
1.12922054709106, 0.482617341273223, 0.650774092876326, 0.5452273225038,
1.61305811763483, 1.66701808699342, 0.514281824935098, 0.525174470147384,
1.6850349371761, 1.78354241230912, 1.83460579403794, 1.86582069105335,
1.40279004365455, 0.594841647571458, 0.691585610303159, 0.619623644706909,
2.06846657922012, 0.710726446010795, 0.997307890433014, 2.40064963745822,
2.22161516025196, 1.79188547652641, 2.19553900228869, 2.1816869110449,
2.1984531582332, 2.55364304827728, 0.918827215513173, 0.930267750935017,
0.798812034349413, 0.830829315142733, 1.13089106389005, 1.00204606351463,
1.07126361979325, 0.871799972892206, 1.28166129954517), .Dim = c(181L,
2L), .Dimnames = list(NULL, NULL), index = structure(c(699, 700,
701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713,
714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726,
727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739,
740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752,
753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765,
766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778,
779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 1065,
1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076,
1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1086, 1087,
1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098,
1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109,
1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120,
1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131,
1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142,
1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153,
1154), class = "Date"), class = "zoo")

Body:
library(hydroTSM)

dm2seasonal(df, FUN=sum, season="DJF")

I've used the package hydroTSM. The package can also be used for other seasons (MAM, JJA, SON) and with other functions (e.g. mean). You can compute the yearly seasonal sums for every column in your matrix (df). seas does the same for every column, but you have to write your own loop to get yearly seasonal sums I guess. mkseas() from seas will compute the sum over all winter months in your timeseries.


答:
According to me you need to remove the element after you get the value of maxfld

```<code>  $('#del').on('click', function() {
     var pricedl=500,
         maxfld=$('.acmp').length,
         totalp=(pricedl*maxfld);
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
    $('.price').html(newp);

  });
</code>```

Title: jquery price not updating on delete

Body:
According to me you need to remove the element after you get the value of maxfld

  $('#del').on('click', function() {
     var pricedl=500,
         maxfld=$('.acmp').length,
         totalp=(pricedl*maxfld);
    $('.acmp:last-child').remove();
    var newp=totalp/maxfld;
    $('.price').html(newp);

  });


问:
Assigning value to undefined in JavaScript
I was writing some code in JavaScript. When I accidentally came across this.

```<code>undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error
</code>```

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.

答:
This is because undefined is not a reserved word in JavaScript, even though it has a special meaning. So it can be assigned a value and the whole statement is valid. Whereas true and null are reserved words and can't be assigned values.

For reference: JavaScript Reserved Words

Body:
I was writing some code in JavaScript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

How is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true, and null are values you can assign to some variable, so all these should be invalid statements.


问:
Web Client Upload Values
I want to make a desktop application that enters a value in textbox and performs button actions for example design an application that enters value in google search box at google.com  and performs action as when any one presses search button i wrote a code but it threw exception The remote server returned an error: (405) Method Not Allowed.</p>

```<code>WebClient wc = new WebClient();
string uri = "http://google.com";

NameValueCollection nvc = new NameValueCollection();

nvc.Add("search", "afnan");

byte[] response = wc.UploadValues(uri, nvc);
textBox1.Text=Encoding.ASCII.GetString(response);
</code>```

答:
UploadValues is trying to do a POST (by default, at least; some other verbs are allowed, but they essentially still treat it as a body payload). It sounds like you just want a GET query like http://www.google.com/search?q=afnan - so just url-encode "afnan". Note, however, that you should always observe the target site's Terms and Conditions - in particular section 5:

You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers)

If you do this, expect to get black-listed.

Title: Web Client Upload Values

Body:
I want to make a desktop application that enters a value in textbox and performs button actions for example design an application that enters value in google search box at google.com  and performs action as when any one presses search button i wrote a code but it threw exception The remote server returned an error: (405) Method Not Allowed.

WebClient wc = new WebClient();
string uri = "http://google.com";

NameValueCollection nvc = new NameValueCollection();

nvc.Add("search", "afnan");

byte[] response = wc.UploadValues(uri, nvc);
textBox1.Text=Encoding.ASCII.GetString(response);


问:
How to determine if a signed in user is a teacher in google classroom?
For the app I am building for elementary schools, teachers can access it by logging into their classroom account, but students cannot. How do I determine if a particular user is a teacher?

I noticed that the test teacher account has the permission CREATE_COURSE, but the student does not. Can I assume that is universally true... that if someone has a CREATE_COURSE permission, they are a teacher for some course.

答:
Just recently, according to https://issuetracker.google.com/issues/36760055, you may use https://developers.google.com/classroom/reference/rest/v1/userProfiles to determine whether the user is teacher</p>

```<code>{
  "verifiedTeacher": boolean
}
</code>```

Body:
Just recently, according to https://issuetracker.google.com/issues/36760055, you may use https://developers.google.com/classroom/reference/rest/v1/userProfiles to determine whether the user is teacher

{
  "verifiedTeacher": boolean
}


问:
Possibilities to deploy a Spring-Boot app and a Pentaho Server?
I have a Spring Boot app running for filling a MySQL database with data I want to analyze with OLAP. I chose Pentaho Data Integration, Schema Workbench and Business Intelligence Server (CE versions) to create my data warehouse. In the ETL process I just fill my data warehouse with the data I generated with my Spring Boot app. In the BI-Server I use the Saiku plugin to make all the OLAP operations and it all works quite nicely.

However I want to make all of that public.
Where is it possible to deploy my app with a database (preferably MySQL) and the BI-Server?

I've looked into Heroku and it seems to use PostgreSQL databases and I haven't found out about a possibility to deploy my BI-Server...  Or should I move away from Pentaho and use other solutions to make OLAP on my data warehouse?

Any recommendations?

答: You`d better use some cloud service like https://www.digitalocean.com/ or amazon. For your own linux server. At this server you can install BI server and Mysql.</p>


问:
How to select all checkbox in angular 2?

  <input  type="checkbox" [checked]="selectAllCheckbox" (click)="selectAll()"> Select All

    <input [checked]="item._selected" (click)="updatedUserList(user, $event)" type="checkbox"> {{user}}

```

users = ["users1", "users2", "users3"]

答:
Its a workaround in angular 2 you canrefer below code
HTML

```<code><ul>
  <li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/>
  </li>
  <li *ngFor="let n of names">
  <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">
  {{n.name}}
  </li>
</ul>
</code>```

Component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: String;
  names: any;
  selectedAll: any;
  constructor() {
    this.title = "Select all/Deselect all checkbox - Angular 2";
    this.names = [
      { name: 'Prashobh', selected: false },
      { name: 'Abraham', selected: false },
      { name: 'Anil', selected: false },
      { name: 'Sam', selected: false },
      { name: 'Natasha', selected: false },
      { name: 'Marry', selected: false },
      { name: 'Zian', selected: false },
      { name: 'karan', selected: false },
    ]

  }
  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }
}
</code>```

Body:
  <input  type="checkbox" [checked]="selectAllCheckbox" (click)="selectAll()"> Select All

    <input [checked]="item._selected" (click)="updatedUserList(user, $event)" type="checkbox"> {{user}}

users = ["users1", "users2", "users3"]

Body:
Its a workaround in angular 2 you canrefer below code
HTML

<ul>
  <li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/>
  </li>
  <li *ngFor="let n of names">
  <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">
  {{n.name}}
  </li>
</ul>

Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: String;
  names: any;
  selectedAll: any;
  constructor() {
    this.title = "Select all/Deselect all checkbox - Angular 2";
    this.names = [
      { name: 'Prashobh', selected: false },
      { name: 'Abraham', selected: false },
      { name: 'Anil', selected: false },
      { name: 'Sam', selected: false },
      { name: 'Natasha', selected: false },
      { name: 'Marry', selected: false },
      { name: 'Zian', selected: false },
      { name: 'karan', selected: false },
    ]

  }
  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }
}


问:
Generating a very large matrix of string combinations using combn() and bigmemory package
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

```<code>Error: cannot allocate vector of size 9.0 Gb
</code>```

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

```<code>library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")
</code>```

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

```<code>test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'
</code>```

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.

答:
At a first approximation, every algorithm trades off storage for speed.

You have hit a boundary trying to preallocate your fully enumerated combination matrix. So maybe you should try not to preallocate this matrix but to try, say,

If you think you need the combinations, calculate them somewhere else and store them in a simple db (or, heck, flat file) and look them up -- 9 gb saved

Take advantage of open source, read the code to combn() and modify it into a client-server thingy:  given a call with index number N, it will loop and return the Nth entry.  Not efficient, but possibly more easily feasible.

Body:
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

Error: cannot allocate vector of size 9.0 Gb

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.


问:
Save the last letter when typing in a textField
I have this function in my application:

```<code>func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)
    }
}
</code>```

In viewDidLoad() I have written this:

```<code>textField.addTarget(self, action: #selector(typingName), for: .editingChanged)
</code>```

All works good, but I want to save only the letter typed by the user.

With this function if I write "hello" it prints:
"h"
"he"
"hel"
"hell"
"hello".

Instead, I want to have this:
"h"
"e"
"l"
"l"
"o".

答:
For any Swift String, You could get the latest letter from a string like this:

```<code>let myString = "Hello, World"
let lastCharacter = myString.characters.last // d
</code>```

Note that the data type of lastCharacter is Character? (optional character), you might want to do it as optional binding:

```<code>let myString = "Hello, World"
if let lastCharacter = myString.characters.last {
    print(lastCharacter) // d
}
</code>```

Since you are listening to editingChanged event, all you have to do in your typingName function is:

```<code>func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)

        if let lastCharacter = tempName.characters.last {
            print(lastCharacter)
        }
    }
}
</code>```

Body:
I have this function in my application:

func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)
    }
}

In viewDidLoad() I have written this:

textField.addTarget(self, action: #selector(typingName), for: .editingChanged)

All works good, but I want to save only the letter typed by the user.

With this function if I write "hello" it prints:
"h"
"he"
"hel"
"hell"
"hello".

Instead, I want to have this:
"h"
"e"
"l"
"l"
"o".

Body:
For any Swift String, You could get the latest letter from a string like this:

let myString = "Hello, World"
let lastCharacter = myString.characters.last // d

Note that the data type of lastCharacter is Character? (optional character), you might want to do it as optional binding:

let myString = "Hello, World"
if let lastCharacter = myString.characters.last {
    print(lastCharacter) // d
}

Since you are listening to editingChanged event, all you have to do in your typingName function is:

func typingName(textField:UITextField){
    if let typedText = textField.text {
        tempName = typedText
        print(tempName)

        if let lastCharacter = tempName.characters.last {
            print(lastCharacter)
        }
    }
}