问:
LLVM: access array parameter in a function
I am trying to write a compiler using LLVM C++ API, and I am trying to access array parameter in a function.

As far as I can tell from clang's IR generation, those two codes has different LLVM IR codes:

```<code>void foo(void) {
  int a[2];
  a[0] = 1;
  // %1 = getelementptr inbounds [2 x i32], [2 x i32]* %0, i32 0, i32 0
  // store i32 1, i32* %1
</code>```

```<code>void bar(int a[]) {
  a[0] = 1;
  // store i32* %0, i32** %3, align 8
  // %4 = load i32*, i32** %3, align 8
  // %5 = getelementptr inbounds i32, i32* %4, i64 0
  // store i32 1, i32* %5, align 4
</code>```

If passing an array as a parameter, I need to use builder.CreateStore() first, then use llvm::GetElementPtrInst::CreateInBounds() to get the pointer to the index.

However, when writing the compiler, I am using the visitor pattern and see codes like a[0] = 1 as assign expression. When visiting the tree node assign_expression, I need to determine whether the load is needed.

Is there a way to determine whether the array is a local defined variable or a parameter?

Update 1:
for example, in C, if a function is defined like this:

void test(int a[]) {
  a[0] = 1;
}
```

<p>the corresponding LLVM C++ code for <code>a[0] = 1</code> is like:</p>

<pre class="lang-cpp prettyprint-override"><code>for(auto arg = theFunction->arg_begin(); arg != theFunction->arg_end(); arg ++) {
  auto param = builder.CreateAlloca(llvm::Type::getInt32Ty(context)->getPointerTo());
  builder.CreateStore(arg, param);
}

// a[0] = 1
auto loaded_tmp = builder.CreateLoad(param);
auto value = llvm::GetElementPtrInst::CreateInBounds(tmp, {Const(0), Const(0)}, "", the_basic_block);
</code>```

However, when the array is defined local, the code auto loaded_tmp = builder.CreateLoad(param); is not needed. So my question is: how do I get to know if I need the CreateLoad?

Update 2:
The LLVM IR generated by clang for the following C code :

int h(int a[]) {
    a[0] = 1;
    a[1] = 2;
}
```

<p>is </p>

```define dso_local i32 @h(i32*) #0 {
  %2 = alloca i32, align 4
  %3 = alloca i32*, align 8
  store i32* %0, i32** %3, align 8
  %4 = load i32*, i32** %3, align 8
  %5 = getelementptr inbounds i32, i32* %4, i64 0
  store i32 1, i32* %5, align 4
  %6 = load i32*, i32** %3, align 8
  %7 = getelementptr inbounds i32, i32* %6, i64 1
  store i32 2, i32* %7, align 4
  %8 = load i32, i32* %2, align 4
  ret i32 %8
}
```

which has a load instruction before each store

答:
Is there a way to determine whether the array is a local defined variable or a parameter?

Method1:

Use isa<Argument> like this:

```<code>Analysis/BasicAliasAnalysis.cpp

 167   if (isa<Argument>(V))
 168     return true;
</code>```

Method2:

Use a combination of LLVMGetFirstParam LLVMGetLastParam and LLVMGetNextParam to find if a value is a parameter.

See:
https://github.com/llvm/llvm-project/blob/master/llvm/lib/IR/Core.cpp#L2456

Body:
I am trying to write a compiler using LLVM C++ API, and I am trying to access array parameter in a function.

As far as I can tell from clang's IR generation, those two codes has different LLVM IR codes:

void foo(void) {
  int a[2];
  a[0] = 1;
  // %1 = getelementptr inbounds [2 x i32], [2 x i32]* %0, i32 0, i32 0
  // store i32 1, i32* %1

void bar(int a[]) {
  a[0] = 1;
  // store i32* %0, i32** %3, align 8
  // %4 = load i32*, i32** %3, align 8
  // %5 = getelementptr inbounds i32, i32* %4, i64 0
  // store i32 1, i32* %5, align 4

If passing an array as a parameter, I need to use builder.CreateStore() first, then use llvm::GetElementPtrInst::CreateInBounds() to get the pointer to the index.

However, when writing the compiler, I am using the visitor pattern and see codes like a[0] = 1 as assign expression. When visiting the tree node assign_expression, I need to determine whether the load is needed.

Is there a way to determine whether the array is a local defined variable or a parameter?

Update 1:
for example, in C, if a function is defined like this:

void test(int a[]) {
  a[0] = 1;
}

the corresponding LLVM C++ code for a[0] = 1 is like:

for(auto arg = theFunction->arg_begin(); arg != theFunction->arg_end(); arg ++) {
  auto param = builder.CreateAlloca(llvm::Type::getInt32Ty(context)->getPointerTo());
  builder.CreateStore(arg, param);
}

// a[0] = 1
auto loaded_tmp = builder.CreateLoad(param);
auto value = llvm::GetElementPtrInst::CreateInBounds(tmp, {Const(0), Const(0)}, "", the_basic_block);

However, when the array is defined local, the code auto loaded_tmp = builder.CreateLoad(param); is not needed. So my question is: how do I get to know if I need the CreateLoad?

Update 2:
The LLVM IR generated by clang for the following C code :

int h(int a[]) {
    a[0] = 1;
    a[1] = 2;
}

is

define dso_local i32 @h(i32*) #0 {
  %2 = alloca i32, align 4
  %3 = alloca i32*, align 8
  store i32* %0, i32** %3, align 8
  %4 = load i32*, i32** %3, align 8
  %5 = getelementptr inbounds i32, i32* %4, i64 0
  store i32 1, i32* %5, align 4
  %6 = load i32*, i32** %3, align 8
  %7 = getelementptr inbounds i32, i32* %6, i64 1
  store i32 2, i32* %7, align 4
  %8 = load i32, i32* %2, align 4
  ret i32 %8
}

which has a load instruction before each store

Body:
Is there a way to determine whether the array is a local defined variable or a parameter?

Method1:

Use isa<Argument> like this:

Analysis/BasicAliasAnalysis.cpp

 167   if (isa<Argument>(V))
 168     return true;

Method2:

Use a combination of LLVMGetFirstParam LLVMGetLastParam and LLVMGetNextParam to find if a value is a parameter.

See:
https://github.com/llvm/llvm-project/blob/master/llvm/lib/IR/Core.cpp#L2456


来源: stackexchange

答:
Could you please try following.

```<code>awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  a[$1,$2]++
  next
}
{
  print a[$1,$2],$0
}
' Input_file Input_file
</code>```

Explanation: reading Input_file 2 times. Where first time I am creating an array named a with index of first and second field and counting their value on each occurrence too. On 2nd time file reading it printing count of the first 2 fields total and then printing while line.

One liner code:

```<code>awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1,$2]++;next} {print a[$1,$2],$0}' Input_file Input_file
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add new column with times same value was found in 2 columns

Body:
Add new column with value of how many times the values in columns 1 and 2 contends exactly same value.

input file

46849,39785,2,012,023,351912.29,2527104.70,174.31
46849,39785,2,012,028,351912.45,2527118.70,174.30
46849,39785,3,06,018,351912.12,2527119.51,174.33
46849,39785,3,06,020,351911.80,2527105.83,174.40
46849,39797,2,012,023,352062.45,2527118.50,173.99
46849,39797,2,012,028,352062.51,2527105.51,174.04
46849,39797,3,06,020,352063.29,2527116.71,174.13,
46849,39809,2,012,023,352211.63,2527104.81,173.74
46849,39809,2,012,028,352211.21,2527117.94,173.69
46849,39803,2,012,023,352211.63,2527104.81,173.74
46849,39803,2,012,028,352211.21,2527117.94,173.69
46849,39801,2,012,023,352211.63,2527104.81,173.74

Expected output file:

4,46849,39785,2,012,023,351912.29,2527104.70,174.31
4,46849,39785,2,012,028,351912.45,2527118.70,174.30
4,46849,39785,3,06,018,351912.12,2527119.51,174.33
4,46849,39785,3,06,020,351911.80,2527105.83,174.40
3,46849,39797,2,012,023,352062.45,2527118.50,173.99
3,46849,39797,2,012,028,352062.51,2527105.51,174.04
3,46849,39797,3,06,020,352063.29,2527116.71,174.13,
2,46849,39809,2,012,023,352211.63,2527104.81,173.74
2,46849,39809,2,012,028,352211.21,2527117.94,173.69
2,46849,39803,2,012,023,352211.63,2527104.81,173.74
1,46849,39803,2,012,028,352211.21,2527117.94,173.69
1,46849,39801,2,012,023,352211.63,2527104.81,173.74

