问:
How do I resolve Activity Not Found Exception
In my android app, I've added an activity MainActivity in the manifest file, on navigating to that activity using an inten I get activity not found error asking if I've added it to manifest

here is my manifest activity

```<code>        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:icon="@mipmap/ic_launcher"
            android:rotationAnimation="seamless"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"
            tools:targetApi="O">

             <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.OPENABLEk" />
             </intent-filter>

<!--            Register as a system camera app-->
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
                <action android:name="android.media.action.VIDEO_CAMERA" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <!-- App links for http/s -->
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="example.android.com" />
                <data android:pathPattern="/camerax" />
            </intent-filter>

            <!-- Declare notch support -->
            <meta-data
                android:name="android.notch_support"
                android:value="true" />
        </activity>
</code>```

here is the log

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 28538
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.android.example.cameraxbasic.SelectOperation$1.onClick(SelectOperation.java:36)
        at android.view.View.performClick(View.java:7044)
        at android.view.View.performClickInternal(View.java:7017)
        at android.view.View.access$3200(View.java:784)
        at android.view.View$PerformClick.run(View.java:26596)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

</code>```

I've done this
How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3
no solution yet

答:
The error message says it all,

android.content.ActivityNotFoundException: Unable to find explicit
  activity class
  {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt};
  have you declared this activity in your AndroidManifest.xml?

From what it seems in your manifst, you haven't.

The only activity declared is MainActivity

```<code><activity
     android:name=".MainActivity"
     ...
</code>```

The exception was raised because in your code you are using a class that is named MainActivityKt.

Probably you mispelled that name, fix it.

Body:
In my android app, I've added an activity MainActivity in the manifest file, on navigating to that activity using an inten I get activity not found error asking if I've added it to manifest

here is my manifest activity

        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:icon="@mipmap/ic_launcher"
            android:rotationAnimation="seamless"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat"
            tools:targetApi="O">

             <intent-filter>
             <action android:name="android.intent.action.MAIN" />

             <category android:name="android.intent.category.OPENABLEk" />
             </intent-filter>

            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />
                <action android:name="android.media.action.STILL_IMAGE_CAMERA" />
                <action android:name="android.media.action.VIDEO_CAMERA" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="http" />
                <data android:scheme="https" />
                <data android:host="example.android.com" />
                <data android:pathPattern="/camerax" />
            </intent-filter>

            <meta-data
                android:name="android.notch_support"
                android:value="true" />
        </activity>

here is the log

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.virtusync.scanningtool, PID: 28538
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.android.example.cameraxbasic.SelectOperation$1.onClick(SelectOperation.java:36)
        at android.view.View.performClick(View.java:7044)
        at android.view.View.performClickInternal(View.java:7017)
        at android.view.View.access$3200(View.java:784)
        at android.view.View$PerformClick.run(View.java:26596)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)

I've done this
How to fix "android.content.ActivityNotFoundException" android-studio 2.3.3
no solution yet

Body:
The error message says it all,

android.content.ActivityNotFoundException: Unable to find explicit
  activity class
  {com.virtusync.scanningtool/com.android.example.cameraxbasic.MainActivityKt};
  have you declared this activity in your AndroidManifest.xml?

From what it seems in your manifst, you haven't.

The only activity declared is MainActivity

<activity
     android:name=".MainActivity"
     ...

The exception was raised because in your code you are using a class that is named MainActivityKt.

Probably you mispelled that name, fix it.


来源: stackexchange

问:
Memory limit on composer installation
I have a cloud in the digital ocean where it has 1 GB of ram.
I need to install a docker, laravel, mysql, nginx environment, I found the laradock and installed it normally but when running the composer in the container I am returning a memory limit error.

Error running: composer install

```<code>root@b9864446a1e1:/var/www/site# composer install
Loading composer repositories with package information
Updating dependencies (including require-dev)

mmap() failed: [12] Cannot allocate memory

mmap() failed: [12] Cannot allocate memory
PHP Fatal error:  Out of memory (allocated 677388288) (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52

Fatal error: Out of memory (allocated 677388288) (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52
</code>```

Error when trying to change memory.

WARNING: Your kernel does not support swap limit capabilities or the
  cgroup is not mounted. Memory limited without swap.

答:
This could be happening because the VPS runs out of memory and has no Swap space enabled.

```<code>free -m

total used free shared buffers cached
Mem:  xxxx xxx xxxx x x xxx
-/+ buffers/cache: xxx xxxx
Swap: 0 0 0
</code>```

To enable the swap you can use for example:

```<code>/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
</code>```

You can make a permanent swap file following this tutorial from DigitalOcean.

ContentLicense: CC BY-SA 4.0

Title: Memory limit on composer installation

Body:
I have a cloud in the digital ocean where it has 1 GB of ram.
I need to install a docker, laravel, mysql, nginx environment, I found the laradock and installed it normally but when running the composer in the container I am returning a memory limit error.

Error running: composer install

root@b9864446a1e1:/var/www/site# composer install
Loading composer repositories with package information
Updating dependencies (including require-dev)

mmap() failed: [12] Cannot allocate memory

mmap() failed: [12] Cannot allocate memory
PHP Fatal error:  Out of memory (allocated 677388288) (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52

Fatal error: Out of memory (allocated 677388288) (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52

Error when trying to change memory.

WARNING: Your kernel does not support swap limit capabilities or the
  cgroup is not mounted. Memory limited without swap.

Body:
This could be happening because the VPS runs out of memory and has no Swap space enabled.

free -m

total used free shared buffers cached
Mem:  xxxx xxx xxxx x x xxx
-/+ buffers/cache: xxx xxxx
Swap: 0 0 0

To enable the swap you can use for example:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1

You can make a permanent swap file following this tutorial from DigitalOcean.


问:
How User account be locked for 30 min after 5 unsuccessful login attempts with asp.net?
I am using asp.net membership provider for managing users. I have a requirement to lock user accounts for 30 mins after 5 unsuccessful attempts. How should I do that using asp.net membership provider on the server side?

Also I want that 'Passwords should expire after 3 months', 'Last 10 used passwords should be remembered'. Is there any way to solve these requirements.

答:
if you are using SqlMembershipProvider then use

maxInvalidPasswordAttempts for attempts

passwordAttemptWindow for locking for specified period

no option for password expiration or password history

but if you are using ActiveDirectoryMembershipProvider then use

maxInvalidPasswordAttempts for attempts

passwordAnswerAttemptLockoutDuration for locking for specified period

and ajust your domain policy for password expiration or password history

full info here

http://msdn.microsoft.com/en-us/library/ff648345.aspx#paght000022_usingthesqlmembershipprovider

ContentLicense: CC BY-SA 3.0


问:
how can i filter the data based on array of cities
I have a select menu where i can select the city
I want to display all book available on this city ( based on array of cities )
what i should write inside checkavailablecity

here is the full code

the full code

HTML :

```<code><select>
<option value="NewYork" v-model="myCity">New York</option>
.. </select>
<ul>
<li v-for="book in checkavailablecity">{{book.bookName}}
</li>
</ul></div>
</code>```

JavaScript :

```<code>data: {
  myCity:'',
  bookinfo:[{
  bookName:'Big Nate: Fun Blaster',
  cities: ['NewYork','Washington','Texas']
  },
  {
  bookName:'Now I Rise',
  cities: ['Texas']
  }
  ]
},
computed: {
  checkavailablecity: function(){
       var mycity = this.myCity;
       return this.bookinfo.filter(function(book){
       ....
     })   }   } })
</code>```

答:
First, you bind a variable to the select dropdown and not on each option.

So the select dropdown in the link you shared would change from:

```<code><select>
 <option value="NewYork" v-model="myCity">New York</option>
 <option value="Texas" v-model="myCity">Texas</option>
</select>
</code>```

to

```<code><select v-model="myCity">
 <option value="NewYork" >New York</option>
 <option value="Texas">Texas</option>
