问:
slideside menu doesn't hide when click on another slideside menu or dropdown menu
I have created a menu similar to the Dropdown menu of bootstrap, the minor difference is, it doesn't slide down, instead, it slides left side on click and this is working fine. But the issue is I want that it must be closed when clicked on another menu(slideside or dropdown) but it is not working when I try to click on another menu link( which is not child or parent of the same slideside menu). It doesn't disappear as dropdown menu disappears when clicked on another menu.However, if I clicked outside anywhere on the window it closes the menu. Take a look at my code which I have taken from bootstrap plugin.
I have used the bootstrap clearMenus function to close the menus and edited however it doesn't resolve my problem. As I snippet you will see if I clicked on both category button they will overlap and I want if I click on another category then it must close the other open cateogry.

var toggle   = '[data-toggle="slideside"]'
     var Slideside = function (element) {
    $(element).on('click', this.toggle)
     }
function getParent($this) {
    var selector = $this.attr('data-target')
    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }
    var $parent = selector && $(selector)
    return $parent && $parent.length ? $parent : $this.parent()
   }
   $(".slideside-toggle").on('click',function(e){
    e.preventDefault();
    var expand ;
    $this = $(this);
    $parent = getParent($this);
    $slide = $this.next('ul').children('.after-slideside');
    if($this.attr('aria-expanded') === 'true')
     expand = 'false';
    else
     expand = 'true';

    $this.attr('aria-expanded', 'true');
    $slide.toggleClass("open");
   });
   $(document).on('click',clearMenus);
   function clearMenus(e){
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var $slide   = $this.next('ul').children('.after-slideside');
      if (!$slide.hasClass('open')) return
      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
      if (e.isDefaultPrevented()) return
      $this.attr('aria-expanded', 'false')
      $slide.removeClass('open')
    })
   }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideside-toggle i.fa-angle-right{
    padding-right:0;
   }
   li.after-slideside{
    position:absolute;
    right:-250px;
    width:250px;
    background-color:ghostwhite;
    transition: all 0.35s linear;
   }
   nav li.open.after-slideside > a{
    padding-left:8px;
    text-align:center;
    border-bottom:1px solid #ececec;
    color:#acacac;
   }
   nav li.open.after-slideside >ul{
    padding-left:0;
   }
   nav li.open.after-slideside >ul>li{
    border-bottom:1px solid #ececec;
   }
   .open.after-slideside{
    right:0;
    transition:all 0.35s linear;
    z-index:1;
   }</code>```

<link href="http://www.hetrotech.in/css/color.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Account

Not Logged In ?

<button class="btn btn-primary" onClick="window.location.href='user.html';">Login</button>

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

```

答:
Remove class open to .after-slideside and .dropdown in slideside-toggle click event

var toggle   = '[data-toggle="slideside"]'
     var Slideside = function (element) {
    $(element).on('click', this.toggle)
     }
function getParent($this) {
    var selector = $this.attr('data-target')
    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }
    var $parent = selector && $(selector)
    return $parent && $parent.length ? $parent : $this.parent()
   }
   $(".slideside-toggle").on('click',function(e){
    e.preventDefault();
    var expand ;
    $this = $(this);
    $parent = getParent($this);
$parent.siblings().find('.after-slideside, .dropdown').removeClass('open');
    $slide = $this.next('ul').children('.after-slideside');
    if($this.attr('aria-expanded') === 'true')
     expand = 'false';
    else
     expand = 'true';

    $this.attr('aria-expanded', 'true');
    $slide.toggleClass("open");
   });
   $(".dropdown").on('click',function(e){
$(this).siblings().find('.after-slideside, .dropdown').removeClass('open');

   });
   $(document).on('click',clearMenus);
   function clearMenus(e){
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var $slide   = $this.next('ul').children('.after-slideside');
      if (!$slide.hasClass('open')) return
      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
      if (e.isDefaultPrevented()) return
      $this.attr('aria-expanded', 'false')
      $slide.removeClass('open')
    })
   }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slideside-toggle i.fa-angle-right{
    padding-right:0;
   }
   li.after-slideside{
    position:absolute;
    right:-250px;
    width:250px;
    background-color:ghostwhite;
    transition: all 0.35s linear;
   }
   nav li.open.after-slideside > a{
    padding-left:8px;
    text-align:center;
    border-bottom:1px solid #ececec;
    color:#acacac;
   }
   nav li.open.after-slideside >ul{
    padding-left:0;
   }
   nav li.open.after-slideside >ul>li{
    border-bottom:1px solid #ececec;
   }
   .open.after-slideside{
    right:0;
    transition:all 0.35s linear;
    z-index:1;
   }</code>```

<link href="http://www.hetrotech.in/css/color.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Account

Not Logged In ?

<button class="btn btn-primary" onClick="window.location.href='user.html';">Login</button>

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

```

Body:
I have created a menu similar to the Dropdown menu of bootstrap, the minor difference is, it doesn't slide down, instead, it slides left side on click and this is working fine. But the issue is I want that it must be closed when clicked on another menu(slideside or dropdown) but it is not working when I try to click on another menu link( which is not child or parent of the same slideside menu). It doesn't disappear as dropdown menu disappears when clicked on another menu.However, if I clicked outside anywhere on the window it closes the menu. Take a look at my code which I have taken from bootstrap plugin.
I have used the bootstrap clearMenus function to close the menus and edited however it doesn't resolve my problem. As I snippet you will see if I clicked on both category button they will overlap and I want if I click on another category then it must close the other open cateogry.

var toggle   = '[data-toggle="slideside"]'
     var Slideside = function (element) {
    $(element).on('click', this.toggle)
     }
function getParent($this) {
    var selector = $this.attr('data-target')
    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }
    var $parent = selector && $(selector)
    return $parent && $parent.length ? $parent : $this.parent()
   }
   $(".slideside-toggle").on('click',function(e){
    e.preventDefault();
    var expand ;
    $this = $(this);
    $parent = getParent($this);
    $slide = $this.next('ul').children('.after-slideside');
    if($this.attr('aria-expanded') === 'true')
     expand = 'false';
    else
     expand = 'true';

    $this.attr('aria-expanded', 'true');
    $slide.toggleClass("open");
   });
   $(document).on('click',clearMenus);
   function clearMenus(e){
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var $slide   = $this.next('ul').children('.after-slideside');
      if (!$slide.hasClass('open')) return
      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
      if (e.isDefaultPrevented()) return
      $this.attr('aria-expanded', 'false')
      $slide.removeClass('open')
    })
   }

.slideside-toggle i.fa-angle-right{
    padding-right:0;
   }
   li.after-slideside{
    position:absolute;
    right:-250px;
    width:250px;
    background-color:ghostwhite;
    transition: all 0.35s linear;
   }
   nav li.open.after-slideside > a{
    padding-left:8px;
    text-align:center;
    border-bottom:1px solid #ececec;
    color:#acacac;
   }
   nav li.open.after-slideside >ul{
    padding-left:0;
   }
   nav li.open.after-slideside >ul>li{
    border-bottom:1px solid #ececec;
   }
   .open.after-slideside{
    right:0;
    transition:all 0.35s linear;
    z-index:1;
   }

<link href="http://www.hetrotech.in/css/color.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

          Account

Not Logged In ?

<button class="btn btn-primary" onClick="window.location.href='user.html';">Login</button>

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

         Category 1

20% Sale

Product1

                     Product2

40% Sale

Product1

Product2

Product3

Product4

Product3

Product4

Body:
Remove class open to .after-slideside and .dropdown in slideside-toggle click event

var toggle   = '[data-toggle="slideside"]'
     var Slideside = function (element) {
    $(element).on('click', this.toggle)
     }
function getParent($this) {
    var selector = $this.attr('data-target')
    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }
    var $parent = selector && $(selector)
    return $parent && $parent.length ? $parent : $this.parent()
   }
   $(".slideside-toggle").on('click',function(e){
    e.preventDefault();
    var expand ;
    $this = $(this);
    $parent = getParent($this);
$parent.siblings().find('.after-slideside, .dropdown').removeClass('open');
    $slide = $this.next('ul').children('.after-slideside');
    if($this.attr('aria-expanded') === 'true')
     expand = 'false';
    else
     expand = 'true';

    $this.attr('aria-expanded', 'true');
    $slide.toggleClass("open");
   });
   $(".dropdown").on('click',function(e){
$(this).siblings().find('.after-slideside, .dropdown').removeClass('open');

   });
   $(document).on('click',clearMenus);
   function clearMenus(e){
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var $slide   = $this.next('ul').children('.after-slideside');
      if (!$slide.hasClass('open')) return
      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
      if (e.isDefaultPrevented()) return
      $this.attr('aria-expanded', 'false')
      $slide.removeClass('open')
    })
   }

.slideside-toggle i.fa-angle-right{
    padding-right:0;
   }
   li.after-slideside{
    position:absolute;
    right:-250px;
    width:250px;
    background-color:ghostwhite;
    transition: all 0.35s linear;
   }
   nav li.open.after-slideside > a{
    padding-left:8px;
    text-align:center;
    border-bottom:1px solid #ececec;
    color:#acacac;
   }
   nav li.open.after-slideside >ul{
    padding-left:0;
   }
   nav li.open.after-slideside >ul>li{
    border-bottom:1px solid #ececec;
   }
   .open.after-slideside{
    right:0;
    transition:all 0.35s linear;
    z-index:1;
   }

