问:
Failure to trace some syscalls with eBPF
I am using bcc to trace several syscalls, why is it that I can trace syscalls like write, close, fchown using a simple attach_kprobe but can't trace syscalls like stat, fstat?

I assume that are other syscalls that I can't trace but haven't found which ones. How can I trace stat, fstat and how are these different from the usual write, close ?

Sample code:

```<code>b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname("fstat"), fn_name="syscall_fstat")
</code>```

In my prog I do a simple print

```<code>int syscall_fstat(void *ctx){
    bpf_trace_printk("fstat\n");
    return 0;
}
</code>```

答: Instead of using stat I should be using newstat. </p>

Body:
I am using bcc to trace several syscalls, why is it that I can trace syscalls like write, close, fchown using a simple attach_kprobe but can't trace syscalls like stat, fstat?

I assume that are other syscalls that I can't trace but haven't found which ones. How can I trace stat, fstat and how are these different from the usual write, close ?

Sample code:

b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname("fstat"), fn_name="syscall_fstat")

In my prog I do a simple print

int syscall_fstat(void *ctx){
    bpf_trace_printk("fstat\n");
    return 0;
}


来源: stackexchange

问:
Explicit C++ template instantiation with clang
Note: Several related questions (e.g., this one) ended up being marked as duplicates of this question. I am aware of this particular question and follow the solution in the corresponding answers. However, different compilers yield different behavior and I don't know why.

My library features a class template and I would like to offer instances for certain template arguments in a library, as the template requires some significant compilation time. The class template could look like this (stack.hpp)

```<code>#ifndef MY_STACK
#define MY_STACK

template<class T>
class stack
{
public:
    stack();
};

#endif
</code>```

and its implementation resides in a corresponding stack.tpp file

```<code>#ifndef MY_STACK_TPP
#define MY_STACK_TPP

#include <iostream>

template<class T>
stack<T>::stack()
{
    std::cout << "My stack constructor!" << std::endl;
}

#endif
</code>```

As I would like to offer support for only certain template arguments, my stack.cpp creates the following explicit template instances:

```<code>#include "stack.hpp"

template class stack<double>;
template class stack<char>;

#include "stack.tpp"
</code>```

This compiles with g++ and clang++ but there are differences in the symbols of resulting shared library:

```<code>g++ -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000049 t _GLOBAL__sub_I_stack.cpp
0000000000000000 W stack<char>::stack()
0000000000000000 W stack<char>::stack()
0000000000000000 n stack<char>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 n stack<double>::stack()
</code>```

vs.

```<code>clang++-7 -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000050 t _GLOBAL__sub_I_stack.cpp
</code>```

In my application, the constructor of such an explicitly instantiated class is not found using clang++, but it works fine with g++. I figure this basic MWE gives the reason. Can anyone tell me how I can get the constructor symbols for my class template using clang++?

答:
This program is well-formed

Quoting [temp.explicit]/1
[emphasis mine]:

A class, function, variable, or member template specialization can be
  explicitly instantiated from its template. A member function,
  member class or static data member of a class template can be
  explicitly instantiated from the member definition associated with
  its class template. [..]

And, quoting [temp.explicit]/9 [emphasis mine]:

An explicit instantiation definition that names a class template
  specialization explicitly instantiates the class template
  specialization and is an explicit instantiation definition of only
  those members that have been defined at the point of instantiation.

Thus, in the OPs example, the explicit instantiation definition of stack<T> will not include an explicit instantiation definition of the constructor, as the explicit instantiation definition of stack<T> is placed before providing the definition of it constructor via the .tpp include.

Quoting [temp.point]/8 [emphasis mine]:

A specialization for a function template, a member function template, or of a member function or static data member of a
  class template may have multiple points of instantiations within a
  translation unit, and in addition to the points of instantiation
  described above, for any such specialization that has a point of
  instantiation within the translation unit, the end of the translation
  unit is also considered a point of instantiation. A specialization
  for a class template has at most one point of instantiation within a
  translation unit. A specialization for any template may have points of
  instantiation in multiple translation units. If two different points
  of instantiation give a template specialization different meanings
  according to the one-definition rule, the program is ill-formed, no
  diagnostic required.

Thus, for the cases wheres stack.cpp includes two different points of instantiations, and where one is before and one is after the inclusion of stack.tpp, then the program is ill-formed.

However, here it becomes a bit tricky, as the points of instantiations depends on how the class template and its member function (/constructor) is used. As covered by [temp.explicit]/9 quoted above, the explicit instantiation of stack<T> will not result in an explicit instantiation definition of its constructor, and we will instead need to fall back on [temp.point] for details, particularly clauses 1, 2 and 4, on when its use context will lead to an instantiation point before the inclusion of stack.tpp.

The stand-alone example in the question is not covered by any of these cases, and thus the program us not ill-formed.

GCC vs clang: seemingly different instantiation behaviour?

Can anyone tell me how I can get the constructor symbols for my class template using clang++?

As the constructor is never used, it should never (need to) be instantiated at all, but it seems as if (from the OPs symbol dump) GCC does so anyway (which is not illegal) whereas clang does not. If one where to use/refer to the constructor after the inclusion of track.tpp, then both GCC and clang naturally instantiates it (for the particular specialization that is used), as they are then required to do so.

ContentLicense: CC BY-SA 4.0

Body:
Note: Several related questions (e.g., this one) ended up being marked as duplicates of this question. I am aware of this particular question and follow the solution in the corresponding answers. However, different compilers yield different behavior and I don't know why.

My library features a class template and I would like to offer instances for certain template arguments in a library, as the template requires some significant compilation time. The class template could look like this (stack.hpp)

#ifndef MY_STACK
#define MY_STACK

template<class T>
class stack
{
public:
    stack();
};

#endif

and its implementation resides in a corresponding stack.tpp file

#ifndef MY_STACK_TPP
#define MY_STACK_TPP

#include <iostream>

template<class T>
stack<T>::stack()
{
    std::cout << "My stack constructor!" << std::endl;
}

#endif

As I would like to offer support for only certain template arguments, my stack.cpp creates the following explicit template instances:

#include "stack.hpp"

template class stack<double>;
template class stack<char>;

#include "stack.tpp"

This compiles with g++ and clang++ but there are differences in the symbols of resulting shared library:

g++ -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000049 t _GLOBAL__sub_I_stack.cpp
0000000000000000 W stack<char>::stack()
0000000000000000 W stack<char>::stack()
0000000000000000 n stack<char>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 W stack<double>::stack()
0000000000000000 n stack<double>::stack()

vs.

clang++-7 -std=c++11 -c stack.cpp -o stack.so
nm -C stack.so | grep stack
0000000000000050 t _GLOBAL__sub_I_stack.cpp

In my application, the constructor of such an explicitly instantiated class is not found using clang++, but it works fine with g++. I figure this basic MWE gives the reason. Can anyone tell me how I can get the constructor symbols for my class template using clang++?


问:
Program type already present: com.google.zxing.ChecksumException
I try using zxing library to scan a qrcode, there's no error until I run the app like this:

```<code>Program type already present: com.google.zxing.ChecksumException

Message{kind=ERROR, text=Program type already present: com.google.zxing.ChecksumException, sources=[Unknown source file], tool name=Optional.of(D8)}
</code>```

here's my gradle:

```<code>android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.std.scanner"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}
</code>```

i think i should using "exclude" in my gradle dependecies, but I don't know how to write the code. please help, thanks in advance.

答:
My mistake was i added a plugin (qrcode) in pubspec.yml which overwrite another class defined from another plugin (animated_qr_code_scanner), and then exist a conflict between plugins (and classes).
You can try comenting the last added plugin to locate the used classes.</p>

ContentLicense: CC BY-SA 3.0

Body:
I try using zxing library to scan a qrcode, there's no error until I run the app like this:

Program type already present: com.google.zxing.ChecksumException

Message{kind=ERROR, text=Program type already present: com.google.zxing.ChecksumException, sources=[Unknown source file], tool name=Optional.of(D8)}

here's my gradle:

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.std.scanner"
        minSdkVersion 18
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}

i think i should using "exclude" in my gradle dependecies, but I don't know how to write the code. please help, thanks in advance.


问:
get data from client with regional language in nodejs
client side data sample as below

```<code>{name:'ABC',age:24,language:'ಕನ್ನಡ'}
</code>```

i need to send language value to another service
but in node console cannot print as above
instead of ಕನ್ನಡ it prints like  {name:'ABC',age:24,language:'����ͷ�'}
my express setup like

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();

    app.use(bodyParser.json({
            limit: '2mb'
        }));
        app.use(bodyParser.urlencoded({
            limit: '900kb',
            extended: true
        }));
    app.use((req, res, next) => {
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});
</code>```

this is indian kannada language.I try with locale module but no luck.
 how to set accept-language please help me to solve

答:
I am not sure whether this will help you or not but I just gave it a try:

```<code>var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json({
    limit: '2mb'
}));
app.use(bodyParser.urlencoded({
    limit: '900kb',
    extended: true
}));
app.use((req, res, next) => {
    console.log(decodeURIComponent(req.body.data));
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});

