问:
Jacoco classes in bundle do not match for Transactional methods
I'm testing an app with JUnit5 and using Jacoco for coverage report.
Tests are executed Ok and test reports are present.

However, Jacoco report has the following logs if service contains methods, annotated with @Transactional

```<code>[ant:jacocoReport] Classes in bundle 'my-service' do no match with execution data. For report generation the same class files must be used as at runtime.
[ant:jacocoReport] Execution data for class mypackage/SampleService does not match.
</code>```

This error occurres for all @Service classes methods, annotated with @Transactional, plain classes coverage is calculated ok.

Here's a sample test:

```<code>@SpringBootTest
@ExtendWith(SpringExtension.class)
public class MyServiceTest {

    @Autowired
    private SampleService sampleService;

    @Test
    public void doWork(){
        sampleService.doWork();
    }
}
</code>```

Works fine. Coverage is non-zero:

```<code>public class SampleService {

    public void doWork(){
        System.out.println("HEY");
    }
}
</code>```

0% coverage:

```<code>public class SampleService {

    @Transactional
    public void doWork(){
        System.out.println("HEY");
    }
}
</code>```

Transactional creates a proxy around actuall class. But, isn't there an out-of-box way for Jacoco  to handle such a common situation?

I've tried @EnableAspectJAutoProxy annotaion with different flag variations, checked that up-to-date Jupiter engine and Jacoco plugin are used

Here's gradle config:

```<code>subprojects {
    test {
        useJUnitPlatform()
    }

    jacocoTestReport {
        afterEvaluate {
            classDirectories.from = files(classDirectories.files.collect {
                fileTree(dir: it, exclude: '*Test.java')
            })
        }

        reports {
            html.enabled = true
            xml.enabled = true
            csv.enabled = false
        }
    }
}
</code>```

Any help appreciated

答:
Based on single module instrumentation example https://stackoverflow.com/a/31916686/7096763 (and updated version for gradle 5+ by  @MikaelF) here's example for multimodule instrumentation:

```<code>subprojects {  subproject ->
    subproject.ext.jacocoOfflineSourceSets = [ 'main' ]
    task doJacocoOfflineInstrumentation(dependsOn: [ classes, subproject.configurations.jacocoAnt ]) {
        inputs.files classes.outputs.files
        File outputDir = new File(subproject.buildDir, 'instrumentedClasses')
        outputs.dir outputDir
        doFirst {
            project.delete(outputDir)
            ant.taskdef(
                    resource: 'org/jacoco/ant/antlib.xml',
                    classpath: subproject.configurations.jacocoAnt.asPath,
                    uri: 'jacoco'
            )
            def instrumented = false
            jacocoOfflineSourceSets.each { sourceSetName ->
                if (file(sourceSets[sourceSetName].output.classesDirs[0]).exists()) {
                    def instrumentedClassedDir = "${outputDir}/${sourceSetName}"
                    ant.'jacoco:instrument'(destdir: instrumentedClassedDir) {
                        fileset(dir: sourceSets[sourceSetName].output.classesDirs[0], includes: '**/*.class')
                    }
                    //Replace the classes dir in the test classpath with the instrumented one
                    sourceSets.test.runtimeClasspath -= files(sourceSets[sourceSetName].output.classesDirs[0])
                    sourceSets.test.runtimeClasspath += files(instrumentedClassedDir)
                    instrumented = true
                }
            }
            if (instrumented) {
                //Disable class verification based on https://github.com/jayway/powermock/issues/375
                test.jvmArgs += '-noverify'
            }
        }
    }
    test.dependsOn doJacocoOfflineInstrumentation
}
</code>```

full example here:
https://github.com/lizardeye/jacocomultimodulesample

Still, I think this is a durty hack, which can be easily broken with gradle or jacoco updates

Body:
I'm testing an app with JUnit5 and using Jacoco for coverage report.
Tests are executed Ok and test reports are present.

However, Jacoco report has the following logs if service contains methods, annotated with @Transactional

[ant:jacocoReport] Classes in bundle 'my-service' do no match with execution data. For report generation the same class files must be used as at runtime.
[ant:jacocoReport] Execution data for class mypackage/SampleService does not match.

This error occurres for all @Service classes methods, annotated with @Transactional, plain classes coverage is calculated ok.

Here's a sample test:

@SpringBootTest
@ExtendWith(SpringExtension.class)
public class MyServiceTest {

    @Autowired
    private SampleService sampleService;

    @Test
    public void doWork(){
        sampleService.doWork();
    }
}

Works fine. Coverage is non-zero:

public class SampleService {

    public void doWork(){
        System.out.println("HEY");
    }
}

0% coverage:

public class SampleService {

    @Transactional
    public void doWork(){
        System.out.println("HEY");
    }
}

Transactional creates a proxy around actuall class. But, isn't there an out-of-box way for Jacoco  to handle such a common situation?

I've tried @EnableAspectJAutoProxy annotaion with different flag variations, checked that up-to-date Jupiter engine and Jacoco plugin are used

Here's gradle config:

subprojects {
    test {
        useJUnitPlatform()
    }

    jacocoTestReport {
        afterEvaluate {
            classDirectories.from = files(classDirectories.files.collect {
                fileTree(dir: it, exclude: '*Test.java')
            })
        }

        reports {
            html.enabled = true
            xml.enabled = true
            csv.enabled = false
        }
    }
}

Any help appreciated

Body:
Based on single module instrumentation example https://stackoverflow.com/a/31916686/7096763 (and updated version for gradle 5+ by  @MikaelF) here's example for multimodule instrumentation:

subprojects {  subproject ->
    subproject.ext.jacocoOfflineSourceSets = [ 'main' ]
    task doJacocoOfflineInstrumentation(dependsOn: [ classes, subproject.configurations.jacocoAnt ]) {
        inputs.files classes.outputs.files
        File outputDir = new File(subproject.buildDir, 'instrumentedClasses')
        outputs.dir outputDir
        doFirst {
            project.delete(outputDir)
            ant.taskdef(
                    resource: 'org/jacoco/ant/antlib.xml',
                    classpath: subproject.configurations.jacocoAnt.asPath,
                    uri: 'jacoco'
            )
            def instrumented = false
            jacocoOfflineSourceSets.each { sourceSetName ->
                if (file(sourceSets[sourceSetName].output.classesDirs[0]).exists()) {
                    def instrumentedClassedDir = "${outputDir}/${sourceSetName}"
                    ant.'jacoco:instrument'(destdir: instrumentedClassedDir) {
                        fileset(dir: sourceSets[sourceSetName].output.classesDirs[0], includes: '**/*.class')
                    }
                    //Replace the classes dir in the test classpath with the instrumented one
                    sourceSets.test.runtimeClasspath -= files(sourceSets[sourceSetName].output.classesDirs[0])
                    sourceSets.test.runtimeClasspath += files(instrumentedClassedDir)
                    instrumented = true
                }
            }
            if (instrumented) {
                //Disable class verification based on https://github.com/jayway/powermock/issues/375
                test.jvmArgs += '-noverify'
            }
        }
    }
    test.dependsOn doJacocoOfflineInstrumentation
}

full example here:
https://github.com/lizardeye/jacocomultimodulesample

Still, I think this is a durty hack, which can be easily broken with gradle or jacoco updates


来源: stackexchange

问:
Insert a node at specific position in a linked list in C (only)
Can anyone help me where I'm going wrong please !!!, I'm a beginner to programming, I'm new to DSA, I'm not able to find my mistake, here is the code please go through it:

This is the outline of my question, hope it is clear! :)

```<code>
sample input : 3 16 13 7 1 2
3 is the number of elements to input into a linked list
so 16 13 7 are elements of the linked list initially
1 is the element I'm interested to insert
2 is the position where I want to insert the element 1
so the expected output will be:
sample output: 16 13 1 7
</code>```

The problem I'm facing :

```<code>
The output I'm getting is: 13 1 7
So the problem is not every element in the list is getting returned, please help !!!
</code>```

This is the code I tried, any suggestions are encouraged, :)

```<code>   struct SinglyLinkedListNode
  {
        int data;
        SinglyLinkedListNode* next;
  };

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position)
{
    int i = 0;
    SinglyLinkedListNode *pcurr, *pnew;

    pnew = (SinglyLinkedListNode*)malloc(sizeof(SinglyLinkedListNode));
    if(position == 0)
    {
        pnew->data = data;
        pnew->next = head->next;
        head = pnew;
        return head;
    }
    if(head == NULL)
    {
        pnew ->data = data;
        return pnew;
    }
    else
    {
        do
        {
            pcurr = head;
            pcurr = pcurr->next;
            head = head->next;
            i++;
        }
        while (i != position-1);
        pnew->next = pcurr->next;
        pnew->data = data;
        pcurr->next = pnew;
        return head;
    }
}
</code>```

I would be glad if anyone suggests a good visualising platform for viewing our code line by line especially for c , just like in python.

答:
There were a few issues and the code is actually much simpler.

You were doing malloc twice instead of only once, so you were leaking memory on each call.

Don't cast malloc:. See: Do I cast the result of malloc?

SinglyLinkedListNode is a bit long. When used in a lot of places, this doesn't scale well. How about something shorter like Node or SlNode

Here's a refactored version:

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

typedef struct node Node;
struct node {
    int data;
    Node *next;
};

Node *
insertNodeAtPosition(Node *head, int data, int position)
{
    int i = 0;
    Node *prev;
    Node *pcurr;
    Node *pnew;

    pnew = malloc(sizeof(Node));
    pnew->data = data;

    // find the correct place to insert
    prev = NULL;
    for (pcurr = head;  pcurr != NULL;  pcurr = pcurr->next, i += 1) {
        if (i >= position)
            break;
        prev = pcurr;
    }

    // link up the element that will follow the new node
    pnew->next = pcurr;

    // insert into middle or end of list
    if (prev != NULL)
        prev->next = pnew;

    // insert into empty list or _before_ the first node
    else
        head = pnew;

    return head;
}

void
printlist(Node *head)
{
    Node *pcurr;

    printf("List:");

    for (pcurr = head;  pcurr != NULL;  pcurr = pcurr->next)
        printf(" %d",pcurr->data);

    printf("\n");
}

