问:
Defining variable after declaration throwing error not defined
I wanted to use a variable before its definition,

```<code>interface IProps extends WithStyles<typeof STYLES>;

const STYLES = () => ({ })
</code>```

it was not causing any error, but a warning

STYLES used before defined no-use-before-define

So I read somewhere and declare it before using, like following-

```<code>declare let STYLES: () => ({})

interface IProps extends WithStyles<typeof STYLES>;

STYLES = () => ({})
</code>```

Now the console is clear, no warnings and no error, but at run time I am getting an error that

ReferenceError: STYLES is not defined.

I have tried by making STYLES variable while defining, like

let STYLES = () => ({})

but it causing the error

Cannot redeclare block-scoped variable 'STYLES'.

So the question is, How can I define the variable before it's used without getting any warning and errors?

答:
Edit your tslint.json file and edit the rules part so that it looks like this</p>

```<code>"rules": {
    ...
    "no-use-before-declare": false
    ...
}
</code>```

Body:
I wanted to use a variable before its definition,

interface IProps extends WithStyles<typeof STYLES>;

const STYLES = () => ({ })

it was not causing any error, but a warning

STYLES used before defined no-use-before-define

So I read somewhere and declare it before using, like following-

declare let STYLES: () => ({})

interface IProps extends WithStyles<typeof STYLES>;

STYLES = () => ({})

Now the console is clear, no warnings and no error, but at run time I am getting an error that

ReferenceError: STYLES is not defined.

I have tried by making STYLES variable while defining, like

let STYLES = () => ({})

but it causing the error

Cannot redeclare block-scoped variable 'STYLES'.

So the question is, How can I define the variable before it's used without getting any warning and errors?

Body:
Edit your tslint.json file and edit the rules part so that it looks like this

"rules": {
    ...
    "no-use-before-declare": false
    ...
}


来源: stackexchange

问:
Iterating through objects with a common base class in contigious memory
I'm trying to figure out how I can iterate through a container (like std::vector) of objects that share a common base parent class contiguously in memory.

To demonstrate the problem let's use the following examples.

```<code>class Base
{
public:
    Base();
    virtual void doStuff() = 0;
};

class DerivedA : public Base
{
private:
    //specific A member variables
public:
    DerivedA();
    virtual void doStuff();
};

class DerivedB : public Base
{
private:
    //specific B member variables
public:
    DerivedB();
    virtual void doStuff();
};
</code>```

Now, using std::vector to iterate would keep the objects in contiguous memory but we would experience slicing as there isn't room for the derived properties.

So we have to use polymorphic technique using pointers like so

```<code>int main ()
{
    std::vector<Base*> container;
    container.push_back(new DerivedA());
    container.push_back(new DerivedB());

    for (std::vector<Base*>::iterator i = container.begin(); i!=container.end(); i++)
    {
        (*(*i)).doStuff();
    }
}
</code>```

As far as I know that should work fine given that the classes are implemented.

Problem:
Now, the vector contains pointers in contiguous memory but that does not mean that the addresses they are pointing to are.

So if I want to be able to delete and insert objects into the vector on the fly at any time, the objects will be spread all over the place in memory.

Question:
It seems like everyone suggests doing it the std::vector way but why isn't it considered problematic that it isn't iterable contiguously in memory (assuming we actually use the pointer)?

Am I forced to do it the copy-pasta way?

```<code>int main ()
{

    std::vector<DerivedA> containerA;
    DerivedA a;
    containerA.push_back(a);

    std::vector<DerivedB> containerB;
    DerivedB b;
    containerB.push_back(b);

    for (std::vector<DerivedA>::iterator i = containerA.begin(); i!=container.end(); i++)
    {
        (*i).doStuff();
    }
    for (std::vector<DerivedB>::iterator i = containerB.begin(); i!=container.end(); i++)
    {
        (*i).doStuff();
    }
}
</code>```

I'm guessing there might not be a real solution to this since keeping objects of various sizes linearly in memory doesn't really make sense but if anyone can give me some advice I'd appreciate it.

答:
If we have to store objects in array, their type must be fixed. Then we have these variants:

allocate dynamically and store pointers - if pointed objects are required to be continuous in memory, use custom allocator

use polymorphic type of a fixed size, e.g. union, as a storage type

For the second variant, the code could be something like this:

#include <new>

struct A {
    A() {}
    virtual void f() {}
};
struct B : A {
    B() {}
    void f() override {}
};

union U {
    A a;
    B b;
    U() {}
};

int main() {
    U u[2];
        new (&u[0]) A;
        new (&u[1]) B;
    ((A*)&u[0])->f(); // A::f
    ((A*)&u[1])->f(); // B::f
}
```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to figure out how I can iterate through a container (like std::vector) of objects that share a common base parent class contiguously in memory.

To demonstrate the problem let's use the following examples.

class Base
{
public:
    Base();
    virtual void doStuff() = 0;
};

class DerivedA : public Base
{
private:
    //specific A member variables
public:
    DerivedA();
    virtual void doStuff();
};

class DerivedB : public Base
{
private:
    //specific B member variables
public:
    DerivedB();
    virtual void doStuff();
};

Now, using std::vector to iterate would keep the objects in contiguous memory but we would experience slicing as there isn't room for the derived properties.

So we have to use polymorphic technique using pointers like so

int main ()
{
    std::vector<Base*> container;
    container.push_back(new DerivedA());
    container.push_back(new DerivedB());

    for (std::vector<Base*>::iterator i = container.begin(); i!=container.end(); i++)
    {
        (*(*i)).doStuff();
    }
}

As far as I know that should work fine given that the classes are implemented.

Problem:
Now, the vector contains pointers in contiguous memory but that does not mean that the addresses they are pointing to are.

So if I want to be able to delete and insert objects into the vector on the fly at any time, the objects will be spread all over the place in memory.

Question:
It seems like everyone suggests doing it the std::vector way but why isn't it considered problematic that it isn't iterable contiguously in memory (assuming we actually use the pointer)?

Am I forced to do it the copy-pasta way?

int main ()
{

    std::vector<DerivedA> containerA;
    DerivedA a;
    containerA.push_back(a);

    std::vector<DerivedB> containerB;
    DerivedB b;
    containerB.push_back(b);

    for (std::vector<DerivedA>::iterator i = containerA.begin(); i!=container.end(); i++)
    {
        (*i).doStuff();
    }
    for (std::vector<DerivedB>::iterator i = containerB.begin(); i!=container.end(); i++)
    {
        (*i).doStuff();
    }
}

I'm guessing there might not be a real solution to this since keeping objects of various sizes linearly in memory doesn't really make sense but if anyone can give me some advice I'd appreciate it.

ContentLicense: CC BY-SA 4.0


问:
Error starting sidekiq in Docker: "Please point sidekiq to a Rails 4/5 application"
Rails 5.2, Docker Compose, Sidekiq, Redis.

This is the docker-compose file:

```<code>version: '3.6'

services:
  redis:
    image: 'redis:4.0-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  sidekiq:
    depends_on:
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'

  api:
    build: .
    volumes:
      - './:/app'
    working_dir: /app
    command: puma
    ports:
      - 3000:3000
    depends_on:
      - db
      - redis
    environment:
      DATABASE_URL: postgres://postgres@db
  db:
    image: postgres:10.3-alpine

volumes:
  redis:
  postgres:
</code>```

It seems sidekiq cannot find my Rails app.

If I change sidekiq to start like this:

```<code>    command: bundle exec sidekiq -C config/sidekiq.yml -r /app
</code>```

then I get this error:

Spring was unable to find your config/application.rb file. Your
  project root was detected at /api, so spring looked for
  /api/config/application.rb but it doesn't exist. You can configure the
  root of your application by setting Spring.application_root in
  config/spring.rb.

If I instead add the working_dir setting to sidekiq:

```<code>sidekiq:
    depends_on:
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'
    working_dir:
      - '/app'
</code>```

then I get this error:

```<code>2019-05-27T20:27:59.770Z 1 TID-gr1e0d7n5 INFO: Booting Sidekiq 5.1.1 with redis options {:url=>"redis://redis:6379/0", :id=>"Sidekiq-server-PID-1"}
sidekiq_1  | could not connect to server: No such file or directory
sidekiq_1  |    Is the server running locally and accepting
sidekiq_1  |    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
</code>```

So how do I make sidekiq start correctly in its container?

I have seen these answers, which are similar but not this particular error:

Question 1

Question 2

Question 3

Question 4

答:
It seems sidekiq could not find the Rails app, which is fixed by adding the 'working-dir' setting, and then it could not find postgres, so I had to add the environment setting to point to postgres.

The final compose file is:

```<code>version: '3.6'

services:
  db:
    image: postgres:10.3-alpine
    ports:
      - '5432:5432'

  redis:
    image: 'redis:4.0-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  sidekiq:
    depends_on:
      - 'db'
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'
    working_dir: /app
    environment:
      DATABASE_URL: postgres://postgres@db

  api:
    build: .
    volumes:
      - './:/app'
    working_dir: /app
    command: puma
    ports:
      - 3000:3000
    depends_on:
      - db
      - redis
    environment:
      DATABASE_URL: postgres://postgres@db

volumes:
  redis:
  postgres:
</code>```

Body:
Rails 5.2, Docker Compose, Sidekiq, Redis.

This is the docker-compose file:

version: '3.6'

services:
  redis:
    image: 'redis:4.0-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  sidekiq:
    depends_on:
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'

  api:
    build: .
    volumes:
      - './:/app'
    working_dir: /app
    command: puma
    ports:
      - 3000:3000
    depends_on:
      - db
      - redis
    environment:
      DATABASE_URL: postgres://postgres@db
  db:
    image: postgres:10.3-alpine

volumes:
  redis:
  postgres:

It seems sidekiq cannot find my Rails app.

If I change sidekiq to start like this:

    command: bundle exec sidekiq -C config/sidekiq.yml -r /app

then I get this error:

Spring was unable to find your config/application.rb file. Your
  project root was detected at /api, so spring looked for
  /api/config/application.rb but it doesn't exist. You can configure the
  root of your application by setting Spring.application_root in
  config/spring.rb.

If I instead add the working_dir setting to sidekiq:

sidekiq:
    depends_on:
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'
    working_dir:
      - '/app'

then I get this error:

2019-05-27T20:27:59.770Z 1 TID-gr1e0d7n5 INFO: Booting Sidekiq 5.1.1 with redis options {:url=>"redis://redis:6379/0", :id=>"Sidekiq-server-PID-1"}
sidekiq_1  | could not connect to server: No such file or directory
sidekiq_1  |    Is the server running locally and accepting
sidekiq_1  |    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

So how do I make sidekiq start correctly in its container?

I have seen these answers, which are similar but not this particular error:

Question 1

Question 2

Question 3

Question 4

Body:
It seems sidekiq could not find the Rails app, which is fixed by adding the 'working-dir' setting, and then it could not find postgres, so I had to add the environment setting to point to postgres.

The final compose file is:

version: '3.6'

services:
  db:
    image: postgres:10.3-alpine
    ports:
      - '5432:5432'

  redis:
    image: 'redis:4.0-alpine'
    command: redis-server
    ports:
      - '6379:6379'
    volumes:
      - 'redis:/data'

  sidekiq:
    depends_on:
      - 'db'
      - 'redis'
    build: .
    command: bundle exec sidekiq -C config/sidekiq.yml
    volumes:
      - './:/app'
    env_file:
      - '.env'
    working_dir: /app
    environment:
      DATABASE_URL: postgres://postgres@db

  api:
    build: .
    volumes:
      - './:/app'
    working_dir: /app
    command: puma
    ports:
      - 3000:3000
    depends_on:
      - db
      - redis
    environment:
      DATABASE_URL: postgres://postgres@db

volumes:
  redis:
  postgres:


问:
SQL Server doesn't have the statistics for the table variable?
I found the MSDN says that "table variables don't have statistics"

https://msdn.microsoft.com/en-us/library/dd535534(v=sql.100).aspx

Also the following article says the SQL Server doesn't support the statistics for the table variable even in SQL 2014

"temporary tables beat table variables easily because their ability to have statistics improves query optimization dramatically. That remains true with the enhancements in SQL Server 2014."

https://www.brentozar.com/archive/2014/04/table-variables-good-temp-tables-sql-2014/

Then I do a test with SQL Server 2014, and found the statistics for the table variable, so in the SQL 2014, now the  table variable has the statistics , right?

```<code>USE tempdb;

DECLARE
@tb_table TABLE(
RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
,ProductName NVARCHAR(50) NOT NULL UNIQUE
,Indate DATETIME NOT NULL  DEFAULT(GETDATE())
,index IX_Indate NONCLUSTERED (Indate)
);

DECLARE
@table_variable_id bigint
;
SELECT TOP 1 @table_variable_id = object_id
FROM tempdb.sys.all_objects AS A
WHERE parent_object_id = 0
ORDER BY create_date DESC

SELECT
statistics_name = st.name
,table_name = OBJECT_NAME(st.object_id)
,column_name = COL_NAME(stc.object_id, stc.column_id)
FROM    tempdb.sys.stats AS st WITH(NOLOCK)
    INNER JOIN tempdb.sys.stats_columns AS stc WITH(NOLOCK)
        ON st.object_id = stc.object_id
        AND st.stats_id = stc.stats_id
 WHERE st.object_id = @table_variable_id
</code>```

BTW, if we remove the line ",index IX_Indate NONCLUSTERED (Indate)" from the script above, we still can see two statistics records in the output in SQL server even in SQL2012.

答:
No SQL Server doesn't maintain statistics for table variables.

There are three indexes on the table variable in your question and SQL Server inserts a corresponding three rows to sysidxstats

Contains a row for each index or statistics for tables and indexed views

These rows do have the 2 flag set in the status column indicating they are for statistics and so are returned by sys.stats but there is no corresponding statistics object.

You can see this using the query here (requires connecting via the DAC)

```<code>SELECT name,
       imageval
FROM   tempdb.sys.stats AS s
       INNER JOIN tempdb.sys.sysobjvalues AS o
               ON s.object_id = o.objid
                  AND s.stats_id = o.subobjid
WHERE  s.object_id = @table_variable_id;
</code>```

Which returns

```<code>+--------------------------------+----------+
|              name              | imageval |
+--------------------------------+----------+
| PK__#AD773B9__FFEE74513158C9C9 | NULL     |
| IX_Indate                      | NULL     |
| UQ__#AD773B9__DD5A978A62C2C478 | NULL     |
+--------------------------------+----------+
</code>```

The imageval which would contain the actual statistics is NULL.

This is nothing new. You also see the same in 2008 (though only for the PK and UQ as the inline index definition cannot be used there).

The maintenance of rowcounts is done separately and does not need a full blown statistics object with histogram. And again this is not new.

Body:
I found the MSDN says that "table variables don't have statistics"

https://msdn.microsoft.com/en-us/library/dd535534(v=sql.100).aspx

Also the following article says the SQL Server doesn't support the statistics for the table variable even in SQL 2014

"temporary tables beat table variables easily because their ability to have statistics improves query optimization dramatically. That remains true with the enhancements in SQL Server 2014."

https://www.brentozar.com/archive/2014/04/table-variables-good-temp-tables-sql-2014/

Then I do a test with SQL Server 2014, and found the statistics for the table variable, so in the SQL 2014, now the  table variable has the statistics , right?

USE tempdb;

DECLARE
@tb_table TABLE(
RowID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
,ProductName NVARCHAR(50) NOT NULL UNIQUE
,Indate DATETIME NOT NULL  DEFAULT(GETDATE())
,index IX_Indate NONCLUSTERED (Indate)
);

DECLARE
@table_variable_id bigint
;
SELECT TOP 1 @table_variable_id = object_id
FROM tempdb.sys.all_objects AS A
WHERE parent_object_id = 0
ORDER BY create_date DESC

SELECT
statistics_name = st.name
,table_name = OBJECT_NAME(st.object_id)
,column_name = COL_NAME(stc.object_id, stc.column_id)
FROM    tempdb.sys.stats AS st WITH(NOLOCK)
    INNER JOIN tempdb.sys.stats_columns AS stc WITH(NOLOCK)
        ON st.object_id = stc.object_id
        AND st.stats_id = stc.stats_id
 WHERE st.object_id = @table_variable_id

BTW, if we remove the line ",index IX_Indate NONCLUSTERED (Indate)" from the script above, we still can see two statistics records in the output in SQL server even in SQL2012.

Body:
No SQL Server doesn't maintain statistics for table variables.

There are three indexes on the table variable in your question and SQL Server inserts a corresponding three rows to sysidxstats

Contains a row for each index or statistics for tables and indexed views

These rows do have the 2 flag set in the status column indicating they are for statistics and so are returned by sys.stats but there is no corresponding statistics object.

You can see this using the query here (requires connecting via the DAC)

SELECT name,
       imageval
FROM   tempdb.sys.stats AS s
       INNER JOIN tempdb.sys.sysobjvalues AS o
               ON s.object_id = o.objid
                  AND s.stats_id = o.subobjid
WHERE  s.object_id = @table_variable_id;

Which returns

+--------------------------------+----------+
|              name              | imageval |
+--------------------------------+----------+
| PK__#AD773B9__FFEE74513158C9C9 | NULL     |
| IX_Indate                      | NULL     |
| UQ__#AD773B9__DD5A978A62C2C478 | NULL     |
+--------------------------------+----------+

The imageval which would contain the actual statistics is NULL.

This is nothing new. You also see the same in 2008 (though only for the PK and UQ as the inline index definition cannot be used there).

The maintenance of rowcounts is done separately and does not need a full blown statistics object with histogram. And again this is not new.


问:
Looking to send Python API request using cURL
I am looking to send a POST request using Python to the OANDA API to open an order. They do not have a Python wrapper and use cURL, so I have had to try and convert from cURL to Python. I have done so using https://curl.trillworks.com/ -- but converting this next one does not work.

You can view the OANDA API documentation here, under the first Green POST tab - http://developer.oanda.com/rest-live-v20/order-ep/

Here is what I am working with. This first block specifies the order details. In this case, a market order in the EUR_USD instrument with a quantity of 100 units and a time in force equalling "fill or kill" :

```<code>body=$(cat << EOF
{
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}
EOF
)
</code>```

```<code>curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer SECRET TOKEN" \
  -d "$body" \
  "https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders"
</code>```

Converted into Python:

```<code>import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer SECRET TOKEN',
}

data = '$body'

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders', headers=headers, data=data)
</code>```

As you can see, I believe there is a formatting error somewhere in the "body=$" portion, but I am not entirely sure. I simply get a 400 error, "invalid values."

答:
If you're sending data in JSON format, you should pass them into json argument instead of data (explanation, method).

```<code>import requests

headers = {
    # 'Content-Type': 'application/json', # will be set automatically
    'Authorization': 'Bearer SECRET TOKEN',
}

body = {
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders',
                         headers=headers, json=body)
