问:
PHP how to move the children up to each parent
I've been stuck on this for a while now, internet has helped but I can't get it right.  I have an array listed below and I've been trying to create a new array from this one with the children in each odd number moved up to the corresponding parent.  I came close with a $new array and a counter checking if the index was odd or even and then if the odd number is true reassign the children to the current parent.

Here's the array.

```<code>Array
(
   [0] => hair-and-beauty
   [1] => Array
    (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [2] => hair-colouring
   [3] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [4] => hair-styling
   [5] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

)
</code>```

I need to get the kids like this.

```<code> Array
  (
       [0] => hair-and-beauty  => Array
         (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     [1] => hair-colouring => Array
          (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

        [2] => hair-styling  => Array
           (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     )
</code>```

My php code isn't working out right for me :(

```<code>    $new = array();
    $number = 0;
     foreach($menu as $current){
         //If number is even
         if ($number % 2 == 0) {
            array_push($new[$current]);
        }else{
            //number isnt even so go for children and add them to parent
            $new[$value['index']] = $current;
        }
        ++$number;
     }
     unset($menu);
    usort($new);

    $x = $new;
    $json=$x;
</code>```

The main array is called $menu.

Any help appreciated.

I'm steering in the direction of an array_merge

Var export :

```<code>array (
  0 => 'hair-and-beauty',
  1 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  2 => 'hair-colouring',
  3 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  4 => 'hair-styling',
  5 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
)null
</code>```

答:
Let $input be the array posted in the question.

This simple piece of code does the job:

```<code>$output = array();
foreach (array_chunk($input, 2) as $i) {
    $output[$i[0]] = array_filter($i[1]);
}
</code>```

The calls to array_filter() remove the empty entries from the arrays on even positions (the new children). Its purpose is to remove the key 0 from them (it is not present in the expected output) but it also removes other keys whose values are equivalent to FALSE.

If you want to keep all the string keys and get rid only of 0 then you can write it as:

```<code>$output = array();
foreach (array_chunk($input, 2) as $i) {
    unset($i[1][0]);
    $output[$i[0]] = $i[1];
}
</code>```

If you use PHP 5.5 or newer you can write it nicer:

```<code>$output = array();
foreach (array_chunk($input, 2) as list($k, $v)) {
    unset($v[0]);
    $output[$k] = $v;
}
</code>```

Body:
I've been stuck on this for a while now, internet has helped but I can't get it right.  I have an array listed below and I've been trying to create a new array from this one with the children in each odd number moved up to the corresponding parent.  I came close with a $new array and a counter checking if the index was odd or even and then if the odd number is true reassign the children to the current parent.

Here's the array.

Array
(
   [0] => hair-and-beauty
   [1] => Array
    (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [2] => hair-colouring
   [3] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

   [4] => hair-styling
   [5] => Array
      (
        [_business_title_0] => Hair Colouring One
        [_business_description_0] => Hair Colouring Desc
        [_business_price_0] => 22
        [_business_image_id_1] => 2351
        [_business_price_1] => 55
        [_business_description_1] => Hair Styling Desc
        [_business_title_1] => Hair Styling
        [_business_image_id_0] => 2366
        [0] =>
    )

)

I need to get the kids like this.

 Array
  (
       [0] => hair-and-beauty  => Array
         (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     [1] => hair-colouring => Array
          (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

        [2] => hair-styling  => Array
           (
            [_business_title_0] => Hair Colouring One
            [_business_description_0] => Hair Colouring Desc
            [_business_price_0] => 22
            [_business_image_id_1] => 2351
            [_business_price_1] => 55
            [_business_description_1] => Hair Styling Desc
            [_business_title_1] => Hair Styling
            [_business_image_id_0] => 2366
          )

     )

My php code isn't working out right for me :(

    $new = array();
    $number = 0;
     foreach($menu as $current){
         //If number is even
         if ($number % 2 == 0) {
            array_push($new[$current]);
        }else{
            //number isnt even so go for children and add them to parent
            $new[$value['index']] = $current;
        }
        ++$number;
     }
     unset($menu);
    usort($new);

    $x = $new;
    $json=$x;

The main array is called $menu.

Any help appreciated.

I'm steering in the direction of an array_merge

Var export :

array (
  0 => 'hair-and-beauty',
  1 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  2 => 'hair-colouring',
  3 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
  4 => 'hair-styling',
  5 =>
  array (
    '_business_title_0' => 'Hair Colouring One',
    '_business_description_0' => 'Hair Colouring Desc',
    '_business_price_0' => '22',
    '_business_image_id_1' => '2351',
    '_business_price_1' => '55',
    '_business_description_1' => 'Hair Styling Desc',
    '_business_title_1' => 'Hair Styling',
    '_business_image_id_0' => '2366',
    0 => NULL,
  ),
)null

Body:
Let $input be the array posted in the question.

This simple piece of code does the job:

$output = array();
foreach (array_chunk($input, 2) as $i) {
    $output[$i[0]] = array_filter($i[1]);
}

The calls to array_filter() remove the empty entries from the arrays on even positions (the new children). Its purpose is to remove the key 0 from them (it is not present in the expected output) but it also removes other keys whose values are equivalent to FALSE.

If you want to keep all the string keys and get rid only of 0 then you can write it as:

$output = array();
foreach (array_chunk($input, 2) as $i) {
    unset($i[1][0]);
    $output[$i[0]] = $i[1];
}

If you use PHP 5.5 or newer you can write it nicer:

$output = array();
foreach (array_chunk($input, 2) as list($k, $v)) {
    unset($v[0]);
    $output[$k] = $v;
}


来源: stackexchange

问:
I want to create an alert for the first time an app is opened
I want to create an alert for the first time an app is opened on the device but I am having some trouble with the code. this is what I have so far, any help would be appreciated </p>

```<code>    // alert first time app is opened
    // making of alert

    let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

    //add ok button
    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

    // detect if first launch
    let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
    if launchedBefore {
    }
    else {
        self.present(alert, animated: true, completion: nil)
        UserDefaults.standard.set(true, forKey: "launchedBefore")
    }
</code>```

<p>this is where I am trying to place the code </p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
</code>```

答:
If you try it in AppDelegate you have to present the alert in window?.rootViewController?

```<code>var alertController = UIAlertController(title: "Title", message: "Any message", preferredStyle: .ActionSheet)
var okAction = UIAlertAction(title: "Yes", style:
UIAlertActionStyle.Default) {
                UIAlertAction in
                NSLog("OK Pressed")
            }
var cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in
                NSLog("Cancel Pressed")
            }
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
</code>```

Check the value(true or false) you are getting in let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore"). Show alert depends on the bool value.

ContentLicense: CC BY-SA 3.0

Body:
I want to create an alert for the first time an app is opened on the device but I am having some trouble with the code. this is what I have so far, any help would be appreciated

    // alert first time app is opened
    // making of alert

    let alert = UIAlertController(title: "Navigation", message: "Tap Right Hand Side of Screen For Next Quote, Left Hand Side To Go Back", preferredStyle: UIAlertControllerStyle.alert)

    //add ok button
    alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))

    // detect if first launch
    let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore")
    if launchedBefore {
    }
    else {
        self.present(alert, animated: true, completion: nil)
        UserDefaults.standard.set(true, forKey: "launchedBefore")
    }

this is where I am trying to place the code

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

Body:
If you try it in AppDelegate you have to present the alert in window?.rootViewController?

var alertController = UIAlertController(title: "Title", message: "Any message", preferredStyle: .ActionSheet)
var okAction = UIAlertAction(title: "Yes", style:
UIAlertActionStyle.Default) {
                UIAlertAction in
                NSLog("OK Pressed")
            }
var cancelAction = UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in
                NSLog("Cancel Pressed")
            }
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

Check the value(true or false) you are getting in let launchedBefore = UserDefaults.standard.bool(forKey: "launcedBefore"). Show alert depends on the bool value.


问:
converting string representation of a date and time to the System.DateTime
```<code>DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);
</code>```

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

答:
If you look at the example given here http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
you can just use:

```<code>bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", out dt);
</code>```

Unless your looking for something more indepth you shouldn't need to use the culture/styles part.

Your trying to use http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

```<code>public static bool TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)