</select>
</code>```

Your callback function would simply check whether your cities for the current book has the current city selected. It would look like below:

```<code>return this.bookinfo.filter(function(book){
     return book.cities.includes(mycity);
})
</code>```

Working Demo: https://jsfiddle.net/k8L4my3u/

Body:
I have a select menu where i can select the city
I want to display all book available on this city ( based on array of cities )
what i should write inside checkavailablecity

here is the full code

the full code

HTML :

<select>
<option value="NewYork" v-model="myCity">New York</option>
.. </select>

{{book.bookName}}

JavaScript :

data: {
  myCity:'',
  bookinfo:[{
  bookName:'Big Nate: Fun Blaster',
  cities: ['NewYork','Washington','Texas']
  },
  {
  bookName:'Now I Rise',
  cities: ['Texas']
  }
  ]
},
computed: {
  checkavailablecity: function(){
       var mycity = this.myCity;
       return this.bookinfo.filter(function(book){
       ....
     })   }   } })

Body:
First, you bind a variable to the select dropdown and not on each option.

So the select dropdown in the link you shared would change from:

<select>
 <option value="NewYork" v-model="myCity">New York</option>
 <option value="Texas" v-model="myCity">Texas</option>
</select>

to

<select v-model="myCity">
 <option value="NewYork" >New York</option>
 <option value="Texas">Texas</option>
</select>

Your callback function would simply check whether your cities for the current book has the current city selected. It would look like below:

return this.bookinfo.filter(function(book){
     return book.cities.includes(mycity);
})

Working Demo: https://jsfiddle.net/k8L4my3u/


问:
Does Rcpp enables C++ datatypes such as int, std::string etc. as input or output parameters?
I was trying something like below (A rough example):

test.cpp:

```<code>#include <Rcpp.h>
#include <string>

// [[Rcpp::export]]
RcppExport int R_load_lib(SEXP R_strDllPath);

int R_load_lib(SEXP R_strDllPath)
{
   int nStatus;
   std::string strDllPath = Rcpp::as<std::string>(R_strDllPath);
   nStatus = LoadLibrary(strDllPath.c_str());

  Rcpp::Rcout << "LoadLib status is " << nStatus << "\n";//This get printed and then crash happens

   return nStatus;
}

</code>```

Compilation steps for C++ code (Using cygwin):

```<code>g++ -static-libgcc -static-libstdc++  -L$(R_HOME)/bin/x64 -lR
-L$(R_HOME)/library/Rcpp/libs/x64 -lRcpp -fPIC -shared test.o -o test.dll

</code>```

test.R:

```<code>dyn.load("test.dll")
status<-.Call("R_load_lib", "D:/R_test/sample.dll")
</code>```

答:
I think I found out the answer to my question. I have gone through http://dirk.eddelbuettel.com/code/rcpp/Rcpp-introduction.pdf. In this pdf some examples are there that shows how we should use SEXP for in or out from C/C++ to R. I have tried the same and it is working fine now without a crash. So my C++ code now look like:</p>

```<code>#include <Rcpp.h>
#include <string>

// [[Rcpp::export]]
RcppExport SEXP R_load_lib(SEXP R_strDllPath);

SEXP R_load_lib(SEXP R_strDllPath)
{
   int nStatus;
   std::string strDllPath = Rcpp::as<std::string>(R_strDllPath);
   nStatus = LoadLibrary(strDllPath.c_str());

  Rcpp::Rcout << "LoadLib status is " << nStatus << "\n";//This get printed and then crash happens

   return Rcpp::NumericVector(nStatus);
}
</code>```

Body:
I was trying something like below (A rough example):

test.cpp:

#include <Rcpp.h>
#include <string>

// [[Rcpp::export]]
RcppExport int R_load_lib(SEXP R_strDllPath);

int R_load_lib(SEXP R_strDllPath)
{
   int nStatus;
   std::string strDllPath = Rcpp::as<std::string>(R_strDllPath);
   nStatus = LoadLibrary(strDllPath.c_str());

  Rcpp::Rcout << "LoadLib status is " << nStatus << "\n";//This get printed and then crash happens

   return nStatus;
}

Compilation steps for C++ code (Using cygwin):

g++ -static-libgcc -static-libstdc++  -L$(R_HOME)/bin/x64 -lR
-L$(R_HOME)/library/Rcpp/libs/x64 -lRcpp -fPIC -shared test.o -o test.dll

test.R:

dyn.load("test.dll")
status<-.Call("R_load_lib", "D:/R_test/sample.dll")

Body:
I think I found out the answer to my question. I have gone through http://dirk.eddelbuettel.com/code/rcpp/Rcpp-introduction.pdf. In this pdf some examples are there that shows how we should use SEXP for in or out from C/C++ to R. I have tried the same and it is working fine now without a crash. So my C++ code now look like:

#include <Rcpp.h>
#include <string>

// [[Rcpp::export]]
RcppExport SEXP R_load_lib(SEXP R_strDllPath);

SEXP R_load_lib(SEXP R_strDllPath)
{
   int nStatus;
   std::string strDllPath = Rcpp::as<std::string>(R_strDllPath);
   nStatus = LoadLibrary(strDllPath.c_str());

  Rcpp::Rcout << "LoadLib status is " << nStatus << "\n";//This get printed and then crash happens

   return Rcpp::NumericVector(nStatus);
}


问:
Need to clean users01.dbf in Oracle 12c
I have Oracle Database 12c in a docker container. At one point, the space in the tablespace expanded (the users01.dbf file became 32GB in size) and I made a new file for this tablespace - users02.dbf. I analyzed the tables and indexes that occupy the most space and made them truncate. I see that the size of the largest tables and indexes has decreased, but the users01.dbf and users02.dbf files remain the same size:

users01.dbf 32G

users02.dbf 8.8G

Here is a screenshot:

Left size before, right after truncate command. How can I clean or reduce the size of users01.dbf and users02.dbf files and not break the database.

答:
alter database datafile    'path_to_datafile/users01.dbf' resize 150M;

Repeat same for 02. Make sure path and file names are correct.

Since you truncated tables it should have dropped the segments altogether, so file should be able to shrink. If you get ORA-03297: file contains used data beyond requested RESIZE value then it means you have data at 150M mark so you should try increasing resize limit more until error goes away.

As always you shouldn't be doing stuff directly on Production but test it out.

Title: Need to clean users01.dbf in Oracle 12c


问:
In R: Extract similar trajectory patterns from a data table
I have a data table that contains several patterns for going from a to c. These patterns are assigned to different expeditions. I want to extract similar patterns for the different expedition_id.

```<code>dt<- data.table(departure = c('a', 'a', 'a', 'b', 'a','d','a', 'b'), arrival =
       c('a','a','b','c','d','c','b','c'), expedition_id = c(1,2,1,1,3,3,2,2))

 >dt
departure      arrival    expedition_id
   a              a            1
   a              a            2
   a              b            1
   b              c            1
   a              d            3
   d              c            3
   a              b            2
   b              c            2
</code>```

The results that I am trying to get look like different data tables for each unique pattern.

```<code>>dt1

departure       arrival         expedition_list
   a                a                1,2
   a                b                1,2
   b                c                1,2

>dt2

departure       arrival         expedition_list
   a                d                3
   d                c                3
</code>```

I'd appreciate your help on this one.

答:
You can try:

```<code>library(data.table)

dt <- dt[, .(expedition_list = toString(expedition_id)), by = .(departure, arrival)]
dt_list <- split(dt, dt$expedition_list)

list2env(
  setNames(
    dt_list,
    paste0('dt', 1:length(dt_list))
  ),
  .GlobalEnv
)
</code>```

Output:

```<code>dt1

   departure arrival expedition_list
1:         a       a            1, 2
2:         a       b            1, 2
3:         b       c            1, 2

dt2

   departure arrival expedition_list
