问:
Accessing Data from within angular 2 component
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

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

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }
</code>```

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

```<code>public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }
</code>```

Any help would be appreciated.

答:
Can you provide UserVideoDto interface or class? Basically you get a fail from typescript compiler since there is no videoData field on UserVideoDto.

For testing you could try this:

```<code>videos: Array<any> = []; // this should make TS error go away, but it won't solve issue you have
</code>```

Also note that correct notation would be

```<code>videos: Array<UserVideoDto> = [];
</code>```

Somewhere in your project you should have something like

```<code>interface UserVideoDto {
    ...
    public videoData: any;
    ...
}
</code>```

or

```<code>class UserVideoDto {
    ...
    public videoData: any;
    ...
}
</code>```

Body:
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

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

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }

Any help would be appreciated.

Body:
Can you provide UserVideoDto interface or class? Basically you get a fail from typescript compiler since there is no videoData field on UserVideoDto.

For testing you could try this:

videos: Array<any> = []; // this should make TS error go away, but it won't solve issue you have

Also note that correct notation would be

videos: Array<UserVideoDto> = [];

Somewhere in your project you should have something like

interface UserVideoDto {
    ...
    public videoData: any;
    ...
}

or

class UserVideoDto {
    ...
    public videoData: any;
    ...
}


来源: stackexchange

问:
Create a multidimensional array dynamically in C++
What is the good way (understand idiomatic/good practice) to dynamically create a multidimensional array in C++.

For example let say I have tree integers w, h and d and I want to create an array MyEnum my_array[w][h][d]. (Of course w, h and d are not known at compile time).

Is it best to use nested std::vector or use new or something ?

Bonus question : Is it possible to set the dimension dynamically too ?

答:
In general, nesting std::vector is not a great idea. It's usually a better plan to allocate memory which will hold the entirety of your multidimensonal array as a contiguous block, and then index into it as if it were multidimensional. This memory block could be allocated via new, but unless you need some precise control over how it's allocated (custom allocator), I'd recommend sticking with a single std::vector.

It's not difficult to create a class to manage such a resource in which the number of dimensions can be set dynamically. A good way to organize such a class is to keep track of the allocated memory, the sizes of each dimension, and the stride pattern for each dimension. The strides describe how many elements must be incremented over in order to reach the next element along a given dimension.

This allows efficient indexing (just pointer arithmetic), as well as very efficient reshaping: as long as the number of elements doesn't change, this just requires changing the shape and stride arrays.

Example:

Here's a very basic class which will store such a dynamical multidimensional array of doubles. It stores data in row-major order, meaning that the last index varies the fastest. So for a 2D array, the first row is stored contiguously, followed by the second row, and so on.

You can reshape the array, changing the number of dimensions, if you want. A basic element access operator[] is shown, too. There's nothing else fancy about the class, but you can extend it to provide whatever functionality you want, e.g., iterators, mathematical operations on the data, I/O operators, etc.

```<code>/*! \file dynamic_array.h
 * Basic dynamic multi-dimensional array of doubles.
 */

#ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H

#include <vector>
#include <numeric>
#include <functional>

class
dynamic_array
{
    public:
        dynamic_array(const std::vector<int>& shape)
            : m_nelem(std::accumulate(shape.begin(), shape.end(),
                        1, std::multiplies<int>()))
            , m_ndim(shape.size())
            , m_shape(shape)
        {
            compute_strides();
            m_data.resize(m_nelem, 0.0);
        }

        ~dynamic_array()
        {
        }

        const double& operator[](int i) const
        {
            return m_data.at(i);
        }

        double& operator[](int i)
        {
            return m_data.at(i);
        }

        const double& operator[](const std::vector<int>& indices) const
        {
            auto flat_index = std::inner_product(
                    indices.begin(), indices.end(),
                    m_strides.begin(), 0);
            return m_data.at(flat_index);
        }

        double& operator[](const std::vector<int>& indices)
        {
            auto flat_index = std::inner_product(
                    indices.begin(), indices.end(),
                    m_strides.begin(), 0);
            return m_data.at(flat_index);
        }

        void reshape(const std::vector<int>& new_shape)
        {
            auto new_nelem = std::accumulate(
                    new_shape.begin(), new_shape.end(),
                    1, std::multiplies<int>());
            if (new_nelem != m_nelem) {
                throw std::invalid_argument("dynamic_array::reshape(): "
                        "number of elements must not change.");
            }
            m_nelem = new_nelem;
            m_ndim = new_shape.size();
            m_shape = new_shape;
            compute_strides();
        }

        const std::vector<int>& shape() const
        {
            return m_shape;
        }

        const std::vector<int>& strides() const
        {
            return m_strides;
        }

        int ndim() const
        {
            return m_ndim;
        }

        int nelem() const
        {
            return m_nelem;
        }

    private:
        int m_ndim;
        int m_nelem;
        std::vector<int> m_shape;
        std::vector<int> m_strides;
        std::vector<double> m_data;

        void compute_strides()
        {
            m_strides.resize(m_ndim);
            m_strides.at(m_ndim - 1) = 1;
            std::partial_sum(m_shape.rbegin(),
                    m_shape.rend() - 1,
                    m_strides.rbegin() + 1,
                    std::multiplies<int>());
        }
};

#endif // include guard
</code>```

Here's a basic demo of the functionality.

```<code>/*! \file test.cc
 * Basic test of the dynamic_array class.
 */
#include "dynamic_array.h"
#include <iostream>

int main(int /* argc */, const char * /* argv */[])
{
    dynamic_array arr({2, 3});
    std::cout << "Shape: { ";
    for (auto& each : arr.shape())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    std::cout << "Strides: { ";
    for (auto& each : arr.strides())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    // Reshape array, changing number of dimensions, but
    // keeping number of elements constant.
    arr.reshape({6});
    std::cout << "Shape: { ";
    for (auto& each : arr.shape())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    // Verify that the stride pattern has now also changed.
    std::cout << "Strides: { ";
    for (auto& each : arr.strides())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    return 0;
}
</code>```

You can compile the test program with g++ -std=c++14 -o test test.cc, assuming the file defining the class is in the same directory as test.cc.

ContentLicense: CC BY-SA 3.0

Body:
In general, nesting std::vector is not a great idea. It's usually a better plan to allocate memory which will hold the entirety of your multidimensonal array as a contiguous block, and then index into it as if it were multidimensional. This memory block could be allocated via new, but unless you need some precise control over how it's allocated (custom allocator), I'd recommend sticking with a single std::vector.

It's not difficult to create a class to manage such a resource in which the number of dimensions can be set dynamically. A good way to organize such a class is to keep track of the allocated memory, the sizes of each dimension, and the stride pattern for each dimension. The strides describe how many elements must be incremented over in order to reach the next element along a given dimension.

This allows efficient indexing (just pointer arithmetic), as well as very efficient reshaping: as long as the number of elements doesn't change, this just requires changing the shape and stride arrays.

Example:

Here's a very basic class which will store such a dynamical multidimensional array of doubles. It stores data in row-major order, meaning that the last index varies the fastest. So for a 2D array, the first row is stored contiguously, followed by the second row, and so on.

You can reshape the array, changing the number of dimensions, if you want. A basic element access operator[] is shown, too. There's nothing else fancy about the class, but you can extend it to provide whatever functionality you want, e.g., iterators, mathematical operations on the data, I/O operators, etc.

/*! \file dynamic_array.h
 * Basic dynamic multi-dimensional array of doubles.
 */

#ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H

#include <vector>
#include <numeric>
#include <functional>

class
dynamic_array
{
    public:
        dynamic_array(const std::vector<int>& shape)
            : m_nelem(std::accumulate(shape.begin(), shape.end(),
                        1, std::multiplies<int>()))
            , m_ndim(shape.size())
            , m_shape(shape)
        {
            compute_strides();
            m_data.resize(m_nelem, 0.0);
        }

        ~dynamic_array()
        {
        }

        const double& operator[](int i) const
        {
            return m_data.at(i);
        }

        double& operator[](int i)
        {
            return m_data.at(i);
        }

        const double& operator[](const std::vector<int>& indices) const
        {
            auto flat_index = std::inner_product(
                    indices.begin(), indices.end(),
                    m_strides.begin(), 0);
            return m_data.at(flat_index);
        }

        double& operator[](const std::vector<int>& indices)
        {
            auto flat_index = std::inner_product(
                    indices.begin(), indices.end(),
                    m_strides.begin(), 0);
            return m_data.at(flat_index);
        }

        void reshape(const std::vector<int>& new_shape)
        {
            auto new_nelem = std::accumulate(
                    new_shape.begin(), new_shape.end(),
                    1, std::multiplies<int>());
            if (new_nelem != m_nelem) {
                throw std::invalid_argument("dynamic_array::reshape(): "
                        "number of elements must not change.");
            }
            m_nelem = new_nelem;
            m_ndim = new_shape.size();
            m_shape = new_shape;
            compute_strides();
        }

        const std::vector<int>& shape() const
        {
            return m_shape;
        }

        const std::vector<int>& strides() const
        {
            return m_strides;
        }

        int ndim() const
        {
            return m_ndim;
        }

        int nelem() const
        {
            return m_nelem;
        }

    private:
        int m_ndim;
        int m_nelem;
        std::vector<int> m_shape;
        std::vector<int> m_strides;
        std::vector<double> m_data;

        void compute_strides()
        {
            m_strides.resize(m_ndim);
            m_strides.at(m_ndim - 1) = 1;
            std::partial_sum(m_shape.rbegin(),
                    m_shape.rend() - 1,
                    m_strides.rbegin() + 1,
                    std::multiplies<int>());
        }
};

#endif // include guard

Here's a basic demo of the functionality.

/*! \file test.cc
 * Basic test of the dynamic_array class.
 */
#include "dynamic_array.h"
#include <iostream>

int main(int /* argc */, const char * /* argv */[])
{
    dynamic_array arr({2, 3});
    std::cout << "Shape: { ";
    for (auto& each : arr.shape())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    std::cout << "Strides: { ";
    for (auto& each : arr.strides())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    // Reshape array, changing number of dimensions, but
    // keeping number of elements constant.
    arr.reshape({6});
    std::cout << "Shape: { ";
    for (auto& each : arr.shape())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    // Verify that the stride pattern has now also changed.
    std::cout << "Strides: { ";
    for (auto& each : arr.strides())
        std::cout << each << " ";
    std::cout << "}" << std::endl;

    return 0;
}

You can compile the test program with g++ -std=c++14 -o test test.cc, assuming the file defining the class is in the same directory as test.cc.

ContentLicense: CC BY-SA 4.0


问:
SqlAlchemy(Flask+Postgres) : How to update only a specific attribute of a json field?
I have a table that has one column declared as a json and I need to update records by adding a key-value to the json value.

model

```<code>class User(db.Model):

    __tablename__ = 'users'

    loginId         = db.Column(db.String(128),  nullable=False, primary_key=True)
    _password       = db.Column(db.String(128),  nullable=True)
    views           = db.Column(JSON,         nullable=True)