app.listen(3000);
</code>```

before posting it:

```<code>encodeURIComponent('ಕನ್ನಡ'); // returns %E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1
</code>```

then try:

```<code>curl -d "data=%E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1" http://localhost:3000/
</code>```

it will print on console:

ಕನ್ನಡ

P.S. As I mentioned this is just one possible way so there might be other ways as well.

Body:
client side data sample as below

{name:'ABC',age:24,language:'ಕನ್ನಡ'}

i need to send language value to another service
but in node console cannot print as above
instead of ಕನ್ನಡ it prints like  {name:'ABC',age:24,language:'����ͷ�'}
my express setup like

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();

    app.use(bodyParser.json({
            limit: '2mb'
        }));
        app.use(bodyParser.urlencoded({
            limit: '900kb',
            extended: true
        }));
    app.use((req, res, next) => {
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});

this is indian kannada language.I try with locale module but no luck.
 how to set accept-language please help me to solve

Body:
I am not sure whether this will help you or not but I just gave it a try:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json({
    limit: '2mb'
}));
app.use(bodyParser.urlencoded({
    limit: '900kb',
    extended: true
}));
app.use((req, res, next) => {
    console.log(decodeURIComponent(req.body.data));
    req.header("Content-Type",  "application/json;charset=UTF-8");
    next();
});

app.listen(3000);

before posting it:

encodeURIComponent('ಕನ್ನಡ'); // returns %E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1

then try:

curl -d "data=%E0%B2%95%E0%B2%A8%E0%B3%8D%E0%B2%A8%E0%B2%A1" http://localhost:3000/

it will print on console:

ಕನ್ನಡ

P.S. As I mentioned this is just one possible way so there might be other ways as well.


问:
Finding several post codes in text (all in one cell)
Im trying to write a script that loops through all cells in a column and checks each cell's text if there are two or more post codes in there. If it finds two or more post codes, it needs to highlight the whole row. Cells are filled with adress, like Street of hard-workers 2/12, 77-200, London. I have something like that below, but it does not include situation in which street's name is written with -.

Any ideas? :(

```<code>sub find_postcode()

For Each cell In Range("D2", Range("D" & Rows.Count).End(xlUp))
    If Len(cell) - Len(Replace(cell, "-", "")) > 1 Then
        cell.EntireRow.Interior.Color = 65535
    End If
Next cell

End sub
</code>```

答:
You could use Regular Expressions (How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops) with a pattern like ([0-9]+)-([0-9]+) (see https://regex101.com/r/gjPLqu/1/) to find only dash - delimited numbers in your address.

If you get a match with that pattern then highlight your cell.

If you have also house numbers like 1-3 like in Another Street 1-3, 77-200, Paris this pattern will recognize them false positive. Then you need to adjust your pattern to something more concrete like , ([0-9]+)-([0-9]+), so it finds only the ones between commata.

Body:
Im trying to write a script that loops through all cells in a column and checks each cell's text if there are two or more post codes in there. If it finds two or more post codes, it needs to highlight the whole row. Cells are filled with adress, like Street of hard-workers 2/12, 77-200, London. I have something like that below, but it does not include situation in which street's name is written with -.

Any ideas? :(

sub find_postcode()

For Each cell In Range("D2", Range("D" & Rows.Count).End(xlUp))
    If Len(cell) - Len(Replace(cell, "-", "")) > 1 Then
        cell.EntireRow.Interior.Color = 65535
    End If
Next cell

End sub


问:
Youtube Data API Access Not Configured
I have this error when trying to recover an endpoint on youtube api.

Access Not Configured. YouTube Data API has not been used in project 602077678805 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=602077678805 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.',

This is image console configuration

This is image com http return

答:
Access Not Configured.

This error message can mean  you have not enabled the api for use in your project.  In order to use an API you must tell google that you intend to use it in your project.  You cant just create a project and automatically use all of the apis google would like to know which ones you intend to use.

Go to the google developer console for your project as instructed in the link.  under Libraries search for YouTube API enable it and apply for a quota.

Title: Youtube Data API Access Not Configured


问:
RelativeLayout layout_centerInParent and layout_below issue
I have a problem with laying out a Relative Layout. Here is the test code

```<code><RelativeLayout
    android:background="@drawable/bg_controls"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/controls_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/controls_layout" />

</RelativeLayout>
</code>```

The result of that is

If I remove android:layout_centerInParent="true" everything works OK. Why does RelativeLayout fails to do that otherwise?

UPD: the intended result is that a second button appears under the LinearLayout.

答: Are you using API level 3 (1.5)?  RelativeLayouts are very quirky for 1.5.  Giving your buttons an id is a good idea.</p>

Body:
I have a problem with laying out a Relative Layout. Here is the test code

<RelativeLayout
    android:background="@drawable/bg_controls"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/controls_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/controls_layout" />

</RelativeLayout>

The result of that is

If I remove android:layout_centerInParent="true" everything works OK. Why does RelativeLayout fails to do that otherwise?

UPD: the intended result is that a second button appears under the LinearLayout.


问:
How to fill multidimensional array in javascript?
I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)

```<code>var A=[[],[]];
for(var i=0;i<12;i++){
    for(var j=0;j<81;j++){
        A[i][j]='q';
    }
}
</code>```

It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.

All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.

答:
This does the job in one line.

var A = Array(12).fill(null).map(()=>Array(81).fill('q'))

This is an array of references and a bad idea as harunurhan commented.

var A = Array(12).fill(Array(81).fill('q'));

Body:
I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)

var A=[[],[]];
for(var i=0;i<12;i++){
    for(var j=0;j<81;j++){
        A[i][j]='q';
    }
}

It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.

All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.


问:
How to calculate the number of documents a term occurs in using python?
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

```<code>for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)
</code>```

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

答:
You can do this. however, what you are trying to calculate is not IDF. It's just the frequency of the particular word in all documents.    </p>

```<code> for i in range(0,len(corpus)):
   words=corpus[i].split(' ')
   for word in words:
     if word in freq:
       freq[word] = freq[word] + 1
     else:
       freq[word] = 1
 print(freq)
