问:
Django can AJAX field filter be designed with CreateView?
I already ahve a CreateView which handles creating objects. I am wondering if I can simply put an AJAX response in the get method to allow for the form fields to be filtered based on previous selections.

e.g. If a user selects an option in the "Category" field called "Food/Beverage" then I send over an AJAX request to GET the queryset which is filtered for that Category, then update the form.

Is this how it is accomplished?

Is this usually done in the get_queryset method or another method?

Is this normally done in a separate view? Should I be using a generic View which is sparate from the CreateView for this?

答:
Let me give you a kick-start.

It is common practice to use Ajax to trigger view functions async. A basic setup could look as follows:

Ajax

```<code>get_queryset = function () {
    $.ajax('get_queryset/', {
            method: 'GET',
            async: "True",
            dataType: "json",
            success: function(response) {
              var queryset = response;

              item = queryset[0].fields.datafield;

            },
    })
}
</code>```

Views.py

```<code># Async Function for Ajax

def get_query(*args, **kwargs):

    # Query all Objects from Model
    queryset = serializers.serialize('json', Entry.objects.all())
    return HttpResponse(queryset)
</code>```

Urls.py

```<code>urlpatterns = [

    path('app/get_queryset/', get_query),
]
</code>```

I hope this is what you are pointing to.

Edit about the filtering:

You filter the queryset straight in your view. So that the server returns the desired data via AJAX to the client-side. Also note that proper query filtering can reduce the amount of queries to the database and therefor increase speed (though this shouldn't be the key impact in smaller applications).

There are a whole bunch of filter and exception methods built-in in Django:
https://docs.djangoproject.com/en/3.0/topics/db/queries/

Check for making queries.

Additionally, if you want to update your html with the new data, you can loop the query dataset and manipulate the aimed html for each item in the queryset like so:

```<code>{% for item in queryset %}

<p>{{ item.field_name_one }}</p>
          [...]
          [...]
<p>{{ item.field_name_two }}</p>

{% endfor %}
</code>```

So if the database query returns 5 items from the database, it will create 5
 elements.

Body:
Let me give you a kick-start.

It is common practice to use Ajax to trigger view functions async. A basic setup could look as follows:

Ajax

get_queryset = function () {
    $.ajax('get_queryset/', {
            method: 'GET',
            async: "True",
            dataType: "json",
            success: function(response) {
              var queryset = response;

              item = queryset[0].fields.datafield;

            },
    })
}

Views.py

# Async Function for Ajax

def get_query(*args, **kwargs):

    # Query all Objects from Model
    queryset = serializers.serialize('json', Entry.objects.all())
    return HttpResponse(queryset)

Urls.py

urlpatterns = [

    path('app/get_queryset/', get_query),
]

I hope this is what you are pointing to.

Edit about the filtering:

You filter the queryset straight in your view. So that the server returns the desired data via AJAX to the client-side. Also note that proper query filtering can reduce the amount of queries to the database and therefor increase speed (though this shouldn't be the key impact in smaller applications).

There are a whole bunch of filter and exception methods built-in in Django:
https://docs.djangoproject.com/en/3.0/topics/db/queries/

Check for making queries.

Additionally, if you want to update your html with the new data, you can loop the query dataset and manipulate the aimed html for each item in the queryset like so:

{% for item in queryset %}

<p>{{ item.field_name_one }}</p>
          [...]
          [...]
<p>{{ item.field_name_two }}</p>

{% endfor %}

So if the database query returns 5 items from the database, it will create 5 <p> elements.


来源: stackexchange

问:
NextJS config file module exports set up
I have looked into other answer that the way to add multiple plugins into next.js config fil is to use composition. However this is not working for me.

```<code>const Dotenv = require('dotenv-webpack');
const withStyles = require('@webdeb/next-styles');

module.exports = withStyles(
  {
    webpack(config, options) {
      config.plugins.push(new Dotenv({ silent: true }));
      return config;
    },
    env: {
      NEXT_PUBLIC_BACKEND_HOST: process.env.NEXT_PUBLIC_BACKEND_HOST,
      AUTH_SECRET: process.env.AUTH_SECRET,
    },
  },
  {
    sass: true, // use .scss files
    modules: true, // style.(m|module).css & style.(m|module).scss for module files
  },
);
</code>```

The above throws an error when I try to import my SCSS file into my component.

However having just

```<code>module.exports = withStyles(
{
  sass: true, // use .scss files
  modules: true, // style.(m|module).css & style.(m|module).scss for module files
},
);
</code>```

Works fine and load my CSS correctly

答:
withStyles only accepts 1 object, in your non-working config you have 2. You want something like the following</p>

```<code>const Dotenv = require('dotenv-webpack');
const withStyles = require('@webdeb/next-styles');

module.exports = withStyles(
  {
    webpack(config, options) {
      config.plugins.push(new Dotenv({ silent: true }));
      return config;
    },
    env: {
      NEXT_PUBLIC_BACKEND_HOST: process.env.NEXT_PUBLIC_BACKEND_HOST,
      AUTH_SECRET: process.env.AUTH_SECRET,
    },
    sass: true, // use .scss files
    modules: true, // style.(m|module).css & style.(m|module).scss for module files
  },
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have looked into other answer that the way to add multiple plugins into next.js config fil is to use composition. However this is not working for me.

const Dotenv = require('dotenv-webpack');
const withStyles = require('@webdeb/next-styles');

module.exports = withStyles(
  {
    webpack(config, options) {
      config.plugins.push(new Dotenv({ silent: true }));
      return config;
    },
    env: {
      NEXT_PUBLIC_BACKEND_HOST: process.env.NEXT_PUBLIC_BACKEND_HOST,
      AUTH_SECRET: process.env.AUTH_SECRET,
    },
  },
  {
    sass: true, // use .scss files
    modules: true, // style.(m|module).css & style.(m|module).scss for module files
  },
);

The above throws an error when I try to import my SCSS file into my component.

However having just

module.exports = withStyles(
{
  sass: true, // use .scss files
  modules: true, // style.(m|module).css & style.(m|module).scss for module files
},
);

Works fine and load my CSS correctly

Body:
withStyles only accepts 1 object, in your non-working config you have 2. You want something like the following

const Dotenv = require('dotenv-webpack');
const withStyles = require('@webdeb/next-styles');

module.exports = withStyles(
  {
    webpack(config, options) {
      config.plugins.push(new Dotenv({ silent: true }));
      return config;
    },
    env: {
      NEXT_PUBLIC_BACKEND_HOST: process.env.NEXT_PUBLIC_BACKEND_HOST,
      AUTH_SECRET: process.env.AUTH_SECRET,
    },
    sass: true, // use .scss files
    modules: true, // style.(m|module).css & style.(m|module).scss for module files
  },
);


问:
Weird behavior of PHP fix for CORS policy
I am developing an application using Angular which runs on port 4200 (localhost). It gets the information from PHP REST API which runs on post 80 (localhost). When I developed a contact us page it was throwing error related to CORS policy which was fixed by placing the following header information in .htaccess file.

```<code>Header add Access-Control-Allow-Origin "http://localhost:4200"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Max-Age "36000"
</code>```

The contact us page is working fine now and I am able to post information (queries) and they are updating in the database correctly.
But now I have developed register user functionality and I am facing a weird problem here. Sometimes I am seeing the CORS policy issue that

```<code>Access to XMLHttpRequest at 'http://localhost/carrentalnew/register' from origin 'http://localhost:4200'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does
not have HTTP ok status.
</code>```

So when I get this error, I am going to PHP api program I developed, and entering some info in the middle of the script so that the script fails.
For example the following is piece of code where in the middle I entered "hello" so that the script fails.

```<code>catch(PDOException $ex) {
  // log connection error for troubleshooting and return a json error response
  error_log("Connection Error: ".$ex, 0);
  $response = new Response();
  $response->setHttpStatusCode(500);
  $response->setSuccess(false);
  $response->addMessage("Database connection error");
  $response->send();
  exit;
}

hello

// handle creating new user
// check to make sure the request is POST only - else exit with error response
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
  $response = new Response();
  $response->setHttpStatusCode(405);
  $response->setSuccess(false);
  $response->addMessage("Request method not allowed");
  $response->send();
  exit;
}
</code>```

Now I am removing the word "hello" and I am trying to post the register user again and it is working fine and no issues at all. This is a very weird behavior I am seeing. Can any one tell me what mistake I am doing here?

Thanks,
Subbu.

答:
For cross origin requests, browser sends pre-flight request with Method Options.
In that case we have to send response with access control allow origin header

In your case as you have already added in ht access, we can just exit if it is options method

```<code>if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
   return 0;
}
</code>```

As you are sending http error response, browser thinks this is a invalid Cross origin request

Body:
I am developing an application using Angular which runs on port 4200 (localhost). It gets the information from PHP REST API which runs on post 80 (localhost). When I developed a contact us page it was throwing error related to CORS policy which was fixed by placing the following header information in .htaccess file.

Header add Access-Control-Allow-Origin "http://localhost:4200"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Max-Age "36000"

The contact us page is working fine now and I am able to post information (queries) and they are updating in the database correctly.
But now I have developed register user functionality and I am facing a weird problem here. Sometimes I am seeing the CORS policy issue that

Access to XMLHttpRequest at 'http://localhost/carrentalnew/register' from origin 'http://localhost:4200'
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does
not have HTTP ok status.

So when I get this error, I am going to PHP api program I developed, and entering some info in the middle of the script so that the script fails.
For example the following is piece of code where in the middle I entered "hello" so that the script fails.

catch(PDOException $ex) {
  // log connection error for troubleshooting and return a json error response
  error_log("Connection Error: ".$ex, 0);
  $response = new Response();
  $response->setHttpStatusCode(500);
  $response->setSuccess(false);
  $response->addMessage("Database connection error");
  $response->send();
  exit;
}

hello

// handle creating new user
// check to make sure the request is POST only - else exit with error response
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
  $response = new Response();
  $response->setHttpStatusCode(405);
  $response->setSuccess(false);
  $response->addMessage("Request method not allowed");
  $response->send();
  exit;
}

Now I am removing the word "hello" and I am trying to post the register user again and it is working fine and no issues at all. This is a very weird behavior I am seeing. Can any one tell me what mistake I am doing here?

Thanks,
Subbu.

Body:
For cross origin requests, browser sends pre-flight request with Method Options.
In that case we have to send response with access control allow origin header

In your case as you have already added in ht access, we can just exit if it is options method

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
   return 0;
}

As you are sending http error response, browser thinks this is a invalid Cross origin request


问:
Writing out a binary structure to file, unexpected results?
I'm trying to write out a packed data structure to a binary file, however as you can see from od -x below the results are not expected in their ordering.  I'm using gcc on a 64-bit Intel system.  Does anyone know why the ordering is wrong?  It doesn't look like an endianness issue.

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

struct B {
     char a;
     int b;
     char c;
     short d;
} __attribute__ ((packed));

int main(int argc, char *argv[])
{
     FILE *fp;
     fp = fopen("temp.bin", "w");

     struct B b = {'a', 0xA5A5, 'b', 0xFF};

     if (fwrite(&b, sizeof(b), 1, fp) != 1)
          printf("Error fwrite\n");

     exit(0);
}
</code>```