Parameters

s
Type: System.String
A string containing a date and time to convert.
provider
Type: System.IFormatProvider
An object that supplies culture-specific formatting information about s.
styles
Type: System.Globalization.DateTimeStyles
A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is None.
result
Type: System.DateTime%
When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uni
</code>```

ContentLicense: CC BY-SA 2.5

Body:
DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);

diditParse is returning false because it is expecting a format MM/DD/YYYY which differs from what I have DD/MM/YYYY

I am not sure what culture/styles or what needs to be do to get the try parse working?

Body:
If you look at the example given here http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
you can just use:

bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", out dt);

Unless your looking for something more indepth you shouldn't need to use the culture/styles part.

Your trying to use http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

public static bool TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)

Parameters

s
Type: System.String
A string containing a date and time to convert.
provider
Type: System.IFormatProvider
An object that supplies culture-specific formatting information about s.
styles
Type: System.Globalization.DateTimeStyles
A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is None.
result
Type: System.DateTime%
When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uni


问:
How to get all elements on same row html css
My screen looks like this:

I want everything to be on the same row. How do I fix this? My html code:

```<code>  .form-box
      %h3 Restrictions
      %legend Restricted Locations
      %fieldset.restrictions-row
        .restrictions-row.restrictions-label
          = label_tag :us_states, "US States"
        .restrictions-row.restrictions-select
          = collection_select :restriction, :category, Restriction.where(category: "US State"), :id, :name, prompt: true
          = hidden_field_tag :product_id, @wine.product.id
          = hidden_field_tag :restriction_category, "US State"
        .restrictions-row
          = button_tag "Add", class: 'btn btn-primary'
        %table.table.table-hover.table-condensed.story-list.restrictions-row
          %th{ style: 'padding: 3% 17%' } State
          %th{ style: 'padding: 3% 17%'} Remove
</code>```

my css:

```<code>  .restrictions-label {
    width: 10%;
    font-weight: bold;
  }
  .restrictions-select {
    width: 10%;
  }
  .restrictions-row {
    display: inline-block;
  }
</code>```

What is taking precedence? why isn't border-line working when I apply it to the divs?

答:
You need to add inline-block to all the elements you need to run inline, not just on the parent. The table for example, is by default display: table. You need to make that inline-block, also.

```<code>.table {
  display: inline-block;
}
</code>```

Body:
My screen looks like this:

I want everything to be on the same row. How do I fix this? My html code:

  .form-box
      %h3 Restrictions
      %legend Restricted Locations
      %fieldset.restrictions-row
        .restrictions-row.restrictions-label
          = label_tag :us_states, "US States"
        .restrictions-row.restrictions-select
          = collection_select :restriction, :category, Restriction.where(category: "US State"), :id, :name, prompt: true
          = hidden_field_tag :product_id, @wine.product.id
          = hidden_field_tag :restriction_category, "US State"
        .restrictions-row
          = button_tag "Add", class: 'btn btn-primary'
        %table.table.table-hover.table-condensed.story-list.restrictions-row
          %th{ style: 'padding: 3% 17%' } State
          %th{ style: 'padding: 3% 17%'} Remove

my css:

  .restrictions-label {
    width: 10%;
    font-weight: bold;
  }
  .restrictions-select {
    width: 10%;
  }
  .restrictions-row {
    display: inline-block;
  }

What is taking precedence? why isn't border-line working when I apply it to the divs?

Body:
You need to add inline-block to all the elements you need to run inline, not just on the parent. The table for example, is by default display: table. You need to make that inline-block, also.

.table {
  display: inline-block;
}


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
Use this instead.</p>

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  float: right;
}
</code>```

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
Use this instead.

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  float: right;
}


问:
Syntax error using => in IE
I have the following line of javascript code

```<code>var res = Object.keys(packages).filter(e => packages[e] === true)
</code>```

The above works well in all the other browser apart from IE. IE complains about Syntax erro at => can someone tell me how to get around this in IE

答:
IE doesn't support the fat arrow notation (Edge does). See http://kangax.github.io/compat-table/es6/. You need the older function notation:</p>

```<code>var res = Object.keys(packages).filter(function(e) { return packages[e] === true })
</code>```

Title: Syntax error using => in IE

Body:
I have the following line of javascript code

var res = Object.keys(packages).filter(e => packages[e] === true)

The above works well in all the other browser apart from IE. IE complains about Syntax erro at => can someone tell me how to get around this in IE

Body:
IE doesn't support the fat arrow notation (Edge does). See http://kangax.github.io/compat-table/es6/. You need the older function notation:

var res = Object.keys(packages).filter(function(e) { return packages[e] === true })