</code>```

Body:
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

Body:
You can do this. however, what you are trying to calculate is not IDF. It's just the frequency of the particular word in all documents.

 for i in range(0,len(corpus)):
   words=corpus[i].split(' ')
   for word in words:
     if word in freq:
       freq[word] = freq[word] + 1
     else:
       freq[word] = 1
 print(freq)


问:
how to populate Dynamic List Java
I want to declare List as Dynamic

```<code>private static final List<KeyValue> columnDataList;
static {
    columnDataList = new ArrayList<DashColumnChartData.KeyValue>();
    columnDataList.add(new KeyValue("Russia1", "100", "500", "100", "100", "50"));
    columnDataList.add(new KeyValue("Canada1", "200", "500", "100", "100", "50"));
}
</code>```

instead i want to create for this...

```<code>while (rs1.next()) {
    ArrayList<Comparable> chartDataList = new ArrayList<Comparable>();
    chartDataList.add(rs1.getString("region_id"));
    columnDataList = new ArrayList<DashColumnChartData.KeyValue>();
    columnDataList.add(new KeyValue(rs1.getString("country_id", rs1.getString("region_id", rs1.getString("state_id"));
}
</code>```

how can I populate dynamic List and where to declare...

答: In Java, local variables are bound to a scope. If you declare a local variable inside a loop, it is only available inside the loop. (Technically, you have a variable chartDataList each per loop iteration.) If you need to access the variable outside the loop, declare it in an outer scope, e.g., the surrounding method. In your 'static' example, the scope is the surrounding class.

Title: how to populate Dynamic List Java

Body:
I want to declare List as Dynamic

private static final List<KeyValue> columnDataList;
static {
    columnDataList = new ArrayList<DashColumnChartData.KeyValue>();
    columnDataList.add(new KeyValue("Russia1", "100", "500", "100", "100", "50"));
    columnDataList.add(new KeyValue("Canada1", "200", "500", "100", "100", "50"));
}

instead i want to create for this...

while (rs1.next()) {
    ArrayList<Comparable> chartDataList = new ArrayList<Comparable>();
    chartDataList.add(rs1.getString("region_id"));
    columnDataList = new ArrayList<DashColumnChartData.KeyValue>();
    columnDataList.add(new KeyValue(rs1.getString("country_id", rs1.getString("region_id", rs1.getString("state_id"));
}

how can I populate dynamic List and where to declare...


问:
Is there any dropdown available with filter feature in angular material? NB: Using mat-select not mat-option
I have searched for a filtered dropdown option in angular material and could not find anything with mat-select multiselect.
I don't think an implementation is available in angular material for mat-select.
Is there a way to implement this using angular material?</p>

答:
There is no default component in Angular Material which has both dropdown and filter built into single component. But there are three different ways to use drop down with filter.

Angular Material autocomplete

Create custom dropdown with    filter by using mat-select and input
as shown here

Use third    party components which provide the same functionality
    like    mat-select-search


问:
SQL - How to join query results in same line
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21
```

```select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc
```

<p>bostamp column is like an id.</p>

<p>Now what I need is a result like this:</p>

<pre class="lang-none prettyprint-override"><code>u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time
</code>```

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

答:
If I understand correctly:

```<code>select u_reference, u_user, u_operation, u_machine,
       start, next_created_at as end,
       <time calculation>  -- this is database dependent
from (select dw.u_reference, dw.u_user, dw.u_operation,
             m.u_design as u_machine, m.epcusto as price,
             dw.u_action, dw.u_created_at as Start,
             dw.u_work_time as Work_time,
             lead(dw.u_created_at) over (partition by dw.u_reference order by dw.u_created_at) as next_created_at,
             lead(dw.u_work_time) over (partition by dw.u_reference order by dw.u_created_at) as next_work_time
      from u_daily_work_alb dw join
           u_machines_alb m
           on m.id = dw.u_machineId
      where dw.bostamp = 'ALB472248D84210CFA9FE30' and
            dw.u_reference = 'p-2000-9429'
     ) dw
where u_action in ('PLAY', 'REPLAY')
order by dw.id asc;
</code>```

This assumes that the record after a "play"/"replay" provides the information for ending.

Also, it is unclear what keys to use for defining "next".  I don't know if user, operation, and machine (or some combination of them) are needed apart from the reference and time.

Body:
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21

select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc

bostamp column is like an id.

Now what I need is a result like this:

u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

Body:
If I understand correctly:

select u_reference, u_user, u_operation, u_machine,
       start, next_created_at as end,
       <time calculation>  -- this is database dependent
from (select dw.u_reference, dw.u_user, dw.u_operation,
             m.u_design as u_machine, m.epcusto as price,
             dw.u_action, dw.u_created_at as Start,
             dw.u_work_time as Work_time,
             lead(dw.u_created_at) over (partition by dw.u_reference order by dw.u_created_at) as next_created_at,
             lead(dw.u_work_time) over (partition by dw.u_reference order by dw.u_created_at) as next_work_time
      from u_daily_work_alb dw join
           u_machines_alb m
           on m.id = dw.u_machineId
      where dw.bostamp = 'ALB472248D84210CFA9FE30' and
            dw.u_reference = 'p-2000-9429'
     ) dw
where u_action in ('PLAY', 'REPLAY')
order by dw.id asc;

This assumes that the record after a "play"/"replay" provides the information for ending.

Also, it is unclear what keys to use for defining "next".  I don't know if user, operation, and machine (or some combination of them) are needed apart from the reference and time.


问:
Laravel group by, count and access and eloquent relationship
I'd like to group by a foreign key ID, count that group and then in the view be able to access the relationship of that foreign key ID. The first two things (group by and count) succeed with the following query:

```<code>$collection = Example::selectRaw('count(*) AS total, foreign_key')
->groupBy('foreign_key')
->orderBy('total', 'DESC')
->get();
</code>```

But I can't figure out how I can access the eloquent relationship of the foreign key, so that in the view I can do something like

```<code>foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}
</code>```

Note that the Example Model has the relationship defined:

```<code>class Example extends Model
{
  public function foreign()
  {
    return $this->hasOne('App\Models\Foreign', 'id', 'foreign_key')
  }
}
</code>```

答:
In your COntroller

```<code>$collection = Example::selectRaw('count(*) AS total, foreign_key')->get();
</code>```

In your blade

```<code>foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}
</code>```

Body:
I'd like to group by a foreign key ID, count that group and then in the view be able to access the relationship of that foreign key ID. The first two things (group by and count) succeed with the following query:

$collection = Example::selectRaw('count(*) AS total, foreign_key')
->groupBy('foreign_key')
->orderBy('total', 'DESC')
->get();

But I can't figure out how I can access the eloquent relationship of the foreign key, so that in the view I can do something like

foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}

Note that the Example Model has the relationship defined:

class Example extends Model
{
  public function foreign()
  {
    return $this->hasOne('App\Models\Foreign', 'id', 'foreign_key')
  }
}

Body:
In your COntroller

$collection = Example::selectRaw('count(*) AS total, foreign_key')->get();

In your blade

foreach($collection as $c)
{
  $c->total;
  $c->foreign->title
  $c->foreign->address
}


问:
Determine if running on a rooted device
My app has a certain piece of functionality that will only work on a device where root is available. Rather than having this feature fail when it is used (and then show an appropriate error message to the user), I'd prefer an ability to silently check if root is available first, and if not,hide the respective options in the first place.

Is there a way to do this?

答:
Forget all that detecting root apps and su binaries. Check for the root daemon process. This can be done from the terminal and you can run terminal commands within an app. Try this one-liner.

```<code>if [ ! "$(/system/bin/ps -A | grep -v grep | grep -c daemonsu)" = "0" ]; then echo "device is rooted"; else echo "device is not rooted"; fi
</code>```

You don't need root permission to achieve this either.

Edit: Now using this method for better detection!

```<code>if [ $(ps -A | grep -e ^shell -e ^root | grep -v "\[" | tr -s ' ' | cut -d ' ' -f 9 | grep -c su) ] || [ $(which su) ]; then echo 'rooted'; else echo 'not rooted'; fi
</code>```

ContentLicense: CC BY-SA 2.5

Title: Determine if running on a rooted device

Body:
Forget all that detecting root apps and su binaries. Check for the root daemon process. This can be done from the terminal and you can run terminal commands within an app. Try this one-liner.

if [ ! "$(/system/bin/ps -A | grep -v grep | grep -c daemonsu)" = "0" ]; then echo "device is rooted"; else echo "device is not rooted"; fi

You don't need root permission to achieve this either.

Edit: Now using this method for better detection!

if [ $(ps -A | grep -e ^shell -e ^root | grep -v "\[" | tr -s ' ' | cut -d ' ' -f 9 | grep -c su) ] || [ $(which su) ]; then echo 'rooted'; else echo 'not rooted'; fi


问:
Disable Property of Azure Functions not working in Visual Studio 2017
I have Azure function with timer trigger.

```<code>public static void Run([TimerTrigger("0 */15 * * * *"), Disable("True")]TimerInfo myTimer, TraceWriter log)
</code>```

Here the Disable("true") is not working. it generates the function.json as
"disabled": "True", which is not correct. It should be "disabled": True,
Disable only accepts string value.
Is there any way to change this? or any other way to disable function?

答:
I wanted to add this answer, as I have been searching for it as well and I believe I found a good way to disable functions for debugging/development purposes (and to avoid these local changes get into the deployment pipelines/source control).

I combine the #if DEBUG statements with the Disable(string SettingsName) attribute:

The following piece of code shows different things at work:

The Disable attribute is not using the parameter to indicate True or False as a value, but it refers to an appsetting (that you can put in the local.settings.json file).  See the second snippet in this post.  So, just by changing that settings in the appsettings file, I can enable and disable triggers easily, without impacting my git repo or deployment pipelines.

The other interesting thing is the RunOnStartup = true parameter when using a TimerTrigger.  This one (which I only enable with the DEBUG compiler directives), will allow me to trigger the timer function immediately, without waiting for the next CRON cycle to happen.  (an alternative would be to do a post to your local functions endpoint, as described in this stackoverflow post).  So again, when assuming you run your production workloads in the RELEASE configuration, this is only impacting your local development environment and not your development team or releases.

1st snippet (attributes)

#if DEBUG
        [Disable("disable-transactioncrawler")]
#endif
        [FunctionName("TransactionCrawler")]
        public async Task Run([TimerTrigger("50 */10 * * * *"
#if DEBUG
                , RunOnStartup = true
#endif
            )]TimerInfo myTimer, ILogger log)
        {
                // Logic comes here
        }
```

<p>2nd snippet (local.appsettings.json)</p>

```{
  "Values":
  {
    "disable-transactioncrawler": false
  }
}
```

The following 'solutions' typically impact your production code, which can lead to issues:

Just using Disable() is not allowing you to configure/change it afterwards

Updating the host.json file to only include the triggers you want to run is also risking to have this change arriving in production.

Body:
I have Azure function with timer trigger.

public static void Run([TimerTrigger("0 */15 * * * *"), Disable("True")]TimerInfo myTimer, TraceWriter log)

Here the Disable("true") is not working. it generates the function.json as
"disabled": "True", which is not correct. It should be "disabled": True,
Disable only accepts string value.
Is there any way to change this? or any other way to disable function?

Body:
I wanted to add this answer, as I have been searching for it as well and I believe I found a good way to disable functions for debugging/development purposes (and to avoid these local changes get into the deployment pipelines/source control).

I combine the #if DEBUG statements with the Disable(string SettingsName) attribute:

The following piece of code shows different things at work:

The Disable attribute is not using the parameter to indicate True or False as a value, but it refers to an appsetting (that you can put in the local.settings.json file).  See the second snippet in this post.  So, just by changing that settings in the appsettings file, I can enable and disable triggers easily, without impacting my git repo or deployment pipelines.

The other interesting thing is the RunOnStartup = true parameter when using a TimerTrigger.  This one (which I only enable with the DEBUG compiler directives), will allow me to trigger the timer function immediately, without waiting for the next CRON cycle to happen.  (an alternative would be to do a post to your local functions endpoint, as described in this stackoverflow post).  So again, when assuming you run your production workloads in the RELEASE configuration, this is only impacting your local development environment and not your development team or releases.

1st snippet (attributes)

#if DEBUG
        [Disable("disable-transactioncrawler")]
#endif
        [FunctionName("TransactionCrawler")]
        public async Task Run([TimerTrigger("50 */10 * * * *"
#if DEBUG
                , RunOnStartup = true
#endif
            )]TimerInfo myTimer, ILogger log)
        {
                // Logic comes here
        }

2nd snippet (local.appsettings.json)

{
  "Values":
  {
    "disable-transactioncrawler": false
  }
}

The following 'solutions' typically impact your production code, which can lead to issues:

Just using Disable() is not allowing you to configure/change it afterwards

Updating the host.json file to only include the triggers you want to run is also risking to have this change arriving in production.


问:
Spring Data Geode Region has local scope and cannot listen to remote Region events
I am using Spring Data for Apache Geode for a Spring Boot app that uses a remote Apache Geode server. To set up local Regions I am using @Configuration class like:

```<code>@Configuration
public class GeodeConfig {

  public static Region<String, String> myRegion;

  @Bean("setupMyRegion")
  public Region<String, String> setupMyRegion(GemFireCache cache) {

    Region<String, String> r = cache.getRegion("myRegion");
    myRegion = r;

    return r;
  }
}
</code>```

This enables me to put and get data with the Region.

When I register interest in subscribing to a key, the subscription is setup with scope=LOCAL like this:

```<code>org.apach.geode.inter.cache.LocalRegion 4439 logKeys: org.apache.geode.internal.cache.LocalRegion[path='/myRegion';scope=LOCAL';dataPolicy=NORMAL; concurrencyChecksEnabled] refreshEntriesFromServerKeys count=1 policy=KEYS_VALUES
</code>```

and I guess that I want to set it up as a CACHING_PROXY so that later, on subscribing to events in the Region, the local subscription will see the server Region events.

I've set subscriptionEnabled=TRUE for the @ClientCacheApplication and I am trying to set

```<code>clientRegionShortcut = ClientRegionShortcut.CACHING_PROXY
</code>```

I don't know where to do this. I've tried the @EnableClusterDefinedRegions annotation but the Region is still being set to local.

If I try to create a Region Factory from the GemFireCache it gives me an error that the method createClientRegionFactory(ClientRegionShortcut) is "undefined" for the type GemFireCache.

THANKS

答:
The main problem here was that the class in which I wanted to use the Geode regions was not registering in the Spring container because I was using new to use that class instead of using @Autowired annotation for Spring. That meant that when I setup the Geode regions per @JohnBlum's answer using @Resource(name = "Example") private Region<Object, Object> example the autowiring was still producing null objects.

Also the class where I wanted to use the regions was in another package outside of my @ComponentScan so I had to amend the @ComponentScan to find that package.

Thing is, once I got through these configurations and properly setup the @EnableClusterDefinedRegions (real easy once you know how!!) and I can put and get with the regions, the register interests doesn't work.

The problem with the register interests was that my application.properties had

spring.data.gemfire.cache.client.durable-client-id=myListener

and when I removed that property the CacheListenerAdapter started to receive events from the server!

Body:
I am using Spring Data for Apache Geode for a Spring Boot app that uses a remote Apache Geode server. To set up local Regions I am using @Configuration class like:

@Configuration
public class GeodeConfig {

  public static Region<String, String> myRegion;

  @Bean("setupMyRegion")
  public Region<String, String> setupMyRegion(GemFireCache cache) {

    Region<String, String> r = cache.getRegion("myRegion");
    myRegion = r;

    return r;
  }
}

This enables me to put and get data with the Region.

When I register interest in subscribing to a key, the subscription is setup with scope=LOCAL like this:

org.apach.geode.inter.cache.LocalRegion 4439 logKeys: org.apache.geode.internal.cache.LocalRegion[path='/myRegion';scope=LOCAL';dataPolicy=NORMAL; concurrencyChecksEnabled] refreshEntriesFromServerKeys count=1 policy=KEYS_VALUES

and I guess that I want to set it up as a CACHING_PROXY so that later, on subscribing to events in the Region, the local subscription will see the server Region events.

I've set subscriptionEnabled=TRUE for the @ClientCacheApplication and I am trying to set

clientRegionShortcut = ClientRegionShortcut.CACHING_PROXY

I don't know where to do this. I've tried the @EnableClusterDefinedRegions annotation but the Region is still being set to local.

If I try to create a Region Factory from the GemFireCache it gives me an error that the method createClientRegionFactory(ClientRegionShortcut) is "undefined" for the type GemFireCache.

THANKS


问:
How to update the data range of an existing graph using app script? [Google Sheets]
I have created the script below, which runs from an onedit function for when cell J1 is edited. The graph exists in the sheet titled 'Daily Data'. The data it will be using is from a sheet titled 'Long Term Data'.

I used the following link as guidance: https://developers.google.com/apps-script/reference/spreadsheet/embedded-chart.

Thank you for any help.

```<code>function onEdit(e) {

  //This IF statement ensures it will only run when cell J1 is edited:
  if (
    e.source.getSheetName() == "Daily Data" &&
    e.range.columnStart == 10 &&
    e.range.columnEnd == 10 &&
    e.range.rowStart >= 1 &&
    e.range.rowEnd <= 1
  ) {

    var spreadsheet = SpreadsheetApp.getActive();
    var daily_data = spreadsheet.getSheetByName("Daily Data");
    var LTD_data = spreadsheet.getSheetByName("Long Term Data");

       //ABOVE HAS BEEN TESTED AND RUNS SUCCESFULLY. THE BELOW DOES NOT...

    var chart = daily_data.getCharts()[0];
    var range = LTD_data.getRange("B2:J3")
    chart = chart.modify()
        .addRange(range)
        .build();
    spreadsheet.updateChart(chart);
  }
}
;
</code>```

答:
You want to update chart in the sheet of Daily Data using Google Apps Script.

If my understanding is correct, how about the following modification?

Modification point:

updateChart() is the method of Class Sheet. But in your script, updateChart() is used for Class Spreadsheet. By this, the script doesn't work.

When above point is reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, the range is added to the existing ranges.

Modified script:

From:

```<code>spreadsheet.updateChart(chart);
</code>```

To:

```<code>daily_data.updateChart(chart);
</code>```

Pattern 2:

In this pattern, the existing ranges are removed and new range is added.

Modified script:

From:

```<code>var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
chart = chart.modify()
    .addRange(range)
    .build();
spreadsheet.updateChart(chart);
</code>```

To:

```<code>var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
var ranges = chart.getRanges();
chart = chart.modify();
ranges.forEach(function(range) {chart.removeRange(range)});
var modifiedChart = chart.addRange(range).build();
daily_data.updateChart(modifiedChart);
</code>```

Note:

In above case, the simple trigger of OnEdit event trigger can be used.

References:

updateChart(chart)

removeRange(range)

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I have created the script below, which runs from an onedit function for when cell J1 is edited. The graph exists in the sheet titled 'Daily Data'. The data it will be using is from a sheet titled 'Long Term Data'.

I used the following link as guidance: https://developers.google.com/apps-script/reference/spreadsheet/embedded-chart.

Thank you for any help.

function onEdit(e) {

  //This IF statement ensures it will only run when cell J1 is edited:
  if (
    e.source.getSheetName() == "Daily Data" &&
    e.range.columnStart == 10 &&
    e.range.columnEnd == 10 &&
    e.range.rowStart >= 1 &&
    e.range.rowEnd <= 1
  ) {

    var spreadsheet = SpreadsheetApp.getActive();
    var daily_data = spreadsheet.getSheetByName("Daily Data");
    var LTD_data = spreadsheet.getSheetByName("Long Term Data");

       //ABOVE HAS BEEN TESTED AND RUNS SUCCESFULLY. THE BELOW DOES NOT...

    var chart = daily_data.getCharts()[0];
    var range = LTD_data.getRange("B2:J3")
    chart = chart.modify()
        .addRange(range)
        .build();
    spreadsheet.updateChart(chart);
  }
}
;

Body:
You want to update chart in the sheet of Daily Data using Google Apps Script.

If my understanding is correct, how about the following modification?

Modification point:

updateChart() is the method of Class Sheet. But in your script, updateChart() is used for Class Spreadsheet. By this, the script doesn't work.

When above point is reflected to your script, it becomes as follows.

Pattern 1:

In this pattern, the range is added to the existing ranges.

Modified script:

From:

spreadsheet.updateChart(chart);

To:

daily_data.updateChart(chart);

Pattern 2:

In this pattern, the existing ranges are removed and new range is added.

Modified script:

From:

var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
chart = chart.modify()
    .addRange(range)
    .build();
spreadsheet.updateChart(chart);

To:

var chart = daily_data.getCharts()[0];
var range = LTD_data.getRange("B2:J3")
var ranges = chart.getRanges();
chart = chart.modify();
ranges.forEach(function(range) {chart.removeRange(range)});
var modifiedChart = chart.addRange(range).build();
daily_data.updateChart(modifiedChart);

Note:

In above case, the simple trigger of OnEdit event trigger can be used.

References:

updateChart(chart)

removeRange(range)

If I misunderstood your question and this was not the result you want, I apologize.


问:
How write notation for a subitem as root element for JSon Embarcadero rest debugger
I need make a subitem (that isn´t the root element) as the root element from a json object.
See picture.

```<code>I need the subnode "Lista" to be the root node, how notate?
result/Lista fails
result:Lista fails
result\Lista fails
result:/Lista fails
result:[Lista] fails
result:{Lista} fails....
</code>```

答:
I found the solution!!
result[0].Lista is the correct notation!!</p>

Body:
I need make a subitem (that isn´t the root element) as the root element from a json object.
See picture.

I need the subnode "Lista" to be the root node, how notate?
result/Lista fails
result:Lista fails
result\Lista fails
result:/Lista fails
result:[Lista] fails
result:{Lista} fails....


问:
Add new value to an existing object with a variable content as the key?
I have an object 'unit', whose keys are different teams. Teams' keys are employees. Each employee is an object with its own fields. I'm looping through some files, getting each employee object. Once I get an employee object, I want to place into its proper team within the unit object. For example:

```<code>var indiv = {'Rich':{'a':3,'b':4,'c':5}};
var teamname = "TeamA";
var unit = {};
unit[teamname] = indiv;

//[object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... }
//   }
// }
</code>```

Now, how can I add the following element to this object?

```<code>var indiv2 = {'Tom':{'a':6,'b':8,'c':10}};
</code>```

So that the result is:

```<code>// [object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... },
//     Tom: [object Object] { ... }
//   }
// }
</code>```

Any clues? Is the only option turning TeamA into an array of objects?

Thanks!

答:
If you don't want/can't change  indiv, indiv2 structure, you can do it this way.

Get the key from indiv2 :

```<code>let key = Object.keys(indiv2)[0]
</code>```

Get values:

```<code>let values = Object.values(indiv2)[0]
</code>```

And now you can do it like this:

```<code>unit[teamname][key] = values
</code>```

Body:
I have an object 'unit', whose keys are different teams. Teams' keys are employees. Each employee is an object with its own fields. I'm looping through some files, getting each employee object. Once I get an employee object, I want to place into its proper team within the unit object. For example:

var indiv = {'Rich':{'a':3,'b':4,'c':5}};
var teamname = "TeamA";
var unit = {};
unit[teamname] = indiv;

//[object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... }
//   }
// }

Now, how can I add the following element to this object?

var indiv2 = {'Tom':{'a':6,'b':8,'c':10}};

So that the result is:

// [object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... },
//     Tom: [object Object] { ... }
//   }
// }

Any clues? Is the only option turning TeamA into an array of objects?

Thanks!

Body:
If you don't want/can't change  indiv, indiv2 structure, you can do it this way.

Get the key from indiv2 :

let key = Object.keys(indiv2)[0]

Get values:

let values = Object.values(indiv2)[0]

And now you can do it like this:

unit[teamname][key] = values


答:
You want Object destructuring

const both = {'Rich':{'a':3,'b':4,'c':5},'Tom':{'a':6,'b':8,'c':10}};
const teamName = "TeamA";
let unit = { [teamName] : {} };
unit[teamName] = {...both}
console.log(unit);```
</div>
</div>
</p>

<p>One at a time:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const persons = [
  { 'Rich':{'a':3,'b':4,'c':5} },
  { 'Tom':{'a':6,'b':8,'c':10} }
];

const teamName = "TeamA"
let unit = { [teamName]: {} };

persons.forEach(person => unit[teamName] = { ...unit[teamName], ...person })
console.log(unit);</code>```

Title: Add new value to an existing object with a variable content as the key?

Body:
You want Object destructuring

const both = {'Rich':{'a':3,'b':4,'c':5},'Tom':{'a':6,'b':8,'c':10}};
const teamName = "TeamA";
let unit = { [teamName] : {} };
unit[teamName] = {...both}
console.log(unit);

One at a time:

const persons = [
  { 'Rich':{'a':3,'b':4,'c':5} },
  { 'Tom':{'a':6,'b':8,'c':10} }
];

const teamName = "TeamA"
let unit = { [teamName]: {} };

persons.forEach(person => unit[teamName] = { ...unit[teamName], ...person })
console.log(unit);


问:
`psql` command to view all existing tablespaces?
What's the psql command to view all existing tablespaces?

\l+ displays all existing databases with their configured tablespace, but it won't display tablespaces which have been created but don't yet contain a database.

答:
As documented in the manual, the command to list tablespaces is \db

If you are looking for a command, just enter \? in the psql command line and it will show you all available commands including a short description.


问:
No route matches [POST] "/downtowns/1/properties/new"
I have an application that has a one to many relationship with downtowns and properties.  What i've been having trouble with is creating new properties from the downtowns.  I keep getting the error that I used as the title for this question.

I have a hunch that the problem is in my form, (which i'm using the simple form gem). I'm able to go to my new page, fill out the form, and then when I hit submit, I get this error.

I'll display my form file first. (I've had trouble understanding simple form's docs, and that's why i think this is where the problem is)

```<code>= simple_form_for (@property), method: 'POST', url: new_downtown_property_path do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year
</code>```

My routes file

```<code>resources :downtowns do
  resources :properties
end
</code>```

My downtown controller

```<code>def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end
</code>```

and my properties controller

```<code>  def new
    @property = Property.new
  end

  def create
    @downtown = property.find(id)
    @property = Property.create(params[:property_params])
    @property.downtown_id = @downtown.id

    if @property.save
      redirect_to @property
    else
      render 'new'
    end
  end

  def show
  end
</code>```

答:
```<code>= simple_form_for([@downtown, @property]) do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year
</code>```

Just pass an array to look up the nested route with the polymorphic route helpers. This will correctly use downtown_properties_path as the action. In Rails you always create resources by posting to the collection path (/downtowns/1/properties). The new route just renders a form. You don't need to specify the method as Rails detects if the model has been persisted and sets the method to POST or PATCH accordingly.

You should also never add a space between the method name and the parens surrounding the argument list in Ruby:

```<code>def add(a,b)
  a + b
end

add (1, 2) # syntax error
add (1), 2 # this is what actually happens
</code>```

Ruby behaves very differently then for example JS here since parens are optional for method calls.

Your controller is also completely off. A nested resource controller should look something like.

```<code>class PropertiesController < ApplicationController
  before_action :set_downtown
  before_action :set_property, only: [:show, :edit, :update, :destroy]

  # GET /downtowns/1/properties/new
  def new
    @property = @downtown.properties.new
  end

  # POST /downtowns/1/properties
  def create
    @property = @downtown.properties.new(property_params)
    if @property.save
      redirect_to @property
    else
      render :new
    end
  end

  # ...

  private

  def set_downtown
    @downtown = Downtown.includes(:properties).find(params[:downtown_id])
  end

  def set_propery
    @property = Property.find(params[:id])
  end

  def property_params
    params.require(:downtown)
          .permit(:name, :city)
  end

  # ...
end
</code>```

Body:
I have an application that has a one to many relationship with downtowns and properties.  What i've been having trouble with is creating new properties from the downtowns.  I keep getting the error that I used as the title for this question.

I have a hunch that the problem is in my form, (which i'm using the simple form gem). I'm able to go to my new page, fill out the form, and then when I hit submit, I get this error.

I'll display my form file first. (I've had trouble understanding simple form's docs, and that's why i think this is where the problem is)

= simple_form_for (@property), method: 'POST', url: new_downtown_property_path do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year

My routes file

resources :downtowns do
  resources :properties
end

My downtown controller

def show
    @properties = Property.where(downtown: @downtown_id)
  end

  def new
    @downtown = Downtown.new
  end

  def create
    @downtown = Downtown.create(downtown_params)
    if @downtown.save
      redirect_to @downtown
    else
      render 'new'
    end
  end

  def downtown_params
    params.require(:downtown).permit(:name, :city)
  end

and my properties controller

  def new
    @property = Property.new
  end

  def create
    @downtown = property.find(id)
    @property = Property.create(params[:property_params])
    @property.downtown_id = @downtown.id

    if @property.save
      redirect_to @property
    else
      render 'new'
    end
  end

  def show
  end

Body:
= simple_form_for([@downtown, @property]) do |f|
  = f.input :name
  = f.input :last_remodel
  = f.input :original_construction_year

Just pass an array to look up the nested route with the polymorphic route helpers. This will correctly use downtown_properties_path as the action. In Rails you always create resources by posting to the collection path (/downtowns/1/properties). The new route just renders a form. You don't need to specify the method as Rails detects if the model has been persisted and sets the method to POST or PATCH accordingly.

You should also never add a space between the method name and the parens surrounding the argument list in Ruby:

def add(a,b)
  a + b
end

add (1, 2) # syntax error
add (1), 2 # this is what actually happens

Ruby behaves very differently then for example JS here since parens are optional for method calls.

Your controller is also completely off. A nested resource controller should look something like.

class PropertiesController < ApplicationController
  before_action :set_downtown
  before_action :set_property, only: [:show, :edit, :update, :destroy]

  # GET /downtowns/1/properties/new
  def new
    @property = @downtown.properties.new
  end

  # POST /downtowns/1/properties
  def create
    @property = @downtown.properties.new(property_params)
    if @property.save
      redirect_to @property
    else
      render :new
    end
  end

  # ...

  private

  def set_downtown
    @downtown = Downtown.includes(:properties).find(params[:downtown_id])
  end

  def set_propery
    @property = Property.find(params[:id])
  end

  def property_params
    params.require(:downtown)
          .permit(:name, :city)
  end

  # ...
end


答:
One way of doing it is as below. With unit[teamname] = {}; you save an empty object under the key teamname. Then you add the single elements to this object under the keys Rich and Tom

var rich = {'a':3,'b':4,'c':5}
var tom = {'a':6,'b':8,'c':10}
var name1 = "Rich"
var name2 = "Tom"
var unit = {};
var teamname = "TeamA";
unit[teamname] = {};
unit[teamname][name1] = rich;
unit[teamname][name2] = tom;
console.log(unit);```


问:
Sql query, selecting on unique identifier gives - Error converting data type varchar to uniqueidentifier
How do I select a column of type uniqueidentifier when I have a guid?

I've tried doing following:

```<code>SELECT * FROM MyTable WHERE id = '442402e-207d-b012-4b60-005056c00123'

and

SELECT * FROM MyTable WHERE id = '{442402e-207d-b012-4b60-005056c00123}'
</code>```

Both give me same error: Error converting data type varchar to uniqueidentifier.

答:
The first query is ok, but you are missing a digit on the first part of the GUID, it should have 8 digits, not seven....something like this:</p>

```<code>SELECT * FROM MyTable WHERE id = '71494DD6-90FB-417D-B9E2-28F34103C039'
</code>```

Body:
How do I select a column of type uniqueidentifier when I have a guid?

I've tried doing following:

SELECT * FROM MyTable WHERE id = '442402e-207d-b012-4b60-005056c00123'

and

SELECT * FROM MyTable WHERE id = '{442402e-207d-b012-4b60-005056c00123}'

Both give me same error: Error converting data type varchar to uniqueidentifier.

Body:
The first query is ok, but you are missing a digit on the first part of the GUID, it should have 8 digits, not seven....something like this:

SELECT * FROM MyTable WHERE id = '71494DD6-90FB-417D-B9E2-28F34103C039'


问:
Javascript Range - onchange event
I have code for slider:

```<code><input id="zoomvalue" class="slider" type="range" min="30" max="100" value="100" style="width: 150px;" />``
</code>```

The problem is onchange event executed when releasing mouse, but I need onchange event for every slider move. May be I don't need input type="range" but slider made on pure javascript/jquery.

答:
You can use oninput event

var val = document.getElementById("val");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="zoomvalue" class="slider" type="range" min="30" max="100" value="100" style="width: 150px;" oninput="val.innerText = this.value"/>
<span id="val"></span></code>```

Title: Javascript Range - onchange event

Body:
I have code for slider:

<input id="zoomvalue" class="slider" type="range" min="30" max="100" value="100" style="width: 150px;" />``

The problem is onchange event executed when releasing mouse, but I need onchange event for every slider move. May be I don't need input type="range" but slider made on pure javascript/jquery.

Body:
You can use oninput event

var val = document.getElementById("val");

<input id="zoomvalue" class="slider" type="range" min="30" max="100" value="100" style="width: 150px;" oninput="val.innerText = this.value"/>
<span id="val"></span>


问:
Sort 2 arrays in C by a joint logic
Given two arrays

```<code>a = [1,3,2,8,5,6]
b = [4,3,2,5,1,2]
</code>```

I would like to sort them in "one pass" where the "logic" involves the two arrays, meaning:

if

```<code>int sortBySum(index i, index j){
    if (a[i]+b[i] > a[j]+b[j]){
        return 1;
    }
    return -1;
}
</code>```

The output of the two arrays will be

```<code>a = [2,1,3,5,6,8]
b = [2,4,3,1,2,5]
</code>```

Because the original arrays sum is a+b=[5,6,4,13,6,8]

答:
When a task is about sorting, qsort is - in most cases - your friend.

But qsort can only sort one array. So you need to copy the elements from array a and b into an array of structs containing the data from a and b. Then use qsort and then copy the data back.

Like:

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int a;
  int b;
} common_data;

// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
  common_data* pa = (common_data*)p1;
  common_data* pb = (common_data*)p2;
  return ((pa->a + pa->b) - (pb->a + pb->b));
}

