问:
Running multiple instances of the same android service
If I create an android service using startService() followed by bindService(), and I never call stopService().
Now, every time my app calls startService() and bindService(), will it create a new instance of the service or reuse the existing one?

If a new instance is created...is the old instance still running or is it terminated?

答:
will it create a new instance

No. If you're calling startService() even if service already running, it will call onStartCommand() with updated Intent

Ps,
Service will run in only one process. So there is no such doubt to create another instance


来源: stackexchange

问:
passing loop of components to html in react
```<code>formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}
</code>```

This is my loop for multiple tr components which I am trying to display on the page as follows

```<code><TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />
</code>```

My transaction Row component:

```<code>import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (
      <tr key={key}>
            <td height="70"><span className="txt-spcng">19 Jan 17<br /><small className="grey-txt">19 Jan 17</small></span></td>
            <td>{transactionRowData.paymentId}</td>
            <td>KTU7-ZAUOSPZ</td>
            <td><span className="txt-limit">firstname.lastnasdsd</span></td>
            <td className="amnt-dbt">₹ {transactionRowData.amount}</td>
            <td><span className="txt-limit">Payment Successdd sdsd d</span></td>
            <td align="center"><div className="tl-tip"><a href="javscript:void(0)" className="icon-dotted"></a></div></td>
        </tr>
    )
}

export default TransactionTableRow
</code>```

But i get an error Each child in an array or iterator should have a unique "key" prop.

答: It is considered duplicate because you assign the same key to TransactionTableRow and then the tr element within it. You can remove the key in tr element. Please refer to https://facebook.github.io/react/docs/lists-and-keys.html#extracting-components-with-keys </p>

ContentLicense: CC BY-SA 3.0

Body:
formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}

This is my loop for multiple tr components which I am trying to display on the page as follows

<TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />

My transaction Row component:

import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (

            19 Jan 17
19 Jan 17
            {transactionRowData.paymentId}
            KTU7-ZAUOSPZ
            firstname.lastnasdsd
            ₹ {transactionRowData.amount}
            Payment Successdd sdsd d

    )
}

export default TransactionTableRow

But i get an error Each child in an array or iterator should have a unique "key" prop.


问:
WPF Toolkit PropertyGrid ExpandableObject attribute doesn't show nested class correctly
I'm using Extended WPF toolkit PropertyGrid to let users fill configurations in my application.

Everything works fine except when I try to include an ExpandableObject attribute to add a nested class.

Here is an example:

```<code>public class TestClassConfig
{
   public string ExcelName { get; set; }

   public string ResultFolder { get; set; }

   [ExpandableObject]
   public ExpandableTest OtherClass { get; set; }
}

public class ExpandableTest
{
   public string Test1 { get; set; }
   public string Test2 { get; set; }
}
</code>```

I can't post an image of the result (first post), so i'll describe it: the "OtherClass" property appears but I can't see the nested class properties (Test1 and Test2) so cannot edit it.

In the PropertyGrid Documentation, it says for the property with ExpandableObject attribute that "This property is a complex property and has no default editor."

Does it means I have to create a custom Editor everytime I want to add a nested class to my property grid ?

Thanks for your answers!

答:
I know it is a late answer, however, make sure the value of the property is not null. In other words, write something like this:</p>

```<code>public class TestClassConfig
{
  [Category("CatWithExpandObj")]
  [ExpandableObject]
   public ExpandableTest OtherClass { get; set; } = new ExpandableTest();
}
</code>```

Body:
I'm using Extended WPF toolkit PropertyGrid to let users fill configurations in my application.

Everything works fine except when I try to include an ExpandableObject attribute to add a nested class.

Here is an example:

public class TestClassConfig
{
   public string ExcelName { get; set; }

   public string ResultFolder { get; set; }

   [ExpandableObject]
   public ExpandableTest OtherClass { get; set; }
}

public class ExpandableTest
{
   public string Test1 { get; set; }
   public string Test2 { get; set; }
}

I can't post an image of the result (first post), so i'll describe it: the "OtherClass" property appears but I can't see the nested class properties (Test1 and Test2) so cannot edit it.

In the PropertyGrid Documentation, it says for the property with ExpandableObject attribute that "This property is a complex property and has no default editor."

Does it means I have to create a custom Editor everytime I want to add a nested class to my property grid ?

Thanks for your answers!

Body:
I know it is a late answer, however, make sure the value of the property is not null. In other words, write something like this:

public class TestClassConfig
{
  [Category("CatWithExpandObj")]
  [ExpandableObject]
   public ExpandableTest OtherClass { get; set; } = new ExpandableTest();
}


问:
Error when attempting to use header(location) code

When I try to use the code below:

```<code><?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ( $result->num_rows == 0 ){ // User doesn't exist
    header("location: error.php");
    $_SESSION['message'] = "User with that email doesn't exist!";
}
</code>```

I get the following error:

```<code>Warning: Cannot modify header information
- headers already sent by
(output started at /some-server/Pages/index.php:10)
in /some-server/Pages/login.php on line 9
</code>```

Can someone please help me solve this issue?
Thank You

//Update//

This is the rrest of the code, sorry for not adding this earlier:

```<code><?php
/* Main page with two forms: sign up and log in */
require 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
   <title>Sign-Up/Login Form</title>
   <?php include 'css/css.html'; ?>
</head>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (isset($_POST['login'])) { //user logging in

        require 'login.php';

    }

    elseif (isset($_POST['register'])) { //user registering

        require 'register.php';

    }
}
?>
</code>```

答:
When you get this error it means that you have echoed/printed something already and so the header cannot be sent.

PHP helpfully tells you that headers already sent by…. If you check the code this is referring to you should be able to easily locate the point where you're echoing something.

It's usually:

An error/warnings outputted by PHP

Debug code left in (print_r, var_dump, etc)

An accidental space before <?php

The first two are usually pretty obviously; the third one can be a bit trickier to spot!

I will happily add specifics to this answer if you post some more code.

Body:
When I try to use the code below:

<?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ( $result->num_rows == 0 ){ // User doesn't exist
    header("location: error.php");
    $_SESSION['message'] = "User with that email doesn't exist!";
}

I get the following error:

Warning: Cannot modify header information
- headers already sent by
(output started at /some-server/Pages/index.php:10)
in /some-server/Pages/login.php on line 9

Can someone please help me solve this issue?
Thank You

//Update//

This is the rrest of the code, sorry for not adding this earlier:

<?php
/* Main page with two forms: sign up and log in */
require 'db.php';
session_start();
?>
<!DOCTYPE html>

   <title>Sign-Up/Login Form</title>
   <?php include 'css/css.html'; ?>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (isset($_POST['login'])) { //user logging in

        require 'login.php';

    }

    elseif (isset($_POST['register'])) { //user registering

        require 'register.php';

    }
}
?>


问:
Its possible to use a microsoft.web.services3 in visual studio database project?
I have done a windows service that gets information from an wsdl class method. A co-worker has suggested me to use an assembly to run a job in sqlserver database. I supossed it wasn't possible but i dont know if it could be done.

The wsdl that i'm using was done with Microsoft.web.services3. The windows service project has a config file which has a necessary section:

```<code><configSections>
     <section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
</code>```

And i also have this reference.

```<code><microsoft.web.services3>
    <tokenIssuer>
       <ttlInSeconds value="900000" />
    </tokenIssuer>
    <security>
       <defaultTtlInSeconds value="9000000" />
      <timeToleranceInSeconds value="9000000" />
    </security>
<web.services3>
</code>```

I think it won't work but if it could be possible, how can i do this in a Database Project to build in one assembly?

答:
Yes it is possible, but it is not really "nice" to do.
What you need to do is to create a SQL Server CLR Assembly where you use the Webservice logic (calling, handling, etc).