问:
How do I make these three aligning divs responsive?
On my website home page (https://abbaproperty.000webhostapp.com/) I have three divs inline that look like this:

But when viewed on a slightly smaller scree (not mobile), it looks like this:

They're no longer the same height. Although I have added some responsive CSS so it does look like this on a smaller mobile device.

So my question here is that there is a sweet spot where these divs are not displayed very well responsively and I can't think of even the logical CSS to get around this.

HTML:

```<code><div class="container" style="width:100%; background-color:#205ba0; padding:30px;">

    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>

</div>
</code>```

答:
Put

```<code><div class='row'>
</code>```

after the container class. It makes the div layer responsive
Also put class="img-responsive" on the image tag to make it responsive too

```<code><div class="container" style="width:100%; background-color:#205ba0; padding:30px;">
<div class="row">
    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>
</row>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
On my website home page (https://abbaproperty.000webhostapp.com/) I have three divs inline that look like this:

But when viewed on a slightly smaller scree (not mobile), it looks like this:

They're no longer the same height. Although I have added some responsive CSS so it does look like this on a smaller mobile device.

So my question here is that there is a sweet spot where these divs are not displayed very well responsively and I can't think of even the logical CSS to get around this.

HTML:

Renting? Landlords welcome.

        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.

        Find out more >

Valuation? Sorted quickly.

        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.

        Find out more >

Selling? Now uncomplicated.

        We aim to make selling easy. Our trained estate agents are constantly available to help.

        Find out more >

Body:
Put

<div class='row'>

after the container class. It makes the div layer responsive
Also put class="img-responsive" on the image tag to make it responsive too

<div class="container" style="width:100%; background-color:#205ba0; padding:30px;">
<div class="row">
    <div class="col-md-offset-3 col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/rent.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Renting? Landlords welcome.</h2>
        A swift liason between landlords and tenants as a fair, independeant party, is just one of our services.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/property-management/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:15px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/val.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Valuation? Sorted quickly.</h2>
        Providing some of the most effecient valuations in town, we're here to help you sort out an important step.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/valuations/" style="color:white;">Find out more ></a>
    </div>

    <div class="col-md-2" align="center" style="color:white; border:2px solid white; font-size:12px; padding:10px;">
        <div class="trip" style="background-color:white; margin-bottom:10px; padding-bottom:5px;">
            <img src="https://abbaproperty.000webhostapp.com/wp-content/uploads/2017/05/sale.png" style="height:100px;">
        </div>
        <h2 style="font-weight:bold;">Selling? Now uncomplicated.</h2>
        We aim to make selling easy. Our trained estate agents are constantly available to help.<br><br>
        <a href="https://abbaproperty.000webhostapp.com/index.php/sell/" style="color:white;">Find out more ></a>
    </div>
</row>
</div>


问:
Can somebody help me to implement extension Subject Alternative Names using BouncyCastle?
I have some string, that is separated with comma. I have to add all extension that match any of GeneralName for Subject Alternative Names extension. Can somebody finish for loop for me?

```<code>    @Override
public boolean saveKeypair(String arg0) {

    KeyPair keyPair = generateKeyPair(Integer.parseInt(access.getPublicKeyParameter()));

    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    X500Name name = new X500Name(access.getSubject());
    BigInteger serial = new BigInteger(access.getSerialNumber());
    Date notBefore = access.getNotBefore();
    Date notAfter = access.getNotAfter();
    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(name, serial, notBefore, notAfter, name,
            publicKey);

    // BEGIN extensions
    // certificate policies
    boolean isCritPol = access.isCritical(3);
    PolicyInformation[] policies = new PolicyInformation[1];
    policies[0] = new PolicyInformation(new ASN1ObjectIdentifier("2.16.840.1.101.2.1.11.5"),
            new DERSequence(new PolicyQualifierInfo(access.getCpsUri())));
    try {
        certBuilder.addExtension(Extension.certificatePolicies, isCritPol, new CertificatePolicies(policies));
    } catch (CertIOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // END CP

    // subject alternative name
    List<GeneralName> altNames = new ArrayList<GeneralName>();
    String [] altSubNames = access.getAlternativeName(5);

    for(String altName : altSubNames){
        // I NEED THIS LOOP, AND I DON'T KNOW HOW TO DO IT
    }

    // END SAN

    // END extensions

    try {
        // Content Signer
        Security.addProvider(new BouncyCastleProvider());
        ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(providerName)
                .build(privateKey);

        // Certificate
        X509Certificate certificate = new JcaX509CertificateConverter().setProvider(providerName)
                .getCertificate(certBuilder.build(sigGen));

     certificate.verify(publicKey);

        X509Certificate[] chain = new X509Certificate[1];
        chain[0] = certificate;
        keyStore.setKeyEntry(arg0, privateKey, password.toCharArray(), chain);

    } catch (OperatorCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return true;
}

// BEGIN of functions for saveKeypair

public KeyPair generateKeyPair(int keySize) {
    KeyPair keyPair = null;

    try {
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algorithm);
        keyGenerator.initialize(keySize);
        keyPair = keyGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return keyPair;
}

// END of functions for saveKeypair
</code>```

The rest of the function is working.

I am using BouncyCastle in Java. altSubName is an array, of some Strings. And those Strings should be somehow checked which of SubjectAlternativeName they are, and the Extension containing all that general names should be added.

答:
According to RFC 5280, some fields of the Subject Alternative Name extension have a defined format:

rfc822Name: format is defined in RFC 2821

ipAddress: defined in RFC 791

dnsName: RFC 1034

And so on (take a look at the RFC 5280 link, it's very detailed).

So, to know what's the field corresponding to each String, you must check if they have the format defined in each of the fields.

For rfc822Name I've found this monster regex:

```<code>String rfc822Regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
String s = "test_ad.fade@mail.com";
if (s.matches(rfc822Regex)) {
    // is valid email
}
</code>```

For the other fields, you can search regexes for each specific format. I think the only problem is the otherName field, because it can have any format (it must be specified for each Certificate Authority):

```<code>OtherName ::= SEQUENCE {
    type-id    OBJECT IDENTIFIER,
    value      [0] EXPLICIT ANY DEFINED BY type-id }
</code>```

Anyway, a generic code will be like this (assuming you already searched how to validate each of the specific formats):

```<code>// check the format and add with the correct field type
if (isValidEmail(altName)) {
    altNames.add(new GeneralName(GeneralName.rfc822Name, "user@mail.com"));
} else if (isValidDnsName(altName)) {
    altNames.add(new GeneralName(GeneralName.dNSName, "test.com"));
} else if (isValidIpAddress(altName)) {
    altNames.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
}
// ... and so on, for all GeneralName types
</code>```

Then you add the extension to certBuilder:

```<code>GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence((GeneralName[]) altNames.toArray(new GeneralName[] {})));
certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
</code>```

Body:
I have some string, that is separated with comma. I have to add all extension that match any of GeneralName for Subject Alternative Names extension. Can somebody finish for loop for me?

    @Override
public boolean saveKeypair(String arg0) {

    KeyPair keyPair = generateKeyPair(Integer.parseInt(access.getPublicKeyParameter()));

    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    X500Name name = new X500Name(access.getSubject());
    BigInteger serial = new BigInteger(access.getSerialNumber());
    Date notBefore = access.getNotBefore();
    Date notAfter = access.getNotAfter();
    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(name, serial, notBefore, notAfter, name,
            publicKey);

    // BEGIN extensions
    // certificate policies
    boolean isCritPol = access.isCritical(3);
    PolicyInformation[] policies = new PolicyInformation[1];
    policies[0] = new PolicyInformation(new ASN1ObjectIdentifier("2.16.840.1.101.2.1.11.5"),
            new DERSequence(new PolicyQualifierInfo(access.getCpsUri())));
    try {
        certBuilder.addExtension(Extension.certificatePolicies, isCritPol, new CertificatePolicies(policies));
    } catch (CertIOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // END CP

    // subject alternative name
    List<GeneralName> altNames = new ArrayList<GeneralName>();
    String [] altSubNames = access.getAlternativeName(5);

    for(String altName : altSubNames){
        // I NEED THIS LOOP, AND I DON'T KNOW HOW TO DO IT
    }

    // END SAN

    // END extensions

    try {
        // Content Signer
        Security.addProvider(new BouncyCastleProvider());
        ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(providerName)
                .build(privateKey);

        // Certificate
        X509Certificate certificate = new JcaX509CertificateConverter().setProvider(providerName)
                .getCertificate(certBuilder.build(sigGen));

     certificate.verify(publicKey);

        X509Certificate[] chain = new X509Certificate[1];
        chain[0] = certificate;
        keyStore.setKeyEntry(arg0, privateKey, password.toCharArray(), chain);

    } catch (OperatorCreationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return true;
}

// BEGIN of functions for saveKeypair

public KeyPair generateKeyPair(int keySize) {
    KeyPair keyPair = null;

    try {
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algorithm);
        keyGenerator.initialize(keySize);
        keyPair = keyGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return keyPair;
}

// END of functions for saveKeypair

The rest of the function is working.

I am using BouncyCastle in Java. altSubName is an array, of some Strings. And those Strings should be somehow checked which of SubjectAlternativeName they are, and the Extension containing all that general names should be added.

Body:
According to RFC 5280, some fields of the Subject Alternative Name extension have a defined format:

rfc822Name: format is defined in RFC 2821

ipAddress: defined in RFC 791

dnsName: RFC 1034

And so on (take a look at the RFC 5280 link, it's very detailed).

So, to know what's the field corresponding to each String, you must check if they have the format defined in each of the fields.

For rfc822Name I've found this monster regex:

String rfc822Regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
String s = "test_ad.fade@mail.com";
if (s.matches(rfc822Regex)) {
    // is valid email
}

For the other fields, you can search regexes for each specific format. I think the only problem is the otherName field, because it can have any format (it must be specified for each Certificate Authority):

OtherName ::= SEQUENCE {
    type-id    OBJECT IDENTIFIER,
    value      [0] EXPLICIT ANY DEFINED BY type-id }

Anyway, a generic code will be like this (assuming you already searched how to validate each of the specific formats):

// check the format and add with the correct field type
if (isValidEmail(altName)) {
    altNames.add(new GeneralName(GeneralName.rfc822Name, "user@mail.com"));
} else if (isValidDnsName(altName)) {
    altNames.add(new GeneralName(GeneralName.dNSName, "test.com"));
} else if (isValidIpAddress(altName)) {
    altNames.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
}
// ... and so on, for all GeneralName types

Then you add the extension to certBuilder:

GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence((GeneralName[]) altNames.toArray(new GeneralName[] {})));
certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);


问:
Comparing array value with object
Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

If id in a matches id in b then print out the id's group value

```<code>var a = [];
var b = [];
var c = {};

if (condition) {
   c  = {id:group}
   b.push(c)

}

if (condition) {
   a.push(id)

}

for (var i = 0; i < a.length; i++) {
   //If id value in a exists in b, get id's corresponding group value from b
}
</code>```

答:
```<code>function find() {
   for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < b.length; j++) {
         if (b[j].hasOwnProperty(a[i])) {
            return b[j][a[i]];
         }
      }
   }
}
</code>```

Title: Comparing array value with object

Body:
Would be really grateful for any help. Im pretty new to javascript and cant figure out how to solve this problem that I am having. Basically I have 2 arrays. One contains an object with an id value and a corresponding group value. The second array contains only the id. I would like to compare the ids of both the arrays and if they match I would like to extract the corresponding group value.

E.g.

a = [1,2,3,4,5];

b = [{1:group1},{2:group2},{3:group3}];

If id in a matches id in b then print out the id's group value

var a = [];
var b = [];
var c = {};

if (condition) {
   c  = {id:group}
   b.push(c)

}

if (condition) {
   a.push(id)

}

for (var i = 0; i < a.length; i++) {
   //If id value in a exists in b, get id's corresponding group value from b
}


问:
Drilldown multiple levels Highchart
We like to Drilldown on multiple levels in Highchart. Is there already an example in Highchart?

Currently used code:

```<code>$(div).highcharts({
    chart: {type: 'column'},
    credits: {enabled: false},
    title: {text: title},
    xAxis: {
        categories: [
            'Instroom',
            'Rijdend',
            'Úitstroom'
        ]
    },
    yAxis: {title: {text: ytitle}},
    legend: {enabled: true},
    plotOptions: {series: { borderWidth: 1, dataLabels: {enabled: true,}}},
    series: first,
    drilldown: {
        series: drillDownObject(second)
    }
});
</code>```

答:
Here is an example that preserves the names on the axis.
(Drilldown works on "Animals" > "Mammals")

Drilldown options looks like this:

```<code>drilldown: {
  series: [{
    id: 'animals',
    data: [{
        name: 'Mammals',
        y: 4,
        drilldown: 'mammals'
      },
      ['Reptiles', 2],
      ['Vertebrates', 1]
    ]
  }, {
    id: 'mammals',
    data: [['Cats', 3], ['Dogs', 2], ['Platypus', 1]]
  },
  ...
</code>```

http://jsfiddle.net/vcsqnr2z/

Title: Drilldown multiple levels Highchart

Body:
We like to Drilldown on multiple levels in Highchart. Is there already an example in Highchart?

Currently used code:

$(div).highcharts({
    chart: {type: 'column'},
    credits: {enabled: false},
    title: {text: title},
    xAxis: {
        categories: [
            'Instroom',
            'Rijdend',
            'Úitstroom'
        ]
    },
    yAxis: {title: {text: ytitle}},
    legend: {enabled: true},
    plotOptions: {series: { borderWidth: 1, dataLabels: {enabled: true,}}},
    series: first,
    drilldown: {
        series: drillDownObject(second)
    }
});

Body:
Here is an example that preserves the names on the axis.
(Drilldown works on "Animals" > "Mammals")

Drilldown options looks like this:

drilldown: {
  series: [{
    id: 'animals',
    data: [{
        name: 'Mammals',
        y: 4,
        drilldown: 'mammals'
      },
      ['Reptiles', 2],
      ['Vertebrates', 1]
    ]
  }, {
    id: 'mammals',
    data: [['Cats', 3], ['Dogs', 2], ['Platypus', 1]]
  },
  ...

http://jsfiddle.net/vcsqnr2z/


答: Try "en-GB" we list our dates DD-MM-YY, instead of MM-DD-YY like they do in the US.</p>

Title: converting string representation of a date and time to the System.DateTime


问:
Using SPFile.OpenBinary() fails with "Cannot open file". StoragePoint RBS issue?
I'm trying to restore a file from a backup content database in SharePoint 2016 by using the Get-SPContentDatabase -ConnectAsUnattachedDatabase and drilling down to the item level to use the OpenBinary() call. I believe this is failing because the BLOB is externalized via StoragePoint, but I'm not sure how to allow this command to access the external BLOB data. Any ideas on what permissions might be necessary? The BLOB and endpoint still exist in SharePoint and on the file share and I am successfully able to see the item and its properties within PowerShell.

I found a similar issue where the OP said they solved it by giving explicit permissions to the StoragePoint databases, but Imm not sure what permissions or which databases need them. listItem.File.OpenBinary()  not working - Remote Blob Storage / FileStreaming not enabled on SQL Server the culprit?

答: I was able to figure this out. I was testing from a server that didn't have the full StoragePoint installation. Testing the same call from one of the web servers in the farm I was able to open and download the file.</p>


问:
unable to connect database : Codeigniter
I have noticed some unexpected behavior while connecting MySQL Codeigniter

Here is scenario:

-> I configured database library for autoload. (config/autoload.php)

```<code>$autoload['libraries'] = array('database', 'session');
</code>```

-> But after configuring that, I can't open anything. I mean to say, Controller or View.

Have I done something wrong?

```<code>$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'password';
$db['default']['database'] = 'myfamilyfirst';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = FALSE;
$db['default']['stricton'] = FALSE;
</code>```

I tried to set $db['default']['autoinit'] = TRUE; to $db['default']['autoinit'] = FALSE;

Now I can open the pages but unable to connect the database.

Please help.

答:
In codeignator latest version we need to connect database using Mysqli. So in database file you need to give database driver as mysqli like this,</p>

```<code>$db['default']['dbdriver'] = 'mysqli';
</code>```

Body:
I have noticed some unexpected behavior while connecting MySQL Codeigniter

Here is scenario:

-> I configured database library for autoload. (config/autoload.php)

$autoload['libraries'] = array('database', 'session');

-> But after configuring that, I can't open anything. I mean to say, Controller or View.

Have I done something wrong?

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = 'password';
$db['default']['database'] = 'myfamilyfirst';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = FALSE;
$db['default']['stricton'] = FALSE;

I tried to set $db['default']['autoinit'] = TRUE; to $db['default']['autoinit'] = FALSE;

Now I can open the pages but unable to connect the database.

Please help.

Body:
In codeignator latest version we need to connect database using Mysqli. So in database file you need to give database driver as mysqli like this,

$db['default']['dbdriver'] = 'mysqli';


问:
How to enable the Google Compute Engine API using python APIs
I am trying to create a project, launch a VM and start a service on Google Compute Engine. I could create a new project however right now I need to manually enable the Compute Engine API by visiting the following page: https://console.developers.google.com/apis/api/compute-component.googleapis.com/overview?project=

Is there any way to enable the APIs programatically?

答:
You need to add the scope "https://www.googleapis.com/auth/compute" to the scopes of the serviceAccount you are using. I do not know how that is done in the Python API but if you go to https://console.cloud.google.com/compute/ and manually add an instance there is an option "Set access for each API" under "Indentity and API access" and "Access scopes". Then select the compute engine API and click the the link at the bottom at the page "Equivalent Rest" to see what the REST request would be to do the same using REST.

You should then probably quite easily be able to translate the same to the Python API.

The documentation is here.


问:
Nodejs Express query mongolab for a single entry using data from a form
I am a Nodejs newbie and am trying to search my mongolab database for an entry(that I know exists) using data from a form entry. Here is my code:

```<code>var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.all('/addUser', function(req, res) {
    res.render('addUser');
    db.collection('users').save(req.body, function(err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
    })
    console.log(req.body);
});

app.get('/outputAll', function(req, res) {
    db.collection('users').find().toArray(function (err, result) {
    if (err) return console.log(err);
    res.render('outputall', {users:result});
    });
});

app.get('/Search', function(req, res) {
    res.render('search');
    var query = {}
    console.log(req.body);
    if (req.body.username)
    {
    console.log("true");
    query.username = req.body.username;
    }
    db.collection('users').find({query}).toArray(function(err, result) {
    if (err) return console.log(err);
    console.log(1);
    });
});
</code>```

The search part is meant to accomplish this objective. But I am not sure how to collect the query from my input form and pass it to the this app.get and have it passed to the database where it is searched. Here is the Search ejs file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
    <div style="margin: 0 auto;width: 500px;">
    <form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">
        <!-- <input type="file" name="picture"> -->
        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
    </form>
    </div>
</body>
</html>
</code>```

The output on the console when I run this is:

Server started at port:3000

{}

[]

{}

[]

I was expecting the {} to be the form data and the [] to be the result of searching the query in the database.
Please help!

----------------EDIT-----------------

The response I am receiving after changing the form method to post is :

```<code>Request body  = undefined
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
Request body  = abc
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
</code>```

I have changed the add.get('Search',fn) to :

```<code>app.all('/Search', function(req, res) {
    res.render('search');
    db.collection('users').find().toArray(function(err, result) {
    if (err) return console.log(err);
    var query = {}
    console.log("Request body  = "+req.body.username);
    // if (req.body.username)
    // {
    //     console.log(req.body);
    //     query.username = req.body.username;
    // }

    console.log(result);
    });
});
</code>```

答:
The /Search request you're making is using GET request & not the POST. If you want to access form data through request body I suggest you use POST method or else access url parameters for GET method.

After receiving data you can then format it for the query by creating an object.

Body:
I am a Nodejs newbie and am trying to search my mongolab database for an entry(that I know exists) using data from a form entry. Here is my code:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.all('/addUser', function(req, res) {
    res.render('addUser');
    db.collection('users').save(req.body, function(err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
    })
    console.log(req.body);
});

app.get('/outputAll', function(req, res) {
    db.collection('users').find().toArray(function (err, result) {
    if (err) return console.log(err);
    res.render('outputall', {users:result});
    });
});

app.get('/Search', function(req, res) {
    res.render('search');
    var query = {}
    console.log(req.body);
    if (req.body.username)
    {
    console.log("true");
    query.username = req.body.username;
    }
    db.collection('users').find({query}).toArray(function(err, result) {
    if (err) return console.log(err);
    console.log(1);
    });
});

The search part is meant to accomplish this objective. But I am not sure how to collect the query from my input form and pass it to the this app.get and have it passed to the database where it is searched. Here is the Search ejs file:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>MY APP</title>

    <form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">

        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
    </form>

The output on the console when I run this is:

Server started at port:3000

{}

[]

{}

[]

I was expecting the {} to be the form data and the [] to be the result of searching the query in the database.
Please help!

----------------EDIT-----------------

The response I am receiving after changing the form method to post is :

Request body  = undefined
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
Request body  = abc
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]

I have changed the add.get('Search',fn) to :

app.all('/Search', function(req, res) {
    res.render('search');
    db.collection('users').find().toArray(function(err, result) {
    if (err) return console.log(err);
    var query = {}
    console.log("Request body  = "+req.body.username);
    // if (req.body.username)
    // {
    //     console.log(req.body);
    //     query.username = req.body.username;
    // }

    console.log(result);
    });
});


问:
Cannot add the msExchArchiveGUID in Powershell
I cannot add the GUID value for msExchArchiveGUID in powershell. Error reports of "constraint violation" or "A value for the attribute was not in the acceptable range of values" depending on which powershell cmdlet is used. From what I can tell the value that needs to be input needs to be up to 16 characters. Anything more and it errors. For example, the GUID value I need to write is 5C669E441173CF4394995E43EC8ED9ED. When pasted using ADSIEdit the output looks like: 5C 66 9E 44 11 73 CF 43 94 99 5E 43 EC 8E D9 ED. If I add the same value using Powershell it errors. How can I write the value in Powershell to give the same result like adding using ADSIEdit?
E.g
Set-aduser -identity "someone" -add @{msExchArchiveGUID="A format the works!
"}

答:
The solution is a bit convoluted (and probably obvious to all but me!) which I will show below.. I'm sure a more concise answer is out there..

I get the GUID value using quest (rather that get-remotemailbox)

```<code>Get-QADUser -Service domain -Identity someone -IncludeAllProperties|select msExchArchiveGUID

    This presents the archive GUID as 5C669E441173CF4394995E43EC8ED9ED

    So.....
    $oct = "5C669E441173CF4394995E43EC8ED9ED"
    $oct1 = $oct.substring(0,2)
    $oct2 = $oct.substring(2,2)
    $oct3 = $oct.substring(4,2)
    $oct4 = $oct.substring(6,2)
    $oct5 = $oct.substring(8,2)
    $oct6 = $oct.substring(10,2)
    $oct7 = $oct.substring(12,2)
    $oct8 = $oct.substring(14,2)
    $oct9 = $oct.substring(16,4)
    $oct10 = $oct.substring(20,12)

    $strOut = "$oct4" + "$oct3" + "$oct2" + "$oct1" + "-" + "$oct6" + "$oct5" + "-" + "$oct8" + "$oct7" + "-" + "$oct9" + "-" + "$oct10"
</code>```

Output is "449E665C-7311-43CF-9499-5E43EC8ED9ED"

```<code>    $Id = [GUID]("449e665c-7311-43cf-9499-5e43ec8ed9ed")
    Set-ADUser -Identity $IPGUser -Clear msexcharchiveGUID
    Set-ADUser User -Add @{msexchArchiveGUId=$id}
</code>```

Body:
The solution is a bit convoluted (and probably obvious to all but me!) which I will show below.. I'm sure a more concise answer is out there..

I get the GUID value using quest (rather that get-remotemailbox)

Get-QADUser -Service domain -Identity someone -IncludeAllProperties|select msExchArchiveGUID

    This presents the archive GUID as 5C669E441173CF4394995E43EC8ED9ED

    So.....
    $oct = "5C669E441173CF4394995E43EC8ED9ED"
    $oct1 = $oct.substring(0,2)
    $oct2 = $oct.substring(2,2)
    $oct3 = $oct.substring(4,2)
    $oct4 = $oct.substring(6,2)
    $oct5 = $oct.substring(8,2)
    $oct6 = $oct.substring(10,2)
    $oct7 = $oct.substring(12,2)
    $oct8 = $oct.substring(14,2)
    $oct9 = $oct.substring(16,4)
    $oct10 = $oct.substring(20,12)

    $strOut = "$oct4" + "$oct3" + "$oct2" + "$oct1" + "-" + "$oct6" + "$oct5" + "-" + "$oct8" + "$oct7" + "-" + "$oct9" + "-" + "$oct10"

Output is "449E665C-7311-43CF-9499-5E43EC8ED9ED"

    $Id = [GUID]("449e665c-7311-43cf-9499-5e43ec8ed9ed")
    Set-ADUser -Identity $IPGUser -Clear msexcharchiveGUID
    Set-ADUser User -Add @{msexchArchiveGUId=$id}


问:
VSTO: Iterating through Outlook inbox raises error when non-mail items appears
I have some code in Visual Studio (VSTO + VB.Net) that shall iterate through all items in my Outlook Inbox. The code works fine until there are other items in my Inbox, such as appointments etc.

The code below is simplified and iterates through all items in a sorted list. The problem occurs when FolderItem (of type MailItem) is assigned with an item that is of other types, e.g. MeetingItemClass. An exception is raised.

I understand why... But I need a solution on how to find a workaround. I want to process ALL items, even meeting items.

```<code>Dim InboxFolder As Outlook.MAPIFolder
Dim FolderItem As Outlook.MailItem
Dim FolderItems As Outlook.Items
Dim ItemNo As Integer

*** removed code that finds the inbox object 'InboxFolder' ***

ItemNo = 1
FolderItems = InboxFolder.Items
FolderItems.Sort("[ReceivedTime]", True)

Do While ItemNo <= FolderItems.Count
    FolderItem = FolderItems(ItemNo)

    *** Do some operations on each inbox-object here ***

    ItemNo = ItemNo + 1
Loop
</code>```

答:
A possiblility is to define FolderItem As Object and then...

...check the type before assigning it to a variable of the specific type

AND

...cast it to the specific type in your while loop if necessary

Something like this (not tested):

```<code>If TypeOf FolderItem Is MailItem Then
   Dim mailItm As MailItem = DirectCast(FolderItem, MailItem)
   'Do something
ElseIf TypeOf FolderItem Is MeetingItem Then
   Dim meetItm As MeetingItem = DirectCast(FolderItem, MeetingItem)
   'Do something
End If
</code>```

Body:
I have some code in Visual Studio (VSTO + VB.Net) that shall iterate through all items in my Outlook Inbox. The code works fine until there are other items in my Inbox, such as appointments etc.

The code below is simplified and iterates through all items in a sorted list. The problem occurs when FolderItem (of type MailItem) is assigned with an item that is of other types, e.g. MeetingItemClass. An exception is raised.

I understand why... But I need a solution on how to find a workaround. I want to process ALL items, even meeting items.

Dim InboxFolder As Outlook.MAPIFolder
Dim FolderItem As Outlook.MailItem
Dim FolderItems As Outlook.Items
Dim ItemNo As Integer

*** removed code that finds the inbox object 'InboxFolder' ***

ItemNo = 1
FolderItems = InboxFolder.Items
FolderItems.Sort("[ReceivedTime]", True)

Do While ItemNo <= FolderItems.Count
    FolderItem = FolderItems(ItemNo)

    *** Do some operations on each inbox-object here ***

    ItemNo = ItemNo + 1
Loop

Body:
A possiblility is to define FolderItem As Object and then...

...check the type before assigning it to a variable of the specific type

AND

...cast it to the specific type in your while loop if necessary

Something like this (not tested):

If TypeOf FolderItem Is MailItem Then
   Dim mailItm As MailItem = DirectCast(FolderItem, MailItem)
   'Do something
ElseIf TypeOf FolderItem Is MeetingItem Then
   Dim meetItm As MeetingItem = DirectCast(FolderItem, MeetingItem)
   'Do something
End If


答:
CanIUse: Arrow function You cannot use it in IE;</p>

```<code>var res = Object.keys(packages).filter(function(e) = {return packages[e] === true})
</code>```

Title: Syntax error using => in IE

Body:
CanIUse: Arrow function You cannot use it in IE;

var res = Object.keys(packages).filter(function(e) = {return packages[e] === true})


问:
How can I apply a class from one directive to another in angularjs?
How to add a class from toggleClass directive to Header directive without using a jQuery selector? Not sure how I can do this in AngularJS, is directive to directive communication needed in this case?

```<code><Header></Header>

<toggleClass></toggleClass>
</code>```

in toggleClass directive I have:

```<code>module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            // add class to Header directive
          }
    }
  }
};
</code>```

and its template:

```<code><div ng-click="expandToggle()">
  <span class="collapseText">Collapse</span>
  <span class="expandText">Expand</span>
</div>
</code>```

答:
1'st way: use $emit

You can $emit event from toggleClass directive to parent controller, and change boolean value to control adding/removing your class.

ToggleClass directive:

```<code>module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            scope.$emit('toggle');
          }
    }
  }
};
</code>```

Parent controller:

```<code>angular
  .module('yourModule')
  .controller('YourController', ['$scope', YourController]);

function YourController($scope) {
  $scope.$on('toggle', function() {
    $scope.apllyNeededClass = true;
  })
}
</code>```

Your HTML:

```<code><Header ng-class="{'classToApply': apllyNeededClass}"></Header>

<toggleClass></toggleClass>
</code>```

2'nd way: use service

You can use services for sharing data between controllers (directive and controller in your case).

ToggleClass directive:

```<code>module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            yourService.apllyNeededClass = true;
            // don't forget to inject "yourService" in this directive
          }
    }
  }
};
</code>```

Parent controller:

```<code>angular
  .module('yourModule')
  .controller('YourController', ['$scope', 'yourService', YourController]);

function YourController($scope, yourService) {
  $scope.apllyNeededClass = yourService.apllyNeededClass;
  // bind service variable to your $scope variable
}
</code>```

Your HTML:

```<code><Header ng-class="{'classToApply': apllyNeededClass}"></Header>

<toggleClass></toggleClass>
</code>```

P.S.

I'm using ng-class on  tag just for example and because I don't know the template of your Header directive.

Body:
How to add a class from toggleClass directive to Header directive without using a jQuery selector? Not sure how I can do this in AngularJS, is directive to directive communication needed in this case?

<toggleClass></toggleClass>

in toggleClass directive I have:

module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            // add class to Header directive
          }
    }
  }
};