attempt:

awk -F, '{x[$1 $2]++}END{ for(i in x) {print i,x[i]}}' file

4684939785 4
4684939797 3
4684939801 1
4684939803 2
4684939809 2

Body:
Could you please try following.

awk '
BEGIN{
  FS=OFS=","
}
FNR==NR{
  a[$1,$2]++
  next
}
{
  print a[$1,$2],$0
}
' Input_file Input_file

Explanation: reading Input_file 2 times. Where first time I am creating an array named a with index of first and second field and counting their value on each occurrence too. On 2nd time file reading it printing count of the first 2 fields total and then printing while line.

One liner code:

awk 'BEGIN{FS=OFS=","} FNR==NR{a[$1,$2]++;next} {print a[$1,$2],$0}' Input_file Input_file


问:
explain output in js
I am getting an issue in the below code:

let a = 13;

function printA() {
  let a = 19;
  console.log(this.a);
}
let obj = {
  a: 10,
  fun: function() {
    console.log(this.a);
  }
};
let obj2 = {
  a: 20
};
let x = obj.fun;
x();```

can anybody tell why it is printing undefined ?
It prints 13 when we remove let from let a = 13

答:
There is no a for your x to fetch, that is why you get undefined.

```<code>let obj = {
    a: 10,
    fun: function () {
        console.log(this.a);
    }
};

let x = obj.fun;
x();
</code>```

Your x is pointing to a function as obj.fun. But there is no obj.fun.x exist, so it will result undefined.

Try the following:

```<code>let obj = {
    a: 10,
    fun: function () {
        console.log(this.a);
    }
};

let x = obj;
x.fun();
</code>```

or

```<code>let obj = {
    fun: function () {
        this.a = 10;
        console.log(this.a);
    }
};

let x = obj.fun;
x();
</code>```

They both will result 10 as output.

These two example both have an x property under the x.

NOTE: By making a let a = 10 under the fun function will not give you result of this.a is because such declaration works like a private parameter declaration in C/JAVA etc.

Title: explain output in js

Body:
I am getting an issue in the below code:

let a = 13;

function printA() {
  let a = 19;
  console.log(this.a);
}
let obj = {
  a: 10,
  fun: function() {
    console.log(this.a);
  }
};
let obj2 = {
  a: 20
};
let x = obj.fun;
x();

can anybody tell why it is printing undefined ?
It prints 13 when we remove let from let a = 13

Body:
There is no a for your x to fetch, that is why you get undefined.

let obj = {
    a: 10,
    fun: function () {
        console.log(this.a);
    }
};

let x = obj.fun;
x();

Your x is pointing to a function as obj.fun. But there is no obj.fun.x exist, so it will result undefined.

Try the following:

let obj = {
    a: 10,
    fun: function () {
        console.log(this.a);
    }
};

let x = obj;
x.fun();

or

let obj = {
    fun: function () {
        this.a = 10;
        console.log(this.a);
    }
};

let x = obj.fun;
x();

They both will result 10 as output.

These two example both have an x property under the x.

NOTE: By making a let a = 10 under the fun function will not give you result of this.a is because such declaration works like a private parameter declaration in C/JAVA etc.


问:
Why index is not used when ordering?
I have this table structure:

```<code>CREATE TABLE users
(
uid bigint NOT NULL,
first_name character varying,
last_name character varying,
email character varying,
login_count integer,
CONSTRAINT users_pkey PRIMARY KEY (uid)
)
</code>```

with this index:

```<code>CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);
</code>```

The login_count column may consists of NULL values and i need to select all users ordered descending by login_count and need NULLs to be at the end.

Unfortunately this query:

```<code>SELECT * FROM users ORDER BY login_count DESC LIMIT 30;
</code>```

won't use the index, so NULLs are at the beggining, why?

答:
How an index is defined does not change the meaning of a query.  In order for the index to be used, the ordering of the index has to match the ordering of the query.

Having said that, it doesn't appear that MySQL supports nulls last.  Try:

```<code>SELECT  *
FROM    users
ORDER BY
        case when login_count is null then -1 else login_count end DESC
LIMIT 30;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why index is not used when ordering?

Body:
I have this table structure:

CREATE TABLE users
(
uid bigint NOT NULL,
first_name character varying,
last_name character varying,
email character varying,
login_count integer,
CONSTRAINT users_pkey PRIMARY KEY (uid)
)

with this index:

CREATE INDEX users__login_count
ON users
USING btree
(login_count DESC NULLS LAST);

The login_count column may consists of NULL values and i need to select all users ordered descending by login_count and need NULLs to be at the end.

Unfortunately this query:

SELECT * FROM users ORDER BY login_count DESC LIMIT 30;

won't use the index, so NULLs are at the beggining, why?

Body:
How an index is defined does not change the meaning of a query.  In order for the index to be used, the ordering of the index has to match the ordering of the query.

Having said that, it doesn't appear that MySQL supports nulls last.  Try:

SELECT  *
FROM    users
ORDER BY
        case when login_count is null then -1 else login_count end DESC
LIMIT 30;


问:
Excel double negative operator with logical operators
I've just learned about double operators and am wondering if you can add logical operators to increase the range looked at. For example if any cell in the range A1:A10 is less 10 AND any corresponding cell next to that particular cell in the range B1:B10 is greater than 5 then sum the values in the corresponding cell in the range C1:C10.
This is clearly not correct, but I would have thought it would have been written something like this.

```<code>=SUMPRODUCT(--(AND(A1:A10<10,B1:B10>5)),C1:C10)
</code>```

The normal -- function is:

```<code>=SUMPRODUCT(--(A1:A10<10),C1:C10)
</code>```

答:
If you multiply, you don't need the double-negative:

```<code>=SUMPRODUCT((A1:A10<10)*(B1:B10>5)*(C1:C10))
</code>```

for example:

Body:
I've just learned about double operators and am wondering if you can add logical operators to increase the range looked at. For example if any cell in the range A1:A10 is less 10 AND any corresponding cell next to that particular cell in the range B1:B10 is greater than 5 then sum the values in the corresponding cell in the range C1:C10.
This is clearly not correct, but I would have thought it would have been written something like this.

=SUMPRODUCT(--(AND(A1:A10<10,B1:B10>5)),C1:C10)

The normal -- function is:

=SUMPRODUCT(--(A1:A10<10),C1:C10)

Body:
If you multiply, you don't need the double-negative:

=SUMPRODUCT((A1:A10<10)*(B1:B10>5)*(C1:C10))

for example:


问:
How to dynamically set a imageView from a file?
I need to set a imageView dynamically. The image is at drawable. This code is ok:

```<code>Bitmap bm2 = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
img_pergunta.setImageBitmap(bm2);
</code>```

The problem is that I need to start from string, but this code doesn´t work:

```<code>File imgFile = new  File("/drawable/image1.png");
Bitmap bm2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
img_pergunta.setImageBitmap(bm2);
</code>```

How do I solve it?

答: You can get the id (which you use in decodeResource()) using context.getResources().getIdentifier() and a name like image4. </p>

Body:
I need to set a imageView dynamically. The image is at drawable. This code is ok:

Bitmap bm2 = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
img_pergunta.setImageBitmap(bm2);

The problem is that I need to start from string, but this code doesn´t work:

File imgFile = new  File("/drawable/image1.png");
Bitmap bm2 = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
img_pergunta.setImageBitmap(bm2);

How do I solve it?


问:
How does .Net runtime "understand" that structure still has a reference
The question is how .Net runtime understands that fields of a structure, that was placed onto memory using Marshal.StructureToPtr, must not be freed by GC.

Below the scenario.

I have the following structure:

```<code>[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public string s;
    public Stream stream;

    public SomeStruct(string s)
    {
        this.s = s;
        this.stream = new MemoryStream(0x100);
    }
}
</code>```

There is a method that instantiates the structure and drops it to memory:

```<code>static IntPtr GetStructRawData()
{
    IntPtr ptr = Marshal.AllocHGlobal(1024);
    Marshal.StructureToPtr(new SomeStruct("hi"), ptr, false);
    return ptr;
}
</code>```