Look at [https://msdn.microsoft.com/en-us/library/w2kae45k(v=vs.100).aspx] on how to do that

Downside to this, you are running this CLR in the SQL Server memory. If you don't dispose your objects in the proper way you might fill up your SQL Server memory with objects that are not meant to be there.

Other solution?
If you need this data in a database, you might want to create a process that calls the webservice and stores the data in a database...

Body:
I have done a windows service that gets information from an wsdl class method. A co-worker has suggested me to use an assembly to run a job in sqlserver database. I supossed it wasn't possible but i dont know if it could be done.

The wsdl that i'm using was done with Microsoft.web.services3. The windows service project has a config file which has a necessary section:

<configSections>

</configSections>

And i also have this reference.

<microsoft.web.services3>
    <tokenIssuer>
       <ttlInSeconds value="900000" />
    </tokenIssuer>
    <security>
       <defaultTtlInSeconds value="9000000" />
      <timeToleranceInSeconds value="9000000" />
    </security>
<web.services3>

I think it won't work but if it could be possible, how can i do this in a Database Project to build in one assembly?


问:
Tell `string::operator==` to start comparing at the back of the string
Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!

答:
I see two options:

Write your own comparison function and call that.

Write a wrapper class around
std::string, and implement operator== for that class to have the behavior you want.

The second is probably overkill.

ContentLicense: CC BY-SA 2.5


问:
Assigning multiple values to dictionary keys from a file in Python 3
I'm fairly new to Python but I haven't found the answer to this particular problem.
I am writing a simple recommendation program and I need to have a dictionary where cuisine is a key and name of a restaurant is a value. There are a few instances where I have to split a string of a few cuisine names and make sure all other restaurants (values) which have the same cuisine get assigned to the same cuisine (key). Here's a part of a file:

```<code>Georgie Porgie
87%
$$$
Canadian, Pub Food

Queen St. Cafe
82%
$
Malaysian, Thai

Mexican Grill
85%
$$
Mexican

Deep Fried Everything
52%
$
Pub Food
</code>```

so it's just the first and the last one with the same cuisine but there are more later in the file.
And here is my code:

```<code>def new(file):
    file = "/.../Restaurants.txt"
    d = {}
    key = []
    with open(file) as file:
        lines = file.readlines()

    for i in range(len(lines)):
        if i % 5 == 0:
            if "," not in lines[i + 3]:
                d[lines[i + 3].strip()] = [lines[i].strip()]
            else:
                key += (lines[i + 3].strip().split(', '))
                for j in key:
                    if j not in d:
                        d[j] = [lines[i].strip()]
                    else:
                        d[j].append(lines[i].strip())
    return d
</code>```

It gets all the keys and values printed but it doesn't assign two values to the same key where it should. Also, with this last 'else' statement, the second restaurant is assigned to the wrong key as a second value. This should not happen. I would appreciate any comments or help.

答:
In the case when there is only one category you don't check if the key is in the dictionary. You should do this analogously as in the case of multiple categories and then it works fine.

I don't know why you have file as an argument when you have a file then overwritten.

Additionally you should make 'key' for each result, and not += (adding it to the existing 'key'

when you check if j is in dictionary, clean way is to check if j is in the keys (d.keys())

```<code>def new(file):
    file = "/.../Restaurants.txt"
    d = {}
    key = []
    with open(file) as file:
        lines = file.readlines()

    for i in range(len(lines)):
        if i % 5 == 0:
            if "," not in lines[i + 3]:
                if lines[i + 3] not in d.keys():
                    d[lines[i + 3].strip()] = [lines[i].strip()]
                else:
                    d[lines[i + 3]].append(lines[i].strip())

            else:
                key = (lines[i + 3].strip().split(', '))
                for j in key:
                    if j not in d.keys():
                        d[j] = [lines[i].strip()]
                    else:
                        d[j].append(lines[i].strip())
    return d
</code>```

Body:
I'm fairly new to Python but I haven't found the answer to this particular problem.
I am writing a simple recommendation program and I need to have a dictionary where cuisine is a key and name of a restaurant is a value. There are a few instances where I have to split a string of a few cuisine names and make sure all other restaurants (values) which have the same cuisine get assigned to the same cuisine (key). Here's a part of a file:

Georgie Porgie
87%
$$$
Canadian, Pub Food

Queen St. Cafe
82%
$
Malaysian, Thai

Mexican Grill
85%
$$
Mexican

Deep Fried Everything
52%
$
Pub Food

so it's just the first and the last one with the same cuisine but there are more later in the file.
And here is my code:

def new(file):
    file = "/.../Restaurants.txt"
    d = {}
    key = []
    with open(file) as file:
        lines = file.readlines()

    for i in range(len(lines)):
        if i % 5 == 0:
            if "," not in lines[i + 3]:
                d[lines[i + 3].strip()] = [lines[i].strip()]
            else:
                key += (lines[i + 3].strip().split(', '))
                for j in key:
                    if j not in d:
                        d[j] = [lines[i].strip()]
                    else:
                        d[j].append(lines[i].strip())
    return d

It gets all the keys and values printed but it doesn't assign two values to the same key where it should. Also, with this last 'else' statement, the second restaurant is assigned to the wrong key as a second value. This should not happen. I would appreciate any comments or help.

Body:
In the case when there is only one category you don't check if the key is in the dictionary. You should do this analogously as in the case of multiple categories and then it works fine.

I don't know why you have file as an argument when you have a file then overwritten.

Additionally you should make 'key' for each result, and not += (adding it to the existing 'key'

when you check if j is in dictionary, clean way is to check if j is in the keys (d.keys())

def new(file):
    file = "/.../Restaurants.txt"
    d = {}
    key = []
    with open(file) as file:
        lines = file.readlines()

    for i in range(len(lines)):
        if i % 5 == 0:
            if "," not in lines[i + 3]:
                if lines[i + 3] not in d.keys():
                    d[lines[i + 3].strip()] = [lines[i].strip()]
                else:
                    d[lines[i + 3]].append(lines[i].strip())

            else:
                key = (lines[i + 3].strip().split(', '))
                for j in key:
                    if j not in d.keys():
                        d[j] = [lines[i].strip()]
                    else:
                        d[j].append(lines[i].strip())
    return d


问:
How to make default Password Reset functionality work in ASP.NET Core
I'm following this Official NET Core tutorial where I've also chosen the Authentication mode as Individual User Accounts. When I try to call ResetPassword Get action method inside the built-in AccountController from a link in the default Index.cshtml view below it, as expected, sends the code parameter to the action method as null. And, as a result, the default error.cshtml page is displayed instead of ResetPassword.cshtml view. Question: How do I call the ResetPassword Get action method so its input parameter code is not null?

Snapshot of Index.cshtml with Reset Password link:

```<code><div class="row">
    <div class="col-md-3">
        <h2>Application uses</h2>
        <ul>
            <li>Sample pages using ASP.NET Core MVC</li>
            <li><a href="http://go.microsoft.com/fwlink/?LinkId=518004">Bower</a> for managing client-side libraries</li>
            <li>Theming using <a href="http://go.microsoft.com/fwlink/?LinkID=398939">Bootstrap</a></li>
            <li><a asp-controller="Account" asp-action="ResetPassword">Reset Password</a></li>
        </ul>
    </div>
    <div class="col-md-3">
        <h2>How to</h2>
        <ul>
....
</div>
</code>```

ResetPassword Action method in AccountController

```<code>[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
    return code == null ? View("Error") : View();
}
</code>```

答: You shouldn't be providing a link to ResetPassword from your Index, but instead should be linking to ForgottenPassword. This action will then generate the code and send an email with the link to click. That link will take the user to the ResetPassword action with the code provided.

Body:
I'm following this Official NET Core tutorial where I've also chosen the Authentication mode as Individual User Accounts. When I try to call ResetPassword Get action method inside the built-in AccountController from a link in the default Index.cshtml view below it, as expected, sends the code parameter to the action method as null. And, as a result, the default error.cshtml page is displayed instead of ResetPassword.cshtml view. Question: How do I call the ResetPassword Get action method so its input parameter code is not null?

Snapshot of Index.cshtml with Reset Password link:

Application uses

Sample pages using ASP.NET Core MVC

Bower for managing client-side libraries

Theming using Bootstrap

Reset Password

How to

....

ResetPassword Action method in AccountController

[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
    return code == null ? View("Error") : View();
}


问:
Making a CSS Drop-down Menu Responsive
I have got a CSS Drop-down menu on a website that I want to make responsive using CSS media queries, but it doesn't respond at certain breakpoints. Am using width and max-width attributes to make it respond but it fails. Please Assist?

HTML

.navbar{
  width:100%;
  max-width:1000px;
  text-align:center;
  margin-top:-8px;
  margin-bottom:23px;
  margin-left:160px;
}
.menu ul{
/*Removes bullets*/
  list-style:none;
}
.menu ul .active{
  background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(red 20%, green); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(red 20%, green); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(red 20%, green); /* For Firefox 3.6 to 15 */
  background: linear-gradient(red 20%, green); /* Standard syntax */
  background: linear-gradient(red 20%, green); /* Standard syntax */
}
/*Styles each list within ul*/
.menu ul li{
  background-color:green;
  border:1px solid #ffffff;
  width:100%;
  max-width:173px;
  height:35px;
  line-height:35px;
  margin:auto;
  text-align:center;
  /*Makes the list dispaly in a horizontal maneer*/
  float:left;
  position:relative;
  border-radius:8px;
  font: 15px;
  font-weight:regular;
}
.menu ul li a{
  text-decoration:none;
  color:white;
  display:block;
}
.menu ul li a:hover{
  background-color:red;
  border-radius:8px;
}
.menu ul ul{
  position:absolute;
  margin-left:-40px;
  display:none;
}
.menu ul li:hover >ul{
  display:block;
}
.menu ul ul ul{
  width:100%;
  margin-left:134px;
  top:0px;
}
@media only screen and (min-width: 1023px)  and (max-width: 1223px) {
  .navbar{
    width:98%;
    max-width:1000px;
  }
  .menu ul li{
    width:98%;
    max-width:173px;
    height:35px;
    line-height:35px;
    margin:auto;
  }
  .menu ul ul ul{
    width:98%;
    margin-left:134px;
    top:0px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="navbar">
  <div class="menu">
    <ul>
      <li class="active">  Home </li>
      <li>  Arts & Social Sciences <span class="arrow">▼ </span>
        <ul>
          <li>  Sociology</li>
          <li>  Anthropology </li>
          <li>  Linguistics </li>
          <li>  Political Science <span class="arrow">  ⟩</span>
            <ul>
            <li> World Civilization </li>
            <li> Politics of Development </li>
            <li> Comparative Politics</li>
            <li> Globalization </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>  Business & Economics <span class="arrow">▼ </span>
        <ul>
          <li>  Business Management</li>
          <li>  Purchasing and Supplies </li>
          <li>  Economics
            <ul>
              <li> Micro Economics </li>
              <li>  Inflation </li>
              <li> Stock Excahange </li>
              <li> Supply Chain </li>
              <li> Macro-Economics </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>  Education<span class="arrow">▼ </span>
        <ul>
          <li>  Education(Arts)</li>
          <li>  Early Childhood </li>
          <li>  Education(Scienmce)</li>
          <li>  Education & Technology
            <ul>
              <li> Marketing </li>
              <li> Supply Chain </li>
            </ul>
          </li>
        </ul>
      </li>
      <li> Contact Us</li>
    </ul>
  </div>
</div></code>```

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Example </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<style type="text/css">
    .bs-example{
        margin: 20px;
    }
</style>
</head>
<body>
<div class="bs-example">
    <nav id="myNavbar" class="navbar navbar-default" role="navigation">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">Brand</a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li><a href="#">Menu</a></li>
                    <li><a href="#">Menu</a></li>
                    <li class="dropdown">
                        <a href="#" data-toggle="dropdown" class="dropdown-toggle">Menu <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Sub-Menu</a></li>
                            <li><a href="#">Sub-Menu</a></li>
                            <li><a href="#">Sub-Menu</a></li>
                            <li><a href="#">Sub-Menu</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div>
    </nav>
</div>
</body>
</html>
</code>```

Title: Making a CSS Drop-down Menu Responsive

Body:
I have got a CSS Drop-down menu on a website that I want to make responsive using CSS media queries, but it doesn't respond at certain breakpoints. Am using width and max-width attributes to make it respond but it fails. Please Assist?

HTML

.navbar{
  width:100%;
  max-width:1000px;
  text-align:center;
  margin-top:-8px;
  margin-bottom:23px;
  margin-left:160px;
}
.menu ul{
/*Removes bullets*/
  list-style:none;
}
.menu ul .active{
  background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(red 20%, green); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(red 20%, green); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(red 20%, green); /* For Firefox 3.6 to 15 */
  background: linear-gradient(red 20%, green); /* Standard syntax */
  background: linear-gradient(red 20%, green); /* Standard syntax */
}
/*Styles each list within ul*/
.menu ul li{
  background-color:green;
  border:1px solid #ffffff;
  width:100%;
  max-width:173px;
  height:35px;
  line-height:35px;
  margin:auto;
  text-align:center;
  /*Makes the list dispaly in a horizontal maneer*/
  float:left;
  position:relative;
  border-radius:8px;
  font: 15px;
  font-weight:regular;
}
.menu ul li a{
  text-decoration:none;
  color:white;
  display:block;
}
.menu ul li a:hover{
  background-color:red;
  border-radius:8px;
}
.menu ul ul{
  position:absolute;
  margin-left:-40px;
  display:none;
}
.menu ul li:hover >ul{
  display:block;
}
.menu ul ul ul{
  width:100%;
  margin-left:134px;
  top:0px;
}
@media only screen and (min-width: 1023px)  and (max-width: 1223px) {
  .navbar{
    width:98%;
    max-width:1000px;
  }
  .menu ul li{
    width:98%;
    max-width:173px;
    height:35px;
    line-height:35px;
    margin:auto;
  }
  .menu ul ul ul{
    width:98%;
    margin-left:134px;
    top:0px;
  }
}

  Home

  Arts & Social Sciences ▼

  Sociology

  Anthropology

  Linguistics

  Political Science   ⟩

 World Civilization

 Politics of Development

 Comparative Politics

 Globalization

  Business & Economics ▼

  Business Management

  Purchasing and Supplies

  Economics

 Micro Economics

  Inflation

 Stock Excahange

 Supply Chain

 Macro-Economics

  Education▼

  Education(Arts)

  Early Childhood

  Education(Scienmce)

  Education & Technology

 Marketing

 Supply Chain

 Contact Us


问:
Can I merge/modify notifications in notification tray?
Actually, I want to create notification like WhatsApp providing in Android. Every time when a new notification comes, I like to merge it in previous one, like this one:

Is there any way to achieve it?

答: It is not posible in iOS, It's different concept for notification on android but in iOS it's not possible to group notifications for a specific app by yourself.</p>


问:
how bind md-input to md-slider value angular2
I'm developing an app with Angular 2.0/meteor, and I don't know how to bind an input to md-slider.

Here's the component html :

```<code><div class="panel-body">
   <form [formGroup]="filtreForm" #f="ngForm">
    <span class="panel-title"> <i class="glyphicon glyphicon-retweet">  Paramétrages 0 </i></span>
    <md-slide-toggle>On</md-slide-toggle>
      <div *ngFor="let filtre of filtres | async">
          <div *ngFor="let filtr of filtre.arguments">
            <span class="panel-title" > <i class="glyphicon glyphicon-retweet">  {{filtr.name}} </i></span>

            <md-input-container class="example-full-width" >
                <input mdInput placeholder="{{filtr.name}}" formControlName="{{filtr.name}}" value="{{filtr.value}}">
              </md-input-container>
          <md-slider
           thumb-label
           [min]="'0'"
           [max]="'200'"
           [value]="filtr.value">
          </md-slider>
          </div>
      </div>

    <div class="btn-group  people-pager">
        <button type="button" class="btn btn-success btn-quirk" (click)="appliquerFiltre()"><i class="fa fa-tencent-weibo   Try it"></i>  Appliquer ce filtre</button>
    </div>
    </form>
  </div>
</code>```

Here's the component ts :

```<code>import {Component, ViewEncapsulation, OnInit, NgZone, Input} from '@angular/core';
import { Router } from '@angular/router';
import { Meteor } from 'meteor/meteor';
import { Observable } from 'rxjs';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

//Collection import
import { Filtres } from '../../../../both/collections/filtres.collection';
import {Filtre} from "../../../../both/models/filtre.model";

import template from './tpl.dashboard.component.html';

@Component({
  selector: 'traitement_par_lot',
  encapsulation: ViewEncapsulation.None,
  template
})

export class TPLcomponent implements OnInit{

  filtres: Observable<Filtre[]>;
  filtreForm: FormGroup;

   constructor(
    private formBuilder: FormBuilder, private router: Router
  ) {}

  ngOnInit(){
    this.filtreForm = this.formBuilder.group({
        spread:['',Validators.required],
        density:['',Validators.required],
        curviness:['',Validators.required],
        reseed:['',Validators.required],
    });

    this.filtres = Filtres.find({}).zone();
    console.log(this.filtres);
  }

  appliquerFiltre(){

  }

}
</code>```

This doesn't work. for now i can get the initial value from the slider but it's doesn't change when i slide

Thanks in advance

答:
For update the value while slidering, you can use change or input event of md-slider, and get the current value from it's event.value.

change event will be fired only after the end of you slide.

input event will be fired immediately when the value of slider changes

you can choose the better one for your situation.
take a look at this plunker.

Body:
I'm developing an app with Angular 2.0/meteor, and I don't know how to bind an input to md-slider.

Here's the component html :

   <form [formGroup]="filtreForm" #f="ngForm">
       Paramétrages 0
    <md-slide-toggle>On</md-slide-toggle>

               {{filtr.name}}

            <md-input-container class="example-full-width" >
                <input mdInput placeholder="{{filtr.name}}" formControlName="{{filtr.name}}" value="{{filtr.value}}">
              </md-input-container>
          <md-slider
           thumb-label
           [min]="'0'"
           [max]="'200'"
           [value]="filtr.value">
          </md-slider>

        <button type="button" class="btn btn-success btn-quirk" (click)="appliquerFiltre()">  Appliquer ce filtre</button>

    </form>

Here's the component ts :

import {Component, ViewEncapsulation, OnInit, NgZone, Input} from '@angular/core';
import { Router } from '@angular/router';
import { Meteor } from 'meteor/meteor';
import { Observable } from 'rxjs';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

//Collection import
import { Filtres } from '../../../../both/collections/filtres.collection';
import {Filtre} from "../../../../both/models/filtre.model";

import template from './tpl.dashboard.component.html';

@Component({
  selector: 'traitement_par_lot',
  encapsulation: ViewEncapsulation.None,
  template
})

export class TPLcomponent implements OnInit{

  filtres: Observable<Filtre[]>;
  filtreForm: FormGroup;

   constructor(
    private formBuilder: FormBuilder, private router: Router
  ) {}

  ngOnInit(){
    this.filtreForm = this.formBuilder.group({
        spread:['',Validators.required],
        density:['',Validators.required],
        curviness:['',Validators.required],
        reseed:['',Validators.required],
    });

    this.filtres = Filtres.find({}).zone();
    console.log(this.filtres);
  }

  appliquerFiltre(){

  }

}

This doesn't work. for now i can get the initial value from the slider but it's doesn't change when i slide

Thanks in advance


问:
Xamarin Dependency Service Issue
In Xamarin Forms i have a solution like this:

```<code>Solution
 |- Libraries
 |   |- IInterface.cs
 |   |- Etc.
 |
 |- Libraries.iOS
 |   |- Interface.cs
 |   |- Etc.
 |
 |- Forms.App
 |   |- App.cs
 |   |- Etc.
 |
 |- Forms.App.iOS
 |   |- Etc.
</code>```

Forms.App.iOS references Libraries.iOS

Forms.App references Libraries

Libraries.iOS references Libraries

Forms.App.iOS references Forms.App

IInterface.cs

```<code>namespace a
{
  public interface IInterface
  {
    void Function ();
  }
}
</code>```

Interface.cs

```<code>[assembly: Xamarin.Forms.Dependency(typeof(a.Interface))]
namespace a
{
  public class Interface : IInterface
  {
    public void Function ()
    {
      return;
    }
  }
}
</code>```

App.cs

```<code>namespace a
{
  public class App
  {
    public static Page GetMainPage ()
    {
      var inter = DependencyService.Get<IInterface> (); // This is always null.
      return new ContentPage {
        Content = new Label {
        Text = "Hello, Forms!",
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand,
        },
      };
    }
  }
}
</code>```

How can i make the dependency service locate my Interface implementation?
I need to have them in a separate project because i need the same implementations in different projects.

答:
I had

[assembly: Dependency(typeof(TestService.IMyService))]

, where I should have

[assembly: Dependency(typeof(TestService.iOS.MyService))]

So always take the implementation and not the interface in your platform specific code! Otherwise you get

System.MissingMethodException: Default constructor not found for [Interface]

Title: Xamarin Dependency Service Issue

Body:
In Xamarin Forms i have a solution like this:

Solution
 |- Libraries
 |   |- IInterface.cs
 |   |- Etc.
 |
 |- Libraries.iOS
 |   |- Interface.cs
 |   |- Etc.
 |
 |- Forms.App
 |   |- App.cs
 |   |- Etc.
 |
 |- Forms.App.iOS
 |   |- Etc.

Forms.App.iOS references Libraries.iOS

Forms.App references Libraries

Libraries.iOS references Libraries

Forms.App.iOS references Forms.App

IInterface.cs

namespace a
{
  public interface IInterface
  {
    void Function ();
  }
}

Interface.cs

[assembly: Xamarin.Forms.Dependency(typeof(a.Interface))]
namespace a
{
  public class Interface : IInterface
  {
    public void Function ()
    {
      return;
    }
  }
}

App.cs

namespace a
{
  public class App
  {
    public static Page GetMainPage ()
    {
      var inter = DependencyService.Get<IInterface> (); // This is always null.
      return new ContentPage {
        Content = new Label {
        Text = "Hello, Forms!",
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand,
        },
      };
    }
  }
}

How can i make the dependency service locate my Interface implementation?
I need to have them in a separate project because i need the same implementations in different projects.


问:
need help with arrays and links in javascript
Hi i have a question regarding html and javascript.

Say that i click on a link on a html site say

```<code><tr>
<td><a href="www.hello1.com">www.hello1.com</a></td>
</tr>
</code>```

then I also want to see if there are any other related link on that site with a narrow name, for example

```<code><tr>
<td><a href="www.hello2.com">www.hello2.com</a></td>
</tr>
</code>```

So what I want to do is construct a javascript method that everytime you click on a link
you run this method and check what link that has been pressed, and then also search the entire html site for a similar link (here its very simple, the site only consist of a table containing links, so there will not be so much to search trough).

How is this done?

I only need the method, I know how to run the method everytime you press a link :)

Thanks in advance :)

Edit
With "similar" i mean something like this

```<code>'\\b'+theUrlToGoTo+'\\b'
</code>```

In other words the only thing that will change is a number after the name for example

hello1 and hello2

Edit 2

Thanks to nemophrost I now know how to do the first one. I now have a second question, before Im done, thats regarding generating html code with javascript.
Now say that I have an array after I have run the everyClickFunc() func that includes

```<code>var myArray = [ 'www.hello1.com', 'www.hello2.com', 'www.hello3.com'];
</code>```

I would now like to generate a simple html page like this

```<code><html>
<head>
</head>
<body>
<table>
<tr>
<td><a href="www.hello1.com">www.hello1.com</a></td>
</tr>
<tr>
<td><a href="www.hello2.com">www.hello2.com</a></td>
</tr>
<tr>
<td><a href="www.hello3.com">www.hello3.com</a></td>
</tr>

</table>
</html>
</code>```

And this file is to be overwritten each time I click on a link. So the links will be diffrent depending on what links i click on, on the original site.

In other words I want something like this

```<code><html>
<head>
</head>
<body>
<table>
<tr>
<td><a href="www.testing1.com">www.testing1.com</a></td>
</tr>
<tr>
<td><a href="www.hello1.com">www.hello1.com</a></td>
</tr>
<tr>
<td><a href="www.testing2.com">www.testing2.com</a></td>
</tr>
<tr>
<td><a href="www.hello2.com">www.hello2.com</a></td>
</tr>
<tr>
<td><a href="www.hello3.com">www.hello3.com</a></td>
</tr>
<tr>
<td><a href="www.difrent1.com">www.diffrent1.com</a></td>
</tr>
<tr>
<td><a href="www.difrent2.com">www.diffrent2.com</a></td>
</tr>
</table>
</html>
</code>```

To generate a new html site that contains the following information if you click on any of the above "hello" links

```<code><html>
<head>
</head>
<body>
<table>
<tr>
<td><a href="www.hello1.com">www.hello1.com</a></td>
</tr>
<tr>
<td><a href="www.hello2.com">www.hello2.com</a></td>
</tr>
<tr>
<td><a href="www.hello3.com">www.hello3.com</a></td>
</tr>

</table>
</html>
</code>```

How is this easiest solved?

Again thanks you so much in advance :)

答:
With jQuery you could do something like this:</p>

```<code>function everyClickFunc(urlToMatch) { // pass in something like 'www.hello1.com'
    var baseURLMatch = urlToMatch.match(/^www\.(.+\D)\d*\.com$/);

    if (baseURLMatch && baseURLMatch.length > 1) {
        var matchExp = new RegExp('^www\\.' + baseURLMatch[1] + '\\d*\\.com$');

        $('a').each(function() {
            if ($(this).attr('href').match(matchExp)) {
                doSomethingBecauseYouGotAMatch(); // Call your successful match function
            }
        });
    }
}
</code>```

Body:
Hi i have a question regarding html and javascript.

Say that i click on a link on a html site say

www.hello1.com

then I also want to see if there are any other related link on that site with a narrow name, for example

www.hello2.com

So what I want to do is construct a javascript method that everytime you click on a link
you run this method and check what link that has been pressed, and then also search the entire html site for a similar link (here its very simple, the site only consist of a table containing links, so there will not be so much to search trough).

How is this done?

I only need the method, I know how to run the method everytime you press a link :)

Thanks in advance :)

