问:
recursive mapping in python
What is the most pythonic way to apply a recursive function to structured/nested lists/list comprehension and return a structured/nested list/list comprehension of the same structure?

A minimal working example:

```<code>list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]
list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]
</code>```

I need a recursive function that is robust to the the structure of list1,
 list2 and possibly more, and to the vanilla function lambda x,y: x*y. The desired result in this tiny example is:

```<code>result = [[[3,4,12],[4,3,5],[10,4,4]],[[3,6],[6,2],[3,4]],[[4,6,8]]]
</code>```

Another example using list1 and list3 where list3 is:

```<code>list3 = [[[3],[2],[2]],[[3],[2],[1]],[[2]]]
</code>```

and the desired result is:

```<code>result = [[[3,6,9],[4,6,10],[10,4,5]], [[3,6],[6,2],[3,4]], [[4,6,8]]
</code>```

答:
you can do this with zip built-in function and list comprehension

```<code>result = [[[x*y for x,y in zip(c,d)]for c,d in zip(a,b)] for a,b in zip(list1,list2)]
</code>```

output:

```<code>[[[3, 4, 12], [4, 3, 5], [10, 4, 4]], [[3, 6], [6, 2], [3, 4]], [[4, 6, 8]]]
</code>```

explanation:

what you're actually doing is that first, you're getting the two first lists of both list1 and list2:

```<code>[[1,2,3],[2,3,5],[5,2,2]]
[[3,2,4],[2,1,1],[2,2,2]]
</code>```

then in these lists access in the same way to :

```<code>[1,2,3]
[3,2,4]
</code>```

then to :

```<code>1
3
</code>```

then simply applying x*y to them and so on for all the data.

Hope this was helpful.

Title: recursive mapping in python

Body:
What is the most pythonic way to apply a recursive function to structured/nested lists/list comprehension and return a structured/nested list/list comprehension of the same structure?

A minimal working example:

list1 = [[[1,2,3],[2,3,5],[5,2,2]], [[1,2],[3,1],[3,4]], [[2,3,4]]
list2 = [[[3,2,4],[2,1,1],[2,2,2]],[[3,3],[2,2],[1,1]],[[2,2,2]]]

I need a recursive function that is robust to the the structure of list1,
 list2 and possibly more, and to the vanilla function lambda x,y: x*y. The desired result in this tiny example is:

result = [[[3,4,12],[4,3,5],[10,4,4]],[[3,6],[6,2],[3,4]],[[4,6,8]]]

Another example using list1 and list3 where list3 is:

list3 = [[[3],[2],[2]],[[3],[2],[1]],[[2]]]

and the desired result is:

result = [[[3,6,9],[4,6,10],[10,4,5]], [[3,6],[6,2],[3,4]], [[4,6,8]]

Body:
you can do this with zip built-in function and list comprehension

result = [[[x*y for x,y in zip(c,d)]for c,d in zip(a,b)] for a,b in zip(list1,list2)]

output:

[[[3, 4, 12], [4, 3, 5], [10, 4, 4]], [[3, 6], [6, 2], [3, 4]], [[4, 6, 8]]]

explanation:

what you're actually doing is that first, you're getting the two first lists of both list1 and list2:

[[1,2,3],[2,3,5],[5,2,2]]
[[3,2,4],[2,1,1],[2,2,2]]

then in these lists access in the same way to :

[1,2,3]
[3,2,4]

then to :

1
3

then simply applying x*y to them and so on for all the data.

Hope this was helpful.


来源: stackexchange

问:
Security concerns for JsonRequestBehavior.AllowGet when using AJAX to get JSON
When I used AJAX to get JSON information I originally received an error mentioning the request was blocked because sensitive information could be disclosed.  I've read around on StackOverflow about JSON Hijacking and a variety of other security concerns.  However, a majority of these posts date years back and I was wondering if the answers themselves are a bit dated... and frankly I found it all to be relatively confusing.

I'm providing a sample script I'm currently using that uses AJAX to get JSON information that utilized JsonRequestBehavior.AllowGet to work properly.  This script is returning the infromation I'm asking it to.  It's returning SalesOrder numbers and nothing more -- so I don't feel it's passing "sensitive" information.  Should I still be concerned about any security vulnerabilities though?  Is it bad practice to use the AllowGet?

Here is the script

```<code>    <script>
        $(document).ready(function () {
            $('#printBtn').click(function () {
                $.ajax({
                    type: 'GET',
                    url: '/Home/GetSalesOrderListAsJSON',
                    success: function(response) {
                        var stringOfSalesOrders = "";
                        var totalToMove = 0;
                        response.forEach(function(str) {
                            stringOfSalesOrders += str + ",";
                            totalToMove++;
                        });

                        alert("Number being moved: " + totalToMove);

                        $.ajax({
                            type: "POST",
                            url: "/Home/PostResults",
                            data: { s: numberOfActiveIds},
                            success: function (results) {
                                if(results == "Success") {
                                    window.location.href = '/Home/Results';
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</code>```

Again, I understand this question has been asked in the past but was looking for an updated, current answer if possible.  If there are valuable resources or posts worth reading please share them and I'll be sure to either mark this question as a duplicate or delete it altogether!

Thanks!

答:
Check this post: Why is JsonRequestBehavior needed?

Excerpts from original post:

Additional useful comments from original post:

ContentLicense: CC BY-SA 3.0

Body:
When I used AJAX to get JSON information I originally received an error mentioning the request was blocked because sensitive information could be disclosed.  I've read around on StackOverflow about JSON Hijacking and a variety of other security concerns.  However, a majority of these posts date years back and I was wondering if the answers themselves are a bit dated... and frankly I found it all to be relatively confusing.

I'm providing a sample script I'm currently using that uses AJAX to get JSON information that utilized JsonRequestBehavior.AllowGet to work properly.  This script is returning the infromation I'm asking it to.  It's returning SalesOrder numbers and nothing more -- so I don't feel it's passing "sensitive" information.  Should I still be concerned about any security vulnerabilities though?  Is it bad practice to use the AllowGet?

Here is the script

Again, I understand this question has been asked in the past but was looking for an updated, current answer if possible.  If there are valuable resources or posts worth reading please share them and I'll be sure to either mark this question as a duplicate or delete it altogether!

Thanks!


问:
Check when object collides with border of canvas
I'm fairly new to Canvas HTML5 and was curious to know how to check if the 'Hero' in my game has collided with the border of the canvas as I would like to give it an alert or something if it did.

Here is my current code:

```<code>// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
    bgReady = true;
};
bgImage.src = "images/background.png";

// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};
heroImage.src = "images/hero.png";

// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
    monsterReady = true;
};
monsterImage.src = "images/flamingo.png";

// Game objects
var hero = {
    speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
    delete keysDown[e.keyCode];
}, false);

// Reset the game when the player catches a monster
var reset = function () {
    hero.x = canvas.width / 2;
    hero.y = canvas.height / 2;

    // Throw the monster somewhere on the screen randomly
    monster.x = 32 + (Math.random() * (canvas.width - 64));
    monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left
        hero.x -= hero.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        hero.x += hero.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    )
    {
        ++monstersCaught;
        reset();
    }

};

// Draw everything
var render = function () {
    if (bgReady) {
        ctx.drawImage(bgImage, 0, 0);
    }

    if (heroReady) {
        ctx.drawImage(heroImage, hero.x, hero.y);
    }

    if (monsterReady) {
        ctx.drawImage(monsterImage, monster.x, monster.y);
    }

    // Score
    ctx.fillStyle = "rgb(250, 250, 250)";
    ctx.font = "24px Helvetica";
    ctx.textAlign = "left";
    ctx.textBaseline = "top";
    ctx.fillText("Flamingos slaughtered: " + monstersCaught, 32, 32);

};

// The main game loop
var main = function () {
    var now = Date.now();
    var delta = now - then;

    update(delta / 1000);
    render();

    then = now;
};

// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible
</code>```

答:
I fixed this :

```<code>var update = function (modifier) {
    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left
        hero.x -= hero.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        hero.x += hero.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset();
    }
    if(hero.x <= 0){
        hero.x = 0;
    }
    else if(isMaxWidth()){
        hero.x = canvas.width -32
    }
    if(hero.y <= 0){
        hero.y = 0;
    }
    else if(isMaxHeight()){
        hero.y = canvas.height -32
    }

};

var isMaxWidth = function(){
    return hero.x >= canvas.width - 32;
};

var isMaxHeight = function(){
    return hero.y >= canvas.height - 32;
};
</code>```

Regards.

Body:
I'm fairly new to Canvas HTML5 and was curious to know how to check if the 'Hero' in my game has collided with the border of the canvas as I would like to give it an alert or something if it did.

Here is my current code:

// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Background image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
    bgReady = true;
};
bgImage.src = "images/background.png";

// Hero image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
    heroReady = true;
};
heroImage.src = "images/hero.png";

// Monster image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
    monsterReady = true;
};
monsterImage.src = "images/flamingo.png";

// Game objects
var hero = {
    speed: 256 // movement in pixels per second
};
var monster = {};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
    delete keysDown[e.keyCode];
}, false);