<link href="http://www.hetrotech.in/css/color.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
   <ul class="nav sidebar-nav">
      <li class="divider"></li>
      <li class="dropdown">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-sliders"></i> Account<span class="caret"></span></a>
         <ul class="dropdown-menu" role="menu">
            <li class="dropdown-header">Not Logged In ?</li>
            <li class="button"><button class="btn btn-primary" onClick="window.location.href='user.html';"><i class="fa fa-fw fa-sign-in"></i>Login</button></li>
         </ul>
      </li>
      <li class="before-slideside" id="category">
         <a href="#" class="slideside-toggle" data-toggle="slideside" aria-expanded="false"><i class="fa fa-fw fa-list-alt"></i>Category 1 <span class="pull-right"><i class="fa fa-fw fa-angle-right"></i></span></a>
         <ul class="slideside-menu">
            <li class="after-slideside">
               <ul class="slideside-menu" role="menu">
                  <li class="dropdown-header">20% Sale</li>
                  <li><a href="#">Product1</a></li>
                  <li>
                     <a href="#" class="slideside-toggle" data-toggle="slideside" aria-expanded="false">Product2 <span class="pull-right"><i class="fa fa-fw fa-angle-right"></i></span></a>
                     <ul class="slideside-menu">
                        <li class="after-slideside">
                           <ul class="slideside-menu" role="menu">
                              <li class="dropdown-header">40% Sale</li>
                              <li><a href="#">Product1</a></li>
                              <li><a href="#">Product2</a></li>
                              <li><a href="#">Product3</a></li>
                              <li><a href="#">Product4</a></li>
                           </ul>
                        </li>
                     </ul>
                  </li>
                  <li><a href="#">Product3</a></li>
                  <li><a href="#">Product4</a></li>
               </ul>
            </li>
         </ul>
      </li>
      <li class="before-slideside" id="category">
         <a href="#" class="slideside-toggle" data-toggle="slideside" aria-expanded="false"><i class="fa fa-fw fa-list-alt"></i>Category 1 <span class="pull-right"><i class="fa fa-fw fa-angle-right"></i></span></a>
         <ul class="slideside-menu">
            <li class="after-slideside">
               <ul class="slideside-menu" role="menu">
                  <li class="dropdown-header">20% Sale</li>
                  <li><a href="#">Product1</a></li>
                  <li>
                     <a href="#" class="slideside-toggle" data-toggle="slideside" aria-expanded="false">Product2 <span class="pull-right"><i class="fa fa-fw fa-angle-right"></i></span></a>
                     <ul class="slideside-menu">
                        <li class="after-slideside">
                           <ul class="slideside-menu" role="menu">
                              <li class="dropdown-header">40% Sale</li>
                              <li><a href="#">Product1</a></li>
                              <li><a href="#">Product2</a></li>
                              <li><a href="#">Product3</a></li>
                              <li><a href="#">Product4</a></li>
                           </ul>
                        </li>
                     </ul>
                  </li>
                  <li><a href="#">Product3</a></li>
                  <li><a href="#">Product4</a></li>
               </ul>
            </li>
         </ul>
      </li>
   </ul>
</nav>


来源: stackexchange

问:
Reading/writing an INI file
Is there any class in the .NET framework that can read/write standard .ini files:

```<code>[Section]
<keyname>=<value>
...
</code>```

Delphi has the TIniFile component and I want to know if there is anything similar for C#?

答:
If you only need read access and not write access and you are using the Microsoft.Extensions.Confiuration (comes bundled in by default with ASP.NET Core but works with regular programs too) you can use the NuGet package Microsoft.Extensions.Configuration.Ini to import ini files in to your configuration settings.

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddIniFile("SomeConfig.ini", optional: false);
    Configuration = builder.Build();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reading/writing an INI file

Body:
Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
<keyname>=<value>
...

Delphi has the TIniFile component and I want to know if there is anything similar for C#?

Body:
If you only need read access and not write access and you are using the Microsoft.Extensions.Confiuration (comes bundled in by default with ASP.NET Core but works with regular programs too) you can use the NuGet package Microsoft.Extensions.Configuration.Ini to import ini files in to your configuration settings.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddIniFile("SomeConfig.ini", optional: false);
    Configuration = builder.Build();
}


问:
How to get IPN status after success full payment in paypal express checkout using checkout.js
I have implemented the new paypal express checkout. I want to pass my success_ipn.php URL and cancelled.php URL to checkout.js.

I have done lots of google and as well as official doc Paypal DOC.

Below is my file code:

```<code><!DOCTYPE html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>
</head>

<body>
    <div id="paypal-button-container"></div>

    <script>
        var EXECUTE_PAYMENT_URL = 'http://example.com/success_ipn.php';
        paypal.Button.render({

            env: 'sandbox', // sandbox | production

            // PayPal Client IDs - replace with your own
            // Create a PayPal app: https://developer.paypal.com/developer/applications/create
            client: {
                sandbox:    'My Sandbox Client ID here.',
                //production: '<insert production client id>'
            },

            // Show the buyer a 'Pay Now' button in the checkout flow
            commit: true,

            // payment() is called when the button is clicked
            payment: function(data, actions) {

                // Make a call to the REST api to create the payment
                return actions.payment.create({
                    payment: {
                        transactions: [
                            {
                                amount: { total: '0.01', currency: 'USD' }
                            }
                        ]
                    }
                });
            },

            // onAuthorize() is called when the buyer approves the payment
            onAuthorize: function(data, actions) {
                return paypal.request.post(EXECUTE_PAYMENT_URL, {
                    paymentID: data.paymentID,
                    payerID:   data.payerID
                }).then(function() {
                        window.alert('Payment Complete!');
                });
            }

        }, '#paypal-button-container');

    </script>
</body>
</html>
</code>```

It's working fine, but how I can pass my IPN file URL and Cancel URL.

After do some more google on this I can get only below variables not transactions ID etc.:

```<code>paymentID: data.paymentID,
payerID:   data.payerID
</code>```

Please help me out this guys.

答:
After the tried too and do google on this I have found the solution.

The paypal has deprecated the Express Checkout - NVP/SOAP after the checckout.js newest version. So, GetExpressCheckoutDetails and DoExpressCheckoutPayment is deprecated as well.

Now, all work will be done on the Rest API.

Below is update code how we can get the Payer information and transaction details in json format. After get the json response we can update our database record as well using aJax.

```<code><script src="https://www.paypalobjects.com/api/checkout.js"></script>
  <div id="paypal-button-container"></div>

<script>
  var EXECUTE_PAYMENT_URL = 'http://example.com/success_checkout.php';

  paypal.Button.render({

      env: 'sandbox', // sandbox | production

      // PayPal Client IDs - replace with your own
      // Create a PayPal app: https://developer.paypal.com/developer/applications/create
      client: {
          sandbox:    '',
          //production: '<insert production client id>'
      },

      // Show the buyer a 'Pay Now' button in the checkout flow
      commit: true,

      // payment() is called when the button is clicked
      payment: function(data, actions) {

          // Make a call to the REST api to create the payment
          return actions.payment.create({
              payment: {
                  transactions: [
                      {
                          amount: { total: '10', currency: 'USD' },
                          custom: 'custom value here'
                      }
                  ]
              }
          });
      },
      onAuthorize: function(data, actions) {
        return actions.payment.get().then(function(payment) {
            //debugger;
            console.log(payment);
            var txn_id = payment.cart;
            var bookID = payment.transactions[0].custom;
            var currency = payment.transactions[0].amount["currency"];
            var amount = payment.transactions[0].amount["total"];
            var payerID = payment.payer.payer_info["payer_id"];
            var pstatus = payment.payer.status;

            var successUrl = EXECUTE_PAYMENT_URL+'?txn_id='+txn_id+'&bookID='+bookID+'&currency='+currency+'&amount='+amount+'&payerID='+payerID+'&pstatus='+pstatus;
            //console.log(newUrl);
           window.location.replace(successUrl);
        });
      },
      onCancel: function(data, actions) {
        var cancelUrl = "http://example.com/cancelled.php";
        //console.log(newUrl);
        window.location.replace(cancelUrl);
      }

  }, '#paypal-button-container');

</script>
</code>```

And you will get response in the success_checkout.php like below:

```<code><?php
echo '```' print_r($_REQUEST);

// do your stuff here