Edit
With "similar" i mean something like this

'\\b'+theUrlToGoTo+'\\b'

In other words the only thing that will change is a number after the name for example

hello1 and hello2

Edit 2

Thanks to nemophrost I now know how to do the first one. I now have a second question, before Im done, thats regarding generating html code with javascript.
Now say that I have an array after I have run the everyClickFunc() func that includes

var myArray = [ 'www.hello1.com', 'www.hello2.com', 'www.hello3.com'];

I would now like to generate a simple html page like this

www.hello1.com

www.hello2.com

www.hello3.com

And this file is to be overwritten each time I click on a link. So the links will be diffrent depending on what links i click on, on the original site.

In other words I want something like this

www.testing1.com

www.hello1.com

www.testing2.com

www.hello2.com

www.hello3.com

www.diffrent1.com

www.diffrent2.com

To generate a new html site that contains the following information if you click on any of the above "hello" links

www.hello1.com

www.hello2.com

www.hello3.com

How is this easiest solved?

Again thanks you so much in advance :)

Body:
With jQuery you could do something like this:

function everyClickFunc(urlToMatch) { // pass in something like 'www.hello1.com'
    var baseURLMatch = urlToMatch.match(/^www\.(.+\D)\d*\.com$/);

    if (baseURLMatch && baseURLMatch.length > 1) {
        var matchExp = new RegExp('^www\\.' + baseURLMatch[1] + '\\d*\\.com$');

        $('a').each(function() {
            if ($(this).attr('href').match(matchExp)) {
                doSomethingBecauseYouGotAMatch(); // Call your successful match function
            }
        });
    }
}