1:         a       d               3
2:         d       c               3
</code>```

Body:
I have a data table that contains several patterns for going from a to c. These patterns are assigned to different expeditions. I want to extract similar patterns for the different expedition_id.

dt<- data.table(departure = c('a', 'a', 'a', 'b', 'a','d','a', 'b'), arrival =
       c('a','a','b','c','d','c','b','c'), expedition_id = c(1,2,1,1,3,3,2,2))

 >dt
departure      arrival    expedition_id
   a              a            1
   a              a            2
   a              b            1
   b              c            1
   a              d            3
   d              c            3
   a              b            2
   b              c            2

The results that I am trying to get look like different data tables for each unique pattern.

>dt1

departure       arrival         expedition_list
   a                a                1,2
   a                b                1,2
   b                c                1,2

>dt2

departure       arrival         expedition_list
   a                d                3
   d                c                3

I'd appreciate your help on this one.

Body:
You can try:

library(data.table)

dt <- dt[, .(expedition_list = toString(expedition_id)), by = .(departure, arrival)]
dt_list <- split(dt, dt$expedition_list)

list2env(
  setNames(
    dt_list,
    paste0('dt', 1:length(dt_list))
  ),
  .GlobalEnv
)

Output:

dt1

   departure arrival expedition_list
1:         a       a            1, 2
2:         a       b            1, 2
3:         b       c            1, 2

dt2

   departure arrival expedition_list
1:         a       d               3
2:         d       c               3


问:
How to delete reversed value on Oracle Database by using Query?
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

```<code>       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2
</code>```

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

答:
You can delete the data in many ways.  I might suggest:

```<code>delete from t
    where t.col1 > t.col2 or
          exists (select 1
                  from t t2
                  where t2.col1 = t.col2 and t2.col2 = t.col1
                 );
</code>```

Then . . . the more important thing.  Prevent this from happening in the future with a unique constraint/index:

```<code>create unique index unq_t_col1_col2 on
     t(least(col1, col2), greatest(col1, col2));
</code>```

Actually, I would fix the data so col1 < col2 always and add the constraints:

```<code>unique (col1, col2),
check (col1 < col2)
</code>```

Nothing like keeping the data clean to keep your database safe.

Body:
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

Body:
You can delete the data in many ways.  I might suggest:

delete from t
    where t.col1 > t.col2 or
          exists (select 1
                  from t t2
                  where t2.col1 = t.col2 and t2.col2 = t.col1
                 );

Then . . . the more important thing.  Prevent this from happening in the future with a unique constraint/index:

create unique index unq_t_col1_col2 on
     t(least(col1, col2), greatest(col1, col2));

Actually, I would fix the data so col1 < col2 always and add the constraints:

unique (col1, col2),
check (col1 < col2)

Nothing like keeping the data clean to keep your database safe.


问:
apache http rewrite/redirect based on ip
I want to redirect an ip to another view of my website, for example, I want the visitor from ip x to see

www.xxx.com?_DEBUG=1

while all other visitors see the normal www.xxx.com,
how would I do this in apache config file, what directives are used?

答:
Here is an example of a rewrite configuration to do what you want - put this inside the virtual host for www.xxx.com on your server:

```<code>RewriteCond %{REMOTE_ADDR} 1.2.3.4
RewriteCond %{QUERY_STRING} !_DEBUG=1
#RewriteRule ^/(.*)$ /$1?_DEBUG=1 [QSA,R,L]
RewriteRule ^/(.*)$ /$1?_DEBUG=1 [QSA,L]
</code>```

A couple of notes:

Change 1.2.3.4 to whatever IP you need

The second RewriteCond prevents URLs already re-written to include _DEBUG=1 from being re-written again

There are two versions of the actual RewriteRule; the first version (commented out) actually performs a redirect.  Use this if you actually want the HTTP client to submit a second request to the server including the _DEBUG=1 argument.  The downside is that if you're combining GET and POST data, this method will not work.

The second version of the RewriteRule is what I recommend you use...it doesn't perform a redirect.  Instead it just appends the _DEBUG=1 parameter to the HTTP request internally in Apache before the request is handled.

Body:
Here is an example of a rewrite configuration to do what you want - put this inside the virtual host for www.xxx.com on your server:

RewriteCond %{REMOTE_ADDR} 1.2.3.4
RewriteCond %{QUERY_STRING} !_DEBUG=1
#RewriteRule ^/(.*)$ /$1?_DEBUG=1 [QSA,R,L]
RewriteRule ^/(.*)$ /$1?_DEBUG=1 [QSA,L]

A couple of notes:

Change 1.2.3.4 to whatever IP you need

The second RewriteCond prevents URLs already re-written to include _DEBUG=1 from being re-written again

There are two versions of the actual RewriteRule; the first version (commented out) actually performs a redirect.  Use this if you actually want the HTTP client to submit a second request to the server including the _DEBUG=1 argument.  The downside is that if you're combining GET and POST data, this method will not work.

The second version of the RewriteRule is what I recommend you use...it doesn't perform a redirect.  Instead it just appends the _DEBUG=1 parameter to the HTTP request internally in Apache before the request is handled.


问:
How to create a iter repeats last element in rust
How to create a iter repeats last element?

for example:

[1, 2, 3] => [1, 2, 3, 3, 3, ...]

My attempt:

```<code>fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(v[v.len()]));
    println!("{}", vi.next().unwrap())
}
</code>```

error[E0271]: type mismatch resolving `<std::iter::Repeat<{integer}> as std::iter::IntoIterator>::Item == &{integer}`
   --> projects\notedown-ast\src\traits\to_html.rs:120:27
    |
120 |     let mut vi = v.iter().chain(repeat(v[v.len()]));
    |                           ^^^^^ expected integer, found `&{integer}`

error[E0599]: no method named `next` found for struct `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>` in the current scope
   --> projects\notedown-ast\src\traits\to_html.rs:121:23
    |
121 |     println!("{}", vi.next().unwrap())
    |                       ^^^^ method not found in `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>`
    |
    = note: the method `next` exists but the following trait bounds were not satisfied:
            `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>> : std::iter::Iterator`

error: aborting due to 2 previous errors
```

答:
Here is a generalized implementation:

```<code>struct LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    it: I,
    next: Option<I::Item>,
    last: bool,
}

impl<I> LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    fn new<It>(it: It) -> Self
    where
        It: IntoIterator<IntoIter = I, Item = I::Item>,
    {
        LastRepeatIter {
            it: it.into_iter(),
            next: None,
            last: false,
        }
    }
}

impl<I> Iterator for LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.last {
            match self.it.next() {
                None => self.last = true,
                Some(next) => self.next = Some(next),
            }
        }

        self.next.clone()
    }
}

#[test]
fn it_works() {
    let mut it = LastRepeatIter::new(vec![1, 2, 3]);

    assert_eq!(it.next(), Some(1));
    assert_eq!(it.next(), Some(2));
    assert_eq!(it.next(), Some(3));
    assert_eq!(it.next(), Some(3));
    assert_eq!(it.next(), Some(3));
}
</code>```

At each iteration, the code checks if there is a next item:

if there is one, next is stored inside the next field,

if there is none, the last flag is put at true.

Body:
How to create a iter repeats last element?

for example:

[1, 2, 3] => [1, 2, 3, 3, 3, ...]

My attempt:

fn main() {
    let v = vec![1, 2, 3];
    let mut vi = v.iter().chain(repeat(v[v.len()]));
    println!("{}", vi.next().unwrap())
}

error[E0271]: type mismatch resolving `<std::iter::Repeat<{integer}> as std::iter::IntoIterator>::Item == &{integer}`
   --> projects\notedown-ast\src\traits\to_html.rs:120:27
    |
120 |     let mut vi = v.iter().chain(repeat(v[v.len()]));
    |                           ^^^^^ expected integer, found `&{integer}`

