问:
Create dynamic component (ComponentFactoryResolver) with dynamic template
I want to dynamically create a component with a dynamic template, so that interpolations of this template will resolve in the context of the dynamic component.

I know that I can use this code to create a dynamic component (which must be mentioned in entryComponents on the module):

My static component:

@Component({
  selector: 'html-type',
  template: `<ng-template #htmlcontrolcomponent></ng-template>`
})
export class HtmlTypeComponent implements AfterViewInit{

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {
    super();
   }

  ngAfterViewInit() {
    this.createComponent("
{{contextvar}}
");
  }

  createComponent(template) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.template = template;       // this doesn't work, is there a way to do it?
  }
```

<p>Component that should be dynamically added:</p>

<pre class="lang-js prettyprint-override"><code>import { Component} from '@angular/core';

@Component({
  selector: 'html-control',
  template: '',
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}

</code>```

Is there a way to reassign the template of a dynamically created component?

What I wanted to achieve: The template of the dynamic component should be dynamic (entered by user and sanitized)

答:
I did it ... with a different approach

I used a DynamicComponentService

Important: I had to turn off "aot: false" in angular.json, otherwise I got Runtime compiler is not loaded errors.

import {
  Compiler,
  Component,
  ComponentFactory,
  Injectable,
  NgModule,
  Type,
  ViewContainerRef,
  ViewEncapsulation
} from "@angular/core";
import {CommonModule} from "@angular/common";

@Injectable({
  providedIn: "root"
})
export class DynamicComponentService {

  protected cacheOfFactories: {[key: string]: ComponentFactory<any>};
  protected componentCache: {[key: string]: Type<any>};
  protected moduleCache: {[key: string]: Type<any>};

  constructor(protected compiler: Compiler) {
    this.cacheOfFactories = {};
    this.componentCache = {};
    this.moduleCache = {};
  }

  /**
   *
   * @param viewContainerRef
   * @param selector
   * @param template
   */
  createComponentFactory(viewContainerRef: ViewContainerRef, selector: string, template: string) {
    const componentFound = this.componentCache[selector];
    if(componentFound) {
      this.compiler.clearCacheFor(componentFound);
      delete this.componentCache[selector];
    }
    const moduleFound = this.moduleCache[selector];
    if(moduleFound) {
      this.compiler.clearCacheFor(moduleFound);
      delete this.moduleCache[selector];
    }

    viewContainerRef.clear();

    this.componentCache[selector] = Component({
      selector,
      template,
      encapsulation: ViewEncapsulation.None
    })(class {
    });

    this.moduleCache[selector] = NgModule({
      imports: [CommonModule],
      declarations: [this.componentCache[selector]]
    })(class {
    });

    return this.compiler.compileModuleAndAllComponentsAsync(this.moduleCache[selector])
      .then((factories) => {
        const foundFactory = factories.componentFactories.find((factory) => {
          return factory.selector === selector;
        });

        if(foundFactory) {
          return viewContainerRef.createComponent(foundFactory);
        }

        throw new Error("component not found");
      })
      .catch((error) => {
        console.log("error", error);

        this.compiler.clearCacheFor(componentFound);
        delete this.componentCache[selector];
        this.compiler.clearCacheFor(moduleFound);
        delete this.moduleCache[selector];

        return Promise.reject(error);
      });
  }

}
```

<p>and changed my html-type component to:</p>

<pre class="lang-js prettyprint-override"><code>export class HtmlTypeComponent implements DoCheck {

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;

  protected oldTemplate: string = "";
  protected componentRef?: ComponentRef<any>;

  constructor(private dynamicComponentService: DynamicComponentService) {}

   ngDoCheck() {
    if(this.entry && this.oldTemplate !== this.to.template) {
      this.oldTemplate = this.to.template;

      if(this.componentRef) {
        this.componentRef.destroy();
        delete this.componentRef;
      }

      this.entry.clear();

      this.dynamicComponentService.createComponentFactory(this.entry, 'html-content', this.to.template)
        .then((component) => {
          this.componentRef = component;
          this.componentRef.instance.model = this.model;
        });
    }
  }

}
</code>```

I could even get rid of the HtmlControlComponent

Body:
I want to dynamically create a component with a dynamic template, so that interpolations of this template will resolve in the context of the dynamic component.

I know that I can use this code to create a dynamic component (which must be mentioned in entryComponents on the module):

My static component:

@Component({
  selector: 'html-type',
  template: `<ng-template #htmlcontrolcomponent></ng-template>`
})
export class HtmlTypeComponent implements AfterViewInit{

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) {
    super();
   }