问:
Executing PHP CURL in While Loop
I have a table where I want to run a PHP script during the maintenance.

I have the following code.

```<code>$sql = "SELECT `id`, `url` FROM `log_requests` WHERE `is_sent` = '0'";
$e = $conn->execute($sql);
</code>```

My url array after fetching the table from DB.

```<code>Array
(
[0] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+1
[1] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+2
[2] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+3
[3] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+4
)
</code>```

Then I run while loop

```<code>$ch = curl_init();
while($row = $e->FetchRow() ){
    curl_setopt($ch, CURLOPT_URL, $row['url']);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
    $conn->execute($q);
}
curl_close($ch);
</code>```

Issue is only one URL is executed using CURL and in my table only one row gets updated as 1 in is_sent column.

Why is it running single url in my while loop. What mistakes am I making here?

************************* EDIT ********************

Okay, now I came out with following and running successfully now. I just want to know whether am doing right or not.

```<code>$set = array();
while ($row = $executequery2->FetchRow()) {
    $set[$row['url']][] = $row;
}

$curl_handles = array();
foreach($set as $url => $rows) {
    $curl_handles[$url] = curl_init();
    curl_setopt($curl_handles[$url], CURLOPT_URL, $url);
    foreach($rows as $row) {
        $query3 = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '" . $row['id'] . "'";
        $conn->Execute($query3);
    }
}

$curl_multi_handle = curl_multi_init();
$i = 0;
$block = array();

foreach($curl_handles as $a_curl_handle) {
    $i++;
    curl_multi_add_handle($curl_multi_handle, $a_curl_handle);
    $block[] = $a_curl_handle;
    if (($i % 5 == 0) or ($i == count($curl_handles))) {
        $running = NULL;
        do {
            $running_before = $running;
            curl_multi_exec($curl_multi_handle, $running);
            if ($running != $running_before) {
                echo ("Waiting for $running sites to finish...<br />");
            }
        }
        while ($running > 0);
        foreach($block as $handle) {
            $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            $curl_errno = curl_errno($handle);
            $curl_error = curl_error($handle);
            if ($curl_error) {
                echo ("    *** cURL error: ($curl_errno) $curl_error\n");
            }
            curl_multi_remove_handle($curl_multi_handle, $handle);
        }
        $block = array();
    }
}

curl_multi_close($curl_multi_handle);
</code>```

Updating the table column is the right way?

答:
I had faced same issue and got this solution online. Just separate curl code from the loop and then try.

Something like this:

```<code>while($row = $e->FetchRow()) {
    $result = call_curl($row['url']);
    if($result === FALSE) {
        die("Error");
    }
    else
    {
        $q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
    }
}

function call_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec ($ch);
    curl_close($ch);
    return $result;
}
</code>```

Hope this helps you as well.