int
main(void)
{
    FILE *fi;
    Node *head = NULL;
    int count;
    int newval;
    int pos;

    fi = fopen("input.txt","r");
    if (fi == NULL) {
        perror("input.txt");
        exit(1);
    }

    fscanf(fi," %d",&count);

    for (int i = 0;  i < count;  ++i) {
        fscanf(fi," %d",&newval);
        printf("new: %d\n",newval);
        head = insertNodeAtPosition(head,newval,count + 10);
    }
    printlist(head);

    while (1) {
        if (fscanf(fi," %d %d",&newval,&pos) != 2)
            break;
        printf("insert: %d at %d\n",newval,pos);
        head = insertNodeAtPosition(head,newval,pos);
    }
    printlist(head);

    fclose(fi);

    return 0;
}
</code>```

Here's the test file: input.txt:

```<code>3
16 13 7
1 2
9 0
8 0
</code>```

Here is the program output:

```<code>new: 16
new: 13
new: 7
List: 16 13 7
insert: 1 at 2
insert: 9 at 0
insert: 8 at 0
List: 8 9 16 13 1 7
</code>```

UPDATE:

can you also tell me why we have to use a pointer *prev? why only pcurr and pnew are not sufficient? It would help me in learning this new concept being a beginner.

Sure. If we're inserting at the head of the list because the list is empty or we want to insert at the head (i.e. we want a new head even if we have other nodes in the list), we adjust head.

But, if we're inserting in the middle of the list or appending to the end of the list, we need to know what the previous node is.

Consider that we're trying to append to the end of the list. We need to know the existing/prior tail [last element] of the list. If we have:

```<code>head | node1 | node2 | node3
</code>```

Then, node3 is the tail of the list. node3->next will be NULL. To append, we create the new node (pnew) and we have to set node3->next = pnew, so we get:

```<code>head | node1 | node2 | node3 | pnew
                       prev
</code>```

Here, prev will end up having the value of node3, so setting prev->next = pnew is just like setting node3->next = pnew. Note that when appending to the end, pcurr will be NULL.

We call it prev because it (the previous node) can also be any node that we wish to insert after, even if prev is in the middle of the list (e.g. node2). That would look like (before the insertion):

```<code>head | node1 | node2 | node3
               prev    pcurr
</code>```

After the insertion, we want:

```<code>head | node1 | node2 | pnew | node3
               prev           pcurr
</code>```

In this case, pcurr will be node3 (i.e. prev->next).

So, prev points to the node just prior to where we want to insert pnew and pcurr points to the node just after where we want to insert pnew.

In other words, after insertion, prev is the node just to the left of pnew (i.e. the node that precedes it). pcurr is the node just to the right of pnew (i.e. the node that follows it). If pcurr is null, there is no following node, but setting pnew->next = pcurr works in all cases, regardless of the values of head or prev being null or not.

If prev ends up being NULL, this means that the list is either empty or we wish to insert pnew at the head/front of the list. In that case, we can't try to dereference [a null] prev, so we just set head to pnew. Then, we're returning an updated head pointer.

There are several possible list states and insertion operations:

list is empty (adjust the head)

we want to insert the new node before the head of the [non-empty] list (adjust the head)

we want to insert the new node somewhere in the middle of the list

we want to append the new node at the end of the list (adjust tail or head if tail is null)

I think it would be helpful for you to diagram each of these separate cases using pencil and paper. Then, verify, by hand, that the code handles each of these cases, even if the list has prior elements or is empty.

The important thing to note about the above code is that it uses variables that work for several different cases, using the same code path, minimizing the number of if/else clauses to handle the various edge cases in a uniform way.

The type of simplification I did occurs again and again when coding. Thoroughly understanding what was done and why will help you immeasurably in the future.

Any one function that one writes, by itself, may not seem like much. But, magnify this across hundreds or thousands of functions, and it will pay dividends far beyond the initial extra work.

A maxim: As simple as it needs to be--and no simpler

The simpler (i.e. the cleaner) the code, the more likely it is to be correct, complete, and the easier it is to check for correctness. Contrary to popular belief, I've also found that the simpler code also tends to be faster.

ContentLicense: CC BY-SA 4.0

Body:
Can anyone help me where I'm going wrong please !!!, I'm a beginner to programming, I'm new to DSA, I'm not able to find my mistake, here is the code please go through it:

This is the outline of my question, hope it is clear! :)

sample input : 3 16 13 7 1 2
3 is the number of elements to input into a linked list
so 16 13 7 are elements of the linked list initially
1 is the element I'm interested to insert
2 is the position where I want to insert the element 1
so the expected output will be:
sample output: 16 13 1 7

The problem I'm facing :

The output I'm getting is: 13 1 7
So the problem is not every element in the list is getting returned, please help !!!

This is the code I tried, any suggestions are encouraged, :)

   struct SinglyLinkedListNode
  {
        int data;
        SinglyLinkedListNode* next;
  };

    SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position)
{
    int i = 0;
    SinglyLinkedListNode *pcurr, *pnew;

    pnew = (SinglyLinkedListNode*)malloc(sizeof(SinglyLinkedListNode));
    if(position == 0)
    {
        pnew->data = data;
        pnew->next = head->next;
        head = pnew;
        return head;
    }
    if(head == NULL)
    {
        pnew ->data = data;
        return pnew;
    }
    else
    {
        do
        {
            pcurr = head;
            pcurr = pcurr->next;
            head = head->next;
            i++;
        }
        while (i != position-1);
        pnew->next = pcurr->next;
        pnew->data = data;
        pcurr->next = pnew;
        return head;
    }
}

I would be glad if anyone suggests a good visualising platform for viewing our code line by line especially for c , just like in python.

Body:
There were a few issues and the code is actually much simpler.

You were doing malloc twice instead of only once, so you were leaking memory on each call.

Don't cast malloc:. See: Do I cast the result of malloc?

SinglyLinkedListNode is a bit long. When used in a lot of places, this doesn't scale well. How about something shorter like Node or SlNode

Here's a refactored version:

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

typedef struct node Node;
struct node {
    int data;
    Node *next;
};

Node *
insertNodeAtPosition(Node *head, int data, int position)
{
    int i = 0;
    Node *prev;
    Node *pcurr;
    Node *pnew;

    pnew = malloc(sizeof(Node));
    pnew->data = data;

    // find the correct place to insert
    prev = NULL;
    for (pcurr = head;  pcurr != NULL;  pcurr = pcurr->next, i += 1) {
        if (i >= position)
            break;
        prev = pcurr;
    }

    // link up the element that will follow the new node
    pnew->next = pcurr;

    // insert into middle or end of list
    if (prev != NULL)
        prev->next = pnew;

    // insert into empty list or _before_ the first node
    else
        head = pnew;

    return head;
}

void
printlist(Node *head)
{
    Node *pcurr;

    printf("List:");

    for (pcurr = head;  pcurr != NULL;  pcurr = pcurr->next)
        printf(" %d",pcurr->data);

    printf("\n");
}

int
main(void)
{
    FILE *fi;
    Node *head = NULL;
    int count;
    int newval;
    int pos;

    fi = fopen("input.txt","r");
    if (fi == NULL) {
        perror("input.txt");
        exit(1);
    }

    fscanf(fi," %d",&count);

    for (int i = 0;  i < count;  ++i) {
        fscanf(fi," %d",&newval);
        printf("new: %d\n",newval);
        head = insertNodeAtPosition(head,newval,count + 10);
    }
    printlist(head);

    while (1) {
        if (fscanf(fi," %d %d",&newval,&pos) != 2)
            break;
        printf("insert: %d at %d\n",newval,pos);
        head = insertNodeAtPosition(head,newval,pos);
    }
    printlist(head);

    fclose(fi);

    return 0;
}

Here's the test file: input.txt:

3
16 13 7
1 2
9 0
8 0

Here is the program output:

new: 16
new: 13
new: 7
List: 16 13 7
insert: 1 at 2
insert: 9 at 0
insert: 8 at 0
List: 8 9 16 13 1 7

UPDATE:

can you also tell me why we have to use a pointer *prev? why only pcurr and pnew are not sufficient? It would help me in learning this new concept being a beginner.

Sure. If we're inserting at the head of the list because the list is empty or we want to insert at the head (i.e. we want a new head even if we have other nodes in the list), we adjust head.

But, if we're inserting in the middle of the list or appending to the end of the list, we need to know what the previous node is.

Consider that we're trying to append to the end of the list. We need to know the existing/prior tail [last element] of the list. If we have:

head | node1 | node2 | node3

Then, node3 is the tail of the list. node3->next will be NULL. To append, we create the new node (pnew) and we have to set node3->next = pnew, so we get:

head | node1 | node2 | node3 | pnew
                       prev

Here, prev will end up having the value of node3, so setting prev->next = pnew is just like setting node3->next = pnew. Note that when appending to the end, pcurr will be NULL.

We call it prev because it (the previous node) can also be any node that we wish to insert after, even if prev is in the middle of the list (e.g. node2). That would look like (before the insertion):

head | node1 | node2 | node3
               prev    pcurr

After the insertion, we want:

head | node1 | node2 | pnew | node3
               prev           pcurr

In this case, pcurr will be node3 (i.e. prev->next).

So, prev points to the node just prior to where we want to insert pnew and pcurr points to the node just after where we want to insert pnew.

In other words, after insertion, prev is the node just to the left of pnew (i.e. the node that precedes it). pcurr is the node just to the right of pnew (i.e. the node that follows it). If pcurr is null, there is no following node, but setting pnew->next = pcurr works in all cases, regardless of the values of head or prev being null or not.

If prev ends up being NULL, this means that the list is either empty or we wish to insert pnew at the head/front of the list. In that case, we can't try to dereference [a null] prev, so we just set head to pnew. Then, we're returning an updated head pointer.

There are several possible list states and insertion operations:

list is empty (adjust the head)

we want to insert the new node before the head of the [non-empty] list (adjust the head)

we want to insert the new node somewhere in the middle of the list

we want to append the new node at the end of the list (adjust tail or head if tail is null)

I think it would be helpful for you to diagram each of these separate cases using pencil and paper. Then, verify, by hand, that the code handles each of these cases, even if the list has prior elements or is empty.

The important thing to note about the above code is that it uses variables that work for several different cases, using the same code path, minimizing the number of if/else clauses to handle the various edge cases in a uniform way.

The type of simplification I did occurs again and again when coding. Thoroughly understanding what was done and why will help you immeasurably in the future.

Any one function that one writes, by itself, may not seem like much. But, magnify this across hundreds or thousands of functions, and it will pay dividends far beyond the initial extra work.

A maxim: As simple as it needs to be--and no simpler

The simpler (i.e. the cleaner) the code, the more likely it is to be correct, complete, and the easier it is to check for correctness. Contrary to popular belief, I've also found that the simpler code also tends to be faster.


问:
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?</p>

答: You can't have next and prev on each item - std::list is not an intrusive container. If you really don't want to use iterators (why?), you can get to each item by calling front() and then removing it by pop_front() until there are no more items in the list.</p>

ContentLicense: CC BY-SA 3.0


问:
How to lookup the value of a dictionary inside a dictionary in C#?
I have this transitionMap: Dictionary<Dictionary<int, char>, int> transitionMap;

And I also have this dictionary: Dictionary<int, char> dictionary = new Dictionary<int, char> {{0, 'a'}};.

How do I get the value inside transitionMap that corresponds to dictionary1.

This is what I've tried:

```<code>        Dictionary<int, char> dictionary = new Dictionary<int, char> {{stateNum, symbol}};

        if (this.transitionMap.ContainsKey(dictionary))
        {
            int nextState = this.transitionMap[dictionary];
            Console.WriteLine("nextstate {0}", nextState);
        }