// Reset the game when the player catches a monster
var reset = function () {
    hero.x = canvas.width / 2;
    hero.y = canvas.height / 2;

    // Throw the monster somewhere on the screen randomly
    monster.x = 32 + (Math.random() * (canvas.width - 64));
    monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left
        hero.x -= hero.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        hero.x += hero.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    )
    {
        ++monstersCaught;
        reset();
    }

};

// Draw everything
var render = function () {
    if (bgReady) {
        ctx.drawImage(bgImage, 0, 0);
    }

    if (heroReady) {
        ctx.drawImage(heroImage, hero.x, hero.y);
    }

    if (monsterReady) {
        ctx.drawImage(monsterImage, monster.x, monster.y);
    }

    // Score
    ctx.fillStyle = "rgb(250, 250, 250)";
    ctx.font = "24px Helvetica";
    ctx.textAlign = "left";
    ctx.textBaseline = "top";
    ctx.fillText("Flamingos slaughtered: " + monstersCaught, 32, 32);

};

// The main game loop
var main = function () {
    var now = Date.now();
    var delta = now - then;

    update(delta / 1000);
    render();

    then = now;
};

// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 1); // Execute as fast as possible

Body:
I fixed this :

var update = function (modifier) {
    if (38 in keysDown) { // Player holding up
        hero.y -= hero.speed * modifier;
    }
    if (40 in keysDown) { // Player holding down
        hero.y += hero.speed * modifier;
    }
    if (37 in keysDown) { // Player holding left
        hero.x -= hero.speed * modifier;
    }
    if (39 in keysDown) { // Player holding right
        hero.x += hero.speed * modifier;
    }

    // Are they touching?
    if (
        hero.x <= (monster.x + 32)
        && monster.x <= (hero.x + 32)
        && hero.y <= (monster.y + 32)
        && monster.y <= (hero.y + 32)
    ) {
        ++monstersCaught;
        reset();
    }
    if(hero.x <= 0){
        hero.x = 0;
    }
    else if(isMaxWidth()){
        hero.x = canvas.width -32
    }
    if(hero.y <= 0){
        hero.y = 0;
    }
    else if(isMaxHeight()){
        hero.y = canvas.height -32
    }

};

var isMaxWidth = function(){
    return hero.x >= canvas.width - 32;
};

var isMaxHeight = function(){
    return hero.y >= canvas.height - 32;
};

Regards.


问:
UIPageViewController Conflict issue

Having trouble getting the UIPageViewController to work. the image shows the error that is occurring.

答:
It looks fine to me, the only things missing are the return statements of the two methods.

Since the return values are optional you can check if it compiles by just returning nil.

Sometimes I get weird behaviors with Xcode, in these cases if I'm sure the syntax is correct I just clean and recompile the project, usually it fixes the problem.

Title: UIPageViewController Conflict issue


问:
Twitter api search query for multiple accounts and words
How can I create a twitter search query for multiple accounts based on multiple words?
For example: Consider two accounts: @hero1 and @hero2. I want all tweets from hero1 containing words 'super' or 'action' and tweets from hero2 containing word 'enemy' or a hashtag '#great'. How can I achieve this in one search query. I am able to search for a single account and single keyword but the multiple case is not working. Any help would be appreciated. Thanks in advance!
Currently my api call looks like:</p>

```<code>https://api.twitter.com/1.1/search/tweets.json?q=from%3Ahero1+super+action&count=10&include_entities=true
</code>```

答:
The advanced search doesn't allow the sort of query that you want in a single request.

You will have to call two separate searches:

super or action from:hero1 and the enemy or #great from:hero2

Body:
How can I create a twitter search query for multiple accounts based on multiple words?
For example: Consider two accounts: @hero1 and @hero2. I want all tweets from hero1 containing words 'super' or 'action' and tweets from hero2 containing word 'enemy' or a hashtag '#great'. How can I achieve this in one search query. I am able to search for a single account and single keyword but the multiple case is not working. Any help would be appreciated. Thanks in advance!
Currently my api call looks like:

https://api.twitter.com/1.1/search/tweets.json?q=from%3Ahero1+super+action&count=10&include_entities=true


问:
How to run TensorFlow on an AWS cluster?
I'm trying to run distributed tensorflow on an EMR/EC2 cluster but I don't know how to specify different instances in the cluster to run parts of the code.

In the documentation, they've used tf.device("/gpu:0") to specify a gpu. But what if I have a master CPU and 5 different slaves GPU instances running in an EMR cluster and I want to specify those GPUs to run some code? I can't input tf.device() with the public DNS names of the instances because it throws an error saying the name cannot be resolved.

答:
Since your question, AWS has released some code to ease the use of distributed TensorFlow on an EC2 cluster.

See this github repository. Everything is described in the README.md but the short story is that it will create an AWS stack with

Security Groups

Elastic File System

EC2 instances with the AWS deep learning AMI and the EFS mounted on them,

The EC2 instances will be configured so you can easily run a distributed tensorflow run by running a command on the master node (see the Running Distributed Training on TensorFlow section).

ContentLicense: CC BY-SA 4.0


问:
How to strech the image to the width of the layout?
HI,

I want to stretch my image to the layout width, how can i do this using xml layouts ?

```<code><LinearLayout android:layout_width="700dp"
        android:layout_height="310dp" android:orientation="vertical">
        <TextView android:id="@+id/widget37" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="Welcome Ramesh Kumar,"
            android:paddingTop="5dp" android:textSize="10dp" android:textColor="#02284D"
            android:gravity="left">
        </TextView>
        <TextView android:id="@+id/widget37" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="Employee Id: 152490"
            android:textSize="10dp" android:textColor="#02284D" android:gravity="left">
        </TextView>
        <RelativeLayout android:layout_width="fill_parent"
            android:layout_height="150dp" android:layout_x="10dp">
            <ImageView android:id="@+id/bannert30"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:src="@drawable/front_screen" android:scaleType="fitEnd"
                android:layout_alignParentLeft="true">
            </ImageView>
        </RelativeLayout>
</code>```

This is my code please help ?

答: You can use android:scaleType="fitXY" for the ImageView and another alternative is to set the image as the background of the layout.

ContentLicense: CC BY-SA 2.5

Body:
HI,

I want to stretch my image to the layout width, how can i do this using xml layouts ?

<LinearLayout android:layout_width="700dp"
        android:layout_height="310dp" android:orientation="vertical">
        <TextView android:id="@+id/widget37" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="Welcome Ramesh Kumar,"
            android:paddingTop="5dp" android:textSize="10dp" android:textColor="#02284D"
            android:gravity="left">
        </TextView>
        <TextView android:id="@+id/widget37" android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:text="Employee Id: 152490"
            android:textSize="10dp" android:textColor="#02284D" android:gravity="left">
        </TextView>
        <RelativeLayout android:layout_width="fill_parent"
            android:layout_height="150dp" android:layout_x="10dp">
            <ImageView android:id="@+id/bannert30"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:src="@drawable/front_screen" android:scaleType="fitEnd"
                android:layout_alignParentLeft="true">
            </ImageView>
        </RelativeLayout>

This is my code please help ?


问:
R: Extract columns from list of data.frames in a tibble
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

```<code>random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)
</code>```

to this tibble d

```<code>d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))
</code>```

thanks

Iain

答:
Do you know your column names ahead of time?

```<code>extract_column <- function( d, column_name ) {
  if( is.null(d) ) {
    NA_character_
  } else {
    as.character(d[[column_name]])
  }
}

cc %>%
  dplyr::mutate(
    a = purrr::map_chr(.$my_data, extract_column, column_name="a"),
    b = purrr::map_chr(.$my_data, extract_column, column_name="b")
  ) %>%
  dplyr::select(-my_data)
</code>```

