问:
Get authorization from Lumen and header from Laravel
In project, all API calls are from Lumen. Front is developed in Laravel. We are calling Lumen APIs using Guzzle http client guzzleHttp.

Now, I need to set header Authorization for all API calls so I'm sending token in header from Laravel but in Lumen I can't get token in Lumen request header.

Below is the example code.

Laravel controller code:

```<code>public function get_category(){

    $accessToken = 'kjdhfdkjfhdkjfhfjkdf9875443213456';

    $response = \Guzzle::request("GET","example.com", "categories",['headers' => [
        'Authorization' => $accessToken
    ]]);

    $category_all = json_decode($response->getBody()->getContents(),true);

    return $category_all;

}
</code>```

Lumen middleware code:

```<code> public function handle($request, Closure $next)
{

   dd($request);

}
</code>```

In Lumen request I can't get token in request header.

答:
If you're using Apache, by default it remove the Authorization header.
You've to add this settings in the .htaccess project's file or in the apache .conf  file (usually in /etc/apache2/sites-available/):

```<code>RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Header set Access-Control-Allow-Headers "Authorization"
</code>```

Body:
In project, all API calls are from Lumen. Front is developed in Laravel. We are calling Lumen APIs using Guzzle http client guzzleHttp.

Now, I need to set header Authorization for all API calls so I'm sending token in header from Laravel but in Lumen I can't get token in Lumen request header.

Below is the example code.

Laravel controller code:

public function get_category(){

    $accessToken = 'kjdhfdkjfhdkjfhfjkdf9875443213456';

    $response = \Guzzle::request("GET","example.com", "categories",['headers' => [
        'Authorization' => $accessToken
    ]]);

    $category_all = json_decode($response->getBody()->getContents(),true);

    return $category_all;

}

Lumen middleware code:

 public function handle($request, Closure $next)
{

   dd($request);

}

In Lumen request I can't get token in request header.

Body:
If you're using Apache, by default it remove the Authorization header.
You've to add this settings in the .htaccess project's file or in the apache .conf  file (usually in /etc/apache2/sites-available/):

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

Header set Access-Control-Allow-Headers "Authorization"


来源: stackexchange

问:
Linear regression and autograd
Let $F \in \mathbb{R}^{S \times F}$ be a matrix of features, I want to classify them using logistic regression with autograd [1]. The code I am using is similar to the one in the following example [2].

The only thing I want to change is that I have an additional weight matrix $W$ in $\mathbb{R}^{F \times L}$ that I want to apply to each feature. So each feature is multiplied with $W$ and then feed into the logistic regression.

Is it somehow possible to train $W$ and the weights of the logistic regression simultaneously using autograd?

I have tried the following code, unfortunately the weights stay at value 0.

```<code>import autograd.numpy as np
from autograd import grad

    global inputs

    def sigmoid(x):
        return 0.5 * (np.tanh(x) + 1)

    def logistic_predictions(weights, inputs):
        # Outputs probability of a label being true according to logistic model.
        return sigmoid(np.dot(inputs, weights))

    def training_loss(weights):
        global inputs
        # Training loss is the negative log-likelihood of the training labels.

        feature_weights = weights[3:]
        feature_weights = np.reshape(feature_weights, (3, 3))

        inputs = np.dot(inputs, feature_weights)

        preds = logistic_predictions(weights[0:3], inputs)
        label_probabilities = preds * targets + (1 - preds) * (1 - targets)

        return -np.sum(np.log(label_probabilities))

    # Build a toy dataset.
    inputs = np.array([[0.52, 1.12, 0.77],
                       [0.88, -1.08, 0.15],
                       [0.52, 0.06, -1.30],
                       [0.74, -2.49, 1.39]])

    targets = np.array([True, True, False, True])

    # Define a function that returns gradients of training loss using autograd.
    training_gradient_fun = grad(training_loss)

    # Optimize weights using gradient descent.
    weights = np.zeros([3 + 3 * 3])
    print "Initial loss:", training_loss(weights)
    for i in xrange(100):
        print(i)
        print(weights)
        weights -= training_gradient_fun(weights) * 0.01

    print  "Trained loss:", training_loss(weights)
</code>```

[1] https://github.com/HIPS/autograd

[2] https://github.com/HIPS/autograd/blob/master/examples/logistic_regression.py

答:
Typical practice is to concatenate all "vectorized" parameters into the decision variables vector.

If you update logistic_predictions to include the W matrix, via something like

```<code>def logistic_predictions(weights_and_W, inputs):
    '''
    Here, :arg weights_and_W: is an array of the form [weights W.ravel()]
    '''
    # Outputs probability of a label being true according to logistic model.
    weights = weights_and_W[:inputs.shape[1]]
    W_raveled = weights_and_W[inputs.shape[1]:]
    n_W = len(W_raveled)
    W = W_raveled.reshape(inputs.shape[1], n_W/inputs.shape[1])

    return sigmoid(np.dot(np.dot(inputs, W), weights))
</code>```

then simply change traning_loss to (from the original source example)

```<code>def training_loss(weights_and_W):
    # Training loss is the negative log-likelihood of the training labels.
    preds = logistic_predictions(weights_and_W, inputs)
    label_probabilities = preds * targets + (1 - preds) * (1 - targets)
    return -np.sum(np.log(label_probabilities))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Linear regression and autograd

Body:
Let $F \in \mathbb{R}^{S \times F}$ be a matrix of features, I want to classify them using logistic regression with autograd [1]. The code I am using is similar to the one in the following example [2].

The only thing I want to change is that I have an additional weight matrix $W$ in $\mathbb{R}^{F \times L}$ that I want to apply to each feature. So each feature is multiplied with $W$ and then feed into the logistic regression.

Is it somehow possible to train $W$ and the weights of the logistic regression simultaneously using autograd?

I have tried the following code, unfortunately the weights stay at value 0.

import autograd.numpy as np
from autograd import grad

    global inputs

    def sigmoid(x):
        return 0.5 * (np.tanh(x) + 1)

    def logistic_predictions(weights, inputs):
        # Outputs probability of a label being true according to logistic model.
        return sigmoid(np.dot(inputs, weights))

    def training_loss(weights):
        global inputs
        # Training loss is the negative log-likelihood of the training labels.

        feature_weights = weights[3:]
        feature_weights = np.reshape(feature_weights, (3, 3))

        inputs = np.dot(inputs, feature_weights)

        preds = logistic_predictions(weights[0:3], inputs)
        label_probabilities = preds * targets + (1 - preds) * (1 - targets)

        return -np.sum(np.log(label_probabilities))

    # Build a toy dataset.
    inputs = np.array([[0.52, 1.12, 0.77],
                       [0.88, -1.08, 0.15],
                       [0.52, 0.06, -1.30],
                       [0.74, -2.49, 1.39]])

    targets = np.array([True, True, False, True])

    # Define a function that returns gradients of training loss using autograd.
    training_gradient_fun = grad(training_loss)

    # Optimize weights using gradient descent.
    weights = np.zeros([3 + 3 * 3])
    print "Initial loss:", training_loss(weights)
    for i in xrange(100):
        print(i)
        print(weights)
        weights -= training_gradient_fun(weights) * 0.01

    print  "Trained loss:", training_loss(weights)

[1] https://github.com/HIPS/autograd

[2] https://github.com/HIPS/autograd/blob/master/examples/logistic_regression.py

Body:
Typical practice is to concatenate all "vectorized" parameters into the decision variables vector.

If you update logistic_predictions to include the W matrix, via something like

def logistic_predictions(weights_and_W, inputs):
    '''
    Here, :arg weights_and_W: is an array of the form [weights W.ravel()]
    '''
    # Outputs probability of a label being true according to logistic model.
    weights = weights_and_W[:inputs.shape[1]]
    W_raveled = weights_and_W[inputs.shape[1]:]
    n_W = len(W_raveled)
    W = W_raveled.reshape(inputs.shape[1], n_W/inputs.shape[1])

    return sigmoid(np.dot(np.dot(inputs, W), weights))

then simply change traning_loss to (from the original source example)

def training_loss(weights_and_W):
    # Training loss is the negative log-likelihood of the training labels.
    preds = logistic_predictions(weights_and_W, inputs)
    label_probabilities = preds * targets + (1 - preds) * (1 - targets)
    return -np.sum(np.log(label_probabilities))


问:
Nested functions in scheme
I'm new to scheme language and trying to execute this code that calculating the n'th Fibonacci series using an internal function.

for some reason it doesn't  work for me and i would like to get some help.
Thank you.

```<code>    (define fibo (lambda (n)
      (define (helperFunction n n1 a_n)
        (begin
        (display a_n)
        (newline)
        (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1))))
       (helperFunction n 1 1)))