and its template:

  Collapse
  Expand

Body:
1'st way: use $emit

You can $emit event from toggleClass directive to parent controller, and change boolean value to control adding/removing your class.

ToggleClass directive:

module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            scope.$emit('toggle');
          }
    }
  }
};

Parent controller:

angular
  .module('yourModule')
  .controller('YourController', ['$scope', YourController]);

function YourController($scope) {
  $scope.$on('toggle', function() {
    $scope.apllyNeededClass = true;
  })
}

Your HTML:

<Header ng-class="{'classToApply': apllyNeededClass}"></Header>

<toggleClass></toggleClass>

2'nd way: use service

You can use services for sharing data between controllers (directive and controller in your case).

ToggleClass directive:

module.exports = Directive;
function Directive(){
  return {
    restrict: 'E',
    templateUrl: '/vic-compare-quotes-expand/templates/directive.html',
    link : function(scope, element){
          scope.expandToggle = function() {
            yourService.apllyNeededClass = true;
            // don't forget to inject "yourService" in this directive
          }
    }
  }
};

Parent controller:

angular
  .module('yourModule')
  .controller('YourController', ['$scope', 'yourService', YourController]);

function YourController($scope, yourService) {
  $scope.apllyNeededClass = yourService.apllyNeededClass;
  // bind service variable to your $scope variable
}

