问:
Create a Dynamic search bar for checkboxes elements JavaScript
I'm trying to make a search bar which shows elements based on their text according to what you enter in a search bar. But most instructions online are about arrays or lists and I can't adapt my code to include those.

I have a succession of checkboxes created according to an array and I don't know how to proceed.

I whould like something like if I write "J" in the search bar, I would see the checkboxes "January" "June" "July".

Here is a snippet to help you to understand. I would prefer Javascript instead of jQuery.

//array of options (change this array and you change the checkboxes)
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

//array of value which have to be automaticly selected
var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }
}
//function which update the text area according to which checkbox is selected or not
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:75px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }</code>```

All | Selected <input type="text" id="SearchBar" placeholder="Search for options..">
 <form>

</form>

<textarea id="t"></textarea>```

答:
You can use the oninput-attribute on the search-field to call a JS-function (let's just call it search(query) for this example). The call should look somewhat like this:

```<code><input oninput="search(this.value);" type="text" id="SearchBar" placeholder="Search for options.." />
</code>```

The search()-function the iterates through the choices-array and compare whether the parameter given to the function matches or is included in the current member of the array. If that's not the case, you can add some kind of .hidden class to the nth  where n is the choice you are currently iterating through. If it is the case, you can remove the class. You can do that using the following jQuery functions (let's say i is the variable that holds the index of the current element):

```<code>$("label:nth-child(" + i + ")").addClass("hidden");
</code>```

and

```<code>$("label:nth-child(" + i + ")").removeClass("hidden");
</code>```

The .hidden-class should look like this:

```<code>.hidden {
    display:none;
}
</code>```

I hope this helps. If you have any questions, feel free to ask.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a search bar which shows elements based on their text according to what you enter in a search bar. But most instructions online are about arrays or lists and I can't adapt my code to include those.

I have a succession of checkboxes created according to an array and I don't know how to proceed.

I whould like something like if I write "J" in the search bar, I would see the checkboxes "January" "June" "July".

Here is a snippet to help you to understand. I would prefer Javascript instead of jQuery.

//array of options (change this array and you change the checkboxes)
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

//array of value which have to be automaticly selected
var target = new Array()
target[0] = "9";
target[1] = "8";
target[2] = "11";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }
}
//function which update the text area according to which checkbox is selected or not
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:75px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }

All | Selected <input type="text" id="SearchBar" placeholder="Search for options..">
 <form>

</form>

<textarea id="t"></textarea>

Body:
You can use the oninput-attribute on the search-field to call a JS-function (let's just call it search(query) for this example). The call should look somewhat like this:

<input oninput="search(this.value);" type="text" id="SearchBar" placeholder="Search for options.." />

The search()-function the iterates through the choices-array and compare whether the parameter given to the function matches or is included in the current member of the array. If that's not the case, you can add some kind of .hidden class to the nth <label> where n is the choice you are currently iterating through. If it is the case, you can remove the class. You can do that using the following jQuery functions (let's say i is the variable that holds the index of the current element):

$("label:nth-child(" + i + ")").addClass("hidden");

and

$("label:nth-child(" + i + ")").removeClass("hidden");

The .hidden-class should look like this:

.hidden {
    display:none;
}

I hope this helps. If you have any questions, feel free to ask.


来源: stackexchange

问:
Check if piwik tracking code is installed
I have made a dashboard where users of my site can download a javascript tracking code for their own websites, using Piwik.

As of now I can only tell if a user's tracker is working properly if there is data incoming from their end. But is there any way to check if the code has physically been installed in the website? I need this to differentiate between users who have the code installed but have no visits since, and users who have not installed the code at all.

Cannot find anything in the piwik documentation that handles this particular problem.

答:
Using PHP you could use:

Using file_get_contents

```<code>$url = 'website URL to check';
$data = file_get_contents($url);
// check if tracking code available
if (strpos($data, 'PIWIKTRACKINGCODE') !== FALSE){
    echo 'TRACKING CODE FOUND';
} else {
    echo 'TRACKING CODE NOT FOUND';
}
</code>```

http://php.net/manual/en/function.file-get-contents.php

Or using curl

```<code>$url = 'website URL to check';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch)
// check if tracking code available
if (strpos($data, 'PIWIKTRACKINGCODE') !== FALSE){
    echo 'TRACKING CODE FOUND';
} else {
    echo 'TRACKING CODE NOT FOUND';
}
</code>```

http://php.net/manual/en/book.curl.php

ContentLicense: CC BY-SA 3.0

Body:
Using PHP you could use:

Using file_get_contents

$url = 'website URL to check';
$data = file_get_contents($url);
// check if tracking code available
if (strpos($data, 'PIWIKTRACKINGCODE') !== FALSE){
    echo 'TRACKING CODE FOUND';
} else {
    echo 'TRACKING CODE NOT FOUND';
}

http://php.net/manual/en/function.file-get-contents.php

Or using curl

$url = 'website URL to check';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch)
// check if tracking code available
if (strpos($data, 'PIWIKTRACKINGCODE') !== FALSE){
    echo 'TRACKING CODE FOUND';
} else {
    echo 'TRACKING CODE NOT FOUND';
}

http://php.net/manual/en/book.curl.php


问:
Wait for Facebook Pixel Load
I want to detect in my JavaScript code that the load of a Facebook pixel has been completed. Is this possible?

For reference here is the Facebook Pixel Tracking code:

```<code><script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','//connect.facebook.net/en_US/fbevents.js');
// Insert Your Facebook Pixel ID below.
fbq('init', 'FB_PIXEL_ID');
fbq('track', 'PageView');
</script>
<!-- Insert Your Facebook Pixel ID below. -->
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=FB_PIXEL_ID&ev=PageView&noscript=1"
/></noscript>
</code>```

Breaking it down, it seems that fbq('init', ...) causes a script tag to be added with the async attribute set and src set to //connect.facebook.net/en_US/fbevents.js.

Subsequently the call to fbq('track', ...) somehow causes an HTTP GET to an image via one redirect.

How to detect that all the steps are complete, especially that the final image load is complete?

答:
The answer of @love-chopra is sort of alright, however I think to use the setTimeout() with 3s delay is not the best solution when we are talking about a webpage. From my POV the solution could be the setInterval() to check it constantly until the fbevents.js not loaded.

```<code>  var fbLoaded = false;
  var tryFB = null;

  function drop_fb_pixel() {
    fbLoaded = true;
    try {
      fbq('track', 'ViewContent', {
        content_ids: ['12'],
        content_type: 'product'
      });
    } catch (err) {
      fbLoaded = false;
    }

    if (fbLoaded) {
      clearInterval(tryFB);
    }
  }

  tryFB = setInterval(function () {
    drop_fb_pixel();
  }, 100);
</code>```

Title: Wait for Facebook Pixel Load

Body:
I want to detect in my JavaScript code that the load of a Facebook pixel has been completed. Is this possible?

For reference here is the Facebook Pixel Tracking code:

Breaking it down, it seems that fbq('init', ...) causes a script tag to be added with the async attribute set and src set to //connect.facebook.net/en_US/fbevents.js.

Subsequently the call to fbq('track', ...) somehow causes an HTTP GET to an image via one redirect.

How to detect that all the steps are complete, especially that the final image load is complete?

Body:
The answer of @love-chopra is sort of alright, however I think to use the setTimeout() with 3s delay is not the best solution when we are talking about a webpage. From my POV the solution could be the setInterval() to check it constantly until the fbevents.js not loaded.

  var fbLoaded = false;
  var tryFB = null;

  function drop_fb_pixel() {
    fbLoaded = true;
    try {
      fbq('track', 'ViewContent', {
        content_ids: ['12'],
        content_type: 'product'
      });
    } catch (err) {
      fbLoaded = false;
    }

    if (fbLoaded) {
      clearInterval(tryFB);
    }
  }

  tryFB = setInterval(function () {
    drop_fb_pixel();
  }, 100);


问:
Cannot use argb color int value in Kotlin?
When I want to animate the textColor of TextView in Kotlin:

```<code>val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE)
</code>```

this error occurs:

```<code>Error:(124, 43) None of the following functions can be called with the arguments supplied:
public open fun <T : Any!> ofInt(target: TextView!, xProperty: Property<TextView!, Int!>!, yProperty: Property<TextView!, Int!>!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun <T : Any!> ofInt(target: TextView!, property: Property<TextView!, Int!>!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, propertyName: String!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, xPropertyName: String!, yPropertyName: String!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(vararg values: Int): ValueAnimator! defined in android.animation.ObjectAnimator
</code>```