(I renamed your c tibble to cc so it can't collide with c().)

Body:
I am wondering how to manipulate a list containing data.frames stored in a tibble.

Specifically, I would like to extract two columns from a data.frame that are stored in a tibble list column.

I would like to go from this tibble c

random_data<-list(a=letters[1:10],b=LETTERS[1:10])
x<-as.data.frame(random_data, stringsAsFactors=FALSE)
y<-list()
y[[1]]<-x[1,,drop=FALSE]
y[[3]]<-x[2,,drop=FALSE]
c<-tibble(z=c(1,2,3),my_data=y)

to this tibble d

d<-tibble(z=c(1,2,3),a=c('a',NA,'b'),b=c('A',NA,'B'))

thanks

Iain

Body:
Do you know your column names ahead of time?

extract_column <- function( d, column_name ) {
  if( is.null(d) ) {
    NA_character_
  } else {
    as.character(d[[column_name]])
  }
}

cc %>%
  dplyr::mutate(
    a = purrr::map_chr(.$my_data, extract_column, column_name="a"),
    b = purrr::map_chr(.$my_data, extract_column, column_name="b")
  ) %>%
  dplyr::select(-my_data)

(I renamed your c tibble to cc so it can't collide with c().)


问:
Purchasing Amazon reserved instances based on average usage
It seems possible to purchase reserved instances based on average usage instead of initial usage.  For example, if I purchased 2 RIs, ran 1 instance on day 1 and ran 3 instances on day 2, it will be essentially the same usage rate as if I ran 2 instances for 2 days.  Will RI calculation see it that way, or will I be charged 3 days of RI usage and 1 day of on-demand usage?</p>

答:
There's no spread across hours.

Each hour is considered separately, and underutilized reserved instance hours don't roll forward or backward into hours where you have more running instances than reserved.

Customers using both Reserved and On-Demand instances will have Reserved Instance rates applied first to minimize costs. You pay the low hourly usage fee for every hour in your Reserved Instance term (which means you’re charged the hourly fee regardless of whether any usage has occurred during an hour).  When your total quantity of running instances during a given hour exceeds the number of applicable Reserved Instances you own, you will be charged the On-Demand rate. (emphasis added)

https://aws.amazon.com/ec2/pricing/reserved-instances/buyer/

While not explicitly stated, of course, "you will charged the On-Demand rate" refers to running instances each hour beyond the number of reserved instances.


问:
How to parse an array that is in a json object
I'm having issues drilling down into a json object that has an array in it. The issue I'm running into is that when I get inside that object it returns object Object.

My code looks like this:

```<code>(function(){
   var rivetAPI = "https://url";
   $.ajax({
          url:rivetAPI,
          type:"GET",
          dataType:"json",
          success: function(obj){
          //var myData = JSON.stringify(obj);

          $.each(obj.data, function(index, value){
             $('.data').text(value);
           })
      }
   });
})();
</code>```

I'm keeping the URL private, but wanted to show that it's coming from a HTTPS just in case that might be part of the problem.

The JSON is formatted as such:

```<code>{ "data": [
  {
     "likes": 10,
     "imageURL": "url",
     "mediaThumbURL": "url",
     "mediaDisplayURL": null,
     "mediaOriginalURL": "url",
     "userProfilePictureURL": null,
     "externalLink": null,
     "description": "The sun was setting behind the mounted memorial to Kaiser Wilhelm I.  (30 May 2015)",
     "mediaType": "Photo",
     "caption": "Sunset behind the memorial to Wilhelm I, Koblenz, Germany",
     "latitude": 50.364437,
     "longitude": 7.605915,
     "mediaID": "e9908afe-c9e1-11e5-829e-22000ae606bd",
     "userName": null,
     "googlePlaceId": "ChIJnX0jdld7vkcRYLPaENXUIgQ",
     "locationText": "Koblenz",
     "identifier": {
        "type": "MemberActivity",
        "id": "e9908afe-c9e1-11e5-829e-22000ae606bd"
     },
     "tags": {
        "itinerary": [
           "rhinegetaway"
        ],
        "season": [
           "spring"
        ],
        "cruise-itinerary": [
           "rhine-getaway"
        ],
        "_country": [
           "DE"
        ],
        "_city": [
           "lutzel"
        ]
     },
     "source": {
        "type": "ProjectActivity",
        "id": "54b97332-b9e4-11e3-876f-22000a240faf"
     },
     "valid": true
  },
  {
     "likes": 10,
     etc....

  }
}
</code>```

答:
In your loop, value will still hold an object (one of the objects in the array that data is), and if you give that to .text(), you'll get object Object just like with any other object.

You can access the individual properties of that object in the loop:

```<code>$.each(obj.data, function(index, value){
    $('.data').text(value.likes); // etc.
})
</code>```

As mentioned in a comment, this will overwrite the content of the .data element with every iteration, so will probably still not yield the expected result.

EDIT: If you want to display all likes, you'll have to assemble the string you want to display first, and then update your HTML.

```<code>var likes = [];

$.each(obj.data, function(index, value){
    likes.push(value.likes);
});

$('.data').text(likes.join(', '));
</code>```

This could of course be done "better" with .reduce, but that requires a more fundamental understanding of JS.

Body:
I'm having issues drilling down into a json object that has an array in it. The issue I'm running into is that when I get inside that object it returns object Object.

My code looks like this:

(function(){
   var rivetAPI = "https://url";
   $.ajax({
          url:rivetAPI,
          type:"GET",
          dataType:"json",
          success: function(obj){
          //var myData = JSON.stringify(obj);

          $.each(obj.data, function(index, value){
             $('.data').text(value);
           })
      }
   });
})();

I'm keeping the URL private, but wanted to show that it's coming from a HTTPS just in case that might be part of the problem.

The JSON is formatted as such:

{ "data": [
  {
     "likes": 10,
     "imageURL": "url",
     "mediaThumbURL": "url",
     "mediaDisplayURL": null,
     "mediaOriginalURL": "url",
     "userProfilePictureURL": null,
     "externalLink": null,
     "description": "The sun was setting behind the mounted memorial to Kaiser Wilhelm I.  (30 May 2015)",
     "mediaType": "Photo",
     "caption": "Sunset behind the memorial to Wilhelm I, Koblenz, Germany",
     "latitude": 50.364437,
     "longitude": 7.605915,
     "mediaID": "e9908afe-c9e1-11e5-829e-22000ae606bd",
     "userName": null,
     "googlePlaceId": "ChIJnX0jdld7vkcRYLPaENXUIgQ",
     "locationText": "Koblenz",
     "identifier": {
        "type": "MemberActivity",
        "id": "e9908afe-c9e1-11e5-829e-22000ae606bd"
     },
     "tags": {
        "itinerary": [
           "rhinegetaway"
        ],
        "season": [
           "spring"
        ],
        "cruise-itinerary": [
           "rhine-getaway"
        ],
        "_country": [
           "DE"
        ],
        "_city": [
           "lutzel"
        ]
     },
     "source": {
        "type": "ProjectActivity",
        "id": "54b97332-b9e4-11e3-876f-22000a240faf"
     },
     "valid": true
  },
  {
     "likes": 10,
     etc....

  }
}

Body:
In your loop, value will still hold an object (one of the objects in the array that data is), and if you give that to .text(), you'll get object Object just like with any other object.

You can access the individual properties of that object in the loop:

$.each(obj.data, function(index, value){
    $('.data').text(value.likes); // etc.
})

As mentioned in a comment, this will overwrite the content of the .data element with every iteration, so will probably still not yield the expected result.

EDIT: If you want to display all likes, you'll have to assemble the string you want to display first, and then update your HTML.

var likes = [];

$.each(obj.data, function(index, value){
    likes.push(value.likes);
});

$('.data').text(likes.join(', '));

This could of course be done "better" with .reduce, but that requires a more fundamental understanding of JS.


问:
Is it possible to run batch files in Android?
Is it possible to run batch/bat file in Android?
Or is there any app to run it?

I hope there is some app what can run it.

答: If you mean a Windows batch file, then no, as Android is not Windows.</p>


问:
React - Accessing nested objects in returned data
I'm using fetch to return some data from a local API. I'm able to return the data and set the state. However, in my render() function when using map and attempting to access anything deeper than the top level object in the data I get an undefined error. I can correctly log any level of the data that I want to the console, but I don't have access to it within the rendered component.

```<code>constructor(props) {
  super(props);
  this.state ={
    verifications: []
  }
}

componentWillMount(){
  fetch('http://localhost:3001/verifications')
    .then(response => response.json())
    .then((verifications) => {
      this.setState({verifications})
      console.log(this.state);
    });
}
</code>```

and in my render

```<code>{this.state.verifications.map(verification =>
  <div key={verification._id}>
    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier.logo}
      title={verification.supplier.companyName}
      description={verification.tasks.length}
    />
  </div>
)}
</code>```

This is the error I get:
Unhandled Rejection (TypeError): Cannot read property 'logo' of null

I've searched high and low for an answer to this, but I feel like I must be approaching this wrong. I come from Angular 1, and I'm extremely new to React. Maybe I'm having a hard time grasping the concepts.

Here's my data:

```<code>[
{
"_id": 1000,
"supplier": {
"_id": 1000,
"companyName": "ACME Business Ventures",
"logo": "/images/logos/suppliers/acme.jpg",
"avettaId": "ADS83J",
"brandColor": "#563E5E",
"clients": [],
"locations": [],
"primaryContact": {},
"address": {},
"createdAt": "2017-06-30T17:42:23.479Z"
},
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 2000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 3000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 4000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
}
]
</code>```

答: One of your suppliers is null (at least one). Consider using something like imageUrl={verification.supplier ? verification.supplier.logo : null} instead of imageUrl={verification.supplier.logo}.

Body:
I'm using fetch to return some data from a local API. I'm able to return the data and set the state. However, in my render() function when using map and attempting to access anything deeper than the top level object in the data I get an undefined error. I can correctly log any level of the data that I want to the console, but I don't have access to it within the rendered component.

constructor(props) {
  super(props);
  this.state ={
    verifications: []
  }
}

componentWillMount(){
  fetch('http://localhost:3001/verifications')
    .then(response => response.json())
    .then((verifications) => {
      this.setState({verifications})
      console.log(this.state);
    });
}

and in my render

{this.state.verifications.map(verification =>

    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier.logo}
      title={verification.supplier.companyName}
      description={verification.tasks.length}
    />

)}

This is the error I get:
Unhandled Rejection (TypeError): Cannot read property 'logo' of null

I've searched high and low for an answer to this, but I feel like I must be approaching this wrong. I come from Angular 1, and I'm extremely new to React. Maybe I'm having a hard time grasping the concepts.

Here's my data:

[
{
"_id": 1000,
"supplier": {
"_id": 1000,
"companyName": "ACME Business Ventures",
"logo": "/images/logos/suppliers/acme.jpg",
"avettaId": "ADS83J",
"brandColor": "#563E5E",
"clients": [],
"locations": [],
"primaryContact": {},
"address": {},
"createdAt": "2017-06-30T17:42:23.479Z"
},
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 2000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 3000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 4000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
}
]


问:
F# Inline Function Specialization
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

```<code>let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)
</code>```

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!

答: Are you sure this strategy of redefining inline functions with different argument types can work? Looks like you're trying to overload to me...

Title: F# Inline Function Specialization

Body:
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!


问:
How to create and upload files to amazon-S3
I have a C# Lambda function that creates a simple .txt file like this:

```<code>string file = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar + "file.txt";
File.Create(file);
</code>```

And then I am trying to upload it to S3

```<code>TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.EUWest1));
fileTransferUtility.Upload(file, MyBucketNameInString);
</code>```

But, it is returning this error:

File createdOne or more errors occurred. (The process cannot access
  the file '/tmp/file.txt' because it is being used by another
  process.):  AggregateException

Any solutions please?

答:
My simpl solution to Uploading a file to amazon S3</p>

```<code>private void AddFile(Stream image)
{
    InitializeKey();
    var uploadRequest = new TransferUtilityUploadRequest();
    uploadRequest.CannedACL = S3CannedACL.PublicRead;
    uploadRequest.InputStream = image;
    uploadRequest.BucketName = AppConfiguration.AmazonS3FileBucketName;
    uploadRequest.Key = _key;

    using (TransferUtility fileTransferUtility = new TransferUtility(_client))
    {
        fileTransferUtility.Upload(uploadRequest);
    }
}
</code>```

Body:
I have a C# Lambda function that creates a simple .txt file like this:

string file = Path.DirectorySeparatorChar + "tmp" + Path.DirectorySeparatorChar + "file.txt";
File.Create(file);

And then I am trying to upload it to S3

TransferUtility fileTransferUtility = new TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.EUWest1));
fileTransferUtility.Upload(file, MyBucketNameInString);