Then I can make new structure from the raw memory:

```<code>IntPtr ptr = GetStructRawData();

GC.Collect();

SomeStruct struct2 = (SomeStruct)Marshal.PtrToStructure(ptr, typeof(SomeStruct));
</code>```

Aftet that struct2 really contains correct string ("hi"), and correct stream. So it seems that there are references to that string and to that stream of struct1. But what holds the references? How does the runtime understands that the string and the stream must not be collected?

答:
But what holds the references? How does the runtime understands that the string and the stream must not be collected?

The string here is a bit of a special case; it is actually an interned string (loaded via ldstr), so it is already rooted by the intern table.

The MemoryStream however... frankly, it isn't rooted. Your code is inherently broken and dangerous, and it could fail horribly at any time. The objects could be collected or moved (compaction) at any time, and that would leave broken references in the unmanaged memory, because the GC isn't looking at the unmanaged memory.

I believe your code is only "working" currently because the GC hasn't been aggressive with you. Also keep in mind: GC doesn't erase objects; if the GC just decided to consider the MemoryStream as collected, you might still be able to talk to it again without it complaining, if the memory still looks OK for a while. But this is just working for the wrong reasons.

Having references in unmanaged memory is a terrible terrible idea and will hurt you.

If you're going to use unmanaged memory, the where T : unmanaged constraint could be a life-saver for you. It prevents you getting into this scenario, but as a necessity restricts what you can do. Meaning: you can't have these fields.

Body:
The question is how .Net runtime understands that fields of a structure, that was placed onto memory using Marshal.StructureToPtr, must not be freed by GC.

Below the scenario.

I have the following structure:

[StructLayout(LayoutKind.Sequential)]
public struct SomeStruct
{
    public string s;
    public Stream stream;

    public SomeStruct(string s)
    {
        this.s = s;
        this.stream = new MemoryStream(0x100);
    }
}

There is a method that instantiates the structure and drops it to memory:

static IntPtr GetStructRawData()
{
    IntPtr ptr = Marshal.AllocHGlobal(1024);
    Marshal.StructureToPtr(new SomeStruct("hi"), ptr, false);
    return ptr;
}

Then I can make new structure from the raw memory:

IntPtr ptr = GetStructRawData();

GC.Collect();

SomeStruct struct2 = (SomeStruct)Marshal.PtrToStructure(ptr, typeof(SomeStruct));

Aftet that struct2 really contains correct string ("hi"), and correct stream. So it seems that there are references to that string and to that stream of struct1. But what holds the references? How does the runtime understands that the string and the stream must not be collected?


问:
Wordpress query adding 0=1 in wp_query and result dissappear
Wp query adding 0=1 in the query and results disappear, I am trying to adding multiple taxonomies in the query but it is producing 0=1. I am trying to fetch results from multiple taxonomies and in case of all I am passing a blank array to get all results</p>

```<code>$category = array('');
    $post_regions = array('');
    $post_tag = array('');
    $post_categories = array('');
    if($_POST['pageType'] !== "all"){
        $category = array (
                'taxonomy' => 'category',
                'field' => 'slug',
                'operator' => 'IN',
                'terms' => explode(',', $_POST['pageType'])
            );
    }

    if($_POST['regions'] !== "default"){
        $post_regions = array(
                'taxonomy' => 'post_regions',
                'field' => 'slug',
                'operator' => 'IN',
                'terms' => explode(',', $_POST['regions'])
            );
    }
    if($_POST['topics'] !== "All"){
        $post_tag = array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => explode(',', $_POST['topics']),
                'operator' =>'IN'
            );
    }

    $args = array(
    'post_type' => 'post',
    'orderby' => 'publish_date',
    'posts_per_page' => -1,
    'order' => 'DESC',
    'post_status'   => 'publish',
    'date_query' => array(
        'relation' => 'OR',
        $dates
    ),
    'tax_query' => array(
        'relation' => 'AND',
            $category,
            $post_regions,
            $post_tag,
            $post_categories,
        ),
);

$query = new WP_Query( $args );
</code>```

答:
There is a block of code who design this SQL return.

In the class class-wp-query.php at line 2106

```<code>if ( ! $this->is_singular ) {
            $this->parse_tax_query( $q );

            $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );

            $join  .= $clauses['join'];
            $where .= $clauses['where'];
        }
</code>```

this return 0=1.... for me

Body:
Wp query adding 0=1 in the query and results disappear, I am trying to adding multiple taxonomies in the query but it is producing 0=1. I am trying to fetch results from multiple taxonomies and in case of all I am passing a blank array to get all results

$category = array('');
    $post_regions = array('');
    $post_tag = array('');
    $post_categories = array('');
    if($_POST['pageType'] !== "all"){
        $category = array (
                'taxonomy' => 'category',
                'field' => 'slug',
                'operator' => 'IN',
                'terms' => explode(',', $_POST['pageType'])
            );
    }

    if($_POST['regions'] !== "default"){
        $post_regions = array(
                'taxonomy' => 'post_regions',
                'field' => 'slug',
                'operator' => 'IN',
                'terms' => explode(',', $_POST['regions'])
            );
    }
    if($_POST['topics'] !== "All"){
        $post_tag = array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => explode(',', $_POST['topics']),
                'operator' =>'IN'
            );
    }

    $args = array(
    'post_type' => 'post',
    'orderby' => 'publish_date',
    'posts_per_page' => -1,
    'order' => 'DESC',
    'post_status'   => 'publish',
    'date_query' => array(
        'relation' => 'OR',
        $dates
    ),
    'tax_query' => array(
        'relation' => 'AND',
            $category,
            $post_regions,
            $post_tag,
            $post_categories,
        ),
);

$query = new WP_Query( $args );

Body:
There is a block of code who design this SQL return.

In the class class-wp-query.php at line 2106

if ( ! $this->is_singular ) {
            $this->parse_tax_query( $q );

            $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );

            $join  .= $clauses['join'];
            $where .= $clauses['where'];
        }

this return 0=1.... for me


问:
$projection & $sum not working as expected in MongoDB aggregation
Here are all the details.

Note: I am mentioning only the required sample fields

Collection 1: orders

```<code>{
    "_id": ObjectId("5e3eb2846cfe9912ece77732"),
    "isApproved": NO,
    "orderCreatedforDate": ISODate("2020-02-15T18:30:00Z"),
    "vendorOrder": [
      {
        "_id": ObjectId("5e3cfb1f3f6d3816a4410d97"),
        "publicationName": "Times of India",
        "productCode": "TCE1",
        "tradeCopies": 40
      },
      {
        "_id": ObjectId("5e3cfb1f3f6d3816a4410d96"),
        "publicationName": "Economic Times",
        "productCode": "ECE1",
        "tradeCopies": 21
      }
    ],
    "frequency": "SA",
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),

}
</code>```

there are multiple documents in this collection but we require document for tomorrow's date i.e :"orderCreatedforDate" : ISODate("2020-02-14T18:30:00Z") and there can be other documents with different vendorId's or dealerId's

Collection 2: publications

```<code>{
    "_id": ObjectId("5e1efac668c3c811c83263cc"),
    "publicationName": "Times Of India",
    "productCode": "ECE1",
    "frequency": "SA",
    "city": "Chennai",
    "coverPrice": 4,

  },
  {
    "_id": ObjectId("5e1efac668c3c811c83263cc"),
    "publicationName": "Times Of India",
    "productCode": "TCE1",
    "frequency": "SA",
    "city": "Chennai",
    "coverPrice": 5.5,

}
</code>```

this is one of the sample document,there are other documents with different frequency like "MO","TU" etc... and with different cities.
I need documents for tomorrow i.e "SA" & city Chennai so that I can fetch (coverPrice + productCode + city)

Collection 3: margins

```<code>{
    "_id": ObjectId("5e4281e7fec2e01a4c60b406"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "productCode": "ECE1",
    "frequency": "SA",
    "discount": 0,

  },
  {
    "_id": ObjectId("5e4281e7fec2e01a4c60b406"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "productCode": "TCE1",
    "frequency": "SA",
    "discount": 26,

}
</code>```

The "discount" in margin collection is in %age [for e.g- "discount":26 is 26%].