Title: Executing PHP CURL in While Loop

Body:
I have a table where I want to run a PHP script during the maintenance.

I have the following code.

$sql = "SELECT `id`, `url` FROM `log_requests` WHERE `is_sent` = '0'";
$e = $conn->execute($sql);

My url array after fetching the table from DB.

Array
(
[0] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+1
[1] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+2
[2] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+3
[3] => https://www.smsgatewaycenter.com/library/send_sms_2.php?UserName=username&Password=password&Type=Individual&To=9999999999&Mask=Senderid&Message=Hello+World+4
)

Then I run while loop

$ch = curl_init();
while($row = $e->FetchRow() ){
    curl_setopt($ch, CURLOPT_URL, $row['url']);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
    $conn->execute($q);
}
curl_close($ch);

Issue is only one URL is executed using CURL and in my table only one row gets updated as 1 in is_sent column.

Why is it running single url in my while loop. What mistakes am I making here?

************************* EDIT ********************

Okay, now I came out with following and running successfully now. I just want to know whether am doing right or not.

$set = array();
while ($row = $executequery2->FetchRow()) {
    $set[$row['url']][] = $row;
}

$curl_handles = array();
foreach($set as $url => $rows) {
    $curl_handles[$url] = curl_init();
    curl_setopt($curl_handles[$url], CURLOPT_URL, $url);
    foreach($rows as $row) {
        $query3 = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '" . $row['id'] . "'";
        $conn->Execute($query3);
    }
}

$curl_multi_handle = curl_multi_init();
$i = 0;
$block = array();

foreach($curl_handles as $a_curl_handle) {
    $i++;
    curl_multi_add_handle($curl_multi_handle, $a_curl_handle);
    $block[] = $a_curl_handle;
    if (($i % 5 == 0) or ($i == count($curl_handles))) {
        $running = NULL;
        do {
            $running_before = $running;
            curl_multi_exec($curl_multi_handle, $running);
            if ($running != $running_before) {
                echo ("Waiting for $running sites to finish...
");
            }
        }
        while ($running > 0);
        foreach($block as $handle) {
            $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
            $curl_errno = curl_errno($handle);
            $curl_error = curl_error($handle);
            if ($curl_error) {
                echo ("    *** cURL error: ($curl_errno) $curl_error\n");
            }
            curl_multi_remove_handle($curl_multi_handle, $handle);
        }
        $block = array();
    }
}

curl_multi_close($curl_multi_handle);

Updating the table column is the right way?

Body:
I had faced same issue and got this solution online. Just separate curl code from the loop and then try.

Something like this:

while($row = $e->FetchRow()) {
    $result = call_curl($row['url']);
    if($result === FALSE) {
        die("Error");
    }
    else
    {
        $q = "UPDATE `log_requests` SET `is_sent` = '1' WHERE `id` = '".$row['id']."'";
    }
}

function call_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec ($ch);
    curl_close($ch);
    return $result;
}

Hope this helps you as well.


问:
I need to modify a VBA code to delete all the other rows but not the one that I input
I have this VBA code

```<code>Sub DeleteRows()
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "Delete"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
For Each rng In InputRng
    If rng.Value = DeleteStr Then
        If DeleteRng Is Nothing Then
            Set DeleteRng = rng
        Else
            Set DeleteRng = Application.Union(DeleteRng, rng)
        End If
    End If
Next
DeleteRng.EntireRow.Delete
End Sub
</code>```

This one deletes all the rows for the word I input. I need it to delete all the others except the word I input.
Thanks in advance!

答:
Your problem is that you allow the user to select a range of more than one column.  With If rng.Value <> DeleteStr Then if the search string exist in one cell of a selected row but not in another cell on the same row, that row is marked for deletion.

So, consider each row seperately.  If any cell in that row equals the search string, exclude the row from from deletion

Something like this

```<code>Sub DeleteRows()
    Dim rng As Range, rw As Range
    Dim delRow As Boolean
    Dim InputRng As Range
    Dim DeleteRng As Range
    Dim DeleteStr As String
    Dim xTitleId As String

    xTitleId = "Delete"
    Set InputRng = Application.Selection
    Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
    DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
    For Each rw In InputRng.Rows
        delRow = True
        For Each rng In rw.Cells
            If rng.Value = DeleteStr Then
                delRow = False
                Exit For
            End If
        Next
        If delRow Then
            If DeleteRng Is Nothing Then
                Set DeleteRng = rw.EntireRow
            Else
                Set DeleteRng = Application.Union(DeleteRng, rw.EntireRow)
            End If
        End If
    Next
    If Not DeleteRng Is Nothing Then
        DeleteRng.Delete
    End If
End Sub
</code>```

Body:
I have this VBA code

Sub DeleteRows()
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "Delete"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
For Each rng In InputRng
    If rng.Value = DeleteStr Then
        If DeleteRng Is Nothing Then
            Set DeleteRng = rng
        Else
            Set DeleteRng = Application.Union(DeleteRng, rng)
        End If
    End If
Next
DeleteRng.EntireRow.Delete
End Sub

This one deletes all the rows for the word I input. I need it to delete all the others except the word I input.
Thanks in advance!

Body:
Your problem is that you allow the user to select a range of more than one column.  With If rng.Value <> DeleteStr Then if the search string exist in one cell of a selected row but not in another cell on the same row, that row is marked for deletion.

So, consider each row seperately.  If any cell in that row equals the search string, exclude the row from from deletion

Something like this

Sub DeleteRows()
    Dim rng As Range, rw As Range
    Dim delRow As Boolean
    Dim InputRng As Range
    Dim DeleteRng As Range
    Dim DeleteStr As String
    Dim xTitleId As String

    xTitleId = "Delete"
    Set InputRng = Application.Selection
    Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
    DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
    For Each rw In InputRng.Rows
        delRow = True
        For Each rng In rw.Cells
            If rng.Value = DeleteStr Then
                delRow = False
                Exit For
            End If
        Next
        If delRow Then
            If DeleteRng Is Nothing Then
                Set DeleteRng = rw.EntireRow
            Else
                Set DeleteRng = Application.Union(DeleteRng, rw.EntireRow)
            End If
        End If
    Next
    If Not DeleteRng Is Nothing Then
        DeleteRng.Delete
    End If
End Sub


问:
s#arp castle injection
I have a soap web service in my web layer (s#arp architecture) which uses a service like this:

```<code>public ReportWebService(IReportService ReportService)
{
 Check.Require(ReportService != null, "ReportService may not be null");
 this.ReportService = ReportService;
}
</code>```

Can someone please remind me how/where I configure the injection of the implementation for IReportService again?

Thanks.

Christian

答:
The short answer is: Just put ReportService into yourProject.ApplicationServices and it will be injected.

The long answer is: In yourProject.Web in Global.asax you will find the method InitializeServiceLocator(). This calls the static method AddComponents on ComponentRegistrar.

ComponentRegistrar is located in yourProject.web/CastleWindsor. In there you will find

```<code>public static void AddComponentsTo(IWindsorContainer container)
    {
        AddGenericRepositoriesTo(container);
        AddCustomRepositoriesTo(container);
        AddApplicationServicesTo(container);

        container.AddComponent("validator",
            typeof(IValidator), typeof(Validator));
    }
</code>```

If you look at AddApplicationServicesTo you can see that is registers all types in yourProject.ApplicationServices (.WithService.FirstInterface()):

```<code>private static void AddApplicationServicesTo(IWindsorContainer container)
    {
        container.Register(
            AllTypes.Pick()
            .FromAssemblyNamed("NewittsStore.ApplicationServices")
            .WithService.FirstInterface());
    }
</code>```

Title: s#arp castle injection

Body:
I have a soap web service in my web layer (s#arp architecture) which uses a service like this:

public ReportWebService(IReportService ReportService)
{
 Check.Require(ReportService != null, "ReportService may not be null");
 this.ReportService = ReportService;
}

Can someone please remind me how/where I configure the injection of the implementation for IReportService again?

Thanks.

Christian

Body:
The short answer is: Just put ReportService into yourProject.ApplicationServices and it will be injected.

The long answer is: In yourProject.Web in Global.asax you will find the method InitializeServiceLocator(). This calls the static method AddComponents on ComponentRegistrar.

ComponentRegistrar is located in yourProject.web/CastleWindsor. In there you will find

public static void AddComponentsTo(IWindsorContainer container)
    {
        AddGenericRepositoriesTo(container);
        AddCustomRepositoriesTo(container);
        AddApplicationServicesTo(container);

        container.AddComponent("validator",
            typeof(IValidator), typeof(Validator));
    }

If you look at AddApplicationServicesTo you can see that is registers all types in yourProject.ApplicationServices (.WithService.FirstInterface()):

private static void AddApplicationServicesTo(IWindsorContainer container)
    {
        container.Register(
            AllTypes.Pick()
            .FromAssemblyNamed("NewittsStore.ApplicationServices")
            .WithService.FirstInterface());
    }


问:
Why it is showing time limit exceeded?
In the following question I am getting time limit exceeded message on whichever compiler I tried(though they were all online compilers).What should be the problem?</p>

```<code>#include <stdio.h>
int fact(int);
int main(void)
{
    int num,res;
    printf("enter any number");
    scanf("%d",&num);
    res=fact(num);
    printf("%d",res);
    return 0;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}
</code>```

答:
Problem is that your fact function never stopped since while loop never ends.

```<code>int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1)); //X is never changed!
    return ans;
}
</code>```

Probably you wanted this:

```<code>int fact(int x)
{
    int ans = 1; //Set default value for return
    if(x!=1) //Go recursive only if X != 1
        ans=(x*fact(x-1));
    return ans;
}
</code>```

Title: Why it is showing time limit exceeded?

Body:
In the following question I am getting time limit exceeded message on whichever compiler I tried(though they were all online compilers).What should be the problem?

#include <stdio.h>
int fact(int);
int main(void)
{
    int num,res;
    printf("enter any number");
    scanf("%d",&num);
    res=fact(num);
    printf("%d",res);
    return 0;
}
int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1));
    return ans;
}