</code>```

controller

```<code>@mod_event.route('/view', methods=['POST'])
def view():
    try:
        params = request.json
        loginId = params['dream']['loginId']
        users.update().\
            where(users.c.loginId==loginId).\
            values(views=<query>))
</code>```

Assume current value in views is {'1001' : 1}
What should be the query if views has to be updated to -

{'1001' : 2}

{'1001' : 1, '1002' : 1}

if i don't want to query the value first, change and update back.

I'm having a hard time figuring how to do this in a single query, please help, thanks!

答:
if you are using JSONB, you can use the jsonb_set function

```<code>(table
 .update()
 .values(views=func.jsonb_set(table.c.views,
                              '{%s}' % '1002',
                              1))
 .where(...))
</code>```

if you are inserting from other column

```<code>(table
 .update()
 .values(views=func.jsonb_set(table.c.views,
                              '{%s}' % '1002',
                             other_table.c.other_column.cast(String).cast(JSONB)))
 .where(...))
</code>```

Body:
I have a table that has one column declared as a json and I need to update records by adding a key-value to the json value.

model

class User(db.Model):

    __tablename__ = 'users'

    loginId         = db.Column(db.String(128),  nullable=False, primary_key=True)
    _password       = db.Column(db.String(128),  nullable=True)
    views           = db.Column(JSON,         nullable=True)

controller

@mod_event.route('/view', methods=['POST'])
def view():
    try:
        params = request.json
        loginId = params['dream']['loginId']
        users.update().\
            where(users.c.loginId==loginId).\
            values(views=<query>))

Assume current value in views is {'1001' : 1}
What should be the query if views has to be updated to -

{'1001' : 2}

{'1001' : 1, '1002' : 1}

if i don't want to query the value first, change and update back.

I'm having a hard time figuring how to do this in a single query, please help, thanks!

Body:
if you are using JSONB, you can use the jsonb_set function

(table
 .update()
 .values(views=func.jsonb_set(table.c.views,
                              '{%s}' % '1002',
                              1))
 .where(...))

if you are inserting from other column

(table
 .update()
 .values(views=func.jsonb_set(table.c.views,
                              '{%s}' % '1002',
                             other_table.c.other_column.cast(String).cast(JSONB)))
 .where(...))


问:
PHP Constant References
I'm a intermediate C++ programmer and know that you can pass a constant reference as a parameter in order to prevent editing to the actual variable. I was wondering if I could do this in PHP?</p>

答:
Is this what you're talking about:</p>

```<code><?php
    $a = 10;
    function foo($p_a) {
        // passing by value is the default
        $p_a++;
    }
    foo($a);
    echo $a; // prints 10

    $a = 10;
    function bar(&$p_a) {
        //-------^ passing by reference
        $p_a++;
    }
    bar($a);
    echo $a; // prints 11
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Constant References

Body:
Is this what you're talking about:

<?php
    $a = 10;
    function foo($p_a) {
        // passing by value is the default
        $p_a++;
    }
    foo($a);
    echo $a; // prints 10

    $a = 10;
    function bar(&$p_a) {
        //-------^ passing by reference
        $p_a++;
    }
    bar($a);
    echo $a; // prints 11
?>


问:
C - Segmentation fault when using strlen?

I'm getting a segmentation fault with using strlen.

My function:

```<code>void myFunction()
{
    int counter = 0;
    char * userInput;
    bool validInput = true;

    while (1)
    {
        validInput = true;
        printf("\nEnter a word: ");
        scanf("%s", userInput);

        for(counter = 0; counter < strlen(userInput); counter++)
        {
            if (islower(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
            if (isalpha(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
        }

        if (!validInput)
        {
            printf("Please enter a wordcontaining only lower-case letters.\n");
            continue;
        }

        // Do something
        break;
    }
}
</code>```

Is there something wrong with my scanf line? I've never had this sort of issue before with using strlen... so I assume maybe I'm not reading the user's input correctly into 'userInput'.

答:
```<code> char * userInput;
</code>```

The above variable is a pointer , and it is pointing to nowhere (Mean no memory location ) .

It should contain a address to store / retrieve data .

So either you must allocate memory for this variable or use strdup

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

int main(int argc,char *argv[])
{
    char *inputStr; //wrong.
    char inputStrArray[100]; //correct
    char *inputStrPtr = malloc(sizeof(char)*100) ;//OK but dont forget to free the memory after use
    int condition = 1;

    while(condition )
    {
        printf("Please enter a string :");
        //scanf("%s",&inputStr); //wrong
        //printf(inputStr);
        scanf("%s",inputStrArray);
        printf("Ok I got it %s \n",inputStrArray);
        printf("Please enter one more time a string: ");
        scanf("%s",inputStrPtr);
        printf("Now I got it %s \n",inputStrPtr);
        condition = 0;

    }
    free(inputStrPtr);
    inputStrPtr = NULL; //try not to use it anywhere else
    return 0;
}
</code>```

Body:
I'm getting a segmentation fault with using strlen.

My function:

void myFunction()
{
    int counter = 0;
    char * userInput;
    bool validInput = true;

    while (1)
    {
        validInput = true;
        printf("\nEnter a word: ");
        scanf("%s", userInput);

        for(counter = 0; counter < strlen(userInput); counter++)
        {
            if (islower(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
            if (isalpha(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
        }

        if (!validInput)
        {
            printf("Please enter a wordcontaining only lower-case letters.\n");
            continue;
        }

        // Do something
        break;
    }
}

Is there something wrong with my scanf line? I've never had this sort of issue before with using strlen... so I assume maybe I'm not reading the user's input correctly into 'userInput'.

Body:
 char * userInput;

The above variable is a pointer , and it is pointing to nowhere (Mean no memory location ) .

It should contain a address to store / retrieve data .

So either you must allocate memory for this variable or use strdup

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

int main(int argc,char *argv[])
{
    char *inputStr; //wrong.
    char inputStrArray[100]; //correct
    char *inputStrPtr = malloc(sizeof(char)*100) ;//OK but dont forget to free the memory after use
    int condition = 1;

    while(condition )
    {
        printf("Please enter a string :");
        //scanf("%s",&inputStr); //wrong
        //printf(inputStr);
        scanf("%s",inputStrArray);
        printf("Ok I got it %s \n",inputStrArray);
        printf("Please enter one more time a string: ");
        scanf("%s",inputStrPtr);
        printf("Now I got it %s \n",inputStrPtr);
        condition = 0;

    }
    free(inputStrPtr);
    inputStrPtr = NULL; //try not to use it anywhere else
    return 0;
}


问:
which approach is good to for assert
First Approach :  Using try-catch block as well as Asset.Fail too.

I am using this technique to print few messages in loggers before and after execution starts

```<code>[TestMethod]
public void abcButton()
    {
want to print messages so many Logger signs are here

                Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    try
    {
        Assert.IsTrue(LoginPage.CheckBtn());
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("******************************************************");
    }
    catch
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
        Assert.Fail();
    }

}
</code>```

OR
Second Approach : Using if-else condition, involved one more extra var
I just want to see if there is a short approach can get from experts

```<code>[TestMethod]