Now discount is [productCode, vendorId & city] dependent if I have an order with a different  "vendorId":ObjectId("5e3d05ba964d0e06c4cc007b") the discount may be different for this vendor i need to keep this in consideration.

This is what I have been able to achieve so far with this query

```<code>db.orders.aggregate([
  {
    "$match": {
      "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
      "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
      "orderCreatedforDate": ISODate("2020-02-15T18:30:00Z"),

    }
  },
  {
    "$unwind": {
      "path": "$vendorOrder"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$vendorOrder"
    }
  },
  {
    $lookup: {
      from: "publications",
      let: {
        productCode: "$productCode"
      },
      pipeline: [
        {
          $match: {
            frequency: "SA",
            $expr: {
              $eq: [
                "$productCode",
                "$$productCode"
              ]
            }
          }
        }
      ],
      as: "publications"
    }
  },
  {
    "$unwind": "$publications"
  },
  {
    $lookup: {
      from: "margins",
      let: {
        productCode: "$productCode"
      },
      pipeline: [
        {
          $match: {
            frequency: "SA",
            $expr: {
              $eq: [
                "$productCode",
                "$$productCode"
              ]
            }
          }
        }
      ],
      as: "margins"
    }
  },
  {
    "$unwind": "$margins"
  },
  {
    "$group": {
      "_id": {
        "productCode": "$productCode",
        "date": "$orderCreatedforDate",
        "coverPrice": "$publications.coverPrice",
        "discount": "$margins.discount",
        "tradeCopies": "$tradeCopies",
        "dealerId": "$orders.dealerId"
      },
      "tradeCopies": {
        "$sum": "$tradeCopies"
      }
    }
  },
  {
    "$project": {
      "dealerId": "$vendorOrder.dealerId",
      "tradeCopies": 1,
      "billOfTheDay": {
        "$multiply": [
          "$tradeCopies",
          {
            "$subtract": [
              "$_id.coverPrice",
              {
                "$multiply": [
                  "$_id.coverPrice",
                  {
                    "$divide": [
                      "$_id.discount",
                      100
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      "totalBill": {
        "$sum": [
          "billOfTheDay"
        ]
      }
    }
  }
])
</code>```

The output of this query is:

```<code>{
    "_id": {
      "productCode": "ECE1",
      "coverPrice": 4,
      "discount": 0,
      "tradeCopies": 67
    },
    "tradeCopies": 67,
    "billOfTheDay": 268,
    "totalBill": 0
  },
  {
    "_id": {
      "productCode": "TCE1",
      "coverPrice": 4,
      "discount": 38,
      "tradeCopies": 30
    },
    "tradeCopies": 30,
    "billOfTheDay": 74.4,
    "totalBill": 0
}
</code>```

I have been able to get the bill of individual tradeCopies as it can be seen in my output TCE1's bill of the day:74.4 & ECE1's bill of the day:268.

I want their total i.e [ TCE1+ECE1 : 74.4,268], but this query doesn't seem to be good. Now I want to achieve the total amount of all the tradeCopies after their calculation with respect to their [productCode,coverPrice,discount(vendorId dependent)]
another problem is calculating outstanding :

Collection 4: payments

```<code>{

     "date" : ISODate("2020-02-15T18:30:00Z"),
     "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
     "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
     "receivables" : 120,
},
{

     "date" : ISODate("2020-02-13T18:30:00Z"),
     "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
     "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
     "receivables" : 110,
}
</code>```

I need to calculate the total receivables then need to calculate the outstanding.

This the output which is expected

```<code>invoice: {
    vendorId: ObjectId("5e3d05ba964d0e06c4bb0f07"),
    dealerId: ObjectId("5e1d82156a67173cb877f67d"),
    billOfTheDay:"342.4"
    recievables: "120"   //latest amount received for the day
    outstanding:"112.4   //"total receivable - bill of the day
}
</code>```

Moreover is it possible to save all this in a new collection for payment history reference, I want to save these fields into paymenthistory collection

```<code>{
    productCode,
    vendorId,
    dealerId,
    receivables,
    effectivePrice:(tradeCopies*(coverPrice-(coverPrice*discount%))),
    date,
    billOfTheDay,
    totalBillOfTheday
}
</code>```

If this can't be saved into a new collection atleast I am able to calculate outstanding

答:
I have been able to get the bill of individual tradeCopies as it can be seen in my output TCE1's bill of the day:74.4 & ECE1's bill of the day:268.  I want their total i.e [ TCE1+ECE1 : 74.4,268], but this query doesn't seem to be good.

You can achieve this by adding an extra $group stage to your pipeline.  If you group by null, the $group stage calculates accumulated values for all the input documents as a whole.

```<code>{
    $group: {
        _id: null,
        totalBill: {
            $sum: "$billOfTheDay"
        }
    }
}
</code>```

So now your pipeline will look like the following:

```<code>[{$unwind: {
  path: '$vendorOrder'
}}, {$replaceRoot: {
  newRoot: '$vendorOrder'
}}, {$lookup: {
  from: 'publications',
  'let': {
    productCode: '$productCode'
  },
  pipeline: [
    {
      $match: {
        frequency: 'SA',
        $expr: {
          $eq: [
            '$productCode',
            '$$productCode'
          ]
        }
      }
    }
  ],
  as: 'publications'
}}, {$unwind: '$publications'}, {$lookup: {
  from: 'margins',
  'let': {
    productCode: '$productCode'
  },
  pipeline: [
    {
      $match: {
        frequency: 'SA',
        $expr: {
          $eq: [
            '$productCode',
            '$$productCode'
          ]
        }
      }
    }
  ],
  as: 'margins'
}}, {$unwind: '$margins'}, {$group: {
  _id: {
    productCode: '$productCode',
    date: '$orderCreatedforDate',
    coverPrice: '$publications.coverPrice',
    discount: '$margins.discount',
    tradeCopies: '$tradeCopies',
    dealerId: '$orders.dealerId'
  },
  tradeCopies: {
    $sum: '$tradeCopies'
  }
}}, {$project: {
  dealerId: '$vendorOrder.dealerId',
  tradeCopies: 1,
  billOfTheDay: {
    $multiply: [
      '$tradeCopies',
      {
        $subtract: [
          '$_id.coverPrice',
          {
            $multiply: [
              '$_id.coverPrice',
              {
                $divide: [
                  '$_id.discount',
                  100
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  totalBill: {
    $sum: [
      'billOfTheDay'
    ]
  }
}}, {$group: {
  _id: null,
        totalBill: {
            $sum: "$billOfTheDay"
        }
}}]
</code>```

Moreover is it possible to save all this in a new collection for payment history reference, I want to save these fields into paymenthistory collection

Yes, you can use $out to take the results of the aggregation pipeline and save them to a collection. https://docs.mongodb.com/manual/reference/operator/aggregation/out/index.html

I didn't follow your other questions inside of your original question.  If you still have questions, please add more details and ask again.

Body:
Here are all the details.

Note: I am mentioning only the required sample fields

Collection 1: orders

{
    "_id": ObjectId("5e3eb2846cfe9912ece77732"),
    "isApproved": NO,
    "orderCreatedforDate": ISODate("2020-02-15T18:30:00Z"),
    "vendorOrder": [
      {
        "_id": ObjectId("5e3cfb1f3f6d3816a4410d97"),
        "publicationName": "Times of India",
        "productCode": "TCE1",
        "tradeCopies": 40
      },
      {
        "_id": ObjectId("5e3cfb1f3f6d3816a4410d96"),
        "publicationName": "Economic Times",
        "productCode": "ECE1",
        "tradeCopies": 21
      }
    ],
    "frequency": "SA",
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),

}

there are multiple documents in this collection but we require document for tomorrow's date i.e :"orderCreatedforDate" : ISODate("2020-02-14T18:30:00Z") and there can be other documents with different vendorId's or dealerId's

Collection 2: publications

{
    "_id": ObjectId("5e1efac668c3c811c83263cc"),
    "publicationName": "Times Of India",
    "productCode": "ECE1",
    "frequency": "SA",
    "city": "Chennai",
    "coverPrice": 4,

  },
  {
    "_id": ObjectId("5e1efac668c3c811c83263cc"),
    "publicationName": "Times Of India",
    "productCode": "TCE1",
    "frequency": "SA",
    "city": "Chennai",
    "coverPrice": 5.5,

}