</code>```

答:
First off, why do you use the long version in fibo and the short version in helperFunction? eg.

(define long-version (lambda (arg) arg))
(define (short-version arg) arg)
```

<p>These are the same. Books often use the long version to point out that functions are values and the names are bindings just as with variables, but its practical to use the short version when you already have started with it. </p>

<p>a <code>begin</code> that wraps the contents of a function is unnecessary since all functions have explicit <code>begin</code>. </p>

<p>An <code>if</code> where you only have a test and a then clause will return a implementation chosen value when the test is false. I tend to use the symbol <code>undefined</code> to not get any surprises on what the undefined value is.</p>

<p>You need to indent your code properly. I use DrRacket and press CTRL+I. With these I get your code like this:</p>

<pre class="lang-scm prettyprint-override"><code>(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        'undefined))
  (helperFunction n 1 1))
</code>```

So lets try this:

(fibo 1) ; ==> undefined
```

<p>That makes sense from looking at the code. It's hardly correct but it does what it has been instructed to do. What if it was <code>2</code>?</p>

<pre class="lang-scm prettyprint-override"><code>(fibo 2) ; ==
(helperFunction 1 2 1) ==> undefined
</code>```

I think your problem is that instead of undefined you should have n1 as the result.

(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        n1))
  (helperFunction n 1 1))
```

<p>A note on the function. A standard fibonacci goes like <code>0,1,1,2,3,5</code> and the function is usually zero indexed such that:</p>

<pre class="lang-scm prettyprint-override"><code>(fib 0) ; ==> 0
(fib 1) ; ==> 1
(fib 10) ; ==> 55
</code>```

Title: Nested functions in scheme

Body:
I'm new to scheme language and trying to execute this code that calculating the n'th Fibonacci series using an internal function.

for some reason it doesn't  work for me and i would like to get some help.
Thank you.

    (define fibo (lambda (n)
      (define (helperFunction n n1 a_n)
        (begin
        (display a_n)
        (newline)
        (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1))))
       (helperFunction n 1 1)))

Body:
First off, why do you use the long version in fibo and the short version in helperFunction? eg.

(define long-version (lambda (arg) arg))
(define (short-version arg) arg)

These are the same. Books often use the long version to point out that functions are values and the names are bindings just as with variables, but its practical to use the short version when you already have started with it.

a begin that wraps the contents of a function is unnecessary since all functions have explicit begin.

An if where you only have a test and a then clause will return a implementation chosen value when the test is false. I tend to use the symbol undefined to not get any surprises on what the undefined value is.

You need to indent your code properly. I use DrRacket and press CTRL+I. With these I get your code like this:

(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        'undefined))
  (helperFunction n 1 1))

So lets try this:

(fibo 1) ; ==> undefined

That makes sense from looking at the code. It's hardly correct but it does what it has been instructed to do. What if it was 2?

(fibo 2) ; ==
(helperFunction 1 2 1) ==> undefined

I think your problem is that instead of undefined you should have n1 as the result.

(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        n1))
  (helperFunction n 1 1))

A note on the function. A standard fibonacci goes like 0,1,1,2,3,5 and the function is usually zero indexed such that:

(fib 0) ; ==> 0
(fib 1) ; ==> 1
(fib 10) ; ==> 55


问:
Why use Spring's Mock MVC when you have unit test of your controller classes
I have seen people around me using Spring MVC in unit tests for controller classes, which is not helpful in what a unit test is for.

Unit tests are supposed to test your actual implementation of the controller class, and this can be achieved more accurately with simple Junit tests rather than using Spring Mock MVC.

But then the question arises, what's the real usage of Spring Mock MVC then? What do you need it for?

Let's say I have below code :

```<code>@Controller
@RequestMapping("/systemusers")
public class SystemUserController
{
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getUser(final Model model)
    {

        // some logic to return user's details as json

        return UserDetailsPage;
    }
 }
</code>```

I can test this class/controller more accurately with Junit than with Spring Mock MVC (all it does is generates some json which can be asserted with junit).

I can also test with Spring Mock MVC like using the correct endpoint returns the correct HTTP status and correct response page string.

But doesn't that mean that we are testing Spring MVC's functionality rather than the actual code for method under test?

P.S. : I have kept the code to minimal which I think is sufficient to explain my question. Assume there is no compilation error.

答:
When it comes to the unit-testing of a Controller (or any Endpoint which is exposed) classes, there are two things that we will validate:

(1) Controller's actual logic itself as standalone i.e., right service calls are invoked or not etc..

(2) Request URL mapping and the Response status & object

Item (1) above is what we test in general with all other classes like Services, Utility classes etc..

Item (2) needs to be covered/tested additionally for the endpoints (controller classes) which have been exposed, so whether we use Spring's MockMVC or other machinery to do that, it is up to us really.

Spring's MockMVC indeed helps us to start the in-memory servlet container & check that the right controller methods are invoked & then the right responses have been coming out.

From my personal experience, testing the controllers (for item(2)) helped me to resolve URL mapping conflict issues (of course, within the same controller) etc.. straight away rather than fixing them at the later stages of the project.

ContentLicense: CC BY-SA 4.0

Body:
I have seen people around me using Spring MVC in unit tests for controller classes, which is not helpful in what a unit test is for.

Unit tests are supposed to test your actual implementation of the controller class, and this can be achieved more accurately with simple Junit tests rather than using Spring Mock MVC.

But then the question arises, what's the real usage of Spring Mock MVC then? What do you need it for?

Let's say I have below code :

@Controller
@RequestMapping("/systemusers")
public class SystemUserController
{
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getUser(final Model model)
    {

        // some logic to return user's details as json

        return UserDetailsPage;
    }
 }

I can test this class/controller more accurately with Junit than with Spring Mock MVC (all it does is generates some json which can be asserted with junit).

I can also test with Spring Mock MVC like using the correct endpoint returns the correct HTTP status and correct response page string.

But doesn't that mean that we are testing Spring MVC's functionality rather than the actual code for method under test?

P.S. : I have kept the code to minimal which I think is sufficient to explain my question. Assume there is no compilation error.


问:
Chinese CultureInfo
Chinese CultureInfo is "zh" (zh-CN and others). But I can't find what does "zh" stand for?</p>

答:
zh-CN means China,
zh-TW means Taiwan,
zh-HK means Hong Kong.

For example:

```<code>为(in zh-CN) 爲(in zh-HK) 為(in zh-TW)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Chinese CultureInfo

Body:
zh-CN means China,
zh-TW means Taiwan,
zh-HK means Hong Kong.

For example:

为(in zh-CN) 爲(in zh-HK) 為(in zh-TW)


问:
ExtJs: How can I select first item of Radiogroup on button click event
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

```<code>Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});
</code>```

Above code is not working. I have also tried below code. But it also doesn't work:

```<code>var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));
</code>```

答:
try to change the line

```<code>Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);
</code>```

to

```<code>Ext.ComponentQuery.query('[name="type"]')[0].items.items[0].setValue(true);
</code>```

check fiddle

Body:
I have a radiogroup and on button click event I want to set the first item of radiogroup to be selected. I have tried below code, but it is not working:

Ext.create('Ext.panel.Panel',{
    items: [
    {
                title: "Types",
                items: {
                    xtype: "radiogroup",
                    name: "type",
                    columns: 2,
                    vertical: true,
                    items: [{
                        xtype: "radio",
                        boxLabel: "Vertical",
                        inputValue: "2",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout",

                    }, {
                        xtype: "radio",
                        boxLabel: "Horizontal",
                        inputValue: "1",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }, {
                        xtype: "radio",
                        boxLabel: "Auto",
                        inputValue: "0",
                        style: {
                            marginLeft: '10px',
                            marginRight: '10px'
                        },
                        hideLabel: true,
                        name: "layout"
                    }]
                }
            }
    , {
        xtype: 'button',
        text: 'Reset',
        handler: function (button) {
            Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

        }
    }],
    renderTo: Ext.getBody()
});