  ngAfterViewInit() {
    this.createComponent("
{{contextvar}}
");
  }

  createComponent(template) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(HtmlControlComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.template = template;       // this doesn't work, is there a way to do it?
  }

Component that should be dynamically added:

import { Component} from '@angular/core';

@Component({
  selector: 'html-control',
  template: '',
})
export class HtmlControlComponent {
   contextvar: string = "This is my current context";
}

Is there a way to reassign the template of a dynamically created component?

What I wanted to achieve: The template of the dynamic component should be dynamic (entered by user and sanitized)

Body:
I did it ... with a different approach

I used a DynamicComponentService

Important: I had to turn off "aot: false" in angular.json, otherwise I got Runtime compiler is not loaded errors.

import {
  Compiler,
  Component,
  ComponentFactory,
  Injectable,
  NgModule,
  Type,
  ViewContainerRef,
  ViewEncapsulation
} from "@angular/core";
import {CommonModule} from "@angular/common";

@Injectable({
  providedIn: "root"
})
export class DynamicComponentService {

  protected cacheOfFactories: {[key: string]: ComponentFactory<any>};
  protected componentCache: {[key: string]: Type<any>};
  protected moduleCache: {[key: string]: Type<any>};

  constructor(protected compiler: Compiler) {
    this.cacheOfFactories = {};
    this.componentCache = {};
    this.moduleCache = {};
  }

  /**
   *
   * @param viewContainerRef
   * @param selector
   * @param template
   */
  createComponentFactory(viewContainerRef: ViewContainerRef, selector: string, template: string) {
    const componentFound = this.componentCache[selector];
    if(componentFound) {
      this.compiler.clearCacheFor(componentFound);
      delete this.componentCache[selector];
    }
    const moduleFound = this.moduleCache[selector];
    if(moduleFound) {
      this.compiler.clearCacheFor(moduleFound);
      delete this.moduleCache[selector];
    }

    viewContainerRef.clear();

    this.componentCache[selector] = Component({
      selector,
      template,
      encapsulation: ViewEncapsulation.None
    })(class {
    });

    this.moduleCache[selector] = NgModule({
      imports: [CommonModule],
      declarations: [this.componentCache[selector]]
    })(class {
    });

    return this.compiler.compileModuleAndAllComponentsAsync(this.moduleCache[selector])
      .then((factories) => {
        const foundFactory = factories.componentFactories.find((factory) => {
          return factory.selector === selector;
        });

        if(foundFactory) {
          return viewContainerRef.createComponent(foundFactory);
        }

        throw new Error("component not found");
      })
      .catch((error) => {
        console.log("error", error);

        this.compiler.clearCacheFor(componentFound);
        delete this.componentCache[selector];
        this.compiler.clearCacheFor(moduleFound);
        delete this.moduleCache[selector];

        return Promise.reject(error);
      });
  }

}

and changed my html-type component to:

export class HtmlTypeComponent implements DoCheck {

  @ViewChild('htmlcontrolcomponent', { read: ViewContainerRef }) entry: ViewContainerRef;

  protected oldTemplate: string = "";
  protected componentRef?: ComponentRef<any>;

  constructor(private dynamicComponentService: DynamicComponentService) {}

   ngDoCheck() {
    if(this.entry && this.oldTemplate !== this.to.template) {
      this.oldTemplate = this.to.template;

      if(this.componentRef) {
        this.componentRef.destroy();
        delete this.componentRef;
      }

      this.entry.clear();

      this.dynamicComponentService.createComponentFactory(this.entry, 'html-content', this.to.template)
        .then((component) => {
          this.componentRef = component;
          this.componentRef.instance.model = this.model;
        });
    }
  }

}

I could even get rid of the HtmlControlComponent


来源: stackexchange

问:
Buttons for showing/hiding divs not working as intended
I'm new on here aswell as new to HTML, CSS and JS.I want to create a button that makes one  visible while at the same time making four other 's invisible. I've tried

```<code>function ShowGraphics() {

element = document.querySelector("#Graphics");
element.style.visibility = "visible";

element = document.querySelector("#Photos");
element.style.visibility = "hidden";

element = document.querySelector("#Renders");
element.style.visibility = "hidden";

element = document.querySelector("#Videos");
element.style.visibility = "hidden";

element = document.querySelector("#Mods");
element.style.visibility = "hidden";
}
</code>```

before - including its' variations for each button- , but nothing happened. I've also tried giving each "element" a unique name, made no difference. Maybe one of you could help me out there. Thx in Advance :)

答:
Try this code below

function ShowGraphics() {

element = document.querySelector("#Graphics");
element.style.display= "block";

element = document.querySelector("#Photos");
element.style.display = "none";

element = document.querySelector("#Renders");
element.style.display = "none";

element = document.querySelector("#Videos");
element.style.display = "none";

element = document.querySelector("#Mods");
element.style.display = "none";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Graphics">
Hello
</div>

<div id="Photos">
Hello
</div>

<div id="Renders">
Hello
</div>

<div id="Videos">
Hello
</div>

<div id="Mods">
Hello
</div>

<button onclick="ShowGraphics()">Click</button></code>```

And if you dont to change the position of button this is your solution :

function ShowGraphics() {
document.getElementById("Graphics").style.visibility = "visible";

document.getElementById("Photos").style.visibility = "hidden";

document.getElementById("Renders").style.visibility = "hidden";

document.getElementById("Videos").style.visibility = "hidden";

document.getElementById("Mods").style.visibility = "hidden";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Graphics">
Hello
</div>
<div id="Photos">
Hello
</div>
<div id="Renders">
Hello
</div>
<div id="Videos">
Hello
</div>
<div id="Mods">
Hello
</div>
<button onclick="ShowGraphics()">
Click
</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new on here aswell as new to HTML, CSS and JS.I want to create a button that makes one  visible while at the same time making four other 's invisible. I've tried

function ShowGraphics() {

element = document.querySelector("#Graphics");
element.style.visibility = "visible";

element = document.querySelector("#Photos");
element.style.visibility = "hidden";

element = document.querySelector("#Renders");
element.style.visibility = "hidden";

element = document.querySelector("#Videos");
element.style.visibility = "hidden";

element = document.querySelector("#Mods");
element.style.visibility = "hidden";
}

before - including its' variations for each button- , but nothing happened. I've also tried giving each "element" a unique name, made no difference. Maybe one of you could help me out there. Thx in Advance :)

Body:
Try this code below

function ShowGraphics() {

element = document.querySelector("#Graphics");
element.style.display= "block";

element = document.querySelector("#Photos");
element.style.display = "none";

element = document.querySelector("#Renders");
element.style.display = "none";

element = document.querySelector("#Videos");
element.style.display = "none";

element = document.querySelector("#Mods");
element.style.display = "none";

}

<div id="Graphics">
Hello
</div>

<div id="Photos">
Hello
</div>

<div id="Renders">
Hello
</div>

<div id="Videos">
Hello
</div>

<div id="Mods">
Hello
</div>

<button onclick="ShowGraphics()">Click</button>

And if you dont to change the position of button this is your solution :

function ShowGraphics() {
document.getElementById("Graphics").style.visibility = "visible";

document.getElementById("Photos").style.visibility = "hidden";

document.getElementById("Renders").style.visibility = "hidden";

document.getElementById("Videos").style.visibility = "hidden";

document.getElementById("Mods").style.visibility = "hidden";

}

<div id="Graphics">
Hello
</div>
<div id="Photos">
Hello
</div>
<div id="Renders">
Hello
</div>
<div id="Videos">
Hello
</div>
<div id="Mods">
Hello
</div>
<button onclick="ShowGraphics()">
Click
</button>


问:
C# if statement interpretation
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

```<code>1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false
</code>```

答:
When the 4. and 5. line is called it also changes the value of the variable:

a is 1 and b is 2

```<code>a == --b && a == b++ = true
</code>```

a is 1 and b is 2

```<code>a == --b && a == b++ = true
</code>```

a is 1 and b is 1 because second part of the above statement did not run. If first part of the or (||) operator is true, second part will not be executed.

```<code>a == --b && a == b++ = false
</code>```

a is not equal to 0 (1 - 1)

Title: C# if statement interpretation

Body:
I'm confused about a simple thing. In my opinion the result of line 4 must be the same as the one of line 6. Can somebody explain what the optimizer is doing on line 5.

I expected b to be decremented and incremented on each line. So the value of b must have 2 at the begin of interpretation of the line. So the result should have been the same for line 4 and 6.

1. int a = 1;
2. int b = 2;
3.
4. Console.WriteLine(a == --b && a == b++); // expected: true, real: true
5. Console.WriteLine(a == --b || a == b++); // expected: true, real: true
6. Console.WriteLine(a == --b && a == b++); // expected: true, real: false

Body:
When the 4. and 5. line is called it also changes the value of the variable:

a is 1 and b is 2

a == --b && a == b++ = true

a is 1 and b is 2

a == --b && a == b++ = true

a is 1 and b is 1 because second part of the above statement did not run. If first part of the or (||) operator is true, second part will not be executed.

a == --b && a == b++ = false

a is not equal to 0 (1 - 1)


问:
How to extract values from pandas Series without index
I have the following when I print my data structure:

print(speed_tf)

44.0   -24.4
45.0   -12.2
46.0   -12.2
47.0   -12.2
48.0   -12.2
Name: Speed, dtype: float64
```

<p>I believe this is a pandas Series but not sure</p>

<p>I do not want the first column at all I just want </p>

<pre class="lang-py prettyprint-override"><code>-24.4
-12.2
-12.2
-12.2
-12.2
</code>```

I tried speed_tf.reset_index()

  index  Speed
0 44.0   -24.4
1 45.0   -12.2
2 46.0   -12.2
3 47.0   -12.2
4 48.0   -12.2
```

How can I just get the Speed values with index starting at 0?

答:
```<code>speed_tf.values
</code>```

Should do what you want.

Body:
I have the following when I print my data structure:

print(speed_tf)

44.0   -24.4
45.0   -12.2
46.0   -12.2
47.0   -12.2
48.0   -12.2
Name: Speed, dtype: float64

I believe this is a pandas Series but not sure

I do not want the first column at all I just want

-24.4
-12.2
-12.2
-12.2
-12.2

I tried speed_tf.reset_index()

  index  Speed
0 44.0   -24.4
1 45.0   -12.2
2 46.0   -12.2
3 47.0   -12.2
4 48.0   -12.2

How can I just get the Speed values with index starting at 0?

Body:
speed_tf.values

Should do what you want.


问:
C Program : Array example
I read somewhere that i should be able to initialize the array like that. but why isn't it working.

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

main()
{
   char s[10];
   s[10]="pen";
   printf("%s\n",s[10]);
}
</code>```

output:
NULL

答:
Here is the solution to your problem

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

main()
{
   char s[10] = "pen";
   printf("%s\n",s);
}
</code>```

And you can't access s[10] as indexing start from 0 i.e s[0]-s[9]
Reason for NULL output is len(s) is 3

Title: C Program : Array example

Body:
I read somewhere that i should be able to initialize the array like that. but why isn't it working.

#include<stdio.h>

main()
{
   char s[10];
   s[10]="pen";
   printf("%s\n",s[10]);
}

output:
NULL

Body:
Here is the solution to your problem

#include<stdio.h>

main()
{
   char s[10] = "pen";
   printf("%s\n",s);
}

And you can't access s[10] as indexing start from 0 i.e s[0]-s[9]
Reason for NULL output is len(s) is 3


问:
Reverse Z Scores
If you have a data vector you are given that contains only z-scored variables is it possible to reverse the z-score values to get the original measure without using the original measure?
In R Program:

```<code>a = runif(100)
az = (a - mean(a))/sd(a)
</code>```

Can you get back 'a' using JUST 'az'?

答: No, it is not possible. The reverse transformation requires knowledge of the summary statistics mean(a) and sd(a), which cannot be recovered from the standardized scores.

Title: Reverse Z Scores

Body:
If you have a data vector you are given that contains only z-scored variables is it possible to reverse the z-score values to get the original measure without using the original measure?
In R Program:

a = runif(100)
az = (a - mean(a))/sd(a)

Can you get back 'a' using JUST 'az'?


问:
Can't get required response using json parameters within get requests
I'm trying to get json response from this webpage using the following approach but this is what I get {"message": "Must provide valid one of: query_id, query_hash", "status": "fail"}. I tried to print the response url, as in r.url in the second script to see if it matches the one I tried to send but I found it different in structure.

If I use the url directly (taken from dev tools) within requests, I get required content:

```<code>import json
import requests

check_url = 'https://www.instagram.com/graphql/query/?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22instagood%22%2C%22first%22%3A2%2C%22after%22%3A%22QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA%3D%3D%22%7D'
r = requests.get(check_url)
print(r.json())
</code>```

But, I can't make it work:

```<code>import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url,params=json.dumps(payload))
    print(r.content)
</code>```

How can I make the above script work?

答:
Your problem is connected to how you encode the params.
From the check_url in your first example we can see:

```<code>?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22...
</code>```

This URL has 2 params:

query_hash - string

variables - looks like a URL encoded string, judging by the escape values (%7B%22).

As you have correctly identified, %7B%22 corresponds to {". In other words, the second parameter is a url-escaped JSON string.

From this we can get a clue about the new solution:

query_url = 'https://www.instagram.com/graphql/query/?'

variables = {"tag_name": "instagood", "first": "2",
             "after": "QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": json.dumps(variables)
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) ' + \
                              'Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url, params=payload)
    print(r.content)
```

As you can see, the params passed to the requests.get method is a dict with two keys. This will get translated into ?query_hash=value1&variables=value2.

To get the correct value for variables, we just dump the JSON to string. The requests library will take care of URL-escaping all the characters like { and " in the string.

Body:
I'm trying to get json response from this webpage using the following approach but this is what I get {"message": "Must provide valid one of: query_id, query_hash", "status": "fail"}. I tried to print the response url, as in r.url in the second script to see if it matches the one I tried to send but I found it different in structure.

If I use the url directly (taken from dev tools) within requests, I get required content:

import json
import requests

check_url = 'https://www.instagram.com/graphql/query/?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22instagood%22%2C%22first%22%3A2%2C%22after%22%3A%22QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA%3D%3D%22%7D'
r = requests.get(check_url)
print(r.json())

But, I can't make it work:

import json
import requests

url = 'https://www.instagram.com/explore/tags/instagood/'
query_url = 'https://www.instagram.com/graphql/query/?'

payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": {"tag_name":"instagood","first":"2","after":"QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url,params=json.dumps(payload))
    print(r.content)

How can I make the above script work?

Body:
Your problem is connected to how you encode the params.
From the check_url in your first example we can see:

?query_hash=7dabc71d3e758b1ec19ffb85639e427b&variables=%7B%22tag_name%22%3A%22...

This URL has 2 params:

query_hash - string

variables - looks like a URL encoded string, judging by the escape values (%7B%22).

As you have correctly identified, %7B%22 corresponds to {". In other words, the second parameter is a url-escaped JSON string.

From this we can get a clue about the new solution:

query_url = 'https://www.instagram.com/graphql/query/?'

variables = {"tag_name": "instagood", "first": "2",
             "after": "QVFDa3djMUFwM1BkRWJNTlEzRmxBYkRGdFBDVzViU2JoNVZPbWNQSmNCTE1HNDlhYWdsdi1EcE5ickhvYjhRWUhqUDhIcXE3YTE4M1JMbmdVN0lMSXM3ZA=="}
payload = {
    "query_hash": "7dabc71d3e758b1ec19ffb85639e427b",
    "variables": json.dumps(variables)
}

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) ' + \
                              'Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(query_url, params=payload)
    print(r.content)

As you can see, the params passed to the requests.get method is a dict with two keys. This will get translated into ?query_hash=value1&variables=value2.

To get the correct value for variables, we just dump the JSON to string. The requests library will take care of URL-escaping all the characters like { and " in the string.


问:
Show filename and line number in grep output
I am trying to search my rails directory using grep. I am looking for a specific word and I want to grep to print out the file name and line number.

Is there a grep flag that will do this for me? I have been trying to use a combination of -n and -l but these are either printing out the file names with no numbers or just dumping out a lot of text to the terminal which can't be easily read.

ex:

```<code>  grep -ln "search" *
</code>```

Do I need to pipe it to awk?

答:
The comment from @ToreAurstad can be spelled grep -Horn 'search' ./, which is easier to remember.

grep -HEroine 'search' ./ could also work ;)

For the curious:

```<code>$ grep --help | grep -Ee '-[HEroine],'
  -E, --extended-regexp     PATTERNS are extended regular expressions
  -e, --regexp=PATTERNS     use PATTERNS for matching
  -i, --ignore-case         ignore case distinctions
  -n, --line-number         print line number with output lines
  -H, --with-filename       print file name with output lines
  -o, --only-matching       show only nonempty parts of lines that match
  -r, --recursive           like --directories=recurse
</code>```

Body:
I am trying to search my rails directory using grep. I am looking for a specific word and I want to grep to print out the file name and line number.

Is there a grep flag that will do this for me? I have been trying to use a combination of -n and -l but these are either printing out the file names with no numbers or just dumping out a lot of text to the terminal which can't be easily read.

ex:

  grep -ln "search" *

Do I need to pipe it to awk?

Body:
The comment from @ToreAurstad can be spelled grep -Horn 'search' ./, which is easier to remember.

grep -HEroine 'search' ./ could also work ;)

For the curious:

$ grep --help | grep -Ee '-[HEroine],'
  -E, --extended-regexp     PATTERNS are extended regular expressions
  -e, --regexp=PATTERNS     use PATTERNS for matching
  -i, --ignore-case         ignore case distinctions
  -n, --line-number         print line number with output lines
  -H, --with-filename       print file name with output lines
  -o, --only-matching       show only nonempty parts of lines that match
  -r, --recursive           like --directories=recurse


问:
Failed to create the host-only adapter - windows 10, docker, virtualbox
I've recently run into this problem after having used docker toolbox without a problem for a while.

Started happening after windows update?

Windows 10 Home - 64

Uninstalled and reinstalled Docker toolbox

Uninstalled and reinstalled various versions of VirtualBox

Still get the same error

```<code>Running pre-create checks...
Creating machine...
(default) Copying C:\Users\me\.docker\machine\cache\boot2docker.iso to C:\Users\me\.docker\machine\machines\default\boot2docker.iso...
(default) Creating VirtualBox VM...
(default) Creating SSH key...
(default) Starting the VM...
(default) Check network to re-create if needed...
(default) Windows might ask for the permission to create a network adapter. Sometimes, such confirmation window is minimized in the taskbar.
(default) Creating a new host-only adapter produced an error: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe hostonlyif create failed:
(default) 0%...
(default) Progress state: E_FAIL
(default) VBoxManage.exe: error: Failed to create the host-only adapter
(default) VBoxManage.exe: error: Querying NetCfgInstanceId failed (0x00000002)
(default) VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component HostNetworkInterfaceWrap, interface IHostNetworkInterface
(default) VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreate(struct HandlerArg *)" at line 71 of file VBoxManageHostonly.cpp
(default)
(default) This is a known VirtualBox bug. Let's try to recover anyway...
Error creating machine: Error in driver during machine creation: Error setting up host only network on machine start: The host-only adapter we just created is not visible. This is a well known VirtualBox bug. You might want to uninstall it and reinstall at least version 5.0.12 that is is supposed to fix this issue
Looks like something went wrong in step ´Checking if machine default exists´... Press any key to continue...
</code>```

答:
I first installed Docker Toolbox yesterday since I have Windows 10 Home which does not support Docker Desktop.

Rebooting or installing Java did not solved it for me. What did was to delete Oracle's VM that was installed with the Toolbox (5.2.12 or something), and reinstall the new 6.1.8. Checking their website, this makes sense:

ContentLicense: CC BY-SA 3.0

Body:
I've recently run into this problem after having used docker toolbox without a problem for a while.

Started happening after windows update?

Windows 10 Home - 64

Uninstalled and reinstalled Docker toolbox

Uninstalled and reinstalled various versions of VirtualBox

Still get the same error

Running pre-create checks...
Creating machine...
(default) Copying C:\Users\me\.docker\machine\cache\boot2docker.iso to C:\Users\me\.docker\machine\machines\default\boot2docker.iso...
(default) Creating VirtualBox VM...
(default) Creating SSH key...
(default) Starting the VM...
(default) Check network to re-create if needed...
(default) Windows might ask for the permission to create a network adapter. Sometimes, such confirmation window is minimized in the taskbar.
(default) Creating a new host-only adapter produced an error: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe hostonlyif create failed:
(default) 0%...
(default) Progress state: E_FAIL
(default) VBoxManage.exe: error: Failed to create the host-only adapter
(default) VBoxManage.exe: error: Querying NetCfgInstanceId failed (0x00000002)
(default) VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component HostNetworkInterfaceWrap, interface IHostNetworkInterface
(default) VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreate(struct HandlerArg *)" at line 71 of file VBoxManageHostonly.cpp
(default)
(default) This is a known VirtualBox bug. Let's try to recover anyway...
Error creating machine: Error in driver during machine creation: Error setting up host only network on machine start: The host-only adapter we just created is not visible. This is a well known VirtualBox bug. You might want to uninstall it and reinstall at least version 5.0.12 that is is supposed to fix this issue
Looks like something went wrong in step ´Checking if machine default exists´... Press any key to continue...


问:
Upgrading from Python 2 to Python 3 Google App Engine
I would like to upgrade my app engine python version from Python 2 to Python 3. But in second generation app engine  we cannot use login field in the handler in app.yaml to make certain pages in app engine only accessible to admin.

As per the guidelines Google suggests as follows: The login field is not supported. Use Cloud Identity and Access Management for user management.

I am not able to figure how can I use Identity and Access Management to control login access?

答:
Are you trying to have admin only endpoints that can actually be used called by an admin user? Or are you trying to have admin only endpoints that are only meant to run cron jobs and/or enqueue tasks?

If it is the former (i.e. have pages/handlers that will actually be viewed by admin personnel), then the dcumentation here may be what you're looking for. Unfortunately, as I have noticed with app engine documentation, you may have to read pages upon pages of "theory" and never see sample code you can try to actually use.  My guess however is that you will probably end up writing a decorator to check user authorization and authentication, found below.

If you are only trying to limit access to endpoints to secure running cron jobs and queueing tasks, then you are probably looking for this and this solution. Basically, you write a decorator to verify if the endpoint/handler is being called by a cron job or a task queue.  Here's working code which should be good to run:

# main.py

from flask import Flask, request, redirect, render_template

app = Flask(__name__)

# Define the decorator to protect your end points
def validate_cron_header(protected_function):
    def cron_header_validator_wrapper(*args, **kwargs):
        # https://cloud.google.com/appengine/docs/standard/python3/scheduling-jobs-with-cron-yaml#validating_cron_requests
        header = request.headers.get('X-Appengine-Cron')
        # If you are validating a TASK request from a TASK QUEUE instead of a CRON request, then use 'X-Appengine-TaskName' instead of 'X-Appengine-Cron'
        # example:
        # header = request.headers.get('X-Appengine-TaskName')
        # Other possible headers to check can be found here: https://cloud.google.com/tasks/docs/creating-appengine-handlers#reading_app_engine_task_request_headers

        # If the header does not exist, then don't run the protected function
        if not header:
            # here you can raise an error, redirect to a page, etc.
            return redirect("/")

        # Run and return the protected function
        return protected_function(*args, **kwargs)

    # The line below is necessary to allow the use of the wrapper on multiple endpoints
    # https://stackoverflow.com/a/42254713
    cron_header_validator_wrapper.__name__ = protected_function.__name__
    return cron_header_validator_wrapper

@app.route("/example/protected/handler")
@validate_cron_header
def a_protected_handler():
    # Run your code here
    your_response_or_error_etc = "text"
    return your_response_or_error_etc

@app.route("/yet/another/example/protected/handler/<myvar>")
@validate_cron_header
def another_protected_handler(some_var=None):
    # Run your code here
    return render_template("my_sample_template", some_var=some_var)
```


问:
How do I load a pickle model when using cx_freeze?
My script, built as an application, stops working when it tries to load pickle model data. The following is the problematic code:

with open('model_pickle','rb') as f:
    mp = pickle.load(f)
```

<p>This is the setup file I’m using:</p>

<pre class="lang-py prettyprint-override"><code>setup(
    name="Test",
    version="1.0",
    options={"build_exe":{"include_files":["model_pickle"]}},
    executables=[target]
)
</code>```

The program works as it should when executing the python script. However, after converting it to an executable via cx_freeze, the issue is with opening the pickle model data file. I have tested this with and without the data, so I’m pretty sure this is the issue.

答:
Have you tested your program with the IDLE ? Maybe there is a pickle decoding error... If not, try using this code for creating your exe. It imports all the libraries that you have on your computer. It's longer, but easier: just one file to run.

Anyways, better user PyInstaller (also a module available on PyPI) - Related Stack Overflow answer

Body:
My script, built as an application, stops working when it tries to load pickle model data. The following is the problematic code:

with open('model_pickle','rb') as f:
    mp = pickle.load(f)

This is the setup file I’m using:

setup(
    name="Test",
    version="1.0",
    options={"build_exe":{"include_files":["model_pickle"]}},
    executables=[target]
)

The program works as it should when executing the python script. However, after converting it to an executable via cx_freeze, the issue is with opening the pickle model data file. I have tested this with and without the data, so I’m pretty sure this is the issue.


问:
Message: 'chromedriver.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
Ok, so I decided to use selenium for some code, but it doesn't work. When I put the chromedriver in my path, manually, it still doesn't work. can anyone help. PS: I already pip installed selenium.

Also, I watch/read the other article on stack overflow about this problem, but it didn't help me.

答:
This problem occurs when the .py file you are running cannot find chrome driver. the best thing you can do in this situation is that the chrome driver that you installed copy and paste it in same folder as your .py file and then keep your path blank. if you keep your path blank it basically means that the .py file will search the driver on in its folder so make sure you have chrome driver in the same folder ask .py file and then keep your web driver as:</p>

```<code>driver = webdriver.Chrome()
</code>```

Body:
This problem occurs when the .py file you are running cannot find chrome driver. the best thing you can do in this situation is that the chrome driver that you installed copy and paste it in same folder as your .py file and then keep your path blank. if you keep your path blank it basically means that the .py file will search the driver on in its folder so make sure you have chrome driver in the same folder ask .py file and then keep your web driver as:

driver = webdriver.Chrome()


问:
Blocking access from server name
Hi I'm hardening a WordPress site that uses Apache for the web server. I want to block access from servername.admin.company.com. I tried editing HTACCESS per another answer I saw here, but the site started 500'ing from https://domainname.com. There are a ton of security issues, and we decided the best way to handle it is to just block access completely since no one really needs to access it that way.

Here's my vhosts file:

```<code>'  <Directory "/var/www/directory">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
    Require not host servername.admin.company.com
  </Directory>
DirectoryIndex index.php index.html

<VirtualHost *:80>
  ServerName site.com
  ServerAlias www.site.com

  DocumentRoot "/var/www/directory"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/html">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

</VirtualHost>

<VirtualHost *:80>
  ServerName business.site.com
  ServerAlias subdomain.site.com
 ServerAlias www.business.site.com

  DocumentRoot "/var/www/directory"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/site">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

  CustomLog /var/log/httpd/site-requests.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName business.site.com
  ServerAlias directory.site.com
 ServerAlias www.subfolder.site.com

  DocumentRoot "/var/www/sitefolder"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/sitefolder">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

  CustomLog /var/log/httpd/sitefolder-requests.log combined
  ErrorLog /var/log/httpd/sitefolder-error.log

</VirtualHost>
</code>```

'

答:
You can achieve this in various ways, iptables, .htaccess, etc.

Please visit this URL, what you need to do is well documented there:

https://httpd.apache.org/docs/2.4/en/howto/access.html

I hope it helps you.

Title: Blocking access from server name

Body:
Hi I'm hardening a WordPress site that uses Apache for the web server. I want to block access from servername.admin.company.com. I tried editing HTACCESS per another answer I saw here, but the site started 500'ing from https://domainname.com. There are a ton of security issues, and we decided the best way to handle it is to just block access completely since no one really needs to access it that way.

Here's my vhosts file:

'  <Directory "/var/www/directory">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
    Require not host servername.admin.company.com
  </Directory>
DirectoryIndex index.php index.html

<VirtualHost *:80>
  ServerName site.com
  ServerAlias www.site.com

  DocumentRoot "/var/www/directory"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/html">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

</VirtualHost>

<VirtualHost *:80>
  ServerName business.site.com
  ServerAlias subdomain.site.com
 ServerAlias www.business.site.com

  DocumentRoot "/var/www/directory"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/site">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

  CustomLog /var/log/httpd/site-requests.log combined
</VirtualHost>

<VirtualHost *:80>
  ServerName business.site.com
  ServerAlias directory.site.com
 ServerAlias www.subfolder.site.com

  DocumentRoot "/var/www/sitefolder"

  # Enable HSTS (tell browsers to use only HTTP)
  Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload;"

  <Directory "/var/www/sitefolder">
    AllowOverride All
    Options -Indexes +FollowSymLinks
    Require all granted
  </Directory>

  RewriteEngine on
  RewriteRule "^(.*/)?\.git/" - [F,L]
  RedirectMatch 404 /\.git

  CustomLog /var/log/httpd/sitefolder-requests.log combined
  ErrorLog /var/log/httpd/sitefolder-error.log

</VirtualHost>

'


问:
linux csv file concatenate columns into one column
I've been looking to do this with sed, awk, or cut. I am willing to use any other command-line program that I can pipe data through.

I have a large set of data that is comma delimited. The rows have between 14 and 20 columns. I need to recursively concatenate column 10 with column 11 per row such that every row has exactly 14 columns. In other words, this:

```<code>a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p
</code>```

will become:

```<code>a,b,c,d,e,f,g,h,i,jkl,m,n,o,p
</code>```

I can get the first 10 columns. I can get the last N columns. I can concatenate columns. I cannot think of how to do it in one line so I can pass a stream of endless data through it and end up with exactly 14 columns per row.

Examples (by request):

How many columns are in the row?

```<code>sed 's/[^,]//g' | wc -c
</code>```

Get the first 10 columns:

```<code>cut -d, -f1-10
</code>```

Get the last 4 columns:

```<code>rev | cut -d, -f1-4 | rev
</code>```

Concatenate columns 10 and 11, showing columns 1-10 after that:

```<code>awk -F',' ' NF { print $1","$2","$3","$4","$5","$6","$7","$8","$9","$10$11}'
</code>```

Body:
I've been looking to do this with sed, awk, or cut. I am willing to use any other command-line program that I can pipe data through.

I have a large set of data that is comma delimited. The rows have between 14 and 20 columns. I need to recursively concatenate column 10 with column 11 per row such that every row has exactly 14 columns. In other words, this:

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p

will become:

a,b,c,d,e,f,g,h,i,jkl,m,n,o,p

I can get the first 10 columns. I can get the last N columns. I can concatenate columns. I cannot think of how to do it in one line so I can pass a stream of endless data through it and end up with exactly 14 columns per row.

Examples (by request):

How many columns are in the row?

sed 's/[^,]//g' | wc -c

Get the first 10 columns:

cut -d, -f1-10

Get the last 4 columns:

rev | cut -d, -f1-4 | rev

Concatenate columns 10 and 11, showing columns 1-10 after that:

awk -F',' ' NF { print $1","$2","$3","$4","$5","$6","$7","$8","$9","$10$11}'

Body:
Solved a similar problem using csvtool. Source file, copied from one of the other answers:

$ cat input.txt
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p
1,2,3,4,5,6,3,4,2,4,3,4,3,2,5,2,3,4
1,2,3,4,5,6,3,4,2,4,a,s,f,e,3,4,3,2,5,2,3,4

Concatenating columns:

$ cat input.txt | csvtool format '%1,%2,%3,%4,%5,%6,%7,%8,%9,%10%11%12,%13,%14,%15,%16,%17,%18,%19,%20,%21,%22\n' -
a,b,c,d,e,f,g,h,i,jkl,m,n,o,p,,,,,,
1,2,3,4,5,6,3,4,2,434,3,2,5,2,3,4,,,,
1,2,3,4,5,6,3,4,2,4as,f,e,3,4,3,2,5,2,3,4
anatoly@anatoly-workstation:cbs$ cat input.txt


问:
How to embed Calendly Anchor Tag With React and Material-UI
I'm trying to embed the anchor tag of Calendly using Reacrjs and Material-UI.

The Calendly instruction is:

```<code><!-- Calendly link widget begin -->
<link href="https://assets.calendly.com/assets/external/widget.css" rel="stylesheet">
<script src="https://assets.calendly.com/assets/external/widget.js" type="text/javascript"></script>
<a href="" onclick="Calendly.initPopupWidget({url: 'https://calendly.com/bbb'});return false;"> Schedule Here</a>
<!-- Calendly link widget end -->
</code>```

I tried doing this:

```<code><Typography className={classes.root}>
    <Link href="#" onClick={Calendly.initPopupWidget({url:'https://calendly.com/bbb'})}>
       Schedule Here
    </Link>
</Typography>
</code>```

And added the script and link tags mentioned on the instructions on the index.html in the public folder of the react app

Thank you.

答:
It looks like you are calling Calendly.initPopupWidget({url:'https://calendly.com/bbb'}) instead of passing the function to the onClick handler. This will cause the popup to appear when the link is rendered instead of when the link is clicked.

You can change the onClick function to the following to prevent this issue:

<Link href="#" onClick={() => window.Calendly.initPopupWidget({url:'https://calendly.com/bbb'})}>
       Schedule Here
</Link>```

This will wrap the call to initPopupWidget in an anonymous function so that the Calendly function only fires when the Link is clicked.

Body:
I'm trying to embed the anchor tag of Calendly using Reacrjs and Material-UI.

The Calendly instruction is:

<link href="https://assets.calendly.com/assets/external/widget.css" rel="stylesheet">

 Schedule Here

I tried doing this:

<Typography className={classes.root}>
    <Link href="#" onClick={Calendly.initPopupWidget({url:'https://calendly.com/bbb'})}>
       Schedule Here
    </Link>
</Typography>

And added the script and link tags mentioned on the instructions on the index.html in the public folder of the react app

Thank you.

Body:
It looks like you are calling Calendly.initPopupWidget({url:'https://calendly.com/bbb'}) instead of passing the function to the onClick handler. This will cause the popup to appear when the link is rendered instead of when the link is clicked.

You can change the onClick function to the following to prevent this issue:

<Link href="#" onClick={() => window.Calendly.initPopupWidget({url:'https://calendly.com/bbb'})}>
       Schedule Here
</Link>

This will wrap the call to initPopupWidget in an anonymous function so that the Calendly function only fires when the Link is clicked.


问:
OAuth2 Refresh token scopes
I am implementing an OAuth2 server that supports refresh token however, there is something that I am not been able to understand fully.

When a user request for a new access token via the refresh_token grant_type and he/she requested lesser scope (3 out of the 5 scopes) than what the original access token has. Should the refresh token have the original scopes or should the refresh token have the new scopes requested?

If the refresh token has the new scopes requested, does this mean that eventually, they will run out of scopes if they keep requesting lesser scopes?

Should the refresh token keep the original scopes? This would mean that an access token returned would have different scopes as to what is stored in the refresh token, and the next request to get a new access token may result in more scopes than the current access token.

Can someone please enlighten me on this issue?

I have read the RFC docs and there is a point that states

If a new refresh token is issued, the refresh token scope MUST be
  identical to that of the refresh token included by the client in the
  request.

答:
For a refresh token grant:

The base behaviour is to receive only a new access token in the response

The original refresh token is then reused a number of times.

Some authorization servers support refresh token rotation and may also:

Issue a new 'rolling' refresh token

This is bound to the original scopes and session time

At least that's the theory, though you need to test for your particular authorization server. Vendor support from the likes of Microsoft, AWS and others varies considerably.

Title: OAuth2 Refresh token scopes


问:
How to append output to the end of a text file
How do I append the output of a command to the end of a text file?</p>

答:
for the whole question:

```<code>cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
</code>```

this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.

Run the above with the cron every hour, or

```<code>while :
do
    cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
    sleep 3600
done
</code>```

Body:
for the whole question:

cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt

this will append 720 lines (30*24) into o.txt and after will rename the file based on the current date.

Run the above with the cron every hour, or

while :
do
    cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
    sleep 3600
done


问:
Permission denied in unprivileged docker image
I am trying to run a rethinkdb image on a Kubernetes cluster that has tight security measures and we must run containers as non-root, therefore I am using user 1000 to run them and I changed the Dockerfile to below:

```<code>FROM ubuntu:18.04

RUN apt update && apt install -y wget libcurl4 libprotobuf10 python3-pip

RUN wget https://github.com/srh/rethinkdb/releases/download/v2.3.6.srh.1/rethinkdb_2.3.6.srh.1.0bionic_amd64.deb
RUN dpkg -i rethinkdb_2.3.6.srh.1.0bionic_amd64.deb

ADD rethinkdb_tables /opt/rethinkdb_tables
RUN pip3 install rethinkdb==2.3

ADD entry_point.sh /opt/entry_point.sh

ENV RUN_ENV docker-compose

RUN id
RUN apt-get update && apt-get install -y sudo
RUN groupadd newuser
RUN useradd -u 1000 -m -g newuser newuser
RUN adduser newuser sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
RUN mkdir /data
RUN chown -R newuser:0 /opt/
RUN chown -R newuser:0 /data
USER newuser

ENTRYPOINT [ "sh", "/opt/entry_point.sh" ]
CMD []
</code>```

The entry_point.sh is a small script that starts the rethinkdb and as soon as the rethinkdb is up it imports some tables. But I am getting below error:

Launch rethinkdb in Kubernetes
Could not create directory 'rethinkdb_data': Permission denied
```

How I can fix this? I have to mention that this is the way that I used to run my other images as non-root and this worked for them.

答: Since the rethinkdb wanted to create the rethinkdb_data at / I decided to create that directory myself in the Dockerfile and change its owner so rethinkdb can access it and this solved my problem.

Body:
I am trying to run a rethinkdb image on a Kubernetes cluster that has tight security measures and we must run containers as non-root, therefore I am using user 1000 to run them and I changed the Dockerfile to below:

FROM ubuntu:18.04

RUN apt update && apt install -y wget libcurl4 libprotobuf10 python3-pip

RUN wget https://github.com/srh/rethinkdb/releases/download/v2.3.6.srh.1/rethinkdb_2.3.6.srh.1.0bionic_amd64.deb
RUN dpkg -i rethinkdb_2.3.6.srh.1.0bionic_amd64.deb

ADD rethinkdb_tables /opt/rethinkdb_tables
RUN pip3 install rethinkdb==2.3

ADD entry_point.sh /opt/entry_point.sh

ENV RUN_ENV docker-compose

RUN id
RUN apt-get update && apt-get install -y sudo
RUN groupadd newuser
RUN useradd -u 1000 -m -g newuser newuser
RUN adduser newuser sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
RUN mkdir /data
RUN chown -R newuser:0 /opt/
RUN chown -R newuser:0 /data
USER newuser

ENTRYPOINT [ "sh", "/opt/entry_point.sh" ]
CMD []

The entry_point.sh is a small script that starts the rethinkdb and as soon as the rethinkdb is up it imports some tables. But I am getting below error:

Launch rethinkdb in Kubernetes
Could not create directory 'rethinkdb_data': Permission denied

How I can fix this? I have to mention that this is the way that I used to run my other images as non-root and this worked for them.


问:
how to set jenkins changeset exclude setting
I'd like to know if there is something opposite to changeset in Jenkins.
For example, in the doc (https://www.jenkins.io/doc/book/pipeline/syntax/), an example is given for changeset setting:

```<code>when { changeset pattern: ".TEST\\.java", comparator: "REGEXP" } or when { changeset pattern: "*/*TEST.java", caseSensitive: true }
</code>```

I'd like to know if I can set "changeset exclude" patterns so that the files match this pattern will not trigger certain stages.

答:
I haven't tried it by myself, but surrounding the condition with not{} should do the trick:

```<code>when {
  not {
    changeset pattern: "*/*TEST.java", caseSensitive: true
  }
}
</code>```

See Pipeline Syntax (when) (scroll down to not).

Body:
I'd like to know if there is something opposite to changeset in Jenkins.
For example, in the doc (https://www.jenkins.io/doc/book/pipeline/syntax/), an example is given for changeset setting:

when { changeset pattern: ".TEST\\.java", comparator: "REGEXP" } or when { changeset pattern: "*/*TEST.java", caseSensitive: true }

I'd like to know if I can set "changeset exclude" patterns so that the files match this pattern will not trigger certain stages.

Body:
I haven't tried it by myself, but surrounding the condition with not{} should do the trick:

when {
  not {
    changeset pattern: "*/*TEST.java", caseSensitive: true
  }
}

See Pipeline Syntax (when) (scroll down to not).


问:
TornadoFX not finding JavaFx
I'm trying my first first app with TornadoFx, so I started with this code:

```<code>package no.tornado.fxsample.workspace

import javafx.application.Application
import tornadofx.*

fun main(args: Array<String>) = launch<MyApp>(args)

class MyApp: App(MyView::class)

class MyView: View() {
    override val root = VBox()
    init {
        with(root) {
        this += Button("Press Me")
        this += Label("Waiting")
        }
    }
}
</code>```

but apparently it is full of errors, and not able to find JavaFX

My gradle.build is:

```<code>// set up the kotlin-gradle plugin
buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
       mavenLocal()    //    mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

// apply the kotlin-gradle plugin
apply plugin: "kotlin"

// add kotlin-stdlib dependencies.
repositories {
    mavenLocal()  // mavenCentral()
}

dependencies {
    //dependencies from a remote repositor
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "no.tornado:tornadofx:1.7.12"
}

jar {
    manifest {
        //Define mainClassName as: '[your_namespace].[your_arctifact]Kt'
        attributes ('Main-Class': 'MyAppKt', "Implementation-Title": "Gradle",
                   "Implementation-Version": 1)
    }
    // NEW LINE HERE !!!
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

sourceSets {
    main.kotlin.srcDirs += 'src/kotlin'
    main.resources.srcDirs += 'src/resources'
}

kotlin {
    experimental.coroutines 'enable'
}

compileKotlin {
    kotlinOptions.jvmTarget= 1.8  // optional, Minimum jvmTarget of 1.8 needed since Kotlin 1.1
    kotlinOptions.suppressWarnings = true
}
</code>```

答:
ver gradle 6.4
ver kotlin 1.3.72
ver tornadofx 1.7.20
ver JDK 14

build.gradle add

```<code>plugins {
    id 'org.openjfx.javafxplugin' version '0.0.8'
}
javafx {
    version = "14"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}
</code>```

Title: TornadoFX not finding JavaFx

Body:
I'm trying my first first app with TornadoFx, so I started with this code:

package no.tornado.fxsample.workspace

import javafx.application.Application
import tornadofx.*

fun main(args: Array<String>) = launch<MyApp>(args)

class MyApp: App(MyView::class)

class MyView: View() {
    override val root = VBox()
    init {
        with(root) {
        this += Button("Press Me")
        this += Label("Waiting")
        }
    }
}

but apparently it is full of errors, and not able to find JavaFX

My gradle.build is:

// set up the kotlin-gradle plugin
buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
       mavenLocal()    //    mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

// apply the kotlin-gradle plugin
apply plugin: "kotlin"

// add kotlin-stdlib dependencies.
repositories {
    mavenLocal()  // mavenCentral()
}

dependencies {
    //dependencies from a remote repositor
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "no.tornado:tornadofx:1.7.12"
}

jar {
    manifest {
        //Define mainClassName as: '[your_namespace].[your_arctifact]Kt'
        attributes ('Main-Class': 'MyAppKt', "Implementation-Title": "Gradle",
                   "Implementation-Version": 1)
    }
    // NEW LINE HERE !!!
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

sourceSets {
    main.kotlin.srcDirs += 'src/kotlin'
    main.resources.srcDirs += 'src/resources'
}

kotlin {
    experimental.coroutines 'enable'
}

compileKotlin {
    kotlinOptions.jvmTarget= 1.8  // optional, Minimum jvmTarget of 1.8 needed since Kotlin 1.1
    kotlinOptions.suppressWarnings = true
}

Body:
ver gradle 6.4
ver kotlin 1.3.72
ver tornadofx 1.7.20
ver JDK 14

build.gradle add

plugins {
    id 'org.openjfx.javafxplugin' version '0.0.8'
}
javafx {
    version = "14"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}


问:
How to call a function from html button
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

```<code><html>
    <head>
        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

     <script>
             function delete(id){

                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                      if (this.readyState == 4 && this.status == 200) {
                        var available = this.responseText;
                      }
                  };
                xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
                xhttp.send();
            }
        </script>
    </head>

    <body>
        <button type="button" onclick="delete(9)">Erase</button>
    </body>

</html>
</code>```

答:
The problem is delete is operator in JavaScript

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

So your code try to delete the object or element mentioned after it and is not calling method you wrote.

As per example in @Pluto https://stackoverflow.com/a/62086635/124891
You have to rename the method and call it.

Title: How to call a function from html button

Body:
I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?

Thank you

This is the code,

        <title>Carrental</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

        <button type="button" onclick="delete(9)">Erase</button>


问:
Form error in Laravel blade. Is "class" or "id" or something the cause?
I don’t know why this form causes an error.  *THIS ISSUE IS NOT RELATED TO ROUTE.  Please read my question thoroughly.

“The POST method is not supported for this route. Supported methods:
  GET, HEAD.”

What does makes it happen?  The first one here works well.

But the second one will happen the error.  Which class or id should I remove?

```<code>//OK
<form action="{{ route('contact_confirm') }}" method="POST">
    {{ csrf_field() }}
    <button class="btn btn-primary btn-xl" type="submit">Send</button></div>
    <input id="title" type="text" name = "title"  />
    <input id="title" type="text" name = "body"  />
</form>

//NG
<div class="row">
    <div class="col-lg-8 mx-auto">
        <form id="contactForm" 　action="{{ route('contact_confirm') }}" method="POST">
            {{ csrf_field() }}
            <div class="control-group">
                <div class="form-group floating-label-form-group controls mb-0 pb-2">
                    <label>TITLE</label>
                    <input class="form-control" id="title" type="text" name = "title" placeholder="Title" required="required" data-validation-required-message="Please enter your name." />
                    <p class="help-block text-danger"></p>
                </div>
            </div>
            <div class="control-group">
                <div class="form-group floating-label-form-group controls mb-0 pb-2">
                    <label>CONTENTS</label>
                    <textarea class="form-control" id="message" rows="5" name ="body" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>
                    <p class="help-block text-danger"></p>
                </div>
            </div>
            <br />
            <div class="form-group">
                <button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Send</button>
            </div>
        </form>
</code>```

PHP
web.php

```<code>Route::post('contact/confirm', 'ContactsController@confirm')->name('contact_confirm');
</code>```

答:
It sounds like the post route could be missing.

Verify in your routes/web.php file that you have something that looks like this:

```<code>Route::post('your/route', ...)->name('contact_confirm');
</code>```

More info on routing can be found here.

Body:
I don’t know why this form causes an error.  *THIS ISSUE IS NOT RELATED TO ROUTE.  Please read my question thoroughly.

“The POST method is not supported for this route. Supported methods:
  GET, HEAD.”

What does makes it happen?  The first one here works well.

But the second one will happen the error.  Which class or id should I remove?

//OK
<form action="{{ route('contact_confirm') }}" method="POST">
    {{ csrf_field() }}
    <button class="btn btn-primary btn-xl" type="submit">Send</button>

    <input id="title" type="text" name = "title"  />
    <input id="title" type="text" name = "body"  />
</form>

//NG

        <form id="contactForm" 　action="{{ route('contact_confirm') }}" method="POST">
            {{ csrf_field() }}

                    TITLE
                    <input class="form-control" id="title" type="text" name = "title" placeholder="Title" required="required" data-validation-required-message="Please enter your name." />

                    CONTENTS
                    <textarea class="form-control" id="message" rows="5" name ="body" placeholder="Message" required="required" data-validation-required-message="Please enter a message."></textarea>

                <button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Send</button>

        </form>

PHP
web.php

Route::post('contact/confirm', 'ContactsController@confirm')->name('contact_confirm');

Body:
It sounds like the post route could be missing.

Verify in your routes/web.php file that you have something that looks like this:

Route::post('your/route', ...)->name('contact_confirm');

More info on routing can be found here.


问:
Does CKAN support video formats?
I'd like to upload video files on a CKAN portal.
Does CKAN support uploading media files eg .mp4

答: Yes, you can upload media files as .mp4. They will be uploaded in your filestore, from where you can download them later on. About the views, the data explorer wouldn't preview the video file by default. I am not 100% sure if the video preview was developed but it was added to the roadmaps some time ago.</p>

Title: Does CKAN support video formats?


答:
If you are using a Windows compiler that in turn uses Microsoft's (non) standard C libraries, you will get exactly the problem you describe. You will also get a warning along the lines of:

warning: unknown conversion type character 'L' in format [-Wformat=]

This is because Microsoft's lib (barely) conforms to the year 1990 version of C (C90), not to the year 1999 (C99) or later versions. This means that it doesn't recognize any printf/scanf conversion specifiers such as %Lf that were added in C99, but will happily produce a broken binary executable regardless.

With the Mingw/gcc compiler, you can fix the issue like this:

```<code>#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
...
</code>```

With MSVC you can't fix it afaik, so consider replacing that one with a different compiler.

Title: why the longDoubleNum is Zeros

Body:
I'm beginner in C I have an issue in the output of my code here it is:

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

int main(void){

printf("float:      byte %lu\n",sizeof(float));
printf("double:     byte %lu\n",sizeof(double));
printf("long double:    byte %lu\n",sizeof(long double));

    float       floatNum =3.0/5.0;
    double      doubleNum=3.0/5.0;
    long double     longDoubleNum=3.0/5.0;

    printf("---------------------------------------\n");
    printf("float:       %1.4f      \n",floatNum);
    printf("double:          %1.4lf     \n",doubleNum);
    printf("long double:         %1.4Lf     \n",longDoubleNum);
    printf("---------------------------------------\n");

    printf("---------------------------------------\n");
    printf("float:       %1.20f     \n",floatNum);
    printf("double:          %1.20lf        \n",doubleNum);
    printf("long double:         %1.20Lf        \n",longDoubleNum);
    printf("---------------------------------------\n");

    printf("---------------------------------------\n");
    printf("float:       %1.60f     \n",floatNum);
    printf("double:          %1.60lf        \n",doubleNum);
    printf("long double:         %1.60Lf        \n",longDoubleNum);
    printf("---------------------------------------\n");
}

here is the output:

float:      byte 4
double:     byte 8
long double:    byte 16
---------------------------------------
float:       0.6000
double:          0.6000
long double:         0.0000
---------------------------------------
---------------------------------------
float:       0.60000002384185791000
double:          0.59999999999999998000
long double:         0.00000000000000000000
---------------------------------------
---------------------------------------
float:       0.600000023841857910000000000000000000000000000000000000000000
double:          0.599999999999999980000000000000000000000000000000000000000000
long double:         0.000000000000000000000000000000000000000000000000000000000000
---------------------------------------

Body:
If you are using a Windows compiler that in turn uses Microsoft's (non) standard C libraries, you will get exactly the problem you describe. You will also get a warning along the lines of:

warning: unknown conversion type character 'L' in format [-Wformat=]

This is because Microsoft's lib (barely) conforms to the year 1990 version of C (C90), not to the year 1999 (C99) or later versions. This means that it doesn't recognize any printf/scanf conversion specifiers such as %Lf that were added in C99, but will happily produce a broken binary executable regardless.

With the Mingw/gcc compiler, you can fix the issue like this:

#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
...

With MSVC you can't fix it afaik, so consider replacing that one with a different compiler.


问:
Simple-peer, how the candidate data is transferred?
I am using Simple-peer to build a webrtc application. To establish connection, we need to first send the offer and receive the answer. After that onicecandidate event gets triggered generating the candidate, we are required to send the candidate data to remote peer. The remote peer will than run addicecandidate and send back the remote candidate data which need to be added on localpeer using addicecandidate and connection gets established.

I want to understand how simple-peer is handling transfer of candidate data. The SDP data related to OFFER and ANSWER is required to be transferred using server in between, in one of the example socket-io has been used. But how the candidate data is getting transferred?

答: In simple-peer the signal from peer.on('signal', data=>{}) contains all the webrtc signaling data. If you print out the value of the signal you'll see it contains sdp, offer and answer all labeled to identify which is which.


问:
How to merge values from different objects in gremlin query?
I have a query that returns the output in the following format,

```<code>{
    "Key": [
      "Value1",
      "Value2"
    ],
    "Count": [
      {
        "Count1": 28,
        "Count2": 28
      },
      {
        "Count3": 16,
        "Count4": 16
      }
    ]
  }
</code>```

I want to display it in the following format

```<code>[
  {
     "Key" : "Value1",
     "Count1": 28,
     "Count2": 28
  },
  {
     "Key" : "Value2",
     "Count3": 16,
     "Count4": 16
  }
]
</code>```

Is it possible?

The gremlin that produces a similar output

```<code>
g.V().
has('organizationId', 'b121672e-8049-40cc-9f28-c62dff4cc2d9').
hasLabel('employee').

group().
by('officeId').
by(project('Id', 'Status').
    by(choose(has('officeId'), constant('Total'), constant(''))).
    by(coalesce(out('hasStatus').
                or(
                        has('release', is(false)),
                        has('autoRelease', is(true)).
                        has('release', is(true)).
                        has('endDate', gte(637250976000000000))
                 ), values('status'), constant('Green'))).
    select(values).
    unfold().
    groupCount()).

    project('Id', 'Count').
    by(select(keys)).
    by(select(values))
</code>```

And the data that I have is an employee vertex and a healthStatus vertex, there's an hasStatus edge between employee and healthStatus

Properties in employee vertex:
id, organizations, officeId, Name, createdOn

Properties in healthStatus vertex:
id, status, startDate, endDate, release, autoRelease, createdOn

Sample Data

```<code> g.addV('employee').
       property('id',1).
       property('organizationId',1).
       property('officeId',1).
       property('name','A').
       property('createdOn', 637263231140000000).as('1').
    addV('employee').
       property('id',2).
       property('organizationId',1).
       property('officeId',2).
       property('name','B').
       property('createdOn', 637263231140000000).as('2').
   addV('employee').
       property('id',5).
       property('organizationId',1).
       property('officeId',3).
       property('name','C').
       property('createdOn', 637263231140000000).as('5').
    addV('healthStatus').
       property('id',3).
       property('status','Red').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000)as('3').
    addV('healthStatus').
       property('id',4).
       property('status','Yellow').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000)as('4').
    addE('hasStatus').from('1').to('3').
    addE('hasStatus').from('4').to('4')
</code>```

Output:

```<code>[
  {
    "Id" : [
        1,
        2,
        3
      ]
  },
  {
    "Count": [
      {
         "Red" : 1
      },
      {
         "Yellow" : 1
      },
      {
         "Green" : 1
      }
    ]
  }
</code>```

Expected Output

```<code>[
  {
     "Id" : 1,
     "Red" : 1
  },
  {
     "Id" : 2,
     "Yellow" : 1
  },
  {
     "Id" : 3,
     "Green" : 1
  }
]
</code>```

Note : This Id in projection is officeId from employee vertex

答:
I think I've captured what you wanted. There were some errors in your sample data script and I wanted some extra data to make sure counts were making sense so I added a bit:

```<code> g = TinkerGraph.open().traversal()
 g.addV('employee').
       property('id',1).
       property('organizationId',1).
       property('officeId',1).
       property('name','A').
       property('createdOn', 637263231140000000).as('1').
    addV('employee').
       property('id',2).
       property('organizationId',1).
       property('officeId',2).
       property('name','B').
       property('createdOn', 637263231140000000).as('2').
   addV('employee').
       property('id',5).
       property('organizationId',1).
       property('officeId',3).
       property('name','C').
       property('createdOn', 637263231140000000).as('5').
   addV('employee').
       property('id',6).
       property('organizationId',1).
       property('officeId',3).
       property('name','D').
       property('createdOn', 637263231140000000).as('6').
    addV('healthStatus').
       property('id',3).
       property('status','Red').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000).as('3').
    addV('healthStatus').
       property('id',4).
       property('status','Yellow').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000).as('4').
    addE('hasStatus').from('1').to('3').
    addE('hasStatus').from('2').to('4').
    addE('hasStatus').from('6').to('4')
</code>```

I've re-written you traversal a bit to provide a different approach that I think provides the data you expect, however in a slightly different form:

```<code>gremlin> g.V().has('employee','organizationId', 1).
......1>   project('Id', 'Status').
......2>     by('officeId').
......3>     by(coalesce(out('hasStatus').
......4>                 or(has('release', false),
......5>                    has('autoRelease', true).has('release', true).has('endDate', gte(637250976000000000))).
......6>                 values('status'),
......7>                 constant('Green'))).
......8>   group().
......9>     by(select('Id')).
.....10>     by(groupCount().
.....11>          by('Status'))
==>[1:[Red:1],2:[Yellow:1],3:[Yellow:1,Green:1]]
</code>```

I prefer this form a bit, but perhaps you require the original format you inquired about, in which case you need another round of manipulation on the collection:

```<code>gremlin> g.V().has('employee','organizationId', 1).
......1>   project('Id', 'Status').
......2>     by('officeId').
......3>     by(coalesce(out('hasStatus').
......4>                 or(has('release', false),
......5>                    has('autoRelease', true).has('release', true).has('endDate', gte(637250976000000000))).
......6>                 values('status'),
......7>                 constant('Green'))).
......8>   group().
......9>     by(select('Id')).
.....10>     by(groupCount().
.....11>          by('Status')).
.....12>   unfold().
.....13>   map(union(project('Id').by(select(keys)),
.....14>             select(values)).
.....15>       unfold().
.....16>       group().by(keys).by(select(values)))
==>[Red:1,Id:1]
==>[Yellow:1,Id:2]
==>[Yellow:1,Id:3,Green:1]
</code>```

Body:
I have a query that returns the output in the following format,

{
    "Key": [
      "Value1",
      "Value2"
    ],
    "Count": [
      {
        "Count1": 28,
        "Count2": 28
      },
      {
        "Count3": 16,
        "Count4": 16
      }
    ]
  }

I want to display it in the following format

[
  {
     "Key" : "Value1",
     "Count1": 28,
     "Count2": 28
  },
  {
     "Key" : "Value2",
     "Count3": 16,
     "Count4": 16
  }
]

Is it possible?

The gremlin that produces a similar output

g.V().
has('organizationId', 'b121672e-8049-40cc-9f28-c62dff4cc2d9').
hasLabel('employee').

group().
by('officeId').
by(project('Id', 'Status').
    by(choose(has('officeId'), constant('Total'), constant(''))).
    by(coalesce(out('hasStatus').
                or(
                        has('release', is(false)),
                        has('autoRelease', is(true)).
                        has('release', is(true)).
                        has('endDate', gte(637250976000000000))
                 ), values('status'), constant('Green'))).
    select(values).
    unfold().
    groupCount()).

    project('Id', 'Count').
    by(select(keys)).
    by(select(values))

And the data that I have is an employee vertex and a healthStatus vertex, there's an hasStatus edge between employee and healthStatus

Properties in employee vertex:
id, organizations, officeId, Name, createdOn

Properties in healthStatus vertex:
id, status, startDate, endDate, release, autoRelease, createdOn

Sample Data

 g.addV('employee').
       property('id',1).
       property('organizationId',1).
       property('officeId',1).
       property('name','A').
       property('createdOn', 637263231140000000).as('1').
    addV('employee').
       property('id',2).
       property('organizationId',1).
       property('officeId',2).
       property('name','B').
       property('createdOn', 637263231140000000).as('2').
   addV('employee').
       property('id',5).
       property('organizationId',1).
       property('officeId',3).
       property('name','C').
       property('createdOn', 637263231140000000).as('5').
    addV('healthStatus').
       property('id',3).
       property('status','Red').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000)as('3').
    addV('healthStatus').
       property('id',4).
       property('status','Yellow').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000)as('4').
    addE('hasStatus').from('1').to('3').
    addE('hasStatus').from('4').to('4')

Output:

[
  {
    "Id" : [
        1,
        2,
        3
      ]
  },
  {
    "Count": [
      {
         "Red" : 1
      },
      {
         "Yellow" : 1
      },
      {
         "Green" : 1
      }
    ]
  }

Expected Output

[
  {
     "Id" : 1,
     "Red" : 1
  },
  {
     "Id" : 2,
     "Yellow" : 1
  },
  {
     "Id" : 3,
     "Green" : 1
  }
]

Note : This Id in projection is officeId from employee vertex

Body:
I think I've captured what you wanted. There were some errors in your sample data script and I wanted some extra data to make sure counts were making sense so I added a bit:

 g = TinkerGraph.open().traversal()
 g.addV('employee').
       property('id',1).
       property('organizationId',1).
       property('officeId',1).
       property('name','A').
       property('createdOn', 637263231140000000).as('1').
    addV('employee').
       property('id',2).
       property('organizationId',1).
       property('officeId',2).
       property('name','B').
       property('createdOn', 637263231140000000).as('2').
   addV('employee').
       property('id',5).
       property('organizationId',1).
       property('officeId',3).
       property('name','C').
       property('createdOn', 637263231140000000).as('5').
   addV('employee').
       property('id',6).
       property('organizationId',1).
       property('officeId',3).
       property('name','D').
       property('createdOn', 637263231140000000).as('6').
    addV('healthStatus').
       property('id',3).
       property('status','Red').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000).as('3').
    addV('healthStatus').
       property('id',4).
       property('status','Yellow').
       property('startDate',637262367140000000).
       property('endDate',637264095140000000).
       property('release',false).
       property('createdOn',637262367140000000).as('4').
    addE('hasStatus').from('1').to('3').
    addE('hasStatus').from('2').to('4').
    addE('hasStatus').from('6').to('4')

I've re-written you traversal a bit to provide a different approach that I think provides the data you expect, however in a slightly different form:

gremlin> g.V().has('employee','organizationId', 1).
......1>   project('Id', 'Status').
......2>     by('officeId').
......3>     by(coalesce(out('hasStatus').
......4>                 or(has('release', false),
......5>                    has('autoRelease', true).has('release', true).has('endDate', gte(637250976000000000))).
......6>                 values('status'),
......7>                 constant('Green'))).
......8>   group().
......9>     by(select('Id')).
.....10>     by(groupCount().
.....11>          by('Status'))
==>[1:[Red:1],2:[Yellow:1],3:[Yellow:1,Green:1]]

I prefer this form a bit, but perhaps you require the original format you inquired about, in which case you need another round of manipulation on the collection:

gremlin> g.V().has('employee','organizationId', 1).
......1>   project('Id', 'Status').
......2>     by('officeId').
......3>     by(coalesce(out('hasStatus').
......4>                 or(has('release', false),
......5>                    has('autoRelease', true).has('release', true).has('endDate', gte(637250976000000000))).
......6>                 values('status'),
......7>                 constant('Green'))).
......8>   group().
......9>     by(select('Id')).
.....10>     by(groupCount().
.....11>          by('Status')).
.....12>   unfold().
.....13>   map(union(project('Id').by(select(keys)),
.....14>             select(values)).
.....15>       unfold().
.....16>       group().by(keys).by(select(values)))
==>[Red:1,Id:1]
==>[Yellow:1,Id:2]
==>[Yellow:1,Id:3,Green:1]


问:
Download file/folder from Public AWS S3 with Python, no credentials
I have opened a public access to S3 bucket and I need to download files / folders with files from the bucket using python. The trick is that I do not want to supply credentials (which boto3 apparently requires). Is it even possible?</p>

答:
You can use  GetObject  from the S3 REST API, together with the Requests library in Python. If you grant READ access to the anonymous user, you can return the object without using an authorization header.

Example of such an S3 REST call::

```<code>> GET /example-object HTTP/1.1
> Host: example-bucket.s3.<Region>.amazonaws.com
</code>```

Python(rough example):

```<code>import requests
url = '/example-object'
headers = {'Host': 'example-bucket.s3.<Region>.amazonaws.com'}
r = requests.get(url, headers=headers)
</code>```

Requests

GetObject

Body:
You can use  GetObject  from the S3 REST API, together with the Requests library in Python. If you grant READ access to the anonymous user, you can return the object without using an authorization header.

Example of such an S3 REST call::

> GET /example-object HTTP/1.1
> Host: example-bucket.s3.<Region>.amazonaws.com

Python(rough example):

import requests
url = '/example-object'
headers = {'Host': 'example-bucket.s3.<Region>.amazonaws.com'}
r = requests.get(url, headers=headers)

Requests

GetObject


问:
Best way to convert FAQ with images into a knowledge base for a QnA bot
I have an FAQ document (MS word) that I want to convert into a QnA knowledge base to support a QnA bot.  I can use QnA Maker to import text from the document but all images get stripped out.  Without the images the answers are nonsensical.  I know QnA maker supports markdown so I could add the images back with image markdown tags.  This is time consuming and requires the images be stored somewhere that can be accessed by QnA maker (eg Azure blog storage).  The other issue with this is that my bot uses Hero Cards for follow on questions (I believe this is the recommended approach for handling follow on questions).  However, Hero Cards don't support markdown.  I could use adaptive cards instead of hero cards.  Adaptive cards do support markdown but not the image tag :(.  Also, markdown is not exactly user friendly.  It's fine if someone technical is managing the KB.  But if this is the responsibility of a non-technical person then markdown isn't ideal.

The fact that QnA Maker doesn't effectively support images seems like a significant oversight.  I get that bot conversations should involve short exchanges between bot and user.  But (apologies for the cliche) a picture is worth a 1000 words sometimes.

Griping aside, does anyone have suggestions on how to effectively build a KB with images?  I'm also open to alternative suggestions on how to use a bot as a front end to an image rich FAQ.  I should also add that my bot is accessed via MS Teams.

Thanks

答:
Not a complete answer but I just noticed (or QnA interface was recently added) that you can edit QnA answers without the need to write markdown directly (hurray!).  You can even add images though you still need to store/organize them yourself
 (screen shot of edit bar).  You can also leave your answer as MD if you'd prefer to edit them directly.</p>


问:
Convert XML data to Pandas
I want to extract data from an XML and convert it to Pandas Data Frame

First off i tried importing with Element Tree xml and just print out some of the columns with this code, no luck

So for now i've managed to extract some of the data with this code

import xml.etree.cElementTree as et
import pandas as pd
def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None
def main():
    """ main """
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)
    for node in parsed_xml.getroot():
        start = node.attrib.get('start')
        stop = node.attrib.get('stop')
        channel = node.attrib.get('channel')
        type = node.attrib.get('type')
        title = node.find('title')
        category = node.find('category')
        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type, getvalueofnode(category), getvalueofnode(title)], index=dfcols),
            ignore_index=True)
    print (df_xml)'