error[E0599]: no method named `next` found for struct `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>` in the current scope
   --> projects\notedown-ast\src\traits\to_html.rs:121:23
    |
121 |     println!("{}", vi.next().unwrap())
    |                       ^^^^ method not found in `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>>`
    |
    = note: the method `next` exists but the following trait bounds were not satisfied:
            `std::iter::Chain<std::slice::Iter<'_, {integer}>, std::iter::Repeat<{integer}>> : std::iter::Iterator`

error: aborting due to 2 previous errors

Body:
Here is a generalized implementation:

struct LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    it: I,
    next: Option<I::Item>,
    last: bool,
}

impl<I> LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    fn new<It>(it: It) -> Self
    where
        It: IntoIterator<IntoIter = I, Item = I::Item>,
    {
        LastRepeatIter {
            it: it.into_iter(),
            next: None,
            last: false,
        }
    }
}

impl<I> Iterator for LastRepeatIter<I>
where
    I: Iterator,
    I::Item: Clone,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        if !self.last {
            match self.it.next() {
                None => self.last = true,
                Some(next) => self.next = Some(next),
            }
        }

        self.next.clone()
    }
}

#[test]
fn it_works() {
    let mut it = LastRepeatIter::new(vec![1, 2, 3]);

    assert_eq!(it.next(), Some(1));
    assert_eq!(it.next(), Some(2));
    assert_eq!(it.next(), Some(3));
    assert_eq!(it.next(), Some(3));
    assert_eq!(it.next(), Some(3));
}

At each iteration, the code checks if there is a next item:

if there is one, next is stored inside the next field,

if there is none, the last flag is put at true.


问:
When clicking on the child don't consider the parent
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">Click me</div>
   <div class="child">Click me</div>
</div></code>```

答:
No, the CSS :active behavior cannot be changed through CSS.

The :active pseudo-class is commonly used on  and  elements. Other common targets of this pseudo-class include elements that contain an activated element, and form elements that are being activated through their associated .

A solution for this would to create your own behavior through JavaScript. When clicking the parent, check if the mouse is on the parent itself or a child inside of it. When it is the parent add a class to the parent element. And remove that class when releasing the mouse.

const parent = document.querySelector('.parent');

parent.addEventListener('mousedown', function(event) {
  if (event.target === parent) {
    parent.classList.add('active');
  }
});

parent.addEventListener('mouseup', function(event) {
  parent.classList.remove('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent.active {
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }</code>```

Click me

Click me

```

Body:
I want some method to convince CSS that when I click on one of the children inside the parent element don't consider that I clicked also on the parent element.
I want you to try clicking on one of the children inside the parent.

  .parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent:active{
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }

Click me

Click me

Body:
No, the CSS :active behavior cannot be changed through CSS.

The :active pseudo-class is commonly used on  and  elements. Other common targets of this pseudo-class include elements that contain an activated element, and form elements that are being activated through their associated .

A solution for this would to create your own behavior through JavaScript. When clicking the parent, check if the mouse is on the parent itself or a child inside of it. When it is the parent add a class to the parent element. And remove that class when releasing the mouse.

const parent = document.querySelector('.parent');

parent.addEventListener('mousedown', function(event) {
  if (event.target === parent) {
    parent.classList.add('active');
  }
});

parent.addEventListener('mouseup', function(event) {
  parent.classList.remove('active');
});

.parent{
    background: blue;
    padding:20px;
    text-align: center;
    margin: 0 auto;
    height: 300px;
    width: 300px;
  }
  .parent.active {
    background: #ddd;
  }
  .child{
    background: red;
    float: left;
    padding: 5px;
    height: 150px;
    width: 150px;
    font-size: 4em;
  }
  .child:nth-child(odd){
    background: pink;
  }

<div class="parent">
  <div class="child">Click me</div>
   <div class="child">Click me</div>
</div>


问:
Android: database is not saving insert
I'm hoping this is a bit of no-brainer.  I'm doing something like:

```<code>values.put("name", name);
m_db.insert(PHOTOS, null, values);

m_db.close();
</code>```

afterwards, when I check (either in my code or the adb console), nothing is there?

What am I missing?

答:
i think this url will Help you
http://androidinsertdata.blogspot.com/2011/05/deals-with-database.html</p>

Title: Android: database is not saving insert

Body:
I'm hoping this is a bit of no-brainer.  I'm doing something like:

values.put("name", name);
m_db.insert(PHOTOS, null, values);

m_db.close();

afterwards, when I check (either in my code or the adb console), nothing is there?

What am I missing?


问:
Time and date data on x-Axis in Python
ON the Raspberry PI 4, I read out a sensor (via HAT) and write the dataset into a .csv file. At the same time, I write for every single value the time and date into the next column.
How do I plot these datas?
I want to set the x axis as the time axis, so eg. at 11:23:48 I measured 4,3 V.

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tkinter import filedialog
from tkinter import *
import sys
import warnings
if not sys.warnoptions:
    warnings.simplefilter("ignore")

root = Tk()
root.filename = filedialog.askopenfilename ( initialdir = "/home/pi", title = "Datei auswählen", filetypes = (("Comma Seperated Values (CSV)", "*.csv"), ("Alle Dateien", "*.*")) )

df = pd.read_csv(root.filename, delimiter = '\t', decimal = ',')
# pressure = df.loc [:, "Chan 0"]
temp = df.loc [:, "Chan 0 "]
df["Uhrzeit"] = df["Uhrzeit"].astype("str")
time = df.loc [:, "Uhrzeit"]
temp_echt = (52.2357*temp)-100.0001
# plt.figure (1)
# plt.plot (pressure, lw = 0.8)
plt.figure (2)
plt.ylabel ('Temperatur [°C]')
plt.plot(time,temp_echt, lw = 1)
plt.xticks (rotation = 45)
print (time)
plt.show()
</code>```

Output:plot

So what is going on here, why does the plot look so weird?
Btw: this is the csv file:csv

答: The plot looks right to me. You have multiple same times and same Chan 0's, thats why multiple lines are over each other. It looks indeed weird. You could try to take only one Chan 0 per same time or just wait until you have more data, it should look more and more alright with the time.</p>

Title: Time and date data on x-Axis in Python

Body:
ON the Raspberry PI 4, I read out a sensor (via HAT) and write the dataset into a .csv file. At the same time, I write for every single value the time and date into the next column.
How do I plot these datas?
I want to set the x axis as the time axis, so eg. at 11:23:48 I measured 4,3 V.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tkinter import filedialog
from tkinter import *
import sys
import warnings
if not sys.warnoptions:
    warnings.simplefilter("ignore")

root = Tk()
root.filename = filedialog.askopenfilename ( initialdir = "/home/pi", title = "Datei auswählen", filetypes = (("Comma Seperated Values (CSV)", "*.csv"), ("Alle Dateien", "*.*")) )

df = pd.read_csv(root.filename, delimiter = '\t', decimal = ',')
# pressure = df.loc [:, "Chan 0"]
temp = df.loc [:, "Chan 0 "]
df["Uhrzeit"] = df["Uhrzeit"].astype("str")
time = df.loc [:, "Uhrzeit"]
temp_echt = (52.2357*temp)-100.0001
# plt.figure (1)
# plt.plot (pressure, lw = 0.8)
plt.figure (2)
plt.ylabel ('Temperatur [°C]')
plt.plot(time,temp_echt, lw = 1)
plt.xticks (rotation = 45)
print (time)
plt.show()

Output:plot

So what is going on here, why does the plot look so weird?
Btw: this is the csv file:csv


问:
Joining Sqlite table on Subqueries
I'm trying to join a sqlite table based on an grouping column, 'year'. I've started with a select clause that returns all the years in the database, and now I want to subquery the same table for various statistics and join it based on the year. The following is what I have.

```<code>select strftime('%Y', `date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = t.year