But, it is returning this error:

File createdOne or more errors occurred. (The process cannot access
  the file '/tmp/file.txt' because it is being used by another
  process.):  AggregateException

Any solutions please?

Body:
My simpl solution to Uploading a file to amazon S3

private void AddFile(Stream image)
{
    InitializeKey();
    var uploadRequest = new TransferUtilityUploadRequest();
    uploadRequest.CannedACL = S3CannedACL.PublicRead;
    uploadRequest.InputStream = image;
    uploadRequest.BucketName = AppConfiguration.AmazonS3FileBucketName;
    uploadRequest.Key = _key;

    using (TransferUtility fileTransferUtility = new TransferUtility(_client))
    {
        fileTransferUtility.Upload(uploadRequest);
    }
}


问:
Return name in ActiveRecord relation along with foreign key id
I have a Sub-Component model which can belong to other sub-components. My Model looks like this:

```<code>class SubComponent < ApplicationRecord
  belongs_to :parent, class_name: "SubComponent", foreign_key: "parent_sub_component_id", optional: true
  has_many :child_sub_components, class_name: "SubComponent", foreign_key: "parent_sub_component_id"

  validates_presence_of :name
end
</code>```

This model is fairly simple, it has a name field and a parent_sub_component_id which as the name suggests is an id of another SubComponent.

I'd like to generate a query that returns all of the SubComponents (with their id, name, and parent_sub_component_id) but also includes the actual name of it's parent_sub_component.

This seems like it should be pretty simple but for the life of me I can't figure out how to do it. I'd like for this query to be done in the database rather than doing an each loop in Ruby or something like that.

EDIT:

I'd like for the output to look something like this:

#<ActiveRecord::Relation [#<SubComponent id: 1, name: "Parent Sub", parent_sub_component_id: nil, parent_sub_component_name: nil created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">, #<SubComponent id: 2, name: "Child Sub", parent_sub_component_id: 1, parent_sub_component_name: "Parent Sub" created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">]>

答:
This is untested, but should get you started in the right direction, you can do this in Arel by doing something like

```<code>def self.execute_query
  parent_table = Arel::Table.new(:sub_component).alias
  child_table = Arel::Table.new(:sub_component)

child_table.join(parent_table, Arel::Nodes::OuterJoin).on(child_table[:parent_sub_component_id].eq(parent_table[:id]).project(child_table[:id], child_table[:name], parent_table[:id], parent_table[:name])
end
</code>```

This results in a query like

```<code>SELECT "sub_component"."id", "sub_component"."name", "sub_component_2"."id", "sub_component_2"."name" FROM "sub_component" LEFT OUTER JOIN "sub_component" "sub_component_2" ON "sub_component"."parent_sub_component_id" = "sub_component_2"."id"
</code>```

this is just off the top of my head by looking at Rails/Arel and probably needs a some work, but the query looks about what I would expect and this should get you going.

Body:
I have a Sub-Component model which can belong to other sub-components. My Model looks like this:

class SubComponent < ApplicationRecord
  belongs_to :parent, class_name: "SubComponent", foreign_key: "parent_sub_component_id", optional: true
  has_many :child_sub_components, class_name: "SubComponent", foreign_key: "parent_sub_component_id"

  validates_presence_of :name
end

This model is fairly simple, it has a name field and a parent_sub_component_id which as the name suggests is an id of another SubComponent.

I'd like to generate a query that returns all of the SubComponents (with their id, name, and parent_sub_component_id) but also includes the actual name of it's parent_sub_component.

This seems like it should be pretty simple but for the life of me I can't figure out how to do it. I'd like for this query to be done in the database rather than doing an each loop in Ruby or something like that.

EDIT:

I'd like for the output to look something like this:

#<ActiveRecord::Relation [#<SubComponent id: 1, name: "Parent Sub", parent_sub_component_id: nil, parent_sub_component_name: nil created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">, #<SubComponent id: 2, name: "Child Sub", parent_sub_component_id: 1, parent_sub_component_name: "Parent Sub" created_at: "2017-07-07 00:29:37", updated_at: "2017-07-07 00:29:37">]>

Body:
This is untested, but should get you started in the right direction, you can do this in Arel by doing something like

def self.execute_query
  parent_table = Arel::Table.new(:sub_component).alias
  child_table = Arel::Table.new(:sub_component)