Above code is not working. I have also tried below code. But it also doesn't work:

var radioGroup = this.settingsFields.down(_.replace('[name="id"]', 'id', id));
radioGroup.select(radioGroup.getStore().getAt(0));

Body:
try to change the line

Ext.ComponentQuery.query('[name="type"]').items.items[0].setValue(true);

to

Ext.ComponentQuery.query('[name="type"]')[0].items.items[0].setValue(true);

check fiddle


问:
How to split lines from Windows text file (/r/n separation)
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

```<code>string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array
</code>```

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

答:
you could use an extension method like the one below and your code would then look like this:

```<code>    var lines = operationText.ReadAsLines();
</code>```

Extension method implementation:

```<code>    public static IEnumerable<string> ReadAsLines(this string text)
    {
        TextReader reader = new StringReader(text);
        while(reader.Peek() >= 0)
        {
            yield return reader.ReadLine();
        }
    }
</code>```

I'm guessing it's not as performant as the split option which is usually very performant but if that's not an issue...

Body:
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

Body:
you could use an extension method like the one below and your code would then look like this:

    var lines = operationText.ReadAsLines();

Extension method implementation:

    public static IEnumerable<string> ReadAsLines(this string text)
    {
        TextReader reader = new StringReader(text);
        while(reader.Peek() >= 0)
        {
            yield return reader.ReadLine();
        }
    }

I'm guessing it's not as performant as the split option which is usually very performant but if that's not an issue...