header('Location: thanks.php');
?>
```

Hope this will help to other developers.

Body:
I have implemented the new paypal express checkout. I want to pass my success_ipn.php URL and cancelled.php URL to checkout.js.

I have done lots of google and as well as official doc Paypal DOC.

Below is my file code:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

It's working fine, but how I can pass my IPN file URL and Cancel URL.

After do some more google on this I can get only below variables not transactions ID etc.:

paymentID: data.paymentID,
payerID:   data.payerID

Please help me out this guys.

Body:
After the tried too and do google on this I have found the solution.

The paypal has deprecated the Express Checkout - NVP/SOAP after the checckout.js newest version. So, GetExpressCheckoutDetails and DoExpressCheckoutPayment is deprecated as well.

Now, all work will be done on the Rest API.

Below is update code how we can get the Payer information and transaction details in json format. After get the json response we can update our database record as well using aJax.

<script src="https://www.paypalobjects.com/api/checkout.js"></script>
  <div id="paypal-button-container"></div>

<script>
  var EXECUTE_PAYMENT_URL = 'http://example.com/success_checkout.php';

  paypal.Button.render({

      env: 'sandbox', // sandbox | production

      // PayPal Client IDs - replace with your own
      // Create a PayPal app: https://developer.paypal.com/developer/applications/create
      client: {
          sandbox:    '',
          //production: '<insert production client id>'
      },

      // Show the buyer a 'Pay Now' button in the checkout flow
      commit: true,

      // payment() is called when the button is clicked
      payment: function(data, actions) {

          // Make a call to the REST api to create the payment
          return actions.payment.create({
              payment: {
                  transactions: [
                      {
                          amount: { total: '10', currency: 'USD' },
                          custom: 'custom value here'
                      }
                  ]
              }
          });
      },
      onAuthorize: function(data, actions) {
        return actions.payment.get().then(function(payment) {
            //debugger;
            console.log(payment);
            var txn_id = payment.cart;
            var bookID = payment.transactions[0].custom;
            var currency = payment.transactions[0].amount["currency"];
            var amount = payment.transactions[0].amount["total"];
            var payerID = payment.payer.payer_info["payer_id"];
            var pstatus = payment.payer.status;

            var successUrl = EXECUTE_PAYMENT_URL+'?txn_id='+txn_id+'&bookID='+bookID+'&currency='+currency+'&amount='+amount+'&payerID='+payerID+'&pstatus='+pstatus;
            //console.log(newUrl);
           window.location.replace(successUrl);
        });
      },
      onCancel: function(data, actions) {
        var cancelUrl = "http://example.com/cancelled.php";
        //console.log(newUrl);
        window.location.replace(cancelUrl);
      }

  }, '#paypal-button-container');

</script>

And you will get response in the success_checkout.php like below:

<?php
echo '<pre>' print_r($_REQUEST);

// do your stuff here

header('Location: thanks.php');
?>

Hope this will help to other developers.


问:
Angular2 auth guard keeps track of current user with observable
I am pretty new to Angular and
I'm trying to write a auth guard in my application,
I know I can hit my server everytime and get session info about the user that is logged in.
But I'd like to like keep track of the logged in user throughout the application...

app.component.ts

```<code>  export class AppComponent implements OnInit {
  title = 'APPTITLE';
  logged_in = true;

  constructor(private authService: AuthenticationService){}
  ngOnInit(){
    this.authService.isAuthenticated.take(1)
    .subscribe(res => {
      console.log(res);
      this.logged_in = res});
  }
}
</code>```

AuthenticationService.ts

```<code>@Injectable()
export class AuthenticationService {
    private currentUserSubject = new BehaviorSubject<IUser>(<IUser>{});
    public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();
    private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
    public isAuthenticated = this.isAuthenticatedSubject.asObservable();
    private isAdminSubject = new ReplaySubject<boolean>(1);
    public isAdmin = this.isAdminSubject.asObservable();

    constructor(private http: HttpService) {
        this.isAuthenticatedSubject.next(false);
        this.isAdminSubject.next(false);
    }

    login(username: string, password: string, onSuccess: (data) => void, onError: (data) => void=null): any {
        this.isAuthenticatedSubject.next(true);
        let query_url = 'login';
        let payload = JSON.stringify({username: username, password: password});
        return this.http.post(query_url, payload)
        .subscribe(user => {
            this.currentUserSubject.next(user);
            this.isAuthenticatedSubject.next(true);
            if (user.usertype == 'admin') this.isAdminSubject.next(true);
            onSuccess(user);
        },
        error => {
            if (onError){
                onError(error);
            }
        });
    }

    logout() {
        let query_url = 'logout';
        return this.http.post(query_url, null)
        .subscribe(res => {
            this.currentUserSubject.next(null);
            this.isAuthenticatedSubject.next(false);
            this.isAdminSubject.next(false);
        })
    }
}
</code>```

auth-guard.ts

```<code>@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private router: Router, private authService: AuthenticationService) {

  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>{
    return this.authService.isAuthenticated.take(1)
  }
}
</code>```

login.component.ts

```<code>@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthenticationService]
})

export class LoginComponent implements OnInit {
    error_message: string = 'Login Unsuccessful'
  login_info: any = {};

  constructor(public router: Router,
    private authenticationService: AuthenticationService) {

  }

  ngOnInit() {
  }

  formSubmitted(data): void {
    this.login(data.username, data.password);
  }