</code>```

答:
Solution with Linq :

class Program
{
    static void Main(string[] args)
    {
        var transitionMap = new Dictionary<Dictionary<int, char>, int>();
        var dictionary = new Dictionary<int, char> { { stateNum, symbol } };

        ...

        var found = transitionMap.Keys.FirstOrDefault(d => Equal(d, dictionary));
        if(found == null)
        {
            int nextState = transitionMap[found];
            Console.WriteLine("nextstate {0}", nextState);
        }
    }

    static bool Equal(Dictionary<int, char> a, Dictionary<int, char> b)
    {
        return a.Count == b.Count && a.All(akv => b.TryGetValue(akv.Key, out char bval) && akv.Value == bval);
    }
}
```

Body:
I have this transitionMap: Dictionary<Dictionary<int, char>, int> transitionMap;

And I also have this dictionary: Dictionary<int, char> dictionary = new Dictionary<int, char> {{0, 'a'}};.

How do I get the value inside transitionMap that corresponds to dictionary1.

This is what I've tried:

        Dictionary<int, char> dictionary = new Dictionary<int, char> {{stateNum, symbol}};

        if (this.transitionMap.ContainsKey(dictionary))
        {
            int nextState = this.transitionMap[dictionary];
            Console.WriteLine("nextstate {0}", nextState);
        }


问:
Flask template inheritance - not executing but no errors
I'm learning about template inheritance and I'm a little confused. When I navigate to index.html, I want the title to appear on the tab in my browser. And I want this functionality to be built into the base.html file, which I'm inheriting from, such that the function index on app.py need only be passed the argument title (and the html file name) to execute as described above.

For some reason, the code is not functioning as intended; the title is not present on the browser tab.

app.py:

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',title='index')

if __name__ == "__main__":
    app.run(debug=True)
</code>```

index.html:

<!DOCTYPE html>
{%extends "base.html"%}

    <meta charset="utf-8">

```

<p>base.html:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
</code>```

Both index.html and base.html are found in the templates folder as is necessary for jinja to function. No errors are being triggered, the title is simply not being formatted as intended.

What am I doing wrong?

答:
Your base.html has two <title> tags. Which isn't valid html.
You'll want to remove the empty one and allow for the title to be passed as an argument in all cases.

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title> <!-- Remove this line here! -->
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
</code>```

Body:
I'm learning about template inheritance and I'm a little confused. When I navigate to index.html, I want the title to appear on the tab in my browser. And I want this functionality to be built into the base.html file, which I'm inheriting from, such that the function index on app.py need only be passed the argument title (and the html file name) to execute as described above.

For some reason, the code is not functioning as intended; the title is not present on the browser tab.

app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',title='index')

if __name__ == "__main__":
    app.run(debug=True)

index.html:

<!DOCTYPE html>
{%extends "base.html"%}

    <meta charset="utf-8">

base.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}

    {%block body%}{%endblock%}

Both index.html and base.html are found in the templates folder as is necessary for jinja to function. No errors are being triggered, the title is simply not being formatted as intended.

What am I doing wrong?

Body:
Your base.html has two <title> tags. Which isn't valid html.
You'll want to remove the empty one and allow for the title to be passed as an argument in all cases.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title> <!-- Remove this line here! -->
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>


问:
Side-by-Side Boxplots in Altair
I have this dataframe:

df = pd.DataFrame(np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9],
                            [4, 7, 10], [5, 8, 11]
                            ]), columns=['a', 'b', 'c'])

```

How would I create side by side boxplots in Altair for each variable?

答:
You have wide-form data, while Altair works best with long-form data. For a discussion of this, see Long-Form vs. Wide-Form Data in the Altair docs.

You can reshape your data either in pandas using the pd.melt function (as demonstrated in @chthonicdaemon's answer), or you can use Altair's Fold Transform to reshape the data within your chart specification.

Here is an example of the transform-based approach:

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

df = pd.DataFrame(np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9],
                            [4, 7, 10], [5, 8, 11]
                            ]), columns=['a', 'b', 'c'])

alt.Chart(df).transform_fold(
    ['a', 'b', 'c'],
    as_=['key', 'value']
).mark_boxplot().encode(
    x='key:N',
    y='value:Q'
)
</code>```

Title: Side-by-Side Boxplots in Altair

Body:
I have this dataframe:

df = pd.DataFrame(np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9],
                            [4, 7, 10], [5, 8, 11]
                            ]), columns=['a', 'b', 'c'])

How would I create side by side boxplots in Altair for each variable?

Body:
You have wide-form data, while Altair works best with long-form data. For a discussion of this, see Long-Form vs. Wide-Form Data in the Altair docs.

You can reshape your data either in pandas using the pd.melt function (as demonstrated in @chthonicdaemon's answer), or you can use Altair's Fold Transform to reshape the data within your chart specification.

Here is an example of the transform-based approach:

import altair as alt
import pandas as pd
import numpy as np

df = pd.DataFrame(np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9],
                            [4, 7, 10], [5, 8, 11]
                            ]), columns=['a', 'b', 'c'])

alt.Chart(df).transform_fold(
    ['a', 'b', 'c'],
    as_=['key', 'value']
).mark_boxplot().encode(
    x='key:N',
    y='value:Q'
)


问:
Halcon - Inverse of image_points_to_world_plane
with image_points_to_world_plane I pass Row/Col coordinates in Pixel and get a coordinate back in mm referred to the world plane..

Is there way to invert this? I need for example to know what Row/Col pixel contains the 0/0 coordinate of the world plane. so for example I give it a coordinate from the world plane and it tells me in what pixel of the image I can find this.

Can this be done?

答: First try and use "cam_par_pose_to_hom_mat3d" to first create a matrix which can map world points to image points. Then try using the instruction "project_point_hom_mat3d" to convert your world point to the image plane. </p>


问:
specifying the length of string in Yii migration
I wish to create a migration whose up method will execute the create_table function.

For example :

```
class m101129_185401_create_news_table extends CDbMigration
{
    public function up()
    {
        $this->createTable('tbl_news', array(
            'id' => 'pk',
            'title' => 'string NOT NULL',
            'content' => 'text',
        ));
    }

    public function down()
    {
        $this->dropTable('tbl_news');
    }
}
```

How do I specify the length of a field  in the migration ? Eg. What would I write if I have to specify that length of the title field should be 100 .

答:
Hey! I believe this was an addition they did last year. I havent tried it, but doesn't this work?

```<code>public function up()
{
    $this->createTable('tbl_news', array(
        'id' => 'pk',
        'title' => 'varchar(20) NOT NULL',
        'content' => 'text',
    ));
}
</code>```

Also, in this site you'll find information which can be helpful, as well as here. Good luck with this!

Body:
I wish to create a migration whose up method will execute the create_table function.

For example :

class m101129_185401_create_news_table extends CDbMigration
{
    public function up()
    {
        $this->createTable('tbl_news', array(
            'id' => 'pk',
            'title' => 'string NOT NULL',
            'content' => 'text',
        ));
    }

    public function down()
    {
        $this->dropTable('tbl_news');
    }
}

How do I specify the length of a field  in the migration ? Eg. What would I write if I have to specify that length of the title field should be 100 .

Body:
Hey! I believe this was an addition they did last year. I havent tried it, but doesn't this work?

public function up()
{
    $this->createTable('tbl_news', array(
        'id' => 'pk',
        'title' => 'varchar(20) NOT NULL',
        'content' => 'text',
    ));
}

Also, in this site you'll find information which can be helpful, as well as here. Good luck with this!


问:
Feed Python Kubernetes client with heredoc instead of filepath
Is there a simple way to create a configuration object for the Python Kubernetes client by passing a variable containing the YAML of the kubeconfig?

It's fairly easy to do something like:

```<code>from kubernetes import client, config, watch
def main():
    config.load_kube_config()
</code>```

or

```<code>from kubernetes import client, config, watch
def main():
    config.load_incluster_config()
</code>```

But I will like to create the config based on a variable with the YAML kubeconfig, Let's say I have:

```<code>k8s_config = yaml.safe_load('''
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://asdf.asdf:443
  name: cluster
contexts:
- context:
    cluster: cluster
    user: admin
  name: admin
current-context: admin
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate-data: LS0tVGYUZiL2sxZlRFTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    client-key-data: LS0tLS1CRUdJTiBSU0EgU0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=
''')
</code>```

And I will like to load it as:

```<code>config.KubeConfigLoader(k8s_config)
</code>```

The reason for this is that I can't store the content of the kubeconfig before loading the config.

The error I'm receiving is: "Error: module 'kubernetes.config' has no attribute 'KubeConfigLoader'"

答:
They don't include KubeConfigLoader in the "pull up" inside config/__init__.py, which is why your kubernetes.config.KubeConfigLoader reference isn't working. You will have to reach into the implementation package and reference the class specifically:

from kubernetes.config.kube_config import KubeConfigLoader

