问:
Data Consistency Across Microservices
While each microservice generally will have its own data - certain entities are required to be consistent across multiple services.

For such data consistency requirement in a highly distributed landscape such as microservices architecture, what are the choices for design? Of course, I do not want shared database architecture, where a single DB manages the state across all the services. That violates isolation and shared-nothing principles.

I do understand that, a microservice can publish an event when an entity is created, updated or deleted. All other microservices which are interested in this event can accordingly update the linked entities in their respective databases.

This is workable, however it leads to a lot of careful and coordinated programming effort across the services.

Can Akka or any other framework solve this use case? How?

EDIT1:

Adding the below diagram for clarity.

Basically, I am trying to understand, if there are available frameworks today that can solve this data consistency problem.

For the queue I can use any AMQP software such as RabbitMQ or Qpid etc.
For the data consistency framework, I am not sure if presently Akka or any other software can help. Or is this scenario so uncommon, and such an anti-pattern that no framework should be ever needed?

答:
Managing Data Access Between Modules

What Is A Module?

A module is a piece of software that has a functionality by itself. A module can be deployed together with others modules as a monolith or seperately as a microservice. When defining a module one should be careful because managing data access between modules becomes harder. Thus it requires a good amount of experience in a specific field to decide. It's better to make the mistake of merging "actual two modules" into one rather than seperating a "single module" into two. Because if you seperate a module into two when you shouldn't there are going to be lots of data acces between these modules, which can be pretty hard to manage especially if there is transactional logic. But sometimes it is necessary to make modules espeacilly when things start to get big. Here is a decision tree I use to decide which kind of strategy I must choose:

Decision Tree For Data Reads

If there are two services such that A depends on B...

and they are in the same module...

and A requires a simple data read: A should use the interface of B which is implemented by direct database read.

and A requires complex data read1 : direct database table join should be used for reads.

and they are in different modules...

and A requires simple data read...

and they are deployed as monolith: A should use the interface of B which is implemented with direct database read.

and they are deployed as microservices:  A should use the interface of B which is implemented with a http client.

and A requires a complex data read...

and they are deployed as monolith: A should copy data from B in a different format optimized for its use case by consuming from an in-memory event bus.

and they are deployed as microservices: A should copy data from B in a different format optimized for its use case using an event bus consumer.

Decision Tree For Data Writes

If there are two services such that A depends on B...

and they are deployed as a monolith: interface of B should be implemented with direct database write.

and they are deployed as microservices... (might require distributed transaction management between services)

and A requires simple data write: A should use the interface of B which is implemented with a HttpClient.

and A requires complex data write2 : A should use the interface of B which is implemented with an event bus poducer.

complex data read1: batch processing, ordering/filtering aftrer join, transaction management etc.
complex data write2: IO intensive, CPU intensive, Network intensive

Title: Data Consistency Across Microservices


来源: stackexchange

问:
C++ Win32 Padding zeros to an int via to_wstring
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}
```

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.

答:
Writing your output to a std::wstringstream object is very similar to writing to the std::wcout stream; you use consecutive calls to the << operator; then, when you are finished, you can get a copy of the underlying wstring object using the .str() member function.

You can control the width and padding character for each field, individually, using the std::setw and std::setfill functions – you can put calls to these, if required, before each field whose output you want to adjust.

In your case, you can use the default formats for all fields except the last, where you would set the width to 2 and the fill character to L'0':

#include <sstream>
#include <string>
#include <iomanip>

std::wstring Time::DisplayGameTime()
{
    std::wstringstream message;
    message
        << L"Current Time: "
        // D,M,Y,H using default format ...
        << L" " << Days()
        << L", " << Months()
        << L", " << Years()
        << L" " << Hours()
        // Add Minute using zero-padded, fixed width of 2 ...
        << L" : " << std::setw(2) << std::setfill(L'0') << Minutes();
    return message.str();
}
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.


问:
How to write a Verilog function that determines if all elements in an array are equal?
Let's say I have N registers and I want a function that checks if all register contents are equal. How do I write that without having to spell out every single element?</p>

```<code>function equal (input [0:N-1][width-1:0] in);
    equal = (???) ? 1'b1 : 1'b0;
endfunction
</code>```

答:
```<code>module tb;

parameter W = 8;
parameter N= 4;

logic [N-1:0][W-1:0] in0, in1;
logic res;

initial begin
    in0 = {8'd6,8'd6,8'd6,8'd6};
    in1 = {8'd6,8'd6,8'd55,8'd6};

    res = equal(in0);
    $display(res);
    res = equal(in1);
    $display(res);
end

function logic equal(input logic [N-1:0][W-1:0] in);
    equal = (in === {N{in[0]}}) ? 1 : 0;
endfunction

endmodule
</code>```

Modelsim results:

```<code># 1
# 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have N registers and I want a function that checks if all register contents are equal. How do I write that without having to spell out every single element?

function equal (input [0:N-1][width-1:0] in);
    equal = (???) ? 1'b1 : 1'b0;
endfunction

Body:
module tb;

parameter W = 8;
parameter N= 4;

logic [N-1:0][W-1:0] in0, in1;
logic res;

initial begin
    in0 = {8'd6,8'd6,8'd6,8'd6};
    in1 = {8'd6,8'd6,8'd55,8'd6};

    res = equal(in0);
    $display(res);
    res = equal(in1);
    $display(res);
end

function logic equal(input logic [N-1:0][W-1:0] in);
    equal = (in === {N{in[0]}}) ? 1 : 0;
endfunction

endmodule

Modelsim results:

# 1
# 0


问:
How to subscribe to input for it to save changes into an object?
I have an input in a form of HTML like this:

```<code> <mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input id = "flowRate" type="number" matInput>
  </mat-form-field>
</code>```

To which I subscribe later in my .ts file like this:

```<code>private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement

 if (flowRateInput: any) {
  let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
      debounceTime(500)
    ).subscribe(res => {
      this.calcData.flowRate = +this.flowRateInput.value;
      console.log(this.flowRateInput.value)
      console.log(this.calcData)
    })
  }
</code>```

However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.

答:
you don't need to subscript and you don't need to to do document.getElementById('flowRate') in angular.

you can use ngModel for example:
<input type="number" matInput [(ngModel)]="flowRate">

```<code>private _flowRate="";
set flowRate(flowRate){
 this._flowRate = flowRate;
  this.calcData.flowRate = +this.flowRateInput.value;
}
get flowRate(){
 return this._flowRate;
}
</code>```

or you can listen to the change event:
<input type="number" matInput (change)="flowRateChange($event)> or <input type="number" matInput [ngModel]="flowRate" (ngModelChange)="flowRateChange($event)"

Body:
I have an input in a form of HTML like this:

 <mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input id = "flowRate" type="number" matInput>
  </mat-form-field>

To which I subscribe later in my .ts file like this:

private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement

 if (flowRateInput: any) {
  let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
      debounceTime(500)
    ).subscribe(res => {
      this.calcData.flowRate = +this.flowRateInput.value;
      console.log(this.flowRateInput.value)
      console.log(this.calcData)
    })
  }

However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.

Body:
you don't need to subscript and you don't need to to do document.getElementById('flowRate') in angular.

you can use ngModel for example:
<input type="number" matInput [(ngModel)]="flowRate">

private _flowRate="";
set flowRate(flowRate){
 this._flowRate = flowRate;
  this.calcData.flowRate = +this.flowRateInput.value;
}
get flowRate(){
 return this._flowRate;
}

or you can listen to the change event:
<input type="number" matInput (change)="flowRateChange($event)> or <input type="number" matInput [ngModel]="flowRate" (ngModelChange)="flowRateChange($event)"


问:
Find first file with given filename
Hello I am trying to find first file with given filename ( piece of filename ).

It works fine but it take a while to take result

There is code

```<code>const fs = require("fs");

const dirCheckIn =
    "\\\\192.168.2.4\\Photos";

exports.checkUploadedFiles = (req, res) => {
    let fileName = req.params.filename;

    const getAllFiles = function (dirPath, arrayOfFiles) {
        files = fs.readdirSync(dirPath);

        arrayOfFiles = arrayOfFiles || [];

        files.forEach(function (file) {
            if (fs.statSync(dirPath + "/" + file).isDirectory()) {
                arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
            } else {
                arrayOfFiles.push(file);
            }
        });

        return arrayOfFiles;
    };

    const uploadedFiles = getAllFiles(inventDirCheckIn);
    console.log(uploadedFiles)
    let result = uploadedFiles.find(
        (result) => result.startsWith(fileName));

    if (!result) {
        res.send('nothing found')
    } else if (result) {
        res.send(result)
    }

}
</code>```

It works fine but for example if I have over 7000 photos it takes about 5 sec to get result.
Maybe there is smarter solution?

How can I make it in better way? I want to check if file is uploaded into dir Photos.
I got simple api route /api/getUploadedFiles/:filename

Also I want use startsWith because sometimes I do not know full name of file

答:
/**
 *
 * @param filePath path to file which is to be checked if it exists.
 */
private checkFileExistsSync(filePath: string) {
  let flag = true;
  try {
    fs.accessSync(filePath, fs.constants.F_OK);
  } catch (e) {
    flag = false;
  }
  return flag;
}

// Example usage
// path to the file
const dirCheckIn =
    "\\\\192.168.2.4\\Photos";

if (checkFileExistsSync(dirCheckIn)) {
  // if the file exists do something...
}