  login(username, password) {
    event.preventDefault();
    this.authenticationService.login(username, password, (data) => {
      console.log(data);
    },
    (err) => {
      console.log(err);
    })
}
</code>```

auth-guard will always return false here, I'm not sure why.
Are the authentication services defined in auth-guard and login different entities?

答:
```<code>return this.authService.isAuthenticated.take(1)
</code>```

Always returns the first value.

Documentation for take : Returns a specified number of contiguous elements from the start of an observable sequence

Change it to

```<code>return this.authService.isAuthenticated;
</code>```

Body:
I am pretty new to Angular and
I'm trying to write a auth guard in my application,
I know I can hit my server everytime and get session info about the user that is logged in.
But I'd like to like keep track of the logged in user throughout the application...

app.component.ts

  export class AppComponent implements OnInit {
  title = 'APPTITLE';
  logged_in = true;

  constructor(private authService: AuthenticationService){}
  ngOnInit(){
    this.authService.isAuthenticated.take(1)
    .subscribe(res => {
      console.log(res);
      this.logged_in = res});
  }
}

AuthenticationService.ts

@Injectable()
export class AuthenticationService {
    private currentUserSubject = new BehaviorSubject<IUser>(<IUser>{});
    public currentUser = this.currentUserSubject.asObservable().distinctUntilChanged();
    private isAuthenticatedSubject = new ReplaySubject<boolean>(1);
    public isAuthenticated = this.isAuthenticatedSubject.asObservable();
    private isAdminSubject = new ReplaySubject<boolean>(1);
    public isAdmin = this.isAdminSubject.asObservable();

    constructor(private http: HttpService) {
        this.isAuthenticatedSubject.next(false);
        this.isAdminSubject.next(false);
    }

    login(username: string, password: string, onSuccess: (data) => void, onError: (data) => void=null): any {
        this.isAuthenticatedSubject.next(true);
        let query_url = 'login';
        let payload = JSON.stringify({username: username, password: password});
        return this.http.post(query_url, payload)
        .subscribe(user => {
            this.currentUserSubject.next(user);
            this.isAuthenticatedSubject.next(true);
            if (user.usertype == 'admin') this.isAdminSubject.next(true);
            onSuccess(user);
        },
        error => {
            if (onError){
                onError(error);
            }
        });
    }

    logout() {
        let query_url = 'logout';
        return this.http.post(query_url, null)
        .subscribe(res => {
            this.currentUserSubject.next(null);
            this.isAuthenticatedSubject.next(false);
            this.isAdminSubject.next(false);
        })
    }
}

auth-guard.ts

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private router: Router, private authService: AuthenticationService) {

  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>{
    return this.authService.isAuthenticated.take(1)
  }
}

login.component.ts

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthenticationService]
})

export class LoginComponent implements OnInit {
    error_message: string = 'Login Unsuccessful'
  login_info: any = {};

  constructor(public router: Router,
    private authenticationService: AuthenticationService) {

  }

  ngOnInit() {
  }

  formSubmitted(data): void {
    this.login(data.username, data.password);
  }

  login(username, password) {
    event.preventDefault();
    this.authenticationService.login(username, password, (data) => {
      console.log(data);
    },
    (err) => {
      console.log(err);
    })
}

auth-guard will always return false here, I'm not sure why.
Are the authentication services defined in auth-guard and login different entities?

Body:
return this.authService.isAuthenticated.take(1)

Always returns the first value.

Documentation for take : Returns a specified number of contiguous elements from the start of an observable sequence

Change it to

return this.authService.isAuthenticated;


问:
how to check whether a string has exactly n words in mysql
Like my table consist of name street and city .
My query is to find customer name whose street address match any string of 1)exactly 3 character 2)at least 3 character</p>

答: It should help you: WHERE CustomerName LIKE 'a_%_%'   Finds any values that start with "a" and are at least 3 characters in length


问:
MySQL Statement that reads data from multiple rows
I need to do a complicated mySQL query with just one mySql statement, i have a table like this where the data for each user is spread out over different rows

```<code> ID  USER_ID FIELD_ID  VALUE
 1      1       2        my name is paul smith
 2      1       3        books
 3      1       4        loggedin
 4      1       5        busy
 5      1       6        lat
 6      1       7        lon
 7      2       2        my name is big boy
 8      2       3        pens
 9      2       4        offline
 10     2       5        idle
 11     2       6        lat
 12     2       7        lon
</code>```

each row contains different data for the same user_id

```<code> FIELD_ID=2 contains the user name
 FIELD_ID=3 contains what they bought
 FIELD_ID=4 logged in or offline
 FIELD_ID=5 is busy or idle
 FIELD_ID=6 is their latitude
 FIELD_ID=7 is their longitude
</code>```

I need one MySQL statement that will return all users who are LOGGED IN and STATE is idle AND bought Books AND is closer than 5 miles for example.

So FOUR things have to be TRUE at the same time:

```<code> 1. user has to be LOGGED IN
 2. user has to be idle
 3. user has to have bought books
 4. user has to be within 5 miles of the office (located at lat=12.3, lon=13.3)
</code>```

So i started off with this (does three of the four things above)

```<code> SELECT distinct a.*
  FROM table a
   inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
   inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
   where a.field_id=3 and a.value='BOOK'
</code>```

Im a total mysql novice, seems like the statement above creates three virtual tables and combines them to make the query, so i figure create two more virtual tables (one for lat and other for long), and combine that with my existing mySQL function calcDist(lat1,lon1,lat2,lon2) that calculates the distance between 2 gps points like this:

```<code> SELECT distinct a.*
  FROM table a
   inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
   inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
   inner join table d on a.user_id = d.user_id and d.field_id = 6
   inner join table e on a.user_id = e.user_id and e.field_id = 7
   where a.field_id=3 and a.value='BOOK' and calcDist(12.3,13.3,d.value,e.value)<5.0;
</code>```

I added two lines (d and e) and modified the last line, the rest are the same.

Sorry im a real mysql novice and cant seem to figure out to compare values on different rows at the same time.

Does anybody knows if this is the right way to do it?

Thanks!

答:
I have edited this, as strawberry wrote there needs to be something to aggregate on, which didnt work for your data. this solution below works. its quite similar to what you had previously done except it wrapped in a sub query. I've tested this and works

```<code>SELECT * FROM
(SELECT DISTINCT
x.USER_ID,
n.value as name,
b.VALUE as bought,
l.VALUE as logged,
s.VALUE as `status`,
lt.VALUE as lat,
ln.VALUE as lon

FROM testing x

LEFT JOIN testing n
ON x.USER_ID = n.USER_ID and n.FIELD_ID = 2

LEFT JOIN testing b
ON x.USER_ID = b.USER_ID and b.FIELD_ID = 3

LEFT JOIN testing l
ON x.USER_ID = l.USER_ID and l.FIELD_ID = 4

LEFT JOIN testing s
ON x.USER_ID = s.USER_ID and s.FIELD_ID = 5

LEFT JOIN testing lt
ON x.USER_ID = lt.USER_ID and lt.FIELD_ID = 6

LEFT JOIN testing ln
ON x.USER_ID = ln.USER_ID and ln.FIELD_ID = 7

)tbl

WHERE tbl.logged = 'loggedin'
AND tbl.status IN ('idle', 'busy')
AND tbl.bought = 'books'
AND calcDist(12.3,13.3, tbl.lat, tbl.lon) > 5
</code>```

Your calcDist function should hopefully do something similar to this

```<code>AND (3959 * acos( cos( radians(12.3) )
      * cos( radians(x.LAT) )
      * cos( radians(x.LON) - radians(13.3)) + sin(radians(12.3))
      * sin( radians(x.LAT) ))) >= 5
</code>```

Body:
I need to do a complicated mySQL query with just one mySql statement, i have a table like this where the data for each user is spread out over different rows

 ID  USER_ID FIELD_ID  VALUE
 1      1       2        my name is paul smith
 2      1       3        books
 3      1       4        loggedin
 4      1       5        busy
 5      1       6        lat
 6      1       7        lon
 7      2       2        my name is big boy
 8      2       3        pens
 9      2       4        offline
 10     2       5        idle
 11     2       6        lat
 12     2       7        lon

each row contains different data for the same user_id

 FIELD_ID=2 contains the user name
 FIELD_ID=3 contains what they bought
 FIELD_ID=4 logged in or offline
 FIELD_ID=5 is busy or idle
 FIELD_ID=6 is their latitude
 FIELD_ID=7 is their longitude

I need one MySQL statement that will return all users who are LOGGED IN and STATE is idle AND bought Books AND is closer than 5 miles for example.

So FOUR things have to be TRUE at the same time:

 1. user has to be LOGGED IN
 2. user has to be idle
 3. user has to have bought books
 4. user has to be within 5 miles of the office (located at lat=12.3, lon=13.3)

So i started off with this (does three of the four things above)

 SELECT distinct a.*
  FROM table a
   inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
   inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
   where a.field_id=3 and a.value='BOOK'

Im a total mysql novice, seems like the statement above creates three virtual tables and combines them to make the query, so i figure create two more virtual tables (one for lat and other for long), and combine that with my existing mySQL function calcDist(lat1,lon1,lat2,lon2) that calculates the distance between 2 gps points like this:

 SELECT distinct a.*
  FROM table a
   inner join table b on a.user_id = b.user_id and b.field_id = 5 and b.value='idle'
   inner join table c on a.user_id = c.user_id and c.field_id = 4 and c.value = 'loggedin'
   inner join table d on a.user_id = d.user_id and d.field_id = 6
   inner join table e on a.user_id = e.user_id and e.field_id = 7
   where a.field_id=3 and a.value='BOOK' and calcDist(12.3,13.3,d.value,e.value)<5.0;

I added two lines (d and e) and modified the last line, the rest are the same.

Sorry im a real mysql novice and cant seem to figure out to compare values on different rows at the same time.

Does anybody knows if this is the right way to do it?

Thanks!

Body:
I have edited this, as strawberry wrote there needs to be something to aggregate on, which didnt work for your data. this solution below works. its quite similar to what you had previously done except it wrapped in a sub query. I've tested this and works

SELECT * FROM
(SELECT DISTINCT
x.USER_ID,
n.value as name,
b.VALUE as bought,
l.VALUE as logged,
s.VALUE as `status`,
lt.VALUE as lat,
ln.VALUE as lon

FROM testing x

LEFT JOIN testing n
ON x.USER_ID = n.USER_ID and n.FIELD_ID = 2

LEFT JOIN testing b
ON x.USER_ID = b.USER_ID and b.FIELD_ID = 3

LEFT JOIN testing l
ON x.USER_ID = l.USER_ID and l.FIELD_ID = 4

LEFT JOIN testing s
ON x.USER_ID = s.USER_ID and s.FIELD_ID = 5

LEFT JOIN testing lt
ON x.USER_ID = lt.USER_ID and lt.FIELD_ID = 6

LEFT JOIN testing ln
ON x.USER_ID = ln.USER_ID and ln.FIELD_ID = 7

)tbl

WHERE tbl.logged = 'loggedin'
AND tbl.status IN ('idle', 'busy')
AND tbl.bought = 'books'
AND calcDist(12.3,13.3, tbl.lat, tbl.lon) > 5

Your calcDist function should hopefully do something similar to this

AND (3959 * acos( cos( radians(12.3) )
      * cos( radians(x.LAT) )
      * cos( radians(x.LON) - radians(13.3)) + sin(radians(12.3))
      * sin( radians(x.LAT) ))) >= 5


问:
How to have the data in the CSV file converted to JSON in the request body when using JMETER CSV Date set config
I have a CSV dataset config pointing to a CSV file with the following data:

```<code>Ids
87541
4551
15441
11117
.....
n
</code>```

Instead of looping through the file and do multiple POST requests for each value, I need to have a single POST request and pass ALL the IDs  the request body which should like this in the generated JSON:

```<code>{
  "ids": [
    84280,
    2334,
    235,
    32554,
    3663,
    346,
    344643,
    ....,
    n
  ]
}
</code>```

答:
In CSV Data Set Config define delimiter which not in file as ~

Put in variable name ids for example.

and then use it in request as { "ids": [ ${ids} ] }

Body:
I have a CSV dataset config pointing to a CSV file with the following data:

Ids
87541
4551
15441
11117
.....
n

Instead of looping through the file and do multiple POST requests for each value, I need to have a single POST request and pass ALL the IDs  the request body which should like this in the generated JSON:

{
  "ids": [
    84280,
    2334,
    235,
    32554,
    3663,
    346,
    344643,
    ....,
    n
  ]
}


问:
"and" and "or" on Theano
I run the following code:

```<code>import theano.tensor as T

print(T.eq(2, 1).eval())
print(T.eq(1, 1).eval())
print((T.eq(2, 1) and T.eq(1, 1)).eval())
print((T.eq(2, 1) or T.eq(1, 1)).eval())
</code>```

The outcome is:

```<code>False
True
True
False
</code>```

Why is this not "False, True, False, True"?

答:
Because theano is a symbolic library, thing like T.eq(1,2) does not directly gets evaluated into boolean.

```<code>>>> bool(T.eq(1,2))
True
>>> type(T.eq(1,2))
<class 'theano.tensor.var.TensorVariable'>
</code>```

The weird result in this question is due to logical operator working on non-boolean object.

```<code>>>> '123' and '456'
'456'
>>> '123' or '456'
'123'
</code>```

Quoted from here, section 9.5:

x and y Returns x if x is False, y otherwise

x or y  Returns y if x is False, x otherwise

The correct way is to use bitwise operator:

```<code>>>> (T.eq(1,1) & T.eq(1,2)).eval()
array(False, dtype=bool)
>>> (T.eq(1,1) | T.eq(1,2)).eval()
array(True, dtype=bool)
</code>```

Title: "and" and "or" on Theano

Body:
I run the following code:

import theano.tensor as T

print(T.eq(2, 1).eval())
print(T.eq(1, 1).eval())
print((T.eq(2, 1) and T.eq(1, 1)).eval())
print((T.eq(2, 1) or T.eq(1, 1)).eval())

The outcome is:

False
True
True
False

Why is this not "False, True, False, True"?

Body:
Because theano is a symbolic library, thing like T.eq(1,2) does not directly gets evaluated into boolean.

>>> bool(T.eq(1,2))
True
>>> type(T.eq(1,2))
<class 'theano.tensor.var.TensorVariable'>

The weird result in this question is due to logical operator working on non-boolean object.

>>> '123' and '456'
'456'
>>> '123' or '456'
'123'

Quoted from here, section 9.5:

x and y Returns x if x is False, y otherwise

x or y  Returns y if x is False, x otherwise

The correct way is to use bitwise operator:

>>> (T.eq(1,1) & T.eq(1,2)).eval()
array(False, dtype=bool)
>>> (T.eq(1,1) | T.eq(1,2)).eval()
array(True, dtype=bool)


问:
Solr: processing of query with punctuation mark
I have the following field in schema.xml:

```<code> <field name="content" type="text_snowballstem" indexed="true" stored="true" multiValued="true" omitNorms="false" termVectors="true" />
</code>```

Field type definition:

```<code>  <fieldType name="text_snowballstem" class="solr.TextField" positionIncrementGap="100">
      <analyzer>
          <tokenizer class="solr.WhitespaceTokenizerFactory"/>
          <filter class="solr.ASCIIFoldingFilterFactory"/>
          <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
          <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
          <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" />
          <filter class="solr.LowerCaseFilterFactory"/>
          <filter class="solr.KeywordRepeatFilterFactory"/>
          <filter class="solr.SnowballPorterFilterFactory" protected="no_stemming.txt"/>
          <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
      </analyzer>
  </fieldType>
</code>```

Now, let's say Solr indexed 2 records with contents:

"Select the items that did not match their description:"

"Description"

For this query

```<code>content:"description"
</code>```

solr will return 2 records. Which is what we expect. But for query

```<code>content:"descirption\:"
</code>```

it also returns 2 records. Why colon symbol is ignored here? I expect to receive only 1 record in results.

Appreciate any advice.

UPD

I've implemented suggested changes to WordDelimeterFilterFactory:

```<code> <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" types="nosplit.txt"/>
</code>```

and nosplit.txt file:

```<code># Don't split numbers at '$', '.' or ':'
: => ALPHA
$ => ALPHA
. => ALPHA
- => ALPHA
</code>```

However Solr analyzer still shows 2 tokens for content:description:

Any ideas?

答:
1st Approach

WordDelimiterFilterFactory is producing two token for description:

description:

description

you can check this. Just go to analysis at solr admin screen. Choose your fieldType and paste the data and then you can see the corresponding tokens.

That's why when you searching for description the description: is also coming in results.

We can control this behaviour that WDF won't split on colon.

```<code><filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" types="nosplit.txt"/>
</code>```

[nosplit.txt]

```<code># Don't split numbers at '$', '.' or ':'
: => ALPHA
$ => ALPHA
. => ALPHA
</code>```

I have added one more argument types which will change the splitting behaviour for WDF. After this it will only produce the 1st token not 2nd one.

P.S :- types argument is available from 6.5 onwards. So if you are using older version it will not work.

2nd Approach

You can use the protected argument

protected: (optional) The pathname of a file that contains a list of
  protected words that should be passed through without splitting.

```<code><filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" protected="prot.txt"/>
</code>```

[prot.txt]

```<code>description:
</code>```

This feature is available in both Solr 5 and 6.

3rd Approach

You can use raw query parser. This query parser search for input test without any text analysis or transformation.

```<code>{!raw f=content}description\:
</code>```

Body:
I have the following field in schema.xml:

 <field name="content" type="text_snowballstem" indexed="true" stored="true" multiValued="true" omitNorms="false" termVectors="true" />

Field type definition:

  <fieldType name="text_snowballstem" class="solr.TextField" positionIncrementGap="100">
      <analyzer>
          <tokenizer class="solr.WhitespaceTokenizerFactory"/>
          <filter class="solr.ASCIIFoldingFilterFactory"/>
          <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
          <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt"/>
          <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" />
          <filter class="solr.LowerCaseFilterFactory"/>
          <filter class="solr.KeywordRepeatFilterFactory"/>
          <filter class="solr.SnowballPorterFilterFactory" protected="no_stemming.txt"/>
          <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
      </analyzer>
  </fieldType>

Now, let's say Solr indexed 2 records with contents:

"Select the items that did not match their description:"

"Description"

For this query

content:"description"

solr will return 2 records. Which is what we expect. But for query

content:"descirption\:"

it also returns 2 records. Why colon symbol is ignored here? I expect to receive only 1 record in results.

Appreciate any advice.

UPD

I've implemented suggested changes to WordDelimeterFilterFactory:

 <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" types="nosplit.txt"/>

and nosplit.txt file:

# Don't split numbers at '$', '.' or ':'
: => ALPHA
$ => ALPHA
. => ALPHA
- => ALPHA

However Solr analyzer still shows 2 tokens for content:description:

Any ideas?

Body:
1st Approach

WordDelimiterFilterFactory is producing two token for description:

description:

description

you can check this. Just go to analysis at solr admin screen. Choose your fieldType and paste the data and then you can see the corresponding tokens.

That's why when you searching for description the description: is also coming in results.

We can control this behaviour that WDF won't split on colon.

<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" types="nosplit.txt"/>

[nosplit.txt]

# Don't split numbers at '$', '.' or ':'
: => ALPHA
$ => ALPHA
. => ALPHA

I have added one more argument types which will change the splitting behaviour for WDF. After this it will only produce the 1st token not 2nd one.

P.S :- types argument is available from 6.5 onwards. So if you are using older version it will not work.

2nd Approach

You can use the protected argument

protected: (optional) The pathname of a file that contains a list of
  protected words that should be passed through without splitting.

<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1"
        catenateWords="1" catenateNumbers="1" catenateAll="1"
        splitOnCaseChange="1" splitOnNumerics="1"
        stemEnglishPossessive="1" preserveOriginal="1" protected="prot.txt"/>

[prot.txt]

description:

This feature is available in both Solr 5 and 6.

3rd Approach

You can use raw query parser. This query parser search for input test without any text analysis or transformation.

{!raw f=content}description\:


问:
IONIC: unable to build app after installing `cordova-plugin-fcm`
I am new with ionic framework.Currently i am working on ionicsidemenu android  app.  I want notification in my app for this i have installed cordova-plugin-fcm plugin.    After installing plugin when i run ionic run android it gives build failed message with below  error

I have configured my app in firebase console.   I have plugins in my app :

Please help me.

答:
Step 1 (for FCM Plugin)
Comment out these lines in the FCMPlugin.gradle file.

```<code>classpath 'com.google.gms:google-services:3.0.0'
apply plugin: com.google.gms.googleservices.GoogleServicesPlugin
</code>```

Step 2 (for FCM Plugin)
Change the plugin.xml of the FCM plugin to use a different version, in my situation 9.8.0.

```<code><framework src="com.google.firebase:firebase-core:9.8.0" />
<framework src="com.google.firebase:firebase-messaging:9.8.0" />
</code>```

Step 3 (for Background-Geolocation-Plugin)
Change the plugin.xml of the Geolocation plugin to use a different version, in my situation 9.8.0 instead of "+".

```<code><framework src="com.google.android.gms:play-services-location:9.8.0" />
</code>```

Step 4
Remove and re-add plattform.

Step 5 (build.gradle file of the android platform folder)
Add this line to the classpath section

```<code>classpath 'com.google.gms:google-services:3.1.0'
</code>```

And add this line below the dependencies, nearly at the bottom of the file

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

Body:
Step 1 (for FCM Plugin)
Comment out these lines in the FCMPlugin.gradle file.

classpath 'com.google.gms:google-services:3.0.0'
apply plugin: com.google.gms.googleservices.GoogleServicesPlugin

Step 2 (for FCM Plugin)
Change the plugin.xml of the FCM plugin to use a different version, in my situation 9.8.0.

<framework src="com.google.firebase:firebase-core:9.8.0" />
<framework src="com.google.firebase:firebase-messaging:9.8.0" />

Step 3 (for Background-Geolocation-Plugin)
Change the plugin.xml of the Geolocation plugin to use a different version, in my situation 9.8.0 instead of "+".

<framework src="com.google.android.gms:play-services-location:9.8.0" />

Step 4
Remove and re-add plattform.

Step 5 (build.gradle file of the android platform folder)
Add this line to the classpath section

classpath 'com.google.gms:google-services:3.1.0'

And add this line below the dependencies, nearly at the bottom of the file

apply plugin: 'com.google.gms.google-services'


问:
r - replace a abbreviations with in address
It might be a common use case, I was doing this in python, but in this case, I have to do it in R. How to replace the rd to road, st to street, etc.. in R.

Suppose I have a mapping dictionary like this,

```<code>dict = { st : street, rd : road, Ln : Lane, Pl : Place}
</code>```

In my df,

```<code>Address
2/20,Queen St,London,UK
1,King Ln,Paris,France
5,Stuart Pl,Paris,France
</code>```

How do I get this,

```<code>Address
2/20,Queen Street,London,UK
1,King Lane,Paris,France
5,Stuart Place,Paris,France
</code>```

Thanks.

答:
You can use the function gsub for that. gsub("Ln", "Lane", addresses) where adresses is a vector with your adresses as strings, replaces all occurences of "Ln" with "Lane". You can use Regex with this, but I don't think that really helps you.

So all you have to do is call that function for all substitutions you want to make and you're done. R doesn't have dictionaries (as far as I know), so doing it all in once would require another format to store your mappings.

To answer your question on how to do it for multiple dictionary entries:

Since we don't have dictionaries in R, we take the next best thing: lists. List entries have a name and an object (value, vector, anything really). We can make the name of the entry the dictionary key, and the value its translation:

```<code>dict <- list(St = "Street",
             Rd = "Road",
             Ln = "Lane",
             Pl = "Place")
</code>```

Taking the adresses in your example:

```<code>Adresses <- c("2/20,Queen St,London,UK",
              "1,King Ln,Paris,France",
              "5,Stuart Pl,Paris,France")
</code>```

Now we can loop over the entries of the list, create the expression (using the \b tags as mentioned by @wibeasley), and replace it with the entry in the list. Each time we overwrite the Adresses vector with the results, so we are sequentially applying all filters.

```<code>for(i in 1:length(dict)){
  Adresses <- gsub(paste0("\\b", names(dict)[i], "\\b"), dict[[i]], Adresses)
}
</code>```

Body:
It might be a common use case, I was doing this in python, but in this case, I have to do it in R. How to replace the rd to road, st to street, etc.. in R.

Suppose I have a mapping dictionary like this,

dict = { st : street, rd : road, Ln : Lane, Pl : Place}

In my df,

Address
2/20,Queen St,London,UK
1,King Ln,Paris,France
5,Stuart Pl,Paris,France

How do I get this,

Address
2/20,Queen Street,London,UK
1,King Lane,Paris,France
5,Stuart Place,Paris,France

Thanks.

Body:
You can use the function gsub for that. gsub("Ln", "Lane", addresses) where adresses is a vector with your adresses as strings, replaces all occurences of "Ln" with "Lane". You can use Regex with this, but I don't think that really helps you.

So all you have to do is call that function for all substitutions you want to make and you're done. R doesn't have dictionaries (as far as I know), so doing it all in once would require another format to store your mappings.

To answer your question on how to do it for multiple dictionary entries:

Since we don't have dictionaries in R, we take the next best thing: lists. List entries have a name and an object (value, vector, anything really). We can make the name of the entry the dictionary key, and the value its translation:

dict <- list(St = "Street",
             Rd = "Road",
             Ln = "Lane",
             Pl = "Place")

Taking the adresses in your example:

Adresses <- c("2/20,Queen St,London,UK",
              "1,King Ln,Paris,France",
              "5,Stuart Pl,Paris,France")

Now we can loop over the entries of the list, create the expression (using the \b tags as mentioned by @wibeasley), and replace it with the entry in the list. Each time we overwrite the Adresses vector with the results, so we are sequentially applying all filters.

for(i in 1:length(dict)){
  Adresses <- gsub(paste0("\\b", names(dict)[i], "\\b"), dict[[i]], Adresses)
}


问:
How can I access the 'select' method from NgbTabSet in the component in Angular2 and ng-bootstrap?
Using Angular 2.3.1 and ng-bootstrap 1.0.0-alpha.18. I am trying to programmatically select a tab based on ID from the component rather than from within the template. The goal is to pull the param from the url and to use that to select the tab in ngOnInit

the template

```<code><section id="policy-terms">
<ngb-tabset>
  <ngb-tab title="Terms and Privacy" id="terms">
    <template ngbTabContent>
      <div class="container page-content">