</code>```

Body:
I am looking to send a POST request using Python to the OANDA API to open an order. They do not have a Python wrapper and use cURL, so I have had to try and convert from cURL to Python. I have done so using https://curl.trillworks.com/ -- but converting this next one does not work.

You can view the OANDA API documentation here, under the first Green POST tab - http://developer.oanda.com/rest-live-v20/order-ep/

Here is what I am working with. This first block specifies the order details. In this case, a market order in the EUR_USD instrument with a quantity of 100 units and a time in force equalling "fill or kill" :

body=$(cat << EOF
{
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}
EOF
)

curl \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer SECRET TOKEN" \
  -d "$body" \
  "https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders"

Converted into Python:

import requests

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer SECRET TOKEN',
}

data = '$body'

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders', headers=headers, data=data)

As you can see, I believe there is a formatting error somewhere in the "body=$" portion, but I am not entirely sure. I simply get a 400 error, "invalid values."

Body:
If you're sending data in JSON format, you should pass them into json argument instead of data (explanation, method).

import requests

headers = {
    # 'Content-Type': 'application/json', # will be set automatically
    'Authorization': 'Bearer SECRET TOKEN',
}

body = {
  "order": {
    "units": "100",
    "instrument": "EUR_USD",
    "timeInForce": "FOK",
    "type": "MARKET",
    "positionFill": "DEFAULT"
  }
}

response = requests.post('https://api-fxpractice.oanda.com/v3/accounts/{ACCOUNT-NUMBER}/orders',
                         headers=headers, json=body)


问:
How can I setup this HEX Assembly?
I will have a presentation in my class about phising. I found a very interesting presentation on the Internet (https://www.youtube.com/watch?v=iRpKdId5-lE)

On Internet Explorer 8 it should be work (WIN 7).

It should open the calculator.

And there is an x86 Assembly hex code what is need to be in the riff.htm, but he didn't show the riff.htm, so: How should I create the riff.htm?

Thanks for the help!

index.htm:

```<code><script language="javascript">
document.write("<html><body style=\"cursor: url('riff.htm');\">   </body></html>");
wait(500);
window.location.reload();
</script>
</code>```

It's should be on riff.htm:

HEX:

```<code>77d8af0a
90909090
90909090
90909090
90909090
90909090
90909090
90909090
90909090
90909090
2068ec8b
68202020
636c6163
50f8458d
86114db8
90d0ff7c
</code>```

In x86Assembly (It has to be similar):

```<code>MOV EBP,ESP
PUSH 20202020
PUSH 636d6163
LEA EAX,DWORD PTR SS:[EBP-8]
PUSH EAX
MOV EAX,kernel32.WinExec
CALL EAX
</code>```

答:
On Internet Explorer 8 it should be work (WIN 7).

The vulnerability you're describing sounds like CVE-2007-0038. This vulnerability was patched several years before Windows 7 was released -- Windows 7 systems were never affected.

In any case, it's unclear how this would be relevant to a presentation about phishing.

Title: How can I setup this HEX Assembly?

Body:
I will have a presentation in my class about phising. I found a very interesting presentation on the Internet (https://www.youtube.com/watch?v=iRpKdId5-lE)

On Internet Explorer 8 it should be work (WIN 7).

It should open the calculator.

And there is an x86 Assembly hex code what is need to be in the riff.htm, but he didn't show the riff.htm, so: How should I create the riff.htm?

Thanks for the help!

index.htm:

It's should be on riff.htm:

HEX:

77d8af0a
90909090
90909090
90909090
90909090
90909090
90909090
90909090
90909090
90909090
2068ec8b
68202020
636c6163
50f8458d
86114db8
90d0ff7c

In x86Assembly (It has to be similar):

MOV EBP,ESP
PUSH 20202020
PUSH 636d6163
LEA EAX,DWORD PTR SS:[EBP-8]
PUSH EAX
MOV EAX,kernel32.WinExec
CALL EAX


问:
How to inject/insert a txt file into another txt file at a specific line in Python
This is a quick problem I have with Python. This is my problem here : I try to inject a txt file inside an other txt file at a specific line. This is what I tried:

# Modify TXT File
with open("avengers.txt", "w") as file1, open("guardians.txt", 'r') as file2:

    for line in file1:
        print line
        if line == 'Blackwidow':
            for line2 in file2:
                file1.write(line2)
```
<p>But it gives me something weird (A lot of break lines)</p>
<h1>avengers.txt</h1>
```This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow

The story is great
About about the movies :
....
....
```
<h1>guardians.txt</h1>
```Groot
Rocket
Star Lord
Gamora
Drax
```
<p>----- RESULT ----</p>
<p>What I want to do is just :</p>
<h1>avengers.txt</h1>
```This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow
Groot <---------------- Insert text here
Rocket
Star Lord
Gamora
Drax

The story is great
About about the movies :
....
....
```

Thank you very much for your help

答:
Using 'readlines'  method, you can turn the text into a list object. Then, find the index of the string, place the text after it:</p>

```<code>with open("avengers.txt", "r+") as file1, open("guardians.txt", 'r') as file2:
    file_new = file1.readlines()
    file1.seek(0)
    bw_index = file_new.index('Blackwidow\n')
    file_new = file_new[:bw_index+1] + file2.readlines() + file_new[bw_index+1 :]
    file1.write(''.join(file_new))
</code>```

Body:
This is a quick problem I have with Python. This is my problem here : I try to inject a txt file inside an other txt file at a specific line. This is what I tried:

# Modify TXT File
with open("avengers.txt", "w") as file1, open("guardians.txt", 'r') as file2:

    for line in file1:
        print line
        if line == 'Blackwidow':
            for line2 in file2:
                file1.write(line2)

But it gives me something weird (A lot of break lines)

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow

The story is great
About about the movies :
....
....

guardians.txt

Groot
Rocket
Star Lord
Gamora
Drax

----- RESULT ----

What I want to do is just :

avengers.txt

This is the avengers

List of the characters :
Captain America
Iron Man
Hulk
Hawkeye
Blackwidow
Groot <---------------- Insert text here
Rocket
Star Lord
Gamora
Drax

The story is great
About about the movies :
....
....

Thank you very much for your help

Body:
Using 'readlines'  method, you can turn the text into a list object. Then, find the index of the string, place the text after it:

with open("avengers.txt", "r+") as file1, open("guardians.txt", 'r') as file2:
    file_new = file1.readlines()
    file1.seek(0)
    bw_index = file_new.index('Blackwidow\n')
    file_new = file_new[:bw_index+1] + file2.readlines() + file_new[bw_index+1 :]
    file1.write(''.join(file_new))


问:
Is there a way to check if notification bar is pulled down?
I am developing an app to detect all the user actions performed on the screen.  So how can I check if the user pulls down the notification bar?

Will this be possible with accessibility service??

答:
As far as i know, there is no proper way to add a callback or any kinds of detection when the notification bar is pulled down.

That is because Android apps are meant to be designed in such a way that the interaction between the notification bar does not affect the functioning of the applications being used in any way.


问:
Why does int.Parse not work on an Enum value?
can you tell me how this first line converts to int and second doesn't work?

```<code>public enum SomeEnumerator { AndHisValue, second, third }

int a = (int)(SomeEnumerator.AndHisValue);

int a = int.Parse(SomeEnumerator.AndHisValue);
</code>```

Type of AndHisValue is string.

Image

答:
As you show in your image, SomeEnumerator is not of type string, but instead an enum.

string constants are denoted by " around them. enum constants, such as SomeEnumerator.AndHisValue are their own kind of value, each usually having their own distinct value.

You are allowed to directly cast any enum-value to int or string, but as int.Parse() expects a string you cannot use your enumerator value here

(see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum as reference for enums)

Body:
can you tell me how this first line converts to int and second doesn't work?

public enum SomeEnumerator { AndHisValue, second, third }

int a = (int)(SomeEnumerator.AndHisValue);

int a = int.Parse(SomeEnumerator.AndHisValue);

Type of AndHisValue is string.

Image


问:
How to write unix regular expression to select for specific files in a cp for-loop
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

```<code>P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src
</code>```

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

```<code>for .*1.src in ./
> do
> cp ../1.src
> done
</code>```

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