```

<p><strong>But title  and category are still empty</strong></p>

<p>This is example of XML:</p>

```    <?xml version="1.0" encoding="utf-8"?>
<tv xmlns="http://www.xmltv.org/xmltv" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <programme ID="58135" start="20200528000000 +0200" stop="20200528013000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Yoga retreat]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
  <programme ID="58136" start="20200528013000 +0200" stop="20200528030000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Doctor Who]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
</tv>
```

desired output that i would like is that i get this columns:

channel, start, stop, title, category

答:
The XML document uses a default namespace (http://www.xmltv.org/xmltv).

One way to do what you want is to use findall() and find() with a wildcard ({*}) for the namespace. This works with Python 3.8.

```<code>import xml.etree.ElementTree as et
import pandas as pd

def getvalueofnode(node):
    return node.text if node is not None else None

def main():
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)

    for programme in parsed_xml.findall("{*}programme"):
        start = programme.get('start')
        stop = programme.get('stop')
        channel = programme.get('channel')
        type = programme.get('type')

        title = programme.find('{*}title')
        category = programme.find('{*}category')

        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type,
                       getvalueofnode(title), getvalueofnode(category)], index=dfcols),
            ignore_index=True)

    pd.options.display.width = 0
    print (df_xml)

main()
</code>```

Result:

```<code>                  start                  stop       channel     type         title       category
0  20200528000000 +0200  20200528013000 +0200  XTV100006361  program  Yoga retreat  Entertainment
1  20200528013000 +0200  20200528030000 +0200  XTV100006361  program    Doctor Who  Entertainment
</code>```

Title: Convert XML data to Pandas

Body:
I want to extract data from an XML and convert it to Pandas Data Frame

First off i tried importing with Element Tree xml and just print out some of the columns with this code, no luck

So for now i've managed to extract some of the data with this code

import xml.etree.cElementTree as et
import pandas as pd
def getvalueofnode(node):
    """ return node text or None """
    return node.text if node is not None else None
def main():
    """ main """
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)
    for node in parsed_xml.getroot():
        start = node.attrib.get('start')
        stop = node.attrib.get('stop')
        channel = node.attrib.get('channel')
        type = node.attrib.get('type')
        title = node.find('title')
        category = node.find('category')
        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type, getvalueofnode(category), getvalueofnode(title)], index=dfcols),
            ignore_index=True)
    print (df_xml)'

But title  and category are still empty

This is example of XML:

    <?xml version="1.0" encoding="utf-8"?>
<tv xmlns="http://www.xmltv.org/xmltv" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <programme ID="58135" start="20200528000000 +0200" stop="20200528013000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Yoga retreat]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
  <programme ID="58136" start="20200528013000 +0200" stop="20200528030000 +0200" channel="XTV100006361" recordable="Y" npvrenable="Y" cpvrenable="N" type="program" deleted="false">
    <blackoutInfo>
      <isBlackout>1</isBlackout>
      <groupIDs>2</groupIDs>
      <streams>00000001</streams>
    </blackoutInfo>
    <title lang="sr"><![CDATA[Doctor Who]]></title>
    <category lang="sr"><![CDATA[Entertainment]]></category>
    <icon src="default_playbill.png" ptype="3" />
    <episode-num system="xmltv_ns">0.0.0</episode-num>
  </programme>
</tv>

desired output that i would like is that i get this columns:

channel, start, stop, title, category

Body:
The XML document uses a default namespace (http://www.xmltv.org/xmltv).

One way to do what you want is to use findall() and find() with a wildcard ({*}) for the namespace. This works with Python 3.8.

import xml.etree.ElementTree as et
import pandas as pd

def getvalueofnode(node):
    return node.text if node is not None else None

def main():
    parsed_xml = et.parse("RTS_XTV100006361.xml")
    dfcols = ['start', 'stop', 'channel', 'type', 'title', 'category']
    df_xml = pd.DataFrame(columns=dfcols)

    for programme in parsed_xml.findall("{*}programme"):
        start = programme.get('start')
        stop = programme.get('stop')
        channel = programme.get('channel')
        type = programme.get('type')

        title = programme.find('{*}title')
        category = programme.find('{*}category')

        df_xml = df_xml.append(
            pd.Series([start, stop, channel, type,
                       getvalueofnode(title), getvalueofnode(category)], index=dfcols),
            ignore_index=True)

    pd.options.display.width = 0
    print (df_xml)

main()

Result:

                  start                  stop       channel     type         title       category
0  20200528000000 +0200  20200528013000 +0200  XTV100006361  program  Yoga retreat  Entertainment
1  20200528013000 +0200  20200528030000 +0200  XTV100006361  program    Doctor Who  Entertainment


问:
Issue with counting upper and lower letters in C
I've written a program which should count upper and lower letters and other signs but it counts anything but when I click Enter and then ^C (EOF). I don't know how to jump over it, hope somebody can help me somehow <3</p>

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

int main()
{
  char ch;
  int uppers = 0, lowers = 0, others = 0;

  while((ch = getchar()) != EOF)
  {
    if(islower(ch))
      lowers++;

    else if(isupper(ch))
      uppers++;

    else
      others++;
  }

  printf("\n\nUpper letters - %d  Lower letters - %d   Others- %d", uppers, lowers, others);

  return 0;
}
</code>```