问:
Presenting ViewController with TabBarController
Okay, so each time I try to present a ViewController (from the AppDelegate file's, "didFinishLaunchingWithOptions" function) using the following code, my tabBar with 4 items disappears, even though the ViewController I want is shown:

```<code>    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController? = tabBarController
</code>```

When I try the following code (also in the AppDelegate file's "didFinishLaunchingWithOptions" function), then I get nothing at all:

```<code>    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController?.tabBarController?.didMove(toParentViewController: tabBarController)
</code>```

I've tried several iterations of the two, but I still can't seem to get what I want...

Essentially, what I want is to programmatically press one of the buttons so that my third view controller becomes the first view the user sees in certain circumstances.

Any help would be greatly appreciated!

答:
Ok this is what i did for my app,
what i did was, i always navigate to the MainView and call performSegue to navigate. then i pushViewController </p>

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

var shortcutItem: UIApplicationShortcutItem?
var mainViewController:MainViewController?
static var  handled = false

enum ShortcutIdentifier: String {
    case AddExpense
    case AddIncome
    case AddExpenseType
    case AddIncomeType

    init?(fullIdentifier: String) {
        guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else {
            return nil
        }
        self.init(rawValue: shortIdentifier)
    }

    func getUIViewController(storyboard : UIStoryboard) -> UIViewController{
        return storyboard.instantiateViewController(withIdentifier:self.rawValue)
    }
}

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    self.shortcutItem = shortcutItem
    completionHandler(handleShortcut(shortcutItem))
}

@discardableResult fileprivate func handleShortcut(_ shortcutItem: UIApplicationShortcutItem) -> Bool {

    let shortcutType = shortcutItem.type
    guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else {
        return false
    }

    return selectTabBarItemForIdentifier(shortcutIdentifier)
}

fileprivate func selectTabBarItemForIdentifier(_ identifier: ShortcutIdentifier) -> Bool {
    if AppDelegate.handled  {
        return false
    }

    var handled = false

    guard let tabBarController = self.window?.rootViewController as? UITabBarController else {
        return false
    }

    tabBarController.selectedIndex = 1

    if let contentViewController  = tabBarController.selectedViewController?.contentViewController as? MainViewController  {
        mainViewController = contentViewController
    }else{

        guard let  navigationController = tabBarController.selectedViewController?.contentViewController.navigationController else {
            return false
        }

        print(type(of:navigationController.contentViewController))
        print(navigationController.viewControllers.count)

        let _ = navigationController.popToRootViewController(animated: true)

    }

    guard let rootView = mainViewController else {
        return false
    }

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    switch (identifier) {
    case .AddExpense:
        rootView.performSegue(withIdentifier: "Expences", sender: rootView)
        handled = true
    case .AddIncome:
        rootView.performSegue(withIdentifier: "Incomes", sender: rootView)
        handled = true
    case .AddExpenseType:
        rootView.performSegue(withIdentifier: "Expences Types", sender: rootView)
        handled = true
    case .AddIncomeType:
        rootView.performSegue(withIdentifier: "Incomes Types", sender: rootView)
        handled = true
    }

    rootView.navigationController!.pushViewController(identifier.getUIViewController(storyboard: storyboard), animated: true)
    AppDelegate.handled = handled
    return handled
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let theme = ThemManager.currentTheme()
    ThemManager.applyTheme(theme: theme)

    var performShortcutDelegate = true

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {

        print("Application launched via shortcut")
        self.shortcutItem = shortcutItem

        performShortcutDelegate = false
    }

    return performShortcutDelegate

}

func applicationDidEnterBackground(_ application: UIApplication) {

    AppDelegate.handled = false
}

func applicationDidBecomeActive(_ application: UIApplication) {

    print("Application did become active")

    guard let shortcut = shortcutItem else { return }

    print("- Shortcut property has been set")

    handleShortcut(shortcut)
    AppDelegate.handled = true
    self.shortcutItem = nil
}
</code>```

<p>}</p>

Body:
Okay, so each time I try to present a ViewController (from the AppDelegate file's, "didFinishLaunchingWithOptions" function) using the following code, my tabBar with 4 items disappears, even though the ViewController I want is shown:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController? = tabBarController

When I try the following code (also in the AppDelegate file's "didFinishLaunchingWithOptions" function), then I get nothing at all:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController?.tabBarController?.didMove(toParentViewController: tabBarController)

I've tried several iterations of the two, but I still can't seem to get what I want...

Essentially, what I want is to programmatically press one of the buttons so that my third view controller becomes the first view the user sees in certain circumstances.

Any help would be greatly appreciated!

Body:
Ok this is what i did for my app,
what i did was, i always navigate to the MainView and call performSegue to navigate. then i pushViewController

class AppDelegate: UIResponder, UIApplicationDelegate {

var shortcutItem: UIApplicationShortcutItem?
var mainViewController:MainViewController?
static var  handled = false

enum ShortcutIdentifier: String {
    case AddExpense
    case AddIncome
    case AddExpenseType
    case AddIncomeType

    init?(fullIdentifier: String) {
        guard let shortIdentifier = fullIdentifier.components(separatedBy: ".").last else {
            return nil
        }
        self.init(rawValue: shortIdentifier)
    }

    func getUIViewController(storyboard : UIStoryboard) -> UIViewController{
        return storyboard.instantiateViewController(withIdentifier:self.rawValue)
    }
}

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    self.shortcutItem = shortcutItem
    completionHandler(handleShortcut(shortcutItem))
}

@discardableResult fileprivate func handleShortcut(_ shortcutItem: UIApplicationShortcutItem) -> Bool {

    let shortcutType = shortcutItem.type
    guard let shortcutIdentifier = ShortcutIdentifier(fullIdentifier: shortcutType) else {
        return false
    }

    return selectTabBarItemForIdentifier(shortcutIdentifier)
}

fileprivate func selectTabBarItemForIdentifier(_ identifier: ShortcutIdentifier) -> Bool {
    if AppDelegate.handled  {
        return false
    }

    var handled = false

    guard let tabBarController = self.window?.rootViewController as? UITabBarController else {
        return false
    }

    tabBarController.selectedIndex = 1

    if let contentViewController  = tabBarController.selectedViewController?.contentViewController as? MainViewController  {
        mainViewController = contentViewController
    }else{

        guard let  navigationController = tabBarController.selectedViewController?.contentViewController.navigationController else {
            return false
        }

        print(type(of:navigationController.contentViewController))
        print(navigationController.viewControllers.count)

        let _ = navigationController.popToRootViewController(animated: true)

    }

    guard let rootView = mainViewController else {
        return false
    }

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    switch (identifier) {
    case .AddExpense:
        rootView.performSegue(withIdentifier: "Expences", sender: rootView)
        handled = true
    case .AddIncome:
        rootView.performSegue(withIdentifier: "Incomes", sender: rootView)
        handled = true
    case .AddExpenseType:
        rootView.performSegue(withIdentifier: "Expences Types", sender: rootView)
        handled = true
    case .AddIncomeType:
        rootView.performSegue(withIdentifier: "Incomes Types", sender: rootView)
        handled = true
    }

    rootView.navigationController!.pushViewController(identifier.getUIViewController(storyboard: storyboard), animated: true)
    AppDelegate.handled = handled
    return handled
}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let theme = ThemManager.currentTheme()
    ThemManager.applyTheme(theme: theme)

    var performShortcutDelegate = true

    if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {

        print("Application launched via shortcut")
        self.shortcutItem = shortcutItem

        performShortcutDelegate = false
    }

    return performShortcutDelegate

}

func applicationDidEnterBackground(_ application: UIApplication) {

    AppDelegate.handled = false
}

func applicationDidBecomeActive(_ application: UIApplication) {

    print("Application did become active")

    guard let shortcut = shortcutItem else { return }

    print("- Shortcut property has been set")

    handleShortcut(shortcut)
    AppDelegate.handled = true
    self.shortcutItem = nil
}

}


答:
you can use zipwithindex and than filter first lines than
you can use a class to check the header

```<code>class convert( var  cin_Nb:String, var start:String, var end:String,
        var event:String, var duration:String, var zed:String,......)extends Product  with Serializable {
      def canEqual(that: Any) = that.isInstanceOf[convert]
      def productArity = 104
      def productElement(idx: Int) = idx match {
                    case 0 => cin_Nb;case 1 =>  start;case 2 =>  end;
                    case 3 =>  event;case 4 =>  duration;case 5 =>  zed;
                    ..........
                    }
      }
</code>```

and you convert the rdd to dataframe using this structure

Title: Spark convert rdd to dataframe using a class

Body:
I'm using Spark 1.6 with Scala.
i was looking here but i didnt find a clear answer
I have a big file, after filtering the first lines that contain some copyrights I want to take the header (104 fields) and convert it to StructType schema.
I was thinking to use a class extends Product trait to define the schema of the Dataframe and then convert it to Dataframe according to that schema.

What is the best way to do it.

This is a sample from my file:

   text  (06.07.03.216)  COPYRIGHT © skdjh 2000-2016
    text  160614_54554.vf Database    53643_csc   Interface   574 zn  65
    Start   Date    14/06/2016  00:00:00:000
    End Date    14/06/2016  00:14:59:999
    State   "s23"

        cin. Nb      Start     End        Event       Con. Duration  IMSI
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx
        32055680    16/09/2010 16:59:59:245 16/09/2016 17:00:00:000 xxxxxxxxxxxxx

T want to convert it to SparkSQL like this schema

    ----------------------------------------------------------------------------------------
  |    cin_Nb |  Start            |   End          |      Event   |   Con_Duration  | IMSI  |
  | ----------------------------------------------------------------------------------------|
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   20556800 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
  |   32055680 |   16/09/2010     |   16:59:59:245 |  16/09/2016  |   17:00:00:000  | xxxxx |
    ----------------------------------------------------------------------------------------

Body:
you can use zipwithindex and than filter first lines than
you can use a class to check the header

class convert( var  cin_Nb:String, var start:String, var end:String,
        var event:String, var duration:String, var zed:String,......)extends Product  with Serializable {
      def canEqual(that: Any) = that.isInstanceOf[convert]
      def productArity = 104
      def productElement(idx: Int) = idx match {
                    case 0 => cin_Nb;case 1 =>  start;case 2 =>  end;
                    case 3 =>  event;case 4 =>  duration;case 5 =>  zed;
                    ..........
                    }
      }

and you convert the rdd to dataframe using this structure


问:
Nuxt.js routes returning 404 in IIS with IISNODE
Just trying to host the nuxt.js and express.js demo in iis with iisnode.
I am getting 404's for the nuxt page routes, but the express api routes are working fine.

All that nuxt does is all express to handle its routes. Not sure why this is not working.

I have set up my web.config with iisnode handler and I have also included the url rewrite config to route everything to the server.prod.js

'use strict';

var Nuxt = require('nuxt');
var app = require('express')();
var host = process.env.HOST || '127.0.0.1';
var port = process.env.PORT || 3000;

app.set('port', port);
// Import API Routes
app.use('/api', require('./api/index'));

// Import and Set Nuxt.js options
var config = require('./nuxt.config.js');
config.dev = !(process.env.NODE_ENV === 'production');

// Init Nuxt.js
var nuxt = new Nuxt(config);
app.use(nuxt.render);

// Build only in dev mode
if (config.dev) {
  nuxt.build().catch(function (error) {
    console.error(error); // eslint-disable-line no-console
    process.exit(1);
  });
}

// Listen the server
app.listen(port, host);
console.log('Server listening on ' + host + ':' + port); // eslint-disable-line no-console
```

<pre class="lang-html prettyprint-override"><code><configuration>
<system.webServer>
   <handlers><add name="iisnode" path="server.prod.js" verb="*" modules="iisnode" /></handlers>
    <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="server.prod.js" />
        </rule>
        <!-- Don't interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^app.js\/debug[\/]?" />
        </rule>

      </rules>

    </rewrite>
        <directoryBrowse enabled="true" />

        <iisnode devErrorsEnabled="true" debuggingEnabled="true" loggingEnabled="true" nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />

     <!-- exclude node_modules directory and subdirectories from serving
     by IIS since these are implementation details of node.js applications -->

     <security>
       <requestFiltering>
         <hiddenSegments>
           <add segment="node_modules" />
         </hiddenSegments>
       </requestFiltering>
     </security>

 </system.webServer>
</configuration>
</code>```

答:
IIS Node uses named pipes, therefore the server render api calls on locahost tcp port 80 were failing...
The server-side needs a full url to work.</p>

Body:
Just trying to host the nuxt.js and express.js demo in iis with iisnode.
I am getting 404's for the nuxt page routes, but the express api routes are working fine.

All that nuxt does is all express to handle its routes. Not sure why this is not working.

I have set up my web.config with iisnode handler and I have also included the url rewrite config to route everything to the server.prod.js

'use strict';

var Nuxt = require('nuxt');
var app = require('express')();
var host = process.env.HOST || '127.0.0.1';
var port = process.env.PORT || 3000;

app.set('port', port);
// Import API Routes
app.use('/api', require('./api/index'));

// Import and Set Nuxt.js options
var config = require('./nuxt.config.js');
config.dev = !(process.env.NODE_ENV === 'production');

// Init Nuxt.js
var nuxt = new Nuxt(config);
app.use(nuxt.render);

// Build only in dev mode
if (config.dev) {
  nuxt.build().catch(function (error) {
    console.error(error); // eslint-disable-line no-console
    process.exit(1);
  });
}

// Listen the server
app.listen(port, host);
console.log('Server listening on ' + host + ':' + port); // eslint-disable-line no-console

<configuration>
<system.webServer>
   <handlers><add name="iisnode" path="server.prod.js" verb="*" modules="iisnode" /></handlers>
    <rewrite>
      <rules>
        <rule name="myapp">
          <match url="/*" />
          <action type="Rewrite" url="server.prod.js" />
        </rule>

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^app.js\/debug[\/]?" />
        </rule>

      </rules>

    </rewrite>
        <directoryBrowse enabled="true" />

        <iisnode devErrorsEnabled="true" debuggingEnabled="true" loggingEnabled="true" nodeProcessCommandLine="C:\Program Files\nodejs\node.exe" />

     <security>
       <requestFiltering>
         <hiddenSegments>
           <add segment="node_modules" />
         </hiddenSegments>
       </requestFiltering>
     </security>

 </system.webServer>
</configuration>


问:
Powershell script for checking AD replication
I adapted an AD replication powershell script I found online to include the code below:

```<code>function ExitWithCode {
param
(
    $exitcode
)

$host.SetShouldExit($exitcode)
exit
}

function Write-Log {
<#
.SYNOPSIS
    Write-Log writes a message to a logfile

.DESCRIPTION
    The Write-Log function is designed to add logging capability to other scripts.
    In addition to writing output and/or verbose you can write to a log file for
    later debugging.
#>
[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [Alias('LogContent')]
    [string]$Message,

    [Parameter(Mandatory = $false)]
    [ValidateSet("Error", "Info", "Status")]
    [string]$Level = "Info",

    [Parameter(Mandatory = $false)]
    [Alias('LogPath')]
    [string]$Path = 'C:\dataloop\ADHealthCheck.log'

)

BEGIN {

    [string]$FormattedDate = Get-Date -Format "dd-MM-yyyy HH:mm"

    If (-NOT (Test-Path $path)) {
        Write-Verbose "Creating $Path"
        [System.IO.FileInfo]$LogFile = New-Item $Path -Force -ItemType file
    }
}
PROCESS {
    [string]$LogLine = "$FormattedDate - $Level - $message"
    $LogLine | Out-File -FilePath $Path -Append

    Switch ($Level) {

        "Info" {Write-Verbose $LogLine}
        "Status" {Write-Output $LogLine}
        "Error" {Write-Error $LogLine}
    }
}
END {}
}

function Get-ADHealthCheck {
    [CmdletBinding()]
        param()

        BEGIN {
        Write-Log "Beginning the AD Health Check..."
        }

        PROCESS {
        $DCs = Get-ADDomainController -Filter * |sort name

        Write-Log "$($DCs.Count) Domain Controllers found" -level Info

        $results = @()

        ForEach ($DC in $DCs) {

            Write-Log "Getting replication metadata for $($DC.HostName)" -level Status
            $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue

            If ($ReplStatuses) {

                 Write-Log "$($ReplStatuses.Count) replication links found for $($DC.HostName)" -level Info

                ForEach ($ReplStatus in $ReplStatuses) {

                    $Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")

                    $results += [pscustomobject] @{
                        'Source DC' = $DC.HostName.ToUpper()
                        'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
                        'Direction' = $ReplStatus.PartnerType
                        'Type' = $ReplStatus.IntersiteTransportType
                        'Last Attempt' = $ReplStatus.LastReplicationAttempt
                        'Last Success' = $ReplStatus.LastReplicationSuccess
                        'Last Result' = $ReplStatus.LastReplicationResult
                    }
                }
            }

            Else {

                Write-Log "Unable to get replication status for $($DC.HostName)" -level Error
                $results += [pscustomobject] @{
                    'Source DC' = $DC.HostName.ToUpper()
                    'Partner DC' = "N/A"
                    Direction = "N/A"
                    Type = "N/A"
                    'Last Attempt' = "N/A"
                    'Last Success' = "N/A"
                    'Last Result' = "N/A"
                }
             }
        }

        ForEach ($result in $results) {

            If ("$($results.'Last Result')" -eq "0") {

                Write-Log "There were no replication issues found" -Level Info
                ExitWithCode -exitcode 0
            }

            Else {

                Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
                $error = $results | where {"$($_.'Last Result')" -ne "0"} | select 'Source DC','Partner DC','Direction' | ft -AutoSize
                Write-Log $error -Level Error
                ExitWithCode -exitcode 2
            }
        }
    }
}
Get-ADHealthCheck
</code>```

Basically the only issue I'm having now is the last if/else block. I need it to loop through every entry in the $results hash table and if the "Last Result" key only contains "0", then exit with code 0. If it finds any other values, it should output the source, partner, and direction value(s) fromt he hash table.

Currently, if it encounters an issue, it jumps to the else block, outputs the information requested and then runs the ExitWithCode function which eventually kills the script so anything that comes after the error is not checked.

I've been looking at this too long and have been unsuccessful so I'm throwing it out to there since it may just be something simple I'm missing.

答:
Look at your for loop variables

```<code>ForEach ($result in $results) {
</code>```

For each single $result in the $results. In the following if statement you should be looking at one $result but instead you are doing a comparison against all results. Your subexpression syntax here is also not required.

```<code> If ("$($results.'Last Result')" -eq "0")
</code>```

Note that this is perfectly valid code but it will not get you the results you expect. It will return all 'last result's that are 0. So if even one in the whole collection is 0 the true condition will always  fire.

So lets just make some minor changes and use the singular $result

```<code>If ($result.'Last Result' -eq "0")
</code>```

That should get you the result you are looking for. I notice that you are looking for equality with the string 0. That will not be an issue here since the LHS sets the type for the comparison. Have a look at this other post to get a better understanding of what PowerShell does here.

Why is $false -eq "" true?

If your last result was the int 0 this would be true

```<code>0 -eq "0"
</code>```

Your logic appears to be flawed as you have mentioned in comments on how to handle overall success and individual failures. Instead of looping through the results like you were I think we need to check the collection as a whole and loop only if errors are encountered.

```<code># Lets check if any of the results contain failure
$failedChecks = $results | Where-object{$_.'Last Result' -ne 0}

# Evaluate $failedChecks as a boolean. If there are no failed checks Else can be assumed that everything is fine.
if($failedChecks){
    Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
    $error = $failedChecks | select 'Source DC','Partner DC','Direction' | ft -AutoSize | Out-String
    Write-Log $error -Level Error
    ExitWithCode -exitcode 2
} else {
    Write-Log "There were no replication issues found" -Level Info
    ExitWithCode -exitcode 0
}
</code>```

Body:
I adapted an AD replication powershell script I found online to include the code below:

function ExitWithCode {
param
(
    $exitcode
)

$host.SetShouldExit($exitcode)
exit
}

function Write-Log {
<#
.SYNOPSIS
    Write-Log writes a message to a logfile

.DESCRIPTION
    The Write-Log function is designed to add logging capability to other scripts.
    In addition to writing output and/or verbose you can write to a log file for
    later debugging.
#>
[CmdletBinding()]
Param
(
    [Parameter(Mandatory = $true,ValueFromPipelineByPropertyName = $true)]
    [ValidateNotNullOrEmpty()]
    [Alias('LogContent')]
    [string]$Message,

    [Parameter(Mandatory = $false)]
    [ValidateSet("Error", "Info", "Status")]
    [string]$Level = "Info",

    [Parameter(Mandatory = $false)]
    [Alias('LogPath')]
    [string]$Path = 'C:\dataloop\ADHealthCheck.log'

)

BEGIN {

    [string]$FormattedDate = Get-Date -Format "dd-MM-yyyy HH:mm"

    If (-NOT (Test-Path $path)) {
        Write-Verbose "Creating $Path"
        [System.IO.FileInfo]$LogFile = New-Item $Path -Force -ItemType file
    }
}
PROCESS {
    [string]$LogLine = "$FormattedDate - $Level - $message"
    $LogLine | Out-File -FilePath $Path -Append

    Switch ($Level) {

        "Info" {Write-Verbose $LogLine}
        "Status" {Write-Output $LogLine}
        "Error" {Write-Error $LogLine}
    }
}
END {}
}

function Get-ADHealthCheck {
    [CmdletBinding()]
        param()

        BEGIN {
        Write-Log "Beginning the AD Health Check..."
        }

        PROCESS {
        $DCs = Get-ADDomainController -Filter * |sort name

        Write-Log "$($DCs.Count) Domain Controllers found" -level Info

        $results = @()

        ForEach ($DC in $DCs) {

            Write-Log "Getting replication metadata for $($DC.HostName)" -level Status
            $ReplStatuses = Get-ADReplicationPartnerMetadata -target $DC.HostName -PartnerType Both -ErrorAction SilentlyContinue

            If ($ReplStatuses) {

                 Write-Log "$($ReplStatuses.Count) replication links found for $($DC.HostName)" -level Info

                ForEach ($ReplStatus in $ReplStatuses) {

                    $Partner = $ReplStatus.Partner.Split(",")[1].Replace("CN=","")

                    $results += [pscustomobject] @{
                        'Source DC' = $DC.HostName.ToUpper()
                        'Partner DC' = (Get-ADComputer $Partner).DNSHostName.ToUpper()
                        'Direction' = $ReplStatus.PartnerType
                        'Type' = $ReplStatus.IntersiteTransportType
                        'Last Attempt' = $ReplStatus.LastReplicationAttempt
                        'Last Success' = $ReplStatus.LastReplicationSuccess
                        'Last Result' = $ReplStatus.LastReplicationResult
                    }
                }
            }

            Else {

                Write-Log "Unable to get replication status for $($DC.HostName)" -level Error
                $results += [pscustomobject] @{
                    'Source DC' = $DC.HostName.ToUpper()
                    'Partner DC' = "N/A"
                    Direction = "N/A"
                    Type = "N/A"
                    'Last Attempt' = "N/A"
                    'Last Success' = "N/A"
                    'Last Result' = "N/A"
                }
             }
        }

        ForEach ($result in $results) {

            If ("$($results.'Last Result')" -eq "0") {

                Write-Log "There were no replication issues found" -Level Info
                ExitWithCode -exitcode 0
            }

            Else {

                Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
                $error = $results | where {"$($_.'Last Result')" -ne "0"} | select 'Source DC','Partner DC','Direction' | ft -AutoSize
                Write-Log $error -Level Error
                ExitWithCode -exitcode 2
            }
        }
    }
}
Get-ADHealthCheck

Basically the only issue I'm having now is the last if/else block. I need it to loop through every entry in the $results hash table and if the "Last Result" key only contains "0", then exit with code 0. If it finds any other values, it should output the source, partner, and direction value(s) fromt he hash table.

Currently, if it encounters an issue, it jumps to the else block, outputs the information requested and then runs the ExitWithCode function which eventually kills the script so anything that comes after the error is not checked.

I've been looking at this too long and have been unsuccessful so I'm throwing it out to there since it may just be something simple I'm missing.

Body:
Look at your for loop variables

ForEach ($result in $results) {

For each single $result in the $results. In the following if statement you should be looking at one $result but instead you are doing a comparison against all results. Your subexpression syntax here is also not required.

 If ("$($results.'Last Result')" -eq "0")

Note that this is perfectly valid code but it will not get you the results you expect. It will return all 'last result's that are 0. So if even one in the whole collection is 0 the true condition will always  fire.

So lets just make some minor changes and use the singular $result

If ($result.'Last Result' -eq "0")

That should get you the result you are looking for. I notice that you are looking for equality with the string 0. That will not be an issue here since the LHS sets the type for the comparison. Have a look at this other post to get a better understanding of what PowerShell does here.

Why is $false -eq "" true?

If your last result was the int 0 this would be true

0 -eq "0"

Your logic appears to be flawed as you have mentioned in comments on how to handle overall success and individual failures. Instead of looping through the results like you were I think we need to check the collection as a whole and loop only if errors are encountered.

# Lets check if any of the results contain failure
$failedChecks = $results | Where-object{$_.'Last Result' -ne 0}

# Evaluate $failedChecks as a boolean. If there are no failed checks Else can be assumed that everything is fine.
if($failedChecks){
    Write-Log "These domain controllers have replication errors. Please review them..." -Level Error
    $error = $failedChecks | select 'Source DC','Partner DC','Direction' | ft -AutoSize | Out-String
    Write-Log $error -Level Error
    ExitWithCode -exitcode 2
} else {
    Write-Log "There were no replication issues found" -Level Info
    ExitWithCode -exitcode 0
}


问:
My quick sort implementation is not working for 10000 sequence numbers
I have a quick sort implementation, this sort implementation is working fine with small arrays and 10000 random numbers but it is throwing a stackoverflow error when the input was 10000 sequence numbers (from 1 to 10000)

```<code>public class QuickSort<T extends Comparable> extends Sort<T>{

public void sort(Comparable[] input) {
    sort(input, 0, input.length-1);
}

private void sort(Comparable[] a, int lo, int hi) {
    if (hi <= lo) return;

    int j = partition(a, lo, hi);
    sort(a, lo, j-1);
    sort(a, j+1, hi);
}

private int partition(Comparable[] a, int lo, int hi) {
    int i=lo;
    int j=hi + 1;
    Comparable v = a[lo];

    while(true) {
        while (less(a[++i], v)) {
            if (i == hi) break;
        }

        while (less(v, a[--j])) {
            if (j == lo) break;
        }

        if(i >= j) break;

        exch(a, i, j);
    }
    exch(a, lo, j);
    return j;
}

public static boolean less (Comparable a, Comparable b) {
    return a.compareTo(b) < 0;
}

public static void exch(Comparable[] array, int i, int j) {
    Comparable temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String...args) {
    Integer[] array = new Integer[] {10,2,9,11,1,19,9,4,6,2,1,4,5,6};
    new QuickSort<>().sort(array);

    for (int temp : array) {
        System.out.print(temp + " ");
    }
}
}
</code>```

It is working for 10000 random numbers and for other input. But throws a stackoverflow error when executed with 10000 sequence numbers (from 1 to 10000)

答:
The stack overflow occurs because you indeed more try to use more stack space then is available for your java program in the JVM.

This happens because your pivot-selection strategy is simply selecting the first element as a pivot, and this causes a worst-case performance when the array is already sorted - in this case the algorithm runs in O(n^2) time and O(n) space - which means the recursion is 10000 deep, using up more stack than available.

You have a few options :

Increase stack space - Default stack size (in most JVMs) in 512k, but you can change this with the -Xss flag. In my env, when I added the flag -Xss18m (18 MB) I could run the program with an array of 200k without stack overflow. You can increase it even much more than that.

Try to use less stack space - stack space is used by the recursion and the stack variables which are defined in the function.

For example, you could change the array itself to be a member of the class QuickSort, and not pass it as a parameter. This would add only two integers (lo and hi) to the stack in each call, and save up stack space.

(The best option) - Use a random pivot - Select a random element between lo and hi as pivot, not always the first one.
instead of

Comparable v = a[p];

use

```<code> int p = lo + r.nextInt(hi  - lo);
 Comparable v = a[p];
</code>```

and in the end

```<code>exch(a, p, j);
</code>```

Body:
I have a quick sort implementation, this sort implementation is working fine with small arrays and 10000 random numbers but it is throwing a stackoverflow error when the input was 10000 sequence numbers (from 1 to 10000)

public class QuickSort<T extends Comparable> extends Sort<T>{

public void sort(Comparable[] input) {
    sort(input, 0, input.length-1);
}

private void sort(Comparable[] a, int lo, int hi) {
    if (hi <= lo) return;

    int j = partition(a, lo, hi);
    sort(a, lo, j-1);
    sort(a, j+1, hi);
}

private int partition(Comparable[] a, int lo, int hi) {
    int i=lo;
    int j=hi + 1;
    Comparable v = a[lo];

    while(true) {
        while (less(a[++i], v)) {
            if (i == hi) break;
        }

        while (less(v, a[--j])) {
            if (j == lo) break;
        }

        if(i >= j) break;

        exch(a, i, j);
    }
    exch(a, lo, j);
    return j;
}

public static boolean less (Comparable a, Comparable b) {
    return a.compareTo(b) < 0;
}

public static void exch(Comparable[] array, int i, int j) {
    Comparable temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

public static void main(String...args) {
    Integer[] array = new Integer[] {10,2,9,11,1,19,9,4,6,2,1,4,5,6};
    new QuickSort<>().sort(array);

    for (int temp : array) {
        System.out.print(temp + " ");
    }
}
}

It is working for 10000 random numbers and for other input. But throws a stackoverflow error when executed with 10000 sequence numbers (from 1 to 10000)

Body:
The stack overflow occurs because you indeed more try to use more stack space then is available for your java program in the JVM.

This happens because your pivot-selection strategy is simply selecting the first element as a pivot, and this causes a worst-case performance when the array is already sorted - in this case the algorithm runs in O(n^2) time and O(n) space - which means the recursion is 10000 deep, using up more stack than available.

You have a few options :

Increase stack space - Default stack size (in most JVMs) in 512k, but you can change this with the -Xss flag. In my env, when I added the flag -Xss18m (18 MB) I could run the program with an array of 200k without stack overflow. You can increase it even much more than that.

Try to use less stack space - stack space is used by the recursion and the stack variables which are defined in the function.

For example, you could change the array itself to be a member of the class QuickSort, and not pass it as a parameter. This would add only two integers (lo and hi) to the stack in each call, and save up stack space.

(The best option) - Use a random pivot - Select a random element between lo and hi as pivot, not always the first one.
instead of

Comparable v = a[p];

use

 int p = lo + r.nextInt(hi  - lo);
 Comparable v = a[p];

and in the end

exch(a, p, j);


问:
Problem with creating a 2D interface in a 3D openGL world
I am working on a project that requires that I create a 2D interface rendered "on top" or a 3D world. On some other forums, I read that you could use "GluOrtho2D()" for the job, and switch back to GluPerspective() once you were done. The only thing is, my test code I wrote for it only displays the 3D world, not the 2D quad. When I disable the 3D rendering code, however, the quad appears where it was supposed to be.
I trimmed down the code to openGL only statements, which I wrote down below. The code is written in Python using the Pyglet library.

The scene initialization code:

```<code>glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/height, .1, 10000.)
glMatrixMode(GL_MODELVIEW)
glClearDepth(1.0)
glShadeModel(GL_FLAT)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
</code>```

The frame rendering code. The call to builder.buildMap() creates the 3D scene, and the glBegin-glEnd pair draws a 2D quad:

```<code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)
stage.set3DMode(window.width, window.height)
builder.buildMap()
stage.set2DMode(window.width, window.height)
glBegin (GL_QUADS)
glVertex2i(0, 0)
glVertex2i(0, 200)
glVertex2i(200, 200)
glVertex2i(200, 0)
glEnd()
</code>```

the stage.set3DMode function:

```<code>glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, width, 0, height)
glMatrixMode(GL_MODELVIEW)
</code>```

and the stage.set3DMode function:

```<code>glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/float(height), .1, 10000.)
glMatrixMode(GL_MODELVIEW)
</code>```

I really hope someone can point out my mistake! And thank you for helping me :)

答:
A lot of people get it wrong how to use glViewport and the like. They always place it in the reshape callback which is simply wrong.

You always to the full setup in your rendering function, just before you need those settings. So your code should be (pesudocode):

```<code>render_scene():
    // first clear the whole window
    glViewport(0, 0, window.width, window.height)
    glClearDepth(1.0)
    glClearColor(1., 1., 1., 1.);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)

    glViewport(3Dstuff.x, 3Dstuff.y, 3Dstuff.w, 3Dstuff.h)
    // maybe also set scissor to clip
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 10000.)
    glMatrixMode(GL_MODELVIEW)
    setup3DstuffModelview()
    glDepthFunc(...)
    glEnable(GL_DEPTH_TEST)
    // other state stuff
    render3Dstuff()

    // now the 2D stuff
    glViewport(2Dstuff.x, 2Dstuff.y, 2Dstuff.w, 2Dstuff.h)
    // clear depth and stencil -- if you need parts of the 3D depth / stencil
    // for some algorithm retain it or save and restore by FBO renderbuffers or
    // glReadPixels, glDrawPixels
    glClearDepth(1.0)
    glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(...)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    setup2DstuffModelview()
    glDepthFunc(...)
    glDisable(GL_DEPTH_TEST)
    // other state stuff
    render2Dstuff()

    // repeat for all the layers you need