child_table.join(parent_table, Arel::Nodes::OuterJoin).on(child_table[:parent_sub_component_id].eq(parent_table[:id]).project(child_table[:id], child_table[:name], parent_table[:id], parent_table[:name])
end

This results in a query like

SELECT "sub_component"."id", "sub_component"."name", "sub_component_2"."id", "sub_component_2"."name" FROM "sub_component" LEFT OUTER JOIN "sub_component" "sub_component_2" ON "sub_component"."parent_sub_component_id" = "sub_component_2"."id"

this is just off the top of my head by looking at Rails/Arel and probably needs a some work, but the query looks about what I would expect and this should get you going.


问:
Double box/border? Is this possible in CSS?
I'm trying to recreate this image in CSS.

This is what I got from experimenting, so far. I used box-shadow to act as the second box. I'm not sure if there's a better way to do this?

h4 {
  font-family: sans-serif;
  text-transform: uppercase;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  background: white;
  box-shadow: 10px 5px 0px 0px #ffffff, 11px 7px 0px 2px #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>3. Scouting for a location</h4></code>```

答: Use an absolute positioned ::after or ::before pseudo element and have its z-index lower than the element itself. </p>

Body:
I'm trying to recreate this image in CSS.

This is what I got from experimenting, so far. I used box-shadow to act as the second box. I'm not sure if there's a better way to do this?

h4 {
  font-family: sans-serif;
  text-transform: uppercase;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  background: white;
  box-shadow: 10px 5px 0px 0px #ffffff, 11px 7px 0px 2px #000000;
}

3. Scouting for a location


问:
SCRIPT7002: XMLHttpRequest: Network Error 0x2ee7, Could not complete the operation due to error 00002ee7
I got this error in Microsoft Edge. What does it mean? Searching online mostly gives me threads about people encountering the error in products.</p>

答:
I received this error when trying to load a local webpage; there was a typo in a ternary statement.

```<code> var foo = (typo) ? 6 : 3;
</code>```

The page loaded just fine in Chrome & Firefox (with a value of 3), but the page would not load in Edge and I got this same cryptic error.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ee7, Could not complete the operation due to error 00002ee7

Fixing the typo resolved the error message.

Body:
I received this error when trying to load a local webpage; there was a typo in a ternary statement.

 var foo = (typo) ? 6 : 3;

The page loaded just fine in Chrome & Firefox (with a value of 3), but the page would not load in Edge and I got this same cryptic error.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ee7, Could not complete the operation due to error 00002ee7

Fixing the typo resolved the error message.


问:
Any drawbacks in sharing service class's member variables across components in Angular2?
In order to sync the data among difference components, I'm using a single service object, and some members variables of the service are assigned to the components local variables in the their ngOnInit callback.

With this approach, and changes to the data can be refreshed on the component view automatically, no need some kind of event subscription techniques.

But I'm not sure if it is the right way for components to interact, or would there be any problem in the future. Would someone please provide comments?

答:
This is a valid way to share properties. Services in Angular are simply singletons within their given provider scope. However, I would say that this is does not closely match a canonical way to share properties for two main reasons:

The component values can be changed without the changes being reflected in the service

Change detection will not be processed if the value reference within the service changes

As a side note on this, change detection will also not be processed on object mutation if the more efficient ChangeDetectionStrategy.OnPush strategy is used

Using Observable objects in the service could help mitigate both of these issues. For example, using BehaviorSubject objects would allow components to change the value provided by the service (via BehaviorSubject.prototype.next(value)) and to subscribe to the service-proivded value to efficiently perform change detection (done simply through the async pipe when in a template). BehaviorSubject objects also conveniently have the getValue() function to synchronously get the existing property value if needed.

That being said, using Observable fields does have an additional cost and its benefit depends on your situation. I suggest sticking with the KISS principle and keep what you have until you'd actually benefit from doing anything more complex.


问:
Declaring a pointer to point to 2-D array pointer
```<code>#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5][5];
  int (*p)[5];

  clrscr();

   p=a;
  a[0][0]=5;

  printf("%d\n",p[0][0]);  //This prints 5.

  getch();
}
</code>```

My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

答:
a is a 2D array.

```<code>int a[5][5];
</code>```

p is a pointer to a 2D array

```<code>int (*p)[5][5] = &a;
</code>```

if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

```<code>int (**dp)[5][5] = &p;
printf("Value of dp %p\n", (void*) dp);
printf("Value of *dp %p and p %p\n", (void*) *dp, (void*) p);
printf("Value of **dp %p and a %p\n", (void*) **dp, (void*) a);
printf("Value of int array element %d\n", (**dp)[0][0]);
</code>```

Body:
#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5][5];
  int (*p)[5];

  clrscr();

   p=a;
  a[0][0]=5;

  printf("%d\n",p[0][0]);  //This prints 5.

  getch();
}

My question is if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

Body:
a is a 2D array.

int a[5][5];

p is a pointer to a 2D array

int (*p)[5][5] = &a;

if we want to have a pointer to p itself(double pointer) and then access the elements, then how do we declare it?

int (**dp)[5][5] = &p;
printf("Value of dp %p\n", (void*) dp);
printf("Value of *dp %p and p %p\n", (void*) *dp, (void*) p);
printf("Value of **dp %p and a %p\n", (void*) **dp, (void*) a);
printf("Value of int array element %d\n", (**dp)[0][0]);


问:
Force reject/resolve promise
I'm trying to validate a file upload by reading the contents of a manifest file within a zip file. I'm using JSZip to read the file and would like to stop the process of uploading the file under certain conditions. What's the correct way to force a resolve/reject with if/else?

```<code>  function validateUpload(file, errFiles) {
    var validateFile = JSZip.loadAsync(file)
    .then(function(zip) {
      var manifest = zip.files['manifest.json'];
      return manifest.async("text") // added return here
      .then(function(contents) {
        var manifestObj = angular.fromJson(contents);
        if((manifestObj.module === 'analytics') && ($state.current.name.indexOf('packages') !== -1)) {
          return $q.reject('Invalid software upload');
        }
        if(!manifestObj.module && ($state.current.name.indexOf('analytics') !== -1)) {
          return $q.reject('Invalid analytics upload');
        }
        return $q.resolve(file);
      });
    });
    validateFile.then(function(data) {
      console.log('success: ' + data);
      uploadFile(file);
    }, function(error) {
      console.log('error: '+ error);
    });
</code>```

Edit

I was missing a return statement before the call to manifest.async, seems to be correctly calling success/error of validateFile promise now.

答: Adding a return statement before the call to manifest.async fixed the issue.</p>

Title: Force reject/resolve promise

Body:
I'm trying to validate a file upload by reading the contents of a manifest file within a zip file. I'm using JSZip to read the file and would like to stop the process of uploading the file under certain conditions. What's the correct way to force a resolve/reject with if/else?

  function validateUpload(file, errFiles) {
    var validateFile = JSZip.loadAsync(file)
    .then(function(zip) {
      var manifest = zip.files['manifest.json'];
      return manifest.async("text") // added return here
      .then(function(contents) {
        var manifestObj = angular.fromJson(contents);
        if((manifestObj.module === 'analytics') && ($state.current.name.indexOf('packages') !== -1)) {
          return $q.reject('Invalid software upload');
        }
        if(!manifestObj.module && ($state.current.name.indexOf('analytics') !== -1)) {
          return $q.reject('Invalid analytics upload');
        }
        return $q.resolve(file);
      });
    });
    validateFile.then(function(data) {
      console.log('success: ' + data);
      uploadFile(file);
    }, function(error) {
      console.log('error: '+ error);
    });

Edit

I was missing a return statement before the call to manifest.async, seems to be correctly calling success/error of validateFile promise now.


问:
Module design to micro-services in Node.js; would like to weigh some choices and get more specific examples
Our platform:  IBM Bluemix platform, IBM Watson Conversation, SLACK client.  Code is deployed in Node.js runtime.

We have a simple bot that mediates a conversation between SLACK user and IBM Watson service.   The conversation allows the user to specify query components to get Billing data or Cost data from back end services.   Works well, for small data sets....

We want our bot to handle larger data sets that come from the back end service.  The use case we are pursuing in this:
SLACK User interacts with the Watson conversation, provides necessary query input, query runs, query results are turned into a CSV file (spreadsheet) and parked in BOX content manager which we have available.  Once the job finishes, the user receives notification in SLACK that the data is in the Box file, with the link provided.

Being a novice Node.js programmer I don't have a good grasp on how to structure the components to handle this type of asynchronous exchange.  My hunch tells me that I should create functions to handle the discrete tasks:  1) calling remote service and bringing data back, 2) wrapping data into CSV format, 3) creating file in BOX, returning link, 4) notifying SLACK user with message including link to the data file in Box.

My research tells me that I should be using Node's Promises, but not sure exactly how to break things down or how to 'Promisify' things so they work together as planned.  Is this what I should be pursuing?  If so, a nice easy example would be appreciated.

答:
IF you want to follow these steps, you can use async or, Promise, see one example:</p>

```<code>function csvFunc(params) {
    return new Promise(function(resolve, reject) {
    //do something CSV
    });
}

function boxManager(params) {
    return new Promise(function(resolve, reject) {
    //do something box, create box
    });
}

Promise.all([csvFunc(params), boxManager(params)]) //add the functions what you want,
    .then(function(allData) { //after all functions are Ok, then....
        // return the value for slack or what you want to do
        console.log("All functions have perfomed")
    });
</code>```

Body:
IF you want to follow these steps, you can use async or, Promise, see one example:

function csvFunc(params) {
    return new Promise(function(resolve, reject) {
    //do something CSV
    });
}

function boxManager(params) {
    return new Promise(function(resolve, reject) {
    //do something box, create box
    });
}

Promise.all([csvFunc(params), boxManager(params)]) //add the functions what you want,
    .then(function(allData) { //after all functions are Ok, then....
        // return the value for slack or what you want to do
        console.log("All functions have perfomed")
    });


问:
Extract the particular portion from a String
I have the below String variable

```<code>String s = "abc,xyz,lmn,ijk";
</code>```

I want to extract only the portion of the String (i.e - 'lmn')

And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()

And this question was asked in my interview.

I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?

```<code>    String s = "abc,xyz,lmn,ijk";
    int counter = 0;

    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        if (ch[i] == ',') {
            counter++;
        }

    }
</code>```

答:
```<code>public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s = "abc,xyz,lmn,ijk";
    StringBuffer sb=new StringBuffer();
    char[] ch = s.toCharArray();

    for (int i = 0; i < ch.length; i++) {
        if(','==(ch[i]))
        {
            if (sb.toString().equals("lmn")) {
                System.out.println(sb.toString());
            }
            else
            {
                int length=sb.length();
                sb.delete(0, length);
            }

        }
        else
        {
            sb.append(ch[i]);
        }

    }

}
</code>```

Body:
I have the below String variable

String s = "abc,xyz,lmn,ijk";

I want to extract only the portion of the String (i.e - 'lmn')

And, Should not use in-built functions like, SubString(), Split(), IndexOf(). But I can use charArray()

And this question was asked in my interview.

I tried the below code,
But not sure how to proceed. Can any one please provide your thoughts?

    String s = "abc,xyz,lmn,ijk";
    int counter = 0;

    char[] ch = s.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        if (ch[i] == ',') {
            counter++;
        }

    }


问:
How to do a 'null' check in 'if' condition action of Azure Logic App
I've created a logic app which contains some trigger, an 'http' connector and then an 'If' condition activity. The 'http' connector returns a 'json' result say jsonObj.

I'm able to check condition as @equal(body('HTTP')['jsonObj'].someProperty,'someValue') but not able to do a null check on that someProperty value.

Below are some ways I tried which are not working.

```<code>@equal(body('HTTP')['jsonObj'].someProperty, null) --Unable to save
@equal(body('HTTP')['jsonObj']?.someProperty,'null') --Comparing with string value 'null'
</code>```

答:
You can now do:

```<code> @equals(triggerBody()['jsonObj']?['someProperty'], null)
</code>```

It's valid and can be saved but if you try to switch to Basic mode you'll get an error. Can still save though.

Body:
I've created a logic app which contains some trigger, an 'http' connector and then an 'If' condition activity. The 'http' connector returns a 'json' result say jsonObj.

I'm able to check condition as @equal(body('HTTP')['jsonObj'].someProperty,'someValue') but not able to do a null check on that someProperty value.

Below are some ways I tried which are not working.

@equal(body('HTTP')['jsonObj'].someProperty, null) --Unable to save
@equal(body('HTTP')['jsonObj']?.someProperty,'null') --Comparing with string value 'null'

Body:
You can now do:

 @equals(triggerBody()['jsonObj']?['someProperty'], null)

It's valid and can be saved but if you try to switch to Basic mode you'll get an error. Can still save though.


问:
C++ Making a random number/letter generator, something wrong in the code
I'm trying to make a word-list generator that generates random letters and numbers, however I'm having an error where it only gets the first word in the list right, the rest only displays 2 letters/numbers, there is no error in the compiler, at this point it feels like I've tried everything without any luck. Here is the code:

```<code>    #include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <windows.h>
#include <ctime>
using namespace std;

static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // chars we need for generation

int stringLength = sizeof(alphanum) - 1;

char genRandom(){
    return alphanum[rand() % stringLength];
}

int main(){

// WORD LISTS LENGTH
int WordListTotalLength;
int WordListThisLength = 0;
cout << " How many words should be added?" << endl;
cin >> WordListTotalLength;

// WORD LISTS LENGTH ENDS HERE

    SetConsoleTitle("LetterNumberGenerator");

    srand(time(0));
    std::string Str;

    int length = 0;

    cout << "Enter the length of each word:" << endl;
    cin >> length;
    length = length - 1;

    for(unsigned int i = 0; i < length; ++i){
    Str += genRandom();
    }
    ofstream myfile;
  myfile.open("OutputWordlist.txt");

  while (WordListThisLength < WordListTotalLength) {

  myfile <<Str + genRandom();
  myfile << "\n" ;
  genRandom();
     Str = genRandom();
  WordListThisLength = WordListThisLength +1;
  }
  myfile.close();
    cout << "Generation is finished." << endl;

cout << endl;
system("PAUSE");
return 0;
}
</code>```

But all I get from the "OutputWordlist.txt" is the following:

If inputing that I want 5 words in total, with 10 letters or numbers on each line I end up with this:

```<code>N5VKP15QAW
EN
YK
48
OK
</code>```

And sorry if my post is a bit blurry, this is my first time posting. Any help or suggestions would be very appreciated!

答:
I took a look at your code and refactored it quite a bit. Here is the repl.it of it https://repl.it/JS45/0

I was too confused as to what your code did to actually look at what was wrong, but I did sort of use the style you were going for.

I changed the GenRandom function to GenRandomWord(length), and instead of using a while loop, I used a for loop which is easier to see how long it will run for

Also I just printed out the characters instead of saving it to a file. I'm sure you can figure out how to do that

Body:
I'm trying to make a word-list generator that generates random letters and numbers, however I'm having an error where it only gets the first word in the list right, the rest only displays 2 letters/numbers, there is no error in the compiler, at this point it feels like I've tried everything without any luck. Here is the code:

    #include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <windows.h>
#include <ctime>
using namespace std;

static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // chars we need for generation

int stringLength = sizeof(alphanum) - 1;

char genRandom(){
    return alphanum[rand() % stringLength];
}

int main(){

// WORD LISTS LENGTH
int WordListTotalLength;
int WordListThisLength = 0;
cout << " How many words should be added?" << endl;
cin >> WordListTotalLength;

// WORD LISTS LENGTH ENDS HERE

    SetConsoleTitle("LetterNumberGenerator");

    srand(time(0));
    std::string Str;

    int length = 0;

    cout << "Enter the length of each word:" << endl;
    cin >> length;
    length = length - 1;

    for(unsigned int i = 0; i < length; ++i){
    Str += genRandom();
    }
    ofstream myfile;
  myfile.open("OutputWordlist.txt");

  while (WordListThisLength < WordListTotalLength) {

  myfile <<Str + genRandom();
  myfile << "\n" ;
  genRandom();
     Str = genRandom();
  WordListThisLength = WordListThisLength +1;
  }
  myfile.close();
    cout << "Generation is finished." << endl;

cout << endl;
system("PAUSE");
return 0;
}

But all I get from the "OutputWordlist.txt" is the following:

If inputing that I want 5 words in total, with 10 letters or numbers on each line I end up with this:

N5VKP15QAW
EN
YK
48
OK

And sorry if my post is a bit blurry, this is my first time posting. Any help or suggestions would be very appreciated!


问:
Can't get DataGridView to refresh over Linq to SQL (WinForm)
Very strange situation here:  I'm using L2S to populate a DataGridView.

Code follows:

```<code>    private void RefreshUserGrid()
    {
    var UserQuery = from userRecord in this.DataContext.tblUsers
                    orderby userRecord.DisplayName
                    select userRecord;

    UsersGridView.DataSource = UserQuery;

//I have also tried
//this.UserBindingSource.DataSource = UserQuery;
//UsersGridView.Datasource = UserBindingSource;

    UsersGridView.Columns[0].Visible = false;
    }
</code>```

Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well.

However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource.

For the life of me, I can't get it to work.

The code I am currently using on my refresh button is this:

```<code>private void button1_Click(object sender, EventArgs e)
{
    this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues);
    RefreshUserGrid();
}
</code>```

But the damn GridView remains unaffected.  All that happens is the selected row becomes unselected.

I have tried .Refresh(), .Invalidate(), I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works.  The only time the Grid refreshes is if I restart the app.

I must be missing something fundamental, but I'm totally stumped and so are my colleagues.

Any ideas?

Thanks!

答: You can Refresh Grid by just re initialising DataContext object. This will relaease current DataContext object which needs to updated. but new instance will automatically have the updated values.

Body:
Very strange situation here:  I'm using L2S to populate a DataGridView.

Code follows:

    private void RefreshUserGrid()
    {
    var UserQuery = from userRecord in this.DataContext.tblUsers
                    orderby userRecord.DisplayName
                    select userRecord;

    UsersGridView.DataSource = UserQuery;

//I have also tried
//this.UserBindingSource.DataSource = UserQuery;
//UsersGridView.Datasource = UserBindingSource;

    UsersGridView.Columns[0].Visible = false;
    }

Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well.

However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource.

For the life of me, I can't get it to work.

The code I am currently using on my refresh button is this:

private void button1_Click(object sender, EventArgs e)
{
    this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues);
    RefreshUserGrid();
}