k8s_config = yaml.safe_load('''...''')
config = KubeConfigLoader(
    config_dict=k8s_config,
    config_base_path=None)
```

Be aware that unlike most of my answers, I didn't actually run this one, but that's the theory

Body:
Is there a simple way to create a configuration object for the Python Kubernetes client by passing a variable containing the YAML of the kubeconfig?

It's fairly easy to do something like:

from kubernetes import client, config, watch
def main():
    config.load_kube_config()

or

from kubernetes import client, config, watch
def main():
    config.load_incluster_config()

But I will like to create the config based on a variable with the YAML kubeconfig, Let's say I have:

k8s_config = yaml.safe_load('''
apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://asdf.asdf:443
  name: cluster
contexts:
- context:
    cluster: cluster
    user: admin
  name: admin
current-context: admin
kind: Config
preferences: {}
users:
- name: admin
  user:
    client-certificate-data: LS0tVGYUZiL2sxZlRFTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    client-key-data: LS0tLS1CRUdJTiBSU0EgU0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=
''')

And I will like to load it as:

config.KubeConfigLoader(k8s_config)

The reason for this is that I can't store the content of the kubeconfig before loading the config.

The error I'm receiving is: "Error: module 'kubernetes.config' has no attribute 'KubeConfigLoader'"

Body:
They don't include KubeConfigLoader in the "pull up" inside config/__init__.py, which is why your kubernetes.config.KubeConfigLoader reference isn't working. You will have to reach into the implementation package and reference the class specifically:

from kubernetes.config.kube_config import KubeConfigLoader

k8s_config = yaml.safe_load('''...''')
config = KubeConfigLoader(
    config_dict=k8s_config,
    config_base_path=None)

Be aware that unlike most of my answers, I didn't actually run this one, but that's the theory


问:
Stubbing and/or spying on an optional global function: Sinon, mocha & chai
I have a method that checks whether or not a global function is defined (it may or may not be available, depends on each client's request).  If it is defined, it will call it with the appropriate data. If not, it will fail silently. That's the desired behavior.

What I want to do is test it. Is there a way to mock and/or spy on libFunction so that I can ensure it's being called once with the correct data (the function here is very much simplified, there's some data processing that happens along the way).

Here's the method in question:

```<code>function sendData(data) {
  let exists;
  try {
    // eslint-disable-next-line no-undef
    if (libFunction) exists = true;
  } catch (e) {
    exists = false;
  }
  if (exists) {
    // eslint-disable-next-line no-undef
    libFunction(data);
  }
}
</code>```

I've tried defining libFunction in my tests and then stubbing that, but that doesn't do what I want:

```<code>describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var stub = sinon.stub(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(stub.called).to.be.true;
  });
});
</code>```

This test does not pass, however: AssertionError: expected undefined to be true

I've tried something similar with a spy:

```<code>describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var spy = sinon.spy(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(spy.called).to.be.true;
  });
});
</code>```

This also fails: AssertionError: expected false to be true

Is there a way to do this?

答:
FWIW, I came across this question while trying to solve an issue for stubbing a global method in Node.  In my case, this worked (my example uses Sinon.sandbox, but "regular" Sinon.spy should work, as well):

```<code>    const encodeSpy = sandbox.spy(global, "encodeURIComponent");
   // later...
   Sinon.assert.calledWith(encodeSpy, {expectedParamValue});
</code>```

Body:
I have a method that checks whether or not a global function is defined (it may or may not be available, depends on each client's request).  If it is defined, it will call it with the appropriate data. If not, it will fail silently. That's the desired behavior.

What I want to do is test it. Is there a way to mock and/or spy on libFunction so that I can ensure it's being called once with the correct data (the function here is very much simplified, there's some data processing that happens along the way).

Here's the method in question:

function sendData(data) {
  let exists;
  try {
    // eslint-disable-next-line no-undef
    if (libFunction) exists = true;
  } catch (e) {
    exists = false;
  }
  if (exists) {
    // eslint-disable-next-line no-undef
    libFunction(data);
  }
}

I've tried defining libFunction in my tests and then stubbing that, but that doesn't do what I want:

describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var stub = sinon.stub(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(stub.called).to.be.true;
  });
});

This test does not pass, however: AssertionError: expected undefined to be true

I've tried something similar with a spy:

describe('sendEvent', function () {

  function libFunction(data) {
    console.log('hi', data);
  }

  it('should call libFunction once', function () {
    var spy = sinon.spy(libFunction);
    var data = "testing";
    sendEvent(data);
    expect(spy.called).to.be.true;
  });
});

This also fails: AssertionError: expected false to be true

Is there a way to do this?

Body:
FWIW, I came across this question while trying to solve an issue for stubbing a global method in Node.  In my case, this worked (my example uses Sinon.sandbox, but "regular" Sinon.spy should work, as well):

    const encodeSpy = sandbox.spy(global, "encodeURIComponent");
   // later...
   Sinon.assert.calledWith(encodeSpy, {expectedParamValue});


问:
How can I add an ampersand for a value in a ASP.net/C# app config file value
I've got a C# program with values in a config file.  What I want is to store ampersands for an url value like...

```<code><appSettings>
  <add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
</appSettings>
</code>```

But I get errors building my site.  The ampersand is not allowed.  I've tried various forms of escaping the ampersands to no avail.  Anyone know of the correct form to do this?  All suggestions are welcome.

答: Although the accepted answer here is technically correct, there seems to be some confusion amongst users based on the comments.  When working with a ViewBag in a .cshtml file, you must use @Html.Raw otherwise your data, after being unescaped by the ConfigurationManager, will become re-escaped once again.  Use Html.Raw() to prevent this from occurring.

OwnerDisplayName: Rob Segal

ContentLicense: CC BY-SA 2.5

Body:
I've got a C# program with values in a config file.  What I want is to store ampersands for an url value like...

<appSettings>
  <add key="myurl" value="http://www.myurl.com?&cid=&sid="/>
</appSettings>

But I get errors building my site.  The ampersand is not allowed.  I've tried various forms of escaping the ampersands to no avail.  Anyone know of the correct form to do this?  All suggestions are welcome.


问:
How to change the attribute value in class without calling the method in Python?
I was doing this Pokemon project on Codecademy, and it asked me to do something that I was completely unable to think of, as I don't have much practice on OOPS and python.

How can I set is_knocked_out = True, without calling any method on my instance? I think that my code should know automatically when the health of pokemon has become zero and automatically change its attribute is_knocked_out to True.
I searched online but didn’t find any definitive solution maybe it has something to do with decorators.

Can someone please explain me how to do this, because I think I might have hit a wall here.

I have written the following code so far:

```<code>class Pokemon:

    def __init__(self,name,level,ptype,is_knocked_out= False):
        self.name = name
        self.level = level
        self.type = ptype
        self.max_health = level
        self.curr_health = max_health
        self.is_knocked_out = is_knocked_out

    def lose_health(self,loss_amount):
        self.curr_health -= loss_amount
        print(f"{self.name} has now health of {self.curr_health}")

    def regain_health(self,gain_amount):
        self.curr_health += gain_amount
        print(f"{self.name} has now health of {self.curr_health}")

    #@property
    def knock_out(self):
        if self.curr_health <=0:
            self.is_knocked_out = True
            print(f"{self.name} has been knocked out")
</code>```

答:
A good approach is to make is_knocked_out a property so its value can always be computed from curr_health:

```<code>class Pokemon:
    ...

    @property
    def is_knocked_out(self):
        return self.curr_health <= 0
</code>```

Body:
I was doing this Pokemon project on Codecademy, and it asked me to do something that I was completely unable to think of, as I don't have much practice on OOPS and python.

How can I set is_knocked_out = True, without calling any method on my instance? I think that my code should know automatically when the health of pokemon has become zero and automatically change its attribute is_knocked_out to True.
I searched online but didn’t find any definitive solution maybe it has something to do with decorators.

Can someone please explain me how to do this, because I think I might have hit a wall here.

I have written the following code so far:

class Pokemon:

    def __init__(self,name,level,ptype,is_knocked_out= False):
        self.name = name
        self.level = level
        self.type = ptype
        self.max_health = level
        self.curr_health = max_health
        self.is_knocked_out = is_knocked_out

    def lose_health(self,loss_amount):
        self.curr_health -= loss_amount
        print(f"{self.name} has now health of {self.curr_health}")

    def regain_health(self,gain_amount):
        self.curr_health += gain_amount
        print(f"{self.name} has now health of {self.curr_health}")

    #@property
    def knock_out(self):
        if self.curr_health <=0:
            self.is_knocked_out = True
            print(f"{self.name} has been knocked out")

Body:
A good approach is to make is_knocked_out a property so its value can always be computed from curr_health:

class Pokemon:
    ...

    @property
    def is_knocked_out(self):
        return self.curr_health <= 0


问:
Why setter function accepts the same datatype as that of its field in typescript?
I am trying to insert a string value to a private array in a typescript class using a setter function.
In my getter function, intellisense says that the value returned is a type mismatch as mentioned in the code below.

```<code>export class Player{
    constructor(private _skills:string[]){}

    get skills(){
        return this._skills  // Type string not assignable to type string[]
    }

    set skills(newSkill:string){
        this._skills = [...this._skills,newSkill]
    }
}
</code>```

On removing the explicit function parameter type newSkill:string to just newSkill, the above error gets resolved as typescript expects an array of strings to be passed in the setter and not just a string.

We can insert a single string  by enclosing it in an array then merging the passed array with the private array field.

```<code>player.skills = ["single skill"]
</code>```

```<code>export class Player{
    constructor(private _skills:string[]){}

    get skills(){
        return this._skills
    }

    set skills(newSkill){
        this._skills = [...this._skills,...newSkill]
    }
}
</code>```

But why should we pass an array and not just a string to the setter function for situations where we need to insert just one skill value to the skills array at a time and not an array of skills?

Why array of just one string and not just string (as a datatype in the setter function) is the question?

Is it possible to avoid the string array datatype and set it to just a string datatype?

Note:
The requirement is to insert/set one string value at a time and not array of values to the skills array using the set keyword of typescript

答:
Got to know that the setter function always expects the field typed value to be passed into it.

In this case, skills is a string array. So the setter expects a string array as a parameter.

player = new Player(["someskills"])
player.skills = [...somemoreskills] //has to be a string[] and not string

```
<h2>Conclusion:</h2>
<p>setter parameter datatype defaults to field datatype and it appears that its unavoidable to change it to accept <strong>just a string</strong> and <strong>not accept array of strings</strong>.
As a workaround to make a setter work with both string and string[], we could use pipe.</p>
<h2>Workaround: Accepts single string but also accepts an array of strings.</h2>
```set skills(newSkill:string[]|string){
        if(typeof(newSkill)==='string'){
            this._skills = [...this._skills,newSkill]
        }else{
        this._skills = [...this._skills,...newSkill]
        }
    }
```