left join (
    select sum(amount) as `income`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = t.year

group by strftime('%Y', `date`, 'unixepoch');
</code>```

When I try to run that sql statement, I get 'no such column: t.year'. Why can't I join based on the aliased column?

答:
The table transactions aliased as t does not contain a column year (which is a derived column).

Change to this:

```<code>select strftime('%Y', t.`date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = strftime('%Y', t.`date`, 'unixepoch')

left join (
    select sum(amount) as `income`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = strftime('%Y', t.`date`, 'unixepoch')

group by strftime('%Y', t.`date`, 'unixepoch');
</code>```

I guess there are other columns from the joined tables that you want to return although not in the current code.

I think that this is what you want to achieve:

```<code>select
  strftime('%Y', t.`date`, 'unixepoch') as `year` ,
  sum(case when type = -1 and user_id = 1 then amount end) as `expenses`,
  sum(case when type = 1 and user_id = 1 then amount end) as `income`
from transactions as t
group by strftime('%Y', t.`date`, 'unixepoch');
</code>```

Title: Joining Sqlite table on Subqueries

Body:
I'm trying to join a sqlite table based on an grouping column, 'year'. I've started with a select clause that returns all the years in the database, and now I want to subquery the same table for various statistics and join it based on the year. The following is what I have.

select strftime('%Y', `date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = t.year

left join (
    select sum(amount) as `income`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = t.year

group by strftime('%Y', `date`, 'unixepoch');

When I try to run that sql statement, I get 'no such column: t.year'. Why can't I join based on the aliased column?

Body:
The table transactions aliased as t does not contain a column year (which is a derived column).

Change to this:

select strftime('%Y', t.`date`, 'unixepoch') as `year` from transactions as t

left join (
    select sum(amount) as `expenses`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = -1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as e on e.year = strftime('%Y', t.`date`, 'unixepoch')

left join (
    select sum(amount) as `income`,
    strftime('%Y', `date`, 'unixepoch') as `year` from transactions
    where type = 1 and user_id = 1
    group by strftime('%Y', `date`, 'unixepoch')
) as i on i.year = strftime('%Y', t.`date`, 'unixepoch')

group by strftime('%Y', t.`date`, 'unixepoch');

I guess there are other columns from the joined tables that you want to return although not in the current code.

I think that this is what you want to achieve:

select
  strftime('%Y', t.`date`, 'unixepoch') as `year` ,
  sum(case when type = -1 and user_id = 1 then amount end) as `expenses`,
  sum(case when type = 1 and user_id = 1 then amount end) as `income`
from transactions as t
group by strftime('%Y', t.`date`, 'unixepoch');


问:
why bindCallback is not a function?
Hi I am using this rxjs libraray .I am getting this error
Rx.Observable.bindCallback is not a function

here is my code
http://jsbin.com/tuxucotake/edit?html,js,console,output

I am reading doc from here
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

```<code>var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
result.subscribe(x => console.log(x), e => console.error(e));
</code>```

答:
Based on @Günter Zöchbauer answer, bindCallback() is not anymore part of Observableso the correct usage for current version of RxJs (6) would be:

jsbin

html

```<code><!DOCTYPE html>
<html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
      <title>JS Bin</title>
    </head>
    <body>
    </body>
</html>
</code>```

js

```<code>var getJSONAsObservable = rxjs.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('https://mysafeinfo.com/api/data? list=englishmonarchs&format=json');
result.subscribe(
  ([data,textStatus,jqXhr]) => console.log(data),
  e => console.error(e));
</code>```

Respectively for node:

```<code>const Rx = require('rxjs')
const {bindCallback} = Rx;
var getJSONAsObservable = bindCallback(jQuery.getJSON);
....
</code>```

Title: why bindCallback is not a function?

Body:
Hi I am using this rxjs libraray .I am getting this error
Rx.Observable.bindCallback is not a function

here is my code
http://jsbin.com/tuxucotake/edit?html,js,console,output

I am reading doc from here
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html

var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
result.subscribe(x => console.log(x), e => console.error(e));

Body:
Based on @Günter Zöchbauer answer, bindCallback() is not anymore part of Observableso the correct usage for current version of RxJs (6) would be:

jsbin

html

<!DOCTYPE html>
<html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
      <title>JS Bin</title>
    </head>
    <body>
    </body>
</html>

js

var getJSONAsObservable = rxjs.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('https://mysafeinfo.com/api/data? list=englishmonarchs&format=json');
result.subscribe(
  ([data,textStatus,jqXhr]) => console.log(data),
  e => console.error(e));

Respectively for node:

const Rx = require('rxjs')
const {bindCallback} = Rx;
var getJSONAsObservable = bindCallback(jQuery.getJSON);
....


问:
Magento PHP check if user is logged in
I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.</p>

```<code><?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { ?>
   <li class="link wishlist" data-bind="scope: 'wishlist'">
    <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>
        <!-- ko if: wishlist().counter -->
        <span data-bind="text: wishlist().counter" class="counter qty"></span>
        <!-- /ko -->
    </a>
</li>
<li>Hello World</li>
?>
<?php
}
else {
?>
    <li>Not logged in</li>
<?php
}
?>

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "wishlist": {
                        "component": "Magento_Wishlist/js/view/wishlist"
                    }
                }
            }
        }
    }
</script>
</code>```

答:
You should not listen to all the users telling you to use objectManager. This is dirty and less performant. And you should always keep the logic in your block class instead of writing it in your template. Always separate buisness logic from the view.

The right way:

For this example I add a new method "isUserLoggedIn()" to the block class \Magento\Checkout\Block\Cart\Sidebar.

First I extend the class with my own Custom\Module\Block\Cart\Sidebar .

```<code><?php

namespace Custom\Module\Block\Cart;

class Sidebar extends \Magento\Checkout\Block\Cart\Sidebar
{
    private $customerSession;
    ...

    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        ...
    ) {

        $this->customerSession = $customerSession;
        ...
    }

    public function isLoggedIn()
    {
        return $this->customerSession->isLoggedIn();
    }
</code>```

Now you can use $block->isLoggedIn() in your template.

Title: Magento PHP check if user is logged in

Body:
I have the following code to see if a user is logged in. It sort of works as in it works within the customer area (user logged in) but doesn't work outside of the customer area even though the customer is still logged in.

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) { ?>

    <a <?php /* @escapeNotVerified */ echo $block->getLinkAttributes() ?>><?php echo $block->escapeHtml($block->getLabel()) ?>

Hello World

?>
<?php
}
else {
?>

Not logged in

<?php
}
?>

Body:
You should not listen to all the users telling you to use objectManager. This is dirty and less performant. And you should always keep the logic in your block class instead of writing it in your template. Always separate buisness logic from the view.

The right way:

For this example I add a new method "isUserLoggedIn()" to the block class \Magento\Checkout\Block\Cart\Sidebar.

First I extend the class with my own Custom\Module\Block\Cart\Sidebar .

<?php

namespace Custom\Module\Block\Cart;

class Sidebar extends \Magento\Checkout\Block\Cart\Sidebar
{
    private $customerSession;
    ...

    public function __construct(
        \Magento\Checkout\Model\Session $checkoutSession,
        ...
    ) {

        $this->customerSession = $customerSession;
        ...
    }

    public function isLoggedIn()
    {
        return $this->customerSession->isLoggedIn();
    }

Now you can use $block->isLoggedIn() in your template.


问:
I18nManager.forceRTL doesn't applies changes in first app load
I have an app that created by awesome React-native and my layout designed to be in RTL mode. I've set up an option for forcing the layout to be RTL but my option doesn't works in first app load after installing. This feature applies in second run.

I wrote this option in our index.js:

```<code>import React, { Component } from 'react';
import { I18nManager } from 'react-native';
import { Provider } from 'react-redux';

I18nManager.forceRTL(true);

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <MainStack />
        </PersistGate>
      </Provider>
    );
  }
}