But the damn GridView remains unaffected.  All that happens is the selected row becomes unselected.

I have tried .Refresh(), .Invalidate(), I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works.  The only time the Grid refreshes is if I restart the app.

I must be missing something fundamental, but I'm totally stumped and so are my colleagues.

Any ideas?

Thanks!


答:
I would do it this way.</p>

```<code>String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";

boolean coincidence = false;

int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x

char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
  if(c == x.length())
    break;
  else{
    if(ch[i] == x.charAt(c) && !coincidence){
      a = i; b = i; c++;
      coincidence = true;
    }
    else if(ch[i] == x.charAt(c) && coincidence){
      b++; c++;
    }else{
      coincidence = false;
      a = 0; b = 0; c = 0;
    }
  }
}

System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));

if(coincidence){
  System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
  // String extration
  for (int i = a; i <= b; i++)
    r += s.charAt(i);

  System.out.println("String extracted: " + r);
}
</code>```

Title: Extract the particular portion from a String

Body:
I would do it this way.

String s = "abc,xyz,lmn,ijk";
String x = "c,x"; // String to found
String r = "";

boolean coincidence = false;

int a=0; // Initial index if of the first character in x is found
int b=0; // Last index If it was possible to search for the last character of x
int c=0; // Index "iterator" on String x

char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
  if(c == x.length())
    break;
  else{
    if(ch[i] == x.charAt(c) && !coincidence){
      a = i; b = i; c++;
      coincidence = true;
    }
    else if(ch[i] == x.charAt(c) && coincidence){
      b++; c++;
    }else{
      coincidence = false;
      a = 0; b = 0; c = 0;
    }
  }
}

System.out.println("String: " + s);
System.out.println("String to find: " + x);
System.out.println("Was found? " + ((coincidence)? "Yes" : "No"));

if(coincidence){
  System.out.println("Intervals indexes in String: ["+a + "," + b +"]");
  // String extration
  for (int i = a; i <= b; i++)
    r += s.charAt(i);

  System.out.println("String extracted: " + r);
}


问:
Rename/Delete specific amount of characters of nested Foldernames
folder layout is like:

root\folder1a\subfolder2a\randommmsubfolder3a

root\folder1b\subfolder2b\randommmsubfolder3b

root\folder1c\subfolder2c\randommmsubfolder3c

i want to delete/strip the 8 characters  of the folder names in the third level deep. basically the "randommm" part of each name. some names have exclamation marks in it.
i have a loop batch but it only renames the first encounter, but does not progress anything after. here is my code:

```<code>cd "C:\Root"
for /D %%i in (*) do (
cd %%i
for /D %%j in (*) do (
cd %%j
setlocal DisableDelayedExpansion
for /D %%k in (*) do (
set name=%%k
setlocal enableextensions enabledelayedexpansion
ren "!name!" "!name:~8!"
endlocal
endlocal
)))
</code>```

答:
@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
pushd "%sourcedir%"
for /D %%i in (*) do (
 pushd "%%i"
  for /D %%j in (*) do (
  pushd "%%j"
  setlocal DisableDelayedExpansion
  for /D %%k in (*) do (
   set "name=%%k"
   setlocal enableextensions ENABLEDELAYEDEXPANSION
   ECHO ren "!name!" "!name:~8!"
   ENDLOCAL
  )
  ENDLOCAL
  popd
 )
 popd
)
popd

GOTO :EOF
```

Two problems - the second endlocal needs to be moved so it matches the nesting level of the corresponding setlocal and cd changes directory, but those directory changes are not backed out by an endlocal AFAII. Using pushd/popd ensures correct progression.

Body:
folder layout is like:

root\folder1a\subfolder2a\randommmsubfolder3a

root\folder1b\subfolder2b\randommmsubfolder3b

root\folder1c\subfolder2c\randommmsubfolder3c

i want to delete/strip the 8 characters  of the folder names in the third level deep. basically the "randommm" part of each name. some names have exclamation marks in it.
i have a loop batch but it only renames the first encounter, but does not progress anything after. here is my code:

cd "C:\Root"
for /D %%i in (*) do (
cd %%i
for /D %%j in (*) do (
cd %%j
setlocal DisableDelayedExpansion
for /D %%k in (*) do (
set name=%%k
setlocal enableextensions enabledelayedexpansion
ren "!name!" "!name:~8!"
endlocal
endlocal
)))

Body:
@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
pushd "%sourcedir%"
for /D %%i in (*) do (
 pushd "%%i"
  for /D %%j in (*) do (
  pushd "%%j"
  setlocal DisableDelayedExpansion
  for /D %%k in (*) do (
   set "name=%%k"
   setlocal enableextensions ENABLEDELAYEDEXPANSION
   ECHO ren "!name!" "!name:~8!"
   ENDLOCAL
  )
  ENDLOCAL
  popd
 )
 popd
)
popd

GOTO :EOF

Two problems - the second endlocal needs to be moved so it matches the nesting level of the corresponding setlocal and cd changes directory, but those directory changes are not backed out by an endlocal AFAII. Using pushd/popd ensures correct progression.


答:
The second index of your array has supplier: null. You can check that supplier exists first

```<code>{this.state.verifications.map(verification =>
  <div key={verification._id}>
    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier && verification.supplier.logo}
      title={verification.supplier && verification.supplier.companyName}
      description={verification.tasks.length}
    />
  </div>
)}
</code>```

Title: React - Accessing nested objects in returned data

Body:
I'm using fetch to return some data from a local API. I'm able to return the data and set the state. However, in my render() function when using map and attempting to access anything deeper than the top level object in the data I get an undefined error. I can correctly log any level of the data that I want to the console, but I don't have access to it within the rendered component.

constructor(props) {
  super(props);
  this.state ={
    verifications: []
  }
}

componentWillMount(){
  fetch('http://localhost:3001/verifications')
    .then(response => response.json())
    .then((verifications) => {
      this.setState({verifications})
      console.log(this.state);
    });
}

and in my render

{this.state.verifications.map(verification =>

    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier.logo}
      title={verification.supplier.companyName}
      description={verification.tasks.length}
    />

)}

This is the error I get:
Unhandled Rejection (TypeError): Cannot read property 'logo' of null

I've searched high and low for an answer to this, but I feel like I must be approaching this wrong. I come from Angular 1, and I'm extremely new to React. Maybe I'm having a hard time grasping the concepts.

Here's my data:

[
{
"_id": 1000,
"supplier": {
"_id": 1000,
"companyName": "ACME Business Ventures",
"logo": "/images/logos/suppliers/acme.jpg",
"avettaId": "ADS83J",
"brandColor": "#563E5E",
"clients": [],
"locations": [],
"primaryContact": {},
"address": {},
"createdAt": "2017-06-30T17:42:23.479Z"
},
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 2000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 3000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
},
{
"_id": 4000,
"supplier": null,
"tasks": [
{
"form": "PQF General",
"question": "How long have you been in business?",
"answer": "18 Years",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "PQF General",
"question": "Have you had any fatalities in the last 3 years?",
"answer": "No",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Diversity Questionnaire",
"question": "Are you a minority-owned business?",
"answer": "Yes",
"status": "incomplete",
"attachment": "",
"comments": []
},
{
"form": "Sustainability Questionnaire",
"question": "What percentage of your business runs on renewable energy?",
"answer": "About 55%, but that's expected to climb to 80% by next year.",
"status": "incomplete",
"attachment": "",
"comments": []
}
]
}
]

Body:
The second index of your array has supplier: null. You can check that supplier exists first

{this.state.verifications.map(verification =>
  <div key={verification._id}>
    <ReviewListItem
      hasAvatar={true}
      imageUrl={verification.supplier && verification.supplier.logo}
      title={verification.supplier && verification.supplier.companyName}
      description={verification.tasks.length}
    />
  </div>
)}


问:
Compiletime transform of tree into tuple
I'm stuck with the following problem:

given a tree represented by non-terminal nodes of type Node<> and terminal nodes of arbitrary types like A, B and so on (see below).

Because I don't want to use runtime-polymorphism I like to transform the tree into a std::tuple via a constexpr function like the immediately invoked lambda expression in the example below.

```<code>struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

template<typename... T>
struct Node {
    constexpr Node(const T&... n) : mChildren{n...} {}
    std::tuple<T...> mChildren;
};

template<uint8_t N>
struct IndexNode {
    std::array<uint8_t, N> mChildren;
};

int main() {
    constexpr auto tree = []() {
        auto t = Node(A(),
                       B(),
                       Node(C(),
                            Node(D())),
                       E());

        // transform t into std::tuple<A, B, C, D, IndexNode<1>{3}, IndexNode<2>{2, 4}, E, IndexNode<4>{0, 1, 5, 6}>

        // return ...;
    }();

}
</code>```

The idea is to use an index to a tuple element as a "pointer" to the active (selected) node of the tree. The overall purpose is to implement a menu-system on a µC without using runtime-polymorphism.

If I can carry out this transformation at compiletime, I can use a special meta-function to retrieve the active tuple-element and call some function on it. This function I wrote already.

The missing link would surely be some sort of depth-first tree-traversal ... but I can't figure it out.

答:
What about using a lot of std::tuple_cat, std::index_sequence and recursion as follows?

```<code>#include <tuple>
#include <array>
#include <iostream>

struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

template <typename... T>
struct Node
 {
   constexpr Node (T const & ... n) : mChildren { n... }
    { }

   std::tuple<T...> mChildren;
 };

template <std::size_t N>
struct IndexNode
 { std::array<uint8_t, N> mChildren; };

template <typename>
struct cntT : public std::integral_constant<std::size_t, 1U>
 { };

template <typename ... Ts>
struct cntT<Node<Ts...>>
   : public std::integral_constant<std::size_t, 1U + (cntT<Ts>::value + ...)>
 { };

template <typename T>
struct getT
 {
   constexpr auto operator() (T const & t, std::size_t & cnt)
    { ++cnt; return std::make_tuple(t); }
 };

template <typename ... Ts>
struct getT<Node<Ts...>>
 {
   template <std::size_t ... Is>
   constexpr auto func (std::tuple<Ts...> const & t,
                        std::index_sequence<Is...> const &,
                        std::size_t & cnt)
    {
      std::size_t val { cnt };

      IndexNode<sizeof...(Ts)> in
          { { { uint8_t(val += cntT<Ts>::value)... } } };

      return std::tuple_cat(getT<Ts>()(std::get<Is>(t), cnt)...,
                            std::make_tuple(in));
    }

   constexpr auto operator() (Node<Ts...> const & n, std::size_t & cnt)
    {
      return func(n.mChildren, std::make_index_sequence<sizeof...(Ts)>{},
                  cnt);
    }
 };

template <typename ... Ts>
constexpr auto linearNode (Node<Ts...> const & n)
 {
   std::size_t cnt ( -1 );

   return getT<Node<Ts...>>()(n, cnt);
 }