ASCII 61 is 'a', so the b.a member.  ASCII 62 is 'b', so the b.c member.  It's odd how 0xA5A5 is spread out over the sequence.

```<code>$ od -x temp.bin
0000000 a561 00a5 6200 00ff
0000010
</code>```

答:
od -x groups the input into 2-byte units and swaps their endianness. It's a confusing output format. Use -t x1 to leave the bytes alone.

```<code>$ od -t x1 temp.bin
0000000 61 a5 a5 00 00 62 ff 00
0000010
</code>```

Or, easier to remember, use hd (hex dump) instead of od (octal dump). hd's default format doesn't need adjusting, plus it shows both a hex and ASCII dump.

```<code>$ hd temp.bin
00000000  61 a5 a5 00 00 62 ff 00                           |a....b..|
00000008
</code>```

Body:
I'm trying to write out a packed data structure to a binary file, however as you can see from od -x below the results are not expected in their ordering.  I'm using gcc on a 64-bit Intel system.  Does anyone know why the ordering is wrong?  It doesn't look like an endianness issue.

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

struct B {
     char a;
     int b;
     char c;
     short d;
} __attribute__ ((packed));

int main(int argc, char *argv[])
{
     FILE *fp;
     fp = fopen("temp.bin", "w");

     struct B b = {'a', 0xA5A5, 'b', 0xFF};

     if (fwrite(&b, sizeof(b), 1, fp) != 1)
          printf("Error fwrite\n");

     exit(0);
}

ASCII 61 is 'a', so the b.a member.  ASCII 62 is 'b', so the b.c member.  It's odd how 0xA5A5 is spread out over the sequence.

$ od -x temp.bin
0000000 a561 00a5 6200 00ff
0000010

Body:
od -x groups the input into 2-byte units and swaps their endianness. It's a confusing output format. Use -t x1 to leave the bytes alone.

$ od -t x1 temp.bin
0000000 61 a5 a5 00 00 62 ff 00
0000010

Or, easier to remember, use hd (hex dump) instead of od (octal dump). hd's default format doesn't need adjusting, plus it shows both a hex and ASCII dump.

$ hd temp.bin
00000000  61 a5 a5 00 00 62 ff 00                           |a....b..|
00000008


问:
Disposing Observable Inside Android Paging Library Data Source
I want to observe my network call changes inside my PageKeyedDataSource and Dispose of the RxJava subscription after user quitting a Fragment which leads to Data Source destruction.

```<code>class ProjectDataSource : PageKeyedDataSource<Int, ProjectPresenter>(), KoinComponent {
    ...

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, ProjectPresenter>
    ) {
        val subscription = mProjectRepository.getProjects(DEFAULT_TAKE, 0)
            .subscribe(
                { projectPresenters ->
                    ...
                },
                { throwable ->
                    ...
                }
            )
          //Where to dispose `subscription`
    }

    ...
}
</code>```

I have RxJava subscription in both my Repository and DataSource that both perform different operations on data. A Repository converts a remote model to a presenter model and ...

I'm not really sure it's a good idea to observe data inside DataSource.

答:
I cannot provide any substantial proof my way is "right way" but here is what I think and typically follow in implementation:

Unless some really edge case, I do not handle disposing under repository or data source

If my repository is using Rx, I'm simply exposing all my Rx entities (Completable's, Single's etc) to consumers (typically view models), they subscribe and they manage disposing (in many cases by clearing them in onCleared)

If my paging data source is using Rx (which by the way can cause unwanted UI effects during invalidation, it is better to run blocking ops in data source loadInitial and methods alike), I'm routing CompositeDisposable instance from view model through data source factory.

Body:
I want to observe my network call changes inside my PageKeyedDataSource and Dispose of the RxJava subscription after user quitting a Fragment which leads to Data Source destruction.

class ProjectDataSource : PageKeyedDataSource<Int, ProjectPresenter>(), KoinComponent {
    ...

    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, ProjectPresenter>
    ) {
        val subscription = mProjectRepository.getProjects(DEFAULT_TAKE, 0)
            .subscribe(
                { projectPresenters ->
                    ...
                },
                { throwable ->
                    ...
                }
            )
          //Where to dispose `subscription`
    }

    ...
}

I have RxJava subscription in both my Repository and DataSource that both perform different operations on data. A Repository converts a remote model to a presenter model and ...

I'm not really sure it's a good idea to observe data inside DataSource.


问:
5/2 is 2 but I'm getting the one in index 3
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates) </p>

```<code>public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.
</code>```

答:
```<code>ListNode x = new ListNode(1);
ListNode y = new ListNode(2, x);
ListNode a = new ListNode(3, y);
ListNode b = new ListNode(4, a);
ListNode c = new ListNode(5, b);
ListNode d = new ListNode(6, c);
</code>```

After you add all the nodes, then your LinkedList will be like this.

```<code>Head d -> c -> b -> a -> y -> x Tail
</code>```

you are passing the head into the while loop to iterate.
so your loop should start with the head and add the values into the same order as you already added.

after you finish your while loop your A node should look like this.

```<code>A[0] - d
A[1] - c
A[2] - b
A[3] - a
A[4] - y
</code>```

You can't get A[5] and x node because x node next has a null value and your condition is while(head.next()!=null)

finally if you return A[5 / 2] then you will get A[2] which contains b node.

when you print r.val you will get b node value 4.

Body:
I have a linked list 1-2-3-4-5-6. I need to get 4. I have a method that inserts all in the array and calculate the middle. if there are two, I'm printing the second one. in my head the method(I have on my text book) prints 3 but when I actually run it I get 4(as the text book indicates)

public static void main(String[] args) {
    ListNode x = new ListNode(1);

    ListNode y = new ListNode(2,x);
    ListNode a = new ListNode(3, y);
    ListNode b = new ListNode(4, a);
    ListNode c = new ListNode(5, b);
    ListNode d = new ListNode(6, c);

    ListNode r= middleNode(d);
    System.out.println(r.val);

}
public static ListNode middleNode(ListNode head) {
    ListNode[] A = new ListNode[100];
    int t = 0;
    while (head.next != null) {
        A[t++] = head;
        head = head.next;
    }
    return A[5 / 2];

}
A[0] = 1
A[1] = 2
A[2] = 3
A[3] = 4
A[4] = 5
A[5] = 6

A[t] =5 t being 5
thus t/2 = 2. so should print 3.

Body:
ListNode x = new ListNode(1);
ListNode y = new ListNode(2, x);
ListNode a = new ListNode(3, y);
ListNode b = new ListNode(4, a);
ListNode c = new ListNode(5, b);
ListNode d = new ListNode(6, c);

After you add all the nodes, then your LinkedList will be like this.

Head d -> c -> b -> a -> y -> x Tail

you are passing the head into the while loop to iterate.
so your loop should start with the head and add the values into the same order as you already added.

after you finish your while loop your A node should look like this.