int main(void)
{
  int a[] = {1,3,2,8,5,6};
  int b[] = {4,3,2,5,1,2};
  size_t sz = sizeof(a)/sizeof(a[0]);
  common_data carr[sz];

  // Copy to common array
  for (size_t i = 0; i < sz; ++i)
  {
    carr[i].a = a[i];
    carr[i].b = b[i];
  }

  // Sort common array
  qsort(carr, sz, sizeof(carr[0]), cmp);

  // Copy to back to original array
  for (size_t i = 0; i < sz; ++i)
  {
    a[i] = carr[i].a;
    b[i] = carr[i].b;
  }

  // Print array a
  for (size_t i = 0; i < sz; ++i)
  {
    printf("%d ", a[i]);
  }
  printf("\n");

  // Print array b
  for (size_t i = 0; i < sz; ++i)
  {
    printf("%d ", b[i]);
  }
  printf("\n");

  return 0;
}
</code>```

Output:

```<code>2 1 3 5 6 8
2 4 3 1 2 5
</code>```

Title: Sort 2 arrays in C by a joint logic

Body:
Given two arrays

a = [1,3,2,8,5,6]
b = [4,3,2,5,1,2]

I would like to sort them in "one pass" where the "logic" involves the two arrays, meaning:

if

int sortBySum(index i, index j){
    if (a[i]+b[i] > a[j]+b[j]){
        return 1;
    }
    return -1;
}

The output of the two arrays will be

a = [2,1,3,5,6,8]
b = [2,4,3,1,2,5]

Because the original arrays sum is a+b=[5,6,4,13,6,8]

Body:
When a task is about sorting, qsort is - in most cases - your friend.

But qsort can only sort one array. So you need to copy the elements from array a and b into an array of structs containing the data from a and b. Then use qsort and then copy the data back.

Like:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
  int a;
  int b;
} common_data;

// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
  common_data* pa = (common_data*)p1;
  common_data* pb = (common_data*)p2;
  return ((pa->a + pa->b) - (pb->a + pb->b));
}

int main(void)
{
  int a[] = {1,3,2,8,5,6};
  int b[] = {4,3,2,5,1,2};
  size_t sz = sizeof(a)/sizeof(a[0]);
  common_data carr[sz];

  // Copy to common array
  for (size_t i = 0; i < sz; ++i)
  {
    carr[i].a = a[i];
    carr[i].b = b[i];
  }

  // Sort common array
  qsort(carr, sz, sizeof(carr[0]), cmp);

  // Copy to back to original array
  for (size_t i = 0; i < sz; ++i)
  {
    a[i] = carr[i].a;
    b[i] = carr[i].b;
  }

  // Print array a
  for (size_t i = 0; i < sz; ++i)
  {
    printf("%d ", a[i]);
  }
  printf("\n");

  // Print array b
  for (size_t i = 0; i < sz; ++i)
  {
    printf("%d ", b[i]);
  }
  printf("\n");

  return 0;
}

Output:

2 1 3 5 6 8
2 4 3 1 2 5


问:
Uninstalling pillow requires another 161 packages to be removed
I'm using Anaconda Navigator 1.9.7 with Python 3.7.4 and accoding to conda list I have pillow 6.2.0 installed, which should be fine. However I cannot import it in a project, neither using import pillow, nor import PIL. I tried to update it to no avail, I did a conda update pillow, but this didn't help. Now I'm trying to conda uninstall pillow, however it tells me then that another 161 (!) packages will be removed, among which anaconda-navigator-1.9.7-py37_0, anaconda-client-1.7.2-py37_0, matplotlib-3.1.3-py37_0,jupyter-1.0.0-py37_7 etc...

This does not sound right! What shall I do? Completely uninstall Anaconda or trying to force removing only the specific pillow package?

EDIT: When trying to remove the pillow package via the Anaconda GUI, it throws the error: "Downgrading/removing these packages will modify Anaconda Navigator dependencies."

EDIT: help('modules') returns that package pil is installed, indeed import pil works. matplotlib though seems to not recognize it??

答: I created a workaround: Since apparently the module is installed as pil and matplotlib is looking for PIL, I modified the image.py file in the matplotlib folder of the package. Instead of import PIL I changed it to import pil. Now the code runs without errors!


问:
NpgsqlCommand over NpgsqlDataAdapter
Why would you use NpgsqlCommand over NpgsqlDataAdapter?

NpgsqlCommand usage, using reader

```<code>var _command = new NpgsqlCommand();
var _reader = _command.ExecuteReader();
...
while (_reader.Read())
{
...
</code>```

NpgsqlDataAdapter usage, using Datasets

```<code>IDbDataAdapter dbDataAdapter = new NpgsqlDataAdapter();
dbDataAdapter.SelectCommand = selectCommand;
...
dbDataAdapter.Fill (dataSet);
</code>```

Basic usage does not mention DataAdapter.
Is NpgsqlCommand and reader more efficient and should be preferred choice?

答: NpgsqlCommand is the more low-level API - you're responsible for providing the raw SQL, and also for reading the resultset via NpgsqlDataReader. DataAdapter/DataTable are a layer above that; it has some shortcomings (e.g. resultsets are buffered in memory) and in general is considered somewhat old/legacy. If what you want is to send SQL and read the results back, consider using NpgsqlCommand unless there's a good reason to use NpgsqlAdapter.</p>

Title: NpgsqlCommand over NpgsqlDataAdapter

Body:
Why would you use NpgsqlCommand over NpgsqlDataAdapter?

NpgsqlCommand usage, using reader

var _command = new NpgsqlCommand();
var _reader = _command.ExecuteReader();
...
while (_reader.Read())
{
...

NpgsqlDataAdapter usage, using Datasets

IDbDataAdapter dbDataAdapter = new NpgsqlDataAdapter();
dbDataAdapter.SelectCommand = selectCommand;
...
dbDataAdapter.Fill (dataSet);

Basic usage does not mention DataAdapter.
Is NpgsqlCommand and reader more efficient and should be preferred choice?


问:
How to fetch data after a specific (primary) key value in Oracle?
I am working on on the following code. I believe there might be a query to do this.

```<code>dsn_tns = cx_Oracle.makedsn(database_host, database_port, database_service)
connection = cx_Oracle.connect(database_username, database_password, dsn_tns, cx_Oracle.SYSDBA)
print("Database connected")
cursor = connection.cursor()
cursor.execute("SELECT * FROM " + database_table)
records = cursor.fetchall()
</code>```

Anyone any idea for improvements?

答:
Yes. You can use a query like this

```<code>SELECT * FROM tbl WHERE pk >= some_value;
</code>```

Primary keys on tables are backed up by indexes, so the searching and filtering job specified in that WHERE clause is efficient. The database finds the first row that satisfies the condition, then reads the rest of the rows sequentially. It's called an index range scan.

Pro tip: Avoid SELECT * and instead use SELECT col, col2, col3, giving the names of your table's columns you actually need. It saves work on your database server, and makes your queries more resilient to possible future changes in your table.

Body:
I am working on on the following code. I believe there might be a query to do this.

dsn_tns = cx_Oracle.makedsn(database_host, database_port, database_service)
connection = cx_Oracle.connect(database_username, database_password, dsn_tns, cx_Oracle.SYSDBA)
print("Database connected")
cursor = connection.cursor()
cursor.execute("SELECT * FROM " + database_table)
records = cursor.fetchall()

Anyone any idea for improvements?

Body:
Yes. You can use a query like this

SELECT * FROM tbl WHERE pk >= some_value;

Primary keys on tables are backed up by indexes, so the searching and filtering job specified in that WHERE clause is efficient. The database finds the first row that satisfies the condition, then reads the rest of the rows sequentially. It's called an index range scan.

Pro tip: Avoid SELECT * and instead use SELECT col, col2, col3, giving the names of your table's columns you actually need. It saves work on your database server, and makes your queries more resilient to possible future changes in your table.


问:
How do I configure backpressure in Spring WebFlux?
I'm trying to understand how to apply backpressure in Spring WebFlux. I understand the theory of backpressure, but I can't reproduce it, so I don't fully understand it.

Let's take the following example:

```<code>public void test() throws InterruptedException {
    EmitterProcessor<String> processor = EmitterProcessor.create();

    new Thread(() -> {
        int i = 0;
        while(runThread) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignored) {
            }
            processor.onNext("Value: " + i);
            i++;
        }
        processor.onComplete();
    }).start();

    processor
            .subscribe(makeSubscriber("FIRST - "), Throwable::printStackTrace);
}