public void abcButton()
{

    Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    var val = LoginPage.CheckBtn() ;
    if(val)){
        Assert.IsTrue(val);
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("**************************************");
    }
    else
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
    }
}
</code>```

Please let me know if we can handle such scenario in less code

答:
I would write the tests like this:

```<code>[TestMethod]
public void abcButtonTest()
{
    Assert.IsTrue(LoginPage.CheckBtn(), "Checking return value");
}
</code>```

Basic example:

```<code>[TestMethod]
public void TestMethod1()
{
    Assert.IsTrue(false, "Assert failed");
}
</code>```

Title: which approach is good to for assert

Body:
First Approach :  Using try-catch block as well as Asset.Fail too.

I am using this technique to print few messages in loggers before and after execution starts

[TestMethod]
public void abcButton()
    {
want to print messages so many Logger signs are here

                Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    try
    {
        Assert.IsTrue(LoginPage.CheckBtn());
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("******************************************************");
    }
    catch
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
        Assert.Fail();
    }

}

OR
Second Approach : Using if-else condition, involved one more extra var
I just want to see if there is a short approach can get from experts

[TestMethod]

public void abcButton()
{

    Utility.Logger.Write("** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is started  *****");
    Utility.Logger.Write("***********************");
    var val = LoginPage.CheckBtn() ;
    if(val)){
        Assert.IsTrue(val);
        Utility.Logger.Write("********************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Passed  *****");
        Utility.Logger.Write("**************************************");
    }
    else
    {
        Utility.Logger.Write("*************************");
        Utility.Logger.Write("***** " + string.Format(" {0} - {1}", GetType().Name, MethodName) + " Test Case is Failed  *****");
        Utility.Logger.Write("*********************");
    }
}

Please let me know if we can handle such scenario in less code

Body:
I would write the tests like this:

[TestMethod]
public void abcButtonTest()
{
    Assert.IsTrue(LoginPage.CheckBtn(), "Checking return value");
}

Basic example:

[TestMethod]
public void TestMethod1()
{
    Assert.IsTrue(false, "Assert failed");
}


问:
forge-viewer CSS breaks site styles
We have to include CSS file for forge-viewer, but it breaks our own site styles. For example:
- forge CSS contains Alertify styles (they overrides our own custom Alertify styles)
- forge CSS has style for "#close" - this breaks our close buttons
- etc

That can you suggest to solve this critical problem?

答:
CSS collisions can easily be solved by scoping your own css or the viewer one. It is hard to tell you exactly how to fix it as there are many different ways to handle it and without knowing exactly how your css/html is structured I can't tell you the best approach.

If you are using LESS or SASS, it is pretty easy: Easily scope CSS using LESS or SASS. You can scope the viewer styles by adding the viewer div id or class to its styles.

Another approach is to adapt your own css, for example your #close button must be a direct child of a specific class:

```<code>// instead of using:
#close { ...}

// add a parent class:
button#close.my-app { ... }
</code>```

Hope that helps

Title: forge-viewer CSS breaks site styles

Body:
CSS collisions can easily be solved by scoping your own css or the viewer one. It is hard to tell you exactly how to fix it as there are many different ways to handle it and without knowing exactly how your css/html is structured I can't tell you the best approach.

If you are using LESS or SASS, it is pretty easy: Easily scope CSS using LESS or SASS. You can scope the viewer styles by adding the viewer div id or class to its styles.

Another approach is to adapt your own css, for example your #close button must be a direct child of a specific class:

// instead of using:
#close { ...}

// add a parent class:
button#close.my-app { ... }

Hope that helps


问:
How to show the vertical bar on the left side of code block in Visual Studio? (see the figure to get the idea)

Screenshot

Question

I noticed some people can show the left bar as shown above.

How to do that?

答:
There's a very useful free add-on for Visual Studio called CodeRush Express which will do this.

http://community.devexpress.com/blogs/markmiller/archive/2009/06/25/coderush-xpress-for-c-and-visual-basic-2008.aspx  (Scroll to the 'Structural Highlighting' bit to see a screenshot of it).

http://www.codekana.com/ is another add-on that does a similar thing.


问:
Linking error in react native IOS app after using Facebook SDK
I am using RNFirebase.io and trying its starter kit. It does work fine but I started getting these below errors after setting up Facebook SDK.

```<code>ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKLoginKit.framework/FBSDKLoginKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKLoginKit.framework/FBSDKLoginKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKShareKit.framework/FBSDKShareKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKShareKit.framework/FBSDKShareKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKCoreKit.framework/FBSDKCoreKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKCoreKit.framework/FBSDKCoreKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/Bolts.framework/Bolts', framework linker option at /Users/xyz/Documents/FacebookSDK/Bolts.framework/Bolts is not a dylib
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FBSDKAccessToken", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAccessToken.o)
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKAccessToken.o)
  "_OBJC_CLASS_$_FBSDKAppEvents", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppEvents.o)
  "_OBJC_CLASS_$_FBSDKAppInviteContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppInviteDialog.o)
  "_OBJC_CLASS_$_FBSDKAppInviteDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppInviteDialog.o)
  "_OBJC_CLASS_$_FBSDKApplicationDelegate", referenced from:
      objc-class-ref in AppDelegate.o
  "_OBJC_CLASS_$_FBSDKGameRequestContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGameRequestDialog.o)
  "_OBJC_CLASS_$_FBSDKGameRequestDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGameRequestDialog.o)
  "_OBJC_CLASS_$_FBSDKGraphRequest", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
  "_OBJC_CLASS_$_FBSDKGraphRequestConnection", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
  "_OBJC_CLASS_$_FBSDKHashtag", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKLikeControl", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLikeControlManager.o)
  "_OBJC_CLASS_$_FBSDKLoginButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLoginButtonManager.o)
  "_OBJC_CLASS_$_FBSDKLoginManager", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLoginManager.o)
  "_OBJC_CLASS_$_FBSDKMessageDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKMessageDialog.o)
  "_OBJC_CLASS_$_FBSDKSendButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKSendButtonManager.o)
  "_OBJC_CLASS_$_FBSDKSettings", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKInitializer.o)
  "_OBJC_CLASS_$_FBSDKShareAPI", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareAPI.o)
  "_OBJC_CLASS_$_FBSDKShareButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareButtonManager.o)
  "_OBJC_CLASS_$_FBSDKShareDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareDialog.o)
  "_OBJC_CLASS_$_FBSDKShareLinkContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphAction", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphObject", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKSharePhoto", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKSharePhotoContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareVideo", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareVideoContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Solutions that I have already tried -
1. Added '~/Documents/FacebookSDK' in 'framework search Paths' in build settings section.
2. Also checked that libRCTFBSDK.a is added in 'Link Binary with Libraries'

What should I do to fix it?

答:
I had same problem and the solution is very easy, but the solution is not obivious!..

Let's go.

Use this steps iOS Guide

But on step 7.

Install the file ios_setup.js by executing the following command in a command prompt at your project's root folder.

I recommend you enter in Raw iOS install script

on terminal in root ios folder use.

vi ios_setup.js

and paste

/*
 Copyright 2004-present Facebook. All Rights Reserved.

 A node script to help set up FBSDK frameworks for use with https://github.com/facebook/react-native-fbsdk
 after you have already run `rnpm install react-native-fbsdk`.

 Note that you need to create a Facebook App in https://developers.facebook.com/
 and get the Facebook APP ID and Facebook APP Name in order to set up the Info.plist.
 Usage:

 1. add to the 'script' section in package.json of your react-native project the following:
    '"ios:setup": "node ./node_modules/react-native-fbsdk/bin/ios_setup.js"'.
 2. do 'npm run ios:setup <AppID> <AppName>'.
 */

'use strict';

/* eslint-disable no-console */

const AdmZip = require('adm-zip');
const ProgressBar = require('progress');

const fall = require('fastfall')();
const fs = require('fs');
const got = require('got');
const path = require('path');
const plist = require('plist');
const pump = require('pump');
const xcode = require('xcode');

const progressBarPattern = '  downloading [:bar] :rate/bps :percent :etas';
const frameworkDir = 'ios/Frameworks/';
const zipFileName = 'fbsdk.zip';
const zipFilePath = path.join(frameworkDir, zipFileName);
const frameworkUrl = 'https://origincache.facebook.com/developers/resources/?id=facebook-ios-sdk-current.zip';

// Get Facebook App ID and App Name.
if (process.argv.length <= 3) {
  console.log('Usage: ios_setup.js <APPID> <APPNAME>');
  process.exit(-1);
}

const appId = process.argv[2];
const appName = process.argv[3];

function downloadFbSdk (next) {
  try {
    fs.accessSync(frameworkDir, fs.F_OK);
  } catch (e) {
    fs.mkdirSync(frameworkDir);
  }

  var bar = null;
  var download = got.stream(frameworkUrl)
    .on('data', chunk => {
      bar.tick(chunk.length);
    })
    .on('response', res => {
      const len = parseInt(res.headers['content-length'], 10);
      bar = new ProgressBar(progressBarPattern, {
        complete: '=',
        incomplete: ' ',
        width: 20,
        total: len,
      });
    });

  var writeToFile = fs.createWriteStream(zipFilePath);
  pump(download, writeToFile, next);
}

function unzipFramework (next) {
  console.log('Unzipping the framework');
  const zip = new AdmZip(zipFilePath);
  zip.extractAllTo(frameworkDir, true);
  fs.unlinkSync(zipFilePath);
  console.log('Framework Unzipped!');
  next();
}

function correctSearchPaths (next) {
  const rctfbsdkProjectPath = './node_modules/react-native-fbsdk/ios/RCTFBSDK.xcodeproj/project.pbxproj';
  const rctfbsdkProject = xcode.project(rctfbsdkProjectPath);
  rctfbsdkProject.parse(function (err) {
    if (err) {
      return next(err);
    }
    rctfbsdkProject.updateBuildProperty('FRAMEWORK_SEARCH_PATHS', '"$(PROJECT_DIR)/../../../ios/Frameworks"');
    fs.writeFileSync(rctfbsdkProjectPath, rctfbsdkProject.writeSync());
    console.log('Updated RCTFBSDK FRAMEWORK_SEARCH_PATHS');
    next();
  });
}