      </div>
    </template>
  </ngb-tab>
  <ngb-tab title="Company Policy" id="policy">
    <template ngbTabContent>
      <div class="container page-content">

      </div>
    </template>
  </ngb-tab>

</ngb-tabset>
</section>
</code>```

And the component code:

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

@Component({
  selector: 'app-policy-terms',
  templateUrl: './policy-terms.component.html',
  styleUrls: ['./policy-terms.component.scss'],
  providers: [
       NgbTabset
   ]
 })
 export class PolicyTermsComponent implements OnInit {

 constructor(
    public tabset: NgbTabset
  ) { }

  ngOnInit() {
    this.tabset.select('policy');
   }
}
</code>```

This just produces an error:

Console log errors

How can I access this method?

答:
Routing with Ngb-TabSet

In AngularJs 1.x using ui-router setting up names routes was straight forward. In Angular 2 with Ng-Bootstrap it’s not as obvious. On the upside, what you need is available in native Angular 2 libraries.

Setting up the Route Configuration

```<code>export const appRoutes: Routes =
    [
        { path: 'prospect/:prospectid/details', component: ProspectTabsView, data:{name:'details'} },
        { path: 'prospect/:prospectid/appointments', component: ProspectTabsView, data:{name:'appointments'} },
        { path: 'prospect/:prospectid/followups', component: ProspectTabsView, data:{name:'followups'} },
        { path: 'prospect/:prospectid/contacts', component: ProspectTabsView, data:{name:'contacts'} },
        { path: '', component: DashboardView },
        { path: '**', redirectTo: '', pathMatch: 'full'}
    ];
</code>```

The configuration is straightforward with one exception: the [data] attribute. You’ll notice it has a key called name. This is the name of the route. Think of it as a data attribute as a data-bag. You can add more than just the route name.

Setting up the TabSet Markup

```<code><ngb-tabset #tabs>
    <ngb-tab id="details">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'details']">Details</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="contacts">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect',prospectId,'contacts']">Contacts</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="appointments">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'appointments']">Appointments</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="followups">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'followups']">Follow Ups</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
</ngb-tabset>
</code>```

There is nothing magical about the above tab markup, there are couple things you want to take note of: first is in the ngb-tabset element, we’ve declared the variable #tab. We’ll use #tab later in the component. Second, each nbg-tab has an id set that matches name we defined in the route configuration (i.e. data:{name:'followups'}).

Setting up the Component

```<code>import {
     AfterViewChecked, Component, OnInit,
    ViewChild
} from '@angular/core';
import '../../assets/css/styles.css';
import {ActivatedRoute} from "@angular/router";
import {NgbTabset} from "@ng-bootstrap/ng-bootstrap";

@Component({
    templateUrl: './tabs.view.html'
})
export class ProspectTabsView implements OnInit, AfterViewChecked{
    prospectId: number;
    selectedTab:string;

    @ViewChild('tabs')
    private tabs:NgbTabset;

    constructor(private route: ActivatedRoute) {
        this.route.data.subscribe(d=>{
            this.selectedTab = d.name;
        });
    }

    ngOnInit(): void {
        this.route.params.subscribe(
            params => {
                this.prospectId = +params['prospectid'];
            }
        );
    }

    ngAfterViewChecked(): void {
        if(this.tabs) {
            this.tabs.select(this.selectedTab);
        }
    }
 }
</code>```

The hardest part in this exercise was getting the order of execution correct. If it’s not correct, a collection or a property won’t be initialized before you operate on it. We’ll start at the top of the class and work our way down.

First, we have the variables. prospectId is the primary key of the data, selectedTab is the name of the currently selected tab, and lastly, we have the tabs variable. tabs is a reference to the attribute (#tab) we added to the ngb-tabset element.

Next is the constructor. It’s not obvious in the documentation, but data is an Observable<data>. To capture the value, we are subscribing to the data property from the route.

Following the constuctor is the ngOnInit. This isn’t important to the tabs, but it does capture the prospectId which we use in the tab’s routing. If you don’t have any dynamic data in your routes, then you don’t need this.

Lastly, we have ngAfterViewChecked. For routing the tabs, this is the most important. Here we use the tabs variable we captured from the markup and it’s where we pass the selected tab name to the tabs to change the selected tab.

Update

To get this working properly, I had to add to hook into the tabChange event on the ngb-tabset.

HTML:

```<code><ngb-tabset [activeId]="selectedTab" #tabs (tabChange)="onTabChange($event)">
</code>```

TypeScript:

Also, I had to hardcode the routes in the onTabChange function.

```<code>onTabChange($event: NgbTabChangeEvent) {
    let routes = {
        details: `/prospect/${this.prospectId}/details`,
        appointments: `/prospect/${this.prospectId}/appointments`,
        followups: `/prospect/${this.prospectId}/followups`,
        notes: `/prospect/${this.prospectId}/notes`,
        dials: `/prospect/${this.prospectId}/dials`,
    };

    this.router.navigateByUrl(routes[$event.nextId]);
}
</code>```

Body:
Using Angular 2.3.1 and ng-bootstrap 1.0.0-alpha.18. I am trying to programmatically select a tab based on ID from the component rather than from within the template. The goal is to pull the param from the url and to use that to select the tab in ngOnInit

the template

<ngb-tabset>
  <ngb-tab title="Terms and Privacy" id="terms">
    <template ngbTabContent>

    </template>
  </ngb-tab>
  <ngb-tab title="Company Policy" id="policy">
    <template ngbTabContent>

    </template>
  </ngb-tab>

</ngb-tabset>

And the component code:

import { Component, OnInit } from '@angular/core';
import { NgbTabset } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-policy-terms',
  templateUrl: './policy-terms.component.html',
  styleUrls: ['./policy-terms.component.scss'],
  providers: [
       NgbTabset
   ]
 })
 export class PolicyTermsComponent implements OnInit {

 constructor(
    public tabset: NgbTabset
  ) { }

  ngOnInit() {
    this.tabset.select('policy');
   }
}