private Consumer<String> makeSubscriber(String label) {
    return v -> {
        System.out.println(label + v);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
        }
    };
}
</code>```

I have created a Hot Flux in the form of an EmitterProcessor and in a separate thread I start producing data for it.
A bit lower, I subscribe to it. The subscriber is slower than the rate at which elements are being produced, so the issues should start to occur, right?
But the subscriber logic is run on the producer thread. When I call processor.onNext(), it synchronously calls all the subscribers, so if the subscribers are slow, the publisher is slowed down as well. So, then backpressure doesn't even seem useful.

I have also tried making two Spring Boot WebFlux applications, one with a Flux endpoint and one that consumes the endpoint, so I can be certain the consumer runs on a separate thread. But then, any attempt I make at backpressure in the consumer does nothing. There is no buffer being filled, there is nothing being dropped or anything!

Can anyone give me a concrete example of backpressure? Preferably in Spring WebFlux but I'll take any reactive Java library.

答:
the documentation to the variant of subscribe method you have chosen reads:

The subscription will request an unbounded demand (Long.MAX_VALUE).

that is, you switched off backpressure yourself.

To use backpressure , subscribe with Flux.subscribe(Subscriber)

Body:
I'm trying to understand how to apply backpressure in Spring WebFlux. I understand the theory of backpressure, but I can't reproduce it, so I don't fully understand it.

Let's take the following example:

public void test() throws InterruptedException {
    EmitterProcessor<String> processor = EmitterProcessor.create();

    new Thread(() -> {
        int i = 0;
        while(runThread) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignored) {
            }
            processor.onNext("Value: " + i);
            i++;
        }
        processor.onComplete();
    }).start();

    processor
            .subscribe(makeSubscriber("FIRST - "), Throwable::printStackTrace);
}

private Consumer<String> makeSubscriber(String label) {
    return v -> {
        System.out.println(label + v);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ignored) {
        }
    };
}

I have created a Hot Flux in the form of an EmitterProcessor and in a separate thread I start producing data for it.
A bit lower, I subscribe to it. The subscriber is slower than the rate at which elements are being produced, so the issues should start to occur, right?
But the subscriber logic is run on the producer thread. When I call processor.onNext(), it synchronously calls all the subscribers, so if the subscribers are slow, the publisher is slowed down as well. So, then backpressure doesn't even seem useful.

I have also tried making two Spring Boot WebFlux applications, one with a Flux endpoint and one that consumes the endpoint, so I can be certain the consumer runs on a separate thread. But then, any attempt I make at backpressure in the consumer does nothing. There is no buffer being filled, there is nothing being dropped or anything!

Can anyone give me a concrete example of backpressure? Preferably in Spring WebFlux but I'll take any reactive Java library.


问:
How to create splats from points with normals in three.js?
I am a newbie in both OpenGL as well as Three.js, I am working on a streaming based "on-line" viewer which uses websockets to transmit points (with surface normals) from one system application to a remote web interface. Long story short, I have modified BufferGeometry and use THREE.PointsMaterial to visualize incoming data with points.

Since I already am sending points locations [xyz], color [rgb] and normals [abc] so I would love to use technique such as surface-splatting Splatting. Unfortunately due to my limited knowledge and lack of internet resources can any one guide me to implement a very basic surface splatting technique using three.js?

Question: How to draw elliptical surfaces instead of points in three.js

Any help will be highly appreciated.

答:
it would probably work using points if you compute the point-size per point such that the whole ellipsis fits in there and use the fragment-shader to compute the area of the ellipsis based on the viewing-angle (i suppose this is what you want to do, right?).

Alternatively, you can use instancing based on a simple quad and use instance-attributes for position and orientation of the quads. In this case, you just need to render a circle into each of the quads.


问:
I want to get a single database SQL string
I got a little problem with this:

```<code>readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();
</code>```

and it returns:

```<code>System.Threading.Tasks.Task`1[System.String]
</code>```