Seems that the value 0xFF8363FF and 0xFFC953BE cannot be cast to Int in Kotlin, however, it's normal in Java:

```<code>ObjectAnimator animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE);
</code>```

Any ideas? Thanks in advance.

答:
0xFF8363FF (as well as 0xFFC953BE) is a Long, not an Int.

You have to cast them to Int explicitly:

```<code>val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF.toInt(), 0xFFC953BE.toInt())
</code>```

The point is that the numeric value of 0xFFC953BE is 4291384254, so it should be stored in a Long variable. But the high bit here is a sign bit, that denotes a negative number: -3583042 which can be stored in Int.

And that's the difference between two languages. In Kotlin you should add the - sign to denote negative Int which is not true in Java:

```<code>// Kotlin
print(-0x80000000)             // >>> -2147483648 (fits into Int)
print(0x80000000)              // >>>  2147483648 (does NOT fit into Int)

// Java
System.out.print(-0x80000000); // >>> -2147483648 (fits into Integer)
System.out.print(0x80000000);  // >>> -2147483648 (fits into Integer)
</code>```

Body:
When I want to animate the textColor of TextView in Kotlin:

val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE)

this error occurs:

Error:(124, 43) None of the following functions can be called with the arguments supplied:
public open fun <T : Any!> ofInt(target: TextView!, xProperty: Property<TextView!, Int!>!, yProperty: Property<TextView!, Int!>!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun <T : Any!> ofInt(target: TextView!, property: Property<TextView!, Int!>!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, propertyName: String!, vararg values: Int): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(target: Any!, xPropertyName: String!, yPropertyName: String!, path: Path!): ObjectAnimator! defined in android.animation.ObjectAnimator
public open fun ofInt(vararg values: Int): ValueAnimator! defined in android.animation.ObjectAnimator

Seems that the value 0xFF8363FF and 0xFFC953BE cannot be cast to Int in Kotlin, however, it's normal in Java:

ObjectAnimator animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF, 0xFFC953BE);

Any ideas? Thanks in advance.

Body:
0xFF8363FF (as well as 0xFFC953BE) is a Long, not an Int.

You have to cast them to Int explicitly:

val animator = ObjectAnimator.ofInt(myTextView, "textColor", 0xFF8363FF.toInt(), 0xFFC953BE.toInt())

The point is that the numeric value of 0xFFC953BE is 4291384254, so it should be stored in a Long variable. But the high bit here is a sign bit, that denotes a negative number: -3583042 which can be stored in Int.

And that's the difference between two languages. In Kotlin you should add the - sign to denote negative Int which is not true in Java:

// Kotlin
print(-0x80000000)             // >>> -2147483648 (fits into Int)
print(0x80000000)              // >>>  2147483648 (does NOT fit into Int)

// Java
System.out.print(-0x80000000); // >>> -2147483648 (fits into Integer)
System.out.print(0x80000000);  // >>> -2147483648 (fits into Integer)


问:
Bad Argument, Invalid Subscription Key when trying to add key from Azure
I am trying to set up my LUIS app in luis.ai (because it seems like I can't set it up in Azure directly?). Anyway, I have created a Language Understanding Intelligent Service (LUIS) (preview) resource, but when I enter one of the keys from that resource into "My Keys" in luis.ai, I get this error: "Bad Argument, Invalid Subscription Key"

Also, I just tried to publish an app with the bootstrap key and got the following errors:

{ "statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription." }

答:
To use european LUIS endpoint within Bot Builder C# SDK, just modify Luis Model parameters as follows:

[LuisModel("YOUR-LUIS-APP-ID", "YOUR-LUIS-EUROPEAN-KEY", domain:
  "westeurope.api.cognitive.microsoft.com")]

Note that you'll need to export your LUIS app over EU.LUIS in order to access the correct endpoint.

Hope it helps.


问:
Php form html integration not working properly (Ion Auth register)
I want to add some nice bottstrap html and css to my register page, but i don't know how to embedding php into html input and show it with style. Is there any way to do this?

The code produces the next view:

Full .php file

Note: it is showing both forms(to compare results), php and html + php. form with only php works fine, the problem is to give it style.

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.js'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.min.js'); ?>">
<div class="container">
    <?php
    echo isset($_SESSION['auth_message']) ? $_SESSION['auth_message'] : FALSE;
    ?>
    <h1>Registro usuario</h1>
    <?php
    echo form_open();
    echo form_label('Nombre:','first_name').'<br />';
    echo form_error('first_name');
    echo form_input('first_name',set_value('first_name')).'<br />';
    echo form_label('Apellidos:','last_name').'<br />';
    echo form_error('last_name');
    echo form_input('last_name',set_value('last_name')).'<br />';
   // echo form_label('Username:','username').'<br />';
    //echo form_error('username');
    //echo form_input('username',set_value('username')).'<br />';
    echo form_label('Email:','email').'<br />';
    echo form_error('email');
    echo form_input('email',set_value('email')).'<br />';
    echo form_label('Contraseña:', 'password').'<br />';
    echo form_error('password');
    echo form_password('password').'<br />';
    echo form_label('Confirmar contraseña:', 'confirm_password').'<br />';
    echo form_error('confirm_password');
    echo form_password('confirm_password').'<br /><br />';
    echo form_submit('register','Confirmar');
    echo form_close();
    ?>
</div>
<form class="form-horizontal">
<fieldset>

<!-- Form Name -->
<legend>Registro de usuario</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Nombre</label>
  <div class="col-md-4">
     <!-- <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: José Manuel..." class="form-control input-md" required=""> -->
     <?php $nombre = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: José Manuel...',
        ); ?>

 <?php echo form_input($nombre); ?>
   <!-- <?php echo form_input('first_name',set_value('first_name')); ?> -->
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Apellidos</label>
  <div class="col-md-4">
    <!--  <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: Palma..." class="form-control input-md" required=""> -->

      <?php $apellidos = array(
          'name'        => 'last_name',
          'id'          => 'last_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: Palma...',
        ); ?>

 <?php echo form_input($apellidos); ?>

  <!--  <?php echo form_input('last_name',set_value('last_name')); ?> -->
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Email</label>
  <div class="col-md-4">
   <!--   <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: herba@gmail.com..." class="form-control input-md" required=""> -->

      <?php $email = array(
          'name'        => 'email',
          'id'          => 'email',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        ); ?>

 <?php echo form_input($email); ?>

  <!--  <?php echo form_input('email',set_value('email'));?> -->
  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Contraseña</label>
  <div class="col-md-4">
  <!--  <input value="" id="passwordinput" name="passwordinput" type="password" placeholder="Ej: herbaricemills9..." class="form-control input-md" required=""> -->

    <?php $password = array(
          'name'        => 'password',
          'id'          => 'password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herbaricemills9...',
        ); ?>

 <?php echo form_input($password); ?>

    <!--  <?php echo form_password('password'); ?> -->
  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Confirmar contraseña</label>
  <div class="col-md-4">
   <!--   <input value="" id="passwordinput" name="passwordinput" type="password" placeholder="Repetir contraseña..." class="form-control input-md" required=""> -->

       <?php $password1 = array(
          'name'        => 'confirm_password',
          'id'          => 'confirm_password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Repetir contraseña...',
        ); ?>

 <?php echo form_input($password1); ?>

  <!--  <?php echo form_password('confirm_password');?> -->
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-4">
    <!--  <button  value="" id="singlebutton" name="singlebutton" class="btn btn-primary">Confirmar</button> -->

    <!--  <?php $confirm = array(
          'name'        => 'singlebutton',
          'id'          => 'singlebutton',
          //'type'          => 'password',
          'class'       => 'btn btn-primary',

        ); ?>

 <?php echo form_input($confirm); ?> -->

   <?php echo form_submit('register','Confirmar');?>

  </div>
</div>

</fieldset>
</form>
</code>```

答:
you can use like below.
for example first_name field

```<code>$data = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Enter First Name',
        );

 echo form_input($data);