This just produces an error:

Console log errors

How can I access this method?

Body:
Routing with Ngb-TabSet

In AngularJs 1.x using ui-router setting up names routes was straight forward. In Angular 2 with Ng-Bootstrap it’s not as obvious. On the upside, what you need is available in native Angular 2 libraries.

Setting up the Route Configuration

export const appRoutes: Routes =
    [
        { path: 'prospect/:prospectid/details', component: ProspectTabsView, data:{name:'details'} },
        { path: 'prospect/:prospectid/appointments', component: ProspectTabsView, data:{name:'appointments'} },
        { path: 'prospect/:prospectid/followups', component: ProspectTabsView, data:{name:'followups'} },
        { path: 'prospect/:prospectid/contacts', component: ProspectTabsView, data:{name:'contacts'} },
        { path: '', component: DashboardView },
        { path: '**', redirectTo: '', pathMatch: 'full'}
    ];

The configuration is straightforward with one exception: the [data] attribute. You’ll notice it has a key called name. This is the name of the route. Think of it as a data attribute as a data-bag. You can add more than just the route name.

Setting up the TabSet Markup

<ngb-tabset #tabs>
    <ngb-tab id="details">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'details']">Details</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="contacts">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect',prospectId,'contacts']">Contacts</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="appointments">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'appointments']">Appointments</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
    <ngb-tab id="followups">
        <ng-template ngbTabTitle>
            <a [routerLink]="['/prospect', prospectId, 'followups']">Follow Ups</a>
        </ng-template>
        <ng-template ngbTabContent>
        </ng-template>
    </ngb-tab>