export default App;
</code>```

答:
Make sure that on iOS, next to having added all relevant RTL locales to your Xcode project (e.g. Arabic). You should also make sure that your .ipa contains .lproj folders for each locale. Otherwise iOS doesn't pick up on the supported languages.

This is a common issue in React Native projects where you don't typically write a lot of Swift/Obj-C code & most of the translations happen in JavaScript (apart maybe from some stuff in you Info.plist).

Body:
I have an app that created by awesome React-native and my layout designed to be in RTL mode. I've set up an option for forcing the layout to be RTL but my option doesn't works in first app load after installing. This feature applies in second run.

I wrote this option in our index.js:

import React, { Component } from 'react';
import { I18nManager } from 'react-native';
import { Provider } from 'react-redux';

I18nManager.forceRTL(true);

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <MainStack />
        </PersistGate>
      </Provider>
    );
  }
}

export default App;


问:
AngularJS Parent and child looping with pagination
How would I possibly loop the parent and child with next page implementation. I want my child to be in the next page with the copy of parent div data which I have set the child items limit to 5.

HTML:

    {{parent.data1}}

        {{child.data1}}

    Page {{$index}}

```

<p><strong>JavaScript</strong>:</p>

```parent.items = [];
var lineItems = item.child.length;
var totalchildpage = Math.ceil(childItems / 5);

for (var f = 1; f <= totalchildpage; f++) {
    parent.items.push(angular.copy(parent.items));
}
```

<p>I want my result to this:</p>

```

 parent 1

     child1

     child2

     child3

     child4

     child5

Page 1

parent 1

     child6

Page 2

parent 2

     child1

Page 1

```

答:
Specify the index at which to begin limitation using the optional second parameter of the limitTo filter:

    {{parent.data1}}
    ̶<̶d̶i̶v̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶c̶h̶i̶l̶d̶ ̶i̶n̶ ̶p̶a̶r̶e̶n̶t̶.̶c̶h̶i̶l̶d̶ ̶|̶ ̶s̶t̶a̶r̶t̶F̶r̶o̶m̶:̶$̶i̶n̶d̶e̶x̶*̶5̶ ̶|̶ ̶l̶i̶m̶i̶t̶T̶o̶ ̶:̶ ̶5̶"̶>̶

        {{child.data1}}

    Page {{$index}}

```

For more information, see

AngularJS limitTo Filter API Reference

Body:
How would I possibly loop the parent and child with next page implementation. I want my child to be in the next page with the copy of parent div data which I have set the child items limit to 5.

HTML:

    {{parent.data1}}

        {{child.data1}}

    Page {{$index}}

JavaScript:

parent.items = [];
var lineItems = item.child.length;
var totalchildpage = Math.ceil(childItems / 5);

for (var f = 1; f <= totalchildpage; f++) {
    parent.items.push(angular.copy(parent.items));
}

I want my result to this:

 parent 1

     child1

     child2

     child3

     child4

     child5

Page 1

parent 1

     child6

Page 2

parent 2

     child1

Page 1

Body:
Specify the index at which to begin limitation using the optional second parameter of the limitTo filter:

<div ng-repeat="parent in parent.items">
    {{parent.data1}}
    ̶<̶d̶i̶v̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶c̶h̶i̶l̶d̶ ̶i̶n̶ ̶p̶a̶r̶e̶n̶t̶.̶c̶h̶i̶l̶d̶ ̶|̶ ̶s̶t̶a̶r̶t̶F̶r̶o̶m̶:̶$̶i̶n̶d̶e̶x̶*̶5̶ ̶|̶ ̶l̶i̶m̶i̶t̶T̶o̶ ̶:̶ ̶5̶"̶>̶
    <div ng-repeat="child in parent.child | limitTo : 5 : $index*5">
        {{child.data1}}
    </div>
    Page {{$index}}
</div>

For more information, see

AngularJS limitTo Filter API Reference


问:
CloudFormation Stacks with Exported Values and Taskcat
I have a bunch of stacks I'm trying to test with Taskcat in our CI pipeline, but some of these stacks rely on other stacks and their exported values.

Does Taskcat have the capability to wait for other stacks in the tests section of the config to complete first before deploying other stacks in the list?

I'm using a taskcat config similar to this:

```<code>project:
  name: cfn-test
  regions:
    - us-east-1
tests:
  test-template-with-exported-values:
    parameters:
      EnvironmentId: ci
    template: ./test-template-1.yml
  test-template-using-exported-values:
    parameters:
      EnvironmentId: ci
    template: ./test-template-2.yml
</code>```

The second test will fail immediately with a similar error shown below:

```<code>No export named SomeExportedValue found
</code>```

答:
At the moment, no, but it's in our backlog. See this GitHub issue for tracking.

https://github.com/aws-quickstart/taskcat/issues/322

We'll post updates there, including the development build version when it becomes available.

Thx

-Andrew

Body:
I have a bunch of stacks I'm trying to test with Taskcat in our CI pipeline, but some of these stacks rely on other stacks and their exported values.

Does Taskcat have the capability to wait for other stacks in the tests section of the config to complete first before deploying other stacks in the list?

I'm using a taskcat config similar to this:

project:
  name: cfn-test
  regions:
    - us-east-1
tests:
  test-template-with-exported-values:
    parameters:
      EnvironmentId: ci
    template: ./test-template-1.yml
  test-template-using-exported-values:
    parameters:
      EnvironmentId: ci
    template: ./test-template-2.yml

The second test will fail immediately with a similar error shown below:

No export named SomeExportedValue found


问:
How to call browser back button in Angular Project
In my Angular 8 project, I currently have a landing page (template-table.component) that shows a list of items that can be filtered and sorted. The filter and sort are added to the route queryParams(ex: "/template-table?name=another&type=Type%201"). If you select an item in the list, you will be taken to another route (that has the template-details.component) that has more details on that item. This details page will have a 'back to list' button that should take the user back to their previous list page.

Since I want the user to be taken back to the list with the filter params they were previously  using, I can't simply go to the route of that component, instead I want to go back in history (like how the browser back button works). So, how do I set an element to link to what the browser back button would be link to?

So, this is the bare minimum of my template-detail.component.html:

```<code><h1>template-details works!</h1>
<div>{{template}}</div>
<div>{{id}}</div>
<div><a routerLink="/template-table/">Return to list page</a></div>
</code>```

I think I also would like to check the route to see if it's the template-table component route with query params, and not an unrelated route. (So, the route would need to be like: "/template-table?params=xxx", and couldn't be "google.com". If the browser back button isn't related to the template-table, then it should go to "/template-table" without any params (or maybe my 404 page.)

The basic functionality that I'm wanting to achieve is for the user to be able to filter a list, go to another route with more info on a list item, and then return to the list with the same filters they previously added. If there would be a better way to do this than by trying to access the browser's back button, I'd love to hear about it.

Thank you for any assistance you can provide.

答:
Arthurofos' suggestion to use the Location service seems to be relevant, as it can be used to navigate back to the view you were in prior to routing to a new component.

Of course, while there are very Javacsripty-ways to do these sort of things, it's always recommended to use Angular's libraries, if such an alternative exists.

In our case, it does, and it presents itself as the 'Location' service you can inject into your component.

```<code>import { Location } from '@angular/common';