</code>```

This is really important: OpenGL is a state machine. Unless you can prove that no undetermined state changes happen you always re-/set all the states you need prior to rendering a certain geometry.

Body:
I am working on a project that requires that I create a 2D interface rendered "on top" or a 3D world. On some other forums, I read that you could use "GluOrtho2D()" for the job, and switch back to GluPerspective() once you were done. The only thing is, my test code I wrote for it only displays the 3D world, not the 2D quad. When I disable the 3D rendering code, however, the quad appears where it was supposed to be.
I trimmed down the code to openGL only statements, which I wrote down below. The code is written in Python using the Pyglet library.

The scene initialization code:

glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/height, .1, 10000.)
glMatrixMode(GL_MODELVIEW)
glClearDepth(1.0)
glShadeModel(GL_FLAT)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

The frame rendering code. The call to builder.buildMap() creates the 3D scene, and the glBegin-glEnd pair draws a 2D quad:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)
stage.set3DMode(window.width, window.height)
builder.buildMap()
stage.set2DMode(window.width, window.height)
glBegin (GL_QUADS)
glVertex2i(0, 0)
glVertex2i(0, 200)
glVertex2i(200, 200)
glVertex2i(200, 0)
glEnd()

the stage.set3DMode function:

glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, width, 0, height)
glMatrixMode(GL_MODELVIEW)

and the stage.set3DMode function:

glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/float(height), .1, 10000.)
glMatrixMode(GL_MODELVIEW)

I really hope someone can point out my mistake! And thank you for helping me :)

Body:
A lot of people get it wrong how to use glViewport and the like. They always place it in the reshape callback which is simply wrong.

You always to the full setup in your rendering function, just before you need those settings. So your code should be (pesudocode):

render_scene():
    // first clear the whole window
    glViewport(0, 0, window.width, window.height)
    glClearDepth(1.0)
    glClearColor(1., 1., 1., 1.);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)

    glViewport(3Dstuff.x, 3Dstuff.y, 3Dstuff.w, 3Dstuff.h)
    // maybe also set scissor to clip
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 10000.)
    glMatrixMode(GL_MODELVIEW)
    setup3DstuffModelview()
    glDepthFunc(...)
    glEnable(GL_DEPTH_TEST)
    // other state stuff
    render3Dstuff()

    // now the 2D stuff
    glViewport(2Dstuff.x, 2Dstuff.y, 2Dstuff.w, 2Dstuff.h)
    // clear depth and stencil -- if you need parts of the 3D depth / stencil
    // for some algorithm retain it or save and restore by FBO renderbuffers or
    // glReadPixels, glDrawPixels
    glClearDepth(1.0)
    glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(...)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    setup2DstuffModelview()
    glDepthFunc(...)
    glDisable(GL_DEPTH_TEST)
    // other state stuff
    render2Dstuff()

    // repeat for all the layers you need

This is really important: OpenGL is a state machine. Unless you can prove that no undetermined state changes happen you always re-/set all the states you need prior to rendering a certain geometry.


问:
Jquery function multiple upload fields add indivdually
I have a contact form that I have set up using contact form 7 for wordpress. What I would like to know is if there is a function that when the user clicks on an add button a new file upload option appears so they can have a maximum of 5 file upload fields but 1 shows initially and then they add another one as they need it.

I found this: http://kg69design.com/multiple-files-uploading-cf7.html but I can't seem to get it to work

any help would be appreciated.

thanks

答:
I used my theme's "add code to the head" section to inject the code from the website and it started working perfectly.

To answer duplicate_content's question, you need to ensure you have space between the file shortcodes in the file attachments section of CF7. Mail tab section of CF7


问:
how to pass array in ajax call using php
I have an array like this

```Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