</ngb-tabset>

There is nothing magical about the above tab markup, there are couple things you want to take note of: first is in the ngb-tabset element, we’ve declared the variable #tab. We’ll use #tab later in the component. Second, each nbg-tab has an id set that matches name we defined in the route configuration (i.e. data:{name:'followups'}).

Setting up the Component

import {
     AfterViewChecked, Component, OnInit,
    ViewChild
} from '@angular/core';
import '../../assets/css/styles.css';
import {ActivatedRoute} from "@angular/router";
import {NgbTabset} from "@ng-bootstrap/ng-bootstrap";

@Component({
    templateUrl: './tabs.view.html'
})
export class ProspectTabsView implements OnInit, AfterViewChecked{
    prospectId: number;
    selectedTab:string;

    @ViewChild('tabs')
    private tabs:NgbTabset;

    constructor(private route: ActivatedRoute) {
        this.route.data.subscribe(d=>{
            this.selectedTab = d.name;
        });
    }

    ngOnInit(): void {
        this.route.params.subscribe(
            params => {
                this.prospectId = +params['prospectid'];
            }
        );
    }

    ngAfterViewChecked(): void {
        if(this.tabs) {
            this.tabs.select(this.selectedTab);
        }
    }
 }

The hardest part in this exercise was getting the order of execution correct. If it’s not correct, a collection or a property won’t be initialized before you operate on it. We’ll start at the top of the class and work our way down.

First, we have the variables. prospectId is the primary key of the data, selectedTab is the name of the currently selected tab, and lastly, we have the tabs variable. tabs is a reference to the attribute (#tab) we added to the ngb-tabset element.

Next is the constructor. It’s not obvious in the documentation, but data is an Observable<data>. To capture the value, we are subscribing to the data property from the route.

Following the constuctor is the ngOnInit. This isn’t important to the tabs, but it does capture the prospectId which we use in the tab’s routing. If you don’t have any dynamic data in your routes, then you don’t need this.

Lastly, we have ngAfterViewChecked. For routing the tabs, this is the most important. Here we use the tabs variable we captured from the markup and it’s where we pass the selected tab name to the tabs to change the selected tab.

Update

To get this working properly, I had to add to hook into the tabChange event on the ngb-tabset.

HTML:

<ngb-tabset [activeId]="selectedTab" #tabs (tabChange)="onTabChange($event)">

TypeScript:

Also, I had to hardcode the routes in the onTabChange function.

onTabChange($event: NgbTabChangeEvent) {
    let routes = {
        details: `/prospect/${this.prospectId}/details`,
        appointments: `/prospect/${this.prospectId}/appointments`,
        followups: `/prospect/${this.prospectId}/followups`,
        notes: `/prospect/${this.prospectId}/notes`,
        dials: `/prospect/${this.prospectId}/dials`,
    };

    this.router.navigateByUrl(routes[$event.nextId]);
}


问:
how to use multiple <http> configurations
I have two file with <http> element. Those two have different configurations.

```<code><http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
</code>```

and

```<code><http path-type="regex" auto-config="false" realm="Protected API" use-expressions="true" create-session="never" entry-point-ref="CustomAPIAuthenticationEntryPoint">
</code>```

but in deployment I get error

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate  element detected
  Offending resource: class path resource [websecurity-http.xml]
      at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
      at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
      at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72)

I'm using spring-3.0.7. Is there a way I can use two different <http> configurations. I have two websecurity.xml files here

答:
As @M. Deinum and @xerx593 suggested we can use <http pattern=""/> for this.

I was using spring-3.0.7. But spring introduce multiple <http> element feature in spring-3.1.0. So I had to upgrade spring.

Body:
I have two file with <http> element. Those two have different configurations.

<http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">

and

<http path-type="regex" auto-config="false" realm="Protected API" use-expressions="true" create-session="never" entry-point-ref="CustomAPIAuthenticationEntryPoint">

but in deployment I get error

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate  element detected
  Offending resource: class path resource [websecurity-http.xml]
      at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
      at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
      at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72)

I'm using spring-3.0.7. Is there a way I can use two different <http> configurations. I have two websecurity.xml files here


问:
Using default application timezone with DateTime.strptime in Rails 5
I read similar questions but did not find a solution.

My Rails 5 App is in

'America/Sao_Paulo'

time zone but saves all times in UTC to the database.

When saving a datetime

'2017-01-01 19:00:00'

to my database it will convert it to UTC and save the UTS time to the database.

Now I need to convert a string to datetime using:

```<code>DateTime.strptime(date + ' ' + time, '%d/%m/%Y %H:%M:%S')
</code>```

And this will take the date and time values as they are and save them to the database without converting to UTC. How can I let my app know that my the datetime is not in UTC yet?

答:
ActiveRecord (by default) will save any datetime to UTC. So, in my opinion you don't need to worry if the time in the database isn't yet in UTC, because ActiveRecord will convert it to UTC.

So, when saving to database, ActiveRecord will always convert it to UTC (whether it is in UTC or not).

And when fetching from database, it follows your configuration in config/application.rb

You can find in the file config.time_zone = 'YOUR_TIMEZONE'.

Reference:
http://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html

Hope it helps, cheers!

Body:
I read similar questions but did not find a solution.

My Rails 5 App is in

'America/Sao_Paulo'

time zone but saves all times in UTC to the database.

When saving a datetime

'2017-01-01 19:00:00'

to my database it will convert it to UTC and save the UTS time to the database.

Now I need to convert a string to datetime using:

DateTime.strptime(date + ' ' + time, '%d/%m/%Y %H:%M:%S')

And this will take the date and time values as they are and save them to the database without converting to UTC. How can I let my app know that my the datetime is not in UTC yet?


问:
How to return an array in c using pthreads?
I tried to write a program that a thread returns an array of numbers by passing a random vector to the thread and thread returns 2 times of the vector.
The program is running fine put I'm not getting the expected output.
The code is as follows:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}

   pthread_exit(sum[i]);
}

int main()
{

 double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");
  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
  pthread_join(tid1, sum[i]);

  total = omp_get_wtime() - total;
  printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}
</code>```

and the output is as follows:

```<code>This is using PThread
Double of the vector:-
 0
 0
 0
 0
 0
0.000188 is time to add
</code>```

Which is not the expected output, so can someone tell me what is the mistake in this code and how to return an array using pthread. In the i should be able to sum all the return values.

I used gcc q.c -lpthread -lrt -fopenmp command to compile this program.

Thank you in advance!

答:
Probably the problem is being caused because of the line int *sum[10]; in this function:

```<code>void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}
</code>```

You are creating a local variable sum, which will have preference over the global variable sum, since it is in a inner scope. Try removing it.

Body:
I tried to write a program that a thread returns an array of numbers by passing a random vector to the thread and thread returns 2 times of the vector.
The program is running fine put I'm not getting the expected output.
The code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}

   pthread_exit(sum[i]);
}

int main()
{

 double total = omp_get_wtime();

 printf("This is using PThread\n");

  pthread_t tid1;
  pthread_create(&tid1, NULL, myThreaddouble, NULL);
  printf("Double of the vector:-   \n");
  for ( i = 0 ; i < 5 ; i++ )
  {
    printf(" %d\n",(int) sum[i]);
  }
  pthread_join(tid1, sum[i]);

  total = omp_get_wtime() - total;
  printf("%lf is time to add\n",total);
  printf("\n");

  return 0;

}

and the output is as follows:

This is using PThread
Double of the vector:-
 0
 0
 0
 0
 0
0.000188 is time to add

Which is not the expected output, so can someone tell me what is the mistake in this code and how to return an array using pthread. In the i should be able to sum all the return values.

I used gcc q.c -lpthread -lrt -fopenmp command to compile this program.

Thank you in advance!

Body:
Probably the problem is being caused because of the line int *sum[10]; in this function:

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
  sum[i]= first[i] + first[i];
}

You are creating a local variable sum, which will have preference over the global variable sum, since it is in a inner scope. Try removing it.


问:
Most Efficient way to access schema with ODBC and OleDB
I am making a DAL template with C# and I am wondering what is the most efficient way to access schema information with ODBC and OleDB. I need the columns, column types, and primary key information.

thanks

答:
For OleDb, there is an OleDbConnection.GetoleDbSchemaTable() method. I've used it with Access.

I have an example in this code on GitHub:
SchemaValidator.cs

There should be a .Schema() method on OdbcConnection too IIRC.

I have noticed that the actual returned values may vary by database, so you'll want to do a fair amount of checking and debugging to see what he returned values may be.

ContentLicense: CC BY-SA 2.5


问:
Why matplotlib is also printing data while doing a subplot?
Hi I can t figure out how to properly use pyplot for multiple plots, in addition to the plot it also print me the full array of data </p>

```<code># import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50) # kinda work, the problem is it print the array and then do the plot