function updateFBSDKFrameworks (next) {
  const files = fs.readdirSync('./ios/');
  var myProjName = files.filter((f) => { return f.substr(-10) === '.xcodeproj'; })[0];
  const myProjPath = path.join('./ios/', myProjName, '/project.pbxproj');
  myProjName = myProjName.replace('.xcodeproj', '');
  console.log('Updating target:' + myProjName + ' at ' + myProjPath + ' ...');

  const myProj = xcode.project(myProjPath);
  myProj.parse(function (err) {
    if (err) {
      return next(err);
    }
    myProj.pbxCreateGroup('Frameworks', './ios/Frameworks');

    // NOTE: Assumes first target is the app.
    const target = myProj.getFirstTarget().uuid;
    myProj.addFramework('./ios/Frameworks/FBSDKCoreKit.framework', { 'customFramework': true, 'target': target, 'link': true });
    myProj.addFramework('./ios/Frameworks/FBSDKShareKit.framework', { 'customFramework': true, 'target': target, 'link': true });
    myProj.addFramework('./ios/Frameworks/FBSDKLoginKit.framework', { 'customFramework': true, 'target': target, 'link': true });

    // WARNING: this will overwrite any existing search paths
    myProj.updateBuildProperty('FRAMEWORK_SEARCH_PATHS', '"$(PROJECT_DIR)/Frameworks/"');
    fs.writeFileSync(myProjPath, myProj.writeSync());
    console.log('Finished updating ' + myProjPath);

    next(null, files);
  });
}

function updatePlist (files, next) {
  console.dir(files);
  var plistDirPath = '';
  files.map(function (file) {
    return path.join('./ios/', file);
  }).filter(function (file) {
    return fs.statSync(file).isDirectory();
  }).forEach(function (file) {
    if (fs.readdirSync(file).indexOf('Base.lproj') !== -1) {
      plistDirPath = file;
    }
  });
  const plistFilePath = path.join(plistDirPath, '/Info.plist');
  const plistFile = fs.readFileSync(plistFilePath, 'utf8');
  const plistObject = plist.parse(plistFile);
  plistObject.CFBundleURLTypes = [{CFBundleURLSchemes: ['fb' + appId]}];
  plistObject.FacebookAppID = appId;
  plistObject.FacebookDisplayName = appName;
  plistObject.LSApplicationQueriesSchemes = ['fbapi', 'fb-messenger-api', 'fbauth2', 'fbshareextension'];
  plistObject.NSLocationWhenInUseUsageDescription = '';
  fs.writeFileSync(plistFilePath, plist.build(plistObject));
  console.log('Finished updating ' + plistFilePath);
  next();
}

function done (err) {
  if (err) {
    console.error(err);
  } else {
    console.log('DONE!');
  }
}

fall([downloadFbSdk, unzipFramework, correctSearchPaths, updateFBSDKFrameworks, updatePlist], done);```
</div>
</div>
</p>

<p>after this, execute the script</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>node ios_setup.js 'fb_id_here' 'fb_app_name_here'</code>```

follow the site.

Hope to help you and others.

Body:
I am using RNFirebase.io and trying its starter kit. It does work fine but I started getting these below errors after setting up Facebook SDK.

ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKLoginKit.framework/FBSDKLoginKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKLoginKit.framework/FBSDKLoginKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKShareKit.framework/FBSDKShareKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKShareKit.framework/FBSDKShareKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/FBSDKCoreKit.framework/FBSDKCoreKit', framework linker option at /Users/xyz/Documents/FacebookSDK/FBSDKCoreKit.framework/FBSDKCoreKit is not a dylib
ld: warning: Auto-Linking supplied '/Users/xyz/Documents/FacebookSDK/Bolts.framework/Bolts', framework linker option at /Users/xyz/Documents/FacebookSDK/Bolts.framework/Bolts is not a dylib
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FBSDKAccessToken", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAccessToken.o)
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKAccessToken.o)
  "_OBJC_CLASS_$_FBSDKAppEvents", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppEvents.o)
  "_OBJC_CLASS_$_FBSDKAppInviteContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppInviteDialog.o)
  "_OBJC_CLASS_$_FBSDKAppInviteDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKAppInviteDialog.o)
  "_OBJC_CLASS_$_FBSDKApplicationDelegate", referenced from:
      objc-class-ref in AppDelegate.o
  "_OBJC_CLASS_$_FBSDKGameRequestContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGameRequestDialog.o)
  "_OBJC_CLASS_$_FBSDKGameRequestDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGameRequestDialog.o)
  "_OBJC_CLASS_$_FBSDKGraphRequest", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
  "_OBJC_CLASS_$_FBSDKGraphRequestConnection", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKGraphRequestConnectionContainer.o)
  "_OBJC_CLASS_$_FBSDKHashtag", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKLikeControl", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLikeControlManager.o)
  "_OBJC_CLASS_$_FBSDKLoginButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLoginButtonManager.o)
  "_OBJC_CLASS_$_FBSDKLoginManager", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKLoginManager.o)
  "_OBJC_CLASS_$_FBSDKMessageDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKMessageDialog.o)
  "_OBJC_CLASS_$_FBSDKSendButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKSendButtonManager.o)
  "_OBJC_CLASS_$_FBSDKSettings", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKInitializer.o)
  "_OBJC_CLASS_$_FBSDKShareAPI", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareAPI.o)
  "_OBJC_CLASS_$_FBSDKShareButton", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareButtonManager.o)
  "_OBJC_CLASS_$_FBSDKShareDialog", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTFBSDKShareDialog.o)
  "_OBJC_CLASS_$_FBSDKShareLinkContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphAction", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareOpenGraphObject", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKSharePhoto", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKSharePhotoContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareVideo", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
  "_OBJC_CLASS_$_FBSDKShareVideoContent", referenced from:
      objc-class-ref in libRCTFBSDK.a(RCTConvert+FBSDKSharingContent.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Solutions that I have already tried -
1. Added '~/Documents/FacebookSDK' in 'framework search Paths' in build settings section.
2. Also checked that libRCTFBSDK.a is added in 'Link Binary with Libraries'

What should I do to fix it?

Body:
I had same problem and the solution is very easy, but the solution is not obivious!..

Let's go.

Use this steps iOS Guide

But on step 7.

Install the file ios_setup.js by executing the following command in a command prompt at your project's root folder.

I recommend you enter in Raw iOS install script

on terminal in root ios folder use.

vi ios_setup.js

and paste

/*
 Copyright 2004-present Facebook. All Rights Reserved.

 A node script to help set up FBSDK frameworks for use with https://github.com/facebook/react-native-fbsdk
 after you have already run `rnpm install react-native-fbsdk`.

 Note that you need to create a Facebook App in https://developers.facebook.com/
 and get the Facebook APP ID and Facebook APP Name in order to set up the Info.plist.
 Usage:

 1. add to the 'script' section in package.json of your react-native project the following:
    '"ios:setup": "node ./node_modules/react-native-fbsdk/bin/ios_setup.js"'.
 2. do 'npm run ios:setup <AppID> <AppName>'.
 */

'use strict';

/* eslint-disable no-console */

const AdmZip = require('adm-zip');
const ProgressBar = require('progress');

const fall = require('fastfall')();
const fs = require('fs');
const got = require('got');
const path = require('path');
const plist = require('plist');
const pump = require('pump');
const xcode = require('xcode');

const progressBarPattern = '  downloading [:bar] :rate/bps :percent :etas';
const frameworkDir = 'ios/Frameworks/';
const zipFileName = 'fbsdk.zip';
const zipFilePath = path.join(frameworkDir, zipFileName);
const frameworkUrl = 'https://origincache.facebook.com/developers/resources/?id=facebook-ios-sdk-current.zip';

// Get Facebook App ID and App Name.
if (process.argv.length <= 3) {
  console.log('Usage: ios_setup.js <APPID> <APPNAME>');
  process.exit(-1);
}

const appId = process.argv[2];
const appName = process.argv[3];

function downloadFbSdk (next) {
  try {
    fs.accessSync(frameworkDir, fs.F_OK);
  } catch (e) {
    fs.mkdirSync(frameworkDir);
  }

  var bar = null;
  var download = got.stream(frameworkUrl)
    .on('data', chunk => {
      bar.tick(chunk.length);
    })
    .on('response', res => {
      const len = parseInt(res.headers['content-length'], 10);
      bar = new ProgressBar(progressBarPattern, {
        complete: '=',
        incomplete: ' ',
        width: 20,
        total: len,
      });
    });

  var writeToFile = fs.createWriteStream(zipFilePath);
  pump(download, writeToFile, next);
}

function unzipFramework (next) {
  console.log('Unzipping the framework');
  const zip = new AdmZip(zipFilePath);
  zip.extractAllTo(frameworkDir, true);
  fs.unlinkSync(zipFilePath);
  console.log('Framework Unzipped!');
  next();
}

function correctSearchPaths (next) {
  const rctfbsdkProjectPath = './node_modules/react-native-fbsdk/ios/RCTFBSDK.xcodeproj/project.pbxproj';
  const rctfbsdkProject = xcode.project(rctfbsdkProjectPath);
  rctfbsdkProject.parse(function (err) {
    if (err) {
      return next(err);
    }
    rctfbsdkProject.updateBuildProperty('FRAMEWORK_SEARCH_PATHS', '"$(PROJECT_DIR)/../../../ios/Frameworks"');
    fs.writeFileSync(rctfbsdkProjectPath, rctfbsdkProject.writeSync());
    console.log('Updated RCTFBSDK FRAMEWORK_SEARCH_PATHS');
    next();
  });
}

function updateFBSDKFrameworks (next) {
  const files = fs.readdirSync('./ios/');
  var myProjName = files.filter((f) => { return f.substr(-10) === '.xcodeproj'; })[0];
  const myProjPath = path.join('./ios/', myProjName, '/project.pbxproj');
  myProjName = myProjName.replace('.xcodeproj', '');
  console.log('Updating target:' + myProjName + ' at ' + myProjPath + ' ...');

  const myProj = xcode.project(myProjPath);
  myProj.parse(function (err) {
    if (err) {
      return next(err);
    }
    myProj.pbxCreateGroup('Frameworks', './ios/Frameworks');

    // NOTE: Assumes first target is the app.
    const target = myProj.getFirstTarget().uuid;
    myProj.addFramework('./ios/Frameworks/FBSDKCoreKit.framework', { 'customFramework': true, 'target': target, 'link': true });
    myProj.addFramework('./ios/Frameworks/FBSDKShareKit.framework', { 'customFramework': true, 'target': target, 'link': true });
    myProj.addFramework('./ios/Frameworks/FBSDKLoginKit.framework', { 'customFramework': true, 'target': target, 'link': true });

    // WARNING: this will overwrite any existing search paths
    myProj.updateBuildProperty('FRAMEWORK_SEARCH_PATHS', '"$(PROJECT_DIR)/Frameworks/"');
    fs.writeFileSync(myProjPath, myProj.writeSync());
    console.log('Finished updating ' + myProjPath);

    next(null, files);
  });
}

function updatePlist (files, next) {
  console.dir(files);
  var plistDirPath = '';
  files.map(function (file) {
    return path.join('./ios/', file);
  }).filter(function (file) {
    return fs.statSync(file).isDirectory();
  }).forEach(function (file) {
    if (fs.readdirSync(file).indexOf('Base.lproj') !== -1) {
      plistDirPath = file;
    }
  });
  const plistFilePath = path.join(plistDirPath, '/Info.plist');
  const plistFile = fs.readFileSync(plistFilePath, 'utf8');
  const plistObject = plist.parse(plistFile);
  plistObject.CFBundleURLTypes = [{CFBundleURLSchemes: ['fb' + appId]}];
  plistObject.FacebookAppID = appId;
  plistObject.FacebookDisplayName = appName;
  plistObject.LSApplicationQueriesSchemes = ['fbapi', 'fb-messenger-api', 'fbauth2', 'fbshareextension'];
  plistObject.NSLocationWhenInUseUsageDescription = '';
  fs.writeFileSync(plistFilePath, plist.build(plistObject));
  console.log('Finished updating ' + plistFilePath);
  next();
}

function done (err) {
  if (err) {
    console.error(err);
  } else {
    console.log('DONE!');
  }
}

fall([downloadFbSdk, unzipFramework, correctSearchPaths, updateFBSDKFrameworks, updatePlist], done);

after this, execute the script

node ios_setup.js 'fb_id_here' 'fb_app_name_here'

follow the site.

Hope to help you and others.


问:
How to impose order on a dictionary?
I wrote a program and then regretted not making certain objects earlier on OrderedDicts instead of dicts. So to fix this after the fact, the one dictionary was converted into an OrderedDict, but I needed to convert the second dictionary also to become an OrderedDict, but with its keys in the same order as the first.

A dict often displays in a way that looks deceivingly ordered, I almost made a mistake. There's a few questions about this apparent ordering here and here. Anyway, however ordered it may look to the eye, one needs to remember:

```<code>{'a':5,'b':7, 'c':3, 'd':9} == {'d':9,'b':7,'a':5, 'c':3}
>> True
</code>```

So if there are two Python dictionaries:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'c':2, 'b':1, 'd':17, 'a':8}