Your HTML:

<Header ng-class="{'classToApply': apllyNeededClass}"></Header>

<toggleClass></toggleClass>

P.S.

I'm using ng-class on <Header> tag just for example and because I don't know the template of your Header directive.


问:
WKWebView interacting with JS in swift3 crashed strangely
I have a viewController in which I created a WKWebView, here is one of the delegate methods:

```<code>func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    let model = SwiftJSModel()

    self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext

    model.jsContext = self.jsContext

    self.jsContext.setObject(model, forKeyedSubscript: "modelObject" as NSCopying & NSObjectProtocol)

}
</code>```

however, my app will crash after this webView has been loaded, the console shows:

```<code>reason: '[<WKWebView 0x7fc41d9c7200> valueForUndefinedKey:]: this class is not key value coding-compliant for the key documentView.'
</code>```

It seems that webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") doesn't work in swift3, does somebody know why?

答:
It seems that WKWebView cannot get the JSContext,
 here is where I found it: How to get JSContext from WKWebView

Body:
I have a viewController in which I created a WKWebView, here is one of the delegate methods:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    let model = SwiftJSModel()

    self.jsContext = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext

    model.jsContext = self.jsContext

    self.jsContext.setObject(model, forKeyedSubscript: "modelObject" as NSCopying & NSObjectProtocol)

}