</code>```

use same for other element too.

Body:
I want to add some nice bottstrap html and css to my register page, but i don't know how to embedding php into html input and show it with style. Is there any way to do this?

The code produces the next view:

Full .php file

Note: it is showing both forms(to compare results), php and html + php. form with only php works fine, the problem is to give it style.

<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.js'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.min.js'); ?>">

    <?php
    echo isset($_SESSION['auth_message']) ? $_SESSION['auth_message'] : FALSE;
    ?>

Registro usuario

    <?php
    echo form_open();
    echo form_label('Nombre:','first_name').'
';
    echo form_error('first_name');
    echo form_input('first_name',set_value('first_name')).'
';
    echo form_label('Apellidos:','last_name').'
';
    echo form_error('last_name');
    echo form_input('last_name',set_value('last_name')).'
';
   // echo form_label('Username:','username').'
';
    //echo form_error('username');
    //echo form_input('username',set_value('username')).'
';
    echo form_label('Email:','email').'
';
    echo form_error('email');
    echo form_input('email',set_value('email')).'
';
    echo form_label('Contraseña:', 'password').'
';
    echo form_error('password');
    echo form_password('password').'
';
    echo form_label('Confirmar contraseña:', 'confirm_password').'
';
    echo form_error('confirm_password');
    echo form_password('confirm_password').'

';
    echo form_submit('register','Confirmar');
    echo form_close();
    ?>

<form class="form-horizontal">
<fieldset>

<legend>Registro de usuario</legend>

  Nombre

     <?php $nombre = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: José Manuel...',
        ); ?>

 <?php echo form_input($nombre); ?>

  Apellidos

      <?php $apellidos = array(
          'name'        => 'last_name',
          'id'          => 'last_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: Palma...',
        ); ?>

 <?php echo form_input($apellidos); ?>

  Email

      <?php $email = array(
          'name'        => 'email',
          'id'          => 'email',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        ); ?>

 <?php echo form_input($email); ?>

  Contraseña

    <?php $password = array(
          'name'        => 'password',
          'id'          => 'password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herbaricemills9...',
        ); ?>

 <?php echo form_input($password); ?>

  Confirmar contraseña

       <?php $password1 = array(
          'name'        => 'confirm_password',
          'id'          => 'confirm_password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Repetir contraseña...',
        ); ?>

 <?php echo form_input($password1); ?>

   <?php echo form_submit('register','Confirmar');?>

</fieldset>
</form>

Body:
you can use like below.
for example first_name field

$data = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Enter First Name',
        );

 echo form_input($data);

use same for other element too.


问:
WPF is it possible to showdialog() on top of Windows lock screen?
I wrote a desktop alerts application that sends a variety of notifications to all clients that are currently logged in.  The app lives in the system tray, with a right-click menu to select an alert.  When an alert is sent, a pop-up displays on each client's desktop with the type of alert.  The pop-up is a simple Window class:

```<code>alertWindow.showDialog();
</code>```

Our PC's have a policy on them to automatically lock the screen after 10 minutes of inactivity.  What I'd like to know is if there's any way to have the alerts display while the screen is locked.  Any help would be appreciated.

答:
The lockscreen itself is de-facto a different user session which runs with winlogon privileges.

i've done such thing under window 7 quite a while ago, but cant recall the details right now.

The general approach is:

open winlogon process handle

copy access token from process

create a new process with the just copied access token

create your windows on the lockscreen

it's a pretty hacky approach using many api calls but the only one that works.

As soon as I'm back at my home-pc i can see if i can find some details on how i exactly have done it.

[Edit]

I now had the chance to review the code and i have to say i'ts a little more complicated than outlined.

Key element is, that you need a service (which i wrote in C++) which runs with system permissions.
This service has to copy the impersonation token from the winlogon process and after that, launch a new process with that new token.
API functions for reference

GetTokenInformation

OpenProcessToken

DuplicateTokenEx

AdjustTokenPrivileges

[/Edit]

Body:
I wrote a desktop alerts application that sends a variety of notifications to all clients that are currently logged in.  The app lives in the system tray, with a right-click menu to select an alert.  When an alert is sent, a pop-up displays on each client's desktop with the type of alert.  The pop-up is a simple Window class:

alertWindow.showDialog();

Our PC's have a policy on them to automatically lock the screen after 10 minutes of inactivity.  What I'd like to know is if there's any way to have the alerts display while the screen is locked.  Any help would be appreciated.


问:
how to set the bash scripts with in the python scripts rather than having separate scripts?
This is how I running the bash script set in myscript.sh

```<code>#!/bin/bash
import subprocess
child = subprocess.Popen(['bash', '-c', '/bin/bash myscript.sh'], stdout = subprocess.PIPE)
output=child.communicate()
print(output)
</code>```

myscript.sh

Why am I making this is because the bash script that I have to run does not have the export command so I am echoing here. Code bellow. I know echoing wont set the environment variable but I just want to echo it and fetch the value so echoing instead of exporting.

```<code>#!/bin/bash
source ia_servers
echo $IA_SRV_cs68_64
</code>```

Where, $IA_SRV_cs68_64

Here is the ia_servers file where the variable values are listed
it looks something like this

```<code>IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "
</code>```

This is how the variables are in it. Many other variable are set in it eliminated because too longer.

TESTED works well from terminal:

source ia_servers

echo IA_SRV_cs68_64

prints the desired values set

Problem:
Though myscript.sh is working and printing the variables . What I want is I don't want to create a separate file write a bash script there to echo the variable as in the myscript.sh but  instead write it within the python.

How do I accomplish it within the python rather rather than making the
  script file and run that.

答:
Here's a universal way to run any kind of script or program where program input is embedded in the Python script.</p>

```<code>import subprocess
scriptres = subprocess.Popen("/bin/bash",
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE).communicate(r'''
# your bash script here
ls
pwd
source whatever
echo $SOMETHING
''')

script_stdout = scriptres[0]
script_stderr = scriptres[1]
</code>```

Body:
This is how I running the bash script set in myscript.sh

#!/bin/bash
import subprocess
child = subprocess.Popen(['bash', '-c', '/bin/bash myscript.sh'], stdout = subprocess.PIPE)
output=child.communicate()
print(output)

myscript.sh

Why am I making this is because the bash script that I have to run does not have the export command so I am echoing here. Code bellow. I know echoing wont set the environment variable but I just want to echo it and fetch the value so echoing instead of exporting.

#!/bin/bash
source ia_servers
echo $IA_SRV_cs68_64

Where, $IA_SRV_cs68_64

Here is the ia_servers file where the variable values are listed
it looks something like this

IA_SRV_cs68_64="ds1 ds2 ds3 ds5 "

This is how the variables are in it. Many other variable are set in it eliminated because too longer.

TESTED works well from terminal:

source ia_servers

echo IA_SRV_cs68_64

prints the desired values set

Problem:
Though myscript.sh is working and printing the variables . What I want is I don't want to create a separate file write a bash script there to echo the variable as in the myscript.sh but  instead write it within the python.

How do I accomplish it within the python rather rather than making the
  script file and run that.

Body:
Here's a universal way to run any kind of script or program where program input is embedded in the Python script.

import subprocess
scriptres = subprocess.Popen("/bin/bash",
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE).communicate(r'''
# your bash script here
ls
pwd
source whatever
echo $SOMETHING
''')

script_stdout = scriptres[0]
script_stderr = scriptres[1]


问:
How to Learn MS SQL Server 2005?
I would like to start learning SQL Server 2005 on my own.  Can anyone recommend good books or websites that will be a good start for me?</p>

答:
here is an additional link for those common questions

The Ten Most Asked SQL Server Questions And Their Answers

OwnerDisplayName: Craig G

ContentLicense: CC BY-SA 2.5

Title: How to Learn MS SQL Server 2005?

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: SQLMenace


问:
How to prevent server blocking php
I'm currently developing a php daemon for connecting and retreiving data from social networks like facebook and twitter. This script allready works but I have some concerns about it.

It's possible to create an infinite amount of accounts that the script has to process and (right now) it runs every 5 minutes to create a 'near' realtime experience. So my concern is that, when, let's say 5000 accounts, have been created and have to be monitored. The script slows down and maybe wil run longer than the 5 minute interval. Is there any way to work around this problem? And better, is there any good way (with php, possible with javascript) to create a better 'near' realtime experience?

Any advice will be great!

Thanks in advance

答:
for most sites you can retrieve a stream containing all that data(in real-time). For example:

1. twitter

site streams allows services,
  such as web sites or mobile push
  services, to receive real-time updates
  for a large number of users without
  any of the hassles of managing REST
  API rate limits

2. Facebook

The Graph API supports real-time
  updates to enable your application
  using Facebook to subscribe to changes
  in data from Facebook.

When using these streams you can process the streams in real-time and don't have to do no(nearly none) polling.

P.S: I would most definitely code this in node.js.

Title: How to prevent server blocking php


问:
OpenNMT issues with Pytorch: cPickle.UnpicklingError: invalid load key, ''
I am trying to run the OpenNMT project using the instruction from the link: http://forum.opennmt.net/t/text-summarization-on-gigaword-and-rouge-scoring/85/6

I am using Python 2.7 and installed pytorch from the github repository.

I am trying to run the program using the prebuild model of the OpenNMT, which I have downloaded from the following: http://opennmt.net/Models/

I tried the command:

```<code>python translate.py -model textsum_epoch7_14.69_release.t7 -src data/Giga/input.txt
</code>```

Got the following error:

```<code>Traceback (most recent call last):
  File "translate.py", line 151, in <module>
    main()
  File "translate.py", line 70, in main
    translator = onmt.Translator(opt)
  File "/home/ubuntu/opennmt/onmt/Translator.py", line 21, in __init__
    checkpoint = torch.load(opt.model)
  File "/usr/local/lib/python2.7/dist-packages/torch/serialization.py", line 229, in load
    return _load(f, map_location, pickle_module)
  File "/usr/local/lib/python2.7/dist-packages/torch/serialization.py", line 367, in _load
    magic_number = pickle_module.load(f)