But why? I wanted a single string like "test" in there.

答:
you need to await operations that are task-like, i.e.

Session["MandantName"] = await logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();
```

however, this requires your code to be async; if it isn't, either make it async (but not async void), or look for a synchronous version of the API.

You should probably look into parameters, too; the code as shown is actively dangerous.

Body:
I got a little problem with this:

readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();

and it returns:

System.Threading.Tasks.Task`1[System.String]

But why? I wanted a single string like "test" in there.

Body:
you need to await operations that are task-like, i.e.

Session["MandantName"] = await logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();

however, this requires your code to be async; if it isn't, either make it async (but not async void), or look for a synchronous version of the API.

You should probably look into parameters, too; the code as shown is actively dangerous.


问:
codeingter3 HMVC 'default_controller' is not working
I am using CI3 HMVC in my project. Now, I am facing problem with routing. I want user to type www.demosite.com and it would automatically call my home module. I do not want to show like www.demosite.com/home. I want to show the url like www.demo.com.  for this,  I set default controller in application/config/routes, like this, as follows;

$route['default_controller'] = "home";

also in my content module, I added a route folder where I wrote

```<code>$route['home'] = 'home';
</code>```

Here is my .htaccess

```<code>    AddType text/x-component .htc
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond $1 !(index\.php|assets/)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>
</code>```