```<code>-bash: `.*1.src': not a valid identifier
</code>```

I then tried the same for loop with the following regular expression:

```<code>^[a-zA-Z0-9_]*1.src$
</code>```

But I got the same error message:

```<code>-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier
</code>```

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

答:
Please correct me if your goal is something other than

"overwrite many existing files sharing a common suffix with the contents of a single file"

```<code>find /path/to/dest_dir -type f -name "*_1.src" |xargs -n1 cp /path/to/source_file
</code>```

Note that without the -maxdepth 1 option, find will recurse through your destination directory.

Body:
I've got a directory with a bunch of files. Instead of describing the filenames and extensions, I'll just show you what is in the directory:

P01_1.atag  P03_3.tgt   P05_6.src   P08_3.atag  P10_5.tgt
P01_1.src   P03_4.atag  P05_6.tgt   P08_3.src   P10_6.atag
P01_1.tgt   P03_4.src   P06_1.atag  P08_3.tgt   P10_6.src
P01_2.atag  P03_4.tgt   P06_1.src   P08_4.atag  P10_6.tgt
P01_2.src   P03_5.atag  P06_1.tgt   P08_4.src   P11_1.atag
P01_2.tgt   P03_5.src   P06_2.atag  P08_4.tgt   P11_1.src
P01_3.atag  P03_5.tgt   P06_2.src   P08_5.atag  P11_1.tgt
P01_3.src   P03_6.atag  P06_2.tgt   P08_5.src   P11_2.atag
P01_3.tgt   P03_6.src   P06_3.atag  P08_5.tgt   P11_2.src
P01_4.atag  P03_6.tgt   P06_3.src   P08_6.atag  P11_2.tgt
P01_4.src   P04_1.atag  P06_3.tgt   P08_6.src   P11_3.atag
P01_4.tgt   P04_1.src   P06_4.atag  P08_6.tgt   P11_3.src
P01_5.atag  P04_1.tgt   P06_4.src   P09_1.atag  P11_3.tgt
P01_5.src   P04_2.atag  P06_4.tgt   P09_1.src   P11_4.atag
P01_5.tgt   P04_2.src   P06_5.atag  P09_1.tgt   P11_4.src
P01_6.atag  P04_2.tgt   P06_5.src   P09_2.atag  P11_4.tgt
P01_6.src   P04_3.atag  P06_5.tgt   P09_2.src   P11_5.atag
P01_6.tgt   P04_3.src   P06_6.atag  P09_2.tgt   P11_5.src
P02_1.atag  P04_3.tgt   P06_6.src   P09_3.atag  P11_5.tgt
P02_1.src   P04_4.atag  P06_6.tgt   P09_3.src   P11_6.atag
P02_1.tgt   P04_4.src   P07_1.atag  P09_3.tgt   P11_6.src
P02_2.atag  P04_4.tgt   P07_1.src   P09_4.atag  P11_6.tgt
P02_2.src   P04_5.atag  P07_1.tgt   P09_4.src   P12_1.atag
P02_2.tgt   P04_5.src   P07_2.atag  P09_4.tgt   P12_1.src
P02_3.atag  P04_5.tgt   P07_2.src   P09_5.atag  P12_1.tgt
P02_3.src   P04_6.atag  P07_2.tgt   P09_5.src   P12_2.atag
P02_3.tgt   P04_6.src   P07_3.atag  P09_5.tgt   P12_2.src
P02_4.atag  P04_6.tgt   P07_3.src   P09_6.atag  P12_2.tgt
P02_4.src   P05_1.atag  P07_3.tgt   P09_6.src   P12_3.atag
P02_4.tgt   P05_1.src   P07_4.atag  P09_6.tgt   P12_3.src
P02_5.atag  P05_1.tgt   P07_4.src   P10_1.atag  P12_3.tgt
P02_5.src   P05_2.atag  P07_4.tgt   P10_1.src   P12_4.atag
P02_5.tgt   P05_2.src   P07_5.atag  P10_1.tgt   P12_4.src
P02_6.atag  P05_2.tgt   P07_5.src   P10_2.atag  P12_4.tgt
P02_6.src   P05_3.atag  P07_5.tgt   P10_2.src   P12_5.atag
P02_6.tgt   P05_3.src   P07_6.atag  P10_2.tgt   P12_5.src
P03_1.atag  P05_3.tgt   P07_6.src   P10_3.atag  P12_5.tgt
P03_1.src   P05_4.atag  P07_6.tgt   P10_3.src   P12_6.atag
P03_1.tgt   P05_4.src   P08_1.atag  P10_3.tgt   P12_6.src
P03_2.atag  P05_4.tgt   P08_1.src   P10_4.atag  P12_6.tgt
P03_2.src   P05_5.atag  P08_1.tgt   P10_4.src
P03_2.tgt   P05_5.src   P08_2.atag  P10_4.tgt
P03_3.atag  P05_5.tgt   P08_2.src   P10_5.atag
P03_3.src   P05_6.atag  P08_2.tgt   P10_5.src

I have a file that is just outside of this directory that I need to copy to all of the files that end with "_1.src" inside the directory.

I'm working with unix in the Terminal app, so I tried writing this for loop, but it rejected my regular expression:

for .*1.src in ./
> do
> cp ../1.src
> done

I've only written regular expressions in Python before and have minimal experience, but I was under the impression that .* would match any combination of characters. However, I got the following error message:

-bash: `.*1.src': not a valid identifier

I then tried the same for loop with the following regular expression:

^[a-zA-Z0-9_]*1.src$

But I got the same error message:

-bash: `^[a-zA-Z0-9_]*1.src$': not a valid identifier

I tried the same regular expression with and without quotation marks, but it always gives the same 'not a valid identifier' error message.

Body:
Please correct me if your goal is something other than

"overwrite many existing files sharing a common suffix with the contents of a single file"

find /path/to/dest_dir -type f -name "*_1.src" |xargs -n1 cp /path/to/source_file

Note that without the -maxdepth 1 option, find will recurse through your destination directory.


问:
How to make Date object toString via stringify use the regular toString instead of toStringISO in javascript?
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

```<code>var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");
</code>```

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

答:
You can customize JSON.stringify with a function:

```<code>JSON.stringify(objectToStringify, function (key, value) {
  if (value instanceof Date) {
    return (new Date(value)).toString(); // Or whatever you want to serialize it to
  }
  return value;
});
</code>```

Body:
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

Body:
You can customize JSON.stringify with a function:

JSON.stringify(objectToStringify, function (key, value) {
  if (value instanceof Date) {
    return (new Date(value)).toString(); // Or whatever you want to serialize it to
  }
  return value;
});


问:
How do I solve this error when unit testing child component with reactive form as input using Jest and Spectator?
I'm trying to write a basic unit test for an Angular component which is used as a child component and receives a reactive form through an Input() from it's parent. I'm trying to write a unit test using a host component to wrap the component to be tested. I'm using https://netbasal.gitbook.io/spectator/ with Jest to write my tests. I can't get the simplest test working for this component and my guess is the problem has something to do with dependencies. I've been searching google extensively but I can't seem to find anybody else running into this error.

I've tried writing the test without the host component but that also doesn't seem to be working.

describe('ProjectFormComponent', () => {
  let host: SpectatorWithHost<ProjectFormComponent>;

const createHost = createHostComponentFactory<ProjectFormComponent>({
    component: ProjectFormComponent,
    imports: [
      CommonModule,
      ReactiveFormsModule,
      FontAwesomeModule,
      HttpClientTestingModule,
      RouterTestingModule,
      NgxErrorsModule,
      NgSelectModule,
      ToastrModule.forRoot(),
      MaterialImportsModule,
      FormsModule,
      SharedModule
    ],
    providers: [
      { provide: NgxErrorDirective, useValue: {} },
      { provide: APP_BASE_HREF, useValue: '/' },
      { provide: Store, useValue: {} },
      { provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
      { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
      { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
    ]
  });

test('ProjectFormComponent is created', inject([FormBuilder], (fb: FormBuilder) => {
    const mockForm = fb.group({
      name: ['', [Validators.required, Validators.maxLength(255)]]
    });

    host = createHost(`<app-project-form></app-project-form>`, false, { parent_form: mockForm });

    expect(host.component).toBeTruthy();

  }));
});
```

It's a simple test which should result positive. But when I run ng test
I get the error: Cannot override module metadata when the test module has already been instantiated. Make sure you are not using inject before overrideModule.

答:
As a way of not repeating the same answers,

https://github.com/NetanelBasal/spectator/issues/57

https://github.com/NetanelBasal/spectator/issues/39

https://github.com/NetanelBasal/spectator

I think you can be benefited by similar issues, see below,

1)Angular2 RC5 how to properly configure test module

2)angular Testbed overrideModule not working

Also a good read
https://codecraft.tv/courses/angular/unit-testing/dependency-injection/

Hope this helps

Body:
I'm trying to write a basic unit test for an Angular component which is used as a child component and receives a reactive form through an Input() from it's parent. I'm trying to write a unit test using a host component to wrap the component to be tested. I'm using https://netbasal.gitbook.io/spectator/ with Jest to write my tests. I can't get the simplest test working for this component and my guess is the problem has something to do with dependencies. I've been searching google extensively but I can't seem to find anybody else running into this error.

I've tried writing the test without the host component but that also doesn't seem to be working.