cPickle.UnpicklingError: invalid load key, ''.
</code>```

Kindly let me know what I need to do so that I can use the model and check the library OpenNMT.

答:
The model you downloaded is for the Lua version of OpenNMT.

If you are just a user of the project, I recommend you to use this version as it is the most supported and stable.

Body:
I am trying to run the OpenNMT project using the instruction from the link: http://forum.opennmt.net/t/text-summarization-on-gigaword-and-rouge-scoring/85/6

I am using Python 2.7 and installed pytorch from the github repository.

I am trying to run the program using the prebuild model of the OpenNMT, which I have downloaded from the following: http://opennmt.net/Models/

I tried the command:

python translate.py -model textsum_epoch7_14.69_release.t7 -src data/Giga/input.txt

Got the following error:

Traceback (most recent call last):
  File "translate.py", line 151, in <module>
    main()
  File "translate.py", line 70, in main
    translator = onmt.Translator(opt)
  File "/home/ubuntu/opennmt/onmt/Translator.py", line 21, in __init__
    checkpoint = torch.load(opt.model)
  File "/usr/local/lib/python2.7/dist-packages/torch/serialization.py", line 229, in load
    return _load(f, map_location, pickle_module)
  File "/usr/local/lib/python2.7/dist-packages/torch/serialization.py", line 367, in _load
    magic_number = pickle_module.load(f)
cPickle.UnpicklingError: invalid load key, ''.

Kindly let me know what I need to do so that I can use the model and check the library OpenNMT.


问:
Django error : global name 'request' is not defined
I'm getting a little problem with my Django view. I have a function Identity_FewUpdates and I get this error : global name 'request' is not defined.

It's pretty strange because I have an other function which looks like very similar and I don't get problems up to now.

My function looks like :

```<code>import requests, os, json, glob
from django.shortcuts import render, reverse, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from models import Person, CountryField
from BirthCertificate.models import BirthCertificate
from forms import PersonForm, PersonForm2
from django.views.generic.edit import UpdateView
from django.template.loader import get_template
from django.template import Context
from xhtml2pdf import pisa

import Logger, Search, Folds, Docs, Buffer, EnterSearch

from chartit import DataPool, Chart

from django.db.models import Count
from django_countries import countries

import time
from random import randint
from django.contrib import messages

import Global_variables

@login_required
def Identity_FewUpdates(requests):

    query_social_number = request.GET.get('social_number')

    if query_social_number :
        query_social_number_list = Person.objects.filter(social_number__icontains=query_social_number)
        print query_social_number_list
    else :
        query_social_number_list = Person.objects.none() # == []

    form = PersonForm(request.POST or None, instance = query_social_number_list.first())

    query_job = request.GET.get('job')

    context = {
        "query_social_number" : query_social_number,
        "query_social_number_list" : query_social_number_list,
        "query_job" : query_job,
        "form": form
    }
    return render(request, "Update.html", context)
</code>```

The function is a draft for the moment.
Do you have any idea about this problem ?

答:
Django view function takes request argument not requests.

```<code>@login_required
def Identity_FewUpdates(request):

    query_social_number = request.GET.get('social_number')
</code>```

Body:
I'm getting a little problem with my Django view. I have a function Identity_FewUpdates and I get this error : global name 'request' is not defined.

It's pretty strange because I have an other function which looks like very similar and I don't get problems up to now.

My function looks like :

import requests, os, json, glob
from django.shortcuts import render, reverse, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from models import Person, CountryField
from BirthCertificate.models import BirthCertificate
from forms import PersonForm, PersonForm2
from django.views.generic.edit import UpdateView
from django.template.loader import get_template
from django.template import Context
from xhtml2pdf import pisa

import Logger, Search, Folds, Docs, Buffer, EnterSearch

from chartit import DataPool, Chart

from django.db.models import Count
from django_countries import countries

import time
from random import randint
from django.contrib import messages

import Global_variables

@login_required
def Identity_FewUpdates(requests):

    query_social_number = request.GET.get('social_number')

    if query_social_number :
        query_social_number_list = Person.objects.filter(social_number__icontains=query_social_number)
        print query_social_number_list
    else :
        query_social_number_list = Person.objects.none() # == []

    form = PersonForm(request.POST or None, instance = query_social_number_list.first())

    query_job = request.GET.get('job')

    context = {
        "query_social_number" : query_social_number,
        "query_social_number_list" : query_social_number_list,
        "query_job" : query_job,
        "form": form
    }
    return render(request, "Update.html", context)

The function is a draft for the moment.
Do you have any idea about this problem ?

Body:
Django view function takes request argument not requests.

@login_required
def Identity_FewUpdates(request):

    query_social_number = request.GET.get('social_number')


问:
simPRO Tivoka Client intermittently failing
does anyone know how to stop the simPRO PHP Tivoka library from failing intermittently,

I have asked simPRO for support and they say that they cannot replicate the issue.
I believe it may be something to do with a set_time_limit() that is called somewhere in one of the libraries however I cannot find it.

Im running the following in PHP

```<code><?php
    set_time_limit(0);
    //simPRO Settings

        $companyID = 0;
        use SimPro\Api\Client as SimProClient;
        use Eher\OAuth\Consumer as OAuthConsumer;
        use \Monolog\Logger;
    {
        //if (PHP_SAPI != 'cli') die("This example must be run from the command line");

        include ("../../simpro_api_examples/vendor/autoload.php");

        define("SERVER", '**************');
        define("CONSUMER_KEY", '**************');
        define("CONSUMER_SECRET", '***************');

        $logger = new Logger('api-client');
        $logger->pushHandler(new \Monolog\Handler\StreamHandler('php://stderr'), Logger::INFO);
        $simPROClient = new SimProClient(SERVER , new OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET), null);
        $simPROClient->setLogger($logger);
    }
    ?>