plt.hist(x, 50, ax=axes[0,0]) # not wokring inner() got multiple values for keyword argument 'ax'
</code>```

答:
I cannot reproduce the described behaviour in

```<code>axes[1,0].hist(x, 50)
</code>```

i.e. the histogram is plotted as expected and the array is not printed. In the second statement, ax is not a valid keyword. Instead you can set the current axes instance with plt.sca():

```<code>plt.sca(axes[0,0])
plt.hist(x, 50)
</code>```

Hope this helps.

Body:
Hi I can t figure out how to properly use pyplot for multiple plots, in addition to the plot it also print me the full array of data

# import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

fig, axes=plt.subplots(nrows=4, ncols=2)

# the histogram of the data
axes[1,0].hist(x, 50) # kinda work, the problem is it print the array and then do the plot

plt.hist(x, 50, ax=axes[0,0]) # not wokring inner() got multiple values for keyword argument 'ax'

Body:
I cannot reproduce the described behaviour in

axes[1,0].hist(x, 50)

i.e. the histogram is plotted as expected and the array is not printed. In the second statement, ax is not a valid keyword. Instead you can set the current axes instance with plt.sca():

plt.sca(axes[0,0])
plt.hist(x, 50)

Hope this helps.


问:
how to show a spinner till the time data recieved from the server in angular2
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

```<code> getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }
</code>```

abc.component.ts

```<code>let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}
</code>```

bcd-chart.component.ts

```<code> initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }
</code>```

styles.css

```<code>.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}
</code>```

答:
Just have a boolean to track if the call is in progress or not

```<code>public inprogress = false;
</code>```

set it to true before the http call and set it to false after the response is received

```<code>initData() {
    this.inprogress = true;
    this.DataService.getdata(clientJson).subscribe(
        success => this.bcdChart(success),
        error => this.errorMessage = error
    );
}
bcdChart(jsonData) {
    this.inprogress= false;
    /* ... */
}
</code>```

If you like it keep it simple and handle in both error and success and not pollute bcdChart method you can do this way.

```<code>this.DataService.getdata(clientJson)
    .do(res => this.inprogress=false)
    .subscribe(
        success => this.bcdChart(success),
        error => this.errorMessage = error
    );
</code>```

Body:
The project have a service.ts to make ajax call(http.post) and several components(abc.component.ts, bcd.component.ts etc) gets the data from the server through service.ts

I am using

  for the spinner view. But, need a better approach to show loader either gif etc.

I want to show a spinner till the time each component fetch data from the server. How to do that?

service.ts

 getdata(){
      let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        let url = "http://883.82./Ser/soSe";
        return this.http.post(url, clientJson).map((res: Response) => res.json());
    }

abc.component.ts

let clientJson = {
        "aoId": "M_AO_918",
        "viewBys": ["usstate"],
        /* ... */
    };
  this.DataService.getdata(clientJson).subscribe(
        success => this.abcChart(success),
        error => this.errorMessage = error
    );
abcChart(jsonData) {
    /* ... */
}

bcd-chart.component.ts

 initData() {
        let clientJson = {
            "aoId": "M_AO_918",
            "viewBys": ["brands"],
            /* ... */
        };
        this.DataService.getdata(clientJson).subscribe(
            success => this.bcdChart(success),
            error => this.errorMessage = error
        );
    }
    bcdChart(jsonData) {
        /* ... */
    }

styles.css

.spinner {
  width: 40px;
  height: 40px;
  background-color: #333;

  margin: 100px auto;
  -webkit-animation: sk-rotateplane 1.2s infinite ease-in-out;
  animation: sk-rotateplane 1.2s infinite ease-in-out;
}

@-webkit-keyframes sk-rotateplane {
  0% { -webkit-transform: perspective(120px) }
  50% { -webkit-transform: perspective(120px) rotateY(180deg) }
  100% { -webkit-transform: perspective(120px) rotateY(180deg)  rotateX(180deg) }
}

@keyframes sk-rotateplane {
  0% {
    transform: perspective(120px) rotateX(0deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(0deg) rotateY(0deg)
  } 50% {
    transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
    -webkit-transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg)
  } 100% {
    transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
    -webkit-transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
  }
}
.loading{
  background-color: #d35400;
}

Body:
Just have a boolean to track if the call is in progress or not

public inprogress = false;

set it to true before the http call and set it to false after the response is received

initData() {
    this.inprogress = true;
    this.DataService.getdata(clientJson).subscribe(
        success => this.bcdChart(success),
        error => this.errorMessage = error
    );
}
bcdChart(jsonData) {
    this.inprogress= false;
    /* ... */
}

If you like it keep it simple and handle in both error and success and not pollute bcdChart method you can do this way.

this.DataService.getdata(clientJson)
    .do(res => this.inprogress=false)
    .subscribe(
        success => this.bcdChart(success),
        error => this.errorMessage = error
    );


问:
Showing public fields of a UserControl in designer
I am trying to add some fields to a custom UserControl that I am making. I have some fields that I like them to be visible in the Properties window of Visual Studio. I tried to use the flags below but I dont see the field in the designer, even after a compile.

How should I do this correctly?

```<code>public partial class TosChartControl: UserControl
{

    #region PUBLIC FIELDS

    [Browsable(true)] //Added this but still does not show up
    [Category("Data")]
    [DefaultValue(0)]
    [Description("ID of the Sensor Node")]
    public int NodeId { get; set; }

    #endregion

    public TosChartControl()
    {
        InitializeComponent();
    }
}
</code>```

I did clean and rebuild the soloution and projects but I cant still see this field in Properties window. Even restarting the Visualstudio didnt help.

答:
To elaborate on henginy's updated answer:

Be sure that you are looking at an instance of the control you want to modify properties for, and not the definition of the control itself.

To clarify, when you add a property to your TosChartControl class, you won't see the property in the TosChartControl.cs [Design] tab, you will see it where you implement a TosChartControl, such as your Form1.cs [Design] tab, e.g. the containing control to which you have added your custom control.

...Assuming that your Properties window is visible, and that you have the control selected.

What to take away from this lesson:

Understanding what the properties window is actually showing you — It's contextual.

The difference between the model and the implementation of the model — e.g. Designing the custom control and designing the form that uses the custom control.

Body:
I am trying to add some fields to a custom UserControl that I am making. I have some fields that I like them to be visible in the Properties window of Visual Studio. I tried to use the flags below but I dont see the field in the designer, even after a compile.

How should I do this correctly?

public partial class TosChartControl: UserControl
{

    #region PUBLIC FIELDS

    [Browsable(true)] //Added this but still does not show up
    [Category("Data")]
    [DefaultValue(0)]
    [Description("ID of the Sensor Node")]
    public int NodeId { get; set; }

    #endregion

    public TosChartControl()
    {
        InitializeComponent();
    }
}

I did clean and rebuild the soloution and projects but I cant still see this field in Properties window. Even restarting the Visualstudio didnt help.


问:
code is returning data of one date only whereas i want data of every date
```<code>function practise()
{
    $this->load->database();
     $qry = mysql_query("select * from demmo");
  if (mysql_num_rows($qry) > 0)
{
     while ($row = mysql_fetch_array($qry))
  {
      $created = $row['created'];
//from here
      $qry = mysql_query("select * from demmo where created = '$created'");

            while ($res = mysql_fetch_array($qry))
            {
                $user_id = $res['id'];
                $name = $res['name'];
                $created2 = $res['created'];
            $users[] = array('user_id' => $user_id, 'name' => $name);
            }
                $dotts[] = array('created' => $created2);
//till here
}
    return array ($dotts,$users);
}
}
</code>```

in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.

答:
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:

For example, to get all of the dates:

```<code>$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
    {
        $user_id = $res['id'];
        $name = $res['name'];
        $created2 = $res['created'];
        array_push($dotts, $created2);
        $users[] = array('user_id' => $user_id, 'name' => $name);
        array_push($allusers, $users);
    }
//
return array ($dotts,$allusers);
</code>```

Body:
function practise()
{
    $this->load->database();
     $qry = mysql_query("select * from demmo");
  if (mysql_num_rows($qry) > 0)
{
     while ($row = mysql_fetch_array($qry))
  {
      $created = $row['created'];
//from here
      $qry = mysql_query("select * from demmo where created = '$created'");

            while ($res = mysql_fetch_array($qry))
            {
                $user_id = $res['id'];
                $name = $res['name'];
                $created2 = $res['created'];
            $users[] = array('user_id' => $user_id, 'name' => $name);
            }
                $dotts[] = array('created' => $created2);
//till here
}
    return array ($dotts,$users);
}
}

in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.

Body:
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:

For example, to get all of the dates:

$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
    {
        $user_id = $res['id'];
        $name = $res['name'];
        $created2 = $res['created'];
        array_push($dotts, $created2);
        $users[] = array('user_id' => $user_id, 'name' => $name);
        array_push($allusers, $users);
    }
//
return array ($dotts,$allusers);


问:
Integers with NA in pandas from json_normalize
I do df = pandas.io.json.json_normalize(data) and I want to specify datatype of an integer column that has missing data. Since pandas doesn't have an integer NaN, I want to use dtype object, i.e. string. As far as I can tell, json_normalize doesn't have any dtype parameter. If I try to .astype(object) the columns afterwards, I'll end up with decimal points in the column.

How can I get the string format with no decimal point into this column?

答:
There should be a more elegant solution, but this one should work for your specific task:

```<code>df['col'] = df['col'].astype(object).apply(lambda x: '%.f' % x)
</code>```

hope it helps.

Body:
There should be a more elegant solution, but this one should work for your specific task:

df['col'] = df['col'].astype(object).apply(lambda x: '%.f' % x)

hope it helps.