int main()
 {
   constexpr auto tree = []()
    {
      auto t = Node { A{}, B{}, Node{ C{}, Node{ D{} } }, E{} };

      return linearNode(t);
    }();

   static_assert( std::is_same<
      decltype(tree),
      std::tuple<A, B, C, D, IndexNode<1>, IndexNode<2>, E,
                 IndexNode<4>> const>::value, "!");

   std::cout << "IndexNode<1> { ";

   for ( auto const & v : std::get<4U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<1> { 3, }

   std::cout << "IndexNode<2> { ";

   for ( auto const & v : std::get<5U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<2> { 2, 4, }

   std::cout << "IndexNode<4> { ";

   for ( auto const & v : std::get<7U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<4> { 0, 1, 5, 6, }
 }
</code>```

Body:
I'm stuck with the following problem:

given a tree represented by non-terminal nodes of type Node<> and terminal nodes of arbitrary types like A, B and so on (see below).

Because I don't want to use runtime-polymorphism I like to transform the tree into a std::tuple via a constexpr function like the immediately invoked lambda expression in the example below.

struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

template<typename... T>
struct Node {
    constexpr Node(const T&... n) : mChildren{n...} {}
    std::tuple<T...> mChildren;
};

template<uint8_t N>
struct IndexNode {
    std::array<uint8_t, N> mChildren;
};

int main() {
    constexpr auto tree = []() {
        auto t = Node(A(),
                       B(),
                       Node(C(),
                            Node(D())),
                       E());

        // transform t into std::tuple<A, B, C, D, IndexNode<1>{3}, IndexNode<2>{2, 4}, E, IndexNode<4>{0, 1, 5, 6}>

        // return ...;
    }();

}

The idea is to use an index to a tuple element as a "pointer" to the active (selected) node of the tree. The overall purpose is to implement a menu-system on a µC without using runtime-polymorphism.

If I can carry out this transformation at compiletime, I can use a special meta-function to retrieve the active tuple-element and call some function on it. This function I wrote already.

The missing link would surely be some sort of depth-first tree-traversal ... but I can't figure it out.

Body:
What about using a lot of std::tuple_cat, std::index_sequence and recursion as follows?

#include <tuple>
#include <array>
#include <iostream>

struct A {};
struct B {};
struct C {};
struct D {};
struct E {};

template <typename... T>
struct Node
 {
   constexpr Node (T const & ... n) : mChildren { n... }
    { }

   std::tuple<T...> mChildren;
 };

template <std::size_t N>
struct IndexNode
 { std::array<uint8_t, N> mChildren; };

template <typename>
struct cntT : public std::integral_constant<std::size_t, 1U>
 { };

template <typename ... Ts>
struct cntT<Node<Ts...>>
   : public std::integral_constant<std::size_t, 1U + (cntT<Ts>::value + ...)>
 { };

template <typename T>
struct getT
 {
   constexpr auto operator() (T const & t, std::size_t & cnt)
    { ++cnt; return std::make_tuple(t); }
 };

template <typename ... Ts>
struct getT<Node<Ts...>>
 {
   template <std::size_t ... Is>
   constexpr auto func (std::tuple<Ts...> const & t,
                        std::index_sequence<Is...> const &,
                        std::size_t & cnt)
    {
      std::size_t val { cnt };

      IndexNode<sizeof...(Ts)> in
          { { { uint8_t(val += cntT<Ts>::value)... } } };

      return std::tuple_cat(getT<Ts>()(std::get<Is>(t), cnt)...,
                            std::make_tuple(in));
    }

   constexpr auto operator() (Node<Ts...> const & n, std::size_t & cnt)
    {
      return func(n.mChildren, std::make_index_sequence<sizeof...(Ts)>{},
                  cnt);
    }
 };

template <typename ... Ts>
constexpr auto linearNode (Node<Ts...> const & n)
 {
   std::size_t cnt ( -1 );

   return getT<Node<Ts...>>()(n, cnt);
 }

int main()
 {
   constexpr auto tree = []()
    {
      auto t = Node { A{}, B{}, Node{ C{}, Node{ D{} } }, E{} };

      return linearNode(t);
    }();

   static_assert( std::is_same<
      decltype(tree),
      std::tuple<A, B, C, D, IndexNode<1>, IndexNode<2>, E,
                 IndexNode<4>> const>::value, "!");

   std::cout << "IndexNode<1> { ";

   for ( auto const & v : std::get<4U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<1> { 3, }

   std::cout << "IndexNode<2> { ";

   for ( auto const & v : std::get<5U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<2> { 2, 4, }

   std::cout << "IndexNode<4> { ";

   for ( auto const & v : std::get<7U>(tree).mChildren )
      std::cout << int(v) << ", ";

   std::cout << "}" << std::endl; // print IndexNode<4> { 0, 1, 5, 6, }
 }


问:
JPA 2 - Foreign key that only includes one field from a composite primary key?
I'm having trouble getting a composite primary key and foreign keys working in JPA 2/Hibernate. I'm trying to create a simple scenario with countries and provinces:

Country Entity:

```<code>@Entity
@Table(name = "country")
public class Country extends DomainObjectBase implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    private List<Province> provinces;
}
</code>```

Province Primary Key:

```<code>@Embeddable
public class ProvincePK implements Serializable {

    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "country_code")
    private String countryCode;
}
</code>```

Province Entity:

```<code>@Entity
@Table(name = "province")
public class Province extends DomainObjectBase implements Serializable {

    @EmbeddedId
    protected ProvincePK provincePK;

    @MapsId("country_code")
    @JoinColumn(name = "country_code", referencedColumnName = "code", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Country country;
}
</code>```

This create the correct tables for me with one exception:

Country Table:

code PK

...

Province Table

code PK FK - This is where the problem is its creating a foreign key reference to the  country table's code column

country_code FK This is the only foreign key reference I want

...

How do I map my entities/composite key for hibernate to generate the schema I want? Right now I can't insert any data into province because its expecting that country contains the province code!

Thanks for any help.

答:
@MapsID argument must match to the name of attribute in ProvincePK class. @JoinColumn should be marked insertable=true,updatable=true, then it works. Here is the code -

```<code>@Entity
@Table(name = "province")
public class Province  implements Serializable {

    @EmbeddedId
    protected ProvincePK provincePK;

    @MapsId(value = "country_code")
    @JoinColumn(name = "country_code", referencedColumnName = "code")
    @ManyToOne(optional = false)
    private Country country;
}

@Embeddable
public class ProvincePK implements Serializable {

    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "country_code")
    private String country_code;
}

@Entity
@Table(name = "country")
public class Country  implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    private List<Province> provinces;
}
</code>```

Hope it helps.

Body:
I'm having trouble getting a composite primary key and foreign keys working in JPA 2/Hibernate. I'm trying to create a simple scenario with countries and provinces:

Country Entity:

@Entity
@Table(name = "country")
public class Country extends DomainObjectBase implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    private List<Province> provinces;
}

Province Primary Key:

@Embeddable
public class ProvincePK implements Serializable {

    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "country_code")
    private String countryCode;
}

Province Entity:

@Entity
@Table(name = "province")
public class Province extends DomainObjectBase implements Serializable {

    @EmbeddedId
    protected ProvincePK provincePK;

    @MapsId("country_code")
    @JoinColumn(name = "country_code", referencedColumnName = "code", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Country country;
}

This create the correct tables for me with one exception:

Country Table:

code PK

...

Province Table

code PK FK - This is where the problem is its creating a foreign key reference to the  country table's code column

country_code FK This is the only foreign key reference I want

...

How do I map my entities/composite key for hibernate to generate the schema I want? Right now I can't insert any data into province because its expecting that country contains the province code!

Thanks for any help.

Body:
@MapsID argument must match to the name of attribute in ProvincePK class. @JoinColumn should be marked insertable=true,updatable=true, then it works. Here is the code -

@Entity
@Table(name = "province")
public class Province  implements Serializable {

    @EmbeddedId
    protected ProvincePK provincePK;

    @MapsId(value = "country_code")
    @JoinColumn(name = "country_code", referencedColumnName = "code")
    @ManyToOne(optional = false)
    private Country country;
}

@Embeddable
public class ProvincePK implements Serializable {

    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @Basic(optional = false)
    @Column(name = "country_code")
    private String country_code;
}

@Entity
@Table(name = "country")
public class Country  implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "code")
    private String code;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
    private List<Province> provinces;
}

Hope it helps.


答:
Try this example

Hope it will help you.

.border {
text-align: center;
border: solid 3px black;
border-radius: 5px;
text-decoration: none;
font-weight: 600;
color: black;
letter-spacing: 2px;
padding: 20px 15px;
margin: 15px 15px;
background: white;
-webkit-box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
-moz-box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">Title</div></code>```

EDIT

Here now you can see that i made box-shadow to 3px and no longer right side corner.

Title: Double box/border? Is this possible in CSS?

Body:
I'm trying to recreate this image in CSS.

This is what I got from experimenting, so far. I used box-shadow to act as the second box. I'm not sure if there's a better way to do this?

h4 {
  font-family: sans-serif;
  text-transform: uppercase;
  text-align: center;
  border: solid 3px black;
  border-radius: 5px;
  text-decoration: none;
  font-weight: 600;
  color: black;
  letter-spacing: 2px;
  padding: 20px 15px;
  background: white;
  box-shadow: 10px 5px 0px 0px #ffffff, 11px 7px 0px 2px #000000;
}

3. Scouting for a location

Body:
Try this example

Hope it will help you.

.border {
text-align: center;
border: solid 3px black;
border-radius: 5px;
text-decoration: none;
font-weight: 600;
color: black;
letter-spacing: 2px;
padding: 20px 15px;
margin: 15px 15px;
background: white;
-webkit-box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
-moz-box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
box-shadow: 3px 3px 0px 0px #ffffff, 3px 3px 0px 3px #000000;
}

<div class="border">Title</div>

EDIT

Here now you can see that i made box-shadow to 3px and no longer right side corner.