```

How to pass this array in ajax call

Javascript Code is:

```<code>$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});
</code>```

答:
```<code>die(json_encode($arr));
</code>```

json_encode converts PHP array to JSON object. die() method sends the response back to client and terminates the PHP script

Body:
I have an array like this

Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

How to pass this array in ajax call

Javascript Code is:

$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});

Body:
die(json_encode($arr));

json_encode converts PHP array to JSON object. die() method sends the response back to client and terminates the PHP script


问:
Adding Java class to Oracle database by SQL Developer - compilation error
I have technical issue with my database. In SQL Developer there is an option designed to add Java code to database. But when I try to add my code, error message appears (shown below). Do you have any idea where I can find info about what comilation error is this? Some log maybe? And what are the requiments for good Java class? I tried to add Hello World code and it worked fine.

Error message:  https://s4.postimg.org/if3ip9zfh/screenshot000213.jpg

答:
It'll probably be easier to create a class via a script with DDL.

We do it like this:

```<code>CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "IP6Address" AS
import java.math.BigInteger;
public class IP6Address
{
  ... -- whatever
}
/
</code>```

We do that for packages as well because we store these scripts in VCS.

Then you just run the script and wait for the compiler messages (as with any other script).

Body:
It'll probably be easier to create a class via a script with DDL.

We do it like this:

CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "IP6Address" AS
import java.math.BigInteger;
public class IP6Address
{
  ... -- whatever
}
/

We do that for packages as well because we store these scripts in VCS.

Then you just run the script and wait for the compiler messages (as with any other script).


问:
Android Studio - Gradle plugin missing from offline maven repository
After downloading android studio 2.3, i keep getting this error in the event log,

```<code>      illegalStateException: Gradle plugin missing from offline maven repository
</code>```

Anyone knows how this can be fixed?

I have Gradle version 3.3, also im not sure if this is relatable to the error above but everytime i click create new project nothing at all happens, but when i click create new module and choose phone module I'am able to go through choosing name of activity but then it doesn't get created!

答:
I encountered the same problem after updating the studio plugin, unable to create a new project. I can only reinstall the solution, do not know where the problem.
https://code.google.com/p/android/issues/detail?id=221536</p>

Body:
After downloading android studio 2.3, i keep getting this error in the event log,

      illegalStateException: Gradle plugin missing from offline maven repository

Anyone knows how this can be fixed?

I have Gradle version 3.3, also im not sure if this is relatable to the error above but everytime i click create new project nothing at all happens, but when i click create new module and choose phone module I'am able to go through choosing name of activity but then it doesn't get created!


问:
Add multiple items into a ListBox from multiple TextBoxes
I want to create a basket for a product and the user enters the product name, quantity and price and then to be put into a list box on the same line. Here is what I have so far

```<code>private void addToBasket_Click(object sender, EventArgs e)
    {

        string product = productName.Text;
        decimal quan = quantity.Value;
        int quant = Convert.ToInt32(quan);
        string p = this.price.Text;
        int price = Convert.ToInt32(p);
        basket.Items.Add(new ListBoxItem(product, quan, price));
    }
}