答:
CherryDt has already provided an appropriate answer.

But just to add to that, EOF is not a character but instead an end condition. It may be OS dependent. You can't rely on it to work the same manner in every environment. My suggest would be to use any character itself as a condition to terminate loop, rather than an condition which is environment dependent.

NOTE : The solution worked of ending the program with keys worked for me on Windows only when I included a fflush(stdin); after the getchar(). Probably, getchar() takes the input you give and leaves newline character \n in the input stream which was causing problem when I tried to terminate using ctrl+D or ctrl+Z or F6.

But once you include fflush(stdin), this would solve the problem and now the program ends successfully when I use the F6 on Windows. You can also try with above mentioned keys if this does not work for you.

Hope this helps some Windows users if the above answer wasn't working for them.

Body:
I've written a program which should count upper and lower letters and other signs but it counts anything but when I click Enter and then ^C (EOF). I don't know how to jump over it, hope somebody can help me somehow <3

#include <stdio.h>
#include <ctype.h>

int main()
{
  char ch;
  int uppers = 0, lowers = 0, others = 0;

  while((ch = getchar()) != EOF)
  {
    if(islower(ch))
      lowers++;

    else if(isupper(ch))
      uppers++;

    else
      others++;
  }

  printf("\n\nUpper letters - %d  Lower letters - %d   Others- %d", uppers, lowers, others);

  return 0;
}