however, my app will crash after this webView has been loaded, the console shows:

reason: '[<WKWebView 0x7fc41d9c7200> valueForUndefinedKey:]: this class is not key value coding-compliant for the key documentView.'

It seems that webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") doesn't work in swift3, does somebody know why?


问:
Nhibernate order of SQL statements when flushing session
According to NHibernate documentation, SQL statements are issued in the following order when a session is flushed:

all entity insertions, in the same order the corresponding objects were saved using ISession.Save()

all entity updates

all collection deletions

all collection element deletions, updates and insertions

all collection insertions

all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete()

Why is it forced in this order and is there any way to change it so that the statements are executed in the same order that I give them?

答:
It's in that order because it's the safest.

And no, you can't change the order. But also, you never gave NHibernate any order: you just mark entities for persistence; NHibernate determines what to do automatically.

If you think you need more control over individual SQL operations, you can use IStatelessSession instead of a regular ISession. You lose all the stuff NH does automatically (lazy loading, caching, dirty-tracking), but you can (must) say explicitly when to Insert, Delete or Update a record.


问:
How to change button color when radio input is selected, but input is wrapped in div before label?
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5942" onclick="">

    <div class="donation-level-amount-container">
    $35.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5943" onclick="">

    <div class="donation-level-amount-container">
    $60.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
  </div>
</div>
<div class="donation-level-container">
  <div class="form-content">

    <div class="donation-level-input-container form-input">

      <div class="donation-level-label-input-container">
        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
      </div>

      <label for="level_flexibleexpanded5944" onclick="">

    <div class="donation-level-amount-container">
    $120.00
    </div>

    </label>

    </div>

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
  </div>
</div></code>```

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

答:
Indeed, this can not be done with pure CSS, since you can't traverse upward in the DOM using CSS selectors. As previous answers mentioned, it can easily be done with jQuery, but it can also be done in vanilla javascript.

```<code>var donationButtons = document.querySelectorAll('.donation-level-amount-container');
var defaultBg = '#1a92b4';
var activeBg = '#f00';