@Component({
  // Other component info
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]
})
export class TestComponent {
   constructor(private location: Location, // Other constructor arguments) { }

   public goBack() {
      this.location.back()
   }
}
</code>```

https://alligator.io/angular/location-service/

Body:
In my Angular 8 project, I currently have a landing page (template-table.component) that shows a list of items that can be filtered and sorted. The filter and sort are added to the route queryParams(ex: "/template-table?name=another&type=Type%201"). If you select an item in the list, you will be taken to another route (that has the template-details.component) that has more details on that item. This details page will have a 'back to list' button that should take the user back to their previous list page.

Since I want the user to be taken back to the list with the filter params they were previously  using, I can't simply go to the route of that component, instead I want to go back in history (like how the browser back button works). So, how do I set an element to link to what the browser back button would be link to?

So, this is the bare minimum of my template-detail.component.html:

template-details works!

{{template}}

{{id}}

Return to list page

I think I also would like to check the route to see if it's the template-table component route with query params, and not an unrelated route. (So, the route would need to be like: "/template-table?params=xxx", and couldn't be "google.com". If the browser back button isn't related to the template-table, then it should go to "/template-table" without any params (or maybe my 404 page.)

The basic functionality that I'm wanting to achieve is for the user to be able to filter a list, go to another route with more info on a list item, and then return to the list with the same filters they previously added. If there would be a better way to do this than by trying to access the browser's back button, I'd love to hear about it.

Thank you for any assistance you can provide.

Body:
Arthurofos' suggestion to use the Location service seems to be relevant, as it can be used to navigate back to the view you were in prior to routing to a new component.

Of course, while there are very Javacsripty-ways to do these sort of things, it's always recommended to use Angular's libraries, if such an alternative exists.

In our case, it does, and it presents itself as the 'Location' service you can inject into your component.

import { Location } from '@angular/common';

@Component({
  // Other component info
  providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}]
})
export class TestComponent {
   constructor(private location: Location, // Other constructor arguments) { }

   public goBack() {
      this.location.back()
   }
}

https://alligator.io/angular/location-service/


问:
angular 9 component rendering
I upgraded an angular 8 application to angular 9. I'm seeing some rendering changes in the DOM.

In Angular 8, the rendering component will be at the top of the current component. But in Angular 9, it another way around.

angular 8 renders

angular 9 renders

Is there any reason for this change or any setting is required?

答:
Angular 9 uses Ivy for rendering the template.
"Ivy is the code name for Angular's next-generation compilation and rendering pipeline. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine."
Ivy documentation

If nothing else changed in your code, this is the reason why:
https://angular.io/guide/ivy

Title: angular 9 component rendering


问:
select box option remove() works but hide() did not
I would like to show and hide select box options depending on the value of an input field. Strangely enough, this only works with $('thisOption'). Remove () but NOT with:

```<code>$('thisOption').hide()
// or:
$('thisOption').css('visibility', 'hidden')
</code>```

$('#Selectkk').Load('JSON / kk_select_box.php')
// callback after select box is ready
function() {
  var i, filter,
    $ input = $('# ort_kk'),
    $ options = $('# select_kk').find('option')
  $ Input.keyup(function() {
    filter = $ input.val()
    $ Options.each(function() {
      var option_text = $(this).text();
      var pos = option_text.search(filter);
      if (pos == -1) {
        $(This).remove();
      }
    })
  });
}
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='input-group'>
  <input name='ort_kk' id='ort_kk' value=''>
</div>
<div id='selectkk'> </div></code>```

I don't want to remove the options. If the input field is corrected, all options for filtering must still be there. So roughly:

```<code>if (pos == -1) {
  $(This).hide();
} else {
  $(This).show();
}
</code>```

I hope I was able to describe the problem clearly and hope for your help.
Thank you very much
Thomas

答:
Sorry!! Once again:
Yes, code works at all.

```<code>$('#selectkk').load('JSON/kk_select_box.php?' + $.param({
          kk: encodeURIComponent(''),
         plz: encodeURIComponent(''),
         ort: encodeURIComponent(''),
     }),
                // callback function after selectbox has load
                function(){
                    var i, filter,
                    $input = $('#ort_kk'),
                    $options =$('#select_kk').find('option')
                    $input.keyup(function(){
                            filter = $input.val()
                            $options.each(function(){
                                var option_text=$(this).text();
                                var pos = option_text.search(filter);
                                if( pos == -1 ){
                                    $(this).remove(); }
                                })

                    });

                }
           );
</code>```

But nevertheless, this won't work:

```<code>...
    if (pos == -1) {
      $(this).hide();
    } else {
      $(this).show();
    }
...
</code>```

Body:
I would like to show and hide select box options depending on the value of an input field. Strangely enough, this only works with $('thisOption'). Remove () but NOT with:

$('thisOption').hide()
// or:
$('thisOption').css('visibility', 'hidden')

$('#Selectkk').Load('JSON / kk_select_box.php')
// callback after select box is ready
function() {
  var i, filter,
    $ input = $('# ort_kk'),
    $ options = $('# select_kk').find('option')
  $ Input.keyup(function() {
    filter = $ input.val()
    $ Options.each(function() {
      var option_text = $(this).text();
      var pos = option_text.search(filter);
      if (pos == -1) {
        $(This).remove();
      }
    })
  });
}
);

  <input name='ort_kk' id='ort_kk' value=''>

I don't want to remove the options. If the input field is corrected, all options for filtering must still be there. So roughly:

if (pos == -1) {
  $(This).hide();
} else {
  $(This).show();
}

I hope I was able to describe the problem clearly and hope for your help.
Thank you very much
Thomas

Body:
Sorry!! Once again:
Yes, code works at all.

$('#selectkk').load('JSON/kk_select_box.php?' + $.param({
          kk: encodeURIComponent(''),
         plz: encodeURIComponent(''),
         ort: encodeURIComponent(''),
     }),
                // callback function after selectbox has load
                function(){
                    var i, filter,
                    $input = $('#ort_kk'),
                    $options =$('#select_kk').find('option')
                    $input.keyup(function(){
                            filter = $input.val()
                            $options.each(function(){
                                var option_text=$(this).text();
                                var pos = option_text.search(filter);
                                if( pos == -1 ){
                                    $(this).remove(); }
                                })

                    });

                }
           );

But nevertheless, this won't work:

...
    if (pos == -1) {
      $(this).hide();
    } else {
      $(this).show();
    }
...


问:
MobX with React best practice with observer
I'm not really facing an issue, it's more like I'm wondering what is the best way I should use mobx with react. So here's my situation:

I'am fairly new to mobx but I've got years of experience using react (mostly with redux).
My new project is using mobx-state-tree alongside with mobx-react-lite in order to connect my components with the function observer wrapping the component. I've set up a root store with multiples stores in it.
I'm really enthusiastic about it for now but I would like some recommendations:

Should I use the containers logic which is pretty common with redux, which means I should only connect a "container" component who will handle the connection with my stores and spread it to its children ? Or should I connect directly with an observer as many components which needs to be provided with data from a store ?

Is the second option more optimized, technically speaking ? Is it still a good idea according to React philosophy ? What's YOUR opinion on this subject ?

Any answer would be really appreciated

答:
Technically, you don't need container/presentation concept. You can use context, or localStore, or globalStore but it doesn't mean container/presentation not useful sometimes.

Mobx patches shouldComponentUpdate lifecycle, and basically optimizes components rendering for you.
mobx-react mentioned in their docs that the more components connected with observer, the better.

It's very common pattern to see shouldComponentUpdate with a bulky checks to avoid unnecessary renders. This isn't needed with MobX at all.

My opinion is that patterns change on monthly basis, so learning the general concepts can ease your transition from global store, local store, context, hooks and other api changes.

React component patterns also change overtime.

Use what you need and understand right now. If it won't matter in 5 years, don't spend more than 5 minutes to think about it. You can always do a fun refactor.

Further reading:

https://mobx.js.org/README.html

https://mobx-react.js.org


问:
How User account be locked for 30 min after 5 unsuccessful login attempts with asp.net?
I am using asp.net membership provider for managing users. I have a requirement to lock user accounts for 30 mins after 5 unsuccessful attempts. How should I do that using asp.net membership provider on the server side?

Also I want that 'Passwords should expire after 3 months', 'Last 10 used passwords should be remembered'. Is there any way to solve these requirements.

答:
you can do all the above mentioned functionalities by creating proper tables in database.
i.e.,