internal class ListBoxItem
{
    private string product;
    private decimal quan;
    private int price;

    public ListBoxItem(string product, decimal quan, int price)
    {
        this.product = product;
        this.quan = quan;
        this.price = price;
    }
}
</code>```

When I click add it puts in the list box: BasketForm.ListBoxItem with no values relating to what I entered into the text box

答:
When objects are bound to a (listbox) control, said control will by default use the ToString method to display the value. You could just override said method in your ListBoxItem class to make any control display the quantity, the item name and the unit price:</p>

```<code>    public override string ToString()
    {
        return string.Format("{0}x {1} @{2}", quan, product, price);
    }
</code>```

Body:
I want to create a basket for a product and the user enters the product name, quantity and price and then to be put into a list box on the same line. Here is what I have so far

private void addToBasket_Click(object sender, EventArgs e)
    {

        string product = productName.Text;
        decimal quan = quantity.Value;
        int quant = Convert.ToInt32(quan);
        string p = this.price.Text;
        int price = Convert.ToInt32(p);
        basket.Items.Add(new ListBoxItem(product, quan, price));
    }
}

internal class ListBoxItem
{
    private string product;
    private decimal quan;
    private int price;

    public ListBoxItem(string product, decimal quan, int price)
    {
        this.product = product;
        this.quan = quan;
        this.price = price;
    }
}

When I click add it puts in the list box: BasketForm.ListBoxItem with no values relating to what I entered into the text box

Body:
When objects are bound to a (listbox) control, said control will by default use the ToString method to display the value. You could just override said method in your ListBoxItem class to make any control display the quantity, the item name and the unit price:

    public override string ToString()
    {
        return string.Format("{0}x {1} @{2}", quan, product, price);
    }


Title: How to divide array into small size chunks?

Body:
I am fetching this array in JavaScript program by ajax in every second, the response from the request takes about 3 to 4 second to be completed. Therefore I want to this array to be split in chunks but failed to complete the array was

{"m":true,
"s":true,
"q":{
"eur":{"b":"1.06783","a":"1.06790","h":"1.06978","l":"1.06729"},
"gbp":{"b":"1.24407","a":"1.24416","h":"1.25093","l":"1.24397"},
"aud":{"b":"0.76456","a":"0.76464","h":"0.76630","l":"0.76387"},
"cad":{"b":"1.33550","a":"1.33557","h":"1.33583","l":"1.33251"},
"jpy":{"b":"111.996","a":"112.002","h":"112.204","l":"111.700"},
"chf":{"b":"1.00110","a":"1.00117","h":"1.00188","l":"0.99850"},
"xau":{"b":"1241.75","a":"1242.1","h":"1244.69","l":"1239.53"},
"xag":{"b":"18.056","a":"18.098","h":"18.175","l":"18.02"},
"nok":{"b":"8.58853","a":"8.5901","h":"8.59342","l":"8.55128"},
"sek":{"b":"8.9308","a":"8.9323","h":"8.9515","l":"8.92151"},
"sgd":{"b":"1.3975","a":"1.3977","h":"1.3959","l":"1.3987"},
"pkr":{"b":"104.8300","a":"105.8300","h":"104.8300","l":"104.620"},
"dkk":{"b":"6.9645","a":"6.9648","h":"6.9500","l":"6.9691"},
"nzd":{"b":"0.69835","a":"0.69859","h":"0.70084","l":"0.69794"},
"zar":{"b":"13.3688","a":"13.37396","h":"13.6475","l":"13.232"},
"hkd":{"b":"7.77017","a":"7.77098","h":"7.77244","l":"7.76847"},
"inr":{"b":"64.8500","a":"64.8600","h":"64.925","l":"64.7800"},
"try":{"b":"3.63447","a":"3.63558","h":"3.65941","l":"3.63076"},
"pln":{"b":"3.9514","a":"3.9520","h":"3.9361","l":"3.9520"},
"cnh":{"b":"6.88261","a":"6.88352","h":"6.89029","l":"6.8706"},
"myr":{"b":"0.2255","a":"0.2265","h":"0.2253","l":"0.2257"},
"sar":{"b":"0.2662","a":"0.2672","h":"0.2662","l":"0.2662"}
}}

Please help me, I am getting stuck on this...

Body:
To split this into array chunks you can use $.map

var json = '{"m":true,"s":true,"q":{"eur":{"b":"1.06783","a":"1.06790","h":"1.06978","l":"1.06729"},"gbp":{"b":"1.24407","a":"1.24416","h":"1.25093","l":"1.24397"},"aud":{"b":"0.76456","a":"0.76464","h":"0.76630","l":"0.76387"},"cad":{"b":"1.33550","a":"1.33557","h":"1.33583","l":"1.33251"},"jpy":{"b":"111.996","a":"112.002","h":"112.204","l":"111.700"},"chf":{"b":"1.00110","a":"1.00117","h":"1.00188","l":"0.99850"},"xau":{"b":"1241.75","a":"1242.1","h":"1244.69","l":"1239.53"},"xag":{"b":"18.056","a":"18.098","h":"18.175","l":"18.02"},"nok":{"b":"8.58853","a":"8.5901","h":"8.59342","l":"8.55128"},"sek":{"b":"8.9308","a":"8.9323","h":"8.9515","l":"8.92151"},"sgd":{"b":"1.3975","a":"1.3977","h":"1.3959","l":"1.3987"},"pkr":{"b":"104.8300","a":"105.8300","h":"104.8300","l":"104.620"},"dkk":{"b":"6.9645","a":"6.9648","h":"6.9500","l":"6.9691"},"nzd":{"b":"0.69835","a":"0.69859","h":"0.70084","l":"0.69794"},"zar":{"b":"13.3688","a":"13.37396","h":"13.6475","l":"13.232"},"hkd":{"b":"7.77017","a":"7.77098","h":"7.77244","l":"7.76847"},"inr":{"b":"64.8500","a":"64.8600","h":"64.925","l":"64.7800"},"try":{"b":"3.63447","a":"3.63558","h":"3.65941","l":"3.63076"},"pln":{"b":"3.9514","a":"3.9520","h":"3.9361","l":"3.9520"},"cnh":{"b":"6.88261","a":"6.88352","h":"6.89029","l":"6.8706"},"myr":{"b":"0.2255","a":"0.2265","h":"0.2253","l":"0.2257"},"sar":{"b":"0.2662","a":"0.2672","h":"0.2662","l":"0.2662"}}}';
json = JSON.parse(json);

var arr = $.map(json.q, function(el) { return el });

console.log(arr);