donationButtons.forEach(function(btn){
    btn.onclick = function(){
        donationButtons.forEach(function(btn){
            // deselect previously selected buttons
            btn.style.background = defaultBg;
        });
        this.style.background = activeBg;
    }
});
</code>```

I'm certain this can be done smoother, but this is the first solution that popped up in my head.

Body:
I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.

Here is my fiddle: https://jsfiddle.net/cgz63qhd/

body {
  padding: 10px;
  font-family: sans-serif;
}

div.donation-levels {
  margin: 3px 0;
}

.donation-level-container {
  display: inline-block;
}

.donation-level-container input {
  visibility: hidden;
}

.donation-level-amount-container {
  text-align: center;
  margin: 5px 2px;
  padding: 0.7em 2em;
  color: #ffffff;
  background-color: #1a92b4;
  border-radius: 5px;
  display: inline-block;
  cursor: pointer;
  font-size: 22px;
}

.donation-level-amount-container:hover {
  background: #e8525f;
  color: #ffffff;
}

.donation-level-label-input-container input:checked~label {
  background: #e8525f;
}

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">

    $35.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">

    $60.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">

        <input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">

    $120.00

    <input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">

Here is my inspiration donate page: https://action.audubon.org/donate/now

Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).

My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?

I've seen a lot of questions here on this topic but I can't seem to get anything to work.

I'm sure there are other issues in the code, please point them out if you see them!

Body:
Indeed, this can not be done with pure CSS, since you can't traverse upward in the DOM using CSS selectors. As previous answers mentioned, it can easily be done with jQuery, but it can also be done in vanilla javascript.

var donationButtons = document.querySelectorAll('.donation-level-amount-container');
var defaultBg = '#1a92b4';
var activeBg = '#f00';

donationButtons.forEach(function(btn){
    btn.onclick = function(){
        donationButtons.forEach(function(btn){
            // deselect previously selected buttons
            btn.style.background = defaultBg;
        });
        this.style.background = activeBg;
    }
});

I'm certain this can be done smoother, but this is the first solution that popped up in my head.


问:
Could NFS be mounted on one of openstack swift storage node?
Currently, I got one CentOS in virtual box with openstack swift running which is installed by SAIO.

Question: Data would not stored in the node which I mount nfs.

For example, I create a container by curl, the output returns 201. But there is no data in the mounted directory. I refer to file  /var/log/swift/proxy.error, and it shows

Error Insufficient storage balabala...

Would anyone help figure why this happens and how to fix it?

Thanks in advance!

Sure, there are some logs about the mounted node.
By following the SAIO guide, the configurations remain almost the same except the ${USER}. I use 'osddev' for the user name and group name.

/dev/sdb1 on /mnt/sdb1 type xfs (rw,noatime,nodiratime,seclabel,attr2,nobarrier,inode64,logbufs=8,noquota)

And I got 4 directories under /mnt/sdb1 named 1, 2, 3 and 4 respectively.
I mounted nfs on the directory '2',

I mount like this:

mount.nfs 192.168.0.1:/mnt/path/to/mount /mnt/sdb1/2

and the output of command 'mount' is like

192.168.0.1:/mnt/path/to/mount on /mnt/sdb1/2 type nfs4(rw,relatime,vers=4.0,rsize=1048576,wsize=1048576,namlen=...,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.0.2,local_lock=none,addr=192.168.0.1)

The structure of the folder of 'mnt' is like this:

/mnt/sdb1
      /1
          /node
              /sdb1
                  /accounts
              /containers
                  /objects
                  /tmp
      /2
          /node
              /sdb2
                  /containers
                  /tmp
      /3
          /node
              /sdb3
                  /accounts
                  /containers
                  /objects
                  /tmp
      /4
          /node
              /sdb4
                  /accounts
                  /containers
                  /objects
                  /tmp

When the mount was done, I tried to create a new container, and it returned 201 created, and there was a db file name '48ce59400b16f806fe2fee7e40e236as.db' and another file named '48ce59400b16f806fe2fee7e40e236as.db.pending' under the directory /mnt/sdb1/2/node/sdb2/containers/291/6ab/48ce59400b16f806fe2fee7e40e236as which was the same as other directoies under /mnt/sdb1.

When I tried to create a new object, there was 'objects' directory under /mnt/sdb1/2/node/sdb1. But in other directories like /mnt/sdb1/1 or /mnt/sdb1/3, the 'objects' directory existed.

So I checked out the error log under /var/log/swift.
And I found that in logs 'proxy.error' and 'storage2.error', there were some errors, I'll list them below:

proxy.error:

Jun  8 17:26:33 localhost proxy-server: Started child 4024
  Jun  8 17:27:04 localhost proxy-server: STDERR: (4024) wsgi starting up on http://127.0.0.1:8080/
  Jun  8 17:28:22 localhost proxy-server: STDERR: (4024) accepted ('127.0.0.1', 57718)
  Jun  8 17:28:22 localhost proxy-server: STDERR: 127.0.0.1 - - [08/Jun/2017 09:28:22] "GET /auth/v1.0 HTTP/1.1" 200 356 0.004022 (txn: tx016fa30128e74197af806-00593918b6)
  Jun  8 17:29:39 localhost proxy-server: STDERR: (4024) accepted ('127.0.0.1', 57721)
  Jun  8 17:29:41 localhost proxy-server: ERROR Insufficient Storage 127.0.0.1:6020/sdb2 (txn: tx45826ac5bc284bd8b15a6-0059391903)
  Jun  8 17:29:41 localhost proxy-server: STDERR: 127.0.0.1 - - [08/Jun/2017 09:29:41] "PUT /v1/AUTH_test/annecontainer/annefile3 HTTP/1.1" 201 254 1.474424 (txn: tx45826ac5bc284bd8b15a6-0059391903)

storage2.error

Jun  8 17:26:31 localhost account-server: Started child 4004
  Jun  8 17:26:31 localhost container-server: Started child 4007
  Jun  8 17:26:32 localhost object-server: Started child 4016
  Jun  8 17:27:03 localhost object-server: STDERR: (4016) wsgi starting up on 127.0.0.1:6020/
  Jun  8 17:27:03 localhost account-server: STDERR: (4004) wsgi starting up on 127.0.0.1:6022/
  Jun  8 17:27:03 localhost container-server: STDERR: (4007) wsgi starting up on 127.0.0.1:6021/
  Jun  8 17:29:39 localhost object-server: STDERR: (4016) accepted ('127.0.0.1', 43279)
  Jun  8 17:29:40 localhost object-server: STDERR: ERROR:root:Filesystem at 9 does not support xattr#012Traceback (most recent call last):#012  File "/home/osddev/swift/swift/obj/diskfile.py", line 150, in write_metadata#012    metastr[:xattr_size])#012  File "/usr/lib64/python2.7/site-packages/xattr-0.9.1-py2.7-linux-x86_64.egg/xattr/init.py", line 185, in setxattr#012    return xattr(f).set(attr, value, options=options)#012  File "/usr/lib64/python2.7/site-packages/xattr-0.9.1-py2.7-linux-x86_64.egg/xattr/init.py", line 78, in set#012    return self._call(_setxattr, _fsetxattr, name, value, 0, options | self.options)#012  File "/usr/lib64/python2.7/site-packages/xattr-0.9.1-py2.7-linux-x86_64.egg/xattr/init.py", line 58, in _call#012    return fd_func(self.value, *args)#012  File "/usr/lib64/python2.7/site-packages/xattr-0.9.1-py2.7-linux-x86_64.egg/xattr/lib.py", line 106, in _fsetxattr#012    raise error()#012  File "/usr/lib64/python2.7/site-packages/xattr-0.9.1-py2.7-linux-x86_64.egg/xattr/lib.py", line 48, in error#012    raise IOError(errno, strerror)#012IOError: [Errno 95] Operation not supported
  Jun  8 17:29:41 localhost container-server: STDERR: (4007) accepted ('127.0.0.1', 45775)
  Jun  8 17:29:41 localhost object-server: STDERR: 127.0.0.1 - - [08/Jun/2017 09:29:41] "PUT /sdb2/957/AUTH_test/annecontainer/annefile3 HTTP/1.1" 507 263 1.300362 (txn: tx45826ac5bc284bd8b15a6-0059391903)
  Jun  8 17:29:41 localhost container-server: STDERR: 127.0.0.1 - - [08/Jun/2017 09:29:41] "PUT /sdb2/291/AUTH_test/annecontainer/annefile3 HTTP/1.1" 201 120 0.044787 (txn: tx45826ac5bc284bd8b15a6-0059391903)

So far, I realized that nfs does not support xattr. Would that caused the issue?

What I want to do is use swift-on-file to store data in the mounted directory(by nfs) like /mnt/sdb1/2.

答:
Objects are stored as binary files on the filesystem with metadata stored in the file’s extended attributes (xattrs). This requires that the underlying filesystem choice for object servers support xattrs on files. Some filesystems, like ext3, have xattrs turned off by default.

Source: https://docs.openstack.org/developer/swift/overview_architecture.html


问:
Select some values in a SQL query while ignoring the Where clause
First of all I have this SQL query:

```<code>DECLARE @list TABLE
(
    [DocID] int,
    [OrderQuantity] decimal(18,3)
)