create one table to store count of wrong attempts, increment count when wrong attempt occurs based on the primary key i.e user name, within 5 attempts if he logs successfully then try to make that count to null

While locking the user after 5 unsuccessful attempts store the time and write one script to check that time continuously, when it meets 30mins call unlock method

For password also take day count, i.e., from changed date, each time when user logs in after checking user validity check for password day count if it cross 3days prompt them to change

If you are taking user name as primary key, create one more table to store max 10 passwords for each user, while inserting password to this table(when user changes his password),check the table for number rows for that user if it is 10 then based on the last lesser date you can delete that row and insert new password and you can compare new password with old passwords also while inserting


问:
SwiftUI Reload View after dismissing a sheet
I have a bool value in UserDefaults to check if user is logged in or not.
In my first page I have a Header where when user click the profile pic it shows a modal (using .sheet) and inside that I have a button for user to LogOut.

How can I change the View when user presses the LogOut button and dismisses the modal?

Or how can I reload the main page after user clicks the LogOut button and dismisses the modal in order to check the new Bool value?

```<code>struct Home: View {

    var body: some View {
        ScrollView {
            VStack {
                // MARK: Header
                Header(title: "Home")
            }
            Spacer()
        }
        .padding(20)
    }
}

struct Header: View {

    public var title: String = ""
    @State private var showProfile = false

    var body: some View {
        HStack {
            // MARK: - User Profile
            Image("profile")
                .resizable()
                .clipShape(Circle())
                .frame(width: 50, height: 50)
                .onTapGesture {
                    print("⚠ Profile has been tapped.")
                    self.showProfile.toggle()
            }
            .sheet(isPresented: $showProfile) {
                Account(showProfile: self.$showProfile)
            }

        }
    }
}

struct Account: View {

    @Binding var showProfile: Bool

    var body: some View {
        NavigationView {

            // MARK: - Account Sections
            List {

                // MARK: - Log Out -
                Section {
                    Button(action: {
                        print("❌ User has been logged out.")
                        self.showProfile.toggle()

                    }) {
                        Text("Log Out")
                            .bold()
                            .foregroundColor(.red)
                    }
                }
            }

                // MARK: - NavigationBar Settings
                .navigationBarTitle("Account", displayMode: .inline)
        }
    }
}
</code>```

and this is my UserDefault class

```<code>class UsersSettings: ObservableObject {

    @Published var isLoggedIn: Bool = UserDefaults.standard.bool(forKey: "isLogged") {
        didSet {
            UserDefaults.standard.set(self.isLoggedIn, forKey: "isLogged")
            print(UserDefaults.standard.bool(forKey: "isLogged"))
        }
    }
}
</code>```

答:
I managed to achieve what I was looking for from this video:
Login Page Using Firebase With SwiftUI - Integrating Login Page With Firebase Using SwiftUI</p>

Body:
I have a bool value in UserDefaults to check if user is logged in or not.
In my first page I have a Header where when user click the profile pic it shows a modal (using .sheet) and inside that I have a button for user to LogOut.

How can I change the View when user presses the LogOut button and dismisses the modal?

Or how can I reload the main page after user clicks the LogOut button and dismisses the modal in order to check the new Bool value?

struct Home: View {

    var body: some View {
        ScrollView {
            VStack {
                // MARK: Header
                Header(title: "Home")
            }
            Spacer()
        }
        .padding(20)
    }
}

struct Header: View {

    public var title: String = ""
    @State private var showProfile = false

    var body: some View {
        HStack {
            // MARK: - User Profile
            Image("profile")
                .resizable()
                .clipShape(Circle())
                .frame(width: 50, height: 50)
                .onTapGesture {
                    print("⚠ Profile has been tapped.")
                    self.showProfile.toggle()
            }
            .sheet(isPresented: $showProfile) {
                Account(showProfile: self.$showProfile)
            }

        }
    }
}

struct Account: View {

    @Binding var showProfile: Bool

    var body: some View {
        NavigationView {

            // MARK: - Account Sections
            List {

                // MARK: - Log Out -
                Section {
                    Button(action: {
                        print("❌ User has been logged out.")
                        self.showProfile.toggle()

                    }) {
                        Text("Log Out")
                            .bold()
                            .foregroundColor(.red)
                    }
                }
            }

                // MARK: - NavigationBar Settings
                .navigationBarTitle("Account", displayMode: .inline)
        }
    }
}

and this is my UserDefault class

class UsersSettings: ObservableObject {

    @Published var isLoggedIn: Bool = UserDefaults.standard.bool(forKey: "isLogged") {
        didSet {
            UserDefaults.standard.set(self.isLoggedIn, forKey: "isLogged")
            print(UserDefaults.standard.bool(forKey: "isLogged"))
        }
    }
}


问:
All the possible combination and permutations with repetition on python
Essentially, I want to do

```<code>def get_all_possible(N)
    for i0 in range(N) :
        for i1 in range(N) :
            for i2 in range(N) :
             ... for iNm1 in range(N) : #Nm1 is N minus 1
                     yield [i0,i1,i2,i3,...,iNm1]
</code>```

and make a list of all the possible combination of number 0-N at each index and their permutations.
So when N=4 then there should be 4^4 possible combinations to be output.
This nested for loop is not efficient, and the code is not easily expandable to general N case.

答: try itertools.permutations or itertools.combinations

Body:
Essentially, I want to do

def get_all_possible(N)
    for i0 in range(N) :
        for i1 in range(N) :
            for i2 in range(N) :
             ... for iNm1 in range(N) : #Nm1 is N minus 1
                     yield [i0,i1,i2,i3,...,iNm1]

and make a list of all the possible combination of number 0-N at each index and their permutations.
So when N=4 then there should be 4^4 possible combinations to be output.
This nested for loop is not efficient, and the code is not easily expandable to general N case.


问:
How to append Newman htmlextra results to existing htmlextra report file
I have two Newman commands

newman run collection.json -e env.json --folder create_clients -d clients.csv -r htmlextra --htmlreporter-export reporter.html

newman run collection.json -e env.json --folder create_orders -d orders.csv -r htmlextra --htmlreporter-export reporter.html

After command #2 is executed reporter.html is overwritten, I want results to be appended.

Is there any possibility, please suggest, thanks.

答:
The --htmlreporter-export reporter.html parameter says to newman to save the html report in a file called reporter.html, so each time you run your command, this file is overwriten.

If you need to save your file with a different name, you can try to add a timestamp to it's name. On unix system, you can try something like :

```<code>--htmlreporter-export reporter-`date +'%y-%m-%d-%H-%M-%S'`.html
</code>```

This will append the output of the date command (formated in a Year-Month-Day-Hour-Min-Sec number string) in the file name, so if your commands runs more than one second, each result will be in a different file (you can of course add -%N to have nano seconds, or man date to seek other usefull values !).

But, you know, using standard outputs is a good practice : everybody using newman expect results to be found as newman/newman-run-report-[date].[json|xml|html], so unless you have an uncommun need to get the result elsewhere, Keep It Simple, and don't reinvent the wheel :-)

Body:
The --htmlreporter-export reporter.html parameter says to newman to save the html report in a file called reporter.html, so each time you run your command, this file is overwriten.

If you need to save your file with a different name, you can try to add a timestamp to it's name. On unix system, you can try something like :

--htmlreporter-export reporter-`date +'%y-%m-%d-%H-%M-%S'`.html

This will append the output of the date command (formated in a Year-Month-Day-Hour-Min-Sec number string) in the file name, so if your commands runs more than one second, each result will be in a different file (you can of course add -%N to have nano seconds, or man date to seek other usefull values !).

But, you know, using standard outputs is a good practice : everybody using newman expect results to be found as newman/newman-run-report-[date].[json|xml|html], so unless you have an uncommun need to get the result elsewhere, Keep It Simple, and don't reinvent the wheel :-)