This is my home controller

```<code>class Home extends MX_Controller{
  function __construct(){
    parent::__construct();

  }

  function index($stub=""){
    $baseUrl=base_url();
    $this->load->helper("url");

      echo $this->_showHomepage();

  }
}
</code>```

However, when I run this. I got 404 error.  What can i do to solve this problem? Thanks in advance.

答: I solved it. I moved the Home folder from Modules folder to Controller folder and then, it just started to work</p>

Body:
I am using CI3 HMVC in my project. Now, I am facing problem with routing. I want user to type www.demosite.com and it would automatically call my home module. I do not want to show like www.demosite.com/home. I want to show the url like www.demo.com.  for this,  I set default controller in application/config/routes, like this, as follows;

$route['default_controller'] = "home";

also in my content module, I added a route folder where I wrote

$route['home'] = 'home';

Here is my .htaccess

    AddType text/x-component .htc
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond $1 !(index\.php|assets/)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>

This is my home controller

class Home extends MX_Controller{
  function __construct(){
    parent::__construct();

  }

  function index($stub=""){
    $baseUrl=base_url();
    $this->load->helper("url");

      echo $this->_showHomepage();

  }
}

However, when I run this. I got 404 error.  What can i do to solve this problem? Thanks in advance.


问:
Durable function based design for long running activity
As per business requirement, we need to on broad customer's data of third party AD in to our application database & then need to establish real time sync with third party AD to sync up with their thereafter changes.

To do that, our side APIs and third party side APIs are ready. Since this on-boarding & real time sync activities happens on demand (not 24x7 but whenever there is change on the third party AD resource or whenever we acquire new client) I prefer to do Azure function based solution but Azure function is having max. timeout of 10mins on consumption plan which I don't believe fits to our requirement. At the moment we are not consider Azure function's other hosting plan.

So thought of doing Durable function orientated design where notification about recent changes on third party AD will be received in Azure queue which triggers durable function execution, in turn orchestrator function will query third party for recent of list of changes on user resource & the response may return user changes in 1000s in numbers.

Then orchestator loop through the user change list and invoke brand new activity function for every single user in the list which in turn calls out in house REST API(will accept only one user object not list of users as its parameter) & onboard the user to our application.

By this design we may end up with thousand instances of same activity function running in our azure account at same time. Is this possible?

Any limitation in turn max number instantiation of particular activity function on given point time?

Is every activity function is nothing but regular Azure function?

Are there better way designing instead of spinning up new instance of activity function for every new onboarding user resource?

Long running Activity function possible with Durable extension of Azure function which alone will take care of activity lasting for more than 30 minutes under consumption plan? please suggest.

答:
Q: By this design we may end up with thousand instances of same activity function running in our azure account at same time. Is this possible?

A: Yes. Your scenario is commonly referred to as the fan-out/fan-in pattern.

Q: Any limitation in turn max number instantiation of particular activity function on given point time?

A: There are a couple of performance targets documented that you can refer to but do note that they will depend on what your activity functions do.

Also, you can try different throttle settings to improve the numbers but beware of the consequences mentioned in the doc.

Q: Is every activity function is nothing but regular Azure function?

A: Yes. Think of it like a queue triggered function

Q: Are there better way designing instead of spinning up new instance of activity function for every new onboarding user resource?

A: The consumption plan should be able to easily handle such scenarios, but note that the fan-in operation runs on a single VM as mentioned in the performance targets doc. If this operation requires processing (like aggregation), you could consider using sub-orchestrations to split it across multiple VMs.

Q: Long running Activity function possible with Durable extension of Azure function which alone will take care of activity lasting for more than 30 minutes under consumption plan?

A: Not possible with the consumption plan. You will have to use the Premium Tier or an App Service Plan.


问:
how would iterate through and compare the students class and the class schedule class and if they are the same then display them on the html page
```<code>                     @*If Student attends the same class ID as the Class Schedule*@
        @foreach (var item in Model.Where(p => p.Class_Schedule.ClassID.Equals(Model.Any(p => p.Student.Enrollments.Any(p => p.ClassID)))))
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.AttendanceID)
                </td>
</code>```

This is my html file that i added to my MVC application, wanted to make an if statement that will check if the student ID is enrolled on the same class as class as the class schedule ID. If it is it will display his details and if he isnt it will ignore him and iterate on. I am getting an error on (p=>p.ClassID) the error is cannot implicitly turn type int into bool