I can fix the order of a like this:

```<code>c = OrderedDict(a)
print (c)
>> OrderedDict([('a', 5), ('b', 7), ('c', 3), ('d', 9)])
</code>```

How do you impose order on dictionary b, convert it into an OrderedDict with its keys in the same order as a?

In my exact use case, both dictionaries have the same keys, but I would be interested to know how you can do this in general, say instead your two dictionaries were:

```<code>a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'f':3, 'c':2, 'd':17, 'a':8, 'e':9, 'b':1}
</code>```

How do you convert a and b to OrderedDict's but make sure that whatever keys b has in common with a, they end up in the same order as those keys in a

答:
If a and b always have exactly the same keys you could just make sure that both ordered dicts are created based on sorted keys:

```<code>oa = OrderedDict(sorted(a.items(), key=lambda t: t[0]))
ob = OrderedDict(sorted(b.items(), key=lambda t: t[0]))
</code>```

or just force b to have whatever order a got:

```<code>oa = OrderedDict(a)
ob = OrderedDict((k, b[k]) for k in oa)
</code>```

Title: How to impose order on a dictionary?

Body:
I wrote a program and then regretted not making certain objects earlier on OrderedDicts instead of dicts. So to fix this after the fact, the one dictionary was converted into an OrderedDict, but I needed to convert the second dictionary also to become an OrderedDict, but with its keys in the same order as the first.

A dict often displays in a way that looks deceivingly ordered, I almost made a mistake. There's a few questions about this apparent ordering here and here. Anyway, however ordered it may look to the eye, one needs to remember:

{'a':5,'b':7, 'c':3, 'd':9} == {'d':9,'b':7,'a':5, 'c':3}
>> True

So if there are two Python dictionaries:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'c':2, 'b':1, 'd':17, 'a':8}

I can fix the order of a like this:

c = OrderedDict(a)
print (c)
>> OrderedDict([('a', 5), ('b', 7), ('c', 3), ('d', 9)])

How do you impose order on dictionary b, convert it into an OrderedDict with its keys in the same order as a?

In my exact use case, both dictionaries have the same keys, but I would be interested to know how you can do this in general, say instead your two dictionaries were:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'f':3, 'c':2, 'd':17, 'a':8, 'e':9, 'b':1}

How do you convert a and b to OrderedDict's but make sure that whatever keys b has in common with a, they end up in the same order as those keys in a

Body:
If a and b always have exactly the same keys you could just make sure that both ordered dicts are created based on sorted keys:

oa = OrderedDict(sorted(a.items(), key=lambda t: t[0]))
ob = OrderedDict(sorted(b.items(), key=lambda t: t[0]))

or just force b to have whatever order a got:

oa = OrderedDict(a)
ob = OrderedDict((k, b[k]) for k in oa)


问:
How to calculate gradients in Tensorflow c++ API based on a saved graph
I want to calculate gradients using Tensorflow c++ API. I got tf.gradients work in Python API:

```<code>import tensorflow as tf

with tf.Session() as sess:
    a = tf.Variable([[5.0,1.0,2.0]], name='a')
    b = tf.Variable([[9.0,2.0,0.0]], name='b')
    c = tf.matmul(a, tf.transpose(b), name="c")
    deriv = tf.gradients(c,a, name="deriv")  #\partial c/\partial a

    sess.run(tf.global_variables_initializer())
    print(sess.run(deriv))

    #### get the tensor by name ####
    tmp = tf.get_default_graph().get_tensor_by_name("deriv/c_grad/MatMul:0")
    print(sess.run(tmp))

    #### save graph ####
    tf.train.write_graph(sess.graph_def, './', 'graph.pb', as_text=False)
    tf.train.write_graph(sess.graph_def, './', 'graph.pbtxt', as_text=True)

    saver = tf.train.Saver()
    saver.save(sess, "variable", global_step=0)
</code>```

I got the correct answer from both print(sess.run(deriv)) and print(sess.run(tmp)) and got graph.pb generated. Then I tried to use the following c++ code to load the graph and do the gradient calculation in a similar manner as I did in Python.

```<code>#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/cc/framework/ops.h"

void checkStatus(const tensorflow::Status& status) {
  if (!status.ok()) {
    std::cout << status.ToString() << std::endl;
    exit(1);
  }
}

int main(int argc, char** argv) {
    namespace tf = tensorflow;

    tf::Session* session;
    tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
    checkStatus(status);

    tf::GraphDef graph_def;
    status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
    checkStatus(status);

    status = session->Create(graph_def);
    checkStatus(status);

    tf::Input::Initializer xi({1.0,2.0,-6.0});
    tf::Input::Initializer yi({9.0,2.0,0.0});
    std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"a", xi.tensor}, {"b", yi.tensor}};
    std::vector<tf::Tensor> output_tensors;
    status = session->Run(input_tensors, {"deriv/c_grad/MatMul"}, {},  &output_tensors);
    checkStatus(status);

    tf::Tensor output = output_tensors[0];
    auto out = output.vec<float>();
    std::cout << out(0) << " " << out(1) << " " << out(2) <<  std::endl;
    session->Close();
    return 0;
}
</code>```

The compilation ran smoothly but I got a runtime error:

Internal: Output 0 of type double does not match declared output type float for node _recv_b_0 = _Recvclient_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=-3399984051910545345, tensor_name="b", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"

Besides "deriv/c_grad/MatMul", I also tried all other names related to "deriv" in graph.pbtxt but none of them works.

So, my question is how to refer to the node of gradient calculation? It seems Python accepts "deriv/c_grad/MatMul" but c++ does not. I am also wondering whether there is any more general way to do that. As I may differentiate a neural network output instead of a dot product w.r.t. an input tensor in the future, MatMul will not be the last step anymore.

答:
Looks like you didn't initialize your yi input tensor properly.

```<code>Internal: Output 0 of type double does not match declared output type float
for node _recv_b_0 = _Recvclient_terminated=true,
recv_device="/job:localhost/replica:0/task:0/cpu:0",
send_device="/job:localhost/replica:0/task:0/cpu:0",
send_device_incarnation=-3399984051910545345,
tensor_name="b",tensor_type=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/cpu:0"
</code>```

In your sample you initialize yi as doubles:

```<code>tf::Input::Initializer yi({9.0,2.0,0.0});
</code>```