Body:
Problem is that your fact function never stopped since while loop never ends.

int fact(int x)
{
    int ans;
    while(x!=1)
        ans=(x*fact(x-1)); //X is never changed!
    return ans;
}

Probably you wanted this:

int fact(int x)
{
    int ans = 1; //Set default value for return
    if(x!=1) //Go recursive only if X != 1
        ans=(x*fact(x-1));
    return ans;
}


问:
C# Generating new id from database on windows forms application
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

```<code>public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}
</code>```

Also I find answer on stackoverflow:

```<code>object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();
</code>```

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.

答:
You may further simplify it like below,

Select isnull(max(accountID),0) as maxID from Account

Body:
I have to make automatic generate new AccountID  on my load windows form app.

So for example when users start windows form "Add new Account" in textbox for "Account id" I have to show latest value from database. If i have two accounts in database on windows form in textbox value will be three.

My code perfectly work if i have at least one account in database, but when my database is empty i got exception.

This is my code:

public int GetLatestAccountID()
{
    try
    {
        command.CommandText = "select Max(AccountID)as maxID from Account";
        command.CommandType = CommandType.Text;

        connection.Open();

        OleDbDataReader reader= command.ExecuteReader();

        if (reader.Read())
        {
            int valueID = Convert.ToInt32(reader["maxID"]);
            return valueID + 1;
        }

        return 1;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (connection!= null)
        {
            connection.Close();
        }
    }
}

Also I find answer on stackoverflow:

object aa = DBNull.Value;
int valueID = (aa as int?).GetValueOrDefault();

But this line of code works if my database is empty, but when I have one account in the database, it will always show on my windows form in account id textbox value one. I use Microsoft Access 2007 database.

I appreciate any help.


问:
Label not display in subview of UITableView
I am designing an iOS hamburger menu with a table view in swift3

I want to display the number of notifications in menu tab.

```<code> let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))

            let subviews = self.view.viewWithTag(100001)
            if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
                if subviews == nil {

                    pieNotifi.tag = 100001;
                    cell.addSubview(pieNotifi)
                    let pieShape = pieNotifi.layer;
                    pieShape.backgroundColor = UIColor.red.cgColor
                    pieShape.cornerRadius = pieShape.bounds.width / 4

                    pieLabNotifi.textColor = UIColor.white
                    pieLabNotifi.adjustsFontSizeToFitWidth = true;
                    pieLabNotifi.minimumScaleFactor = 0.5
                    pieLabNotifi.textAlignment = NSTextAlignment.center
                    pieNotifi.addSubview(pieLabNotifi)
                    pieLabNotifi.text = String(myGlobal.unreaddot)

                }
                else{
                    pieLabNotifi.text = String(myGlobal.unreaddot)
                }

            }else{
                let subviews = cell.viewWithTag(100001)
                subviews?.removeFromSuperview()
                print("remove red dot")
            }
</code>```

however,  it only display the red colour layer but do not have the label. refer to the picture shown below
enter image description here

I had tried to set

```<code> .sendSubview(to back:)
 .bringSubview(toFront: )
 .layer.zPosition = 1
</code>```

all these key word not work for me.

Can anyone advise me to solve this problem?

答:
i think the issue is with the positions of your label. You are giving your label x coordinate as cell.contentView.frame.size.width-40, but you want to add it inside the red image view. Changing the x position and y position to 0 (or whatever value you need )for your label will solve your problem. I have modified your code accordingly :

let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(0,0, 30, 20))

```<code>        let subviews = self.view.viewWithTag(100001)
        if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
            if subviews == nil {

                pieNotifi.tag = 100001;
                cell.addSubview(pieNotifi)
                let pieShape = pieNotifi.layer;
                pieShape.backgroundColor = UIColor.red.cgColor
                pieShape.cornerRadius = pieShape.bounds.width / 4

                pieLabNotifi.textColor = UIColor.white
                pieLabNotifi.adjustsFontSizeToFitWidth = true;
                pieLabNotifi.minimumScaleFactor = 0.5
                pieLabNotifi.textAlignment = NSTextAlignment.center
                pieNotifi.addSubview(pieLabNotifi)
                pieLabNotifi.text = String(myGlobal.unreaddot)

            }
            else{
                pieLabNotifi.text = String(myGlobal.unreaddot)
            }

        }else{
            let subviews = cell.viewWithTag(100001)
            subviews?.removeFromSuperview()
            print("remove red dot")
        }
</code>```

Also try to see your label position in UiDebugger , you might discover that label is added at wrong position.

Body:
I am designing an iOS hamburger menu with a table view in swift3

I want to display the number of notifications in menu tab.

 let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))

            let subviews = self.view.viewWithTag(100001)
            if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
                if subviews == nil {

                    pieNotifi.tag = 100001;
                    cell.addSubview(pieNotifi)
                    let pieShape = pieNotifi.layer;
                    pieShape.backgroundColor = UIColor.red.cgColor
                    pieShape.cornerRadius = pieShape.bounds.width / 4

                    pieLabNotifi.textColor = UIColor.white
                    pieLabNotifi.adjustsFontSizeToFitWidth = true;
                    pieLabNotifi.minimumScaleFactor = 0.5
                    pieLabNotifi.textAlignment = NSTextAlignment.center
                    pieNotifi.addSubview(pieLabNotifi)
                    pieLabNotifi.text = String(myGlobal.unreaddot)

                }
                else{
                    pieLabNotifi.text = String(myGlobal.unreaddot)
                }

            }else{
                let subviews = cell.viewWithTag(100001)
                subviews?.removeFromSuperview()
                print("remove red dot")
            }

however,  it only display the red colour layer but do not have the label. refer to the picture shown below
enter image description here

I had tried to set

 .sendSubview(to back:)
 .bringSubview(toFront: )
 .layer.zPosition = 1

all these key word not work for me.

Can anyone advise me to solve this problem?

Body:
i think the issue is with the positions of your label. You are giving your label x coordinate as cell.contentView.frame.size.width-40, but you want to add it inside the red image view. Changing the x position and y position to 0 (or whatever value you need )for your label will solve your problem. I have modified your code accordingly :

let pieNotifi = UIImageView(frame: CGRectMake(cell.contentView.frame.size.width-40, cell.contentView.frame.size.height/2-7, 30, 20))
            let pieLabNotifi = UILabel(frame: CGRectMake(0,0, 30, 20))

        let subviews = self.view.viewWithTag(100001)
        if myGlobal.unreaddot != 0 {     //just a count for notifcaiton
            if subviews == nil {

                pieNotifi.tag = 100001;
                cell.addSubview(pieNotifi)
                let pieShape = pieNotifi.layer;
                pieShape.backgroundColor = UIColor.red.cgColor
                pieShape.cornerRadius = pieShape.bounds.width / 4

                pieLabNotifi.textColor = UIColor.white
                pieLabNotifi.adjustsFontSizeToFitWidth = true;
                pieLabNotifi.minimumScaleFactor = 0.5
                pieLabNotifi.textAlignment = NSTextAlignment.center
                pieNotifi.addSubview(pieLabNotifi)
                pieLabNotifi.text = String(myGlobal.unreaddot)

            }
            else{
                pieLabNotifi.text = String(myGlobal.unreaddot)
            }

        }else{
            let subviews = cell.viewWithTag(100001)
            subviews?.removeFromSuperview()
            print("remove red dot")
        }

Also try to see your label position in UiDebugger , you might discover that label is added at wrong position.


问:
How to access the element at variable index of a tuple?
I'm writing a function to read vectors from stdin, and here is what I have so far:

```<code>fn read_vector() -> (i64, i64, i64) {
    let mut vec = (0, 0, 0);
    let mut value = String::new();

    for i in 0..3 {
        io::stdin().read_line(&mut value).expect("Failed to read line");
        vec.i = value.trim().parse().expect("Failed to read number!"); // error!
    }
}
</code>```

However, the annotated line contains an error:

error: no field `i` on type `({integer}, {integer}, {integer})`
  --> src/main.rs:13:13
   |
13 |         vec.i = value.trim().parse().expect("Failed to read number!");
   |             ^
```

Reading the documentation entry doesn't reveal any get, or similar function.

So, is there any way to get the ith value of a tuple?

答:
While there are no built-in methods to extract the i-th value for non-constant i, there exist crates like tuple to implement dynamic indexing of a homogeneous tuple.

```<code>extern crate tuple;