Suggestions with setting the setter param datatype  as a (string alone) would help!

Body:
I am trying to insert a string value to a private array in a typescript class using a setter function.
In my getter function, intellisense says that the value returned is a type mismatch as mentioned in the code below.

export class Player{
    constructor(private _skills:string[]){}

    get skills(){
        return this._skills  // Type string not assignable to type string[]
    }

    set skills(newSkill:string){
        this._skills = [...this._skills,newSkill]
    }
}

On removing the explicit function parameter type newSkill:string to just newSkill, the above error gets resolved as typescript expects an array of strings to be passed in the setter and not just a string.

We can insert a single string  by enclosing it in an array then merging the passed array with the private array field.

player.skills = ["single skill"]

export class Player{
    constructor(private _skills:string[]){}

    get skills(){
        return this._skills
    }

    set skills(newSkill){
        this._skills = [...this._skills,...newSkill]
    }
}

But why should we pass an array and not just a string to the setter function for situations where we need to insert just one skill value to the skills array at a time and not an array of skills?

Why array of just one string and not just string (as a datatype in the setter function) is the question?

Is it possible to avoid the string array datatype and set it to just a string datatype?

Note:
The requirement is to insert/set one string value at a time and not array of values to the skills array using the set keyword of typescript

Body:
Got to know that the setter function always expects the field typed value to be passed into it.

In this case, skills is a string array. So the setter expects a string array as a parameter.

player = new Player(["someskills"])
player.skills = [...somemoreskills] //has to be a string[] and not string

Conclusion:

setter parameter datatype defaults to field datatype and it appears that its unavoidable to change it to accept just a string and not accept array of strings.
As a workaround to make a setter work with both string and string[], we could use pipe.

Workaround: Accepts single string but also accepts an array of strings.

set skills(newSkill:string[]|string){
        if(typeof(newSkill)==='string'){
            this._skills = [...this._skills,newSkill]
        }else{
        this._skills = [...this._skills,...newSkill]
        }
    }

Suggestions with setting the setter param datatype  as a (string alone) would help!


问:
How to extract values from a dataframe based on dates?
I have a DataFrame (see image below) with daily values of which I want to retrieve a couple of values. I want to retrieve: Monthly mean, Monthly min, Monthly max, Yearly min, Amount of years etc. Currently I am resampling my DataFrame to retrieve these values (see code below) but there must be a better way.

```<code> T_monthly=pd.DataFrame()                                                   # Create dataframe for monthly temperatures
 T_monthly['Basse']=temp_basse.iloc[:,3].resample("M").mean()               # Add Basse
 T_monthly['Basse_min']=temp_basse.iloc[:,3].resample("M").min()
 T_monthly['Basse_max']=temp_basse.iloc[:,3].resample("M").max()

 T_monthly['Kedougou']=temp_kedougou.iloc[:,3].resample("M").mean()         # Add Kedougou
 T_monthly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("M").min()
 T_monthly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("M").max()

 T_yearly=pd.DataFrame()                                                    # Create dataframe for yearly temperatures
 T_yearly['Basse_min']=temp_basse.iloc[:,3].resample("Y").min()
 T_yearly['Basse_max']=temp_basse.iloc[:,3].resample("Y").max()
 T_yearly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("Y").min()
 T_yearly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("Y").max()
</code>```

Preferably I want to have a function where I can put in a date, e.g. 2014, 2 (Y, M) and retrieve all the necessary values without resampling to new DataFrames. For example:

input: (2014, 2)

output: [monthly mean, monthly min, monthly max, yearly min, yearly max]

At the moment my functions make use of the index number of the dataframes (see below). However, if I want to put in a certain date I first need to find the corresponding index number.

```<code> T_monthly.iloc[i, 3]
</code>```

Thanks in advance!

答:
Added two more columns after the sugestion of Sowjanya R Bhat, containing ['year'] and ['month']

```<code> df['year'] = pd.DatetimeIndex(df['date']).year
 df['month'] = pd.DatetimeIndex(df['date']).month
</code>```

Next selecting data by:

```<code> df.loc[(df['year'] == year) & (df['month'] == month)].iloc[:,3]
</code>```

Not exactly how I wanted it (based on index), but great for looping through the data with the functions I wrote.

Body:
I have a DataFrame (see image below) with daily values of which I want to retrieve a couple of values. I want to retrieve: Monthly mean, Monthly min, Monthly max, Yearly min, Amount of years etc. Currently I am resampling my DataFrame to retrieve these values (see code below) but there must be a better way.

 T_monthly=pd.DataFrame()                                                   # Create dataframe for monthly temperatures
 T_monthly['Basse']=temp_basse.iloc[:,3].resample("M").mean()               # Add Basse
 T_monthly['Basse_min']=temp_basse.iloc[:,3].resample("M").min()
 T_monthly['Basse_max']=temp_basse.iloc[:,3].resample("M").max()

 T_monthly['Kedougou']=temp_kedougou.iloc[:,3].resample("M").mean()         # Add Kedougou
 T_monthly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("M").min()
 T_monthly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("M").max()

 T_yearly=pd.DataFrame()                                                    # Create dataframe for yearly temperatures
 T_yearly['Basse_min']=temp_basse.iloc[:,3].resample("Y").min()
 T_yearly['Basse_max']=temp_basse.iloc[:,3].resample("Y").max()
 T_yearly['Kedougou_min']=temp_kedougou.iloc[:,3].resample("Y").min()
 T_yearly['Kedougou_max']=temp_kedougou.iloc[:,3].resample("Y").max()

Preferably I want to have a function where I can put in a date, e.g. 2014, 2 (Y, M) and retrieve all the necessary values without resampling to new DataFrames. For example:

input: (2014, 2)

output: [monthly mean, monthly min, monthly max, yearly min, yearly max]

At the moment my functions make use of the index number of the dataframes (see below). However, if I want to put in a certain date I first need to find the corresponding index number.

 T_monthly.iloc[i, 3]

Thanks in advance!

Body:
Added two more columns after the sugestion of Sowjanya R Bhat, containing ['year'] and ['month']

 df['year'] = pd.DatetimeIndex(df['date']).year
 df['month'] = pd.DatetimeIndex(df['date']).month

Next selecting data by:

 df.loc[(df['year'] == year) & (df['month'] == month)].iloc[:,3]

Not exactly how I wanted it (based on index), but great for looping through the data with the functions I wrote.


问:
How does Perl handle password prompts?
I'd like to pass a password through Perl. In my Perl script, it invokes SSH but gets stuck when the terminal is promoted for a password.

I've looked into using NET::SSH::Perl and other libraries but as of now they are not viable options. I just need to SSH into the machine, retrieve a file and leave.

答:
Expect is the standard way to automate applications that talk to /dev/tty as ssh.

Though, as runrig has already pointed out, there are several module available from CPAN specific to SSH. Is there any particular reason because you are unable to use them?

Title: How does Perl handle password prompts?


问:
how to send information from mobile NFC to RFID-RC522 module?
I have a RFID-RC522 module that is connected to arduino micro. I want to send data from NFC of android mobile to that module. is that possible ? and if so, how can I perform that ?</p>

答:
Not possible, this reader barely supports reading/writing to Mifare Classic cards

It does not support Host Card Emulation or Peer to Peer or other standard cards.

A better module based on PN532 chip would be possible.

Check out https://github.com/miguelbalboa/rfid


问:
powershell - split csv into multiple csv by column
I have .csv like that:

but many more lines of course.. (sorry I have added it like picture because text was not able to be formatted correctly)