</code>```

When I retrieve multiple Jobs using

```<code>    <?php
    $jobIDs = array(1,2,3,4,5,6,7,8,9,...,500);
    foreach($jobIDs as $current Job)
    {
        $jobDetails = $simPROClient -> JobRetrieve(0/*this is the company id as per their doccumentation at http://api.simpro.co/*,$currentJob);
    }
?>
</code>```

at some point in execution (but never the same pint) it returns the following

Fatal error: Uncaught Tivoka\Exception\ConnectionException: Connection
  to "https://integrated-za.simprosuite.com/api/" failed in C:\Abyss Web
  Server\htdocs\simpro_api_examples\vendor\tivoka\tivoka\lib\Tivoka\Client\Connection.php:114
  Stack trace: #0 C:\Abyss Web
  Server\htdocs\simpro_api_examples\src\SimPro\Api\Client.php(109):
  Tivoka\Client\Connection->send(Object(Tivoka\Client\Request)) #1
  C:\Abyss Web
  Server\htdocs\ICG\CustomerReports\CustomerReport.php(1625):
  SimPro\Api\Client->__call('JobRetrieve', Array) #2 {main} thrown in
  C:\Abyss Web
  Server\htdocs\simpro_api_examples\vendor\tivoka\tivoka\lib\Tivoka\Client\Connection.php
  on line 114

if I execute the command with fewer job ID's in the $jobIDs array the script executes without failure.

i have adjusted my php.ini to allow for unlimited script execution and input time

答:
The Simpro PHP library uses an old version of the tivoka RPC client that has the timeout hard-coded to 10 seconds, and because the SimproAPI is slow this very easily times out unfortunately with almost no information.  I'm assuming this is your problem.

See the timeout for version 3.1 (that Simpro uses) set here.

Personally I'm using Guzzle to do OAuth 1.0 requests to the Simpro API.  It's a much better client.

It's also a good idea to cache some of the data retrieved locally because   the Simpro API is awfully slow.

Body:
does anyone know how to stop the simPRO PHP Tivoka library from failing intermittently,

I have asked simPRO for support and they say that they cannot replicate the issue.
I believe it may be something to do with a set_time_limit() that is called somewhere in one of the libraries however I cannot find it.

Im running the following in PHP

<?php
    set_time_limit(0);
    //simPRO Settings

        $companyID = 0;
        use SimPro\Api\Client as SimProClient;
        use Eher\OAuth\Consumer as OAuthConsumer;
        use \Monolog\Logger;
    {
        //if (PHP_SAPI != 'cli') die("This example must be run from the command line");

        include ("../../simpro_api_examples/vendor/autoload.php");

        define("SERVER", '**************');
        define("CONSUMER_KEY", '**************');
        define("CONSUMER_SECRET", '***************');

        $logger = new Logger('api-client');
        $logger->pushHandler(new \Monolog\Handler\StreamHandler('php://stderr'), Logger::INFO);
        $simPROClient = new SimProClient(SERVER , new OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET), null);
        $simPROClient->setLogger($logger);
    }
    ?>

When I retrieve multiple Jobs using

    <?php
    $jobIDs = array(1,2,3,4,5,6,7,8,9,...,500);
    foreach($jobIDs as $current Job)
    {
        $jobDetails = $simPROClient -> JobRetrieve(0/*this is the company id as per their doccumentation at http://api.simpro.co/*,$currentJob);
    }
?>

at some point in execution (but never the same pint) it returns the following

Fatal error: Uncaught Tivoka\Exception\ConnectionException: Connection
  to "https://integrated-za.simprosuite.com/api/" failed in C:\Abyss Web
  Server\htdocs\simpro_api_examples\vendor\tivoka\tivoka\lib\Tivoka\Client\Connection.php:114
  Stack trace: #0 C:\Abyss Web
  Server\htdocs\simpro_api_examples\src\SimPro\Api\Client.php(109):
  Tivoka\Client\Connection->send(Object(Tivoka\Client\Request)) #1
  C:\Abyss Web
  Server\htdocs\ICG\CustomerReports\CustomerReport.php(1625):
  SimPro\Api\Client->__call('JobRetrieve', Array) #2 {main} thrown in
  C:\Abyss Web
  Server\htdocs\simpro_api_examples\vendor\tivoka\tivoka\lib\Tivoka\Client\Connection.php
  on line 114

if I execute the command with fewer job ID's in the $jobIDs array the script executes without failure.

i have adjusted my php.ini to allow for unlimited script execution and input time


答:
You can use this JavaScript/JQuery function:

```<code>function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains('+$('#SearchBar').val()+')').show();
  }
}
</code>```

And call it oninput in the input, with this line:

```<code><input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
</code>```

And include JQuery like this at the bottom/top of the head/body;

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

//array of options (change this array and you change the checkboxes)
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";
//array of value which have to be automaticly selected
var target = new Array();
target[0] = "9";
target[1] = "8";
target[2] = "11";
var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";
var j = "";
var t = document.getElementById('t');
// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();
  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");
  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText);
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }
}
updateText();
//function which update the text area according to which checkbox is selected or not
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '');
}
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains('+$('#SearchBar').val()+')').show();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}
#data {
  padding: 5px;
  width: 100vw;
}
.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  background-color: #eee;
  width: 100vw;
  white-space: normal;
  height: 75px;
}
.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}
label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}</code>```

<!DOCTYPE html>

  <title></title>

  All | Selected
  <form>
    <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
  </form>
  <form>

  </form>
  <textarea id="t"></textarea>

```
</div>
</div>
</p>

<p><b>Edit:</b> to make the search case-insensitive, add this amazing JQuery, found here.</p>

```$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
```

Title: Create a Dynamic search bar for checkboxes elements JavaScript

Body:
You can use this JavaScript/JQuery function:

function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains('+$('#SearchBar').val()+')').show();
  }
}

And call it oninput in the input, with this line:

<input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">

And include JQuery like this at the bottom/top of the head/body;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

//array of options (change this array and you change the checkboxes)
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "June";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";
//array of value which have to be automaticly selected
var target = new Array();
target[0] = "9";
target[1] = "8";
target[2] = "11";
var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";
var j = "";
var t = document.getElementById('t');
// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();
  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");
  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText);
  if (target.indexOf(i) >= 0) {
    cb.checked = true;
  }
}
updateText();
//function which update the text area according to which checkbox is selected or not
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '');
}
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});
function updateCheckboxes(x) {
  if ($('#SearchBar').val() == '') {
    $('#checkboxes > label').show();
  } else {
    $('#checkboxes > label').hide();
    $('#checkboxes > label:contains('+$('#SearchBar').val()+')').show();
  }
}

* {
  box-sizing: border-box;
}
#data {
  padding: 5px;
  width: 100vw;
}
.multiselect {
  overflow: visible;
  padding: 0;
  padding-left: 1px;
  border: none;
  background-color: #eee;
  width: 100vw;
  white-space: normal;
  height: 75px;
}
.checkboxes {
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  background-color: white;
  margin-left: -1px;
  display: inline-block;
}
label {
  display: inline-block;
  border: 1px grey solid;
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <span onclick="">All</span> | <span onclick="">Selected</span>
  <form>
    <input id="SearchBar" placeholder="Search for options.." type="text" oninput="updateCheckboxes(this)" autocomplete="off">
  </form>
  <form>
    <div id="data">
      <div class="multiselect">
        <div id="c_b">
          <div id="checkboxes"></div>
        </div>
      </div>
    </div>
  </form>
  <textarea id="t"></textarea>
</body>
</html>

Edit: to make the search case-insensitive, add this amazing JQuery, found here.

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});


问:
HtmlAgilityPack Debugging asks for source code
I have added html agility pack to my class library in project. Whenever i try to debug the HtmlAgilityPack specific code it opens a browse window asking for a HtmlAgilityPack source file (for example HtmlDocument.cs) or gives the error "There is no source code available for the current location."

What the heck is this, why I can not debug the HtmlAgilityPack related code.

答:
Please try the following...

Visual Studio -> Debug -> Options -> Check both "Enable Just My Code" and "Warn if no user code on lunch (Managed Only)"

Options


问:
Remote Commands fail after adding machines to TrustedHosts
I added both local and remote machine to TrustedHosts:

```<code>winrm set winrm/config/client '@{TrustedHosts="WIN-XXXXX,Windows7-1"}'
</code>```

After doing that remote commands now fail

```<code>Invoke-Command -ComputerName "Windows7-1" -Credential $cred -ScriptBlock {Rename-Computer -ComputerName 'Windows7-1' -NewName 'XXXX' -Force -PassThru -Restart }
</code>```

If I wait for 2 mins and run same code it will work fine...

答:
```<code>$hostName="DomainName"
$winrmPort = "5986"
$username = "Username"
$secpasswd = ConvertTo-SecureString “Password” -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential (“$username”, $secpasswd)
$soptions = New-PSSessionOption -SkipCACheck
Invoke-Command -ComputerName $hostName -ScriptBlock { Command Session } -Port $winrmPort -Credential $mycreds -SessionOption $soptions -UseSSL
</code>```

Body:
I added both local and remote machine to TrustedHosts:

winrm set winrm/config/client '@{TrustedHosts="WIN-XXXXX,Windows7-1"}'

After doing that remote commands now fail

Invoke-Command -ComputerName "Windows7-1" -Credential $cred -ScriptBlock {Rename-Computer -ComputerName 'Windows7-1' -NewName 'XXXX' -Force -PassThru -Restart }

If I wait for 2 mins and run same code it will work fine...


问:
Formatting with SQL DATEPART
I am using DATEPART(WEEK,mydate) to return the week number of my date, but when the week is only single number i.e. at the beginning of the year I want to format it as 01 instead of 1.

I am using SQL Server 2014, I have tried using the option format(datepart(week,mydate),'ww') but am just getting ww as my answer which as you can tell isn't quite right

答:
You can use FORMAT with d2

```<code>SELECT FORMAT(datepart(week,'2017-01-05'), 'd2')
-- RETURN 01

SELECT FORMAT(datepart(week,GETDATE()), 'd2')
-- RETURN 23
</code>```

Title: Formatting with SQL DATEPART

Body:
You can use FORMAT with d2

SELECT FORMAT(datepart(week,'2017-01-05'), 'd2')
-- RETURN 01

SELECT FORMAT(datepart(week,GETDATE()), 'd2')
-- RETURN 23


问:
UWP Binding to a property
I am making a UWP and cannot correctly grasp DataBinding and INotifyPropertyChanged
I am trying to bind some TextBox in a ContentDialog to properties in my code-behind cs file.

Here's my view model:

```<code>class UserViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public string _fname { get; set; }
    public string _lname { get; set; }

    public string Fname
    {
        get { return _fname; }
        set
        {
            _fname = value;
            this.OnPropertyChanged();
        }
    }

    public string Lname
    {
        get { return _lname; }
        set
        {
            _lname = value;
            this.OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Code behind:

```<code>public sealed partial class MainPage : Page
{
    UserViewModel User { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        User = new UserViewModel();
    }
    ....
    ....
    private void SomeButton_Click(object sender, TappedRoutedEventArgs e)
    {
        //GetUserDetails is a static method that returns UserViewModel
        User = UserStore.GetUserDetails();

        //show the content dialog
        ContentDialogResult result = await UpdateUserDialog.ShowAsync();
    }
}
</code>```

Here's the XAML for the ContentDialog:

```<code><ContentDialog Name="UpdateUserDialog">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"></ColumnDefinition>
        <ColumnDefinition Width="1*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbFirstNameUpdate"
        Text="{x:Bind Path=User.Fname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>

    <TextBox Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbLastNameUpdate"
        Text="{x:Bind Path=User.Lname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>
</ContentDialog>
</code>```

NOTE: Binding works well when I initialize the view model in the MainPage constructor itself like this:

```<code>User = new UserViewModel { Fname = "name", Lname = "name" };
</code>```

答:
You don't fire a PropertyChanged event when you replace the value of the User property with a new view model instance.

You may however simply replace

```<code>User = UserStore.GetUserDetails();
</code>```

by

```<code>var user = UserStore.GetUserDetails();
User.Fname = user.Fname;
User.Lname = user.Lname;
</code>```

and hence update the existing instance of your view model.

Title: UWP Binding to a property

Body:
I am making a UWP and cannot correctly grasp DataBinding and INotifyPropertyChanged
I am trying to bind some TextBox in a ContentDialog to properties in my code-behind cs file.

Here's my view model:

class UserViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public string _fname { get; set; }
    public string _lname { get; set; }

    public string Fname
    {
        get { return _fname; }
        set
        {
            _fname = value;
            this.OnPropertyChanged();
        }
    }

    public string Lname
    {
        get { return _lname; }
        set
        {
            _lname = value;
            this.OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Code behind:

public sealed partial class MainPage : Page
{
    UserViewModel User { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        User = new UserViewModel();
    }
    ....
    ....
    private void SomeButton_Click(object sender, TappedRoutedEventArgs e)
    {
        //GetUserDetails is a static method that returns UserViewModel
        User = UserStore.GetUserDetails();

        //show the content dialog
        ContentDialogResult result = await UpdateUserDialog.ShowAsync();
    }
}

Here's the XAML for the ContentDialog:

<ContentDialog Name="UpdateUserDialog">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"></ColumnDefinition>
        <ColumnDefinition Width="1*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbFirstNameUpdate"
        Text="{x:Bind Path=User.Fname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>

    <TextBox Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbLastNameUpdate"
        Text="{x:Bind Path=User.Lname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>
</ContentDialog>

NOTE: Binding works well when I initialize the view model in the MainPage constructor itself like this:

User = new UserViewModel { Fname = "name", Lname = "name" };

Body:
You don't fire a PropertyChanged event when you replace the value of the User property with a new view model instance.

You may however simply replace

User = UserStore.GetUserDetails();

by

var user = UserStore.GetUserDetails();
User.Fname = user.Fname;
User.Lname = user.Lname;

and hence update the existing instance of your view model.


问:
Django gettext doesn't works
I try to serve my django-cms website in multiple languages

makemessages and compilemessages works like a charm, but when I runserver , my strings stay untranslated

The python files where i used ugettext_lazy:

```<code>from cms.toolbar_pool import toolbar_pool
from cms.extensions.toolbar import ExtensionToolbar
from django.utils.translation import ugettext_lazy as _
from .models import CategoryExtension

@toolbar_pool.register
class CategoryExtensionToolbar(ExtensionToolbar):
    # defines the model for the current toolbar
    model = CategoryExtension

    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu:
            # retrieves the instance of the current extension (if any) and the toolbar item URL
            page_extension, url = self.get_page_extension_admin()
            if url:
                # adds a toolbar item in position 0 (at the top of the menu)
                current_page_menu.add_modal_item(_('Page Category'), url=url,
                                                 disabled=not self.toolbar.edit_mode, position=0)
</code>```

My settings related to translations :

```<code>def gettext(s):
    return s

LOCALE_PATHS = (
    BASE_DIR + "/locale",
)

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'Europe/Paris'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGES = (
    ('fr-fr', gettext('fr-fr')),
)

CMS_LANGUAGES = {
    1: [
        {
            'code': 'fr-fr',
            'name': gettext('fr-fr'),
            'redirect_on_fallback': True,
            'public': True,
            'hide_untranslated': False,
        },
    ],
    'default': {
        'redirect_on_fallback': True,
        'public': True,
        'hide_untranslated': False,
    },
}
</code>```

And my po file (in PROJECT_ROOT/locale/fr-fr/LC_MESSAGES/django.po) :

```<code># SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE
# package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-06-06 19:11+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#: myapp/cms_toolbars.py:22
msgid "Page Category"
msgstr "Catégorie de Page"

#: myapp/configuration/cms_settings.py:6
msgid "Page"
msgstr "Page"

#: myapp/configuration/cms_settings.py:7
msgid "Page with instagram pictures"
msgstr "Page avec bandeau instagram"

#: myapp/configuration/cms_settings.py:8
msgid "Page who list children"
msgstr "Page qui liste ses enfants"

#: myapp/configuration/i18n_settings.py:25
#: myapp/configuration/i18n_settings.py:32
msgid "fr-fr"
msgstr "fr-fr"
</code>```

答:
I think your LANGUAGES setting is incorrect, please try this: </p>

```<code>LANGUAGES = [
    ('fr', gettext('French')),
]
</code>```

Title: Django gettext doesn't works

Body:
I try to serve my django-cms website in multiple languages

makemessages and compilemessages works like a charm, but when I runserver , my strings stay untranslated

The python files where i used ugettext_lazy:

from cms.toolbar_pool import toolbar_pool
from cms.extensions.toolbar import ExtensionToolbar
from django.utils.translation import ugettext_lazy as _
from .models import CategoryExtension

@toolbar_pool.register
class CategoryExtensionToolbar(ExtensionToolbar):
    # defines the model for the current toolbar
    model = CategoryExtension

    def populate(self):
        # setup the extension toolbar with permissions and sanity checks
        current_page_menu = self._setup_extension_toolbar()

        # if it's all ok
        if current_page_menu:
            # retrieves the instance of the current extension (if any) and the toolbar item URL
            page_extension, url = self.get_page_extension_admin()
            if url:
                # adds a toolbar item in position 0 (at the top of the menu)
                current_page_menu.add_modal_item(_('Page Category'), url=url,
                                                 disabled=not self.toolbar.edit_mode, position=0)

My settings related to translations :

def gettext(s):
    return s

LOCALE_PATHS = (
    BASE_DIR + "/locale",
)

LANGUAGE_CODE = 'fr-fr'

TIME_ZONE = 'Europe/Paris'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGES = (
    ('fr-fr', gettext('fr-fr')),
)

CMS_LANGUAGES = {
    1: [
        {
            'code': 'fr-fr',
            'name': gettext('fr-fr'),
            'redirect_on_fallback': True,
            'public': True,
            'hide_untranslated': False,
        },
    ],
    'default': {
        'redirect_on_fallback': True,
        'public': True,
        'hide_untranslated': False,
    },
}

And my po file (in PROJECT_ROOT/locale/fr-fr/LC_MESSAGES/django.po) :

# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE
# package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2017-06-06 19:11+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"

#: myapp/cms_toolbars.py:22
msgid "Page Category"
msgstr "Catégorie de Page"

#: myapp/configuration/cms_settings.py:6
msgid "Page"
msgstr "Page"

#: myapp/configuration/cms_settings.py:7
msgid "Page with instagram pictures"
msgstr "Page avec bandeau instagram"

#: myapp/configuration/cms_settings.py:8
msgid "Page who list children"
msgstr "Page qui liste ses enfants"

#: myapp/configuration/i18n_settings.py:25
#: myapp/configuration/i18n_settings.py:32
msgid "fr-fr"
msgstr "fr-fr"

Body:
I think your LANGUAGES setting is incorrect, please try this:

LANGUAGES = [
    ('fr', gettext('French')),
]


问:
Xamarin - Refresh list after PopAsync()
I am writing an application using Xamarin-forms. When I navigate away from my page which edits a list, using popAsync() , I want to refresh a list on the previous page so that my changes are shown.

my PopulateMachineSelectionList() adds my machine objects to the list.

This is what I've tried so far

```<code>    protected override void OnAppearing()
    {

        PopulateMachineSelectionList();
        base.OnAppearing();
    }

    async void PopulateMachineSelectionList()
    {
        loadedMachines = await machineSync.GetMachines();
        if (loadedMachines.Count() != 0)
        {
            machineSelectionList.Clear();

            foreach (Machine mach in loadedMachines)
            { //I have an archive boolean that determines whether or not machines should be shown
                if (!mach.archived)
                {
                    Console.WriteLine("Adding: " + mach.name + " to the list template");
                    machineSelectionList.Add(new ListTemplate(null, mach.name, true, true));
                }
            }
            Console.WriteLine("Refresh List");
            machineList.ItemsSource = machineSelectionList;

        }
        machineList.SelectedItem = null;

    }
</code>```

答:
If you have a page A (with the ListView) and a page B (that edit the list binded to ListView) I think you can pass pageAViewModel (that should have the "list") to pageB, and modify it. You should have your changes automatically updated to PageA (if you use ObservableCollection and INPC).

Otherwise you could use MessagingCenter. Send a Message from B to A before the Pop and on "Subscribe" set your ItemsSource again

Title: Xamarin - Refresh list after PopAsync()

Body:
I am writing an application using Xamarin-forms. When I navigate away from my page which edits a list, using popAsync() , I want to refresh a list on the previous page so that my changes are shown.

my PopulateMachineSelectionList() adds my machine objects to the list.

This is what I've tried so far

    protected override void OnAppearing()
    {

        PopulateMachineSelectionList();
        base.OnAppearing();
    }

    async void PopulateMachineSelectionList()
    {
        loadedMachines = await machineSync.GetMachines();
        if (loadedMachines.Count() != 0)
        {
            machineSelectionList.Clear();

            foreach (Machine mach in loadedMachines)
            { //I have an archive boolean that determines whether or not machines should be shown
                if (!mach.archived)
                {
                    Console.WriteLine("Adding: " + mach.name + " to the list template");
                    machineSelectionList.Add(new ListTemplate(null, mach.name, true, true));
                }
            }
            Console.WriteLine("Refresh List");
            machineList.ItemsSource = machineSelectionList;

        }
        machineList.SelectedItem = null;

    }


问:
multiple div's shown with select option
Im still kind of new to scripts, but i know what im trying to do is not impossible. im trying to use a select option to show div's, I have it currently so it shows 1 div at a time currently but I cannot get it to show 2 separate divs at the same time. so for example im trying to select option 1, and to unhide the same selected options that were selected.
I tried what was suggested in "Can an Option in a Select tag carry multiple values?"

but none of it worked

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>
</div>

<div class="temps">
<div id="temp1" class="initial"><?php include "temp1.php"; ?></div>
<div id="temp2" class="initial"><?php include "temp2.php"; ?></div>
</div>

<div class="forms">
<div id="form1" class="initial"><?php include "form1.php"; ?></div>
<div id="form2" class="initial"><?php include "form2.php"; ?></div>
</div></code>```

答:
document.getElementById('target').addEventListener('change', function () {
  let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"

  for (let i = 0; i < divs.length; i++) {
    // loop over all divs
    let div = divs[i];
    if (div.classList.contains(this.value)) {
      // the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
      div.classList.remove('initial');
      div.classList.add('vis'); // make the div visible
    } else {
      div.classList.add('initial');
      div.classList.remove('vis'); // otherwise make the divs invisible
    }
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.initial {
  display: none;
}</code>```

  <select name="dropdown" id="target">
    <option value="option-1">option1</option>
    <option value="option-2">option2</option>
  </select>

Temp 1

Temp 2

Form 1

Form 2

```

Title: multiple div's shown with select option

Body:
Im still kind of new to scripts, but i know what im trying to do is not impossible. im trying to use a select option to show div's, I have it currently so it shows 1 div at a time currently but I cannot get it to show 2 separate divs at the same time. so for example im trying to select option 1, and to unhide the same selected options that were selected.
I tried what was suggested in "Can an Option in a Select tag carry multiple values?"

but none of it worked

<select name="dropdown" id='target'>
<option value="temp1" value2="form1">option1</option>
<option value="temp2" value2="form2">option2</option>
</select>

<?php include "temp1.php"; ?>

<?php include "temp2.php"; ?>

<?php include "form1.php"; ?>

<?php include "form2.php"; ?>

Body:
document.getElementById('target').addEventListener('change', function () {
  let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"

  for (let i = 0; i < divs.length; i++) {
    // loop over all divs
    let div = divs[i];
    if (div.classList.contains(this.value)) {
      // the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
      div.classList.remove('initial');
      div.classList.add('vis'); // make the div visible
    } else {
      div.classList.add('initial');
      div.classList.remove('vis'); // otherwise make the divs invisible
    }
  }

});

.initial {
  display: none;
}

<div class="header">
  <select name="dropdown" id="target">
    <option value="option-1">option1</option>
    <option value="option-2">option2</option>
  </select>
</div>

<div class="temps">
  <div class="initial option-1">Temp 1</div>
  <div class="initial option-2">Temp 2</div>
</div>

<div class="forms">
  <div class="initial option-1">Form 1</div>
  <div class="initial option-2">Form 2</div>
</div>


问:
Three.js | How to use object's child's property outside loader.load
I need to update the object's color property dynamically using dat.GUI().
It was simple if the object is created using three.js geometry but as I'm working on an imported object (.obj & .mtl), I need to update the property outside the loader.load function.
How can I achieve it?

edit:

```<code>var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/Cube/' );
mtlLoader.load( 'cube.mtl', function( materials ) {
materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials( materials );
    objLoader.setPath( 'obj/Cube/' );
    objLoader.load( 'cube.obj', function( object ) {
        object.traverse( function( child ) {
            if ( child instanceof THREE.Mesh ) {
                child.castShadow = true;
                child.material.color.set( 0x00ff00 );  // change color without dat.GUI
            }
        } );
    companion = object;
    scene.add( object );
    });
});

gui = new dat.GUI();

parameters =
{
    color: "#ff0000",
    visible: true,
};

var objColor = gui.addColor( parameters, 'color' ).name('Color (Diffuse)').listen();
objColor.onChange(function(value) // onFinishChange
{   companion.material.color.setHex( value.replace("#", "0x") );   });

gui.open();
updateColor(companion);
</code>```

```<code>function updateColor(obj)
{
    obj.material.color.setHex( parameters.color.replace("#", "0x") ); //I need to use the property here.
}
</code>```

答:
How about this? - </p>

```<code>objColor.onChange(function(value) // onFinishChange
{
    companion.traverse( function( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.material.color.setHex(value.replace("#", "0x"));
            child.material.needsUpdate = true;
        }
    } );
});
</code>```

Body:
I need to update the object's color property dynamically using dat.GUI().
It was simple if the object is created using three.js geometry but as I'm working on an imported object (.obj & .mtl), I need to update the property outside the loader.load function.
How can I achieve it?

edit:

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/Cube/' );
mtlLoader.load( 'cube.mtl', function( materials ) {
materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials( materials );
    objLoader.setPath( 'obj/Cube/' );
    objLoader.load( 'cube.obj', function( object ) {
        object.traverse( function( child ) {
            if ( child instanceof THREE.Mesh ) {
                child.castShadow = true;
                child.material.color.set( 0x00ff00 );  // change color without dat.GUI
            }
        } );
    companion = object;
    scene.add( object );
    });
});

gui = new dat.GUI();

parameters =
{
    color: "#ff0000",
    visible: true,
};

var objColor = gui.addColor( parameters, 'color' ).name('Color (Diffuse)').listen();
objColor.onChange(function(value) // onFinishChange
{   companion.material.color.setHex( value.replace("#", "0x") );   });

gui.open();
updateColor(companion);

function updateColor(obj)
{
    obj.material.color.setHex( parameters.color.replace("#", "0x") ); //I need to use the property here.
}

Body:
How about this? -

objColor.onChange(function(value) // onFinishChange
{
    companion.traverse( function( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.material.color.setHex(value.replace("#", "0x"));
            child.material.needsUpdate = true;
        }
    } );
});


问:
add string dynamically in objc
I want to add string value dynamically from result.text and I wanted to display it in this way [@"17052648287",@"17052607335"] without losing the value. How can I do it?

```<code>NSMutableArray *strings = [@[@"17052648287",@"17052607335"] mutableCopy];
</code>```

Add on coding

```<code>- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result{
    if (!result) return;

if(self.hasScannedResult == NO)
{
    //Scan Result, added into array
    NSString *scanPackage = [NSString stringWithFormat:@"%@", result.text];

    scanLists = [NSMutableArray new];
    [scanLists addObject:scanPackage];

    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    NSMutableArray *strings = [[NSMutableArray alloc]init];
    strings = [@[result.text] mutableCopy];
    [preferences setObject:strings forKey:@"strings"];
    NSMutableArray *stringsArray = [preferences objectForKey:@"strings"];
    for (NSString *string in stringsArray) {
        NSLog(@"string: %@", string);
    }
</code>```

答:
Declare an results array: </p>

```<code>NSMutableArray * array = [NSMutableArray new];
</code>```

<p>Write below code where you get your result.text: </p>

```<code>NSString *scanPackage = [NSString stringWithFormat:@"%@", result.text]; // If this code is working for you
[array addObject: scanPackage];
NSString *combined = [array componentsJoinedByString:@","];
NSLog(@"combined: %@", combined);
</code>```

Title: add string dynamically in objc

Body:
I want to add string value dynamically from result.text and I wanted to display it in this way [@"17052648287",@"17052607335"] without losing the value. How can I do it?

NSMutableArray *strings = [@[@"17052648287",@"17052607335"] mutableCopy];

Add on coding

- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result{
    if (!result) return;

if(self.hasScannedResult == NO)
{
    //Scan Result, added into array
    NSString *scanPackage = [NSString stringWithFormat:@"%@", result.text];

    scanLists = [NSMutableArray new];
    [scanLists addObject:scanPackage];

    NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
    NSMutableArray *strings = [[NSMutableArray alloc]init];
    strings = [@[result.text] mutableCopy];
    [preferences setObject:strings forKey:@"strings"];
    NSMutableArray *stringsArray = [preferences objectForKey:@"strings"];
    for (NSString *string in stringsArray) {
        NSLog(@"string: %@", string);
    }

Body:
Declare an results array:

NSMutableArray * array = [NSMutableArray new];

Write below code where you get your result.text:

NSString *scanPackage = [NSString stringWithFormat:@"%@", result.text]; // If this code is working for you
[array addObject: scanPackage];
NSString *combined = [array componentsJoinedByString:@","];
NSLog(@"combined: %@", combined);


问:
ASP.NET web api token expiration time did not work on server
I set up the expiration time of my token to 200 days. It worked fine locally, but after I upload this to server, it appears that it just keeps defaulting to 20 minutes. </p>

```<code> OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new
                     PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(200),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };
</code>```

答:
using variable for new OAuthAuthorizationServerOptions

```<code>  public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {   AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };
</code>```

and then using generator

```<code>app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
</code>```

Body:
I set up the expiration time of my token to 200 days. It worked fine locally, but after I upload this to server, it appears that it just keeps defaulting to 20 minutes.

 OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new
                     PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(200),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

Body:
using variable for new OAuthAuthorizationServerOptions

  public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {   AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

and then using generator

app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


问:
How to find the TypeOf a VB6 control in VB.NET
I am writing a .NET DLL to iterate through all controls in the a VB6 Form passed byref.

So far it seems to work VB.NET code:

```<code>Public Sub AddFormRefLegacy(ByRef strAppName As String, ByRef objForm As Object)

        'update the forms caption
        objForm.Caption = FindValue(strAppName, objForm.Name, "", "0", objForm.Caption)

        'iterate through all the controls on the form
        For Each ctl As Object In objForm.Controls
           if TypeOf ctl is Label then
             'this doesn't pick up any labels
           end if
        Next
    End Sub
</code>```

Called from this VB6 code:

```<code>Dim libDD As New Lib.clsDataDictionary
libDD.AddFormRefLegacy "nnne", Me
</code>```

but the TypeOf operator does not work. Is there another way to find the type of control?

答:
Could it be you're comparing two different "Label" type objects.

You haven't qualified the LABEL type in the IF TYPEOF line, so you could be comparing a VB6 label to a .net label, and they wouldn't be the same.

You could use TYPENAME, but that might not be exactly what you need iether. I'd make sure you're really comparing the types that you think you're comparing.

Body:
I am writing a .NET DLL to iterate through all controls in the a VB6 Form passed byref.

So far it seems to work VB.NET code:

Public Sub AddFormRefLegacy(ByRef strAppName As String, ByRef objForm As Object)

        'update the forms caption
        objForm.Caption = FindValue(strAppName, objForm.Name, "", "0", objForm.Caption)

        'iterate through all the controls on the form
        For Each ctl As Object In objForm.Controls
           if TypeOf ctl is Label then
             'this doesn't pick up any labels
           end if
        Next
    End Sub

Called from this VB6 code:

Dim libDD As New Lib.clsDataDictionary
libDD.AddFormRefLegacy "nnne", Me

but the TypeOf operator does not work. Is there another way to find the type of control?


问:
Button asks for a URL then opens it?
I have a webView of a URL that works great but I also have a link that needs some info to load.

```<code>mylink.com/page.php?name=Stack
</code>```

How can I make a button ask for the user's name then put it in the link and load the webView?

i.e: popup asks for a username (user puts the name as "Stack") and 'Stack' gets moved into the URL and loaded.

答:
I think this below can help you:

```<code>function goUrl() {
     var name = prompt("Please enter your name", "Place holder");
     console.log(name);
     window.location.href = 'https://www.google.com/search?q=' + name;
 };
</code>```

Function prompt() opens an popup from your browser with text field. The function returns what you have put in the text field so that you can use it anywhere you want eg. you can put the code above into a function that is being call on button click:

```<code><button onclick="goUrl()">Click it!</button>
</code>```

Title: Button asks for a URL then opens it?

Body:
I have a webView of a URL that works great but I also have a link that needs some info to load.

mylink.com/page.php?name=Stack

How can I make a button ask for the user's name then put it in the link and load the webView?

i.e: popup asks for a username (user puts the name as "Stack") and 'Stack' gets moved into the URL and loaded.

Body:
I think this below can help you:

function goUrl() {
     var name = prompt("Please enter your name", "Place holder");
     console.log(name);
     window.location.href = 'https://www.google.com/search?q=' + name;
 };

Function prompt() opens an popup from your browser with text field. The function returns what you have put in the text field so that you can use it anywhere you want eg. you can put the code above into a function that is being call on button click:

<button onclick="goUrl()">Click it!</button>