...
*vec.get_mut(i).unwrap() = value.trim().parse().expect("!");
</code>```

(But, as @fjh mentioned, it is far better to operate on an array [i64; 3] instead of a tuple (i64, i64, i64).)

Body:
I'm writing a function to read vectors from stdin, and here is what I have so far:

fn read_vector() -> (i64, i64, i64) {
    let mut vec = (0, 0, 0);
    let mut value = String::new();

    for i in 0..3 {
        io::stdin().read_line(&mut value).expect("Failed to read line");
        vec.i = value.trim().parse().expect("Failed to read number!"); // error!
    }
}

However, the annotated line contains an error:

error: no field `i` on type `({integer}, {integer}, {integer})`
  --> src/main.rs:13:13
   |
13 |         vec.i = value.trim().parse().expect("Failed to read number!");
   |             ^

Reading the documentation entry doesn't reveal any get, or similar function.

So, is there any way to get the ith value of a tuple?

Body:
While there are no built-in methods to extract the i-th value for non-constant i, there exist crates like tuple to implement dynamic indexing of a homogeneous tuple.

extern crate tuple;

...
*vec.get_mut(i).unwrap() = value.trim().parse().expect("!");

(But, as @fjh mentioned, it is far better to operate on an array [i64; 3] instead of a tuple (i64, i64, i64).)


问:
How to get to know about developer code blame in android studio
I am working on project which is shared by few developers, how to get to know about developer blame in android studio?? any shortcuts or any idea? which will help us to know about code blame.</p>

答:
Use Annotate feature of Android Studio

1.Right click in line number pane

:

2.Select Annotate


问:
Handle tap on same segmented button?
I'm trying to handle a tap event on a segmented control, but when the selected button is clicked again. For example, for the screenshot below where "Second" is already selected, how do I handle the action when the "Second" button is clicked again?

I tried an IBOutlet, but it only triggers when the value has changed. Then I tried the code below, but the same thing where it triggers only when the value changes. In both cases while "Second" is selected, clicking "Second" again does not fire anything. Is there a way to do this?

```<code>segmentedControl.addTarget(self, action: "segementedAnyTap:", forControlEvents: .AllEvents)
</code>```

答:
Great Answer @Sgorbyo, here is a Swift 3 version of it:</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    let segmentedTapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureSegment(_:)))
    segmentedControl.addGestureRecognizer(segmentedTapGesture)
}

@IBAction func onTapGestureSegment(_ tapGesture: UITapGestureRecognizer) {
    let point = tapGesture.location(in: segmentedControl)
    let segmentSize = tipSegmentedControl.bounds.size.width / CGFloat(segmentedControl.numberOfSegments)
    let touchedSegment = Int(point.x / segmentSize)

    if segmentedControl.selectedSegmentIndex != touchedSegment {
        // Normal behaviour the segment changes
        segmentedControl.selectedSegmentIndex = touchedSegment
    } else {
        // Tap on the already selected segment
        segmentedControl.selectedSegmentIndex = touchedSegment
    }
    onSegment(segmentedControl)
}

@IBAction func onSegment(_ sender: Any) {
// Your segment changed selector
}
</code>```

Title: Handle tap on same segmented button?

Body:
I'm trying to handle a tap event on a segmented control, but when the selected button is clicked again. For example, for the screenshot below where "Second" is already selected, how do I handle the action when the "Second" button is clicked again?

I tried an IBOutlet, but it only triggers when the value has changed. Then I tried the code below, but the same thing where it triggers only when the value changes. In both cases while "Second" is selected, clicking "Second" again does not fire anything. Is there a way to do this?

segmentedControl.addTarget(self, action: "segementedAnyTap:", forControlEvents: .AllEvents)

Body:
Great Answer @Sgorbyo, here is a Swift 3 version of it:

override func viewDidLoad() {
    super.viewDidLoad()
    let segmentedTapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureSegment(_:)))
    segmentedControl.addGestureRecognizer(segmentedTapGesture)
}

@IBAction func onTapGestureSegment(_ tapGesture: UITapGestureRecognizer) {
    let point = tapGesture.location(in: segmentedControl)
    let segmentSize = tipSegmentedControl.bounds.size.width / CGFloat(segmentedControl.numberOfSegments)
    let touchedSegment = Int(point.x / segmentSize)

    if segmentedControl.selectedSegmentIndex != touchedSegment {
        // Normal behaviour the segment changes
        segmentedControl.selectedSegmentIndex = touchedSegment
    } else {
        // Tap on the already selected segment
        segmentedControl.selectedSegmentIndex = touchedSegment
    }
    onSegment(segmentedControl)
}

@IBAction func onSegment(_ sender: Any) {
// Your segment changed selector
}


问:
Can't access Javascript object
I am creating an app in ionic. In that I need to store a value of an object into another variable; the name of the array of objects is username.

This is username[0] :

```<code>Object {username: "user1"}
</code>```

Here I want to store the value of username into another $scope variable. So I did as follows:

```<code>$scope.username=$scope.username[0].username;
</code>```

But, it returned error. Why? and how to solve it.

答:
Try this</p>

```<code>var obj = {username: "user1"};

$scope.username = obj.username;
</code>```

Title: Can't access Javascript object

Body:
I am creating an app in ionic. In that I need to store a value of an object into another variable; the name of the array of objects is username.

This is username[0] :

Object {username: "user1"}

Here I want to store the value of username into another $scope variable. So I did as follows:

$scope.username=$scope.username[0].username;

But, it returned error. Why? and how to solve it.

Body:
Try this

var obj = {username: "user1"};

$scope.username = obj.username;


问:
DB Connection on Ajax
I have a chat on my website, and it runs on AJAX calls.  Knowing that the PHP script is being ran 2-3 times per second, is it a bad idea to connect to a database and pull / insert data?  I am wondering if it will slow down my PHP significantly, or not change it much at all.</p>

答:
Sorry I can't comment yet, so i don't know if that's your answer..

So basically of course this will cause all lot of traffic on your database. Depending on Webserver this might not be that big of a deal. But if a Clients physic computer is just from 2000, his side will just lag out the tab because his browser is sending all the time requests to your database and is trying to get the answer.

But i think this is the easiest method to get live data, which you need for your chat. But in my opinion I would suggest you to run the AJAX-Request like every 2 Seconds. I don't know what's exactly your purpose. But for a normal chat (not real time data exchange) this will last.

By the way: I am also not sure how you are initializing your AJAX-Request. But i would suggest doing this with jQuery:

```<code>$(document).ready(function(){
    call_php_ajax()
});

function call_php_ajax(){
    $("#div_toinsert").load("ajax.php");
    setTimeout(call_php_ajax, 3000)  // 3 Seconds
</code>```

And in your MySQL-Query-File (ajax.php) you perform your queries

Title: DB Connection on Ajax

Body:
Sorry I can't comment yet, so i don't know if that's your answer..

So basically of course this will cause all lot of traffic on your database. Depending on Webserver this might not be that big of a deal. But if a Clients physic computer is just from 2000, his side will just lag out the tab because his browser is sending all the time requests to your database and is trying to get the answer.

But i think this is the easiest method to get live data, which you need for your chat. But in my opinion I would suggest you to run the AJAX-Request like every 2 Seconds. I don't know what's exactly your purpose. But for a normal chat (not real time data exchange) this will last.

By the way: I am also not sure how you are initializing your AJAX-Request. But i would suggest doing this with jQuery:

$(document).ready(function(){
    call_php_ajax()
});