and I would like to have 4 .csv files like which contains every column separatelly so in x.csv, I will only have data from first column. in y.csv I will have only data from second column (they are separated by ";"

so far I have this code but I'm not able to even loop through columns (looping through rows works..)

```<code>$dataaa = Import-Csv ".\input.csv" -Delimiter ";" | Group ID | %{
    $ID=".\out.csv" -f $_.Name
    $_.Group | export-csv "$CurDir\$ID" -NoType
}

$a=0
echo "$a"

$Results = foreach( $Column in $dataaa ){
$a=$a+1
echo "$a" #echo number of column
#select first column and export into x.csv - have NO idea how to
}

echo "$a"
</code>```

thank you for your help

答:
You can do the following, which allows for any potential column names you may have:

```<code>$csv = Import-Csv -Path input.csv -Delimiter ';'
$properties = (Get-Member -InputObject $csv[0] -MemberType Properties).Name
foreach ($property in $properties) {
    $csv | Select-Object @{n=$property;e={$_.$property}} |
        Export-Csv -LiteralPath "$property.csv" -NoTypeInformation -Delimiter ';'
}
</code>```

Select-Object will need a calculated property here because your property names have wildcard characters. The use of the -LiteralPath switch may be necessary on some commands because of the wildcard characters as well.

Body:
I have .csv like that:

but many more lines of course.. (sorry I have added it like picture because text was not able to be formatted correctly)

and I would like to have 4 .csv files like which contains every column separatelly so in x.csv, I will only have data from first column. in y.csv I will have only data from second column (they are separated by ";"

so far I have this code but I'm not able to even loop through columns (looping through rows works..)

$dataaa = Import-Csv ".\input.csv" -Delimiter ";" | Group ID | %{
    $ID=".\out.csv" -f $_.Name
    $_.Group | export-csv "$CurDir\$ID" -NoType
}

$a=0
echo "$a"

$Results = foreach( $Column in $dataaa ){
$a=$a+1
echo "$a" #echo number of column
#select first column and export into x.csv - have NO idea how to
}

echo "$a"

thank you for your help

Body:
You can do the following, which allows for any potential column names you may have:

$csv = Import-Csv -Path input.csv -Delimiter ';'
$properties = (Get-Member -InputObject $csv[0] -MemberType Properties).Name
foreach ($property in $properties) {
    $csv | Select-Object @{n=$property;e={$_.$property}} |
        Export-Csv -LiteralPath "$property.csv" -NoTypeInformation -Delimiter ';'
}

Select-Object will need a calculated property here because your property names have wildcard characters. The use of the -LiteralPath switch may be necessary on some commands because of the wildcard characters as well.


问:
How to remove or disable the slash at the end of the URL?
I don't know exactly what is the problem, but I have done a lot of research about trailing slash in PHP.

My problem is that when I visit my site I always see trailing slash and it causes all the resources to fail to load.

How do I disable trailing slash that's being added in .htaccess.
Thanks!

答:
The / in a URL indicates a directory on the file systen of your webserver so your request for file.php/ is looking for a directory and not a PHP script file.

A htaccess rewrite so that any directory automatically has a trailing slash appended can be found in the rewrite guide:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R]
</code>```

Body:
The / in a URL indicates a directory on the file systen of your webserver so your request for file.php/ is looking for a directory and not a PHP script file.

A htaccess rewrite so that any directory automatically has a trailing slash appended can be found in the rewrite guide:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [R]


问:
Amazon lex skip a slot based on resolved value of previous slot
I have 7 slots in my amazon lex bot intent.

```<code>{
  slot1: null,
  slot2: null,
  slot3: null,
  slot4: null,
  slot5: null,
  slot6: null,
  slot7: null
}
</code>```

slot2 has 2 values for resolution. Yes or No.

  slot3 has 3 values for resolution.

What I want to achieve is if Yes is selected then display values in slot3 and fullfill the intent.

If No is selected then skip slot3 and proceed with further slots.

Below is the lambda code used for Initialization and validation code hook, do read the comments:

```<code>exports.handler = async(event) => {
  if (event.currentIntent.slots.slot2 != null) {
    if (event.currentIntent.slots.slot4 == null) {
    // handle slot2 "yes" or "no"
      switch (event.currentIntent.slots.slot2) {
        case 'No':
          return {
            dialogAction: {
              type: "ElicitSlot",
              intentName: event.currentIntent.name,
              slots: event.currentIntent.slots,
              slotToElicit: "slot4"

            }
          };
      }
    }

    // If slot2 value is yes and any one of the value from slot3 is selected then fulfill the intent. Alo if you can tell me that we can add some call to action on slot3 value clicks like mailto: or tel: it will be really helpful.
    if (event.currentIntent.slots.slot2 === "Yes" && event.currentIntent.slots.slot3 != null) {
      return {
        dialogAction: {
          type: "Close",
          fulfillmentState: "Fulfilled",
          message: {
            contentType: "PlainText",
            content: "Fullfillment text"
          }
        }
      }
    }

    // here I am trying to remove slot3 from the intent when slot2 value is "no"
    if (event.currentIntent.slots.slot2 === "No" && event.currentIntent.slots.slot4 != null) {
      delete event.currentIntent.slots.slot3;
    }

  }

// default return dialog action
  return {
    dialogAction: {
      type: "Delegate",
      slots: event.currentIntent.slots
    }
  };
};
</code>```

答:
Looks pretty good.

Firstly, don't delete slot3. Basically, anytime you don't need to use a slot, just leave it or set it to null and make sure it is not ticked as required in your Lex console, that's all. If you delete it then your response will no longer match all the slots that Lex expects.

You are using DialogAction: "Delegate", which lets Lex determine which slot to elicit next. So after Lex elicits slot2, I believe Lex will simply choose the next slot. However, Lex may choose the next required slot as priority over non-required slots, so again make sure that slot3 is not ticked as required.

To have better control over your conversation, you may not want to use Delegate at all, and instead, build the conversation logic exactly to your liking, using only ElicitSlot to ensure the correct slots are elicited at the correct points of the conversation.

If I simplify your code it would look like this:

```<code>if slot2 != null
    if slot4 == null
        if slot2 == No
             elicit slot4

    if slot2 == Yes and slot3 != null
        fulfill intent
else
    delegate
</code>```

There are some things you can clean up about that and seeing it this way may shed light on the issue for you but perhaps you have plans to expand it and there's a reason to it for example why you are using switch case with only one case (for now?).

Consider a more straight-forward and controlled approach without delegate:

```<code>if slot1 == null
    elicit slot1
else                             // slot1 filled
    if slot2 == null
        elicit slot2
    else                         // slot2 filled
        (validate slot2 value)
        if slot2 == Yes
            if slot3 == null
                elicit slot3
            else                  // slot3 filled
                (validate slot3 value)
                fulfill intent
        if slot2 == No
             elicit slot4
        ...
</code>```

Body:
I have 7 slots in my amazon lex bot intent.

{
  slot1: null,
  slot2: null,
  slot3: null,
  slot4: null,
  slot5: null,
  slot6: null,
  slot7: null
}

slot2 has 2 values for resolution. Yes or No.

  slot3 has 3 values for resolution.

What I want to achieve is if Yes is selected then display values in slot3 and fullfill the intent.

If No is selected then skip slot3 and proceed with further slots.

Below is the lambda code used for Initialization and validation code hook, do read the comments:

exports.handler = async(event) => {
  if (event.currentIntent.slots.slot2 != null) {
    if (event.currentIntent.slots.slot4 == null) {
    // handle slot2 "yes" or "no"
      switch (event.currentIntent.slots.slot2) {
        case 'No':
          return {
            dialogAction: {
              type: "ElicitSlot",
              intentName: event.currentIntent.name,
              slots: event.currentIntent.slots,
              slotToElicit: "slot4"

            }
          };
      }
    }

    // If slot2 value is yes and any one of the value from slot3 is selected then fulfill the intent. Alo if you can tell me that we can add some call to action on slot3 value clicks like mailto: or tel: it will be really helpful.
    if (event.currentIntent.slots.slot2 === "Yes" && event.currentIntent.slots.slot3 != null) {
      return {
        dialogAction: {
          type: "Close",
          fulfillmentState: "Fulfilled",
          message: {
            contentType: "PlainText",
            content: "Fullfillment text"
          }
        }
      }
    }

    // here I am trying to remove slot3 from the intent when slot2 value is "no"
    if (event.currentIntent.slots.slot2 === "No" && event.currentIntent.slots.slot4 != null) {
      delete event.currentIntent.slots.slot3;
    }

  }

// default return dialog action
  return {
    dialogAction: {
      type: "Delegate",
      slots: event.currentIntent.slots
    }
  };
};

Body:
Looks pretty good.

Firstly, don't delete slot3. Basically, anytime you don't need to use a slot, just leave it or set it to null and make sure it is not ticked as required in your Lex console, that's all. If you delete it then your response will no longer match all the slots that Lex expects.

You are using DialogAction: "Delegate", which lets Lex determine which slot to elicit next. So after Lex elicits slot2, I believe Lex will simply choose the next slot. However, Lex may choose the next required slot as priority over non-required slots, so again make sure that slot3 is not ticked as required.

To have better control over your conversation, you may not want to use Delegate at all, and instead, build the conversation logic exactly to your liking, using only ElicitSlot to ensure the correct slots are elicited at the correct points of the conversation.

If I simplify your code it would look like this:

if slot2 != null
    if slot4 == null
        if slot2 == No
             elicit slot4

    if slot2 == Yes and slot3 != null
        fulfill intent
else
    delegate

There are some things you can clean up about that and seeing it this way may shed light on the issue for you but perhaps you have plans to expand it and there's a reason to it for example why you are using switch case with only one case (for now?).

Consider a more straight-forward and controlled approach without delegate:

if slot1 == null
    elicit slot1
else                             // slot1 filled
    if slot2 == null
        elicit slot2
    else                         // slot2 filled
        (validate slot2 value)
        if slot2 == Yes
            if slot3 == null
                elicit slot3
            else                  // slot3 filled
                (validate slot3 value)
                fulfill intent
        if slot2 == No
             elicit slot4
        ...


问:
Windows MessageBox Display Issue with Cross Thread
I am trying to display error message notification using MessageBox.Show() method. But I am getting Cross thread operation issue. I used the below code. How can I resolve the cross thread issue? I tried with MethodInvoker but it is not solving my issue. Kindly suggest me the guidelines to resolve this issue.

```<code> public static class Notification()
 {

   public static void ShowErrorMessage(IWin32Window owner, String msg)
   {
       MessageBox.Show(owner, msg, Caption+ " - " + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

}
</code>```

Issue :

Cross-thread operation not valid:Control 'MainPage' accessed from a thread other than the thread it was created on.

答:
It seems there is an answer here MessageBox.show() is it not safe to call in worker thread? , though the question is a bit misleading.

Also, this Microsoft documentation page explains in detail how to make thread-safe calls to WinForm controls, and provides you with code examples.

Body:
I am trying to display error message notification using MessageBox.Show() method. But I am getting Cross thread operation issue. I used the below code. How can I resolve the cross thread issue? I tried with MethodInvoker but it is not solving my issue. Kindly suggest me the guidelines to resolve this issue.

 public static class Notification()
 {

   public static void ShowErrorMessage(IWin32Window owner, String msg)
   {
       MessageBox.Show(owner, msg, Caption+ " - " + "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

}

Issue :

Cross-thread operation not valid:Control 'MainPage' accessed from a thread other than the thread it was created on.


问:
HTML style, showing message start from bottom, but cannot be scroll?
I would like to create a surface like wechat.. all message start from bottom, but why it doesn't scroll able? If message start from top, it was scroll able.. but I would like the message start from bottom..

How to improve my script? Thanks.

     var childrens = document.querySelector("#chat").children.length;
     document.querySelector("#chat").childNodes[childrens-1].scrollIntoView() ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="height: 100vh; background-position: top center; width: 100%; max-height: 1366px; position: relative;">
 <div style="height: 40px; background-color: black; color: white; line-height: 40px; position: fixed; top: 0px; width: 100%; z-index: 999" align="right">
  <div style="margin-right: 1em">menu</div>
 </div>
 <div style="bottom:0; background-color: white; color: white; line-height: 50px; position: fixed; width: 100%; height: 50px; z-index: 999; border-top: 1px solid #D3D3D3;" align="right">
  <div style="width: 100%">
   <div style="padding-left:1em; padding-right: 1em;" align="left"><input type="text" style="width: 90%;"><div style="float: right; border: 2px solid grey; height: 20px; margin-top: 0.5em; width: 20px; border-radius: 30px; color: grey; line-height: 20px; font-size: 1.5em;" align="center">+</div></div>
  </div>
 </div>
 <div style="background-color: transparent; color: white; position: absolute; width: 100%; height: 100%; overflow: auto;" align="right">
  <div style="padding-top: 40px; padding-right: 1em; padding-left: 1em; padding-bottom: 60px; position: absolute;">
   <div id="chat" style="width: 100%; color: black; padding-top: 1em; font-size: 12px;">
    <div>First message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Message here</div><div>Last message</div>
   </div>
  </div>
 </div>
</div></code>```

答:
Give id "chat" to parent div of all messages and use this script   </p>

```<code> <script>
     var childrens = document.querySelector("#chat").children.length;
     document.querySelector("#chat").childNodes[childrens-1].scrollIntoView()
 </script>
</code>```

Body:
I would like to create a surface like wechat.. all message start from bottom, but why it doesn't scroll able? If message start from top, it was scroll able.. but I would like the message start from bottom..

How to improve my script? Thanks.

     var childrens = document.querySelector("#chat").children.length;
     document.querySelector("#chat").childNodes[childrens-1].scrollIntoView()

menu

<input type="text" style="width: 90%;">
+

First message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Message here

Last message

Body:
Give id "chat" to parent div of all messages and use this script

 <script>
     var childrens = document.querySelector("#chat").children.length;
     document.querySelector("#chat").childNodes[childrens-1].scrollIntoView()
 </script>


问:
How to set last added row as selected in Slickgrid
I am adding a new row to slickgrid as follows:

```<code>this.dataset.push(
      {
        id: idObjet,
        id_objet: idObjet,
        name: ElementType[elementType] + '-' + idObjet.toString(),
        type: ElementType[elementType],
        delete: 0,
      }
    );

    this.angularGrid.dataView.refresh();
</code>```

At this point I want to highlight this row. So I first retrieve the index of this row:

```<code>const rowIndex = this.dataView.getIdxById(id);
</code>```

I then try to set this row as selected using:

```<code>this.slickGrid.setSelectedRows([rowIndex]);
</code>```

However it does not highlight/select the last added row. This command works on any other existing rows in the grid.

Is it that since the rowview has not been rendered yet, it cannot be selected? Is ther a workaround?

答:
Note that I'm the author of Angular-Slickgrid

You can use the addItem method from the Grid Service, it will highlight the row by default. Take a look at this Example, this will not however select the row by default but there's extra option on that method which you can use selectRow: true

For that Example I mentioned, here's the code to do it.

```<code>angularGridReady(angularGrid: AngularGridInstance) {
    this.angularGrid = angularGrid;
    this.dataView = angularGrid.dataView;
    this.grid = angularGrid.slickGrid;
    this.gridService = angularGrid.gridService;
}

addNewItem(insertPosition?: 'top' | 'bottom') {
    const newId = this.dataset.length;
    const randomYear = 2000 + Math.floor(Math.random() * 10);
    const randomMonth = Math.floor(Math.random() * 11);
    const randomDay = Math.floor((Math.random() * 29));
    const randomPercent = Math.round(Math.random() * 100);

    const newItem = {
      id: newId,
      title: 'Task ' + newId,
      duration: Math.round(Math.random() * 100) + '',
      percentComplete: randomPercent,
      percentCompleteNumber: randomPercent,
      start: new Date(randomYear, randomMonth, randomDay),
      finish: new Date(randomYear, (randomMonth + 2), randomDay),
      effortDriven: true
    };
    this.angularGrid.gridService.addItem(newItem, { position: insertPosition, selectRow: true });
  }
</code>```

Please note that the addItem only support a position of top or bottom (which basically will insert on first row or last row in the grid).

If you really wish to insert the row at a specific row index in the grid, then you'll have to look at how I've implement this addItem method here. All the methods in the Grid Service are basically just helper methods, they all use the SlickGrid & DataView methods to do the final execution. Also note that the highlight is a bit more tricky to deal with, you need to use SlickGrid MetaData to change CSS classes (add/remove css class for a second) on that row in order to simulate a highlight, so that is another reason to simply use the Grid Service.

Body:
I am adding a new row to slickgrid as follows:

this.dataset.push(
      {
        id: idObjet,
        id_objet: idObjet,
        name: ElementType[elementType] + '-' + idObjet.toString(),
        type: ElementType[elementType],
        delete: 0,
      }
    );

    this.angularGrid.dataView.refresh();

At this point I want to highlight this row. So I first retrieve the index of this row:

const rowIndex = this.dataView.getIdxById(id);

I then try to set this row as selected using:

this.slickGrid.setSelectedRows([rowIndex]);

However it does not highlight/select the last added row. This command works on any other existing rows in the grid.

Is it that since the rowview has not been rendered yet, it cannot be selected? Is ther a workaround?

Body:
Note that I'm the author of Angular-Slickgrid

You can use the addItem method from the Grid Service, it will highlight the row by default. Take a look at this Example, this will not however select the row by default but there's extra option on that method which you can use selectRow: true

For that Example I mentioned, here's the code to do it.

angularGridReady(angularGrid: AngularGridInstance) {
    this.angularGrid = angularGrid;
    this.dataView = angularGrid.dataView;
    this.grid = angularGrid.slickGrid;
    this.gridService = angularGrid.gridService;
}

addNewItem(insertPosition?: 'top' | 'bottom') {
    const newId = this.dataset.length;
    const randomYear = 2000 + Math.floor(Math.random() * 10);
    const randomMonth = Math.floor(Math.random() * 11);
    const randomDay = Math.floor((Math.random() * 29));
    const randomPercent = Math.round(Math.random() * 100);

    const newItem = {
      id: newId,
      title: 'Task ' + newId,
      duration: Math.round(Math.random() * 100) + '',
      percentComplete: randomPercent,
      percentCompleteNumber: randomPercent,
      start: new Date(randomYear, randomMonth, randomDay),
      finish: new Date(randomYear, (randomMonth + 2), randomDay),
      effortDriven: true
    };
    this.angularGrid.gridService.addItem(newItem, { position: insertPosition, selectRow: true });
  }

Please note that the addItem only support a position of top or bottom (which basically will insert on first row or last row in the grid).

If you really wish to insert the row at a specific row index in the grid, then you'll have to look at how I've implement this addItem method here. All the methods in the Grid Service are basically just helper methods, they all use the SlickGrid & DataView methods to do the final execution. Also note that the highlight is a bit more tricky to deal with, you need to use SlickGrid MetaData to change CSS classes (add/remove css class for a second) on that row in order to simulate a highlight, so that is another reason to simply use the Grid Service.


问:
Inconsistent scope in python
I have tried creating a function like this:

```<code>n = ["one", "two"]
result=""
def join_strings(words):
  for word in words:
    result+=word
  return result
print (join_strings(n))
</code>```

This does not work and outputs:

```<code>UnboundLocalError: local variable 'result' referenced before assignment
</code>```

The result variable has to be inside the function for it to work.

However, when I have this simple function:

```<code>x=3
def price():
  return (x+3)
print (price())
</code>```

This works and prints the price, even though x is outside of the function. Why is this happening?

答:
The difference is that in the second example you aren't trying to modify or reassign x.  (You'll get the same error if you say something like x += 3 in the price function.)  Once you use an assignment operator, you're binding a new value to that name, shadowing the outer scope.

If you want to be able to modify something from an outer scope, put it inside a mutable container (like a list); you can then modify the contents without reassigning that variable.

```<code>result = [""]
def join_strings(words):
    for word in words:
        result[0] += word
    return result[0]
</code>```

If you just want to be able to reference the result value, without modifying it, that's fine too, but you have to assign it to a new variable then:

```<code>result = ""
def join_strings(words):
    ret = result
    for word in words:
        ret += word
    return ret
</code>```

Title: Inconsistent scope in python

Body:
I have tried creating a function like this:

n = ["one", "two"]
result=""
def join_strings(words):
  for word in words:
    result+=word
  return result
print (join_strings(n))

This does not work and outputs:

UnboundLocalError: local variable 'result' referenced before assignment

The result variable has to be inside the function for it to work.

However, when I have this simple function:

x=3
def price():
  return (x+3)
print (price())

This works and prints the price, even though x is outside of the function. Why is this happening?

Body:
The difference is that in the second example you aren't trying to modify or reassign x.  (You'll get the same error if you say something like x += 3 in the price function.)  Once you use an assignment operator, you're binding a new value to that name, shadowing the outer scope.

If you want to be able to modify something from an outer scope, put it inside a mutable container (like a list); you can then modify the contents without reassigning that variable.

result = [""]
def join_strings(words):
    for word in words:
        result[0] += word
    return result[0]

If you just want to be able to reference the result value, without modifying it, that's fine too, but you have to assign it to a new variable then:

result = ""
def join_strings(words):
    ret = result
    for word in words:
        ret += word
    return ret


问:
GraphDB: use similarity search with embedded repository
I have been using GraphDB's (version 9.2) similarity search from the workbench. Now I also want to use this feature for an embedded repository using graphdb-free-runtime 9.2.1. However I have no clue how this feature can be used from the APIs provided by the runtime. My questions are:

In http://graphdb.ontotext.com/documentation/standard/semantic-similarity-searches.html it is mentioned that similarity search is a plugin. However I could not find any such plugin within the runtime. Do I have to load it from some external resource? Where?

Is there any documentation or example how to create a similarity index programmatically?

Would it be an option to run the workbench as some kind of server and access the similarity search via REST API? However the REST API documentation at http://graphdb.ontotext.com/documentation/9.0/free/using-the-workbench-rest-api.html does not mention any API for similarity searches. Am I missing something?

Any hints or pointers are welcome.

答:
You could add similarity plugin runtime, setting following "graphdb.extra.plugins" property to directory where similarity-plugin (you could find such into GDB instance -> dist/lib/plugins) is located , or:

-Dgraphdb.extra.plugins=directory

System.setProperty("graphdb.extra.plugins", "directory");

You may create index programmatically using SPARQL or:

to create similarity text index "allNews" execute following update:

```<code>PREFIX : <http://www.ontotext.com/graphdb/similarity/>
PREFIX inst: <http://www.ontotext.com/graphdb/similarity/instance/>
PREFIX pred: <http://www.ontotext.com/graphdb/similarity/psi/>
insert {
    inst:allNews :createIndex "-termweight idf" ;
        :analyzer "org.apache.lucene.analysis.en.EnglishAnalyzer" ;
        :documentID ?documentID .
        ?documentID :documentText ?documentText .
} where {
    SELECT ?documentID ?documentText {
        ?documentID ?p ?documentText .
        filter(isLiteral(?documentText))
    }
}
</code>```

to delete index "allNews" execute following update:

```<code>PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

insert { inst:allNews :deleteIndex '' } where {}
</code>```

to rebuild index "allNews":

```<code>PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

insert { inst:allNews :rebuildIndex '' } where {}
</code>```

followed by the create query!

to list all created indexes, execute following query:

```<code>PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

select ?index ?status ?type
where {
  ?index :status ?status .
  ?index :type ?type .
}
</code>```

Body:
You could add similarity plugin runtime, setting following "graphdb.extra.plugins" property to directory where similarity-plugin (you could find such into GDB instance -> dist/lib/plugins) is located , or:

-Dgraphdb.extra.plugins=directory

System.setProperty("graphdb.extra.plugins", "directory");

You may create index programmatically using SPARQL or:

to create similarity text index "allNews" execute following update:

PREFIX : <http://www.ontotext.com/graphdb/similarity/>
PREFIX inst: <http://www.ontotext.com/graphdb/similarity/instance/>
PREFIX pred: <http://www.ontotext.com/graphdb/similarity/psi/>
insert {
    inst:allNews :createIndex "-termweight idf" ;
        :analyzer "org.apache.lucene.analysis.en.EnglishAnalyzer" ;
        :documentID ?documentID .
        ?documentID :documentText ?documentText .
} where {
    SELECT ?documentID ?documentText {
        ?documentID ?p ?documentText .
        filter(isLiteral(?documentText))
    }
}

to delete index "allNews" execute following update:

PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

insert { inst:allNews :deleteIndex '' } where {}

to rebuild index "allNews":

PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

insert { inst:allNews :rebuildIndex '' } where {}

followed by the create query!

to list all created indexes, execute following query:

PREFIX :<http://www.ontotext.com/graphdb/similarity/>
PREFIX inst:<http://www.ontotext.com/graphdb/similarity/instance/>

select ?index ?status ?type
where {
  ?index :status ?status .
  ?index :type ?type .
}


问:
Can we skip using instance variables to render JSON?
If there's no need to use an instance variable, is there any benefits or drawback doing so ? Can I use one liner inside controller's actions ?

def index
  render Foo.all
end
```

If routes are wraped inside contraints format: :json { ... }, Rails renders data formatted as expected and I don't see the need of using an instance variable.

答: Sometimes, an instance variable that is not strictly necessary can be used to document or split up complex 1-liners. In this case, the relative simplicity does not warrant this adjustment - your code is fine as-is.</p>

Body:
If there's no need to use an instance variable, is there any benefits or drawback doing so ? Can I use one liner inside controller's actions ?

def index
  render Foo.all
end

If routes are wraped inside contraints format: :json { ... }, Rails renders data formatted as expected and I don't see the need of using an instance variable.


问:
How to load json file data to existing couchbase bucket through command line or manually?
As i have created a data file in JSON format and I want to know how to load that JSON file to existing Couchbase Server bucket through command line or manually?</p>

答:
There is a cbimport command line tool that ships with Couchbase Server that you can use to import JSON (or CSV) data.

Here's an example that imports a JSON "lines" file into localhost and generates a UUID key

```<code>$ cbimport json -c couchbase://localhost -u myusername -p mypassword \
 -b mybucket -d file:///data/myjson.json -f lines -g #UUID#
</code>```

Body:
There is a cbimport command line tool that ships with Couchbase Server that you can use to import JSON (or CSV) data.

Here's an example that imports a JSON "lines" file into localhost and generates a UUID key

$ cbimport json -c couchbase://localhost -u myusername -p mypassword \
 -b mybucket -d file:///data/myjson.json -f lines -g #UUID#


问:
how can i group by 3 attributes?
Let's say i have an array like this :

[

```<code>{
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D1",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D2",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D3",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C2",
    "col4" : "D4",
}
</code>```

]

I want to group by the first 3 attributes, and then show it in the HTML file like the picture in the link.

Is there any JavaScript function for the grouping? And how can i show it as an HTML table?

https://imgur.com/a/n2CKOmD

I am using angular cli version 9.0.6

答:
Here is my solution :-
Working Stackblitz :- https://stackblitz.com/edit/angular-eau2qn

HTML :-

```<code><table>
    <thead>
        <tr>
            <th *ngFor="let colHead of allKeys">{{colHead | titlecase}}</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="oneCol" *ngFor="let data of uniqueKeysCol | keyvalue">
                <table *ngIf="data.value.length">
          <ng-container *ngFor="let item of data.value">
                    <tr *ngIf="result[item] > 0">
                        {{item}}
                    <tr>
            </ng-container>
                </table>
            <td>
        <tr>
    </tbody>
</table>
</code>```

CSS :-

```<code>table {
  border: 1px solid black;
  border-collapse: collapse;
  width: 100%;
  height: 100%;
}
.oneCol tr {
  border: 1px solid black;
}
td {
  border: 1px solid black;
  text-align: center;
}
.oneCol tr {
  height: 100%;
}
</code>```

Typescript

```<code>import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public uniqueKeysCol = {};
  public allKeys = [];
  public result = {};
  public data = [
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D1"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D2"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D3"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C2",
      col4: "D4"
    }
  ];
  ngOnInit(){
    this.filterData(this.data);
  }
  public filterData(data) {
    this.allKeys = Object.keys(data[0]);
    var resultData = [];
    this.allKeys.forEach((key, index) => {
     this.uniqueKeysCol[key] = [];
     data.forEach((dataObj) => {
       if(this.uniqueKeysCol[key].indexOf(dataObj[key]) === -1) {
         this.uniqueKeysCol[key].push(dataObj[key]);
         this.result[dataObj[key]] = 0;
       }
       this.result[dataObj[key]]++;
     })
    });

    console.log('uniqueKeysCol')
    console.log(this.uniqueKeysCol);
    console.log('result');
    console.log(this.result);
    console.log('allkeys');
    console.log(this.allKeys)
  }
}
</code>```

Title: how can i group by 3 attributes?

Body:
Let's say i have an array like this :

[

{
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D1",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D2",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C1",
    "col4" : "D3",
},
 {
    "col1" : "A1",
    "col2" : "B1",
    "col3" : "C2",
    "col4" : "D4",
}

]

I want to group by the first 3 attributes, and then show it in the HTML file like the picture in the link.

Is there any JavaScript function for the grouping? And how can i show it as an HTML table?

https://imgur.com/a/n2CKOmD

I am using angular cli version 9.0.6

Body:
Here is my solution :-
Working Stackblitz :- https://stackblitz.com/edit/angular-eau2qn

HTML :-

<table>
    <thead>
        <tr>
            <th *ngFor="let colHead of allKeys">{{colHead | titlecase}}</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="oneCol" *ngFor="let data of uniqueKeysCol | keyvalue">
                <table *ngIf="data.value.length">
          <ng-container *ngFor="let item of data.value">
                    <tr *ngIf="result[item] > 0">
                        {{item}}
                    <tr>
            </ng-container>
                </table>
            <td>
        <tr>
    </tbody>
</table>

CSS :-

table {
  border: 1px solid black;
  border-collapse: collapse;
  width: 100%;
  height: 100%;
}
.oneCol tr {
  border: 1px solid black;
}
td {
  border: 1px solid black;
  text-align: center;
}
.oneCol tr {
  height: 100%;
}

Typescript

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public uniqueKeysCol = {};
  public allKeys = [];
  public result = {};
  public data = [
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D1"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D2"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C1",
      col4: "D3"
    },
    {
      col1: "A1",
      col2: "B1",
      col3: "C2",
      col4: "D4"
    }
  ];
  ngOnInit(){
    this.filterData(this.data);
  }
  public filterData(data) {
    this.allKeys = Object.keys(data[0]);
    var resultData = [];
    this.allKeys.forEach((key, index) => {
     this.uniqueKeysCol[key] = [];
     data.forEach((dataObj) => {
       if(this.uniqueKeysCol[key].indexOf(dataObj[key]) === -1) {
         this.uniqueKeysCol[key].push(dataObj[key]);
         this.result[dataObj[key]] = 0;
       }
       this.result[dataObj[key]]++;
     })
    });

    console.log('uniqueKeysCol')
    console.log(this.uniqueKeysCol);
    console.log('result');
    console.log(this.result);
    console.log('allkeys');
    console.log(this.allKeys)
  }
}


答:
PHP does not add / to URLs by default, it's your script doing that.

If you want to use the style.css regardless, use the absolute or the full path - so if your style.css is on http://domain.com/style.css, then you can either use

```<code><link rel="stylesheet" type="text/css" href="/style.css">
</code>```

or

```<code><link rel="stylesheet" type="text/css" href="http://domain.com/style.css">
</code>```

With your file.php thing, it looks in http://domain.com/file.php/style.css, while either of the above uses the file you created at http://domain.com/style.css.

That would as well work for http://domain.com/folder/file.php - simply use /folder/style.css in the href-tag or, once again, the full URL to it.

Title: How to remove or disable the slash at the end of the URL?

Body:
I don't know exactly what is the problem, but I have done a lot of research about trailing slash in PHP.

My problem is that when I visit my site I always see trailing slash and it causes all the resources to fail to load.

How do I disable trailing slash that's being added in .htaccess.
Thanks!

Body:
PHP does not add / to URLs by default, it's your script doing that.

If you want to use the style.css regardless, use the absolute or the full path - so if your style.css is on http://domain.com/style.css, then you can either use

<link rel="stylesheet" type="text/css" href="/style.css">

or

<link rel="stylesheet" type="text/css" href="http://domain.com/style.css">

With your file.php thing, it looks in http://domain.com/file.php/style.css, while either of the above uses the file you created at http://domain.com/style.css.

That would as well work for http://domain.com/folder/file.php - simply use /folder/style.css in the href-tag or, once again, the full URL to it.