A[0] - d
A[1] - c
A[2] - b
A[3] - a
A[4] - y

You can't get A[5] and x node because x node next has a null value and your condition is while(head.next()!=null)

finally if you return A[5 / 2] then you will get A[2] which contains b node.

when you print r.val you will get b node value 4.


问:
Put JSON data into html form input hidden?
I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.

This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.

This is a solution I found some time ago:

```<code><a href="bla" data-itemId="1" .... more data.
</code>```

There are two problems with this method.

I can't represent arrays.

It's just ugly.

I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:

```<code>{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
</code>```

This json was inside an input[type=hidden] element.

I tried to do the same thing with json_encode();

```<code><input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
</code>```

But when I try getting the value I get this {.

I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.

How can I put JSON into HTML correctly and then get it with jquery/javascript?

答:
php
set array in </p>

```<code><input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>
</code>```

Body:
I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.

This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.

This is a solution I found some time ago:

<a href="bla" data-itemId="1" .... more data.

There are two problems with this method.

I can't represent arrays.

It's just ugly.

I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:

{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}

This json was inside an input[type=hidden] element.

I tried to do the same thing with json_encode();

<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />

But when I try getting the value I get this {.

I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.

How can I put JSON into HTML correctly and then get it with jquery/javascript?

Body:
php
set array in

<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>


问:
Start two springboot apps in eclipse
Is it possible to start two spring boot applications in eclipse, in the same workspace in the same time? How can i set two different ports for that two spring boot applications?</p>

答:
Follow these steps:

Go to /src/main/resources/application.properties

Add server.port= PortNo(for example server.port=8081 in first app's application.properties and server.port=8082 in second app's application.properties)

Right-click on each application one by one and Run As Spring Boot App

Go the browser and hit localhost:8081 for the first app and localhost:8082 for the second app, it should work.

ContentLicense: CC BY-SA 3.0

Title: Start two springboot apps in eclipse


问:
Easiest way to map Azure Table Storage Data Model in Node.js
When I want to add my javascript objects (or entities) to my Azure Table Storage, I first need to run them through the entityGenerator.

My objects could look like this:

```<code>{
  id: 1,
  name: 'foo',
  timestamp: new Date()
}
</code>```

The entities I need to pass to the TableService are going to look like this:

```<code>{
  id: { '_': 1, '$': 'Edm.Int32' },
  name: { '_': 'foo', '$': 'Edm.String' },
  timestamp:{ '_': new Date(), '$': 'Edm.DateTime' },
}
</code>```

This is also the format in which the entities are returned from the TableService.

To map my objects to the correct format for sending them to my Table Storage is pretty straightforward, but I haven't found an easy way to convert the returned entities form my service back to regular JavaScript objects I can easily work with.

I could create some sort of generic mapper function to get the values out of the _ property on the entities, but it seems that some metadata properties are also passed into the entities itself.

Does anyone know of an easy way to map between JavaScript objects and Azure Table Storage entities?

Is (or should) this functionality be included in the azure-storage library?

答:
In case someone else stumbles upon this: you can access the values in the body part of response. The result contains the actual table entity.

So to access the name part in the example use response.body.name.

Body:
When I want to add my javascript objects (or entities) to my Azure Table Storage, I first need to run them through the entityGenerator.

My objects could look like this:

{
  id: 1,
  name: 'foo',
  timestamp: new Date()
}

The entities I need to pass to the TableService are going to look like this:

{
  id: { '_': 1, '$': 'Edm.Int32' },
  name: { '_': 'foo', '$': 'Edm.String' },
  timestamp:{ '_': new Date(), '$': 'Edm.DateTime' },
}

This is also the format in which the entities are returned from the TableService.

To map my objects to the correct format for sending them to my Table Storage is pretty straightforward, but I haven't found an easy way to convert the returned entities form my service back to regular JavaScript objects I can easily work with.

I could create some sort of generic mapper function to get the values out of the _ property on the entities, but it seems that some metadata properties are also passed into the entities itself.

Does anyone know of an easy way to map between JavaScript objects and Azure Table Storage entities?

Is (or should) this functionality be included in the azure-storage library?


问:
Multi-threaded method to rearrange array?
I have character array just like 'XOOOXOX' and I need to rearrange this array-like 'XXXOOOO'. I can create simple python code for this. But I am find a way to do it using multithreading. Can anyone help me to do this?</p>

答:
This might be a funny answer, but the question was about using threads. So I just created a dummy threading work. This might won't show a performance gain at all:

import random
import threading

a = random.choices(['X', 'O'], k=10000)
a = ''.join(a)

print(a.count('X'), a.count('O'))

thread_count = 4
lock = threading.Lock()

x_count = 0
o_count = 0

def chunk_it(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

def d(i):
    global x_count
    global o_count

    data_part = chunk_it(a, thread_count)[i]

    with lock:
        x_count += data_part.count('X')
        o_count += data_part.count('O')

ts = []
for i in range(thread_count):
    t = threading.Thread(target=d, args=(i, ))
    ts.append(t)

for t in ts:
    t.start()

for t in ts:
    t.join()

a = 'X' * x_count + 'O' * o_count
print(a)
print(a.count('X'), a.count('O'))
```

You can copy and try it.

This demo meant to show using a relatively lower level threading api.

Concurrency in python led by several modules: threading, multiprocessing, concurrent.futures, asyncio and so. You definitely might want to check out these. Diving right into official documentations might be difficult for this concept. You should read from others and practice.

Body:
This might be a funny answer, but the question was about using threads. So I just created a dummy threading work. This might won't show a performance gain at all:

import random
import threading

a = random.choices(['X', 'O'], k=10000)
a = ''.join(a)

print(a.count('X'), a.count('O'))

thread_count = 4
lock = threading.Lock()

x_count = 0
o_count = 0

def chunk_it(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

def d(i):
    global x_count
    global o_count

    data_part = chunk_it(a, thread_count)[i]

    with lock:
        x_count += data_part.count('X')
        o_count += data_part.count('O')

ts = []
for i in range(thread_count):
    t = threading.Thread(target=d, args=(i, ))
    ts.append(t)

for t in ts:
    t.start()

for t in ts:
    t.join()

a = 'X' * x_count + 'O' * o_count
print(a)
print(a.count('X'), a.count('O'))

You can copy and try it.

This demo meant to show using a relatively lower level threading api.

Concurrency in python led by several modules: threading, multiprocessing, concurrent.futures, asyncio and so. You definitely might want to check out these. Diving right into official documentations might be difficult for this concept. You should read from others and practice.


问:
Alternative to regular PHP Class
Generally when creating a PHP class I would do something as such

```<code>class Foo
{
    public function Foo(){}
    public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();
</code>```

I have noticed that on the web people are frowning upon the global vars for classes but without it I would not be able to access the class inside other functions.

Now an alternative to this would be using static classes as such:

```<code>class Foo
{
    static public function RandomFunction(){}
}
Foo::RandomFunction();
</code>```

My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?

答:
In good OO practice, if a class needs to access an instance of another class, you pass object in as a parameter and then access it's properties and methods from there.

If you have a well designed object model the code should be relatively clean and logical, however if you aren't planning on creating a strict OO application, you probably shouldn't worry about your classes being in global scope or not.

Title: Alternative to regular PHP Class

Body:
Generally when creating a PHP class I would do something as such

class Foo
{
    public function Foo(){}
    public function RandomFunction(){};
}
global $foo;
$foo = new Foo();
$foo->RandomFunction();

I have noticed that on the web people are frowning upon the global vars for classes but without it I would not be able to access the class inside other functions.

Now an alternative to this would be using static classes as such:

class Foo
{
    static public function RandomFunction(){}
}
Foo::RandomFunction();

My Question is this, is this the best alternative to global vars for classes? Or is there a better way to go about it all together?


问:
Read subprocess stdout while maintaining it in the buffer
Is it possible to read a subprocess's stdout but at the end of the program still maintain the whole process.communicate()?

For example i have a python script that starts a c# app in a Popen subprocess and checks the log file it produces live to determine the state it is in but certain errors are not dumped in the logs and are in the stdout and certain errors there will cause the process to hang. I want to be able to detect that output and in those cases be able to kill the process.

This is easy while doing process.stdout.readline() but at the end of the program i loose the ability to dump the entire stdout in it's native formatting  because the buffer get's flushed after reading. Is it possible to maintain that buffer?

Or at the very least save the read lines in a variable in it's native formatting?

答:
You can read stdout line by line, process it and save it to a list or buffer, and have the buffer available later. In this example processing is just print, but you could change that however you want. I also assumed you just want to collect stderr in the background, so created a separate thread.

```<code>import subprocess as subp
import threading
import io

def _pipe_read_thread(stream, output):
    output.write(stream.read())
    stream.close()

def proc_runner(cmd):
    stdout_lines = []
    stdout_buf = io.BytesIO()
    stderr_buf = io.BytesIO()
    p = subp.Popen(cmd, stdout=subp.PIPE, stderr=subp.PIPE)
    stderr_t = threading.Thread(target=_pipe_read_thread,
        args=(p.stderr, stderr_buf))
    stderr_t.start()
    for line in p.stdout:
        print(line)
        stdout_buf.write(line)
    returncode = p.wait()
    stderr_t.join()
    stdout_buf. seek(0)
    stderr_buf.seek(0)
    return returncode, stdout_buf, stderr_buf

returncode, stdout, stderr = proc_runner(['ls', '-a'])
print('=============================')
print(stdout.read())
print('=============================')
print(stderr.read())
</code>```

Body:
You can read stdout line by line, process it and save it to a list or buffer, and have the buffer available later. In this example processing is just print, but you could change that however you want. I also assumed you just want to collect stderr in the background, so created a separate thread.

import subprocess as subp
import threading
import io

def _pipe_read_thread(stream, output):
    output.write(stream.read())
    stream.close()

def proc_runner(cmd):
    stdout_lines = []
    stdout_buf = io.BytesIO()
    stderr_buf = io.BytesIO()
    p = subp.Popen(cmd, stdout=subp.PIPE, stderr=subp.PIPE)
    stderr_t = threading.Thread(target=_pipe_read_thread,
        args=(p.stderr, stderr_buf))
    stderr_t.start()
    for line in p.stdout:
        print(line)
        stdout_buf.write(line)
    returncode = p.wait()
    stderr_t.join()
    stdout_buf. seek(0)
    stderr_buf.seek(0)
    return returncode, stdout_buf, stderr_buf

returncode, stdout, stderr = proc_runner(['ls', '-a'])
print('=============================')
print(stdout.read())
print('=============================')
print(stderr.read())


问:
Error while executing and initializing kubeadm
While initializing kubeadm I am getting following errors. I have also tried command kubeadm reset before doing kubadm init. Kubelet is also running and command I have used for same is systemctl enable kubelet && systemctl start kubelet. Following is log after executing kubeadm init

[kubeadm] WARNING: kubeadm is in beta, please do not use it for production clusters.
[init] Using Kubernetes version: v1.8.2
[init] Using Authorization modes: [Node RBAC]
[preflight] Running pre-flight checks
[preflight] WARNING: Connection to "https://192.168.78.48:6443" uses proxy "http://user:pwd@192.168.78.15:3128/". If that is not intended, adjust your proxy settings
[preflight] WARNING: Running with swap on is not supported. Please disable swap or set kubelet's --fail-swap-on flag to false.
[preflight] Starting the kubelet service
[kubeadm] WARNING: starting in 1.8, tokens expire after 24 hours by default (if you require a non-expiring token use --token-ttl 0)
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [steller.india.com kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.140.48]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "scheduler.conf"
[controlplane] Wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] Wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] Wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] Waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests"
[init] This often takes around a minute; or longer if the control plane images have to be pulled.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
 ```
</div>
</div>
</p>

<p>Following is output of <code>journalctl -u kubelet</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>-- Logs begin at Thu 2017-11-02 16:20:50 IST, end at Fri 2017-11-03 17:11:12 IST. --
Nov 03 16:36:48 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:36:48 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998467   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998532   52511 controller.go:114] kubelet config controller: starting controller
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998536   52511 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837248   52511 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837282   52511 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.839719   52511 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.846959   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.847216   52511 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:36:49 steller.india.com kubelet[52511]: error: failed to run Kubelet: unable to load bootstrap kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such
Nov 03 16:36:49 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service failed.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service holdoff time over, scheduling restart.
Nov 03 16:37:00 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:37:00 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134702   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134763   52975 controller.go:114] kubelet config controller: starting controller
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134767   52975 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141273   52975 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141364   52975 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.143023   52975 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.149537   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.149780   52975 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.179873   52975 certificate_manager.go:361] Requesting new certificate.
Nov 03 16:37:00 steller.india.com kubelet[52975]: E1103 16:37:00.180392   52975 certificate_manager.go:284] Failed while requesting a signed certificate from the master:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.181404   52975 manager.go:149] cAdvisor running in container: "/sys/fs/cgroup/cpu,cpuacct/system.slice/k
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.223876   52975 manager.go:157] unable to connect to Rkt api service: rkt: cannot tcp Dial rkt api servic
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.224005   52975 manager.go:166] unable to connect to CRI-O api service: Get http://%2Fvar%2Frun%2Fcrio.so
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262573   52975 fs.go:139] Filesystem UUIDs: map[17856e0b-777f-4065-ac97-fb75d7a1e197:/dev/dm-1 2dc6a878-
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262604   52975 fs.go:140] Filesystem partitions: map[/dev/sdb:{mountpoint:/D major:8 minor:16 fsType:xfs
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.268969   52975 manager.go:216] Machine: {NumCores:56 CpuFrequency:2600000 MemoryCapacity:540743667712 Hu
Nov 03 16:37:00 steller.india.com kubelet[52975]: 967295 Mtu:1500} {Name:eno49 MacAddress:14:02:ec:82:57:30 Speed:10000 Mtu:1500} {Name:eno50 MacAddress:14:02:ec:82:57:3
Nov 03 16:37:00 steller.india.com kubelet[52975]: evel:1} {Size:262144 Type:Unified Level:2}]} {Id:13 Threads:[12 40] Caches:[{Size:32768 Type:Data Level:1} {Size:32768
Nov 03 16:37:00 steller.india.com kubelet[52975]: s:[26 54] Caches:[{Size:32768 Type:Data Level:1} {Size:32768 Type:Instruction Level:1} {Size:262144 Type:Unified Level:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.270145   52975 manager.go:222] Version: {KernelVersion:3.10.0-229.14.1.el7.x86_64 ContainerOsVersion:Cen
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.271263   52975 server.go:422] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaultin
Nov 03 16:37:00 steller.india.com kubelet[52975]: error: failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:37:00 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service failed.</code>```

答:
Some Kubernetes Deployments Need Swap

Generally speaking, the official requirement is to disable swap.

Reason? not yet supported by kubernetes. IMO they ask you to disable swap to prevent issues with multi-node cluster workload shifting.

However, I have a valid use case - I'm developing an on-prem product, linux distro, included with kubeadm. no horizontal scaling by design. To survive opportunistic memory peaks and still function (but slow), I definitely need swap.

To install kubeadm with swap enabled:

Create a file in /etc/systemd/system/kubelet.service.d/20-allow-swap.conf with the content:

```<code>[Service]
Environment="KUBELET_EXTRA_ARGS=--fail-swap-on=false"
</code>```

Run

```<code>sudo systemctl daemon-reload
</code>```

Initialize kubeadm with flag --ignore-preflight-errors=Swap

```<code>kubeadm init --ignore-preflight-errors=Swap
</code>```

Body:
While initializing kubeadm I am getting following errors. I have also tried command kubeadm reset before doing kubadm init. Kubelet is also running and command I have used for same is systemctl enable kubelet && systemctl start kubelet. Following is log after executing kubeadm init

[kubeadm] WARNING: kubeadm is in beta, please do not use it for production clusters.
[init] Using Kubernetes version: v1.8.2
[init] Using Authorization modes: [Node RBAC]
[preflight] Running pre-flight checks
[preflight] WARNING: Connection to "https://192.168.78.48:6443" uses proxy "http://user:pwd@192.168.78.15:3128/". If that is not intended, adjust your proxy settings
[preflight] WARNING: Running with swap on is not supported. Please disable swap or set kubelet's --fail-swap-on flag to false.
[preflight] Starting the kubelet service
[kubeadm] WARNING: starting in 1.8, tokens expire after 24 hours by default (if you require a non-expiring token use --token-ttl 0)
[certificates] Generated ca certificate and key.
[certificates] Generated apiserver certificate and key.
[certificates] apiserver serving cert is signed for DNS names [steller.india.com kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.140.48]
[certificates] Generated apiserver-kubelet-client certificate and key.
[certificates] Generated sa key and public key.
[certificates] Generated front-proxy-ca certificate and key.
[certificates] Generated front-proxy-client certificate and key.
[certificates] Valid certificates and keys now exist in "/etc/kubernetes/pki"
[kubeconfig] Wrote KubeConfig file to disk: "admin.conf"
[kubeconfig] Wrote KubeConfig file to disk: "kubelet.conf"
[kubeconfig] Wrote KubeConfig file to disk: "controller-manager.conf"
[kubeconfig] Wrote KubeConfig file to disk: "scheduler.conf"
[controlplane] Wrote Static Pod manifest for component kube-apiserver to "/etc/kubernetes/manifests/kube-apiserver.yaml"
[controlplane] Wrote Static Pod manifest for component kube-controller-manager to "/etc/kubernetes/manifests/kube-controller-manager.yaml"
[controlplane] Wrote Static Pod manifest for component kube-scheduler to "/etc/kubernetes/manifests/kube-scheduler.yaml"
[etcd] Wrote Static Pod manifest for a local etcd instance to "/etc/kubernetes/manifests/etcd.yaml"
[init] Waiting for the kubelet to boot up the control plane as Static Pods from directory "/etc/kubernetes/manifests"
[init] This often takes around a minute; or longer if the control plane images have to be pulled.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz' failed with error: Get http://localhost:10255/healthz: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.
[kubelet-check] It seems like the kubelet isn't running or healthy.
[kubelet-check] The HTTP call equal to 'curl -sSL http://localhost:10255/healthz/syncloop' failed with error: Get http://localhost:10255/healthz/syncloop: dial tcp [::1]:10255: getsockopt: connection refused.

Following is output of journalctl -u kubelet

-- Logs begin at Thu 2017-11-02 16:20:50 IST, end at Fri 2017-11-03 17:11:12 IST. --
Nov 03 16:36:48 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:36:48 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998467   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998532   52511 controller.go:114] kubelet config controller: starting controller
Nov 03 16:36:48 steller.india.com kubelet[52511]: I1103 16:36:48.998536   52511 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837248   52511 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.837282   52511 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.839719   52511 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:36:49 steller.india.com kubelet[52511]: I1103 16:36:49.846959   52511 feature_gate.go:156] feature gates: map[]
Nov 03 16:36:49 steller.india.com kubelet[52511]: W1103 16:36:49.847216   52511 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:36:49 steller.india.com kubelet[52511]: error: failed to run Kubelet: unable to load bootstrap kubeconfig: stat /etc/kubernetes/bootstrap-kubelet.conf: no such
Nov 03 16:36:49 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:36:49 steller.india.com systemd[1]: kubelet.service failed.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service holdoff time over, scheduling restart.
Nov 03 16:37:00 steller.india.com systemd[1]: Started kubelet: The Kubernetes Node Agent.
Nov 03 16:37:00 steller.india.com systemd[1]: Starting kubelet: The Kubernetes Node Agent...
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134702   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134763   52975 controller.go:114] kubelet config controller: starting controller
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.134767   52975 controller.go:118] kubelet config controller: validating combination of defaults and flag
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141273   52975 client.go:75] Connecting to docker on unix:///var/run/docker.sock
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.141364   52975 client.go:95] Start docker client with request timeout=2m0s
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.143023   52975 cni.go:196] Unable to update cni config: No networks found in /etc/cni/net.d
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.149537   52975 feature_gate.go:156] feature gates: map[]
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.149780   52975 server.go:289] --cloud-provider=auto-detect is deprecated. The desired cloud provider sho
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.179873   52975 certificate_manager.go:361] Requesting new certificate.
Nov 03 16:37:00 steller.india.com kubelet[52975]: E1103 16:37:00.180392   52975 certificate_manager.go:284] Failed while requesting a signed certificate from the master:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.181404   52975 manager.go:149] cAdvisor running in container: "/sys/fs/cgroup/cpu,cpuacct/system.slice/k
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.223876   52975 manager.go:157] unable to connect to Rkt api service: rkt: cannot tcp Dial rkt api servic
Nov 03 16:37:00 steller.india.com kubelet[52975]: W1103 16:37:00.224005   52975 manager.go:166] unable to connect to CRI-O api service: Get http://%2Fvar%2Frun%2Fcrio.so
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262573   52975 fs.go:139] Filesystem UUIDs: map[17856e0b-777f-4065-ac97-fb75d7a1e197:/dev/dm-1 2dc6a878-
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.262604   52975 fs.go:140] Filesystem partitions: map[/dev/sdb:{mountpoint:/D major:8 minor:16 fsType:xfs
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.268969   52975 manager.go:216] Machine: {NumCores:56 CpuFrequency:2600000 MemoryCapacity:540743667712 Hu
Nov 03 16:37:00 steller.india.com kubelet[52975]: 967295 Mtu:1500} {Name:eno49 MacAddress:14:02:ec:82:57:30 Speed:10000 Mtu:1500} {Name:eno50 MacAddress:14:02:ec:82:57:3
Nov 03 16:37:00 steller.india.com kubelet[52975]: evel:1} {Size:262144 Type:Unified Level:2}]} {Id:13 Threads:[12 40] Caches:[{Size:32768 Type:Data Level:1} {Size:32768
Nov 03 16:37:00 steller.india.com kubelet[52975]: s:[26 54] Caches:[{Size:32768 Type:Data Level:1} {Size:32768 Type:Instruction Level:1} {Size:262144 Type:Unified Level:
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.270145   52975 manager.go:222] Version: {KernelVersion:3.10.0-229.14.1.el7.x86_64 ContainerOsVersion:Cen
Nov 03 16:37:00 steller.india.com kubelet[52975]: I1103 16:37:00.271263   52975 server.go:422] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaultin
Nov 03 16:37:00 steller.india.com kubelet[52975]: error: failed to run Kubelet: Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service: main process exited, code=exited, status=1/FAILURE
Nov 03 16:37:00 steller.india.com systemd[1]: Unit kubelet.service entered failed state.
Nov 03 16:37:00 steller.india.com systemd[1]: kubelet.service failed.

Body:
Some Kubernetes Deployments Need Swap

Generally speaking, the official requirement is to disable swap.

Reason? not yet supported by kubernetes. IMO they ask you to disable swap to prevent issues with multi-node cluster workload shifting.

However, I have a valid use case - I'm developing an on-prem product, linux distro, included with kubeadm. no horizontal scaling by design. To survive opportunistic memory peaks and still function (but slow), I definitely need swap.

To install kubeadm with swap enabled:

Create a file in /etc/systemd/system/kubelet.service.d/20-allow-swap.conf with the content:

[Service]
Environment="KUBELET_EXTRA_ARGS=--fail-swap-on=false"

Run

sudo systemctl daemon-reload

Initialize kubeadm with flag --ignore-preflight-errors=Swap

kubeadm init --ignore-preflight-errors=Swap


问:
C++: storing a matrix in a 1D array
I am very new to C++, but I have the task of translating a section of C++ code into python.

Going through the file, I found this section of code, which confuses me:

```<code>int n_a=(e.g 10)

int n_b=n_a-1;
int l_b[2*n_b];
int l_c[3*n_b];
int l_d[4*n_b];
for (int i=0; i<n_b; i++){
    for (int j=0; j<2; j++) l_b[i*2+j]=0;
    for (int j=0; j<3; j++) l_c[i*3+j]=0;
    for (int j=0; j<4; j++) l_d[i*4+j]=0;
</code>```

I know that it creates 3 arrays, the length of each defined by the action on the n_b variable, and sets all the elements to zero, but I do not understand what exactly this matrix is supposed to look like, e.g. if written on paper.

答:
A common way to store a matrix with R rows and C columns is to store all elements in a vector of size R * C. Then when you need element (i, j) you just index the vector with i*C + j. This is not the only way your "matrix" could be stored in memory, but it is a common one.

In this code there are 3 C arrays that declared and initialized with zeros. The l_b array seems to be storage for a n_a x 2 matrix, the l_c array for a n_a x 3 matrix and the l_d array for a n_a x 4 matrix.

Of course, this is only an impression since to be sure we would need to see how these arrays are used later.

As in the comments, if you are going to convert this to python then you should probably use numpy for the matrices. In fact, the numpy arrays will store the elements in memory exactly like indexing I mentioned (by default, but you can also choose an alternative way passing an extra argument). You could do the same of this C++ code in oython with just

import numpy as np

n_a = (e.g 10)

l_b = np.zeros(shape=(n_a, 2))
l_c = np.zeros(shape=(n_a, 3))
l_d = np.zeros(shape=(n_a, 4))
```

<p>These variables in numpy are 2D arrays and you can index them as usual.
Ex:</p>

```l_d[2, 1] = 15.5
```

<hr>

<p>We can also have a nice syntax for working with vector, matrices and linear algebra in C++ by using one of the available libraries. One such library is armadillo. We can create the three previous matrices of zeros using armadillo as</p>

<pre class="lang-cpp prettyprint-override"><code>#include <armadillo>

int main(int argc, char *argv[]) {
    unsigned int n_a = 10;

    // A 10 x 3 matrix of doubles with all elements being zero
    // The 'arma::fill::zeros' argument is optional and without it the matrix
    // elements will not be initialized
    arma::mat l_b(n_a, 2, arma::fill::zeros);
    arma::mat l_c(n_a, 3, arma::fill::zeros);
    arma::mat l_d(n_a, 4, arma::fill::zeros);

    // We use parenthesis for index, since "[]" can only receive one element in C/C++
    l_b(2, 1) = 15.5;

    // A nice function for printing, but it also works with operator<<
    l_b.print("The 'l_b' matrix is");

    return 0;
}
</code>```

If you inspect armadillo types in gdb you will see that it has a mem atribute which is a pointer. This is in fact a C array for the internal elements of the matrix and when you index the matrix in armadillo it will translate the indexes into the proper index in this internal 1D array.

You can print the elements in this internal arry in gdb. For instance, print l_b.mem[0] will print the first element, print l_b.mem[1] will print the second element, and so one.

Title: C++: storing a matrix in a 1D array

Body:
I am very new to C++, but I have the task of translating a section of C++ code into python.

Going through the file, I found this section of code, which confuses me:

int n_a=(e.g 10)

int n_b=n_a-1;
int l_b[2*n_b];
int l_c[3*n_b];
int l_d[4*n_b];
for (int i=0; i<n_b; i++){
    for (int j=0; j<2; j++) l_b[i*2+j]=0;
    for (int j=0; j<3; j++) l_c[i*3+j]=0;
    for (int j=0; j<4; j++) l_d[i*4+j]=0;

I know that it creates 3 arrays, the length of each defined by the action on the n_b variable, and sets all the elements to zero, but I do not understand what exactly this matrix is supposed to look like, e.g. if written on paper.

Body:
A common way to store a matrix with R rows and C columns is to store all elements in a vector of size R * C. Then when you need element (i, j) you just index the vector with i*C + j. This is not the only way your "matrix" could be stored in memory, but it is a common one.

In this code there are 3 C arrays that declared and initialized with zeros. The l_b array seems to be storage for a n_a x 2 matrix, the l_c array for a n_a x 3 matrix and the l_d array for a n_a x 4 matrix.

Of course, this is only an impression since to be sure we would need to see how these arrays are used later.

As in the comments, if you are going to convert this to python then you should probably use numpy for the matrices. In fact, the numpy arrays will store the elements in memory exactly like indexing I mentioned (by default, but you can also choose an alternative way passing an extra argument). You could do the same of this C++ code in oython with just

import numpy as np

n_a = (e.g 10)

l_b = np.zeros(shape=(n_a, 2))
l_c = np.zeros(shape=(n_a, 3))
l_d = np.zeros(shape=(n_a, 4))

These variables in numpy are 2D arrays and you can index them as usual.
Ex:

l_d[2, 1] = 15.5

We can also have a nice syntax for working with vector, matrices and linear algebra in C++ by using one of the available libraries. One such library is armadillo. We can create the three previous matrices of zeros using armadillo as

#include <armadillo>

int main(int argc, char *argv[]) {
    unsigned int n_a = 10;

    // A 10 x 3 matrix of doubles with all elements being zero
    // The 'arma::fill::zeros' argument is optional and without it the matrix
    // elements will not be initialized
    arma::mat l_b(n_a, 2, arma::fill::zeros);
    arma::mat l_c(n_a, 3, arma::fill::zeros);
    arma::mat l_d(n_a, 4, arma::fill::zeros);

    // We use parenthesis for index, since "[]" can only receive one element in C/C++
    l_b(2, 1) = 15.5;

    // A nice function for printing, but it also works with operator<<
    l_b.print("The 'l_b' matrix is");

    return 0;
}

If you inspect armadillo types in gdb you will see that it has a mem atribute which is a pointer. This is in fact a C array for the internal elements of the matrix and when you index the matrix in armadillo it will translate the indexes into the proper index in this internal 1D array.

You can print the elements in this internal arry in gdb. For instance, print l_b.mem[0] will print the first element, print l_b.mem[1] will print the second element, and so one.


问:
Is there a way to make VBA Power query refresh faster?
I have this macro that can successfully Open a workbook and refresh every Power Query connection in it. If I manually click the "Refresh All", the whole process takes 3 - 5 mins. But if I run the macro, it takes up to an hour to complete the process.

I have tried using Application.ScreenUpdating = False but there was no impact. Is there any way to make the refresh faster?

```<code>Dim fname As String
    Dim owb As Workbook
    Dim Cname As String
    Dim objConnection As WorkbookConnection, bBackground As Boolean
    fname = "PowerQuery04-CSVMultipleFileImport.xlsx"
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
        For Each objConnection In ActiveWorkbook.Connections
            If Left(objConnection.Name, 8) = "Query - " Then
            Cname = objConnection.Name
                With ActiveWorkbook.Connections(Cname).OLEDBConnection
                    .BackgroundQuery = False  'or true, up to you
                    .Refresh
                End With
            End If
        Next
    'owb.RefreshAll
    Application.Wait (Now + TimeValue("0:02:00"))
    Application.DisplayAlerts = False
    owb.Save
    owb.Close
    Application.DisplayAlerts = True
</code>```

答:
I suspect you'll get better performance if you use the Workbook.RefreshAll method rather than looping through queries.</p>

```<code>ActiveWorkbook.RefreshAll
</code>```

Body:
I have this macro that can successfully Open a workbook and refresh every Power Query connection in it. If I manually click the "Refresh All", the whole process takes 3 - 5 mins. But if I run the macro, it takes up to an hour to complete the process.

I have tried using Application.ScreenUpdating = False but there was no impact. Is there any way to make the refresh faster?

Dim fname As String
    Dim owb As Workbook
    Dim Cname As String
    Dim objConnection As WorkbookConnection, bBackground As Boolean
    fname = "PowerQuery04-CSVMultipleFileImport.xlsx"
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
        For Each objConnection In ActiveWorkbook.Connections
            If Left(objConnection.Name, 8) = "Query - " Then
            Cname = objConnection.Name
                With ActiveWorkbook.Connections(Cname).OLEDBConnection
                    .BackgroundQuery = False  'or true, up to you
                    .Refresh
                End With
            End If
        Next
    'owb.RefreshAll
    Application.Wait (Now + TimeValue("0:02:00"))
    Application.DisplayAlerts = False
    owb.Save
    owb.Close
    Application.DisplayAlerts = True

Body:
I suspect you'll get better performance if you use the Workbook.RefreshAll method rather than looping through queries.

ActiveWorkbook.RefreshAll


问:
Wordpress Custom Table Query using Multiple Values
I have been researching the last hour of whether or not I can run a query within wordpress on a custom table that I made using two WHERES.  Now I'm new to mysql and php ( 9 months in ) and am just wondering if there is a way to do it besides a AND.

Here is an example of my code

```<code>$check_current = $wpdb->get_row("SELECT * FROM $weather_table WHERE status = 'current' AND  condition = $current_weather");
</code>```

status and condition are both fields and I'm trying to find out whether both exist to rewrite the current field.  The closest I've come is possibly using the prepare function in Wordpress and php but don't know what that is exactly just know it helps with sql injection and security.  Can you run a multiple value query in Wordpress?

答:
Using the AND operator in MySQL is the right way to test for a compound condition.

Be sure to put quotes around any variables (like $current_weather) if the underlying data type is a string.

Also, best practice is to avoid using "*" in the select. Rather, explicitly declare the fields you want to return. This is good for performance.

Body:
I have been researching the last hour of whether or not I can run a query within wordpress on a custom table that I made using two WHERES.  Now I'm new to mysql and php ( 9 months in ) and am just wondering if there is a way to do it besides a AND.

Here is an example of my code

$check_current = $wpdb->get_row("SELECT * FROM $weather_table WHERE status = 'current' AND  condition = $current_weather");

status and condition are both fields and I'm trying to find out whether both exist to rewrite the current field.  The closest I've come is possibly using the prepare function in Wordpress and php but don't know what that is exactly just know it helps with sql injection and security.  Can you run a multiple value query in Wordpress?


问:
Tabs with FlatLists inside ScrollView - like Instagram or Twitter profile pages
I would like to have a set of tabs that each have a FlatList inside a ScrollView. This is similar to the layout of Instagram or Twitter.

I am aware that there are some issues with having a FlatList inside a ScrollView and getting onEndReached to be triggered as only the ScrollView's scroll events are registered?

This results in the inner onEndReached being called immediately on load and then over and over again...

If you make the ScrollView scrollEnabled false and flex: 1 instead of flexGrow: 1 then you can get the inner FlatLists to scroll but the outer content doesnt... This looks like this:

I think there are a lot of people who are struggling with this problem and I can't find a really clear solution anywhere.

I have also tried to implement react-navigation-collapsible with createMaterialTopTabNavigator to create the tabs. However, you can't implement a pull-to-refresh on the whole screen?

Any help would be much appreciated.

Update

I've also looked into implementing: FlatList inside ScrollView doesn't scroll

AND I've looked at dynamically toggling the scrollEnabled property (even though it creates a re-render. This ALMOST works... but there is an issue with the ScrollView height being flexGrow: 1 and the inner FlatList not filling the space...

SECOND UPDATE

This snack almost does the right thing... https://snack.expo.io/@satya164/collapsible-header-with-tabview
It uses react-native-tab-view and collapses the header using animation. If the header was a component, it could fetch data on load but you would only get a pull-to-refresh on the inner list (unlike Instagram).

Related questions:

There is an issue with onEndReached being called infinitely
- https://github.com/facebook/react-native/issues/18887
- https://github.com/facebook/react-native/issues/6002

FlatList cannot work right inside a ScrollView...
- https://github.com/facebook/react-native/issues/12827#issuecomment-320509824

Flatlist inside ScrollView
- https://github.com/facebook/react-native/issues/19971

FlatList inside ScrollView doesn't scroll
- https://github.com/facebook/react-native/issues/19971

FlatList child is calling onEndReached on render
- https://github.com/react-native-community/react-native-tab-view/issues/501

React Native Nested Listview Triggers onEndReached Multiple Times
- React Native nested ListView triggers onEndReached multiple times on loading

When FlatList wrapped inside ScollView, onEndReached doesnt work expected.
- https://github.com/facebook/react-native/issues/22008

Twitter-like profile layout - How to create Twitter like profile layout? But I believe that the answer is now not correct.

答:
Probably you should work with Animated api to handle the translateY of the content of TabView and the header.

For example:

```<code><View>
   <Header />
   <TabView /> //With lists
<View>
</code>```

Your Header should have a position: 'absolute' and a fixed height, and your TabView should have a paddingTop transparent to match the Header height.
Once you scroll one or other list, you should move the Header with transform: [{ translateY }] and your TabView too, so it can match the position of the Header until it clamps.

EDIT:

Sorry, didn't saw your update about the expo example.

Your expo example has some errors. For example if you scroll one list (to hide the header) your second list will have a blank space.

You should set the height of the list (TabView containing the lists) to be the  window height - header size clamped.
With this you can set translateY of the tabview to be the size of the header. Once you start scroll up, you should translateY both the header and the tabview until it clamps. From that point you should only scroll the list.

Another solution would be increase the height of tabView onScroll to match the translateY of header

Body:
Probably you should work with Animated api to handle the translateY of the content of TabView and the header.

For example:

<View>
   <Header />
   <TabView /> //With lists
<View>

Your Header should have a position: 'absolute' and a fixed height, and your TabView should have a paddingTop transparent to match the Header height.
Once you scroll one or other list, you should move the Header with transform: [{ translateY }] and your TabView too, so it can match the position of the Header until it clamps.

EDIT:

Sorry, didn't saw your update about the expo example.

Your expo example has some errors. For example if you scroll one list (to hide the header) your second list will have a blank space.

You should set the height of the list (TabView containing the lists) to be the  window height - header size clamped.
With this you can set translateY of the tabview to be the size of the header. Once you start scroll up, you should translateY both the header and the tabview until it clamps. From that point you should only scroll the list.

Another solution would be increase the height of tabView onScroll to match the translateY of header


问:
What are the rules for building user phrases and Google responses (OnOff and Cook traits)?
Current documentation doesn't fully describe the rules for how a user can build the phrases to trigger any operation and possible answers. Could you please provide the following:

for "action.devices.traits.OnOff" trait:

the full set of phrases that user can use to trigger turning on/off OR rules to build them;

possible response phrases from Google Assistant if turning on/off was started successfully OR rules to build them.

for "action.devices.traits.Cook" trait (for two ways of parameters combination: cookingMode + foodPreset  OR cookingMode + foodPreset  + quantity + unit (ounces)):

the full set of phrases that user can use to trigger cook operation OR rules to build them;

possible response phrases from Google Assistant if cook operation was started successfully OR rules to build them;

the full set of phrases that user can use to cancel cook operation OR rules to build them;

possible response phrases from Google Assistant if cancellation of cook operation was started successfully OR rules to build them.

what additional words could the user add when framing this phrase for these two traits? For example, “me”, “please”, “my new {foodPreset}”, “a cup of {foodPreset}” (“cup” is not a “unit”) and any other words and phrases. What are the rules for this?

are there any recommendations for “foodPreset” parameter (words amount, words complexity)?

答:
There are no strict rules. Traits can be triggered through natural language processing, so you may expect any relevant phrase should work. The documentation provides examples for OnOff and Cook but aren't limited by the provided phrases.

Responses also are based around good voice design and natural language, so there aren't any strict rules to what you'd expect. Additionally, such requests and responses may change as the platform continues to evolve. The NLP system is able to extract meaning from larger statements, so general things like "turn on the light", "turn on the light please", and "please turn on the light for me" should all match.

With regards to foodPreset, the key can be whatever you want for your service. The synonyms should be fairly varied and include any possible way that an individual would refer to that food item.


问:
Manage a 4 dimensional array or a 5 dimensional with foreach statement in php
I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.

A very simple example below

```<code>  $documents = array(
    array(
         "name"=>"Markos",
        "lastname"=>"papadopoulos",
        "country"=>"Greece",
        "nationality"=>"greek",
        "job"=>"web developer",
        "hobbies"=>array(
                "sports"=>"boxing",
                "others"=>array(
                        "freetime"=>"watching Tv"
                )
        )

    )
);

foreach($documents as $document){
    echo $document['name']."<br>"
        .$document['lastname']."<br>"
        .$document['country']."<br>"
        .$document['nationality']."<br>"
        .$document['job']."<br>";

            foreach ($document['hobbies'] as $key=>$value){
                echo $key." ".$value."<br>";

                    foreach ($value['others'] as $subkey=>$subvalue){
                        echo $subkey['freetime'];
                    }

                }
}
</code>```

I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.

答:
try </p>

```<code>foreach($documents as $document){
echo $document['name']."<br>"
    .$document['lastname']."<br>"
    .$document['country']."<br>"
    .$document['nationality']."<br>"
    .$document['job']."<br>";

        foreach ($document['hobbies'] as $key=>$value){
            if (is_array($value)) {
                foreach ($value as $subkey=>$subvalue){
                    echo $subvalue;
                }
            } else {
                echo $key." ".$value."<br>";
            }
        }
}
</code>```

Body:
I am having a really bad time right now, since everyone on the internet is saying that PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people. So I can't find someone to help me.

A very simple example below

  $documents = array(
    array(
         "name"=>"Markos",
        "lastname"=>"papadopoulos",
        "country"=>"Greece",
        "nationality"=>"greek",
        "job"=>"web developer",
        "hobbies"=>array(
                "sports"=>"boxing",
                "others"=>array(
                        "freetime"=>"watching Tv"
                )
        )

    )
);

foreach($documents as $document){
    echo $document['name']."
"
        .$document['lastname']."
"
        .$document['country']."
"
        .$document['nationality']."
"
        .$document['job']."
";

            foreach ($document['hobbies'] as $key=>$value){
                echo $key." ".$value."
";

                    foreach ($value['others'] as $subkey=>$subvalue){
                        echo $subkey['freetime'];
                    }

                }
}

I am stuck, I can't display the "others"=>array("freetime"=>"watching tv") can anyone advice me? And if I had also another array in the "others"=>array("freetime"=>"watching tv"), how could I display that array to? I am trying to learn the logic.

Body:
try

foreach($documents as $document){
echo $document['name']."<br>"
    .$document['lastname']."<br>"
    .$document['country']."<br>"
    .$document['nationality']."<br>"
    .$document['job']."<br>";

        foreach ($document['hobbies'] as $key=>$value){
            if (is_array($value)) {
                foreach ($value as $subkey=>$subvalue){
                    echo $subvalue;
                }
            } else {
                echo $key." ".$value."<br>";
            }
        }
}


问:
Date Manipulation in Python
I am trying to code a condition that the date for a trade being entered is the same as the trade date. My code is below. Similar to creating a filter.

```<code>Tradedate = ba[ba['TIMESTAMP'] <= '10.15'] & ba[ba['TRADE_ENTRY'] == 'TRADE_DATE']
</code>```

I get the following error below. Any advice on how to only display the trades if trade date = trade entry date. Both dates are in datetime64[ns] format.

For example:

```<code>Trade Date        Trade Entry Date
2019-06-17        2019-06-17
2019-06-18        2019-06-19
</code>```

The only trade I want to be displayed is the first date since the trade date and trade entry dare for the second one is different.

Thanks

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-5cdaf27939a8> in <module>
      1 df['TRADE_ENTRY'] = pd.to_datetime(df['TRADE_ENTRY']).dt.date
      2 df['TRADE_DATE'] = pd.to_datetime(df['TRADE_DATE']).dt.date
----> 3 Tradedate = ba[ba['TIMESTAMP'] <= '10.15'] & ba[ba['TRADE_ENTRY'] == 'TRADE_DATE']
      4
      5 #Trade date = trade entry date as filter

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in f(self, other, axis, level, fill_value)
    701
    702             left, right = self.align(other, join="outer", level=level, copy=False)
--> 703             new_data = left._combine_frame(right, pass_op, fill_value)
    704             return left._construct_result(new_data)
    705

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _combine_frame(self, other, func, fill_value, level)
   5298         if ops.should_series_dispatch(self, other, func):
   5299             # iterate over columns
-> 5300             new_data = ops.dispatch_to_series(self, other, _arith_op)
   5301         else:
   5302             with np.errstate(all="ignore"):

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in dispatch_to_series(left, right, func, str_rep, axis)
    414         raise NotImplementedError(right)
    415
--> 416     new_data = expressions.evaluate(column_op, str_rep, left, right)
    417     return new_data
    418

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr)
    206     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
    207     if use_numexpr:
--> 208         return _evaluate(op, op_str, a, b)
    209     return _evaluate_standard(op, op_str, a, b)
    210

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b)
    119
    120     if result is None:
--> 121         result = _evaluate_standard(op, op_str, a, b)
    122
    123     return result

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b)
     68         _store_test_result(False)
     69     with np.errstate(all="ignore"):
---> 70         return op(a, b)
     71
     72

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in column_op(a, b)
    383
    384         def column_op(a, b):
--> 385             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    386
    387     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in <dictcomp>(.0)
    383
    384         def column_op(a, b):
--> 385             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    386
    387     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
     62         other = item_from_zerodim(other)
     63
---> 64         return method(self, other)
     65
     66     return new_method

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(self, other)
    547         rvalues = extract_array(other, extract_numpy=True)
    548
--> 549         res_values = logical_op(lvalues, rvalues, op)
    550         return _construct_result(self, res_values, index=self.index, name=res_name)
    551

~\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in logical_op(left, right, op)
    349
    350     if should_extension_dispatch(lvalues, rvalues):
--> 351         res_values = dispatch_to_extension_op(op, lvalues, rvalues)
    352
    353     else:

~\Anaconda3\lib\site-packages\pandas\core\ops\dispatch.py in dispatch_to_extension_op(op, left, right)
    123     # The op calls will raise TypeError if the op is not defined
    124     # on the ExtensionArray
--> 125     res_values = op(left, right)
    126     return res_values

TypeError: unsupported operand type(s) for &: 'DatetimeArray' and 'DatetimeArray'
</code>```

答:
Use this :

Tradedate = ba[(ba['TIMESTAMP'] <= '10.15') & (ba['TRADE_ENTRY'] == 'TRADE_DATE')]
```

Title: Date Manipulation in Python

Body:
I am trying to code a condition that the date for a trade being entered is the same as the trade date. My code is below. Similar to creating a filter.

Tradedate = ba[ba['TIMESTAMP'] <= '10.15'] & ba[ba['TRADE_ENTRY'] == 'TRADE_DATE']

I get the following error below. Any advice on how to only display the trades if trade date = trade entry date. Both dates are in datetime64[ns] format.

For example:

Trade Date        Trade Entry Date
2019-06-17        2019-06-17
2019-06-18        2019-06-19

The only trade I want to be displayed is the first date since the trade date and trade entry dare for the second one is different.

Thanks

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-5cdaf27939a8> in <module>
      1 df['TRADE_ENTRY'] = pd.to_datetime(df['TRADE_ENTRY']).dt.date
      2 df['TRADE_DATE'] = pd.to_datetime(df['TRADE_DATE']).dt.date
----> 3 Tradedate = ba[ba['TIMESTAMP'] <= '10.15'] & ba[ba['TRADE_ENTRY'] == 'TRADE_DATE']
      4
      5 #Trade date = trade entry date as filter

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in f(self, other, axis, level, fill_value)
    701
    702             left, right = self.align(other, join="outer", level=level, copy=False)
--> 703             new_data = left._combine_frame(right, pass_op, fill_value)
    704             return left._construct_result(new_data)
    705

~\Anaconda3\lib\site-packages\pandas\core\frame.py in _combine_frame(self, other, func, fill_value, level)
   5298         if ops.should_series_dispatch(self, other, func):
   5299             # iterate over columns
-> 5300             new_data = ops.dispatch_to_series(self, other, _arith_op)
   5301         else:
   5302             with np.errstate(all="ignore"):

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in dispatch_to_series(left, right, func, str_rep, axis)
    414         raise NotImplementedError(right)
    415
--> 416     new_data = expressions.evaluate(column_op, str_rep, left, right)
    417     return new_data
    418

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, use_numexpr)
    206     use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b)
    207     if use_numexpr:
--> 208         return _evaluate(op, op_str, a, b)
    209     return _evaluate_standard(op, op_str, a, b)
    210

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b)
    119
    120     if result is None:
--> 121         result = _evaluate_standard(op, op_str, a, b)
    122
    123     return result

~\Anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b)
     68         _store_test_result(False)
     69     with np.errstate(all="ignore"):
---> 70         return op(a, b)
     71
     72

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in column_op(a, b)
    383
    384         def column_op(a, b):
--> 385             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    386
    387     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in <dictcomp>(.0)
    383
    384         def column_op(a, b):
--> 385             return {i: func(a.iloc[:, i], b.iloc[:, i]) for i in range(len(a.columns))}
    386
    387     elif isinstance(right, ABCSeries) and axis == "columns":

~\Anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
     62         other = item_from_zerodim(other)
     63
---> 64         return method(self, other)
     65
     66     return new_method

~\Anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(self, other)
    547         rvalues = extract_array(other, extract_numpy=True)
    548
--> 549         res_values = logical_op(lvalues, rvalues, op)
    550         return _construct_result(self, res_values, index=self.index, name=res_name)
    551

~\Anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in logical_op(left, right, op)
    349
    350     if should_extension_dispatch(lvalues, rvalues):
--> 351         res_values = dispatch_to_extension_op(op, lvalues, rvalues)
    352
    353     else:

~\Anaconda3\lib\site-packages\pandas\core\ops\dispatch.py in dispatch_to_extension_op(op, left, right)
    123     # The op calls will raise TypeError if the op is not defined
    124     # on the ExtensionArray
--> 125     res_values = op(left, right)
    126     return res_values

TypeError: unsupported operand type(s) for &: 'DatetimeArray' and 'DatetimeArray'


问:
Initialization of a struct instance data member in constructor?
I have a c++ class which as a private data member has a struct defined:

```<code>Class example {

...

private:
   struct Impl;
   Impl& structure_;
};
</code>```

Assuming that the struct Impl is defined as follows:

```<code>struct example::Impl{
    int m1;
    int m2;
    int m3;
};
</code>```

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

```<code>example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}
</code>```

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks

答: Since your structure_ is a reference, it needs to be referenced by something that is created outside of your "example" class. You could either change the reference into a pointer and allocate the structure somehow, or define the structure in the class-definition, allowing you to instance it directly instead of using a reference.</p>

Body:
I have a c++ class which as a private data member has a struct defined:

Class example {

...

private:
   struct Impl;
   Impl& structure_;
};

Assuming that the struct Impl is defined as follows:

struct example::Impl{
    int m1;
    int m2;
    int m3;
};

how would I be able to initialize the struct instance ( structure_ ) in the class's constructor?

Right now I have:

example::example() :
     structure_ .m1(00),
     structure_ .m2(00),
     structure_ .m3(00) {
...
}

.. for the initialization list, but I'm getting this error:

'example::structure_' : must be initialized in constructor base/member initializer list

how would I fix this?

Thanks


问:
Using Fetch First with Case Expression
DB2 UDB v11.x.

Is it possible to use FETCH FIRST in an UPDATE query that uses CASE?  I sort of understand why it doesnt work but was wondering if there was a way.  for instance:

```<code>db2 "UPDATE mytable SET cstate = CASE WHEN cstate = 801 THEN cstate = 1 AND rstate = 1 WHEN cstate = 804 THEN cstate = 4 AND rstate = 4 END FETCH FIRST 20000 ROWS ONLY"
</code>```

This results in only one row being changed at a time.

Tried:

```<code>db2 "UPDATE mytable SET cstate = CASE WHEN cstate = (SELECT cstate FROM mytable WHERE cstate = 801 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 1 AND rstate = 1 WHEN cstate = (SELECT cstate FROM mytable WHERE cstate = 804 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 4 AND rstate = 4 END"
</code>```

This gets:

```<code>SQL0811N  The result of a scalar fullselect, SELECT INTO statement, or VALUES
INTO statement is more than one row
</code>```

Any way to do this? Was hoping not to split it up and reiterating through the table twice (or having to do one update at a time).

答:
Please use IN clause while dealing with subquery, you may have multiple values in the other table,</p>

```<code>"UPDATE mytable SET cstate = CASE WHEN cstate in (SELECT cstate FROM mytable WHERE cstate = 801 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 1 AND rstate = 1 WHEN cstate in (SELECT cstate FROM mytable WHERE cstate = 804 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 4 AND rstate = 4 END"
</code>```

Title: Using Fetch First with Case Expression

Body:
DB2 UDB v11.x.

Is it possible to use FETCH FIRST in an UPDATE query that uses CASE?  I sort of understand why it doesnt work but was wondering if there was a way.  for instance:

db2 "UPDATE mytable SET cstate = CASE WHEN cstate = 801 THEN cstate = 1 AND rstate = 1 WHEN cstate = 804 THEN cstate = 4 AND rstate = 4 END FETCH FIRST 20000 ROWS ONLY"

This results in only one row being changed at a time.

Tried:

db2 "UPDATE mytable SET cstate = CASE WHEN cstate = (SELECT cstate FROM mytable WHERE cstate = 801 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 1 AND rstate = 1 WHEN cstate = (SELECT cstate FROM mytable WHERE cstate = 804 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 4 AND rstate = 4 END"

This gets:

SQL0811N  The result of a scalar fullselect, SELECT INTO statement, or VALUES
INTO statement is more than one row

Any way to do this? Was hoping not to split it up and reiterating through the table twice (or having to do one update at a time).

Body:
Please use IN clause while dealing with subquery, you may have multiple values in the other table,

"UPDATE mytable SET cstate = CASE WHEN cstate in (SELECT cstate FROM mytable WHERE cstate = 801 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 1 AND rstate = 1 WHEN cstate in (SELECT cstate FROM mytable WHERE cstate = 804 FETCH FIRST 20000 ROWS ONLY) THEN cstate = 4 AND rstate = 4 END"