if (!checkFileExistsSync(dirCheckIn)) {
  // if the file doesn't exists do something...
}```

Title: Find first file with given filename

Body:
Hello I am trying to find first file with given filename ( piece of filename ).

It works fine but it take a while to take result

There is code

const fs = require("fs");

const dirCheckIn =
    "\\\\192.168.2.4\\Photos";

exports.checkUploadedFiles = (req, res) => {
    let fileName = req.params.filename;

    const getAllFiles = function (dirPath, arrayOfFiles) {
        files = fs.readdirSync(dirPath);

        arrayOfFiles = arrayOfFiles || [];

        files.forEach(function (file) {
            if (fs.statSync(dirPath + "/" + file).isDirectory()) {
                arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles);
            } else {
                arrayOfFiles.push(file);
            }
        });

        return arrayOfFiles;
    };

    const uploadedFiles = getAllFiles(inventDirCheckIn);
    console.log(uploadedFiles)
    let result = uploadedFiles.find(
        (result) => result.startsWith(fileName));

    if (!result) {
        res.send('nothing found')
    } else if (result) {
        res.send(result)
    }

}

It works fine but for example if I have over 7000 photos it takes about 5 sec to get result.
Maybe there is smarter solution?

How can I make it in better way? I want to check if file is uploaded into dir Photos.
I got simple api route /api/getUploadedFiles/:filename

Also I want use startsWith because sometimes I do not know full name of file


问:
Maven flyway Found non-empty schema(s) "PUBLIC" but no schema history table
I am just learning Spring Boot with Maven and I have encountered an error that I cannot resolve.
I have attached a dependency from Flyway and when I want to install it (I'm clicking install on Lifecycle), I get this error:

Found non-empty schema(s) "PUBLIC" but no schema history table.
Use baseline() or set baselineOnMigrate to true to initialize the schema history table.

What could be causing this and how to fix it?

I'm using Java 8 and my dependency with Flyway looks like this:

```<code><dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
</dependency>
</code>```

答:
Spring Boot is trying to run Flyway migrate as part of a maven goal it has configured.

Found non-empty schema(s) "PUBLIC" but no schema history table.

The error message is stating that the default schema which Flyway is trying to run against, which is PUBLIC, is not empty. As a result, Flyway know needs to know what the state the database before it is able to create a schema history table and migrate.

Use baseline() or set baselineOnMigrate to true to initialize the schema history table.

These are the two ways you can correct this by creating a baseline to build your migrations upon. https://flywaydb.org/documentation/command/baseline

In spring boot, baseline on migrate can be configured with spring.flyway.baselineOnMigrate=true.

Additionally, install in Maven does not mean install the dependencies but builds and puts the build artifacts of your product in your .m2 maven repository.

Body:
I am just learning Spring Boot with Maven and I have encountered an error that I cannot resolve.
I have attached a dependency from Flyway and when I want to install it (I'm clicking install on Lifecycle), I get this error:

Found non-empty schema(s) "PUBLIC" but no schema history table.
Use baseline() or set baselineOnMigrate to true to initialize the schema history table.

What could be causing this and how to fix it?

I'm using Java 8 and my dependency with Flyway looks like this:

<dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
</dependency>


问:
How to get string value from object datatype column in python dataframe which have combination of datatype values in column
I want to get row from this dataframe which have string value in column "city".

```<code>  | city  | region
0 | 5     | 19
1 | Pakri | 37
2 | 9     | 26
3 | 452   | 59
4 | 66    | 2
5 | 226   | 19
</code>```

Answer should like the below snippet which contain row that have string value in its first column

```<code>  | city  | region
0 | Pakri | 37
</code>```

答:
You could use a boolean filter using apply to the pandas DataFrame o Series.

consider:

```<code>import pandas as pd
import numpy as np

#create a series
s=  pd.Series([5,100,'string'], dtype=object)

#set type to string
s =  s.astype(str)

# apply
temp = s.apply(lambda x: x.isdigit())

#return
#(0, True) (1, True) (2, False)

#index of the string
index = np.where(temp == False)

#select by index
s.loc[index]