function call_php_ajax(){
    $("#div_toinsert").load("ajax.php");
    setTimeout(call_php_ajax, 3000)  // 3 Seconds

And in your MySQL-Query-File (ajax.php) you perform your queries


问:
How to add cyclomatic complexity to sonar-cxx?
I'm trying to add lizard report (https://github.com/terryyin/lizard) to sonar in order to create issues over functions are over a threshold

There are any way to achieve that?

答:
Sonar have his own cyclomatic-complexity calculation, so I dont need to import external report (lizard).

To create issue is as easy as activate new rules on Quality Profiles with tag brain-overload:

Files should not be too complex : default threshold 200

Functions should not be too complex : default 10, in my case I let 30


问:
How to get both like and dislike count of the post in single query using cake php or php
I have researched a day but I not get the solution.if it is possible to get he likes and dislike count of all post using single CakePHP query
table structure

```<code>id user_id  posts_id  like_and_dislike
1    1         1          1
2    2         1          1
3    4         1          0
4    5         2          1
</code>```

Here we need to get the like and dislike count of all posts that is for
post 1 like -> 2 and dislike -> 1 And for post - 2 like -> 1 and dislike -> 0
need to list the count.please any one help on this query if it not possible please help in php query

答:
You have two options

Use the CounterCache behavior

Or do two sub-queries to get the counts in the same query, which is less efficient

Body:
I have researched a day but I not get the solution.if it is possible to get he likes and dislike count of all post using single CakePHP query
table structure

id user_id  posts_id  like_and_dislike
1    1         1          1
2    2         1          1
3    4         1          0
4    5         2          1

Here we need to get the like and dislike count of all posts that is for
post 1 like -> 2 and dislike -> 1 And for post - 2 like -> 1 and dislike -> 0
need to list the count.please any one help on this query if it not possible please help in php query


问:
Symfony : sticky locale doesnt work
I'm trying to follow the "Making the Locale "Sticky" during a User's Session" Symfony tutorial but, I've got an error and I don't know why...

When I click on a flag to change language, the new language is set in session and, after the redirect, I've got the selected language in "$request->getLocale()" BUT not in the translator... Do you have an idea of the problem ? Thank very much !

Edit : I just want use locale by session

LocaleListener.php

<?php
// src/AppBundle/EventListener/LocaleListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'fr')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // Si aucune locale n'a été fixée explicitement dans la requête, on utilise celle de la session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered after the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}
```

<p>change_language.html.twig (to change the language)</p>

```key
```

<p>LanguageController.php</p>

<pre class="lang-php prettyprint-override"><code><?php

namespace AppBundle\Controller;

use AppBundle\Form\Model\Language\Language;
use AppBundle\Form\Type\LanguageType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class LanguageController.
 */
class LanguageController extends AbstractController
{
    /**
     * @Route("/changelanguage/{language}", name="app_change_language", options={"expose"=true})
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function setLanguageAction(Request $request, $language = null)
    {

        $defaultLanguage = $request->getLocale();

        // pour test
        $languages = [
            'fr' => 'French',
            'gb' => 'English',
            'es' => 'Spanish',

        ];

        if(isset($language))
        {

            $this->get('session')->set("_locale", $language);

            $url = $this->generateUrl('app_homepage');
            return $this->redirect($url);

        }

        return $this->render('AppBundle:Language:change_language.html.twig',  array(
                   'languages' => $languages,
                   'defaultLanguage' => $defaultLanguage)
                );
    }
}
</code>```

app/config/services.xml

  app.eventListeners.locale_listener:
      class: AppBundle\EventListener\LocaleListener
      arguments: ["%kernel.default_locale%"]
      tags:
          - { name: kernel.event_subscriber }
```

答:
Following Fracsi's answer :

DefaultController :

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;

    /**
     * Class DefaultController.
     */
    class DefaultController extends AbstractController
    {

        /**
         * @Route("/", name="app_homepage")
         *
         * @param Request $request
         *
         * @return \Symfony\Component\HttpFoundation\Response
         */
        public function indexAction(Request $request)
        {
            $locale     = $request->getLocale();
            // locale = "gb" (after click on the flag and redirect)

            $translator = $this->get('translator');

            var_dump($translator->getLocale()); // fr

            $this->get('translator')->setLocale('gb');

            var_dump($this->get('translator')->getLocale()); // display "gb"
            var_dump($translator->trans('menu.home')); // display translation in french...

        }
```

Title: Symfony : sticky locale doesnt work

Body:
I'm trying to follow the "Making the Locale "Sticky" during a User's Session" Symfony tutorial but, I've got an error and I don't know why...

When I click on a flag to change language, the new language is set in session and, after the redirect, I've got the selected language in "$request->getLocale()" BUT not in the translator... Do you have an idea of the problem ? Thank very much !

Edit : I just want use locale by session

LocaleListener.php

<?php
// src/AppBundle/EventListener/LocaleListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'fr')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // Si aucune locale n'a été fixée explicitement dans la requête, on utilise celle de la session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered after the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

change_language.html.twig (to change the language)

key

LanguageController.php

<?php

namespace AppBundle\Controller;

use AppBundle\Form\Model\Language\Language;
use AppBundle\Form\Type\LanguageType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class LanguageController.
 */
class LanguageController extends AbstractController
{
    /**
     * @Route("/changelanguage/{language}", name="app_change_language", options={"expose"=true})
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function setLanguageAction(Request $request, $language = null)
    {

        $defaultLanguage = $request->getLocale();

        // pour test
        $languages = [
            'fr' => 'French',
            'gb' => 'English',
            'es' => 'Spanish',

        ];

        if(isset($language))
        {

            $this->get('session')->set("_locale", $language);

            $url = $this->generateUrl('app_homepage');
            return $this->redirect($url);

        }

        return $this->render('AppBundle:Language:change_language.html.twig',  array(
                   'languages' => $languages,
                   'defaultLanguage' => $defaultLanguage)
                );
    }
}

app/config/services.xml

  app.eventListeners.locale_listener:
      class: AppBundle\EventListener\LocaleListener
      arguments: ["%kernel.default_locale%"]
      tags:
          - { name: kernel.event_subscriber }


问:
How to deploy my Dynamic web project on internet
I am working in my final year project and I created a web service in a dynamic web project using eclipse JEE, tomcat 8.5 and Axis 2 ( all this is running in Ubuntu 16). this web servicie calls some programs that are installed on a computer ( Matlab for instance) so I need this computer to host the Web Service. This web service works fine in local host ( I created a client  to check it) now I need to do the next step. how can I deploy this web service on internet? ( NO localhost), There is any tutorial or documentation to do something like this? The computer where I am working is of my university so it is connected to the university network.

I have read that I need a WAR file, I know that if  I right click my project and the select export it says "WAR file", this  war is going to have all the references and .jar that I added ? ( I am afraid of this because I neeeded to add some .jar and also some native library locations to them) Also I know that I need to have a Statc IP instead of a dynamic one. how can I achieve it if I have no access to the university routers?

Thanks for your help.

答:
If you want your own domain, then you will have to buy a domain if you want to be on internet. There are website like GoDaddy or BigRock, that provide domains.

If you are doing it for testing or demonstration purpose, you can use NGROK tool. This tool will provide a domain over internet (something like http://.ngrok.io), that will be mapped to your localhost. The domain can be customized if you are using paid version.

```<code>ngrok.exe http 8080
</code>```

OR

```<code>ngrok.exe start -config="config.yml" config-name
</code>```

config.yml

```<code>http_proxy: ""
log: ngrok.log
tunnels:
  config-name:
    proto: http
    addr: 8080
</code>```

Body:
If you want your own domain, then you will have to buy a domain if you want to be on internet. There are website like GoDaddy or BigRock, that provide domains.

If you are doing it for testing or demonstration purpose, you can use NGROK tool. This tool will provide a domain over internet (something like http://.ngrok.io), that will be mapped to your localhost. The domain can be customized if you are using paid version.

ngrok.exe http 8080

OR

ngrok.exe start -config="config.yml" config-name

config.yml

http_proxy: ""
log: ngrok.log
tunnels:
  config-name:
    proto: http
    addr: 8080


问:
RC Car through PARALLEL PORT
I'am making project, in which i'am controlling a remote control car from PC using parallel port...
I want to know whether there is any library or code in C# which could help me in resolving this problem using window form application.....
I'am using transistor for this propose</p>

答:
There are a few resources out there for controlling ports with .net code:

Here's a great article on codeproject: I/O Ports Uncensored - 1 - Controlling LEDs (Light Emiting Diodes) with Parallel Port

And here's a good place to find lots of info (and inpout32.dll as well): http://www.lvr.com/parport.htm

Title: RC Car through PARALLEL PORT


问:
How to pass parameter to command
I have Xamarin Forms solution and on one page there is list with images. When image is clicked, I would like to trigger procedure witch has image path as parameter. In xaml I define image with:

```<code><Image Source="{Binding ImagePath}"
        WidthRequest="30" HeightRequest="30"
        HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" >
  <Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding ImagePath}" />
  </Image.GestureRecognizers>
</Image>
</code>```

and TapImageCommand is defined in view model's constructor as:

TapImageCommand = new Command<string>(ImagePath =>
{
    OnImageTapped(ImagePath);
});
```

<p>and TapImageCommand is defined with:</p>

<pre class="lang-cs prettyprint-override"><code>public ICommand TapImageCommand { get; set; }
</code>```

Problem is OnImageTapped is never triggered. What am I doing wrong?

答:
The problem here is that you think you are binding the ImagePath of the object behind the list, but you are not. Look at the Command you are binding, this is part of the PageModel, not the object in the list, so neither is the CommandParameter.

Therefore, ImagePath is probably null, and it does not match the signature you have for the Command which expects a string.

In this particular case it is probably easiest to supply the whole object as a parameter and get out the property yourself. I will assume the object in the list is of type Foo, then edit your code like underneath.

In your view, edit the TapGestureRecognizer to this:

TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding .}" />

The dot points to itself, in this case the specific instance of Foo in your list. Then edit the Command like this:

```<code>TapImageCommand = new Command<Foo>(fooObject =>
{
    OnImageTapped(fooObject);
});
</code>```

Now in your OnImageTapped method you can extract the ImagePath property.

Title: How to pass parameter to command

Body:
I have Xamarin Forms solution and on one page there is list with images. When image is clicked, I would like to trigger procedure witch has image path as parameter. In xaml I define image with:

<Image Source="{Binding ImagePath}"
        WidthRequest="30" HeightRequest="30"
        HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" >
  <Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding ImagePath}" />
  </Image.GestureRecognizers>
</Image>

and TapImageCommand is defined in view model's constructor as:

TapImageCommand = new Command<string>(ImagePath =>
{
    OnImageTapped(ImagePath);
});

and TapImageCommand is defined with:

public ICommand TapImageCommand { get; set; }

Problem is OnImageTapped is never triggered. What am I doing wrong?

Body:
The problem here is that you think you are binding the ImagePath of the object behind the list, but you are not. Look at the Command you are binding, this is part of the PageModel, not the object in the list, so neither is the CommandParameter.

Therefore, ImagePath is probably null, and it does not match the signature you have for the Command which expects a string.

In this particular case it is probably easiest to supply the whole object as a parameter and get out the property yourself. I will assume the object in the list is of type Foo, then edit your code like underneath.

In your view, edit the TapGestureRecognizer to this:

TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding .}" />

The dot points to itself, in this case the specific instance of Foo in your list. Then edit the Command like this:

TapImageCommand = new Command<Foo>(fooObject =>
{
    OnImageTapped(fooObject);
});

Now in your OnImageTapped method you can extract the ImagePath property.


问:
How to get text from TextViews which are created dynamically in android?
I do not know the number. of textview which should be created at runtime. List of Textviews are getting from server. I am creating textviews using below function. Since i am new to android i unable to get text from all textviews. Please suggest me the solution

private void textview(String text)
 {

```<code>    TextView txt_view= new TextView(this);

    txt_view.setText(text);

    linearLayout.addView(txt_view);

}
</code>```

Please suggest me the solution i m stuck in getting the text from many textview

Above image is my form, what i want to get text from all views which are created dynamically and store to firebase

答:
add your TextView to HashMap with a unique key
and match your key and get value from map, it will surely help you. after that at time of fetching data use for loop and get data using that unique key

Body:
I do not know the number. of textview which should be created at runtime. List of Textviews are getting from server. I am creating textviews using below function. Since i am new to android i unable to get text from all textviews. Please suggest me the solution

private void textview(String text)
 {

    TextView txt_view= new TextView(this);

    txt_view.setText(text);

    linearLayout.addView(txt_view);

}

Please suggest me the solution i m stuck in getting the text from many textview

Above image is my form, what i want to get text from all views which are created dynamically and store to firebase