You should probably just try (note added f's):

```<code>tf::Input::Initializer yi({9.0f, 2.0f, 0.0f});
</code>```

Body:
I want to calculate gradients using Tensorflow c++ API. I got tf.gradients work in Python API:

import tensorflow as tf

with tf.Session() as sess:
    a = tf.Variable([[5.0,1.0,2.0]], name='a')
    b = tf.Variable([[9.0,2.0,0.0]], name='b')
    c = tf.matmul(a, tf.transpose(b), name="c")
    deriv = tf.gradients(c,a, name="deriv")  #\partial c/\partial a

    sess.run(tf.global_variables_initializer())
    print(sess.run(deriv))

    #### get the tensor by name ####
    tmp = tf.get_default_graph().get_tensor_by_name("deriv/c_grad/MatMul:0")
    print(sess.run(tmp))

    #### save graph ####
    tf.train.write_graph(sess.graph_def, './', 'graph.pb', as_text=False)
    tf.train.write_graph(sess.graph_def, './', 'graph.pbtxt', as_text=True)

    saver = tf.train.Saver()
    saver.save(sess, "variable", global_step=0)

I got the correct answer from both print(sess.run(deriv)) and print(sess.run(tmp)) and got graph.pb generated. Then I tried to use the following c++ code to load the graph and do the gradient calculation in a similar manner as I did in Python.

#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/cc/framework/ops.h"

void checkStatus(const tensorflow::Status& status) {
  if (!status.ok()) {
    std::cout << status.ToString() << std::endl;
    exit(1);
  }
}

int main(int argc, char** argv) {
    namespace tf = tensorflow;

    tf::Session* session;
    tf::Status status = tf::NewSession(tf::SessionOptions(), &session);
    checkStatus(status);

    tf::GraphDef graph_def;
    status = ReadBinaryProto(tf::Env::Default(), "graph.pb", &graph_def);
    checkStatus(status);

    status = session->Create(graph_def);
    checkStatus(status);

    tf::Input::Initializer xi({1.0,2.0,-6.0});
    tf::Input::Initializer yi({9.0,2.0,0.0});
    std::vector<std::pair<tf::string, tf::Tensor>> input_tensors = {{"a", xi.tensor}, {"b", yi.tensor}};
    std::vector<tf::Tensor> output_tensors;
    status = session->Run(input_tensors, {"deriv/c_grad/MatMul"}, {},  &output_tensors);
    checkStatus(status);

    tf::Tensor output = output_tensors[0];
    auto out = output.vec<float>();
    std::cout << out(0) << " " << out(1) << " " << out(2) <<  std::endl;
    session->Close();
    return 0;
}

The compilation ran smoothly but I got a runtime error:

Internal: Output 0 of type double does not match declared output type float for node _recv_b_0 = _Recvclient_terminated=true, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/cpu:0", send_device_incarnation=-3399984051910545345, tensor_name="b", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"

Besides "deriv/c_grad/MatMul", I also tried all other names related to "deriv" in graph.pbtxt but none of them works.

So, my question is how to refer to the node of gradient calculation? It seems Python accepts "deriv/c_grad/MatMul" but c++ does not. I am also wondering whether there is any more general way to do that. As I may differentiate a neural network output instead of a dot product w.r.t. an input tensor in the future, MatMul will not be the last step anymore.

Body:
Looks like you didn't initialize your yi input tensor properly.

Internal: Output 0 of type double does not match declared output type float
for node _recv_b_0 = _Recvclient_terminated=true,
recv_device="/job:localhost/replica:0/task:0/cpu:0",
send_device="/job:localhost/replica:0/task:0/cpu:0",
send_device_incarnation=-3399984051910545345,
tensor_name="b",tensor_type=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/cpu:0"

In your sample you initialize yi as doubles:

tf::Input::Initializer yi({9.0,2.0,0.0});

You should probably just try (note added f's):

tf::Input::Initializer yi({9.0f, 2.0f, 0.0f});


答:
If you want an OrderedDict with b's items in c's order, iterate over c to produce the ordering:

```<code>d = OrderedDict((k, b[k]) for k in c)
</code>```

However, keep in mind that c's ordering is not guaranteed to be consistent across different executions of the program.

Title: How to impose order on a dictionary?

Body:
If you want an OrderedDict with b's items in c's order, iterate over c to produce the ordering:

d = OrderedDict((k, b[k]) for k in c)

However, keep in mind that c's ordering is not guaranteed to be consistent across different executions of the program.


问:
How can I get one of my foreign key outputs to repeat in a merge transformation in SSIS?
I tried asking this question before and it seemed to have gotten swept under the rug.

First thing first, here are these two pictures to show the table structure and the current output I get in SSIS.

Table Diagram

Current Output

So in table three, there is only one entry. This entry (name) applies to the other foreign keys though. What I want the final output to look like is like my current output, but instead of the NULLS, there should just be ones.

I was able to get this far on my own through researching and learning about the merge transformations but I can't seem to find anything on manipulating the data in the way that I want.

I greatly appreciate any tips or advice you can offer.

EDIT: Since the images can't be seen apparently, I will try and describe them.

The table diagram has four tables, the top one in the waterfall has a primary key formed from the three foreign keys for the three different tables.

Trying to accomplish filling out this table in SSIS, my output has each foreign key id from the first two tables, but only one in the third table. The rest from the third foreign key are all NULLS. I believe this is because there is only one entry in that table for now, but this entry applies to all of the foreign key ids and so it should be repeating.

It should look like this:

```<code>ID1     ID2     ID3
1       1       1
2       2       1
3       3       1
</code>```

But instead, I am only getting nulls in the ID3 field after the first record. How do I make the single id repeat in ID3?

EDIT 2: Some additional screenshots of my data flow and merge transformation as requested.

```<code>[![SSIS Dataflow][3]][3]
</code>```

答:
If Table3 will always have just a single row, the simplest solution would be to use an Execute SQL task to save the T3id to a variable (Control Flow), then use a Derived Column task (Data Flow) to add the variable as a new column.

If that won't work for you (or your data), you can take a look here to see how to fudge the Merge Join task to do what you want.

Body:
I tried asking this question before and it seemed to have gotten swept under the rug.

First thing first, here are these two pictures to show the table structure and the current output I get in SSIS.

Table Diagram

Current Output

So in table three, there is only one entry. This entry (name) applies to the other foreign keys though. What I want the final output to look like is like my current output, but instead of the NULLS, there should just be ones.

I was able to get this far on my own through researching and learning about the merge transformations but I can't seem to find anything on manipulating the data in the way that I want.

I greatly appreciate any tips or advice you can offer.

EDIT: Since the images can't be seen apparently, I will try and describe them.

The table diagram has four tables, the top one in the waterfall has a primary key formed from the three foreign keys for the three different tables.

Trying to accomplish filling out this table in SSIS, my output has each foreign key id from the first two tables, but only one in the third table. The rest from the third foreign key are all NULLS. I believe this is because there is only one entry in that table for now, but this entry applies to all of the foreign key ids and so it should be repeating.

It should look like this:

ID1     ID2     ID3
1       1       1
2       2       1
3       3       1

But instead, I am only getting nulls in the ID3 field after the first record. How do I make the single id repeat in ID3?

EDIT 2: Some additional screenshots of my data flow and merge transformation as requested.

[![SSIS Dataflow][3]][3]


答:
Your existing dictionary makes no promises about the ordering.  Let's make it an ordered dictionary first:

```<code>ordered_a = OrderedDict(a.items())
</code>```

Now, suppose you have the other dictionary b, and you wish its keys to be in the same order as ordered_a, if they exist, then:

```<code>ordered_b = OrderedDict(
    [(k, b[k]) for k in itertools.chain(ordered_a, b.keys() - a.keys())
     if k in b])
</code>```

Here we add the items from b into ordered_b in the same order as ordered_a, where they exist, and then add the remaining items of b in an arbitrary order.  This will handle the possibilities that:

a contains keys that b does not have; or

b contains keys that a does not have.

Title: How to impose order on a dictionary?

Body:
Your existing dictionary makes no promises about the ordering.  Let's make it an ordered dictionary first:

ordered_a = OrderedDict(a.items())

Now, suppose you have the other dictionary b, and you wish its keys to be in the same order as ordered_a, if they exist, then:

ordered_b = OrderedDict(
    [(k, b[k]) for k in itertools.chain(ordered_a, b.keys() - a.keys())
     if k in b])

Here we add the items from b into ordered_b in the same order as ordered_a, where they exist, and then add the remaining items of b in an arbitrary order.  This will handle the possibilities that:

a contains keys that b does not have; or

b contains keys that a does not have.


问:
How to get both REPL/arrow key functionality and Unicode characters working with Python3 under Git Bash/WinPTY
Windows 7, restricted user account running
Git git version 2.14.1.windows.1

MINGW/MSYS MINGW64_NT-6.1 REDACTED 2.8.2(0.313/5/3) 2017-07-12 15:35 x86_64 Msys

Python Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32

locale has been set:

```<code>$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=
</code>```

Python IO Encoding env variable has been set

```<code>$ env | grep "PYTHON"
PYTHONIOENCODING=utf-8
</code>```

Now for the 'tests':

```<code>$ /c/Python34/python.exe -i
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'utf-8'
>>> print('\u2660')
♠
>>>
</code>```

Unicode works but the arrow key functionality has been lost in the REPL.  So instead, execute using WinPTY

```<code>$ winpty /c/Python34/python.exe -i
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'utf-8'
>>> print('\u2660')
ΓÖá
>>>
</code>```

Now I can navigate the history in the REPL, but Unicode is wonky.

So seemingly I can either be able to use the arrow keys in the REPL or proper unicode encoding, but not both.  Anyone else have this issue or did I miss something here that will make this all work?

Note: I am restricted to this environment; I cannot readily install/update/modify apps at will.

答: In the WinPTY case, the console is still using cp437 (default US OEM Windows encoding) but you've force Python to output UTF-8 via PYTHONIOENCODING. Switch to Python 3.6 since that version now uses the Windows Unicode console APIs to output Unicode and shouldn't have issues with encodings.</p>

Body:
Windows 7, restricted user account running
Git git version 2.14.1.windows.1

MINGW/MSYS MINGW64_NT-6.1 REDACTED 2.8.2(0.313/5/3) 2017-07-12 15:35 x86_64 Msys

Python Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32

locale has been set:

$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=

Python IO Encoding env variable has been set

$ env | grep "PYTHON"
PYTHONIOENCODING=utf-8

Now for the 'tests':

$ /c/Python34/python.exe -i
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'utf-8'
>>> print('\u2660')
♠
>>>

Unicode works but the arrow key functionality has been lost in the REPL.  So instead, execute using WinPTY

$ winpty /c/Python34/python.exe -i
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'utf-8'
>>> print('\u2660')
ΓÖá
>>>

Now I can navigate the history in the REPL, but Unicode is wonky.

So seemingly I can either be able to use the arrow keys in the REPL or proper unicode encoding, but not both.  Anyone else have this issue or did I miss something here that will make this all work?

Note: I am restricted to this environment; I cannot readily install/update/modify apps at will.


问:
Proper get_post blog php - safest way
What is the proper, safe way to cull blog posts? I'm just being cautious before I code it on my ecommerce site.

On my personal site I've found this to work just fine.

```<code><?php
$args = array(
  'numberposts' => 12,
  'offset'      => 1
);
$latest_post = get_posts( $args ); ?>
<?php foreach( $latest_post as $post ) : setup_postdata( $post ); ?>

<div class="col-sm-12 col-md-6 col-lg-4 waypoint_card">
    <a href="<?php echo esc_url( get_permalink() ); ?>">
        <div class="waypoint_img" style="background-image:url('<?php echo get_the_post_thumbnail_url(); ?>');"></div>
        <div class="waypoint_content">
            <h3><?php echo the_title(); ?></h3>
        </div>
    </a>
</div>

<?php endforeach; ?>
<?php wp_reset_query(); ?>
</code>```

I end up doubling this $args array so I can separate the first post from the rest (offset 1). Is there a better way to do this?

答: It's legit,  if your purpose is to get the first 12 posts minus the first. </p>

Title: Proper get_post blog php - safest way

Body:
What is the proper, safe way to cull blog posts? I'm just being cautious before I code it on my ecommerce site.

On my personal site I've found this to work just fine.

<?php
$args = array(
  'numberposts' => 12,
  'offset'      => 1
);
$latest_post = get_posts( $args ); ?>
<?php foreach( $latest_post as $post ) : setup_postdata( $post ); ?>

    <a href="<?php echo esc_url( get_permalink() ); ?>">
        <div class="waypoint_img" style="background-image:url('<?php echo get_the_post_thumbnail_url(); ?>');">

<?php echo the_title(); ?>

<?php endforeach; ?>
<?php wp_reset_query(); ?>

I end up doubling this $args array so I can separate the first post from the rest (offset 1). Is there a better way to do this?


问:
Finding equivalent gaussian filter mask in frequency domain for given mask in space domain
So far I've implemented a gaussian blur filter entirely in the space domain, making use of the separability of the gaussian, that is, applying a 1D gaussian kernel along the rows and then along the columns of an image. That worked fine.

Now, given only with the size N of the NxN convolution matrix of the space domain, I want to achieve the exact same blurred image over the frequency domain. That means that I'll load the image into a matrix (numpy, I'm using python), apply the FFT on it (then I have G(x,y)), and then I have to have also a filter H(u,v) in the frequency domain that also resembles the shape of some 2d gaussian, with its center value being 1.0 and then having values falling off to 0 the further away from the center I am. I do then the multiplication in frequency domain (before I have to consider to do a center-shift of H) and then apply the iFFT.

The trouble I have is to find the exact formula (i.e. to find sigma, the std-deviation) that will result in the corresponding H(u,v). From the space domain, if I have been given a mask-size N, I know that the std-dev sigma can be approximated as sigma=(maskSize-1)/2/2.575, e.g. for a mask size N=15 I get std-dev=2.71845 for e^-(x²/2sigma²), just considering 1D cases for now.

But how do I get sigma for the frequency domain?

Funny thing is btw that in theory I know how to get sigma, using Mathematica, but the result is pure bogus, as I can demonstrate here:

```<code>gauss1d[x_, sigma_] := Exp[-(x^2)/(2 sigma^2)]
Simplify[FourierTransform[gauss1d[x, sigma], x, omega], sigma > 0]
</code>```

The result is E^(-(1/2) omega^2 sigma^2) * sigma

This is bogus because it turns, in the exponent of the E function, the 1/sigma² into a sigma². Consequently, if you draw this, you will see that the standard deviation has become a lot smaller, since the H(u,v)-gaussian is a lot "thinner". However, it should actually be a lot wider in the frequency domain than in the space domain!! It doesn't make any sense...

答:
The Fourier Transform of the a Gaussian is a Gaussian as you can see from

http://en.wikipedia.org/wiki/Fourier_transform

But note that the std. dev. DOES invert!!!!

You say that is bogus BUT it is not. The frequency domain is, in some sense, the inversion of the time domain.

freq = 1/time

The standard deviation given is in time, when you transform it is still in time(the constant does not get transformed).

Suppose your you found the time version of the Gaussian using some s in terms of time. You transform the data into freq space. You can use that s and it will behave exactly the way it is suppose to. e.g., if you have a small s then it will cause the freq std. dev. in the frequency version to be large.

Again, this is because frequency is the inversion of time(again, in a sense).

Suppose your Gaussian has very small std. dev. Then it approximates a dirac delta function. We know this because gets transformed into a sinusoid in the freq domain. i.e., something that spans the whole frequency domain. (i.e., has infinite std. dev.(if it were a Gaussian).

Think of it like this: You are wanting to smooth in the frequency domain. Smooth what? High frequency components, right? By convoluting with a gaussian you are smoothing near by data. If the std. dev. is small you are keeping higher frequencies. In the frequency domain this means you are KEEPING more frequencies. But the conv is a multiplication in frequency domain. If we mulitplied by a thin gaussian in the frequency domain we would be left with a small group of frequencies.

G(t)*f(t)
G[w]*f[w]

The first, a convolution. For a smooth filter we want G(t) to be "large"(std. dev. to be large). This means in we want less of the high frequency components(a sort of low pass filter). In the freq. domain we are multiplying by G[w]. This means that G[w] must be thin(and centered around the origin) so that we block out the highs.

I think basically you are not realizing that in the time domain we have a convolution and the frequency domain it is a multiplication. G cannot be the same in both. If G is thin in the time domain and thin in the frequency domain they will not result in the same effect. G thin in the convolution gives almost no effect but G thin in the freq. domain almost completely removes all the frequencies(just the very low are kept).

Body:
So far I've implemented a gaussian blur filter entirely in the space domain, making use of the separability of the gaussian, that is, applying a 1D gaussian kernel along the rows and then along the columns of an image. That worked fine.

Now, given only with the size N of the NxN convolution matrix of the space domain, I want to achieve the exact same blurred image over the frequency domain. That means that I'll load the image into a matrix (numpy, I'm using python), apply the FFT on it (then I have G(x,y)), and then I have to have also a filter H(u,v) in the frequency domain that also resembles the shape of some 2d gaussian, with its center value being 1.0 and then having values falling off to 0 the further away from the center I am. I do then the multiplication in frequency domain (before I have to consider to do a center-shift of H) and then apply the iFFT.

The trouble I have is to find the exact formula (i.e. to find sigma, the std-deviation) that will result in the corresponding H(u,v). From the space domain, if I have been given a mask-size N, I know that the std-dev sigma can be approximated as sigma=(maskSize-1)/2/2.575, e.g. for a mask size N=15 I get std-dev=2.71845 for e^-(x²/2sigma²), just considering 1D cases for now.

But how do I get sigma for the frequency domain?

Funny thing is btw that in theory I know how to get sigma, using Mathematica, but the result is pure bogus, as I can demonstrate here:

gauss1d[x_, sigma_] := Exp[-(x^2)/(2 sigma^2)]
Simplify[FourierTransform[gauss1d[x, sigma], x, omega], sigma > 0]

The result is E^(-(1/2) omega^2 sigma^2) * sigma

This is bogus because it turns, in the exponent of the E function, the 1/sigma² into a sigma². Consequently, if you draw this, you will see that the standard deviation has become a lot smaller, since the H(u,v)-gaussian is a lot "thinner". However, it should actually be a lot wider in the frequency domain than in the space domain!! It doesn't make any sense...


问:
Having issues with a program that skips the If Else part of the code
I am creating a text-based game and, so far, I have gotten the if and the else statements to work. However, the else if does not work. I've gone through several sites and several pages and even talked with a  fellow coder. I've done what I can, such as replacing == with "?".equals(Call#)) then changing to Call#.equals("?"). I had the else if as a nested if but that also failed.

```<code>public static void FirstRoom(){
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call = console.next();
    if (Call.equals("Inspect")) {
        System.out.println("\nYou can only see darkness");
        System.out.println("\n ----- \n");
    } else if(Call.equals("Light Lantern")){
        System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
    System.out.println("\n ----- \n");
    }else{
        System.out.println("\nWhat do you mean?");
        System.out.println("\n ----- \n");
    FirstRoom();
   }
   String Call2 = console.next();
   if(Call.equals("Inspect")) {
       System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
       System.out.println("\n ----- \n");
   }
}
</code>```

When I type in Light Lantern, I expect it to say You pull the lighter from your pocket and, turning the knob, raise the lantern's wick and light it. Instead, it skips to the second statement (supposed to also wait for you to input for the second) and says You see a large sword to your right and a bag to your left. There is a door in front of you and a door behind.

Inspect

You can only see
darkness

Light Lantern
You see a large sword to your
right and a bag to your left.
There is a door in front
 of you and a door behind.

答:
You are stopping to take input at String Call2 = console.next(); before checking if Call is equal to "Inspect".  You should be checking Call2.

This would be my suggestion to reworking that method:

```<code>public static void FirstRoom() {
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call;
    boolean exitRoom = false;
    boolean lantern = false;
    while(!exitRoom) {
        Call = console.nextLine();
        if(Call.equals("Inspect") && !lantern) {
            System.out.println("\nYou can only see darkness");
            System.out.println("\n ----- \n");
        } else if(Call.equals("Light Lantern")) {
            System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
            System.out.println("\n ----- \n");
            lantern = true;
        } else if(Call.equals("Inspect") && lantern) {
            System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
            System.out.println("\n ----- \n");
        } else if(Call.equals("Leave")) {
            System.out.println("You leave the room");
            System.out.println("\n ----- \n");
            exitRoom = true;
        } else {
            System.out.println("\nWhat do you mean?");
            System.out.println("\n ----- \n");
            FirstRoom();
        }
    }
}
</code>```

When a command to leave the room is requested, the while loop ends.

Body:
I am creating a text-based game and, so far, I have gotten the if and the else statements to work. However, the else if does not work. I've gone through several sites and several pages and even talked with a  fellow coder. I've done what I can, such as replacing == with "?".equals(Call#)) then changing to Call#.equals("?"). I had the else if as a nested if but that also failed.

public static void FirstRoom(){
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call = console.next();
    if (Call.equals("Inspect")) {
        System.out.println("\nYou can only see darkness");
        System.out.println("\n ----- \n");
    } else if(Call.equals("Light Lantern")){
        System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
    System.out.println("\n ----- \n");
    }else{
        System.out.println("\nWhat do you mean?");
        System.out.println("\n ----- \n");
    FirstRoom();
   }
   String Call2 = console.next();
   if(Call.equals("Inspect")) {
       System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
       System.out.println("\n ----- \n");
   }
}

When I type in Light Lantern, I expect it to say You pull the lighter from your pocket and, turning the knob, raise the lantern's wick and light it. Instead, it skips to the second statement (supposed to also wait for you to input for the second) and says You see a large sword to your right and a bag to your left. There is a door in front of you and a door behind.

Inspect

You can only see
darkness

Light Lantern
You see a large sword to your
right and a bag to your left.
There is a door in front
 of you and a door behind.

Body:
You are stopping to take input at String Call2 = console.next(); before checking if Call is equal to "Inspect".  You should be checking Call2.

This would be my suggestion to reworking that method:

public static void FirstRoom() {
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call;
    boolean exitRoom = false;
    boolean lantern = false;
    while(!exitRoom) {
        Call = console.nextLine();
        if(Call.equals("Inspect") && !lantern) {
            System.out.println("\nYou can only see darkness");
            System.out.println("\n ----- \n");
        } else if(Call.equals("Light Lantern")) {
            System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
            System.out.println("\n ----- \n");
            lantern = true;
        } else if(Call.equals("Inspect") && lantern) {
            System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
            System.out.println("\n ----- \n");
        } else if(Call.equals("Leave")) {
            System.out.println("You leave the room");
            System.out.println("\n ----- \n");
            exitRoom = true;
        } else {
            System.out.println("\nWhat do you mean?");
            System.out.println("\n ----- \n");
            FirstRoom();
        }
    }
}

When a command to leave the room is requested, the while loop ends.


问:
Form Submit - Open New Tab at same time
I have a contact form on my website. I'm using a free bootstrap template that I've been editing and configuring because I don't know much about coding.

I want a new tab to open and go to a specific website when the user hits the submit button (so both submit the form, and take them to a new web page). How can I do that?

```<code><form name="sentMessage" id="contactForm" target="blank" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">
                                <p class="help-block text-danger"></p>
                            </div>
                            <div class="form-group">
                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>
                        <div class="clearfix"></div>
                        <br><br>
                        <div class="col-lg-12 text-center">
                            <div id="success"></div>
                            <button type="submit" class="btn btn-xl">Send Message</button>
                        </div>
                    </div>
                </form>
</code>```

答:
You just need to add in the

```<code>action="/newpage.php" method="post"
</code>```

so in your example, it would look like:

```<code><form name="sentMessage" id="contactForm" action="/newpage.php" method="post"  novalidate>
</code>```

Hope that helps... Note the /newpage is the page (wherever it is) which will process your POST request.

Title: Form Submit - Open New Tab at same time

Body:
I have a contact form on my website. I'm using a free bootstrap template that I've been editing and configuring because I don't know much about coding.

I want a new tab to open and go to a specific website when the user hits the submit button (so both submit the form, and take them to a new web page). How can I do that?

<form name="sentMessage" id="contactForm" target="blank" novalidate>

                                <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                            <button type="submit" class="btn btn-xl">Send Message</button>

                </form>

Body:
You just need to add in the

action="/newpage.php" method="post"

so in your example, it would look like:

<form name="sentMessage" id="contactForm" action="/newpage.php" method="post"  novalidate>

Hope that helps... Note the /newpage is the page (wherever it is) which will process your POST request.


问:
How to perform element-wise multiplication of two vectors having different dimensions
I have two vectors A & B having dimensions (1, 100) & (784, 100) respectively. I thought A would be broadcast along the raw to the same dimension as B, but got error that "Dimensions must be equal". Can you please explain why?</p>

答:
Broadcasting of matrices with the same rank (i.e. 2) seems to work as it says on the tin:

import tensorflow as tf
tf.__version__
# 1.3.0

A = tf.constant([[1, 2], [3, 4], [5, 6]], dtype=tf.float32)
B = tf.constant([[1, -1]], dtype=tf.float32)

sess = tf.Session()
sess.run(A * B)
# array([[ 1., -2.],
#        [ 3., -4.],
#        [ 5., -6.]], dtype=float32)

sess.run(tf.multiply(A, B))
# array([[ 1., -2.],
#        [ 3., -4.],
#        [ 5., -6.]], dtype=float32)
```


问:
PHP access values in multi dimensional array
I have an array called $ticket_quantities coming from an API which when I var dump comes out as

```<code>array(1) {
    [4128] => array(1) {
        [168] => array(2) {
            [7] => int(4)[8] => int(2)
        }
    }
}
</code>```

How can I access the [7] => int(4) value and [8] => int(2) value?

答:
It should be</p>

```<code>$ticket_quantities[4128][168][7]
$ticket_quantities[4128][168][8]
</code>```

Body:
I have an array called $ticket_quantities coming from an API which when I var dump comes out as

array(1) {
    [4128] => array(1) {
        [168] => array(2) {
            [7] => int(4)[8] => int(2)
        }
    }
}

How can I access the [7] => int(4) value and [8] => int(2) value?

Body:
It should be

$ticket_quantities[4128][168][7]
$ticket_quantities[4128][168][8]


问:
IN clause in pony orm query
How can I use subquery in pony orm for query like

```<code>SELECT *
FROM  child_table
WHERE child_table.masterno IN (SELECT masterno
                    FROM   mastertable
                    WHERE  mastertable.recorddate > SYSDATE -1)
</code>```

In another word. I wanted to do somthing like

```<code>master_result = target_model.mastertable.select()\
                .filter(lambda mt: mt.recorddate > DATE)

output = target_model.child_table.select()\
           .filter(lambda ct: ct.masterno in master_result)
</code>```

I got error

```<code>pony.orm.sqltranslation.IncomparableTypesError: Incomparable types 'int' and 'mastertable' in expression: ct.masterno in master_result
</code>```

where master_result is

```<code>print(type(master_result))
</code>```

<'pony.orm.core.QueryResult'>

答:
Yes, by Pony API you will get QueryResult object from select() and filter() functions. If you want to have entities from that query you could change your line
master_result = target_model.mastertable.select()\
                .filter(lambda mt: mt.recorddate > DATE)
 to

master_result = target_model.mastertable.select()\
                .filter(lambda mt: mt.recorddate > DATE)[:] <- this will fetch objects

Another way you can cast QueryResult to list like results = list(master_result). Also you can iterate over QueryResult object and you will get Entity objects as item.

for mastertable in mastertable.select():
    mastertable.recordtable = *smth*

Title: IN clause in pony orm query

Body:
How can I use subquery in pony orm for query like

SELECT *
FROM  child_table
WHERE child_table.masterno IN (SELECT masterno
                    FROM   mastertable
                    WHERE  mastertable.recorddate > SYSDATE -1)

In another word. I wanted to do somthing like

master_result = target_model.mastertable.select()\
                .filter(lambda mt: mt.recorddate > DATE)

output = target_model.child_table.select()\
           .filter(lambda ct: ct.masterno in master_result)

I got error

pony.orm.sqltranslation.IncomparableTypesError: Incomparable types 'int' and 'mastertable' in expression: ct.masterno in master_result

where master_result is

print(type(master_result))

<'pony.orm.core.QueryResult'>


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答:
This regular expression matches sequences, that consist of one or more words of letters, that are concatenated by dashes.</p>

```<code>^[a-zA-Z]+(?:-[a-zA-Z]+)*$
</code>```

OwnerDisplayName: new-to-rails

Title: a simple regexp validator

Body:
This regular expression matches sequences, that consist of one or more words of letters, that are concatenated by dashes.

^[a-zA-Z]+(?:-[a-zA-Z]+)*$

OwnerDisplayName: Gumbo

LastEditorDisplayName: Gumbo