#return
# (2, 'string')
</code>```

Body:
I want to get row from this dataframe which have string value in column "city".

  | city  | region
0 | 5     | 19
1 | Pakri | 37
2 | 9     | 26
3 | 452   | 59
4 | 66    | 2
5 | 226   | 19

Answer should like the below snippet which contain row that have string value in its first column

  | city  | region
0 | Pakri | 37

Body:
You could use a boolean filter using apply to the pandas DataFrame o Series.

consider:

import pandas as pd
import numpy as np

#create a series
s=  pd.Series([5,100,'string'], dtype=object)

#set type to string
s =  s.astype(str)

# apply
temp = s.apply(lambda x: x.isdigit())

#return
#(0, True) (1, True) (2, False)

#index of the string
index = np.where(temp == False)

#select by index
s.loc[index]

#return
# (2, 'string')


问:
Split text in hash value into new hash using separator in Ruby
I found another question similar to the one I have, but I was not able to replicate it (probably because it doesn't deal with hashes neither have symbols).

So, given the following array of hashes:

```<code>[{:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
 {:id=>2, :name=>"BA;BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]
</code>```

I would like to achieve the following result:

```<code>[{:id=>1, :name=>"AA", :title=>"A row"},
 {:id=>1, :name=>"AB", :title=>"A row"},
 {:id=>1, :name=>"AC", :title=>"A row"},
 {:id=>2, :name=>"BA", :title=>"B row"},
 {:id=>2, :name=>"BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]
</code>```

In brief, I want to fully replicate a hash, splitting it by semicolon. In this case, :name have two hashes with one or more semicolons that should be split and consist on another hash.

I hope you have understand my question. Any help is highly appreciated.

答:
You could iterate over your array of hashes and split their name value, and map that result merging it with the current hash. Then you can flatten the result:

```<code>[
  {:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
  {:id=>2, :name=>"BA;BB", :title=>"B row"},
  {:id=>3, :name=>"CA", :title=>"C row"}
].flat_map do |hsh|
  hsh[:name].split(";").map do |name|
    hsh.merge(name: name)
  end
end

# [{:id=>1, :name=>"AA", :title=>"A row"},
#  {:id=>1, :name=>"AB", :title=>"A row"},
#  {:id=>1, :name=>"AC", :title=>"A row"},
#  {:id=>2, :name=>"BA", :title=>"B row"},
#  {:id=>2, :name=>"BB", :title=>"B row"},
#  {:id=>3, :name=>"CA", :title=>"C row"}]
</code>```

Body:
I found another question similar to the one I have, but I was not able to replicate it (probably because it doesn't deal with hashes neither have symbols).

So, given the following array of hashes:

[{:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
 {:id=>2, :name=>"BA;BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

I would like to achieve the following result:

[{:id=>1, :name=>"AA", :title=>"A row"},
 {:id=>1, :name=>"AB", :title=>"A row"},
 {:id=>1, :name=>"AC", :title=>"A row"},
 {:id=>2, :name=>"BA", :title=>"B row"},
 {:id=>2, :name=>"BB", :title=>"B row"},
 {:id=>3, :name=>"CA", :title=>"C row"}]

In brief, I want to fully replicate a hash, splitting it by semicolon. In this case, :name have two hashes with one or more semicolons that should be split and consist on another hash.

I hope you have understand my question. Any help is highly appreciated.

Body:
You could iterate over your array of hashes and split their name value, and map that result merging it with the current hash. Then you can flatten the result:

[
  {:id=>1, :name=>"AA;AB;AC", :title=>"A row"},
  {:id=>2, :name=>"BA;BB", :title=>"B row"},
  {:id=>3, :name=>"CA", :title=>"C row"}
].flat_map do |hsh|
  hsh[:name].split(";").map do |name|
    hsh.merge(name: name)
  end
end

# [{:id=>1, :name=>"AA", :title=>"A row"},
#  {:id=>1, :name=>"AB", :title=>"A row"},
#  {:id=>1, :name=>"AC", :title=>"A row"},
#  {:id=>2, :name=>"BA", :title=>"B row"},
#  {:id=>2, :name=>"BB", :title=>"B row"},
#  {:id=>3, :name=>"CA", :title=>"C row"}]


问:
How to configure server for reloading page in reactjs
I am using Apache 2.2, on centos OS to host my reactjs app ... in my App.js I have this code

```<code>import React from "react";
import { createBrowserHistory } from "history";
import { BrowserRouter, Route, Switch} from "react-router-dom";
import axios from "axios";
// import { useSelector } from "react-redux";

// core components
import AuthLayout from "layouts/Auth.js";
import RtlLayout from "layouts/RTL.js";
import AdminLayout from "layouts/Admin.js";
import LoginPage from "views/Pages/LoginPage";
import User from "layouts/User";

import "assets/scss/material-dashboard-pro-react.scss?v=1.10.0";
import moment from 'moment'

require('moment-timezone')
moment.tz.setDefault('Africa/Nairobi')

const App = () => {

  const hist = createBrowserHistory();

  axios.defaults.baseURL = `https://myurl.com:8443/strategy/api/`;

  return (
    <BrowserRouter history={hist}>
    <Switch>
      <Route path="/rtl" component={RtlLayout} />
      <Route path="/auth" component={AuthLayout} />
      <Route path="/admin" component={AdminLayout} />
      <Route path="/user" component={User} />
      <Route path="/" component={LoginPage} />
          </Switch>
  </BrowserRouter>
  );
}

export default App;

</code>```

I then use yarn build and everything in my build folder is moved to my DocumentRoot folder /var/www/html/stratex

In this /var/www/html/stratex i also have a .htaccess file and in that I have

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /subdirectory
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>
</code>```

After this , i restarted my server :

```<code>sudo service httpd restart
</code>```

When i go to /admin/dashboard it is fine and when i hit refresh i get

```<code>The requested URL /admin/dashboard was not found on this server.
</code>```

I also have another link /user/dashboard which loads fine but on refresh it says

```<code>The requested URL /user/dashboard was not found on this server
</code>```

Has anyone come across this issue ? I see so much online about the .htaccess file fixing the issue but it has not worked for me at all. I also added this line in my httpd.conf

```<code>LoadModule rewrite_module modules/mod_rewrite.so

</code>```

Any recommendations/help will be appreciated.

答:
To solve this , i added this in my virtualhost

```<code> <Directory /var/www/html/stratex>
    AllowOverride All
 </Directory>
</code>```

I followed this tutorial.

And my .htaccess looks like this :

```<code> RewriteEngine On
  RewriteBase /subdirectory
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</code>```

Body:
I am using Apache 2.2, on centos OS to host my reactjs app ... in my App.js I have this code

import React from "react";
import { createBrowserHistory } from "history";
import { BrowserRouter, Route, Switch} from "react-router-dom";
import axios from "axios";
// import { useSelector } from "react-redux";

// core components
import AuthLayout from "layouts/Auth.js";
import RtlLayout from "layouts/RTL.js";
import AdminLayout from "layouts/Admin.js";
import LoginPage from "views/Pages/LoginPage";
import User from "layouts/User";

import "assets/scss/material-dashboard-pro-react.scss?v=1.10.0";
import moment from 'moment'

require('moment-timezone')
moment.tz.setDefault('Africa/Nairobi')

const App = () => {

  const hist = createBrowserHistory();

  axios.defaults.baseURL = `https://myurl.com:8443/strategy/api/`;

  return (
    <BrowserRouter history={hist}>
    <Switch>
      <Route path="/rtl" component={RtlLayout} />
      <Route path="/auth" component={AuthLayout} />
      <Route path="/admin" component={AdminLayout} />
      <Route path="/user" component={User} />
      <Route path="/" component={LoginPage} />
          </Switch>
  </BrowserRouter>
  );
}

export default App;

I then use yarn build and everything in my build folder is moved to my DocumentRoot folder /var/www/html/stratex

In this /var/www/html/stratex i also have a .htaccess file and in that I have

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /subdirectory
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

After this , i restarted my server :

sudo service httpd restart

When i go to /admin/dashboard it is fine and when i hit refresh i get

The requested URL /admin/dashboard was not found on this server.

I also have another link /user/dashboard which loads fine but on refresh it says

The requested URL /user/dashboard was not found on this server

Has anyone come across this issue ? I see so much online about the .htaccess file fixing the issue but it has not worked for me at all. I also added this line in my httpd.conf

LoadModule rewrite_module modules/mod_rewrite.so

Any recommendations/help will be appreciated.

Body:
To solve this , i added this in my virtualhost

 <Directory /var/www/html/stratex>
    AllowOverride All
 </Directory>

I followed this tutorial.

And my .htaccess looks like this :

 RewriteEngine On
  RewriteBase /subdirectory
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]


问:
Is it possible to run multiple threads simultaneously on a same core?
I am calling a Flask server(running with 64 gunicorn workers) via http with ThreadPoolExecutor to test execution time.

Both(test script and Flask server) are running on the same host. Inside the Flask endpoint, there is a DB(Postgres) call.

Machine stats (11 cores, 16 GB ram)

Test script:

```<code>class StressTest():

    def __init__(self, max_workers):
        self.__max_workers = max_workers

    def __async_test(self, x=range(1000)):
        with ThreadPoolExecutor(max_workers=self.__max_workers) as executor:
            futures = [
                executor.submit(
                    self.__test,
                    n=n
                )
                for n in x
            ]

        for future in futures:
            try:
                future.result()
            except Exception as e:
                raise Exception(e)

    def __test(self, n):
        # Rest call

    def run(self):
        start_time = datetime.now()
        self.__async_test()

        duration = datetime.now() - start_time
        self.logger.info(f"duration for the process is {duration.total_seconds()} seconds")

if __name__ == "__main__":
    StressTest(1).run()
    StressTest(2).run()
    StressTest(4).run()
    .......
</code>```

Results as follows:

No of threads
Execution time (s)

1
50

2
25

4
12

8
8.5

16
8

32
7.5

64
7.5

My question is why execution time is saturating after 8 threads? Isn't it possible to run multiple threads at the same time in a given core?

Any given time, only 11 threads are running (via htop) during the test.

Please let me know if you want additional information about my test. Thank you!

答:
TL/DR: Regardless a programming language used, given core can execute only 1 thread for a given moment of time.

More details:
While we say "thread" we can mean CPU-level execution entity (and the answer is above, period), or we can actually talk about so called "tasks", or "async execution", or "futures", whatever. All that terms are about describing a next-level abstraction over a thread via specifying logical steps to get the business be done, not about direct utilization of CPU capabilities. However, actual execution of that abstraction is still performed via CPU thread(s). And that returns us back to the very first disclaimer: given core can execute only 1 thread for a given moment of time.

Body:
I am calling a Flask server(running with 64 gunicorn workers) via http with ThreadPoolExecutor to test execution time.

Both(test script and Flask server) are running on the same host. Inside the Flask endpoint, there is a DB(Postgres) call.

Machine stats (11 cores, 16 GB ram)

Test script:

class StressTest():

    def __init__(self, max_workers):
        self.__max_workers = max_workers

    def __async_test(self, x=range(1000)):
        with ThreadPoolExecutor(max_workers=self.__max_workers) as executor:
            futures = [
                executor.submit(
                    self.__test,
                    n=n
                )
                for n in x
            ]

        for future in futures:
            try:
                future.result()
            except Exception as e:
                raise Exception(e)

    def __test(self, n):
        # Rest call

    def run(self):
        start_time = datetime.now()
        self.__async_test()

        duration = datetime.now() - start_time
        self.logger.info(f"duration for the process is {duration.total_seconds()} seconds")

if __name__ == "__main__":
    StressTest(1).run()
    StressTest(2).run()
    StressTest(4).run()
    .......

Results as follows:

No of threads
Execution time (s)

1
50

2
25

4
12

8
8.5

16
8

32
7.5

64
7.5

My question is why execution time is saturating after 8 threads? Isn't it possible to run multiple threads at the same time in a given core?

Any given time, only 11 threads are running (via htop) during the test.

Please let me know if you want additional information about my test. Thank you!


问:
Use active record to find a record by month and day, ignoring year and time
I have a model (Entries) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00, will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.

RoR 3.0.9 / Ruby 1.9.2p290

答:
Assuming that you are using mysql:</p>

```<code>User.where(["DAY(created_at) = ? AND MONTH(created_at) = ?", date.day, date.month])
</code>```

Body:
Assuming that you are using mysql:

User.where(["DAY(created_at) = ? AND MONTH(created_at) = ?", date.day, date.month])


问:
Count by group using dplyr, but also count 0s
I'm making a count table for 2 data frames. One looks like this:

```<code>table1 <- data.table("Col1" = c("Al", "Al", "Al", "Cu", "Cu", "Cu", "Pb", "Pb",
"Pb"), "Col2" = c("F", "UF", "P", "F", "UF", "P", "F", "UF", "P"), "Col3" = c("C",
"UC", "<", "C", "UC", "<", "C", "UC", "<"))

table2 <- data.table("Col1" = c("Al", "Al", "Cu", "Pb", "Pb", "Pb"), "Col2" = c("F",
"UF", "F", "F", "UF", "P"), "Col3" = c("C", "UC", "<", "C", "UC", "<"))
</code>```

I'd create a count table for table1 and table2 like this:

```<code>table1 %>% group_by(Col1, Col2, Col3) %>% tally()

# A tibble: 9 x 4
# Groups:   Col1, Col2 [9]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    P     <         1
3 Al    UF    UC        1
4 Cu    F     C         1
5 Cu    P     <         1
6 Cu    UF    UC        1
7 Pb    F     C         1
8 Pb    P     <         1
9 Pb    UF    UC        1

table2 %>% group_by(Col1, Col2, Col3) %>% tally()
# A tibble: 6 x 4
# Groups:   Col1, Col2 [6]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    UF    UC        1
3 Cu    F     <         1
4 Pb    F     C         1
5 Pb    P     <         1
6 Pb    UF    UC        1
</code>```

But I'd like the count table for table2 to have the 0 counts with the combinations from table1, not remove them completely so it doesn't show the 0 counts. Is there a way I can do this with dplyr or a different package?

Thank you for your help!

答:
What about this?

```<code>table1 %>%
  left_join(cbind(table2, n = 1)) %>%
  group_by(Col1, Col2, Col3) %>%
  mutate(n = sum(n, na.rm = TRUE))
</code>```

and we will see

```<code>  Col1  Col2  Col3      n
  <chr> <chr> <chr> <dbl>
1 Al    F     C         1
2 Al    UF    UC        1
3 Al    P     <         0
4 Cu    F     C         0
5 Cu    UF    UC        0
6 Cu    P     <         0
7 Pb    F     C         1
8 Pb    UF    UC        1
9 Pb    P     <         1
</code>```

Body:
I'm making a count table for 2 data frames. One looks like this:

table1 <- data.table("Col1" = c("Al", "Al", "Al", "Cu", "Cu", "Cu", "Pb", "Pb",
"Pb"), "Col2" = c("F", "UF", "P", "F", "UF", "P", "F", "UF", "P"), "Col3" = c("C",
"UC", "<", "C", "UC", "<", "C", "UC", "<"))

table2 <- data.table("Col1" = c("Al", "Al", "Cu", "Pb", "Pb", "Pb"), "Col2" = c("F",
"UF", "F", "F", "UF", "P"), "Col3" = c("C", "UC", "<", "C", "UC", "<"))

I'd create a count table for table1 and table2 like this:

table1 %>% group_by(Col1, Col2, Col3) %>% tally()

# A tibble: 9 x 4
# Groups:   Col1, Col2 [9]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    P     <         1
3 Al    UF    UC        1
4 Cu    F     C         1
5 Cu    P     <         1
6 Cu    UF    UC        1
7 Pb    F     C         1
8 Pb    P     <         1
9 Pb    UF    UC        1

table2 %>% group_by(Col1, Col2, Col3) %>% tally()
# A tibble: 6 x 4
# Groups:   Col1, Col2 [6]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    UF    UC        1
3 Cu    F     <         1
4 Pb    F     C         1
5 Pb    P     <         1
6 Pb    UF    UC        1

But I'd like the count table for table2 to have the 0 counts with the combinations from table1, not remove them completely so it doesn't show the 0 counts. Is there a way I can do this with dplyr or a different package?

Thank you for your help!

Body:
What about this?

table1 %>%
  left_join(cbind(table2, n = 1)) %>%
  group_by(Col1, Col2, Col3) %>%
  mutate(n = sum(n, na.rm = TRUE))

and we will see

  Col1  Col2  Col3      n
  <chr> <chr> <chr> <dbl>
1 Al    F     C         1
2 Al    UF    UC        1
3 Al    P     <         0
4 Cu    F     C         0
5 Cu    UF    UC        0
6 Cu    P     <         0
7 Pb    F     C         1
8 Pb    UF    UC        1
9 Pb    P     <         1


问:
Remove characters from the last column of a list of data frame
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

```<code>Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks
</code>```

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

答:
Base R solution:</p>
```<code>## requires R version 4.1 or higher
listDF = lapply(listDF,
  \(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })
</code>```
```<code>## any R version
listDF = lapply(listDF,
  function(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })
</code>```

Body:
I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

Body:
Base R solution:

## requires R version 4.1 or higher
listDF = lapply(listDF,
  \(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })

## any R version
listDF = lapply(listDF,
  function(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })


问:
Git rebase a branch on another after parent branch is merged to master
If I have branch_1 forked out of master with let's say 2 commits.

Next, I made branch_2 forked out of branch_1.

On branch_2 I have made changes which are not in the area branch_1. I of course have changes from branch_1 included here but I have not touched those changes.

Now let's say branch_1 merges into master.

Next, on branch_2 I do git pull upstream master --rebase to rebase branch_2 on top of master so that commits from branch_1 disappear from commit history of branch_2. I should not get merge conflicts here. Right? But I do in the same lines of code which were changed on branch_1. This is strange! Is this expected?

答:
Your assumption about what the rebase would do is valid, if git knows the relationship between branch_1 and branch_2. Your problem is that you threw away that relationship by rebasing or squashing branch_1.

With a true merge, your commit graph would look like this (where "M" is the merge commit when you merged branch_1 into master):

```<code>            master
              |
              v
... <- A <--- M
        \    /
         <- B <- C
            ^    ^
            |    |
       branch_1 branch_2
</code>```

Then, when you rebased branch_2 onto master, git would find that commit B is already reachable from master (as a parent of commit M), so wouldn't include it in the list of commits to replay.

However, when you squashed branch_1, you created this (where "BS" is the result of squashing branch_1):

```<code>            master
              |
              v
... <- A <--- BS
        \
         <- B <- C
            ^    ^
            |    |
       branch_1 branch_2
</code>```

Now when you ask to rebase branch_2 on master, it finds that commit B is not reachable from master (commit BS), so includes it in the list of commits to replay. If commit B was actually multiple commits, it will apply them one by one, and since the changes have already happened in BS, you'll get conflicts when it does so.

The solution (other than using true merges from now on ) is to be more explicit about what you want to rebase, by either:

Using an interactive rebase (git rebase -i upstream/master) and manually deleting the commits from branch_1 from the todo list

Using the three-argument form of git rebase, "rebase old_base old_tip --onto new_base": git rebase branch_1 branch_2 --onto upstream/master

Body:
Your assumption about what the rebase would do is valid, if git knows the relationship between branch_1 and branch_2. Your problem is that you threw away that relationship by rebasing or squashing branch_1.

With a true merge, your commit graph would look like this (where "M" is the merge commit when you merged branch_1 into master):

            master
              |
              v
... <- A <--- M
        \    /
         <- B <- C
            ^    ^
            |    |
       branch_1 branch_2

Then, when you rebased branch_2 onto master, git would find that commit B is already reachable from master (as a parent of commit M), so wouldn't include it in the list of commits to replay.

However, when you squashed branch_1, you created this (where "BS" is the result of squashing branch_1):

            master
              |
              v
... <- A <--- BS
        \
         <- B <- C
            ^    ^
            |    |
       branch_1 branch_2

Now when you ask to rebase branch_2 on master, it finds that commit B is not reachable from master (commit BS), so includes it in the list of commits to replay. If commit B was actually multiple commits, it will apply them one by one, and since the changes have already happened in BS, you'll get conflicts when it does so.

The solution (other than using true merges from now on ) is to be more explicit about what you want to rebase, by either:

Using an interactive rebase (git rebase -i upstream/master) and manually deleting the commits from branch_1 from the todo list

Using the three-argument form of git rebase, "rebase old_base old_tip --onto new_base": git rebase branch_1 branch_2 --onto upstream/master


问:
Can remove cookie in IE8 but not chrome13, firefox3.6
Has cookie on browser, my domain is zhu13890.prod.xxxx.corp

Cookie information:

name:Vanilla-Volatile

value:1-1313808454|54614728ee113ab09e4db5c863cd5cfa|1313635654|1|1313808454

domain:zhu13890.prod.xxxx.corp

path:/

I send a request a request to zhu13890.prod.xxxx.corp/ddd/j-security-logout, in fiddler i can see the response code is 302, and contains header:

Set-Cookie: Vanilla-Volatile=""; Domain=zhu13890.prod.xxxx.corp; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/

however, the cookie is not removed.

[8.26]
Last time when I test, I can remove cookie in IE, but can not remove cookie in chrome and firefox. But today can remove in chrome but not in IE or firefox. so confuse

答: IE8 and its predecessors are garbage and don't actually delete cookies until the browser is restarted, even if you tell it to. Does the cookie exist after a browser restart? http://ebmgh.com/blog/2009/12/ie8-does-not-really-delete-cookies-until-restart/</p>


问:
How to change time axis interval on LightWeightChart of TradingView?
Recently, I'm developing stock information web application via TtradingView Chart library.
But, I don't know how to change X-Axis interval on LightWeightChart.  I want to change to bellows.

from
09:00,  09:35, 10:18, 11:03

to
09:00,   09:30,  10:00, 10:30

I saw the TradingView docs and Issues tab on github. But above info does not found.

答:
There is no option for that so far. The grid is based the data you provided to the chart so if your data has gaps or too inconsistent data items within similar periods you will see such picture on the chart. The grid is trying to keep the same space (or similar; in pixels) between displayed values.

So you can either have inconsistent points or spaces and from UX perspective it looks like having spacing consistency is better rather than points one


问:
Manifest merger failed : android:exported needs to be explicitly specified for <receiver>

Merging Errors: Error: android:exported needs to be explicitly specified for element
<receiver#com.instacart.library.truetime.BootCompletedBroadcastReceiver>.
Apps targeting Android 12 and higher are required to specify an
explicit value for android:exported when the corresponding component
has an intent filter defined. See
https://developer.android.com/guide/topics/manifest/activity-element#exported
for details. test.app main manifest (this file), line 19

I don't even know what to do. I struggled with this mistake for a whole week, but I couldn't.

Here is my sdk version

```<code>compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app"
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
        ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

Wrote android:exported on all intent-filter, service, and provider. Ah, I don't have the receiver mentioned in this error.

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation "com.android.billingclient:billing:4.0.0"

    implementation "com.google.firebase:firebase-messaging:23.0.0"
    implementation "com.google.firebase:firebase-crashlytics:18.2.7"
    implementation "com.google.firebase:firebase-analytics:20.0.2"
    implementation "com.google.firebase:firebase-perf:20.0.4"
    implementation "com.google.firebase:firebase-dynamic-links:21.0.0"

    implementation 'com.google.firebase:firebase-core:20.0.2'
    implementation 'com.google.firebase:firebase-database:20.0.3'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-config:21.0.1'
    implementation "com.facebook.android:facebook-login:9.0.0"
    implementation "com.facebook.android:facebook-share:[5,6)"
    implementation "com.linecorp:linesdk:5.0.1"

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'

    implementation "com.squareup.retrofit2:retrofit:2.8.1"
    implementation "com.squareup.retrofit2:converter-gson:2.8.1"
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
    implementation 'io.reactivex:rxandroid:1.2.1'

    implementation 'com.google.code.gson:gson:2.8.6'

    implementation 'com.sun.easysnackbar:easysnackbar:1.0.1'

    implementation 'com.romandanylyk:pageindicatorview:1.0.3@aar'

    implementation 'com.google.android.exoplayer:exoplayer:2.16.1'

    //MULTI DEX
    implementation "androidx.multidex:multidex:2.0.1"

    implementation 'com.google.android:flexbox:2.0.1'

    implementation 'com.github.florent37:diagonallayout:1.0.9'

    implementation('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }

    implementation 'com.github.instacart.truetime-android:library:3.4'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.4'

    implementation "androidx.navigation:navigation-fragment-ktx:2.4.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.4.0"

    implementation "com.github.bumptech.glide:glide:4.12.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.12.0"

    implementation "de.hdodenhof:circleimageview:3.1.0"

    implementation "com.pixplicity.easyprefs:library:1.9.0"

    implementation "com.jakewharton.timber:timber:4.7.1"

    implementation "com.airbnb.android:lottie:3.4.0"

    implementation 'com.github.jinatonic.confetti:confetti:1.1.2'

    implementation "com.nabinbhandari.android:permissions:3.8"

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation "com.github.YarikSOffice:lingver:1.2.1"

    implementation 'com.github.mreram:showcaseview:1.2.0'
    implementation 'com.github.shripal17:MaterialIntroView-v2:2.2.0'

    implementation 'com.github.unsplash:unsplash-photopicker-android:1.0.0'

    implementation 'com.giphy.sdk:ui:2.1.0'

    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core:1.4.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.test.ext:junit:1.1.3"
}
</code>```

答:
```<code>com.instacart.library.truetime.BootCompletedBroadcastReceiver
</code>```

check this in manifest file....

check your lib you imported  if they compatible with your android version

Rebuild your project.

share you manifest and

```<code>compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app" /// change your app Id not to use example... This will be rejected on play store
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
       //comment out this ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
</code>```

Body:
Merging Errors: Error: android:exported needs to be explicitly specified for element
<receiver#com.instacart.library.truetime.BootCompletedBroadcastReceiver>.
Apps targeting Android 12 and higher are required to specify an
explicit value for android:exported when the corresponding component
has an intent filter defined. See
https://developer.android.com/guide/topics/manifest/activity-element#exported
for details. test.app main manifest (this file), line 19

I don't even know what to do. I struggled with this mistake for a whole week, but I couldn't.

Here is my sdk version

compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app"
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
        ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

Wrote android:exported on all intent-filter, service, and provider. Ah, I don't have the receiver mentioned in this error.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'

    implementation "com.android.billingclient:billing:4.0.0"

    implementation "com.google.firebase:firebase-messaging:23.0.0"
    implementation "com.google.firebase:firebase-crashlytics:18.2.7"
    implementation "com.google.firebase:firebase-analytics:20.0.2"
    implementation "com.google.firebase:firebase-perf:20.0.4"
    implementation "com.google.firebase:firebase-dynamic-links:21.0.0"

    implementation 'com.google.firebase:firebase-core:20.0.2'
    implementation 'com.google.firebase:firebase-database:20.0.3'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-config:21.0.1'
    implementation "com.facebook.android:facebook-login:9.0.0"
    implementation "com.facebook.android:facebook-share:[5,6)"
    implementation "com.linecorp:linesdk:5.0.1"

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.6.10'

    implementation "com.squareup.retrofit2:retrofit:2.8.1"
    implementation "com.squareup.retrofit2:converter-gson:2.8.1"
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.2.1'
    implementation 'io.reactivex:rxandroid:1.2.1'

    implementation 'com.google.code.gson:gson:2.8.6'

    implementation 'com.sun.easysnackbar:easysnackbar:1.0.1'

    implementation 'com.romandanylyk:pageindicatorview:1.0.3@aar'

    implementation 'com.google.android.exoplayer:exoplayer:2.16.1'

    //MULTI DEX
    implementation "androidx.multidex:multidex:2.0.1"

    implementation 'com.google.android:flexbox:2.0.1'

    implementation 'com.github.florent37:diagonallayout:1.0.9'

    implementation('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }

    implementation 'com.github.instacart.truetime-android:library:3.4'
    implementation 'com.github.instacart.truetime-android:library-extension-rx:3.4'

    implementation "androidx.navigation:navigation-fragment-ktx:2.4.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.4.0"

    implementation "com.github.bumptech.glide:glide:4.12.0"
    annotationProcessor "com.github.bumptech.glide:compiler:4.12.0"

    implementation "de.hdodenhof:circleimageview:3.1.0"

    implementation "com.pixplicity.easyprefs:library:1.9.0"

    implementation "com.jakewharton.timber:timber:4.7.1"

    implementation "com.airbnb.android:lottie:3.4.0"

    implementation 'com.github.jinatonic.confetti:confetti:1.1.2'

    implementation "com.nabinbhandari.android:permissions:3.8"

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation "com.github.YarikSOffice:lingver:1.2.1"

    implementation 'com.github.mreram:showcaseview:1.2.0'
    implementation 'com.github.shripal17:MaterialIntroView-v2:2.2.0'

    implementation 'com.github.unsplash:unsplash-photopicker-android:1.0.0'

    implementation 'com.giphy.sdk:ui:2.1.0'

    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core:1.4.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.test.ext:junit:1.1.3"
}

Body:
com.instacart.library.truetime.BootCompletedBroadcastReceiver

check this in manifest file....

check your lib you imported  if they compatible with your android version

Rebuild your project.

share you manifest and

compileSdkVersion 32
    defaultConfig {
        multiDexEnabled true
        applicationId "com.example.app" /// change your app Id not to use example... This will be rejected on play store
        minSdkVersion 21
        targetSdkVersion 32
        versionCode 53
        versionName "2.0.4"
       //comment out this ndk.abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }


问:
How to trigger the simple "Add to home screen" feature (the one without service worker)
There are in fact two "Add to home screen" features on Android browsers:

The popup dialog that is automatically showed on the bottom of Chrome Android when specific conditions are met (manifest.json available, having a service worker as discussed here, website visited at least twice in > 5 minutes, etc.)

The Chrome menu item that we can trigger for any website, even if it does not have a service worker. This one simply creates a shortcut to the website on the home screen of the mobile device:

Question: How to add a button on a HTML page that triggers the creation of a home screen shortcut, like in the second bullet before? (i.e. for a very simple HTML website, without any service worker)

答: I believe that what you want to achieve is not yet possible. In order to be able to make a shortcut, a dedicated API would be needed for that. Until then, there is no API other than service workers that can achieve this.</p>


问:
How to filter a string list containing specific characters in python
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
</code>```

Does anybody have an idea of how to do that?

Thank you in advance!

答: You can filter your list using python filter() method.</p>

Body:
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]

Does anybody have an idea of how to do that?

Thank you in advance!


答:
Using document.getElementById('flowRate') is discouraged when you are using Angular, instead, you should template-driven forms or reactive-forms, which is the angular way of doing so.

I'll show the reactive-form example

First import the ReactiveFormsModule in your app.module.ts, so that FormControls work in your example.

<mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input [formControl]="flowRateControl" type="number" matInput>
</mat-form-field>
```
<p>In your <code>.ts</code> component</p>
<pre class="lang-js prettyprint-override"><code> flowRateControl: FormControl = new FormControl();

 ngOnInit(): void {
    this.flowRateControl.valueChanges.subscribe(val => {
            console.log(val);
       });
  }
</code>```

Also, the benefits of using this approach are that you can use multiple RxJs operators like debounce, distinctUntilChanged which can boost your user experience.

Title: How to subscribe to input for it to save changes into an object?

Body:
I have an input in a form of HTML like this:

 <mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input id = "flowRate" type="number" matInput>
  </mat-form-field>

To which I subscribe later in my .ts file like this:

private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement

 if (flowRateInput: any) {
  let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
      debounceTime(500)
    ).subscribe(res => {
      this.calcData.flowRate = +this.flowRateInput.value;
      console.log(this.flowRateInput.value)
      console.log(this.calcData)
    })
  }

However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.

Body:
Using document.getElementById('flowRate') is discouraged when you are using Angular, instead, you should template-driven forms or reactive-forms, which is the angular way of doing so.

I'll show the reactive-form example

First import the ReactiveFormsModule in your app.module.ts, so that FormControls work in your example.

<mat-form-field appearance="fill">
    <mat-label>Flowrate: </mat-label>
    <input [formControl]="flowRateControl" type="number" matInput>
</mat-form-field>

In your .ts component

 flowRateControl: FormControl = new FormControl();

 ngOnInit(): void {
    this.flowRateControl.valueChanges.subscribe(val => {
            console.log(val);
       });
  }

Also, the benefits of using this approach are that you can use multiple RxJs operators like debounce, distinctUntilChanged which can boost your user experience.


问:
How can I track down what's slowing down Visual Studio 2008?
I'm running a large C++ solution, and it's incredibly slow. By "slow", I mean that the output window is spitting out logs line...by...line... and if I hit an assert it can take almost a minute for the debugger to catch up and show my execution point. (The exe halts right away, but VS is still printing in the output window for ages).

The exe is running fine; not that slow at all. But the debugger is way behind.

I've deleted all breakpoints, closed all other windows (threads, watch, etc...), disabled intellisence, added a symbol cache, removed the symbol cache, and probably some other stuff. Google isn't any help (searching for "slow visual studio" and various other things turns up a lot, but nothing that helps).

A couple of coworkers are having the same problem, and we're stumped. Does anyone have any ideas for tracking down the bottleneck?

答:
Use the /log switch

http://blogs.msdn.com/b/saraford/archive/2008/11/27/did-you-know-there-s-a-way-to-have-visual-studio-log-its-activity-for-troubleshooting-366.aspx

http://blogs.msdn.com/b/visualstudio/archive/2010/02/24/troubleshooting-with-the-activity-log.aspx

Also, make sure that your symbol environment variable is not pointing to unreachable Url, Are machines connected to internet ?

http://blogs.msdn.com/b/mahuja/archive/2008/07/08/resolving-very-slow-symbol-loading-with-vs-2008-during-debugging.aspx


问:
Is memory_order_acquire on reference counted pointers to trivially destructible types superfluous?
This question is specifically about trivially destructible types within reference counted pointers. See the example from Boost's documentation on uses of atomics.

The decrement is as follows:

```<code>if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) {
  // A
  boost::atomic_thread_fence(boost::memory_order_acquire);
  delete x;
}
</code>```

We know that, due to memory_order_release, all reads/writes of x are completed before the fetch_sub (see here). Thus, if we happen to reach point A then all uses of x are complete.

At point A in the code, we are not guaranteed by the standard to see the latest value of x until after the memory_order_acquire fence...

So here is my question regarding the second statement about memory_order_acquire:

When x points to a trivially destructible type (for example, int where x is int * const) is the memory_order_acquire pointless? The rationale I have is because if x is trivially destructible then the latest changes to x does no affect the deletion of x?

For example, whether the deleting thread's delete x; sees the latest x such that *x = 10 or an outdated value such that *x = 8 the destruction process is always the same regardless (as long as the pointer x itself remains constant). It knows that no one is going to modify the x from that point thanks to the release and so all it has to do is deallocate.

Is there another benefit of memory_order_acquire that I am missing here?
Is my thinking correct and if not then why do we need to see the latest value of x on the deleting thread?

答:
The standard is not written in terms of which interleavings of operations in racing threads might happen. I gather such a specification would be too strict: compilers need to reorder loads and stores, even across sync points, for speed.

Instead, the standard simply says what a data race is, and that they're undefined behavior.

Informally, a data race occurs when:

one thread accesses memory;

another thread writes to the same memory location; and

there's no synchronization between the two threads to impose an
order on the two accesses.

Deleting an object counts as a write, even if the destructor is trivial. If two threads access *x and then decref it using your code, and one thread deletes x, we can see that all three requirements are fulfilled. There is a data race on *x.

The data race isn't on x->refcount_, since both threads access it with an atomic operation (an explicit exception, in the standard, to the sloppy definition of "data race" I gave above). But because the memory ordering is release on both threads, it doesn't synchronize the two threads.

People often try to imagine what compiler shenanigans might lead to actual misbehavior in practice, to see if the race might be considered "benign", but I've given up on this. According to the standard, the lack of a release-acquire handoff makes the behavior undefined.

Body:
This question is specifically about trivially destructible types within reference counted pointers. See the example from Boost's documentation on uses of atomics.

The decrement is as follows:

if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) {
  // A
  boost::atomic_thread_fence(boost::memory_order_acquire);
  delete x;
}

We know that, due to memory_order_release, all reads/writes of x are completed before the fetch_sub (see here). Thus, if we happen to reach point A then all uses of x are complete.

At point A in the code, we are not guaranteed by the standard to see the latest value of x until after the memory_order_acquire fence...

So here is my question regarding the second statement about memory_order_acquire:

When x points to a trivially destructible type (for example, int where x is int * const) is the memory_order_acquire pointless? The rationale I have is because if x is trivially destructible then the latest changes to x does no affect the deletion of x?

For example, whether the deleting thread's delete x; sees the latest x such that *x = 10 or an outdated value such that *x = 8 the destruction process is always the same regardless (as long as the pointer x itself remains constant). It knows that no one is going to modify the x from that point thanks to the release and so all it has to do is deallocate.

Is there another benefit of memory_order_acquire that I am missing here?
Is my thinking correct and if not then why do we need to see the latest value of x on the deleting thread?


问:
remove rows with conditions based on columns
I am trying to remove rows that belong to the same TRIAL group and Trait group with empty traitvalue

```<code>dt <- tibble(
TRIAL = c("M20-07RND1", "M20-07RND1", "M20-07RND1", " M20-07RND1", " M20-06RND5", " M20-06RND5", " M20-06RND5", " M20-06RND5", " V-01RND1", " V-01RND1", " V-01RND1", "V-01RND1"),
  PLOT= c(1, 2, 3, 1, 6, 3, 2, 3, 1,67,34,34),
  trait = c("ASI", "ASI", "AD", "AD", "ASI", "ASI", "FY", "FY", "FOR", "FOR", "CY", "CY"),
  trialValue = c(2, 7, 2, 2, NA,34 ,NA ,NA ,10 ,NA ,NA ,NA)
)

# # A tibble: 11 x 4
 #      TRIAL     PLOT  trait    trialValue
        <chr>     <dbl> <chr>      <dbl
  #1   M20-07RND1   1    ASI        2
  #2   M20-07RND1   2    ASI        7
  #3   M20-07RND1   3    AD         2
  #4   M20-07RND1   1    AD         2
  #5   M20-06RND5   6    ASI
  #6   M20-06RND5   3    ASI       34
  #7   M20-06RND5   2    FY
  #8   M20-06RND5   3    FY
  #9   V-01RND1     1    FOR       10
  #10  V-01RND1     67   FOR
  #11  v-01RND1     34   CY
  #12  v-01RND1     34   CY
</code>```

This is what I want to achieve: If a group of trait has an empty traitvalue and belong to the same TRIAL Group then remove the whole rows where the condition met.

```<code> # # A tibble: 11 x 4
 #      TRIAL     PLOT  trait     trialValue
        <chr>     <dbl> <chr>       <dbl
  #1   M20-07RND1   1    ASI         2
  #2   M20-07RND1   2    ASI         7
  #3   M20-07RND1   3    AD          2
  #4   M20-07RND1   1    AD          2
  #5   M20-06RND5   6    ASI
  #6   M20-06RND5   3    ASI        34
  #9   V-01RND1     1    FOR        10
  #10  V-01RND1     67   FOR
</code>```

I don’t know how to go about it, kindly help out.

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

dt %>%
  group_by(TRIAL, trait) %>%
  filter(sum(trialValue, na.rm = TRUE) != 0)

# A tibble: 8 x 4
# Groups:   TRIAL, trait [5]
  TRIAL          PLOT trait trialValue
  <chr>         <dbl> <chr>      <dbl>
1 "M20-07RND1"      1 ASI            2
2 "M20-07RND1"      2 ASI            7
3 "M20-07RND1"      3 AD             2
4 " M20-07RND1"     1 AD             2
5 " M20-06RND5"     6 ASI           NA
6 " M20-06RND5"     3 ASI           34
7 " V-01RND1"       1 FOR           10
8 " V-01RND1"      67 FOR           NA
</code>```

Body:
I am trying to remove rows that belong to the same TRIAL group and Trait group with empty traitvalue

dt <- tibble(
TRIAL = c("M20-07RND1", "M20-07RND1", "M20-07RND1", " M20-07RND1", " M20-06RND5", " M20-06RND5", " M20-06RND5", " M20-06RND5", " V-01RND1", " V-01RND1", " V-01RND1", "V-01RND1"),
  PLOT= c(1, 2, 3, 1, 6, 3, 2, 3, 1,67,34,34),
  trait = c("ASI", "ASI", "AD", "AD", "ASI", "ASI", "FY", "FY", "FOR", "FOR", "CY", "CY"),
  trialValue = c(2, 7, 2, 2, NA,34 ,NA ,NA ,10 ,NA ,NA ,NA)
)

# # A tibble: 11 x 4
 #      TRIAL     PLOT  trait    trialValue
        <chr>     <dbl> <chr>      <dbl
  #1   M20-07RND1   1    ASI        2
  #2   M20-07RND1   2    ASI        7
  #3   M20-07RND1   3    AD         2
  #4   M20-07RND1   1    AD         2
  #5   M20-06RND5   6    ASI
  #6   M20-06RND5   3    ASI       34
  #7   M20-06RND5   2    FY
  #8   M20-06RND5   3    FY
  #9   V-01RND1     1    FOR       10
  #10  V-01RND1     67   FOR
  #11  v-01RND1     34   CY
  #12  v-01RND1     34   CY

This is what I want to achieve: If a group of trait has an empty traitvalue and belong to the same TRIAL Group then remove the whole rows where the condition met.

 # # A tibble: 11 x 4
 #      TRIAL     PLOT  trait     trialValue
        <chr>     <dbl> <chr>       <dbl
  #1   M20-07RND1   1    ASI         2
  #2   M20-07RND1   2    ASI         7
  #3   M20-07RND1   3    AD          2
  #4   M20-07RND1   1    AD          2
  #5   M20-06RND5   6    ASI
  #6   M20-06RND5   3    ASI        34
  #9   V-01RND1     1    FOR        10
  #10  V-01RND1     67   FOR

I don’t know how to go about it, kindly help out.


问:
Bumblebee Android studio Plugin [id: 'com.android.application', version: '7.1.0', apply: false] was not found in any of the following sources:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

```<code>plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

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

答:
I have the same problem。
Here's how I did it:

```<code>//Comment the following code from settings.gradle:
/*pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}*/
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}
</code>```

Modify the buildScript node in build.gradle in the project root directory:

```<code>buildscript {
    ext {
        kotlin_version = '1.6.10'
        compose_version = '1.0.5'
    }
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.1.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

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

Body:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

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

Body:
I have the same problem。
Here's how I did it:

//Comment the following code from settings.gradle:
/*pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
    }
}*/
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

Modify the buildScript node in build.gradle in the project root directory:

buildscript {
    ext {
        kotlin_version = '1.6.10'
        compose_version = '1.0.5'
    }
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:7.1.1"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

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


问:
SQL query execution fails
I am trying to execute query and it doesnt work.

```<code>SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
AND idOperacije = 105
AND total > 2000
GROUP BY idOperacije
</code>```

Error I get is:

Unknown column 'total' in 'where clause' Even if I use sum(kolicina)
in where statement I get same issue.

I need to sum(kolicina) for idRadniNalog and idOperacije and display only items where sum is higer than 2000

答:
The where clause filters the rows used to execute the query. You're trying to get only the rows that have sum > 2000 so you need to use the HAVING clause after the GROUP BY one.
In this way you filter the first rows you impact in your query, you group them in groups of 'idOperacije' and verify the condition you need on those groups (the sum is not a column of your db i think so you can't use it as a condition for where).</p>

Title: SQL query execution fails

Body:
I am trying to execute query and it doesnt work.

SELECT id,
       idOperacije,
       idRadniNalog,
       sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9
AND idOperacije = 105
AND total > 2000
GROUP BY idOperacije

Error I get is:

Unknown column 'total' in 'where clause' Even if I use sum(kolicina)
in where statement I get same issue.

I need to sum(kolicina) for idRadniNalog and idOperacije and display only items where sum is higer than 2000


问:
docker nginx reverse proxy css and image rendering issue
I have a environment where I have 2 tomcat containers are exposed say dev and test on ports 8080 and 8081 respectively. I am able to access the tomcat instances with host and port combinations as below.

```<code>http://<ip>:8080
http://<ip>:8081
</code>```

Now I am trying to setup an nginx container as a proxy to send all /dev requests to dev(8080) container and all /test requests to test(8081) container.
Below is my docker-compose.yml

```<code>version: "3.5"
services:
  web1:
    image: "tomcat:latest"
    container_name: "web1"
    ports:
    - "8080:8080"
  web2:
    image: "tomcat:latest"
    container_name: "web2"
    ports:
    - "8081:8080"
  nginx:
    image: "nginx:latest"
    container_name: "nginx"
    ports:
    - "8000:80"
    volumes:
    - "./nginx.conf:/etc/nginx/nginx.conf"
    #- "./default.conf:/etc/nginx/conf.d/default.conf"
</code>```

Below is my nginx.conf file

```<code>user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;

        proxy_redirect           off;
        proxy_set_header         X-Real-IP $remote_addr;
        proxy_set_header         X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header         Host $http_host;
        proxy_set_header         Upgrade $http_upgrade;
        proxy_set_header         Connection "upgrade";
        proxy_set_header         X-Real-IP $remote_addr;
        proxy_set_header         X-Scheme $scheme;
        client_max_body_size     0;

        location / {
        }

        location /dev {
            proxy_pass http://35.239.73.252:8080/;
        }
        location /test {
            proxy_pass http://35.239.73.252:8081/;
        }
    }
}
</code>```

Now the problem is when i try to load my tomcat containers directly they work fine. But when they are accessed through nginx with uri paths /dev and /test the pages are broken and images and css are not loaded.

What could the issue and how to fix it.

答:
I believe you need a closing "/" after both your location path and your target. Here's a working example from a project of mine:</p>
```<code>    location ^~ /ll/ {
        proxy_pass http://werther:8080/;
    }
</code>```

Body:
I have a environment where I have 2 tomcat containers are exposed say dev and test on ports 8080 and 8081 respectively. I am able to access the tomcat instances with host and port combinations as below.

http://<ip>:8080
http://<ip>:8081

Now I am trying to setup an nginx container as a proxy to send all /dev requests to dev(8080) container and all /test requests to test(8081) container.
Below is my docker-compose.yml

version: "3.5"
services:
  web1:
    image: "tomcat:latest"
    container_name: "web1"
    ports:
    - "8080:8080"
  web2:
    image: "tomcat:latest"
    container_name: "web2"
    ports:
    - "8081:8080"
  nginx:
    image: "nginx:latest"
    container_name: "nginx"
    ports:
    - "8000:80"
    volumes:
    - "./nginx.conf:/etc/nginx/nginx.conf"
    #- "./default.conf:/etc/nginx/conf.d/default.conf"

Below is my nginx.conf file

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;

        proxy_redirect           off;
        proxy_set_header         X-Real-IP $remote_addr;
        proxy_set_header         X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header         Host $http_host;
        proxy_set_header         Upgrade $http_upgrade;
        proxy_set_header         Connection "upgrade";
        proxy_set_header         X-Real-IP $remote_addr;
        proxy_set_header         X-Scheme $scheme;
        client_max_body_size     0;

        location / {
        }

        location /dev {
            proxy_pass http://35.239.73.252:8080/;
        }
        location /test {
            proxy_pass http://35.239.73.252:8081/;
        }
    }
}

Now the problem is when i try to load my tomcat containers directly they work fine. But when they are accessed through nginx with uri paths /dev and /test the pages are broken and images and css are not loaded.

What could the issue and how to fix it.

Body:
I believe you need a closing "/" after both your location path and your target. Here's a working example from a project of mine:

    location ^~ /ll/ {
        proxy_pass http://werther:8080/;
    }


问:
How set expiration date to an localStoarge item in Javascript?
I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:

localStorage.setItem('ispremium', '1');
```

And my website is on Blogger platform, if that matters!

答:
Normally this would be solved on the server side. The localStorage may be cleared if a user selects "clear browsing history" on some browsers. It may not be available across sessions if the user works with multiple browsers or incognito mode. Other than that someone with a bit of technical knowledge can insert the "ispremium" flag easily into his localStorage to gain access to your premium feature.

If you still want to solve this via client, you could store a timestamp instead of a boolean flag and check if the current time is still in the validity range. LocalStorage itself doesn't let you set an expiration date on entries.

Body:
I am working on making premium access to my website. While doing so I want the login that had set the localStorage item as 1 to expire and get deleted after a month. I searched the web, but got confused as I am still learning JavaScript and jQuery. Can you help me out in setting expiration to the localStorage item? Here's the line of code that is setting the localStorage:

localStorage.setItem('ispremium', '1');

And my website is on Blogger platform, if that matters!


答:
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:</p>
```<code>const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
  initial: null,
  expiresOn: null
};
const TIMESTAMP = Date.now();

if (!JSON.parse(localStorage.getItem(NAMESPACE))) {
  // when the user access your website for the first time, set the initial and expiresOn values:

  localStorage.setItem(NAMESPACE, JSON.stringify({
    initial: TIMESTAMP,
    expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
  }));
} else {
    // then, when user access the website again, check the expiresOn, it it's value is bigger than current date
  const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;

  if (Date.now() > EXPIRE_DATE) {
    console.log('session expired');
  }
}
</code>```

Title: How set expiration date to an localStoarge item in Javascript?

Body:
You can set the actual value as the first time user joined and the time to expire. And whenever the user opens again the website, you need to check that expiration date. But this is extremely unsecure, you shouldn't do that for sessions. Just to answer to your question, you can do the following:

const NAMESPACE = 'MY_ID';
const TIMESTAMP_MODEL = {
  initial: null,
  expiresOn: null
};
const TIMESTAMP = Date.now();

if (!JSON.parse(localStorage.getItem(NAMESPACE))) {
  // when the user access your website for the first time, set the initial and expiresOn values:

  localStorage.setItem(NAMESPACE, JSON.stringify({
    initial: TIMESTAMP,
    expiresOn: TIMESTAMP + 1000*60*60*24*30 // 1month in ms
  }));
} else {
    // then, when user access the website again, check the expiresOn, it it's value is bigger than current date
  const EXPIRE_DATE = JSON.parse(localStorage.getItem(NAMESPACE)).expiresOn;

  if (Date.now() > EXPIRE_DATE) {
    console.log('session expired');
  }
}


问:
Can MOSS 2007 integrate with multiple LDAP/AD stores?
Can MOSS integrate and get user profiles from multiple Active Directory and/or LDAP stores?

I have seen from Integrating Microsoft SharePoint Server With Oracle Virtual Directory that there may be intermediary products that can help with this.

It looks like Rohati has a solution as well, but is the out of the box without third party products?

答:
One way would be to extend your website application and to attach different providers to different zones. I think there're should be something like LDAP Membership Provider you can use. But I guess that's not what you're looking for. </p>

<p>Another way would be to build your own Membership Provider which internally retrieves users, groups  from multiple sources. </p>

OwnerDisplayName: Kirk Liemohn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kirk Liemohn

Body:
One way would be to extend your website application and to attach different providers to different zones. I think there're should be something like LDAP Membership Provider you can use. But I guess that's not what you're looking for.

Another way would be to build your own Membership Provider which internally retrieves users, groups  from multiple sources.

OwnerDisplayName: Flo


答:
You can try complete

```<code>library(tidyverse)

table2 %>%
  count(Col1, Col2, Col3, name = "sum") %>%
  complete(distinct_all(table1), fill = list(sum=0))
# A tibble: 10 x 4
   Col1  Col2  Col3    sum
   <chr> <chr> <chr> <dbl>
 1 Al    F     C         1
 2 Al    P     <         0
 3 Al    UF    UC        1
 4 Cu    F     C         0
 5 Cu    P     <         0
 6 Cu    UF    UC        0
 7 Pb    F     C         1
 8 Pb    P     <         1
 9 Pb    UF    UC        1
10 Cu    F     <         1
</code>```

Or a full_join

```<code>table2 %>%
  count(Col1, Col2, Col3, name = "sum") %>%
  full_join(distinct_all(table1)) %>%
  mutate(sum=replace_na(sum, 0))
</code>```

Title: Count by group using dplyr, but also count 0s

Body:
I'm making a count table for 2 data frames. One looks like this:

table1 <- data.table("Col1" = c("Al", "Al", "Al", "Cu", "Cu", "Cu", "Pb", "Pb",
"Pb"), "Col2" = c("F", "UF", "P", "F", "UF", "P", "F", "UF", "P"), "Col3" = c("C",
"UC", "<", "C", "UC", "<", "C", "UC", "<"))

table2 <- data.table("Col1" = c("Al", "Al", "Cu", "Pb", "Pb", "Pb"), "Col2" = c("F",
"UF", "F", "F", "UF", "P"), "Col3" = c("C", "UC", "<", "C", "UC", "<"))

I'd create a count table for table1 and table2 like this:

table1 %>% group_by(Col1, Col2, Col3) %>% tally()

# A tibble: 9 x 4
# Groups:   Col1, Col2 [9]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    P     <         1
3 Al    UF    UC        1
4 Cu    F     C         1
5 Cu    P     <         1
6 Cu    UF    UC        1
7 Pb    F     C         1
8 Pb    P     <         1
9 Pb    UF    UC        1

table2 %>% group_by(Col1, Col2, Col3) %>% tally()
# A tibble: 6 x 4
# Groups:   Col1, Col2 [6]
  Col1  Col2  Col3      n
  <chr> <chr> <chr> <int>
1 Al    F     C         1
2 Al    UF    UC        1
3 Cu    F     <         1
4 Pb    F     C         1
5 Pb    P     <         1
6 Pb    UF    UC        1

But I'd like the count table for table2 to have the 0 counts with the combinations from table1, not remove them completely so it doesn't show the 0 counts. Is there a way I can do this with dplyr or a different package?

Thank you for your help!

Body:
You can try complete

library(tidyverse)

table2 %>%
  count(Col1, Col2, Col3, name = "sum") %>%
  complete(distinct_all(table1), fill = list(sum=0))
# A tibble: 10 x 4
   Col1  Col2  Col3    sum
   <chr> <chr> <chr> <dbl>
 1 Al    F     C         1
 2 Al    P     <         0
 3 Al    UF    UC        1
 4 Cu    F     C         0
 5 Cu    P     <         0
 6 Cu    UF    UC        0
 7 Pb    F     C         1
 8 Pb    P     <         1
 9 Pb    UF    UC        1
10 Cu    F     <         1

Or a full_join

table2 %>%
  count(Col1, Col2, Col3, name = "sum") %>%
  full_join(distinct_all(table1)) %>%
  mutate(sum=replace_na(sum, 0))


答:
You can't refer to an alias or an aggregate in the WHERE clause.  Move the restriction on the total to the HAVING clause.

SELECT idOperacije, SUM(kolicina) AS total
FROM artikli_presetorijum_zapisi
WHERE idRadniNalog = 9 AND idOperacije = 105
GROUP BY idOperacije
HAVING total > 2000;
```

Note that as we are aggregating by idOperacije only this column and aggregates of other columns belong in the SELECT clause.

Title: SQL query execution fails

Body:
You can't refer to an alias or an aggregate in the WHERE clause.  Move the restriction on the total to the HAVING clause.

SELECT idOperacije, SUM(kolicina) AS total
FROM artikli_presetorijum_zapisi
WHERE idRadniNalog = 9 AND idOperacije = 105
GROUP BY idOperacije
HAVING total > 2000;

Note that as we are aggregating by idOperacije only this column and aggregates of other columns belong in the SELECT clause.


答:
Use any:

library(dplyr)
dt %>%
  group_by(TRIAL, trait) %>%
  filter(any(!is.na(trialValue)))
```
<p>output</p>
<pre class="lang-r prettyprint-override"><code># A tibble: 8 x 4
# Groups:   TRIAL, trait [5]
  TRIAL          PLOT trait trialValue
  <chr>         <dbl> <chr>      <dbl>
1 "M20-07RND1"      1 ASI            2
2 "M20-07RND1"      2 ASI            7
3 "M20-07RND1"      3 AD             2
4 " M20-07RND1"     1 AD             2
5 " M20-06RND5"     6 ASI           NA
6 " M20-06RND5"     3 ASI           34
7 " V-01RND1"       1 FOR           10
8 " V-01RND1"      67 FOR           NA
</code>```

Title: remove rows with conditions based on columns

Body:
Use any:

library(dplyr)
dt %>%
  group_by(TRIAL, trait) %>%
  filter(any(!is.na(trialValue)))

output

# A tibble: 8 x 4
# Groups:   TRIAL, trait [5]
  TRIAL          PLOT trait trialValue
  <chr>         <dbl> <chr>      <dbl>
1 "M20-07RND1"      1 ASI            2
2 "M20-07RND1"      2 ASI            7
3 "M20-07RND1"      3 AD             2
4 " M20-07RND1"     1 AD             2
5 " M20-06RND5"     6 ASI           NA
6 " M20-06RND5"     3 ASI           34
7 " V-01RND1"       1 FOR           10
8 " V-01RND1"      67 FOR           NA


答:
Items in the WHERE clause are evaluated as each row is encountered, before the grouping is finished, and therefore you can't use items that need aggregate functions (like SUM()). Instead, put that condition in the HAVING clause:

```<code>SELECT id, idOperacije, idRadniNalog, sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9 and idOperacije = 105
GROUP BY idOperacije
HAVING sum(kolicina) > 2000
</code>```

It's also poor practice to include items in the SELECT clause that are not also either accounted for in the GROUP BY clause or aggregated with a function like SUM(). Specifically, the id, and idRadniNalog fields are non-deterministic here, and it might be possible to get different results each time you run the query. Most databases don't even allow this (MySql is kind of bad this way). You should include these in your GROUP BY clause even if the existing idOperacije field is enough to uniquely identify those values.

```<code>SELECT id, idOperacije, idRadniNalog, sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9 and idOperacije = 105
GROUP BY idOperacije, id, idRadniNalog
HAVING sum(kolicina) > 2000
</code>```

Title: SQL query execution fails

Body:
Items in the WHERE clause are evaluated as each row is encountered, before the grouping is finished, and therefore you can't use items that need aggregate functions (like SUM()). Instead, put that condition in the HAVING clause:

SELECT id, idOperacije, idRadniNalog, sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9 and idOperacije = 105
GROUP BY idOperacije
HAVING sum(kolicina) > 2000

It's also poor practice to include items in the SELECT clause that are not also either accounted for in the GROUP BY clause or aggregated with a function like SUM(). Specifically, the id, and idRadniNalog fields are non-deterministic here, and it might be possible to get different results each time you run the query. Most databases don't even allow this (MySql is kind of bad this way). You should include these in your GROUP BY clause even if the existing idOperacije field is enough to uniquely identify those values.

SELECT id, idOperacije, idRadniNalog, sum(kolicina) as total
FROM `artikli_presetorijum_zapisi`
WHERE idRadniNalog = 9 and idOperacije = 105
GROUP BY idOperacije, id, idRadniNalog
HAVING sum(kolicina) > 2000


问:
vue navigation submenu component
i am just learning vue 3. If the menu has a child, I want to start a different component, but I couldn't quite figure out how to do it.
I wanted to write as an example what I want to do. Thank you from now.

I'm having trouble describing myself, I hope you don't mind my explanation.

```<code><div class="navigation-group">
<div class="navigation-basic-item">Home</div>
<div class="navigation-basic-item">about</div>
<div class="navigation-collapsable-item">subtitle</div>
</div>
</code>```

LayoutDense.vue

```<code><template>
    <NavigationGroup :menu="menuItem"/>
</template>

<script>
import NavigationGroup from "./Navigation/NavigationGroup";

export default {
    name: "LayoutDense",
    components: {NavigationGroup},
    data() {
        return {
            menuItem: [
                {
                    name: 'home',
                    path: '/home',
                    Icon: 'home',
                },
                {
                    name: 'about',
                    path: '/about',
                    Icon: 'about'
                },
                {
                    name: 'subtitle',
                    path: '/subtitle',
                    Icon: 'subtitle',
                    children: [
                        {
                            name: 'sub 1',
                            path: 'sub1',
                        },
                        {
                            name: 'sub 2',
                            path: 'sub2',
                        }
                    ]
                },
            ]
        }
    }
}
</script>
</code>```

NavigationGroup.vue

```<code><template>
    <div class="navigation-group">
        <slot>
            <template v-for="(link,Index) in menu">
                <navigation-item v-if="link.children===0" :link="link"/>
                <template v-else v-for="(subLink, SubIndex) in link.children">
                    <navigation-collapsable :sub="subLink"/>
                </template>
            </template>
        </slot>
    </div>
</template>

<script>
import NavigationItem from "./NavigationItem";
import NavigationCollapsable from "./NavigationCollapsable";

export default {
    name: "NavigationGroup",
    components: {
        NavigationItem,
        NavigationCollapsable
    },
    props: {
        menu: {
            type: Object,
        }
    }
}
</script>
</code>```

答: Can we get your actual result or maybe some more information? You want to use another component for the children items? Or do you want just an iterable component to create your list passing your children as an argument?</p>

Title: vue navigation submenu component

Body:
i am just learning vue 3. If the menu has a child, I want to start a different component, but I couldn't quite figure out how to do it.
I wanted to write as an example what I want to do. Thank you from now.

I'm having trouble describing myself, I hope you don't mind my explanation.

Home

about

subtitle

LayoutDense.vue

<template>
    <NavigationGroup :menu="menuItem"/>
</template>

NavigationGroup.vue

<template>

        <slot>
            <template v-for="(link,Index) in menu">
                <navigation-item v-if="link.children===0" :link="link"/>
                <template v-else v-for="(subLink, SubIndex) in link.children">
                    <navigation-collapsable :sub="subLink"/>
                </template>
            </template>
        </slot>

</template>


答:
```<code>SELECT idOperacije, idRadniNalog, sum(kolicina) as total
    FROM `artikli_presetorijum_zapisi`
     group by idOperacije ,idRadniNalog
    HAVING SUM(kolicina)>2000
</code>```

You can use a HAVING clause to test the value of an aggregate function.
It doesn't even have to be the same aggregate used in the projection. You
can evaluate different functions over different columns (and combine them with logical expressions) as long as it makes sense to apply the aggregate over the specified group.  The same grouping will be used for all the aggregate expressions.

Title: SQL query execution fails

Body:
SELECT idOperacije, idRadniNalog, sum(kolicina) as total
    FROM `artikli_presetorijum_zapisi`
     group by idOperacije ,idRadniNalog
    HAVING SUM(kolicina)>2000

You can use a HAVING clause to test the value of an aggregate function.
It doesn't even have to be the same aggregate used in the projection. You
can evaluate different functions over different columns (and combine them with logical expressions) as long as it makes sense to apply the aggregate over the specified group.  The same grouping will be used for all the aggregate expressions.


问:
Are Scipy Optimize Bounds inclusive?
I am trying to minimize a complex objective function that has 2 decision variables

The variables have bounds as mentioned below:

0<= var1/var2 < Some_upper_bound

As per my understanding of bounds variable in the optimize.minimize() function, both upper and lower values are inclusive.

How do I create a bound such that one value is inclusive (0) and the other is exclusive (Some_upper_bound)?

Any help with this is much appreciated. Thanks in advance!

答: No tool will do what you want. For a reason: the feasible region is no longer compact and the optimization problem is no longer well defined. Also, most solvers actually use a feasibility tolerance, so their constraint effectively becomes: x <= a + feastol. This is done because computations suffer from limited floating point precision. See: https://yetanothermathprogrammingconsultant.blogspot.com/2017/03/strict-inequalities-in-optimization.html.

Title: Are Scipy Optimize Bounds inclusive?


问:
Terminating app due to uncaught exception 'NativeScript encountered a fatal error: ReferenceError: Can't find variable: NativeClass
```<code>While running the app on simulator or real iOS device, it gives below error.
Any help would be appreciated.
</code>```

Git hub link - https://github.com/AjiteshMDK/GeoLocation-Update/issues/1

答:
What that's telling you is that you have code, whether your own or a plugin, that has not been updated for NativeScript 7/8.  See this link.

If the code is within a plugin, then may have to see if a revised version exists, or contact the plugin owner.  I've had two cases recently where I had to migrate a plugin myself.

Body:
While running the app on simulator or real iOS device, it gives below error.
Any help would be appreciated.

Git hub link - https://github.com/AjiteshMDK/GeoLocation-Update/issues/1