this is one of the sample document,there are other documents with different frequency like "MO","TU" etc... and with different cities.
I need documents for tomorrow i.e "SA" & city Chennai so that I can fetch (coverPrice + productCode + city)

Collection 3: margins

{
    "_id": ObjectId("5e4281e7fec2e01a4c60b406"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "productCode": "ECE1",
    "frequency": "SA",
    "discount": 0,

  },
  {
    "_id": ObjectId("5e4281e7fec2e01a4c60b406"),
    "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
    "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "productCode": "TCE1",
    "frequency": "SA",
    "discount": 26,

}

The "discount" in margin collection is in %age [for e.g- "discount":26 is 26%].

Now discount is [productCode, vendorId & city] dependent if I have an order with a different  "vendorId":ObjectId("5e3d05ba964d0e06c4cc007b") the discount may be different for this vendor i need to keep this in consideration.

This is what I have been able to achieve so far with this query

db.orders.aggregate([
  {
    "$match": {
      "dealerId": ObjectId("5e1d82156a67173cb877f67d"),
      "vendorId": ObjectId("5e3d05ba964d0e06c4bb0f07"),
      "orderCreatedforDate": ISODate("2020-02-15T18:30:00Z"),

    }
  },
  {
    "$unwind": {
      "path": "$vendorOrder"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$vendorOrder"
    }
  },
  {
    $lookup: {
      from: "publications",
      let: {
        productCode: "$productCode"
      },
      pipeline: [
        {
          $match: {
            frequency: "SA",
            $expr: {
              $eq: [
                "$productCode",
                "$$productCode"
              ]
            }
          }
        }
      ],
      as: "publications"
    }
  },
  {
    "$unwind": "$publications"
  },
  {
    $lookup: {
      from: "margins",
      let: {
        productCode: "$productCode"
      },
      pipeline: [
        {
          $match: {
            frequency: "SA",
            $expr: {
              $eq: [
                "$productCode",
                "$$productCode"
              ]
            }
          }
        }
      ],
      as: "margins"
    }
  },
  {
    "$unwind": "$margins"
  },
  {
    "$group": {
      "_id": {
        "productCode": "$productCode",
        "date": "$orderCreatedforDate",
        "coverPrice": "$publications.coverPrice",
        "discount": "$margins.discount",
        "tradeCopies": "$tradeCopies",
        "dealerId": "$orders.dealerId"
      },
      "tradeCopies": {
        "$sum": "$tradeCopies"
      }
    }
  },
  {
    "$project": {
      "dealerId": "$vendorOrder.dealerId",
      "tradeCopies": 1,
      "billOfTheDay": {
        "$multiply": [
          "$tradeCopies",
          {
            "$subtract": [
              "$_id.coverPrice",
              {
                "$multiply": [
                  "$_id.coverPrice",
                  {
                    "$divide": [
                      "$_id.discount",
                      100
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      "totalBill": {
        "$sum": [
          "billOfTheDay"
        ]
      }
    }
  }
])

The output of this query is:

{
    "_id": {
      "productCode": "ECE1",
      "coverPrice": 4,
      "discount": 0,
      "tradeCopies": 67
    },
    "tradeCopies": 67,
    "billOfTheDay": 268,
    "totalBill": 0
  },
  {
    "_id": {
      "productCode": "TCE1",
      "coverPrice": 4,
      "discount": 38,
      "tradeCopies": 30
    },
    "tradeCopies": 30,
    "billOfTheDay": 74.4,
    "totalBill": 0
}

I have been able to get the bill of individual tradeCopies as it can be seen in my output TCE1's bill of the day:74.4 & ECE1's bill of the day:268.

I want their total i.e [ TCE1+ECE1 : 74.4,268], but this query doesn't seem to be good. Now I want to achieve the total amount of all the tradeCopies after their calculation with respect to their [productCode,coverPrice,discount(vendorId dependent)]
another problem is calculating outstanding :

Collection 4: payments

{

     "date" : ISODate("2020-02-15T18:30:00Z"),
     "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
     "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
     "receivables" : 120,
},
{

     "date" : ISODate("2020-02-13T18:30:00Z"),
     "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
     "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
     "receivables" : 110,
}

I need to calculate the total receivables then need to calculate the outstanding.

This the output which is expected

invoice: {
    vendorId: ObjectId("5e3d05ba964d0e06c4bb0f07"),
    dealerId: ObjectId("5e1d82156a67173cb877f67d"),
    billOfTheDay:"342.4"
    recievables: "120"   //latest amount received for the day
    outstanding:"112.4   //"total receivable - bill of the day
}

Moreover is it possible to save all this in a new collection for payment history reference, I want to save these fields into paymenthistory collection

{
    productCode,
    vendorId,
    dealerId,
    receivables,
    effectivePrice:(tradeCopies*(coverPrice-(coverPrice*discount%))),
    date,
    billOfTheDay,
    totalBillOfTheday
}

If this can't be saved into a new collection atleast I am able to calculate outstanding

Body:
I have been able to get the bill of individual tradeCopies as it can be seen in my output TCE1's bill of the day:74.4 & ECE1's bill of the day:268.  I want their total i.e [ TCE1+ECE1 : 74.4,268], but this query doesn't seem to be good.

You can achieve this by adding an extra $group stage to your pipeline.  If you group by null, the $group stage calculates accumulated values for all the input documents as a whole.

{
    $group: {
        _id: null,
        totalBill: {
            $sum: "$billOfTheDay"
        }
    }
}

So now your pipeline will look like the following:

[{$unwind: {
  path: '$vendorOrder'
}}, {$replaceRoot: {
  newRoot: '$vendorOrder'
}}, {$lookup: {
  from: 'publications',
  'let': {
    productCode: '$productCode'
  },
  pipeline: [
    {
      $match: {
        frequency: 'SA',
        $expr: {
          $eq: [
            '$productCode',
            '$$productCode'
          ]
        }
      }
    }
  ],
  as: 'publications'
}}, {$unwind: '$publications'}, {$lookup: {
  from: 'margins',
  'let': {
    productCode: '$productCode'
  },
  pipeline: [
    {
      $match: {
        frequency: 'SA',
        $expr: {
          $eq: [
            '$productCode',
            '$$productCode'
          ]
        }
      }
    }
  ],
  as: 'margins'
}}, {$unwind: '$margins'}, {$group: {
  _id: {
    productCode: '$productCode',
    date: '$orderCreatedforDate',
    coverPrice: '$publications.coverPrice',
    discount: '$margins.discount',
    tradeCopies: '$tradeCopies',
    dealerId: '$orders.dealerId'
  },
  tradeCopies: {
    $sum: '$tradeCopies'
  }
}}, {$project: {
  dealerId: '$vendorOrder.dealerId',
  tradeCopies: 1,
  billOfTheDay: {
    $multiply: [
      '$tradeCopies',
      {
        $subtract: [
          '$_id.coverPrice',
          {
            $multiply: [
              '$_id.coverPrice',
              {
                $divide: [
                  '$_id.discount',
                  100
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  totalBill: {
    $sum: [
      'billOfTheDay'
    ]
  }
}}, {$group: {
  _id: null,
        totalBill: {
            $sum: "$billOfTheDay"
        }
}}]

Moreover is it possible to save all this in a new collection for payment history reference, I want to save these fields into paymenthistory collection

Yes, you can use $out to take the results of the aggregation pipeline and save them to a collection. https://docs.mongodb.com/manual/reference/operator/aggregation/out/index.html

I didn't follow your other questions inside of your original question.  If you still have questions, please add more details and ask again.


问:
In my htaccess RewriteRule is not working
I just need to navigate to the subfolder.

```<code><IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^admin.mydomain.com [NC,OR]
    RewriteCond %{HTTP_HOST} ^www.admin.mydomain.com [NC]
    RewriteRule ^$ admin/App/ [L]
    RewriteRule (.*) admin/App/$1 [L,NC]
</IfModule>
</code>```

Can anyone help to show what's wrong in my .htaccess file.

答:
It seems you your apache has some issue.

Try this steps

1) cd etc/apache2/

2) sudo vi apache2.conf

Then edit the file and save

```<code><Directory /var/www/>
     Options Indexes FollowSymLinks MultiViews
     AllowOverride All    <------------ Set All
     Order allow,deny
     allow from all
</Directory>
</code>```

To save the file :wq

4) sudo systemctl restart apache2

Body:
I just need to navigate to the subfolder.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^admin.mydomain.com [NC,OR]
    RewriteCond %{HTTP_HOST} ^www.admin.mydomain.com [NC]
    RewriteRule ^$ admin/App/ [L]
    RewriteRule (.*) admin/App/$1 [L,NC]
</IfModule>

Can anyone help to show what's wrong in my .htaccess file.

Body:
It seems you your apache has some issue.

Try this steps

1) cd etc/apache2/

2) sudo vi apache2.conf

Then edit the file and save

<Directory /var/www/>
     Options Indexes FollowSymLinks MultiViews
     AllowOverride All    <------------ Set All
     Order allow,deny
     allow from all
</Directory>

To save the file :wq

4) sudo systemctl restart apache2


问:
Named export / unnamed export
I currently follow this tutorial here which uses:

```<code>import { AUTH_TOKEN } from '../constants'
</code>```

While I followed the tutorial step-by-step I have to use

```<code>import AUTH_TOKEN from '../constants'
</code>```

My constants.js looks like this:

```<code>export const AUTH_TOKEN = "auth-token";
</code>```

I struggle to understand why my React.js app behaves the opposite.

答:
```<code>import { AUTH_TOKEN } from '../constants'
export const AUTH_TOKEN = "auth-token";
</code>```

this means that there are more than one to export..
but if you changed the code like this:

```<code>export default const AUTH_TOKEN = "auth-token";
</code>```

so you can make your import like this:

```<code>import AUTH_TOKEN from '../constants'
</code>```

Title: Named export / unnamed export

Body:
I currently follow this tutorial here which uses:

import { AUTH_TOKEN } from '../constants'

While I followed the tutorial step-by-step I have to use

import AUTH_TOKEN from '../constants'

My constants.js looks like this:

export const AUTH_TOKEN = "auth-token";

I struggle to understand why my React.js app behaves the opposite.

Body:
import { AUTH_TOKEN } from '../constants'
export const AUTH_TOKEN = "auth-token";

this means that there are more than one to export..
but if you changed the code like this:

export default const AUTH_TOKEN = "auth-token";

so you can make your import like this:

import AUTH_TOKEN from '../constants'


问:
How to create a path to another module in cucumber java?
I have a question about cucumber, I'm integrating cucumber into an existing java project.
In the past many modules are defined in the project.
The steps are defined in the "testApi" module. The test classes and the feature file are defined in the "integrationTest" module.

example:

```<code>->project
  ->testApi
    ->src
      ->test
        ->java
          ->com
            ->apiXyz
              myTestSteps.java
  ->integrationTest
    ->src
      ->test
        ->java
          ->com
            ->cucumber
              myTestClass.java
      ->resources
        ->cucumber
           myTest.feature
</code>```

How do I specify the path to the step definition (myTestSteps.java) in myTestClass.java?
With "glue" I can only specify steps in the same src path.

答:
Hey You can Integrate Your Test Cases Module Wise:

```<code><modelVersion>4.0.0</modelVersion>
<groupId>com.xxx.awsam</groupId>
<artifactId>AW-END-TO-END-TESTS</artifactId>
<version>1.0.0.1034-SNAPSHOT</version>
<packaging>pom</packaging>
<name>AW-END-TO_END_TESTS</name>
<modules>
    <module>Module1</module>
    <module>Module1</module>
</modules>
</code>```

For Runner Class:

```<code>     features = "classpath:cucumber/myTest.feature",
     glue = {"YourStepDefPackage:com.apiXyz"}
</code>```

Body:
I have a question about cucumber, I'm integrating cucumber into an existing java project.
In the past many modules are defined in the project.
The steps are defined in the "testApi" module. The test classes and the feature file are defined in the "integrationTest" module.

example:

->project
  ->testApi
    ->src
      ->test
        ->java
          ->com
            ->apiXyz
              myTestSteps.java
  ->integrationTest
    ->src
      ->test
        ->java
          ->com
            ->cucumber
              myTestClass.java
      ->resources
        ->cucumber
           myTest.feature

How do I specify the path to the step definition (myTestSteps.java) in myTestClass.java?
With "glue" I can only specify steps in the same src path.

Body:
Hey You can Integrate Your Test Cases Module Wise:

<modelVersion>4.0.0</modelVersion>
<groupId>com.xxx.awsam</groupId>
<artifactId>AW-END-TO-END-TESTS</artifactId>
<version>1.0.0.1034-SNAPSHOT</version>
<packaging>pom</packaging>
<name>AW-END-TO_END_TESTS</name>
<modules>
    <module>Module1</module>
    <module>Module1</module>
</modules>

For Runner Class:

     features = "classpath:cucumber/myTest.feature",
     glue = {"YourStepDefPackage:com.apiXyz"}


问:
wkhtmltopdf is not executable from wicked-pdf within war
I am trying to create a pdf using wicked-pdf from Ruby On Rails. It works great in development mode, but when I deploy in production I get the error:

```<code>wkhtmltopdf is not executable
</code>```

I have the wkhtmltopdf executable located at:

```<code>rails_root/bin/wkhtmltopdf-i386
</code>```

Warbler is setup to include the bin folder in the war:

```<code>config.includes = FileList["classes/*","bin/*"]
</code>```

I have wicked pdf configured to find the bin in the correct spot:

```<code>WickedPdf.config = {
  :exe_path => Rails.root.join('bin', 'wkhtmltopdf-i386').to_s
}
</code>```

I run warbler and then deploy the war on jBoss application server. When I try to generate a PDF I get the error about it not being executable. It runs fine in development mode - not in a war.

The permissions on the binary should be fine:

```<code>-rwxr-xr-x  1 username group 11446024 Apr  3 11:40 wkhtmltopdf-i386
</code>```

Instead of manually including the wkhtmltopdf binary, I tried using wkhtmltopdf-binary gem. This too worked fine in development mode, but Wicked PDF can't find the binary in production.

Update: I changed the wicked-pdf config to point to the binary provided by 'wkhtmltopdf-binary' gem when in production mode. It also is getting wkhtmltopdf is not executable error. The path ends up being: jboss-5.1.0.GA/server/default/tmp/3j001-3g0fg5-hf2xi49o-1-hf2xiuld-9q/myrailsapp.war/WEB-INF/gems/gems/wkhtmltopdf-binary-0.9.9.1/bin/wkhtmltopdf_linux_386

答:
I faced this same issue when working with a Rails 5.2.3 application on an Ubuntu 18.04.

The error displayed is this:

Gem::Exception: can't find executable wkhtmltopdf for gem wkhtmltopdf-binary. wkhtmltopdf-binary is not currently included in the bundle, perhaps you meant to add it to your Gemfile?

Here's how I solved it:

I simply added the wkhtmltopdf-binary gem to the production group which already had the wkhtmltopdf-heroku in the Gemfile.

```<code>group :production do
 gem 'wkhtmltopdf-heroku'
 gem 'wkhtmltopdf-binary'
end
</code>```

And then installed the gem

```<code>bundle install --without development test
</code>```

If you're running on a production server, please endeavour to install the libxrender1 library, since it's a dependency for wkhtmltopdf (for rendering PDFs), to avoid en error when rendering PDFs.

```<code>sudo apt-get install libxrender1
</code>```

That's all.

I hope this helps

Body:
I am trying to create a pdf using wicked-pdf from Ruby On Rails. It works great in development mode, but when I deploy in production I get the error:

wkhtmltopdf is not executable

I have the wkhtmltopdf executable located at:

rails_root/bin/wkhtmltopdf-i386

Warbler is setup to include the bin folder in the war:

config.includes = FileList["classes/*","bin/*"]

I have wicked pdf configured to find the bin in the correct spot:

WickedPdf.config = {
  :exe_path => Rails.root.join('bin', 'wkhtmltopdf-i386').to_s
}

I run warbler and then deploy the war on jBoss application server. When I try to generate a PDF I get the error about it not being executable. It runs fine in development mode - not in a war.

The permissions on the binary should be fine:

-rwxr-xr-x  1 username group 11446024 Apr  3 11:40 wkhtmltopdf-i386

Instead of manually including the wkhtmltopdf binary, I tried using wkhtmltopdf-binary gem. This too worked fine in development mode, but Wicked PDF can't find the binary in production.

Update: I changed the wicked-pdf config to point to the binary provided by 'wkhtmltopdf-binary' gem when in production mode. It also is getting wkhtmltopdf is not executable error. The path ends up being: jboss-5.1.0.GA/server/default/tmp/3j001-3g0fg5-hf2xi49o-1-hf2xiuld-9q/myrailsapp.war/WEB-INF/gems/gems/wkhtmltopdf-binary-0.9.9.1/bin/wkhtmltopdf_linux_386

Body:
I faced this same issue when working with a Rails 5.2.3 application on an Ubuntu 18.04.

The error displayed is this:

Gem::Exception: can't find executable wkhtmltopdf for gem wkhtmltopdf-binary. wkhtmltopdf-binary is not currently included in the bundle, perhaps you meant to add it to your Gemfile?

Here's how I solved it:

I simply added the wkhtmltopdf-binary gem to the production group which already had the wkhtmltopdf-heroku in the Gemfile.

group :production do
 gem 'wkhtmltopdf-heroku'
 gem 'wkhtmltopdf-binary'
end

And then installed the gem

bundle install --without development test

If you're running on a production server, please endeavour to install the libxrender1 library, since it's a dependency for wkhtmltopdf (for rendering PDFs), to avoid en error when rendering PDFs.

sudo apt-get install libxrender1

That's all.

I hope this helps


问:
how to change a button background and enable it after other buttons are pressed
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

```<code>int one = 0;
int two = 0;
int three = 0;
int four = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_price_estimate_question_one);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}
</code>```

Quesions

答:
The simplest implementation that comes to my mind is to check all of the int values you defined. You can do it in a helper method together with background and color changes

```<code>private void helperMethodName (Button buttonNo, Button buttonYes){
    buttonNo.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
    buttonNo.setBackground(getDrawable(R.drawable.button_background));
    buttonYes.setTextColor(getApplication().getResources().getColor(R.color.black));
    buttonYes.setBackground(getDrawable(R.drawable.inactive_button_background));

    if (one != 0 && two != 0 && three != 0 && fore != 0) {
        nextstep.setEnabled(true);
    }
}
</code>```

And then just call this method in your on clicks

```<code>public void onClick(View v) {
one = 1;
helperMethodName(ques_one_no, ques_one_yes);
}
</code>```

Body:
How do I enable the "Next" button after 'Yes' or 'No' from each question is pressed? I want to make my "Next" button active (change the background and enable) only after all the questions have been answered. I don't know whether I should use loop or if it's possible by if-else. Any help is very appreciated.

I have developed my program in a way that users can either press the 'yes' or 'no' button and after answering all questions the "Next" button should get activated (change the background and enable).

int one = 0;
int two = 0;
int three = 0;
int four = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_price_estimate_question_one);

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String phone_price = extras.getString("phone_price");
        final String numonly = phone_price.replaceAll("[^0-9]", "");

        final int phoneprice = Integer.parseInt(numonly);

        final Button ques_one_yes = (Button)findViewById(R.id.ques_one_yes);
        final Button ques_one_no = (Button)findViewById(R.id.ques_one_no);
        final Button ques_two_yes = (Button)findViewById(R.id.ques_two_yes);
        final Button ques_two_no = (Button)findViewById(R.id.ques_two_no);
        final Button ques_three_yes = (Button)findViewById(R.id.ques_three_yes);
        final Button ques_three_no = (Button)findViewById(R.id.ques_three_no);
        final Button ques_four_yes = (Button)findViewById(R.id.ques_four_yes);
        final Button ques_four_no = (Button)findViewById(R.id.ques_four_no);
        final Button nextstep = (Button)findViewById(R.id.next_step);

        ques_one_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_one_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                one = 1;
                ques_one_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_one_no.setBackground(getDrawable(R.drawable.button_background));
                ques_one_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_one_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_no.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

        ques_two_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                two = 1;
                ques_two_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_two_no.setBackground(getDrawable(R.drawable.button_background));
                ques_two_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_two_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_three_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                three = 1;
                ques_three_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_three_no.setBackground(getDrawable(R.drawable.button_background));
                ques_three_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_three_yes.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_yes.setBackground(getDrawable(R.drawable.button_background));
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_no.setBackground(getDrawable(R.drawable.inactive_button_background));
            }
        });

        ques_four_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                four = 1;
                ques_four_no.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
                ques_four_no.setBackground(getDrawable(R.drawable.button_background));
                ques_four_yes.setTextColor(getApplication().getResources().getColor(R.color.black));
                ques_four_yes.setBackground(getDrawable(R.drawable.inactive_button_background));

            }
        });

    }
}

Quesions

Body:
The simplest implementation that comes to my mind is to check all of the int values you defined. You can do it in a helper method together with background and color changes

private void helperMethodName (Button buttonNo, Button buttonYes){
    buttonNo.setTextColor(getApplication().getResources().getColor(R.color.colorAccent));
    buttonNo.setBackground(getDrawable(R.drawable.button_background));
    buttonYes.setTextColor(getApplication().getResources().getColor(R.color.black));
    buttonYes.setBackground(getDrawable(R.drawable.inactive_button_background));

    if (one != 0 && two != 0 && three != 0 && fore != 0) {
        nextstep.setEnabled(true);
    }
}

And then just call this method in your on clicks

public void onClick(View v) {
one = 1;
helperMethodName(ques_one_no, ques_one_yes);
}


问:
NuGet has problems with missing packages, how to restore?
When I try to compile my program I get the following error:

```<code>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567.
</code>```

Now when I right click on the solution and press

```<code>All packages are already installed and there is nothing to restore.
</code>```

I tried manually reinstalling every package which didn't solve the problem, I tried reinstalling NuGet but that didn't help either and I even tried reinstalling visual studio.

I also tried moving the package folder from the tfs folder to overwrite my package folder but that didn't solve anything.  I also tried redownloading them with this package missing, that didn' t solve the problem either.

Anybody know how to restore the nuget packages?

答:
I ran into this issue when I tried to build my project on a computer where the packages-folder did not already exist in the solution root.

When the project file was initially created, it seems VS2019 added the following into the project file:

```<code><Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
</code>```

From what I understand those settings are deprecated nowadays, no idea why VS inserted it in the first place.

Anyway, after removing those lines VS restored the packages and built the solution correctly again.

Body:
When I try to compile my program I get the following error:

This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567.

Now when I right click on the solution and press

All packages are already installed and there is nothing to restore.

I tried manually reinstalling every package which didn't solve the problem, I tried reinstalling NuGet but that didn't help either and I even tried reinstalling visual studio.

I also tried moving the package folder from the tfs folder to overwrite my package folder but that didn't solve anything.  I also tried redownloading them with this package missing, that didn' t solve the problem either.

Anybody know how to restore the nuget packages?

Body:
I ran into this issue when I tried to build my project on a computer where the packages-folder did not already exist in the solution root.

When the project file was initially created, it seems VS2019 added the following into the project file:

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>

From what I understand those settings are deprecated nowadays, no idea why VS inserted it in the first place.

Anyway, after removing those lines VS restored the packages and built the solution correctly again.


答:
You can use the Sumifs, it put many criterias you want to sum a column.</p>

```<code> =Sumifs(C1:C10;B1:B10;">5";A1:A10;"<10")
</code>```

Title: Excel double negative operator with logical operators

Body:
I've just learned about double operators and am wondering if you can add logical operators to increase the range looked at. For example if any cell in the range A1:A10 is less 10 AND any corresponding cell next to that particular cell in the range B1:B10 is greater than 5 then sum the values in the corresponding cell in the range C1:C10.
This is clearly not correct, but I would have thought it would have been written something like this.

=SUMPRODUCT(--(AND(A1:A10<10,B1:B10>5)),C1:C10)

The normal -- function is:

=SUMPRODUCT(--(A1:A10<10),C1:C10)

Body:
You can use the Sumifs, it put many criterias you want to sum a column.

 =Sumifs(C1:C10;B1:B10;">5";A1:A10;"<10")


问:
How to obtain text of a  element from another  element with jquery
I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.

My html looks like this:

```<code>  <table>
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td><button>Get First Name</button></td>
    </tr>
  </table>
</code>```

And my Javascript is this:

```<code>$(document).ready(function(){
    $("button").click(function(){
      var first = $(this).closest("tr").childNodes[0].text();
      alert(first)
        })
    });
</code>```

答:
you could find the :first child and get his html(), as below:

$(document).ready(function() {
  $("button").click(function() {
    var first = $(this).closest("tr").children(":first").html();
    alert(first)
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td><button>Get First Name</button></td>
  </tr>
</table></code>```

Title: How to obtain text of a <td> element from another <td> element with jquery

Body:
I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.

My html looks like this:

      John
      Doe
      <button>Get First Name</button>

And my Javascript is this:

$(document).ready(function(){
    $("button").click(function(){
      var first = $(this).closest("tr").childNodes[0].text();
      alert(first)
        })
    });

Body:
you could find the :first child and get his html(), as below:

$(document).ready(function() {
  $("button").click(function() {
    var first = $(this).closest("tr").children(":first").html();
    alert(first)
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td><button>Get First Name</button></td>
  </tr>
</table>


问:
Prometheus job "kubernetes-nodes" endpoints in state "UNKNOWN"
We are facing one issue, that some endpoints are in state "UNKNOWN". Prometheus job "kubernetes-nodes".

Nodes and Prometheus are all up for several days. We tried to curl those "kubernetes-nodes" endpoints, which are in "UNKNOWN" state. Metrics can be correctly curled, but endpoint state is still "UNKNOWN". We don't know the reason (criteria, on which case it will be marked as "UNKNOWN").

I know before Prometheus does its first scrape, endpoints are in "UNKNOWN" state. Then, if scrape successes, endpoint will be "UP", if fails, "DOWN". However, in below screenshot it seems some endpoints are never been scraped...We just don't know why.

Could you please give advice, about the possible reason of such case?
Does this mean this node (name hide in red block...) has something wrong? If so, is it possible to fix, that will let Prometheus treat it as "UP"?

Thanks in advance.

```<code>- job_name: kubernetes-nodes
  scrape_interval: 1m
  scrape_timeout: 10s
  metrics_path: /metrics
  scheme: https
  kubernetes_sd_configs:
  - api_server: null
    role: node
    namespaces:
      names: []
  bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
  tls_config:
    ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    insecure_skip_verify: true
  relabel_configs:
  - separator: ;
    regex: __meta_kubernetes_node_label_(.+)
    replacement: $1
    action: labelmap
  - separator: ;
    regex: (.*)
    target_label: __address__
    replacement: kubernetes.default.svc:443
    action: replace
  - source_labels: [__meta_kubernetes_node_name]
    separator: ;
    regex: (.+)
    target_label: __metrics_path__
    replacement: /api/v1/nodes/${1}/proxy/metrics
    action: replace
  - source_labels: [__meta_kubernetes_namespace]
    separator: ;
    regex: (.*)
    target_label: namespace
    replacement: $1
    action: replace
</code>```

答: I think you're missing nodes/proxy resource in your prometheus cluster role. Here's official example github.com/prometheus/documentation/examples/rbac-setup.yml.

Body:
We are facing one issue, that some endpoints are in state "UNKNOWN". Prometheus job "kubernetes-nodes".

Nodes and Prometheus are all up for several days. We tried to curl those "kubernetes-nodes" endpoints, which are in "UNKNOWN" state. Metrics can be correctly curled, but endpoint state is still "UNKNOWN". We don't know the reason (criteria, on which case it will be marked as "UNKNOWN").

I know before Prometheus does its first scrape, endpoints are in "UNKNOWN" state. Then, if scrape successes, endpoint will be "UP", if fails, "DOWN". However, in below screenshot it seems some endpoints are never been scraped...We just don't know why.

Could you please give advice, about the possible reason of such case?
Does this mean this node (name hide in red block...) has something wrong? If so, is it possible to fix, that will let Prometheus treat it as "UP"?

Thanks in advance.

- job_name: kubernetes-nodes
  scrape_interval: 1m
  scrape_timeout: 10s
  metrics_path: /metrics
  scheme: https
  kubernetes_sd_configs:
  - api_server: null
    role: node
    namespaces:
      names: []
  bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
  tls_config:
    ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    insecure_skip_verify: true
  relabel_configs:
  - separator: ;
    regex: __meta_kubernetes_node_label_(.+)
    replacement: $1
    action: labelmap
  - separator: ;
    regex: (.*)
    target_label: __address__
    replacement: kubernetes.default.svc:443
    action: replace
  - source_labels: [__meta_kubernetes_node_name]
    separator: ;
    regex: (.+)
    target_label: __metrics_path__
    replacement: /api/v1/nodes/${1}/proxy/metrics
    action: replace
  - source_labels: [__meta_kubernetes_namespace]
    separator: ;
    regex: (.*)
    target_label: namespace
    replacement: $1
    action: replace


问:
React Native: Exporting a function from a functional component
Issue:

I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".

I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".

This is the "ContractHandler.js":

```<code>import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;
</code>```

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".

This is the import:

```<code>import { addPostCode } from '../../database/ContractHandler';
</code>```

This is the navigation with the "addPostCode"-function.

```<code><TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>
</code>```

"postCode" is just a variable that is given a value from a TextInput.

If I'm not being clear enough please let me know and I will try to explain better :)

答: There are two ways to solve this. You can use a state manager like redux or you have to pass the function as props from component to component. Personally I would use redux because it makes it simpler to share state between components.</p>

Body:
Issue:

I'm trying to figure out how to export a function that is called "addPostCode" from the functional component "ContractHandler".

I want to use "addPostCode" in an other functional component called "RentalDetailScreen" so that when I navigate to the next page it will trigger the "addPostCode" and store the state of "postCode" in "ContractHandler".

This is the "ContractHandler.js":

import React, { useState } from 'react';

const ContractHandler = () => {

  const [postCode, setPostCode] = useState();

  const addPostCode = (data) => {
    setPostCode(data)
    console.log(postCode)
  };

  return(
    <View>
      <Text></Text>
    </View>
  )

}

export default ContractHandler;

These are parts of the RentalDetailScreen.js where I navigate to the next page and want to trigger the "addPostCode"-function and send the "postCode"-value to the "ContractHandler.js".

This is the import:

import { addPostCode } from '../../database/ContractHandler';

This is the navigation with the "addPostCode"-function.

<TouchableOpacity onPress={() => { navigation.navigate('SecurityDetail'); addPostCode(postCode); }}>
  <View style={slider.buttonStyle}>
    <Text style={slider.textStyle}>Neste</Text>
    <Ionicons name='ios-arrow-forward'style={slider.iconStyle} />
  </View>
</TouchableOpacity>

"postCode" is just a variable that is given a value from a TextInput.

If I'm not being clear enough please let me know and I will try to explain better :)


问:
Detect end of event time session window (Apache Flink Java)
Assuming all events arrive on time and no lateness is allowed, how do I do some processing only when the session window has ended? I.e. the watermark has passed (lastEventInWindowTimestamp + inactivityGap).
I couldn't find any API method that is called when this happens. Can I implement this logic using a custom ProcessWindowFunction?

答:
Yes, a ProcessWindowFunction serves exactly this purpose. Such a function is called when the window is complete, and is passed (among other things) an Iterable containing the stream elements that have been assigned to the window. In the case of a session window, the ProcessWindowFunction isn't called until after the period of inactivity has passed.

Update: How can you report both the start and end timestamps for each session window?

I will assume that you can extract the timestamp for each event from the event itself. Then, if you are using a ProcessWindowFunction, you can iterate over the events in the window and determine the min and max timestamps for the events in the session -- these will be the start and end timestamps.

If, on the other hand, you would rather use a reduce function that incrementally computes the window results, you can work with tuples that track the (min, max) timestamps for each window.


问:
Invoke JavaScript function with argument via pointer?
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

```<code>function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);
</code>```

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

答:
Of course you can pass in functions as callbacks, in fact by doing

```<code>jQuery.post('/soon/check.json', { var:a }, function(resp) {...
</code>```

You are passing a callback that will be called after the post.

So the problem is somewhere else. Is the anonymous function passed to $.post really called ?

Hope this will help

Body:
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

Body:
Of course you can pass in functions as callbacks, in fact by doing

jQuery.post('/soon/check.json', { var:a }, function(resp) {...

You are passing a callback that will be called after the post.

So the problem is somewhere else. Is the anonymous function passed to $.post really called ?

Hope this will help