答:
You're getting an error because .ANY returns boolean not an int like ClassID (i.e. Int <> Bool).

What you're trying to accomplish may be easier to do in two separate loops like so (you may have to align to your models but just the general concept):

```<code>@foreach (var classItem in Model.Class_Schedule)
   {
        var classId = classItem.ClassID;

        <tr><td>@* classItem.Whatever your class name is *@ </td></tr>

        @foreach(var student in Model.Student.Enrollments.Where(e => e.ClassID == classId))
            {
              <tr>
                 <td>
                    @Html.DisplayFor(student => student.AttendanceID)
                 </td>
               </tr>
            }

    }
</code>```

Body:
                     @*If Student attends the same class ID as the Class Schedule*@
        @foreach (var item in Model.Where(p => p.Class_Schedule.ClassID.Equals(Model.Any(p => p.Student.Enrollments.Any(p => p.ClassID)))))
        {

                    @Html.DisplayFor(modelItem => item.AttendanceID)

This is my html file that i added to my MVC application, wanted to make an if statement that will check if the student ID is enrolled on the same class as class as the class schedule ID. If it is it will display his details and if he isnt it will ignore him and iterate on. I am getting an error on (p=>p.ClassID) the error is cannot implicitly turn type int into bool

Body:
You're getting an error because .ANY returns boolean not an int like ClassID (i.e. Int <> Bool).

What you're trying to accomplish may be easier to do in two separate loops like so (you may have to align to your models but just the general concept):

@foreach (var classItem in Model.Class_Schedule)
   {
        var classId = classItem.ClassID;

        <tr><td>@* classItem.Whatever your class name is *@ </td></tr>

        @foreach(var student in Model.Student.Enrollments.Where(e => e.ClassID == classId))
            {
              <tr>
                 <td>
                    @Html.DisplayFor(student => student.AttendanceID)
                 </td>
               </tr>
            }

    }


问:
Initial steps to get up and running with Selenium RC and tests written in Ruby?
Can someone tell me the exact steps (be specific) to test (write tests and then execute them) a website through Firefox using Selenium RC and the Ruby programming language?

I'm new to this and have only done it with Java, Eclipse, and JUnit 4 (and Selenium RC + IDE of course). I'm looking for steps similar to what it took for me to get it up and running with Java.

To get up and running with Java I did the following:

Created new Java project in Eclipse.

To this projected I added selenium-java-client-driver.jar, selenium-server.jar, and Junit4 Library.

Using Selenium IDE I created a test and exported it in the Java language.

I created a class in my Java project (in Eclipse) and imported this code; which needed some tweeking.

I then click on the "Run " in eclipse and it works great.

Can someone give me comparable steps to get up and running with Ruby and any IDE?

Thank you

答:
Okay, figured it out.

Install ruby.

Install selenium ide on FF

DL and run the selenium server

record a test in the selenium IDE
for FF and export it as a ruby file

open command line with ruby
(confirm by typing "ruby -v") and
navigate to this newly exported ruby
file

run "gem install selenium-client"

"ruby your_file_name.rb". And
that's it!


问:
Find the intersection of two lists in linq?
I have list of int A,B. i like to do the following step in linq

```<code>list<int> c = new List<int>();

for (int i = 0; i < a.count; i++)
{
    for (int j = 0; j < b.count; j++)
    {
        if (a[i] == b[j])
        {
            c.add(a[i]);
        }
    }
}
</code>```

if its a and b is object , I need check particular properties like this manner and add list if it equals how can i do this in linq?

答:
This is my version of intersection:</p>

```<code>var a = new List<int>();
var b = new List<int>();

// intersection
var c = a.Where(x => b.Any(y => x == y)).ToList();
</code>```

Body:
I have list of int A,B. i like to do the following step in linq

list<int> c = new List<int>();

for (int i = 0; i < a.count; i++)
{
    for (int j = 0; j < b.count; j++)
    {
        if (a[i] == b[j])
        {
            c.add(a[i]);
        }
    }
}

if its a and b is object , I need check particular properties like this manner and add list if it equals how can i do this in linq?

Body:
This is my version of intersection:

var a = new List<int>();
var b = new List<int>();

// intersection
var c = a.Where(x => b.Any(y => x == y)).ToList();


问:
How return back original SimpleDraweeView after blurring
I've have SimpleDraweeView(Fresco). How can I return back original image after blurring?

Blur code:

```<code>val blurController = Fresco.newDraweeControllerBuilder()
   .setImageRequest(
       ImageRequestBuilder.newBuilderWithSource(Uri.parse(imageUrl))
           .setPostprocessor(IterativeBoxBlurPostProcessor(7))
           .build()
   )
   .setOldController(image.controller)
   .build()

image.controller = blurController
</code>```

答:
You can simply set uri for SimpleDraweeView like this:

```<code>var offBlur=view.findViewById<ImageButton>(R.id.blur_off)
offBlur.setOnClickListener {
    image.setImageURI(uri)  // this line
}
</code>```

After set uri again, blur effect will disappear.

Body:
I've have SimpleDraweeView(Fresco). How can I return back original image after blurring?

Blur code:

val blurController = Fresco.newDraweeControllerBuilder()
   .setImageRequest(
       ImageRequestBuilder.newBuilderWithSource(Uri.parse(imageUrl))
           .setPostprocessor(IterativeBoxBlurPostProcessor(7))
           .build()
   )
   .setOldController(image.controller)
   .build()

image.controller = blurController

Body:
You can simply set uri for SimpleDraweeView like this:

var offBlur=view.findViewById<ImageButton>(R.id.blur_off)
offBlur.setOnClickListener {
    image.setImageURI(uri)  // this line
}

After set uri again, blur effect will disappear.


问:
XPAGE validateexpression problem in a time field
i'm trying to prevent the user from inserting a period longer than 2 hours in an application form , this is my code :
i've wrote my validation code in the field "Heure_fin" which is a time field which is calculate the diffrence between "Heur_fin" and "heur_debut"

```<code><xp:inputText value="#{document1.Heure_fin}"
                id="heur_fin"
                style="width:31.0%;font-family:Verdana,sans-serif;height:20px"
                disableClientSideValidation="true">
                <xp:this.converter>
                    <xp:convertDateTime type="time"
                        timeStyle="short">
                    </xp:convertDateTime>
                </xp:this.converter>

                <xp:this.validators>

                    <xp:validateRequired message="required field"></xp:validateRequired>

                    <xp:validateExpression>

<xp:this.expression><![CDATA[#{javascript:
var dStart:NotesDateTime =session.createDateTime(getComponent("date_debut1").getValue());
var hStart:NotesDateTime =session.createDateTime(getComponent("heur_debut1").getValue());
var dateTimeStart:NotesDateTime=session.createDateTime(dStart.getDateOnly()+" "+hStart.getTimeOnly())
var hEnd:NotesDateTime=session.createDateTime(getComponent("heur_fin").getValue());
var dateTimeEnd:NotesDateTime=session.createDateTime(dStart.getDateOnly()+" "+hEnd.getTimeOnly())
var hours = dateTimeEnd.timeDifferenceDouble(dateTimeStart)
if ((hours/3600)<=2)

{
     return true
}else
    return false

}]]></xp:this.expression>
                        </xp:validateExpression>
                    </xp:this.validators>
                    <xp:dateTimeHelper id="dateTimeHelper4"></xp:dateTimeHelper>

                </xp:inputText>
</code>```

but i keep getting the following error message :
    Expression is invalid.
    Expression did not return a boolean value.

i've put the same code in a computed field and it works fine ,
is there any thing wrong that i'm missing , i appreciate your help .
Regards,

答: In a validator you need to use getSubmittedValue() instead of getValue(). See this blog post I did to give more details about the partial refresh (JSF) lifecycle of XPages, which should help explain why https://www.intec.co.uk/understanding-partial-execution-part-three-jsf-lifecycle/

Body:
i'm trying to prevent the user from inserting a period longer than 2 hours in an application form , this is my code :
i've wrote my validation code in the field "Heure_fin" which is a time field which is calculate the diffrence between "Heur_fin" and "heur_debut"

<xp:inputText value="#{document1.Heure_fin}"
                id="heur_fin"
                style="width:31.0%;font-family:Verdana,sans-serif;height:20px"
                disableClientSideValidation="true">
                <xp:this.converter>
                    <xp:convertDateTime type="time"
                        timeStyle="short">
                    </xp:convertDateTime>
                </xp:this.converter>

                <xp:this.validators>

                    <xp:validateRequired message="required field"></xp:validateRequired>

                    <xp:validateExpression>

<xp:this.expression><![CDATA[#{javascript:
var dStart:NotesDateTime =session.createDateTime(getComponent("date_debut1").getValue());
var hStart:NotesDateTime =session.createDateTime(getComponent("heur_debut1").getValue());
var dateTimeStart:NotesDateTime=session.createDateTime(dStart.getDateOnly()+" "+hStart.getTimeOnly())
var hEnd:NotesDateTime=session.createDateTime(getComponent("heur_fin").getValue());
var dateTimeEnd:NotesDateTime=session.createDateTime(dStart.getDateOnly()+" "+hEnd.getTimeOnly())
var hours = dateTimeEnd.timeDifferenceDouble(dateTimeStart)
if ((hours/3600)<=2)

{
     return true
}else
    return false

}]]></xp:this.expression>
                        </xp:validateExpression>
                    </xp:this.validators>
                    <xp:dateTimeHelper id="dateTimeHelper4"></xp:dateTimeHelper>

                </xp:inputText>

but i keep getting the following error message :
    Expression is invalid.
    Expression did not return a boolean value.

i've put the same code in a computed field and it works fine ,
is there any thing wrong that i'm missing , i appreciate your help .
Regards,