INSERT INTO @list (DocID, OrderQuantity)
    (SELECT
         tblCusDocsPos.DocID, tblCusDocsPos.OrderQuantity,
     FROM
         tblCusDocsPos
     LEFT OUTER JOIN
         tblCusDocsPos ON tblCusDocsPos.DocID = tblCusDocsPos.DocID
     WHERE
         (tblCusDocs.ActualAB = 0)
     GROUP BY
         tblCusDocsPos.DocID , tblCusDocsPos.OrderQuantity)

SELECT
    [tblCusDocs].[DocID], [tblCusDocs].[DocTypeID],
    [tblCusDocs].[ContractNum],
    [tblCusDocs].[OrderQuantity], list.OrderQuantity
FROM
    tblCusDocs
LEFT OUTER JOIN
    [tblCusDocsPos] ON [tblCusDocsPos].DocID = [tblCusDocs].DocID
LEFT OUTER JOIN
    @list ON list.DocID = [tblCusDocs].DocID
WHERE
    [tblCusDocs].ActualAB = 1
</code>```

The problem here is the following: I'm inserting values into my table called list with the condition ActualAB = 0. Now the table is getting filled but in the main WHERE clause of the SELECT statement. These values are getting thrown out because of the condition ActualAB = 1.

Is it possible to ignore the main where clause for the items in my list table and return all values from there? Can this be done in one query?

Thanks very much.

EDIT:

this is getting bound to a grid over properties at the end. So we are using a kind of loader which evaluates the SELECT statement and receives all data but because of the WHERE clause at the end the values from the list table are getting filtered a second time.
So the Output should be one table with values. Three columns that are filtered by the main WHERE clause and one (list.OrderQuantity) which is filtered by the WHERE clause above.

EDIT2:

Ok I'm trying to explain it more clearly with Kind of sample table with data.

I'm filtering from a table with such content:

DocID | AB | OrderQuantity | ContractNum

1        1         2            111

2        0         5            111

3        1         0            222

4        1         10           333

5        1         3            444

In this case I would get all values with AB=1 because of the main WHERE clause.
Let's say I'm filtering over the ContractNum. In my case I would like to have also four results but when I have the same ContractNums, i would rather choose the OrderQuantity value where AB=1.

答:
This is a shot in the dark guess that you want results where the ActualAB = 1 OR the result is in the list table.</p>

```<code>DECLARE @list TABLE
(
    [DocID] int,
    [OrderQuantity] decimal(18,3)
)

INSERT INTO @list (DocID, OrderQuantity)
    (SELECT
         tblCusDocsPos.DocID, tblCusDocsPos.OrderQuantity,
     FROM
         tblCusDocsPos
     LEFT OUTER JOIN
         tblCusDocsPos ON tblCusDocsPos.DocID = tblCusDocsPos.DocID
     WHERE
         (tblCusDocs.ActualAB = 0)
     GROUP BY
         tblCusDocsPos.DocID , tblCusDocsPos.OrderQuantity)

SELECT
    [tblCusDocs].[DocID], [tblCusDocs].[DocTypeID],
    [tblCusDocs].[ContractNum],
    [tblCusDocs].[OrderQuantity], list.OrderQuantity
FROM
    tblCusDocs
LEFT OUTER JOIN
    [tblCusDocsPos] ON [tblCusDocsPos].DocID = [tblCusDocs].DocID
LEFT OUTER JOIN
    @list ON list.DocID = [tblCusDocs].DocID
WHERE
    [tblCusDocs].ActualAB = 1 OR list.DocID IS NOT NULL
</code>```

Body:
First of all I have this SQL query:

DECLARE @list TABLE
(
    [DocID] int,
    [OrderQuantity] decimal(18,3)
)

INSERT INTO @list (DocID, OrderQuantity)
    (SELECT
         tblCusDocsPos.DocID, tblCusDocsPos.OrderQuantity,
     FROM
         tblCusDocsPos
     LEFT OUTER JOIN
         tblCusDocsPos ON tblCusDocsPos.DocID = tblCusDocsPos.DocID
     WHERE
         (tblCusDocs.ActualAB = 0)
     GROUP BY
         tblCusDocsPos.DocID , tblCusDocsPos.OrderQuantity)

SELECT
    [tblCusDocs].[DocID], [tblCusDocs].[DocTypeID],
    [tblCusDocs].[ContractNum],
    [tblCusDocs].[OrderQuantity], list.OrderQuantity
FROM
    tblCusDocs
LEFT OUTER JOIN
    [tblCusDocsPos] ON [tblCusDocsPos].DocID = [tblCusDocs].DocID
LEFT OUTER JOIN
    @list ON list.DocID = [tblCusDocs].DocID
WHERE
    [tblCusDocs].ActualAB = 1

The problem here is the following: I'm inserting values into my table called list with the condition ActualAB = 0. Now the table is getting filled but in the main WHERE clause of the SELECT statement. These values are getting thrown out because of the condition ActualAB = 1.

Is it possible to ignore the main where clause for the items in my list table and return all values from there? Can this be done in one query?

Thanks very much.

EDIT:

this is getting bound to a grid over properties at the end. So we are using a kind of loader which evaluates the SELECT statement and receives all data but because of the WHERE clause at the end the values from the list table are getting filtered a second time.
So the Output should be one table with values. Three columns that are filtered by the main WHERE clause and one (list.OrderQuantity) which is filtered by the WHERE clause above.

EDIT2:

Ok I'm trying to explain it more clearly with Kind of sample table with data.

I'm filtering from a table with such content:

DocID | AB | OrderQuantity | ContractNum

1        1         2            111

2        0         5            111

3        1         0            222

4        1         10           333

5        1         3            444

In this case I would get all values with AB=1 because of the main WHERE clause.
Let's say I'm filtering over the ContractNum. In my case I would like to have also four results but when I have the same ContractNums, i would rather choose the OrderQuantity value where AB=1.

Body:
This is a shot in the dark guess that you want results where the ActualAB = 1 OR the result is in the list table.

DECLARE @list TABLE
(
    [DocID] int,
    [OrderQuantity] decimal(18,3)
)

INSERT INTO @list (DocID, OrderQuantity)
    (SELECT
         tblCusDocsPos.DocID, tblCusDocsPos.OrderQuantity,
     FROM
         tblCusDocsPos
     LEFT OUTER JOIN
         tblCusDocsPos ON tblCusDocsPos.DocID = tblCusDocsPos.DocID
     WHERE
         (tblCusDocs.ActualAB = 0)
     GROUP BY
         tblCusDocsPos.DocID , tblCusDocsPos.OrderQuantity)

SELECT
    [tblCusDocs].[DocID], [tblCusDocs].[DocTypeID],
    [tblCusDocs].[ContractNum],
    [tblCusDocs].[OrderQuantity], list.OrderQuantity
FROM
    tblCusDocs
LEFT OUTER JOIN
    [tblCusDocsPos] ON [tblCusDocsPos].DocID = [tblCusDocs].DocID
LEFT OUTER JOIN
    @list ON list.DocID = [tblCusDocs].DocID
WHERE
    [tblCusDocs].ActualAB = 1 OR list.DocID IS NOT NULL