describe('ProjectFormComponent', () => {
  let host: SpectatorWithHost<ProjectFormComponent>;

const createHost = createHostComponentFactory<ProjectFormComponent>({
    component: ProjectFormComponent,
    imports: [
      CommonModule,
      ReactiveFormsModule,
      FontAwesomeModule,
      HttpClientTestingModule,
      RouterTestingModule,
      NgxErrorsModule,
      NgSelectModule,
      ToastrModule.forRoot(),
      MaterialImportsModule,
      FormsModule,
      SharedModule
    ],
    providers: [
      { provide: NgxErrorDirective, useValue: {} },
      { provide: APP_BASE_HREF, useValue: '/' },
      { provide: Store, useValue: {} },
      { provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
      { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
      { provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS }
    ]
  });

test('ProjectFormComponent is created', inject([FormBuilder], (fb: FormBuilder) => {
    const mockForm = fb.group({
      name: ['', [Validators.required, Validators.maxLength(255)]]
    });

    host = createHost(`<app-project-form></app-project-form>`, false, { parent_form: mockForm });

    expect(host.component).toBeTruthy();

  }));
});

It's a simple test which should result positive. But when I run ng test
I get the error: Cannot override module metadata when the test module has already been instantiated. Make sure you are not using inject before overrideModule.


问:
Include HTTPResponse object with template? Trying to display pyplot to webpage
I am trying to display a pyplot chart to a webpage along with a template including other variables. Right now the pyplot image is being saved with PIL to the response object, however, I want more than just the image to be in the response. Is there a way to append the HTTPResponse object as a variable on a template?

I've tried using Jquery to request the plot after loading the rest of the template but the plot takes a while to render and ends up being displayed a long time after the rest of the template. I want the image to be loaded with the rest of the template

```<code>buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
response = HttpResponse(content_type="image/png")
im.save(response, "PNG")
buf.close()
plt.close(fig)
return response
</code>```

答: Found a solution that works for my needs.. I set the image source in the template to the view in my original question then used this solution (How to create a JavaScript callback for knowing when an image is loaded?) to detect when the image was done loading and prevent the template from displaying until the image request finished</p>

Body:
I am trying to display a pyplot chart to a webpage along with a template including other variables. Right now the pyplot image is being saved with PIL to the response object, however, I want more than just the image to be in the response. Is there a way to append the HTTPResponse object as a variable on a template?

I've tried using Jquery to request the plot after loading the rest of the template but the plot takes a while to render and ends up being displayed a long time after the rest of the template. I want the image to be loaded with the rest of the template

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)
response = HttpResponse(content_type="image/png")
im.save(response, "PNG")
buf.close()
plt.close(fig)
return response


问:
How to compare the "_id" in mongodb via mongocxx?
I'm going to build a server, and i have a list containing a struct("_id" is in it), now i want to compare the _id between the exist one in mongodb and the one in instruct.

I've finished the code, and when it comes to compiling,  there are two same errors occured:

/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/stream/value_context.hpp:70:9: error: no matching function for call to ‘bsoncxx::v_noabi::builder::core::append(bsoncxx::v_noabi::document::element)’
         _core->append(std::forward<T>(t));
         ^
```

<p>where the original code are:</p>

<pre class="lang-cpp prettyprint-override"><code> #include <iostream>
  2 #include <cstdint>
  3 #include <mongocxx/instance.hpp>
  4 #include <mongocxx/client.hpp>
  5 #include <mongocxx/options/find.hpp>
  6 #include <mongocxx/stdx.hpp>
  7
  8 #include <bsoncxx/builder/basic/array.hpp>
  9 #include <bsoncxx/builder/stream/document.hpp>
 10 #include <bsoncxx/json.hpp>
 11 #include <bsoncxx/types.hpp>
 12
 13
 14 #include "DataStruct.h"
 15 using bsoncxx::types::value;
 16 using bsoncxx::builder::stream::finalize;
 17 using bsoncxx::builder::stream::document;
 18 using bsoncxx::builder::stream::open_document;
 19 using bsoncxx::builder::stream::close_document;
 20
 21 int main(int, char**)
 22 {
 23         mongocxx::instance inst{};
 24         mongocxx::client conn{mongocxx::uri{"mongodb://172.16.103.100:27017"}};
 25
 26
 27         std::string m_Which_Attendance;
 28
 29          LIST_Attendance lstInfo;
 30          LIST_Attendance::iterator iter;
 31
 32
 33          for(iter = lstInfo.begin(); iter != lstInfo.end(); ++iter)
 34              {
 35                   char datepick [10];
 36                   strcpy(datepick,(*iter).date.c_str());
 37                   int m_Mouth = (datepick[5]-48)*10+datepick[6]-48; //char to int -48
 38                   int m_Date = (datepick[8]-48)*10+datepick[9]-48;
 39
 40                         if( m_Date <16 )  //find attendance_date <16 to  _1
 41                         {
 42                                 m_Which_Attendance  = "kg_attendance_"+std::to_string(m_Mouth)+"_1";
 43                         }
 44                         else
 45                         {
 46                                 m_Which_Attendance  = "kg_attendance_"+std::to_string(m_Mouth)+"_2";
 47
 48                         }
 49
 50
 51
 52
  53                   auto db = conn["myattendance"];
 54                   auto cursor = db[m_Which_Attendance].find({});
 55                   {
 56                         for(auto&& doc : cursor)
 57                         {
 58                             if( (*iter)._id == doc["_id"].get_oid().value.to_string() )   //delete same id which was exist
 59                             {
 60
 61                                  auto filter_builder = bsoncxx::builder::stream::document{};
 62                                  bsoncxx::document::value filter_value = filter_builder
 63                                  <<"_id" <<  doc["_id"] << bsoncxx::builder::stream::finalize;
 64                                  db[m_Which_Attendance].delete_one(filter_value.view());
 65
 66
 67                            }
 68
 69                       /*
 70                             auto builder = bsoncxx::builder::stream::document {};
 71                             bsoncxx::document::value doc_value = builder
 72                             << "_id" << (*iter)._id
 73                             << "name" << (*iter).name
 74                             << "owner" <<  (*iter).owner_id
 75                             << "owner_type" << (*iter).owner_type
 76                             << "status" <<  (*iter).status
 77                             << "date" <<  (*iter).date
 78                             << "relationship" << (*iter).relationship
 79                             << "guardian_id" << (*iter).guardian_id
 80                             << "school_id" <<  (*iter).school_id
 81                             << "dep_id" <<  (*iter).dep_id
 82                             << "dep_code" <<  (*iter).dep_code
 83                             << "grade_code" <<  (*iter).grade_code
 84                             << "signin_time" <<  (*iter).signin_time
 85                             << "signout_time" <<  (*iter).signout_time
 86                             << "signin_score" <<  (*iter).signin_score
 87                             << "signout_score" <<  (*iter).signout_score
 88                             << "signin_image_name" <<  (*iter).signin_image_name
 89                             << "signout_image_name" <<  (*iter).signout_image_name
 90                             << bsoncxx::builder::stream::finalize;
 91
 92                            bsoncxx::stdx::optional<mongocxx::result::insert_one> result =
 93                              db[m_Which_Attendance].insert_one( std::move(doc_value) );
 94                         */
 95                         }
 96                   }
 97
 98
 99              }
100
101 }
</code>```

can someone help pls~

答:
The compilation error is caused by doc["_id"] when you're building the document:

```<code> 62              bsoncxx::document::value filter_value = filter_builder
 63              <<"_id" <<  doc["_id"] << bsoncxx::builder::stream::finalize;
</code>```

doc["_id"] is a bsoncxx::v_noabi::document::element but you need to build it using a bsoncxx::oid since the _id is a MongoDB ObjectId type.

With your current code, you can try with the following:

```<code>            auto filter_builder = bsoncxx::builder::stream::document{};
            bsoncxx::document::value filter_value = filter_builder
                << "_id"
                << bsoncxx::oid{ doc["_id"].get_oid().value.to_string() } // <- This is the change
                << bsoncxx::builder::stream::finalize;
            db[m_Which_Attendance].delete_one(filter_value.view());
</code>```

But looking at what you want to do, it seems that the find_one_and_delete might work for you better.

Instead of retrieving all documents (line 54) and looping on all docs trying to find the one with the matching _id, just perform the find_one_and_delete operation using the _id as shown above. Here's an example from mongocxx repository.

Body:
I'm going to build a server, and i have a list containing a struct("_id" is in it), now i want to compare the _id between the exist one in mongodb and the one in instruct.

I've finished the code, and when it comes to compiling,  there are two same errors occured:

/usr/local/include/bsoncxx/v_noabi/bsoncxx/builder/stream/value_context.hpp:70:9: error: no matching function for call to ‘bsoncxx::v_noabi::builder::core::append(bsoncxx::v_noabi::document::element)’
         _core->append(std::forward<T>(t));
         ^

where the original code are:

 #include <iostream>
  2 #include <cstdint>
  3 #include <mongocxx/instance.hpp>
  4 #include <mongocxx/client.hpp>
  5 #include <mongocxx/options/find.hpp>
  6 #include <mongocxx/stdx.hpp>
  7
  8 #include <bsoncxx/builder/basic/array.hpp>
  9 #include <bsoncxx/builder/stream/document.hpp>
 10 #include <bsoncxx/json.hpp>
 11 #include <bsoncxx/types.hpp>
 12
 13
 14 #include "DataStruct.h"
 15 using bsoncxx::types::value;
 16 using bsoncxx::builder::stream::finalize;
 17 using bsoncxx::builder::stream::document;
 18 using bsoncxx::builder::stream::open_document;
 19 using bsoncxx::builder::stream::close_document;
 20
 21 int main(int, char**)
 22 {
 23         mongocxx::instance inst{};
 24         mongocxx::client conn{mongocxx::uri{"mongodb://172.16.103.100:27017"}};
 25
 26
 27         std::string m_Which_Attendance;
 28
 29          LIST_Attendance lstInfo;
 30          LIST_Attendance::iterator iter;
 31
 32
 33          for(iter = lstInfo.begin(); iter != lstInfo.end(); ++iter)
 34              {
 35                   char datepick [10];
 36                   strcpy(datepick,(*iter).date.c_str());
 37                   int m_Mouth = (datepick[5]-48)*10+datepick[6]-48; //char to int -48
 38                   int m_Date = (datepick[8]-48)*10+datepick[9]-48;
 39
 40                         if( m_Date <16 )  //find attendance_date <16 to  _1
 41                         {
 42                                 m_Which_Attendance  = "kg_attendance_"+std::to_string(m_Mouth)+"_1";
 43                         }
 44                         else
 45                         {
 46                                 m_Which_Attendance  = "kg_attendance_"+std::to_string(m_Mouth)+"_2";
 47
 48                         }
 49
 50
 51
 52
  53                   auto db = conn["myattendance"];
 54                   auto cursor = db[m_Which_Attendance].find({});
 55                   {
 56                         for(auto&& doc : cursor)
 57                         {
 58                             if( (*iter)._id == doc["_id"].get_oid().value.to_string() )   //delete same id which was exist
 59                             {
 60
 61                                  auto filter_builder = bsoncxx::builder::stream::document{};
 62                                  bsoncxx::document::value filter_value = filter_builder
 63                                  <<"_id" <<  doc["_id"] << bsoncxx::builder::stream::finalize;
 64                                  db[m_Which_Attendance].delete_one(filter_value.view());
 65
 66
 67                            }
 68
 69                       /*
 70                             auto builder = bsoncxx::builder::stream::document {};
 71                             bsoncxx::document::value doc_value = builder
 72                             << "_id" << (*iter)._id
 73                             << "name" << (*iter).name
 74                             << "owner" <<  (*iter).owner_id
 75                             << "owner_type" << (*iter).owner_type
 76                             << "status" <<  (*iter).status
 77                             << "date" <<  (*iter).date
 78                             << "relationship" << (*iter).relationship
 79                             << "guardian_id" << (*iter).guardian_id
 80                             << "school_id" <<  (*iter).school_id
 81                             << "dep_id" <<  (*iter).dep_id
 82                             << "dep_code" <<  (*iter).dep_code
 83                             << "grade_code" <<  (*iter).grade_code
 84                             << "signin_time" <<  (*iter).signin_time
 85                             << "signout_time" <<  (*iter).signout_time
 86                             << "signin_score" <<  (*iter).signin_score
 87                             << "signout_score" <<  (*iter).signout_score
 88                             << "signin_image_name" <<  (*iter).signin_image_name
 89                             << "signout_image_name" <<  (*iter).signout_image_name
 90                             << bsoncxx::builder::stream::finalize;
 91
 92                            bsoncxx::stdx::optional<mongocxx::result::insert_one> result =
 93                              db[m_Which_Attendance].insert_one( std::move(doc_value) );
 94                         */
 95                         }
 96                   }
 97
 98
 99              }
100
101 }

can someone help pls~

Body:
The compilation error is caused by doc["_id"] when you're building the document:

 62              bsoncxx::document::value filter_value = filter_builder
 63              <<"_id" <<  doc["_id"] << bsoncxx::builder::stream::finalize;

doc["_id"] is a bsoncxx::v_noabi::document::element but you need to build it using a bsoncxx::oid since the _id is a MongoDB ObjectId type.

With your current code, you can try with the following:

            auto filter_builder = bsoncxx::builder::stream::document{};
            bsoncxx::document::value filter_value = filter_builder
                << "_id"
                << bsoncxx::oid{ doc["_id"].get_oid().value.to_string() } // <- This is the change
                << bsoncxx::builder::stream::finalize;
            db[m_Which_Attendance].delete_one(filter_value.view());

But looking at what you want to do, it seems that the find_one_and_delete might work for you better.

Instead of retrieving all documents (line 54) and looping on all docs trying to find the one with the matching _id, just perform the find_one_and_delete operation using the _id as shown above. Here's an example from mongocxx repository.


问:
images not displaying through jquery
ok here is the full code

chenging the background image css property through jquery and the images are not displaying .... checked the paths and they are ok

divs exist, css is ok , paths are ok, images exist BUT it works on the on.show function and it does not work on the click function

```<code>    // when new category show default images
    $('#newCategory').on('show.bs.modal', function () {

        var category = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/profiles/default.png';
        var banner = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/banners/default.png';

        $( '#categoryPreview' ).css( { backgroundImage: 'url(' + category + ')' } );
        $( '#bannerPreview' ).css( { backgroundImage: 'url(' + banner + ')' } );
    });

    // load category info before display dialog
    $('body').on('click', '.btn-upd-id',function(){

        var id = $(this).attr('upd-id');

        $("#update-category-id").val(id);

        if( id != "" ){
            $.post('category/category_info.php', {id: id}, function(data){
                var obj = JSON.parse(data);

                $("#upd-name").val(obj[0].name);

                var category = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/profiles/' + obj[0].category_image;

                var banner = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/banners/' + obj[0].banner_image;

                $( '#updCategoryPreview' ).css( { backgroundImage: 'url(' + category + ')' } );
                $( '#updBannerPreview' ).css( { backgroundImage: 'url(' + banner + ')' } );
            })
        }
    });
</code>```

HTML

```<code>                                <!-- category image -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="category">Category Image</label>
                                            <br/>
                                            <div id="updCategoryPreview"></div>
                                            <input type="file" class="img" id="upd-category" name="upd-category">
                                        </div>
                                    </div>
                                </div>
                                <!-- banner image -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="banner">Category Banner</label>
                                            <br>
                                            <div id="updBannerPreview"></div>
                                            <input type="file" class="img" id="upd-banner" name="upd-banner">
                                        </div>
                                    </div>
                                </div>
</code>```

I expect it to load the image but it displays nothing.

答:
fed up
used this piece of code and its working

```<code>image = new Image();
image.src = url;
image.onload = function () {
    $('#image-holder').empty().append(image);
};
</code>```

found here
Can I get the image and load via ajax into div

thank you all for your help

Title: images not displaying through jquery

Body:
ok here is the full code

chenging the background image css property through jquery and the images are not displaying .... checked the paths and they are ok

divs exist, css is ok , paths are ok, images exist BUT it works on the on.show function and it does not work on the click function

    // when new category show default images
    $('#newCategory').on('show.bs.modal', function () {

        var category = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/profiles/default.png';
        var banner = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/banners/default.png';

        $( '#categoryPreview' ).css( { backgroundImage: 'url(' + category + ')' } );
        $( '#bannerPreview' ).css( { backgroundImage: 'url(' + banner + ')' } );
    });

    // load category info before display dialog
    $('body').on('click', '.btn-upd-id',function(){

        var id = $(this).attr('upd-id');

        $("#update-category-id").val(id);

        if( id != "" ){
            $.post('category/category_info.php', {id: id}, function(data){
                var obj = JSON.parse(data);

                $("#upd-name").val(obj[0].name);

                var category = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/profiles/' + obj[0].category_image;

                var banner = "<?php echo $_SESSION['home-url']; ?>" + 'admin/images/categories/banners/' + obj[0].banner_image;

                $( '#updCategoryPreview' ).css( { backgroundImage: 'url(' + category + ')' } );
                $( '#updBannerPreview' ).css( { backgroundImage: 'url(' + banner + ')' } );
            })
        }
    });

HTML

                                            Category Image

                                            <input type="file" class="img" id="upd-category" name="upd-category">

                                            Category Banner

                                            <input type="file" class="img" id="upd-banner" name="upd-banner">

I expect it to load the image but it displays nothing.

Body:
fed up
used this piece of code and its working

image = new Image();
image.src = url;
image.onload = function () {
    $('#image-holder').empty().append(image);
};

found here
Can I get the image and load via ajax into div

thank you all for your help


问:
I have repeated date values in my x axis. How do i create a different row with a single average of those values?
I have been working with a dataset which contains information about houses that have been sold on a particular market. There are two columns, 'price', and 'date'.

I would like to make a line plot to show how the prices of this market have chaged over time.

The problem is, I see that some houses have been sold at the same date but with a diferent price.

So ideally i would need to get the mean/average price of the house sold on each date before plotting.

So for example, if I had something like this:

DATE  /                PRICE

02/05/2015      /     $100

02/05/2015      /     $200

I would need to get a new row with the following average:

DATE          /      PRICE

02/05/2015      /      $150

I just havent been able to figure it out yet. I would appreciate anyone who could guide me in this matter. Thanks in advance.

答:
Assuming you're using pandas:

pd.groupby('DATE')['PRICE'].mean()


问:
Bulma Navbar Color Modifiers are Not Working
Adding color modifier classes to Bulma's navbar is supposed to change the background color (as mentioned here:  http://bulma.io/documentation/components/navbar/#colors).

I find that this is working fine if I use the css version.  But I"m using the sass version and it is not working.

Any idea why not?

Note -- this is also an unanswered issue on Github:  https://github.com/jgthms/bulma/issues/1192

答:
You have to create file like my-bulma-theme.scss, then override needed variables or import other .scss files with variables and finally, import bulma from node_modules and include that my-bulma-theme.scss in your pages/preprocessor.

For example my-bulma-theme.scss:

```<code>$navbar-background-color: #f0f0f0;
$another-bulma-variable: 14px;

@import './another-style-variables.scss';

@import '../node_modules/bulma/bulma.sass'; // must be the last thing in file
</code>```

Body:
You have to create file like my-bulma-theme.scss, then override needed variables or import other .scss files with variables and finally, import bulma from node_modules and include that my-bulma-theme.scss in your pages/preprocessor.

For example my-bulma-theme.scss:

$navbar-background-color: #f0f0f0;
$another-bulma-variable: 14px;

@import './another-style-variables.scss';

@import '../node_modules/bulma/bulma.sass'; // must be the last thing in file


问:
Avoid double execution of computation that depends on updated slider value
Background: In a Shiny app, I have (i) a data-entry text area and (ii) a slider. The slider's value and end points are updated by the data because the slider range should be appropriate for the scale of the data. A subsequent time-consuming computation uses both the data from the text area and the value from the slider.

The problem: When the data are changed, the time-consuming computation executes twice, first using the previous value of the slider (not the updated value of the slider), and then a second time using the updated value of the slider. My intention is for it to execute only once, using the updated value of the slider not the previous value of slider.

A minimal example: The R code below demonstrates the problem with as small a set-up as seemed relevant. Just copy and paste into RStudio and click Run App. You'll see the output at the bottom of the screen: After a few seconds it displays 4025, and then after a few more seconds it displays 50. Click re-load to watch it again. The initial output (i.e., 4025) is irrelevant. Only the final output (i.e., 50) is intended.

Other nuances: The slider is on a debounce delay so that its motion doesn't instantly trigger the time-consuming computation. The user should be able to move the slider a bit tentatively without the computation getting triggered immediately. This is important for the app, but tangential to the double-execution problem. And the data textAreaInput uses an actionButton so that typing text doesn't instantly trigger the computation. Again, important for the app but tangential to the double-execution problem.

Thank you in advance for suggestions!

library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label="Type data, then click Submit:" ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      actionButton( inputId="dataSubmit" ,
                    label="Submit Data" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
                   min=3000 , max=5000 , value=4000 ,
                   round=FALSE , step=1 , ticks=FALSE )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  # Parse data values out of data text:
  theData = reactive({
    input$dataSubmit # establish dependency on dataSubmit button
    yText = isolate(input$dataText) # remove dependency on dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    if ( any(is.na(y)) | length(y) < 2 ) {
      y=c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput( session ,
                           inputId="dataText" ,
                           value=paste(as.character(y),collapse=" ") )
    }
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min( theData() )
    val = median( theData() )
    high = max( theData() )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    return( input$slider1 )
  }) %>% debounce(debounceDelay)

  # Compute output:
  output$theOutput <- renderText({
    Sys.sleep(3) # simulate lengthy computation time
    return( paste( "Time-consuming computation...
        Mean of data plus slider value: " ,
        mean(theData()) + sliderValue() ) )
  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)
```

<p><strong>AMENDMENT in response to initial version of reply from @ismirsehregal:</strong></p>

<p>Using the suggestion to protect the long computation by <code>eventReactive( input$runComp , { ...long computation... } )</code>, I have revised my initial script. There is no longer a need to <code>debounce</code> the slider value because the long computation is not triggered by the slider. There is also no need to have <code>req(theData(), sliderValue())</code>, as far as I can tell. I also added an <code>if(){}else{}</code> in the computation section to check for invalid text data entry. This revised script constitutes one solution to the problem.</p>

<pre class="lang-r prettyprint-override"><code>library(shiny)

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label=HTML( "<b>Type data here.</b> <small>(Must be at least two numeric values separated by whitespace.)</small>" ) ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("<b>Select constant to add to mean of data.</b> <small>(Slider settings will change if data change.)</small>") ,
                   min=NA , max=NA , value=NA ,
                   round=FALSE , step=1 , ticks=FALSE ),
      HTML("<p>Click the button to start the time-consuming computation:") ,
      actionButton( inputId="runComp" ,
                    label="Start Computation" )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  theDataDefault = c(-1, 1)

  # Parse data values out of data text:
  theData = reactive({
    yText = input$dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    if ( any(is.na(theData())) | length(theData()) < 2 ) {
      y = theDataDefault
    } else {
      y = theData()
    }
    low = min( y )
    val = mean( range( y ) )
    high = max( y )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Compute output:
  textOut <- eventReactive( input$runComp, {
    if ( any(is.na(theData())) | length(theData()) < 2 ) {
      return( "ERROR: Data must be at least two numeric values (no letters) separated by whitespace (no commas, etc.)." )
    } else {
      Sys.sleep(3) # simulate lengthy computation time
      return( paste( "Time-consuming computation...
                   Mean of data plus slider value: " ,
                     mean( theData()) + input$slider1 ) )
    }
  })

  output$theOutput <- renderText({
    textOut()
  })

} # end server

shinyApp(ui = ui, server = server)
</code>```

答:
Please check if this meets your expectations:

The initial value for your slider now is NA, so that you can block the inital display via req(). Furthermore I isolated theData() in renderText to avoid it beeing triggered twice (only listening for changes of the slider).

```<code>library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label="Adapt slider data:" ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
                   min=NA , max=NA , value=NA ,
                   round=FALSE , step=1 , ticks=FALSE ),
      actionButton( inputId="runComp" ,
                    label="Start Computation" )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  # Parse data values out of data text:
  theData = reactive({
    yText = input$dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    if ( any(is.na(y)) | length(y) < 2 ) {
      y=c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput( session ,
                           inputId="dataText" ,
                           value=paste(as.character(y),collapse=" ") )
    }
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min( theData() )
    val = median( theData() )
    high = max( theData() )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    return( input$slider1 )
  }) %>% debounce(debounceDelay)

  # Compute output:
  textOut <- eventReactive(input$runComp, {
    req(theData(), sliderValue())
    Sys.sleep(3) # simulate lengthy computation time
    print(paste(Sys.time(), "Time-consuming computation..."))
    return( paste( "Time-consuming computation...
        Mean of data plus slider value: " ,
                   mean(theData()) + sliderValue() ) )
  })

  output$theOutput <- renderText({
    textOut()
  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)
</code>```

Edit: Here is a (time based) solution adressing the expected behaviour as described by @JohnK.Kruschke. I personally prefer the above solution (This might fail if the host PC is slowed down by external circumstances, nevertheless it worked during my tests).

```<code>library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput(
        inputId = "dataText" ,
        label = "Type data, then click Submit:" ,
        value = "10 20 30 40" ,
        width = "200px" ,
        height = "100px"
      ) ,
      p(actionButton(inputId = "dataSubmit" ,
                   label = "Submit Data")) ,
      # Slider input, to be updated by data:
      sliderInput(
        inputId = "slider1" ,
        label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
        min=3000 , max=5000 , value=4000 ,
        round = FALSE ,
        step = 1 ,
        ticks = FALSE
      )
    ) ,
    # end sidebarPanel
    mainPanel(textOutput("theOutput"))
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {
  sliderUpdates <- reactiveValues(latestProgrammatic = Sys.time(), timeDiff = 0)

  # Parse data values out of data text:
  theData = reactive({
    input$dataSubmit# establish dependency on dataSubmit button
    yText = isolate(input$dataText) # remove dependency on dataText
    y = as.numeric(unlist(strsplit(yText, "\\s+")[[1]]))
    if (any(is.na(y)) | length(y) < 2) {
      y = c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput(session ,
                          inputId = "dataText" ,
                          value = paste(as.character(y), collapse = " "))
    }
    return(y)
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min(theData())
    val = median(theData())
    high = max(theData())
    return(list(
      low = low ,
      val = val ,
      high = high
    ))
  })
  # Update slider based on data values:
  observeEvent(upUI(), {
    sliderUpdates$latestProgrammatic <- Sys.time()
    print(paste("Programmatic slider update was triggered:" , sliderUpdates$latestProgrammatic))
    updateSliderInput(
      session ,
      inputId = "slider1" ,
      min = upUI()$low ,
      max = upUI()$high ,
      value = upUI()$val
    )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    latestUnkown <- Sys.time()
    print(paste("Slider was updated:" , latestUnkown))
    sliderUpdates$timeDiff <- latestUnkown - sliderUpdates$latestProgrammatic

    req(input$slider1)
    return(input$slider1)
  }) %>% debounce(debounceDelay)

  # Compute output:
  output$theOutput <- renderText({
    req(theData(), sliderValue(), req(isolate(sliderUpdates$timeDiff)))

    print(paste("Elapsed time since the last programmatic slider update:", isolate(sliderUpdates$timeDiff)))
    if(isolate(sliderUpdates$timeDiff) > 0.2){
      Sys.sleep(3) # simulate lengthy computation time
      return(
        paste(
          "Time-consuming computation...
        Mean of data plus slider value: " ,
          mean(theData()) + sliderValue()
        )
      )
    } else {
      NULL
    }

  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)
</code>```

Body:
Background: In a Shiny app, I have (i) a data-entry text area and (ii) a slider. The slider's value and end points are updated by the data because the slider range should be appropriate for the scale of the data. A subsequent time-consuming computation uses both the data from the text area and the value from the slider.

The problem: When the data are changed, the time-consuming computation executes twice, first using the previous value of the slider (not the updated value of the slider), and then a second time using the updated value of the slider. My intention is for it to execute only once, using the updated value of the slider not the previous value of slider.

A minimal example: The R code below demonstrates the problem with as small a set-up as seemed relevant. Just copy and paste into RStudio and click Run App. You'll see the output at the bottom of the screen: After a few seconds it displays 4025, and then after a few more seconds it displays 50. Click re-load to watch it again. The initial output (i.e., 4025) is irrelevant. Only the final output (i.e., 50) is intended.

Other nuances: The slider is on a debounce delay so that its motion doesn't instantly trigger the time-consuming computation. The user should be able to move the slider a bit tentatively without the computation getting triggered immediately. This is important for the app, but tangential to the double-execution problem. And the data textAreaInput uses an actionButton so that typing text doesn't instantly trigger the computation. Again, important for the app but tangential to the double-execution problem.

Thank you in advance for suggestions!

library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label="Type data, then click Submit:" ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      actionButton( inputId="dataSubmit" ,
                    label="Submit Data" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
                   min=3000 , max=5000 , value=4000 ,
                   round=FALSE , step=1 , ticks=FALSE )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  # Parse data values out of data text:
  theData = reactive({
    input$dataSubmit # establish dependency on dataSubmit button
    yText = isolate(input$dataText) # remove dependency on dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    if ( any(is.na(y)) | length(y) < 2 ) {
      y=c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput( session ,
                           inputId="dataText" ,
                           value=paste(as.character(y),collapse=" ") )
    }
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min( theData() )
    val = median( theData() )
    high = max( theData() )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    return( input$slider1 )
  }) %>% debounce(debounceDelay)

  # Compute output:
  output$theOutput <- renderText({
    Sys.sleep(3) # simulate lengthy computation time
    return( paste( "Time-consuming computation...
        Mean of data plus slider value: " ,
        mean(theData()) + sliderValue() ) )
  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)

AMENDMENT in response to initial version of reply from @ismirsehregal:

Using the suggestion to protect the long computation by eventReactive( input$runComp , { ...long computation... } ), I have revised my initial script. There is no longer a need to debounce the slider value because the long computation is not triggered by the slider. There is also no need to have req(theData(), sliderValue()), as far as I can tell. I also added an if(){}else{} in the computation section to check for invalid text data entry. This revised script constitutes one solution to the problem.

library(shiny)

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label=HTML( "Type data here. (Must be at least two numeric values separated by whitespace.)" ) ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("Select constant to add to mean of data. (Slider settings will change if data change.)") ,
                   min=NA , max=NA , value=NA ,
                   round=FALSE , step=1 , ticks=FALSE ),
      HTML("
Click the button to start the time-consuming computation:") ,
      actionButton( inputId="runComp" ,
                    label="Start Computation" )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  theDataDefault = c(-1, 1)

  # Parse data values out of data text:
  theData = reactive({
    yText = input$dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    if ( any(is.na(theData())) | length(theData()) < 2 ) {
      y = theDataDefault
    } else {
      y = theData()
    }
    low = min( y )
    val = mean( range( y ) )
    high = max( y )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Compute output:
  textOut <- eventReactive( input$runComp, {
    if ( any(is.na(theData())) | length(theData()) < 2 ) {
      return( "ERROR: Data must be at least two numeric values (no letters) separated by whitespace (no commas, etc.)." )
    } else {
      Sys.sleep(3) # simulate lengthy computation time
      return( paste( "Time-consuming computation...
                   Mean of data plus slider value: " ,
                     mean( theData()) + input$slider1 ) )
    }
  })

  output$theOutput <- renderText({
    textOut()
  })

} # end server

shinyApp(ui = ui, server = server)

Body:
Please check if this meets your expectations:

The initial value for your slider now is NA, so that you can block the inital display via req(). Furthermore I isolated theData() in renderText to avoid it beeing triggered twice (only listening for changes of the slider).

library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput( inputId="dataText" ,
                     label="Adapt slider data:" ,
                     value="10 20 30 40" ,
                     width="200px" ,
                     height="100px" ) ,
      # Slider input, to be updated by data:
      sliderInput( inputId = "slider1" ,
                   label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
                   min=NA , max=NA , value=NA ,
                   round=FALSE , step=1 , ticks=FALSE ),
      actionButton( inputId="runComp" ,
                    label="Start Computation" )
    ) , # end sidebarPanel
    mainPanel(
      textOutput("theOutput")
    )
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {

  # Parse data values out of data text:
  theData = reactive({
    yText = input$dataText
    y = as.numeric(unlist(strsplit(yText,"\\s+")[[1]]))
    if ( any(is.na(y)) | length(y) < 2 ) {
      y=c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput( session ,
                           inputId="dataText" ,
                           value=paste(as.character(y),collapse=" ") )
    }
    return( y )
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min( theData() )
    val = median( theData() )
    high = max( theData() )
    return( list( low=low , val=val , high=high ) )
  })
  # Update slider based on data values:
  observe({
    updateSliderInput( session , inputId="slider1" ,
                       min=upUI()$low ,
                       max=upUI()$high ,
                       value=upUI()$val )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    return( input$slider1 )
  }) %>% debounce(debounceDelay)

  # Compute output:
  textOut <- eventReactive(input$runComp, {
    req(theData(), sliderValue())
    Sys.sleep(3) # simulate lengthy computation time
    print(paste(Sys.time(), "Time-consuming computation..."))
    return( paste( "Time-consuming computation...
        Mean of data plus slider value: " ,
                   mean(theData()) + sliderValue() ) )
  })

  output$theOutput <- renderText({
    textOut()
  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)

Edit: Here is a (time based) solution adressing the expected behaviour as described by @JohnK.Kruschke. I personally prefer the above solution (This might fail if the host PC is slowed down by external circumstances, nevertheless it worked during my tests).

library(shiny)
library(magrittr) # for pipe operator, %>%, used with debounce().
debounceDelay = 2000 # milliseconds

ui <- fluidPage(
  titlePanel("Data affect Slider, both affect Subsequent Long Computation"),
  sidebarLayout(
    sidebarPanel(
      # Data input:
      textAreaInput(
        inputId = "dataText" ,
        label = "Type data, then click Submit:" ,
        value = "10 20 30 40" ,
        width = "200px" ,
        height = "100px"
      ) ,
      p(actionButton(inputId = "dataSubmit" ,
                   label = "Submit Data")) ,
      # Slider input, to be updated by data:
      sliderInput(
        inputId = "slider1" ,
        label = HTML("Constant to Add to Mean of Data
                                (after debounce delay):") ,
        min=3000 , max=5000 , value=4000 ,
        round = FALSE ,
        step = 1 ,
        ticks = FALSE
      )
    ) ,
    # end sidebarPanel
    mainPanel(textOutput("theOutput"))
  ) # end sidebarLayout
) # end ui fluidPage

server <- function(input, output, session) {
  sliderUpdates <- reactiveValues(latestProgrammatic = Sys.time(), timeDiff = 0)

  # Parse data values out of data text:
  theData = reactive({
    input$dataSubmit# establish dependency on dataSubmit button
    yText = isolate(input$dataText) # remove dependency on dataText
    y = as.numeric(unlist(strsplit(yText, "\\s+")[[1]]))
    if (any(is.na(y)) | length(y) < 2) {
      y = c(-12.3, 45.6, 78.9) # arbitrary replacement values
      updateTextAreaInput(session ,
                          inputId = "dataText" ,
                          value = paste(as.character(y), collapse = " "))
    }
    return(y)
  })
  # Computation on data for using in slider update:
  upUI <- reactive({
    low = min(theData())
    val = median(theData())
    high = max(theData())
    return(list(
      low = low ,
      val = val ,
      high = high
    ))
  })
  # Update slider based on data values:
  observeEvent(upUI(), {
    sliderUpdates$latestProgrammatic <- Sys.time()
    print(paste("Programmatic slider update was triggered:" , sliderUpdates$latestProgrammatic))
    updateSliderInput(
      session ,
      inputId = "slider1" ,
      min = upUI()$low ,
      max = upUI()$high ,
      value = upUI()$val
    )
  })

  # Debounce the slider value so it doesn't instantly trigger a cascade of long
  # computations
  sliderValue <- reactive({
    latestUnkown <- Sys.time()
    print(paste("Slider was updated:" , latestUnkown))
    sliderUpdates$timeDiff <- latestUnkown - sliderUpdates$latestProgrammatic

    req(input$slider1)
    return(input$slider1)
  }) %>% debounce(debounceDelay)

  # Compute output:
  output$theOutput <- renderText({
    req(theData(), sliderValue(), req(isolate(sliderUpdates$timeDiff)))

    print(paste("Elapsed time since the last programmatic slider update:", isolate(sliderUpdates$timeDiff)))
    if(isolate(sliderUpdates$timeDiff) > 0.2){
      Sys.sleep(3) # simulate lengthy computation time
      return(
        paste(
          "Time-consuming computation...
        Mean of data plus slider value: " ,
          mean(theData()) + sliderValue()
        )
      )
    } else {
      NULL
    }

  }) # end of renderText

} # end server

shinyApp(ui = ui, server = server)


问:
ion-tabs displaying, but not switching to other tabs
I couldn't find a question that helps me.

I've this on every one of my pages. The navbar is displaying, but the buttons aren't switching to other tabs. This is quite literally copied from the ionic start myApp tabs.

This is one of the pages:

<ion-header>
  <ion-toolbar>
    <ion-title>Playlists</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

</ion-content>

<ion-tabs>
    <ion-tab-bar slot="bottom">
        <ion-tab-button tab="saved">
            <ion-icon name="heart"></ion-icon>
            <ion-label>Saved</ion-label>
        </ion-tab-button>
        <ion-tab-button tab="search">
            <ion-icon name="search"></ion-icon>
            <ion-label>Search</ion-label>
        </ion-tab-button>
        <ion-tab-button tab="playlists">
            <ion-icon name="list"></ion-icon>
            <ion-label>Playlists</ion-label>
        </ion-tab-button>
    </ion-tab-bar>
</ion-tabs>
```

<p>And this is my <code>app-routing.modules.ts</code> file:</p>

<pre class="lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'saved', pathMatch: 'full' },
  { path: 'saved', loadChildren: './pages/saved/saved.module#SavedPageModule' },
  { path: 'search', loadChildren: './pages/search/search.module#SearchPageModule' },
  { path: 'playlists', loadChildren: './pages/playlists/playlists.module#PlaylistsPageModule' }
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

答: Just went with the default tabs template again, you need a tabs router. I hadn't made any progress so it's fine.</p>

Body:
I couldn't find a question that helps me.

I've this on every one of my pages. The navbar is displaying, but the buttons aren't switching to other tabs. This is quite literally copied from the ionic start myApp tabs.

This is one of the pages:

<ion-header>
  <ion-toolbar>
    <ion-title>Playlists</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

</ion-content>

<ion-tabs>
    <ion-tab-bar slot="bottom">
        <ion-tab-button tab="saved">
            <ion-icon name="heart"></ion-icon>
            <ion-label>Saved</ion-label>
        </ion-tab-button>
        <ion-tab-button tab="search">
            <ion-icon name="search"></ion-icon>
            <ion-label>Search</ion-label>
        </ion-tab-button>
        <ion-tab-button tab="playlists">
            <ion-icon name="list"></ion-icon>
            <ion-label>Playlists</ion-label>
        </ion-tab-button>
    </ion-tab-bar>
</ion-tabs>

And this is my app-routing.modules.ts file:

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', redirectTo: 'saved', pathMatch: 'full' },
  { path: 'saved', loadChildren: './pages/saved/saved.module#SavedPageModule' },
  { path: 'search', loadChildren: './pages/search/search.module#SearchPageModule' },
  { path: 'playlists', loadChildren: './pages/playlists/playlists.module#PlaylistsPageModule' }
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}