问:
Jquery process append values from ajax
so I've read about callback and asynchronous behaviour of ajax but I can't figure out how to create an event from appended values from ajax.

I've got this html :

var searchRequest = null;
$(function() {
  $(':input[type="submit"]').prop('disabled', true);
  var minlength = 5;
  $("#cp").keyup(function() {
    var that = this,
      value = $(this).val().trim();;
    value = value.replace(/\s/g, '');

    if (value.length == minlength) {
      if (searchRequest != null)
        searchRequest.abort();
      searchRequest = $.ajax({
        type: "POST",
        url: "post_job_ville.php",
        data: {
          'searchterm': value
        },
        dataType: "text",
        success: function(msg) {
          $("#ville").append(msg);
        }
      });
    }
  });
});

// Code to remove the disabled state of submit button
if ($('#ville').val()) {
  $(':input[type="submit"]').prop('disabled', false);
  $(':input[type="submit"]').toggleClass('btn-custom btn-primary');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <input name="cp" id="cp" class="form-control">
</div>
<div class="form-group">
  <select class="form-control" id="ville">
 <option selected="selected" value="">Select a value</option>
 </select>
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" value="Submit"></code>```

My ajax call is working fine. When someone type 5 caracters in the input field (#cp) it triggers the ajax call and append

```<code> <option value="x">...</option>
</code>```

to the select menu (#ville).

Problem is, I'd like to Jquery to remove the disable state of the submit button if an ajax called option with a value is selected. So i wrote the code at the end of the JS but since ajax is async it can't work like that. I tried to put the code in the success part of the ajax call but it didn't work.

If someone has an idea on how to proceed I'd really appreciate.

Thank you !

答:
You can try to place an event on your select like this:

```<code>$('#ville').on('change', function(e) {
  if (e.target.value) {
    $(':input[type="submit"]').prop('disabled', false);
    /* other stuffs... */
  } else {
    $(':input[type="submit"]').prop('disabled', true);
    /* other stuffs... */
  }
})
</code>```

The "on()" method from Jquery Selector allow you to place an event of your choice on the selected element.
Here we place the 'change' event to call back a function when the input value 'change'.
You just need to check if your selected value is not empty (like the first entry of your select) and it's done.

or something like that:

```<code>$('#ville').on('change', function(e) {
  const value = e.target.value
  $(':input[type="submit"]').prop('disabled', !value);
  /* other stuffs... */
})
</code>```

Title: Jquery process append values from ajax

Body:
so I've read about callback and asynchronous behaviour of ajax but I can't figure out how to create an event from appended values from ajax.

I've got this html :

var searchRequest = null;
$(function() {
  $(':input[type="submit"]').prop('disabled', true);
  var minlength = 5;
  $("#cp").keyup(function() {
    var that = this,
      value = $(this).val().trim();;
    value = value.replace(/\s/g, '');

    if (value.length == minlength) {
      if (searchRequest != null)
        searchRequest.abort();
      searchRequest = $.ajax({
        type: "POST",
        url: "post_job_ville.php",
        data: {
          'searchterm': value
        },
        dataType: "text",
        success: function(msg) {
          $("#ville").append(msg);
        }
      });
    }
  });
});

// Code to remove the disabled state of submit button
if ($('#ville').val()) {
  $(':input[type="submit"]').prop('disabled', false);
  $(':input[type="submit"]').toggleClass('btn-custom btn-primary');
}

  <input name="cp" id="cp" class="form-control">

  <select class="form-control" id="ville">
 <option selected="selected" value="">Select a value</option>
 </select>

<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" value="Submit">

My ajax call is working fine. When someone type 5 caracters in the input field (#cp) it triggers the ajax call and append

 <option value="x">...</option>

to the select menu (#ville).

Problem is, I'd like to Jquery to remove the disable state of the submit button if an ajax called option with a value is selected. So i wrote the code at the end of the JS but since ajax is async it can't work like that. I tried to put the code in the success part of the ajax call but it didn't work.

If someone has an idea on how to proceed I'd really appreciate.

Thank you !

Body:
You can try to place an event on your select like this:

$('#ville').on('change', function(e) {
  if (e.target.value) {
    $(':input[type="submit"]').prop('disabled', false);
    /* other stuffs... */
  } else {
    $(':input[type="submit"]').prop('disabled', true);
    /* other stuffs... */
  }
})

The "on()" method from Jquery Selector allow you to place an event of your choice on the selected element.
Here we place the 'change' event to call back a function when the input value 'change'.
You just need to check if your selected value is not empty (like the first entry of your select) and it's done.

or something like that:

$('#ville').on('change', function(e) {
  const value = e.target.value
  $(':input[type="submit"]').prop('disabled', !value);
  /* other stuffs... */
})


来源: stackexchange

问:
App.Config Custom configuration section problem
I've created a custom config section for my application. For some reason Visual Studio 2010 isn't picking up and of my custom properties. I'm getting warnings similar to this for all the "add" keys:

```<code>Could not find schema information for the element 'urlFilterSection'
</code>```

CONFIG FILE:

```<code><configSections>
    <section name="urlFilterSection" type="BotFinderApp.Models.UrlFilterSection, BotFinder" />
</configSections>

<urlFilterSection>
    <urlFilterCollection>
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
    </urlFilterCollection>
</urlFilterSection>
</code>```

UrlFilterSection:

```<code>namespace BotFinderApp.Models
{
    public class UrlFilterSection : ConfigurationSection
    {
        public UrlFilterSection()
        {
        }

        [ConfigurationProperty("urlFilterCollection", IsDefaultCollection = false)]
        [ConfigurationCollection(typeof(UrlFilterCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
        public UrlFilterCollection Urls
        {
            get
            {
                var urlsCollection = (UrlFilterCollection)base["urlFilterCollection"];
                return urlsCollection;
            }
        }
    }
}
</code>```

UrlFilterCollection

```<code>namespace BotFinderApp.Models
{
    public class UrlFilterCollection : ConfigurationElementCollection
    {
        public UrlFilterCollection()
        {
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new UrlFilter();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((UrlFilter)element).Url;
        }
    }
}
</code>```

UrlFilter

```<code>namespace BotFinderApp.Models
{
    public class UrlFilter : ConfigurationElement
    {
        public UrlFilter()
        {
        }

        [ConfigurationProperty("url", DefaultValue = "", IsRequired = true)]
        public string Url
        {
            get { return (string)this["url"]; }
            set { this["url"] = value; }
        }

        [ConfigurationProperty("numberOfIpsToExtract", DefaultValue = "0", IsRequired = true)]
        public int NumberOfIpsToExtract
        {
            get { return (int)this["numberOfIpsToExtract"]; }
            set { this["numberOfIpsToExtract"] = value; }
        }
    }
}
</code>```

答:
Found the problem:

Decyclone was correct, errors were in fact just compile time warnings.

The real problem was I was accessing my configuration like this:

```<code>UrlFilterCollection serviceConfigSection = ConfigurationManager.GetSection("urlFilterSection") as UrlFilterCollection;
</code>```

when it should have been like this

```<code>UrlFilterSection serviceConfigSection = ConfigurationManager.GetSection("urlFilterSection") as UrlFilterSection;
</code>```

Thank you FlipScript and Decyclone :)

UPDATE:

I found out how to remove the compile time warnings - I'm using Visual Studio 2010. After creating my custom configuration section/s I used the "Create Schema" button from the toolbar which generates the schema file for the config. I then saved this to my project and the warnings disappeared.

ContentLicense: CC BY-SA 2.5

Body:
I've created a custom config section for my application. For some reason Visual Studio 2010 isn't picking up and of my custom properties. I'm getting warnings similar to this for all the "add" keys:

Could not find schema information for the element 'urlFilterSection'

CONFIG FILE:

<configSections>

</configSections>

<urlFilterSection>
    <urlFilterCollection>
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
        <add url="urlhere.com.au" numberOfIpsToExtract="10" />
    </urlFilterCollection>
</urlFilterSection>

UrlFilterSection:

namespace BotFinderApp.Models
{
    public class UrlFilterSection : ConfigurationSection
    {
        public UrlFilterSection()
        {
        }

        [ConfigurationProperty("urlFilterCollection", IsDefaultCollection = false)]
        [ConfigurationCollection(typeof(UrlFilterCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
        public UrlFilterCollection Urls
        {
            get
            {
                var urlsCollection = (UrlFilterCollection)base["urlFilterCollection"];
                return urlsCollection;
            }
        }
    }
}

UrlFilterCollection

namespace BotFinderApp.Models
{
    public class UrlFilterCollection : ConfigurationElementCollection
    {
        public UrlFilterCollection()
        {
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new UrlFilter();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((UrlFilter)element).Url;
        }
    }
}

UrlFilter

namespace BotFinderApp.Models
{
    public class UrlFilter : ConfigurationElement
    {
        public UrlFilter()
        {
        }

        [ConfigurationProperty("url", DefaultValue = "", IsRequired = true)]
        public string Url
        {
            get { return (string)this["url"]; }
            set { this["url"] = value; }
        }

        [ConfigurationProperty("numberOfIpsToExtract", DefaultValue = "0", IsRequired = true)]
        public int NumberOfIpsToExtract
        {
            get { return (int)this["numberOfIpsToExtract"]; }
            set { this["numberOfIpsToExtract"] = value; }
        }
    }
}

Body:
Found the problem:

Decyclone was correct, errors were in fact just compile time warnings.

The real problem was I was accessing my configuration like this:

UrlFilterCollection serviceConfigSection = ConfigurationManager.GetSection("urlFilterSection") as UrlFilterCollection;

when it should have been like this

UrlFilterSection serviceConfigSection = ConfigurationManager.GetSection("urlFilterSection") as UrlFilterSection;

Thank you FlipScript and Decyclone :)

UPDATE:

I found out how to remove the compile time warnings - I'm using Visual Studio 2010. After creating my custom configuration section/s I used the "Create Schema" button from the toolbar which generates the schema file for the config. I then saved this to my project and the warnings disappeared.


问:
Calling converted string from UIDataPicker date
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

```<code>@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }
</code>```

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

```<code>@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}
</code>```

}

please help, what should I write in

```<code>let date =
</code>```

and

```<code>= item.date
</code>```

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

答:
This is how I figured it out:</p>

```<code>func dateToString (date: NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.stringFromDate(date)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if saveButton === sender {
            let name = nameTextField.text ?? ""
            let date = dateToString (myDatePicker.date) ?? ""
            item = Item (name: name, date: date)
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Now I am learning Swift and making a typical ToDo app.
I found a function to convert date data from UIDatePicker to String, here is my ViewController chunk of code:

@IBAction func dateToString(sender: UIDatePicker) {
            var dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
            var strDate = dateFormatter.stringFromDate(myDatePicker.date)
            return ()
        }

But the problem is that I can not access the string results from this function, in my app
i have 2 labels in every tableViewCell, one simple label text data, and another is date data from date picker (also should be a string):

@IBOutlet weak var saveButton: UIBarButtonItem!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if saveButton === sender {
        let name = nameTextField.text ?? ""
        let date =
        item = Item (name: name, date: date)
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    if let item = item {
        nameTextField.text = item.name
                           = item.date

}

}

please help, what should I write in

let date =

and

= item.date

to define a date?
I've tried to call a function let date = dateToString; but it doesn't work for me.
Greatly appreciate any help here!

Body:
This is how I figured it out:

func dateToString (date: NSDate) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"
        return dateFormatter.stringFromDate(date)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if saveButton === sender {
            let name = nameTextField.text ?? ""
            let date = dateToString (myDatePicker.date) ?? ""
            item = Item (name: name, date: date)
        }


问:
String equality in generic class
What is the difference between == and Equals in generic class if T is a string.

I prepared sample code with 2 tests. TestMethod1 fails on 2nd assert, but TestMethod2 passes.

Source code:

```<code>[TestFixture]
public class Test
{
    class Foo<T> where T : class
    {
        public static bool Foo1(T item1, T item2)
        {
            return item1 == item2;
        }

        public static bool Foo2(T item1, T item2)
        {
            return item1.Equals(item2);
        }
    }

    [TestCase]
    public void TestMethod1()
    {
        var name = "str" + 1;
        // passes
        Assert.IsTrue(Foo<string>.Foo2(name, "str1"));
        // fails !
        Assert.IsTrue(Foo<string>.Foo1(name, "str1"));
    }

    [TestCase]
    public void TestMethod2()
    {
        // passes
        Assert.IsTrue(Foo<string>.Foo2("str1", "str1"));
        // also passes!
        Assert.IsTrue(Foo<string>.Foo1("str1", "str1"));
    }
}
</code>```

Related question:
c# compare two generic values

答:
As Matt has already mentioned, half of your problem is interning.

And the other half is that the compiler has no idea about your type parameter being string and treats it like just some reference type, hence it calls object's methods.

But don't take it on faith, let's take a look at IL.

ceq here tells us that there's no == operator overload, so reference check is performed on boxed arguments.

```<code>Foo`1.Foo1:
IL_0000:  nop
IL_0001:  ldarg.0
IL_0002:  box         Test+Foo<>.T
IL_0007:  ldarg.1
IL_0008:  box         Test+Foo<>.T
IL_000D:  ceq
IL_000F:  stloc.0
IL_0010:  br.s        IL_0012
IL_0012:  ldloc.0
IL_0013:  ret
</code>```

On the other hand, here we can see callvirt of System.Object.Equals and at runtime it will be resolved into a call of whatever implementation actual type parameter has, i.e. string.Equals.

```<code>Foo`1.Foo2:
IL_0000:  nop
IL_0001:  ldarg.0
IL_0002:  box         Test+Foo<>.T
IL_0007:  ldarg.1
IL_0008:  box         Test+Foo<>.T
IL_000D:  callvirt    System.Object.Equals
IL_0012:  stloc.0
IL_0013:  br.s        IL_0015
IL_0015:  ldloc.0
IL_0016:  ret
</code>```

Title: String equality in generic class

Body:
What is the difference between == and Equals in generic class if T is a string.

I prepared sample code with 2 tests. TestMethod1 fails on 2nd assert, but TestMethod2 passes.

Source code:

[TestFixture]
public class Test
{
    class Foo<T> where T : class
    {
        public static bool Foo1(T item1, T item2)
        {
            return item1 == item2;
        }

        public static bool Foo2(T item1, T item2)
        {
            return item1.Equals(item2);
        }
    }

    [TestCase]
    public void TestMethod1()
    {
        var name = "str" + 1;
        // passes
        Assert.IsTrue(Foo<string>.Foo2(name, "str1"));
        // fails !
        Assert.IsTrue(Foo<string>.Foo1(name, "str1"));
    }

    [TestCase]
    public void TestMethod2()
    {
        // passes
        Assert.IsTrue(Foo<string>.Foo2("str1", "str1"));
        // also passes!
        Assert.IsTrue(Foo<string>.Foo1("str1", "str1"));
    }
}

Related question:
c# compare two generic values

Body:
As Matt has already mentioned, half of your problem is interning.

And the other half is that the compiler has no idea about your type parameter being string and treats it like just some reference type, hence it calls object's methods.

But don't take it on faith, let's take a look at IL.

ceq here tells us that there's no == operator overload, so reference check is performed on boxed arguments.

Foo`1.Foo1:
IL_0000:  nop
IL_0001:  ldarg.0
IL_0002:  box         Test+Foo<>.T
IL_0007:  ldarg.1
IL_0008:  box         Test+Foo<>.T
IL_000D:  ceq
IL_000F:  stloc.0
IL_0010:  br.s        IL_0012
IL_0012:  ldloc.0
IL_0013:  ret

On the other hand, here we can see callvirt of System.Object.Equals and at runtime it will be resolved into a call of whatever implementation actual type parameter has, i.e. string.Equals.

Foo`1.Foo2:
IL_0000:  nop
IL_0001:  ldarg.0
IL_0002:  box         Test+Foo<>.T
IL_0007:  ldarg.1
IL_0008:  box         Test+Foo<>.T
IL_000D:  callvirt    System.Object.Equals
IL_0012:  stloc.0
IL_0013:  br.s        IL_0015
IL_0015:  ldloc.0
IL_0016:  ret


问:
PHP form submission with echo html post's empty array
I'm using php to dynamically create multiple buttons on my web page that have increasing values 01 to 09. When I create the forms as below the buttons are created as expected with the correct values but when I submit the form an empty array is posted.

The code here is inside a for loop that increments $i:

echo '<form action="test.php" method="post">';
echo '<input type="hidden" name="RunSmokeTest" value="0'.$i.'">';
echo '<input type="submit" name="submit" value="Run Test">';
echo '</form>';```
</div>
</div>
</p>

<p>Here is the HTML that is created:</p>

<p><img src="https://i.stack.imgur.com/hFQlA.png" alt="enter image description here"></p>

<p>However, when I change the code to take out the $i variable, the form will be submitted as expected but all the buttons will have the same value which I can't have.</p>

<p>Here is the start of test.php that prints out array(0) { } when I click the submit button and an alert comes up with message 'empty'.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>var_dump($_POST);

if(empty($_POST['RunSmokeTest']))
{
  echo '<script language="javascript">';
  echo 'alert("empty")';
  echo '</script>';
}
else{
  ...
}</code>```

答:
Try this .

```<code><?php
if(isset($_POST['submit'])) {
    echo $_POST['RunSmokeTest'];
}
for ($i=0; $i < 10; $i++) {
    echo '<form action="test.php" method="post">';
    echo '<input type="hidden" name="RunSmokeTest" value="0'.$i.'">';
    echo '<input type="submit" name="submit" value="Run Test">';
    echo '</form>';
}
?>
</code>```

Demo is here

Body:
I'm using php to dynamically create multiple buttons on my web page that have increasing values 01 to 09. When I create the forms as below the buttons are created as expected with the correct values but when I submit the form an empty array is posted.

The code here is inside a for loop that increments $i:

echo '<form action="test.php" method="post">';
echo '<input type="hidden" name="RunSmokeTest" value="0'.$i.'">';
echo '<input type="submit" name="submit" value="Run Test">';
echo '</form>';

Here is the HTML that is created:

However, when I change the code to take out the $i variable, the form will be submitted as expected but all the buttons will have the same value which I can't have.

Here is the start of test.php that prints out array(0) { } when I click the submit button and an alert comes up with message 'empty'.

var_dump($_POST);

if(empty($_POST['RunSmokeTest']))
{
  echo '';
}
else{
  ...
}

Body:
Try this .

<?php
if(isset($_POST['submit'])) {
    echo $_POST['RunSmokeTest'];
}
for ($i=0; $i < 10; $i++) {
    echo '<form action="test.php" method="post">';
    echo '<input type="hidden" name="RunSmokeTest" value="0'.$i.'">';
    echo '<input type="submit" name="submit" value="Run Test">';
    echo '</form>';
}
?>

Demo is here


问:
Browser navigation issue in selenium webdriver
I have started learning selenium WebDriver recently. I was trying to automate a simple task of launching a browser and  logging into an account using Firefox browser.

The difference I noticed is when I opened the browser manually and click on login link from homepage, a small pop-up window is opened to accept login credentials. I captured the elements (i.e username, password and login) using Firebug and completed my script(using Java).

But when I ran the same script, after a click on login link from home page,browser navigated to new page(instead of pop up window on same page which opened during manual process) to accept login credentials (whose web elements(i.e username, password and login)values are completely different than one captured during manual process). Which finally leads to 'NoSuchElementException'.

Any reason why we see the difference while launching browser through selenium? And also how to handle these scenarios in live environment?

Any help will be appreciated.

Thanks,
Sri.

答:
If I understand correctly, you are saying that there are 2 different types of "Login" page and the script you wrote only works for one of them.

So what you need to do now is to write an if condition to check which login page type is detected and then perform the authentication accordingly.


问:
CASE Statement to select a particular value if value exists in another table
I have a requirement where I need to order the records in the result set cursor returned by a stored procedure in a particular order. For example, assume that the SP returned 10 records.The result contains a field named FLD1. The records whose FLD1 value is present in another table must be placed at the top of the result set. That is the records whose FLD1 value returns results when used in a query like SELECT * FROM RESULTS WHERE FLD1 IN (SELECT FLD2 FROM TABLE2) must be placed at the top of the result set and the records which do not return any records must come afterward.

The approach I am following is to first select the records which satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign a seq.no 1 and store the results in a temp table. Then select the records which do not satisfy the condition FLD1 IN (SELECT FLD2 FROM TABLE2) and assign them a sequence 2. Finally, merge the results and open a result cursor at the end of the SP ordering by the Sequence number.

Please suggest any better approach if you know of one. I was thinking of using a CASE statement like CASE WHEN FLD1 IN (SELECT FLD2 FROM TABLE2) THEN "1" ELSE "2". But this does not seem to work in DB2.

答:
simply like this :</p>

```<code>select case when t2.fld2 is not null then 1 else 2 end as seq, t1.*
from table1 t1
left outer join table2 t2 on t1.fld1=t2.fld2
order by 1
</code>```

Body:
simply like this :

select case when t2.fld2 is not null then 1 else 2 end as seq, t1.*
from table1 t1
left outer join table2 t2 on t1.fld1=t2.fld2
order by 1


问:
Route an event into sibling control in WPF
I have a TextBox control for search, and a TreeView control below it. What I need is when I press the "Down Key ↓" while the focus on the search TextBox, I need to tell the TreeView "a Down Key has been pressed while the focus on you" ... I don't need to raise a KeyUp event on the TreeView or something, I need it to do the same action as if I pressed the Down Key while the focus on it!

Is this possible?

答:
Can you do something like following:</p>

```<code>private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    TreeView1.RaiseEvent(e);
}
</code>```

Body:
Can you do something like following:

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    TreeView1.RaiseEvent(e);
}


问:
Database name as variable in MySQL query
I am creating a MySQL dump file, that needs to run with multiple databases.
The structure is almost like this :

```<code>SET @parent_database = 'db_name';
CREATE OR REPLACE VIEW t_colours AS
   SELECT `key_name`, `value`
   FROM @parent_database. `colours` as COLOURS WHERE 1;
</code>```

When I run this query next time, my plan is to only change the variable parent_database.

Is this possible?

Everytime now I run this, I receive an error :

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '@parent_database.`colours` as COLOURS WHERE 1' at line 1

Any way to make this happen?

There are many more views to create.

答:
When you execute the queries the mysql thinks of table names as objects and not as string, and hence this would not work as you would expect.

However, there is a way  out and you could use something similar to below snippet.

```<code>SET @parent_database = 'db_name';
SET @q = CONCAT('CREATE OR REPLACE VIEW t_colours AS SELECT `key_name`,`value` FROM', @parent_database, '.`colours` as COLOURS WHERE 1;');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a MySQL dump file, that needs to run with multiple databases.
The structure is almost like this :

SET @parent_database = 'db_name';
CREATE OR REPLACE VIEW t_colours AS
   SELECT `key_name`, `value`
   FROM @parent_database. `colours` as COLOURS WHERE 1;

When I run this query next time, my plan is to only change the variable parent_database.

Is this possible?

Everytime now I run this, I receive an error :

#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '@parent_database.`colours` as COLOURS WHERE 1' at line 1

Any way to make this happen?

There are many more views to create.

Body:
When you execute the queries the mysql thinks of table names as objects and not as string, and hence this would not work as you would expect.

However, there is a way  out and you could use something similar to below snippet.

SET @parent_database = 'db_name';
SET @q = CONCAT('CREATE OR REPLACE VIEW t_colours AS SELECT `key_name`,`value` FROM', @parent_database, '.`colours` as COLOURS WHERE 1;');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
Assign new value to var in loop
Don´t have access to var in loop. Why? thanks.

```<code>   var grupo = "A"
   for (a <- dataframe) {
        grupo = "B"
    }
    println(grupo) //Print A
</code>```

Edit!

dataframe filterP show like this:

```<code>|   CODIGO|LISTA|NUMERO|OPCION|NUMERO|OP|VALOR|
+---------+-----+------+------+------+--+-----+
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    2|
|110111001|    P|  0000|     A|  0000| 1|    3|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     B|  0000| 1|    2|
</code>```

Code:

```<code>var grupo = List(filterP.first()(3).toString())
   var grupo_tmp = grupo(0)
   println("first group:" + grupo(0))
   for (a <- filterP) {
       if(grupo_tmp != a(3).toString()){
         println(grupo_tmp + "|" + a(3).toString())
         grupo = a(3).toString() :: grupo
         grupo_tmp = a(3).toString()
       }
    }
    println(grupo_tmp)
    println("Grupos de lista "+grupo.length)
    for(i <- 0 to grupo.length-1){
      println("grupo: "+ grupo(i))
    }
</code>```

This print:

```<code>   first group:A
   A|B
   A
   Grupos de lista 1
   grupo: A
</code>```

I don`t see where is the problem..

答:
It definitely has access to var inside loop.

Maybe you have a separate variable inside a loop named grupo or

maybe you loop is not meeting the conditions at all, meaning dataframe is empty.

try printing a inside your loop to debug.

see the example,

```<code>scala> var grupo = "A"
grupo: String = A

scala> for (a <- Array("MUTATE-1", "MUTATE-2")) { grupo = a }

scala> grupo
res6: String = MUTATE-2
</code>```

Title: Assign new value to var in loop

Body:
Don´t have access to var in loop. Why? thanks.

   var grupo = "A"
   for (a <- dataframe) {
        grupo = "B"
    }
    println(grupo) //Print A

Edit!

dataframe filterP show like this:

|   CODIGO|LISTA|NUMERO|OPCION|NUMERO|OP|VALOR|
+---------+-----+------+------+------+--+-----+
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     A|  0000| 1|    2|
|110111001|    P|  0000|     A|  0000| 1|    3|
|110111001|    P|  0000|     A|  0000| 1|    1|
|110111001|    P|  0000|     B|  0000| 1|    2|

Code:

var grupo = List(filterP.first()(3).toString())
   var grupo_tmp = grupo(0)
   println("first group:" + grupo(0))
   for (a <- filterP) {
       if(grupo_tmp != a(3).toString()){
         println(grupo_tmp + "|" + a(3).toString())
         grupo = a(3).toString() :: grupo
         grupo_tmp = a(3).toString()
       }
    }
    println(grupo_tmp)
    println("Grupos de lista "+grupo.length)
    for(i <- 0 to grupo.length-1){
      println("grupo: "+ grupo(i))
    }

This print:

   first group:A
   A|B
   A
   Grupos de lista 1
   grupo: A

I don`t see where is the problem..

Body:
It definitely has access to var inside loop.

Maybe you have a separate variable inside a loop named grupo or

maybe you loop is not meeting the conditions at all, meaning dataframe is empty.

try printing a inside your loop to debug.

see the example,

scala> var grupo = "A"
grupo: String = A

scala> for (a <- Array("MUTATE-1", "MUTATE-2")) { grupo = a }

scala> grupo
res6: String = MUTATE-2


问:
debugging compiled .net application
1- i designed application which has two interfaces (english, arabic), the user can choose the UI language at runtime, and the change will be seen after application restarted. i store the selected langauge in app.config.

2- from the form constructor i change the CurrentUICulture to the selected lang by this code:

```<code>Public.ArabicView = UmAlQuraCalender.Properties.Settings.Default.ArabicView;

if (Public.ArabicView == true)
   System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-SA");
else
   System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
</code>```

3- the application work without problem in my development machine.

4- when i test the application in another machine, only one user interface is working (english), if i check the other language and restart the application nothing happen the interface remain english although the arabic local is installed.

i use two radio button: one for arabic and the other for english, and inside the click event i change CurrentUICulture to the selected language inside this code:

```<code>private void rbArabic_Click(object sender, EventArgs e)
{
    Public.ArabicView = rbArabic.Checked;

    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-SA");

    UmAlQuraCalender.Properties.Settings.Default.ArabicView = Public.ArabicView;
    UmAlQuraCalender.Properties.Settings.Default.Save();

    MessageBox.Show("UI Language will be changed after application resart");

}

private void rbEnglish_Click(object sender, EventArgs e)
{
    Public.ArabicView = rbArabic.Checked;
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
    UmAlQuraCalender.Properties.Settings.Default.ArabicView = Public.ArabicView;
    UmAlQuraCalender.Properties.Settings.Default.Save();

    MessageBox.Show("UI Language will be changed after application resart");
}
</code>```

5- also how i can debug (trace the source code) in the test machine to figure out the problem?

if any one can help me i will be thankful.

答:
thanks my friend for your help

i installed VS in the test machine and i discovered that i forget to include the localized DLL which VS Created in the debug directory.

when i included this directory which has the localized DLL for arabic language the problem was solved.

thanks for the every one reply to my question

Title: debugging compiled .net application

Body:
1- i designed application which has two interfaces (english, arabic), the user can choose the UI language at runtime, and the change will be seen after application restarted. i store the selected langauge in app.config.

2- from the form constructor i change the CurrentUICulture to the selected lang by this code:

Public.ArabicView = UmAlQuraCalender.Properties.Settings.Default.ArabicView;

if (Public.ArabicView == true)
   System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-SA");
else
   System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

3- the application work without problem in my development machine.

4- when i test the application in another machine, only one user interface is working (english), if i check the other language and restart the application nothing happen the interface remain english although the arabic local is installed.

i use two radio button: one for arabic and the other for english, and inside the click event i change CurrentUICulture to the selected language inside this code:

private void rbArabic_Click(object sender, EventArgs e)
{
    Public.ArabicView = rbArabic.Checked;

    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-SA");

    UmAlQuraCalender.Properties.Settings.Default.ArabicView = Public.ArabicView;
    UmAlQuraCalender.Properties.Settings.Default.Save();

    MessageBox.Show("UI Language will be changed after application resart");

}

private void rbEnglish_Click(object sender, EventArgs e)
{
    Public.ArabicView = rbArabic.Checked;
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
    UmAlQuraCalender.Properties.Settings.Default.ArabicView = Public.ArabicView;
    UmAlQuraCalender.Properties.Settings.Default.Save();

    MessageBox.Show("UI Language will be changed after application resart");
}

5- also how i can debug (trace the source code) in the test machine to figure out the problem?

if any one can help me i will be thankful.


问:
Open file with its default program via python
I need to implement the user guide of my program and I was thinking on putting a button that opens the pdf, like if its double clicked on Windows Explorer.
But I've tried with os.popen(myfile) and open(myfile) and the interpreter open it in python, so I can print and it prints me the info of the object <_io.TextIOWrapper name='userguide.pdf' mode='r' encoding'cp1252' and what I need is to open it with its native application to avoid embed the pdf into the program.
Any way to do this?
Thanks

答:
To open it in the default application for that file type:
subprocess.Popen([file],shell=True)

Considering that you are implementing a user guide, you may want to open it in a web browser.

import webbrowser
webbrowser.open_new(r'file://C:\path\to\file.pdf')


问:
Launching Google Maps Directions via an intent on Android
My app needs to show Google Maps directions from A to B, but I don't want to put the Google Maps into my application - instead, I want to launch it using an Intent. Is this possible? If yes, how?</p>

答:
Using the latest cross-platform Google Maps URLs:
Even if google maps app is missing it will open in browser

Example https://www.google.com/maps/dir/?api=1&origin=81.23444,67.0000&destination=80.252059,13.060604

```<code>Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.google.com")
    .appendPath("maps")
    .appendPath("dir")
    .appendPath("")
    .appendQueryParameter("api", "1")
    .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
</code>```

Body:
Using the latest cross-platform Google Maps URLs:
Even if google maps app is missing it will open in browser

Example https://www.google.com/maps/dir/?api=1&origin=81.23444,67.0000&destination=80.252059,13.060604

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.google.com")
    .appendPath("maps")
    .appendPath("dir")
    .appendPath("")
    .appendQueryParameter("api", "1")
    .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);


问:
How to open/run YML compose file?
How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how.</p>

答:
If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux.
If your question is about running the compose yaml file, then run this command from the directory where compose file is residing:

```<code>docker-compose -f {compose file name} up
</code>```

You can avoid -f if your filename is docker-compose.yml

Title: How to open/run YML compose file?

Body:
If you are asking how to open YAML files, then you can use some common editors like NotePad++ in windows or vim in linux.
If your question is about running the compose yaml file, then run this command from the directory where compose file is residing:

docker-compose -f {compose file name} up

You can avoid -f if your filename is docker-compose.yml


问:
Dictionary and object to web service content type string
I have Dictionary with values how to convert them to string of format  application/json and application/x-www-form-urlencoded simplest standard  way:

```<code>    var values = new Dictionary<string, string>
    {
        {"id", "1"},
        {"amount", "5"}
    };
</code>```

The same question regarding class object with the same fields:

```<code>class values
{
    public String id  { get; set; }
    public string amount { get; set; }

}
</code>```

答:
simple way is using json.NET library in order to post the data. you can convert your object to application/json like this:

```<code>var jsonString = JsonConvert.SerializeObject(values);
</code>```

then post it to your service like this:

```<code>private static T Call<T>(string url, string body)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = 60 * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "POST";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
        responseString = reader.ReadToEnd();

    return JsonConvert.DeserializeObject<T>(responseString);
}
</code>```

Body:
I have Dictionary with values how to convert them to string of format  application/json and application/x-www-form-urlencoded simplest standard  way:

    var values = new Dictionary<string, string>
    {
        {"id", "1"},
        {"amount", "5"}
    };

The same question regarding class object with the same fields:

class values
{
    public String id  { get; set; }
    public string amount { get; set; }

}

Body:
simple way is using json.NET library in order to post the data. you can convert your object to application/json like this:

var jsonString = JsonConvert.SerializeObject(values);

then post it to your service like this:

private static T Call<T>(string url, string body)
{
    var contentBytes = Encoding.UTF8.GetBytes(body);
    var request = (HttpWebRequest)WebRequest.Create(url);

    request.Timeout = 60 * 1000;
    request.ContentLength = contentBytes.Length;
    request.Method = "POST";
    request.ContentType = @"application/json";

    using (var requestWritter = request.GetRequestStream())
        requestWritter.Write(contentBytes, 0, (int)request.ContentLength);

    var responseString = string.Empty;
    var webResponse = (HttpWebResponse)request.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
        responseString = reader.ReadToEnd();

    return JsonConvert.DeserializeObject<T>(responseString);
}


问:
How print dialog box selected printer to printing process
I am trying to print PDF file using Process

```<code>PrintDialog pdf = new PrintDialog();
if (pdf.ShowDialog() == DialogResult.OK)
{
  pdf.AllowSelection = true;
  pdf.AllowSomePages = true;
  ProcessStartInfo info = new ProcessStartInfo();
  info.Arguments = pdf.PrinterSettings.PrinterName;
  info.CreateNoWindow = true;
  info.Verb = "print";
  info.FileName = filename;
  //info.WindowStyle = ProcessWindowStyle.Hidden;
  try
  {
    Process p = new Process();
    p.StartInfo = info;
    p.EnableRaisingEvents = true; //Important line of code
    //p.PriorityBoostEnabled = true;
    p.Start();
    p.WaitForExit();
    p.Close();
  }
  catch (Exception ex){}
}
else
{
  MessageBox.Show("Print Canceled");
}
}
catch (Exception ex){}
</code>```

But this code not take user selected printer for print process. It print pdf by default printer.
what would be the fault?
Thanks.

答:
@RiksonTool,

Your code is printing to pdf by default printer as it is reading the settings from control panel of windows.
This is not a fault, it is a manifestation of the default settings in windows.

Hope it helps

Body:
I am trying to print PDF file using Process

PrintDialog pdf = new PrintDialog();
if (pdf.ShowDialog() == DialogResult.OK)
{
  pdf.AllowSelection = true;
  pdf.AllowSomePages = true;
  ProcessStartInfo info = new ProcessStartInfo();
  info.Arguments = pdf.PrinterSettings.PrinterName;
  info.CreateNoWindow = true;
  info.Verb = "print";
  info.FileName = filename;
  //info.WindowStyle = ProcessWindowStyle.Hidden;
  try
  {
    Process p = new Process();
    p.StartInfo = info;
    p.EnableRaisingEvents = true; //Important line of code
    //p.PriorityBoostEnabled = true;
    p.Start();
    p.WaitForExit();
    p.Close();
  }
  catch (Exception ex){}
}
else
{
  MessageBox.Show("Print Canceled");
}
}
catch (Exception ex){}

But this code not take user selected printer for print process. It print pdf by default printer.
what would be the fault?
Thanks.


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答: It encourages bad coding style, basically. See: Goto Considered Harmful [pdf]</p>

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

OwnerDisplayName: Alex Fort


问:
getline in C++ - Help needed
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

```<code>#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}
</code>```

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++

答:
You're trying to alternate between grabbing up until a \t and grabbing up until a \n. But the times that you find a '#' comment line throw off your alternation.

By far the easiest and most robust way to handle this sort of thing is to read each line first, and then re-parse the line.

Title: getline in C++ - Help needed

Body:
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++


问:
I want to get inner tag value for the md-autocomplete but I am not able to get text valu , Find code below
HTML:

```<code><md-virtual-repeat-container role="presentation" ng-class="{ 'md-not-found': $mdAutocompleteCtrl.notFoundVisible() }" class="md-autocomplete-suggestions-container md-whiteframe-z1 md-virtual-repeat-container md-orient-vertical ng-hide" ng-hide="$mdAutocompleteCtrl.hidden" ng-mouseup="$mdAutocompleteCtrl.mouseUp()" ng-mouseleave="$mdAutocompleteCtrl.listLeave()" ng-mouseenter="$mdAutocompleteCtrl.listEnter()" md-auto-shrink-min="1" md-auto-shrink="" aria-hidden="true" style="left: 676.483px; min-width: 270.717px; max-width: 941.2px; top: auto; bottom: -147.917px; max-height: 240px; height: 96px;">
<div class="md-virtual-repeat-scroller">
    <div class="md-virtual-repeat-sizer" style="height: 96px;"></div>
    <div class="md-virtual-repeat-offsetter">
        <ul id="ul-3" ng-class="::menuClass" class="md-autocomplete-suggestions">
            <!-- mdVirtualRepeat: item in $mdAutocompleteCtrl.matches -->
            <li md-extra-name="$mdAutocompleteCtrl.itemName" ng-click="$mdAutocompleteCtrl.select($index)" ng-class="{ selected: $index === $mdAutocompleteCtrl.index }" md-virtual-repeat="item in $mdAutocompleteCtrl.matches" class="ng-scope" role="button" tabindex="0">
                <!-- mdAutocompleteParentScope: -->
                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    <span md-highlight-text="searchText1" id="pincodeCity"><span class="highlight">110081</span>,Delhi</span>
                </md-autocomplete-parent-scope>
            </li>
            <li md-extra-name="$mdAutocompleteCtrl.itemName" ng-click="$mdAutocompleteCtrl.select($index)" ng-class="{ selected: $index === $mdAutocompleteCtrl.index }" md-virtual-repeat="item in $mdAutocompleteCtrl.matches" class="ng-scope" role="button" tabindex="0">
                <!-- mdAutocompleteParentScope: -->
                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    <span md-highlight-text="searchText1" id="pincodeCity"><span class="highlight">110081</span>,Nizampur</span>
                </md-autocomplete-parent-scope>
            </li>
            <!-- ngIf: $mdAutocompleteCtrl.notFoundVisible() -->
        </ul>
    </div>
</div>
</code>```

Protractor code:

```<code>let foo = $$('.md-autocomplete-suggestions').$$('.highlight');
    expect(foo.getText()).toEqual([',Delhi', ',Nizampur']);
</code>```

I have tried with above code, but it didn't work.

Is there any way I can find/Select text field in a span tag.

答:
Ok you have to put id at the span

es:

```<code> <span id="Spansearch" md-highlight-text="searchText1"><span class="highlight">110081</span>,Delhi</span>
</code>```

after whit this you can get all html with this

```<code>$( "#Spansearch" ).html();
</code>```

if you wont tu get only Nizampur

you can use this

```<code>$( "#Spansearch" ).html().split(",")[1];
</code>```

Body:
HTML:

<md-virtual-repeat-container role="presentation" ng-class="{ 'md-not-found': $mdAutocompleteCtrl.notFoundVisible() }" class="md-autocomplete-suggestions-container md-whiteframe-z1 md-virtual-repeat-container md-orient-vertical ng-hide" ng-hide="$mdAutocompleteCtrl.hidden" ng-mouseup="$mdAutocompleteCtrl.mouseUp()" ng-mouseleave="$mdAutocompleteCtrl.listLeave()" ng-mouseenter="$mdAutocompleteCtrl.listEnter()" md-auto-shrink-min="1" md-auto-shrink="" aria-hidden="true" style="left: 676.483px; min-width: 270.717px; max-width: 941.2px; top: auto; bottom: -147.917px; max-height: 240px; height: 96px;">

                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    110081,Delhi
                </md-autocomplete-parent-scope>

                <md-autocomplete-parent-scope md-autocomplete-replace="" class="ng-scope">
                    110081,Nizampur
                </md-autocomplete-parent-scope>

Protractor code:

let foo = $$('.md-autocomplete-suggestions').$$('.highlight');
    expect(foo.getText()).toEqual([',Delhi', ',Nizampur']);

I have tried with above code, but it didn't work.

Is there any way I can find/Select text field in a span tag.

Body:
Ok you have to put id at the span

es:

 <span id="Spansearch" md-highlight-text="searchText1"><span class="highlight">110081</span>,Delhi</span>

after whit this you can get all html with this

$( "#Spansearch" ).html();

if you wont tu get only Nizampur

you can use this

$( "#Spansearch" ).html().split(",")[1];


问:
headers.append simple syntax
I am trying to append multiple header values. what I am doing is

```<code> options.headers.append('Content-Type', 'application/json');
 options.headers.append('X-Requested-By', 'api-client');
 ... etc.,
</code>```

instead of mentioning each one separately, can we do something like

```<code>ley heads= {
 'Content-Type': 'application/json',
 'X-Requested-By': 'api-client',
 ... etc.,
}

options.headers.append(types);
</code>```

or any other methods availabe

答:
You can create this as part of RequestOptionsArgs</p>

```<code>let headers={};
let obj = new Headers(headers);
</code>```

Title: headers.append simple syntax

Body:
I am trying to append multiple header values. what I am doing is

 options.headers.append('Content-Type', 'application/json');
 options.headers.append('X-Requested-By', 'api-client');
 ... etc.,

instead of mentioning each one separately, can we do something like

ley heads= {
 'Content-Type': 'application/json',
 'X-Requested-By': 'api-client',
 ... etc.,
}

options.headers.append(types);

or any other methods availabe

Body:
You can create this as part of RequestOptionsArgs

let headers={};
let obj = new Headers(headers);


问:
How to solve this warning: failed to open stream: No such file or directory
Recently, I had a problem as:

```<code>Warning:include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269
</code>```

I used Xampp and codeigniter-3.

答:
Just copy error folders in your codeigniter application to codeigniter view folder.
It will correct error page path. And the warnings will removed.</p>

Body:
Recently, I had a problem as:

Warning:include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php): failed to open stream: No such file or directory in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

Warning: include(): Failed opening 'C:\xampp\htdocs\crackverbal\application\views\errors\html\error_php.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\crackverbal\system\core\Exceptions.php on line 269

I used Xampp and codeigniter-3.


问:
How to use radiobutton to count something eg if the first option shows list 1 if option 2 marked show list 2?
I have two RadioButtons in RadioGroup. What I want: if first RadioButton ischecked to display method one and second RadioButton ischecked to dispaly method two.
How to do it?

```<code>public void onRadioButtonClicked (View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {
        case R.id.radio_button_equal_payment_principal:
            if (checked) {
            "display method PaymentPrincipal"

            }
            break;
        case R.id.radio_button_equal_payment_total:
            if (checked) {
          "display method PaymentTotal"
            }
            break;
    }
    return ;
}
</code>```

答:
you can try following code:</p>

```<code>radioGroup = (RadioGroup) findViewById(R.id.radioSex);
     radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
             switch(checkedId){
                 case R.id.radio1:
                     // do operations specific to this selection
                     break;
                 case R.id.radio2:
                     // do operations specific to this selection
                     break;

             }
         }
     });
</code>```

Body:
I have two RadioButtons in RadioGroup. What I want: if first RadioButton ischecked to display method one and second RadioButton ischecked to dispaly method two.
How to do it?

public void onRadioButtonClicked (View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {
        case R.id.radio_button_equal_payment_principal:
            if (checked) {
            "display method PaymentPrincipal"

            }
            break;
        case R.id.radio_button_equal_payment_total:
            if (checked) {
          "display method PaymentTotal"
            }
            break;
    }
    return ;
}

Body:
you can try following code:

radioGroup = (RadioGroup) findViewById(R.id.radioSex);
     radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         @Override
         public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
             switch(checkedId){
                 case R.id.radio1:
                     // do operations specific to this selection
                     break;
                 case R.id.radio2:
                     // do operations specific to this selection
                     break;

             }
         }
     });


问:
datatables.min.js how to sort records
I am using datatables.min.js to display my listing in wordpress. I want to display records such that latest entries should be display first (ORDER BY ID DESC). My query is correct but for some reasons it is not displaying as per my query order by clause (ORDER BY id DESC). It is displaying the oldest records first. Anybody can help how to fix this issue ?</p>

答:
Try Below Solution :

```<code>$(document).ready(function() {
    $("#patientStoryLst").DataTable({
        "sPaginationType" : "full_numbers",
        "iDisplayLength " : 5,
        "bJQueryUI" : true,
        "sDom" : 'rt',
        "aoColumns": [{"bSortable": false }, null, null, null, null, null, null, null, null, null, null],
        "aaSorting": [[0, 'desc']]
    });
});
</code>```

Title: datatables.min.js how to sort records

Body:
Try Below Solution :

$(document).ready(function() {
    $("#patientStoryLst").DataTable({
        "sPaginationType" : "full_numbers",
        "iDisplayLength " : 5,
        "bJQueryUI" : true,
        "sDom" : 'rt',
        "aoColumns": [{"bSortable": false }, null, null, null, null, null, null, null, null, null, null],
        "aaSorting": [[0, 'desc']]
    });
});


问:
Where is the reference for options for writing or reading per format?
I use Spark 1.6.1.

We are trying to write an ORC file to HDFS using HiveContext and DataFrameWriter. While we can use

```<code>df.write().orc(<path>)
</code>```

we would rather do something like

```<code>df.write().options(Map("format" -> "orc", "path" -> "/some_path")
</code>```

This is so that we have the flexibility to change the format or root path depending on the application that uses this helper library. Where can we find a reference to the options that can be passed into the DataFrameWriter? I found nothing in the docs here

https://spark.apache.org/docs/1.6.0/api/java/org/apache/spark/sql/DataFrameWriter.html#options(java.util.Map)

答:
Where can we find a reference to the options that can be passed into the DataFrameWriter?

The most definitive and authoritative answer are the sources:

CSVOptions

JDBCOptions

JSONOptions

ParquetOptions

TextOptions

OrcOptions

...

Some description you may find in the docs, but there is no single page (that could possibly be auto-generated from the sources to stay up-to-date the most).

The reason being that the options are separated from the format implementation on purpose to have the flexibility you want to offer per use case (as you duly noted):

This is so that we have the flexibility to change the format or root path depending on the application that uses this helper library.

Your question seems similar to How to know the file formats supported by Databricks? where I said:

Where can I get the list of options supported for each file format?

That's not possible as there is no API to follow (like in Spark MLlib) to define options. Every format does this on its own...unfortunately and your best bet is to read the documentation or (more authoritative) the source code.

Body:
I use Spark 1.6.1.

We are trying to write an ORC file to HDFS using HiveContext and DataFrameWriter. While we can use

df.write().orc(<path>)

we would rather do something like

df.write().options(Map("format" -> "orc", "path" -> "/some_path")

This is so that we have the flexibility to change the format or root path depending on the application that uses this helper library. Where can we find a reference to the options that can be passed into the DataFrameWriter? I found nothing in the docs here

https://spark.apache.org/docs/1.6.0/api/java/org/apache/spark/sql/DataFrameWriter.html#options(java.util.Map)


问:
Customizing more in UITabBarController - "configure"
How to modify the UINavigationBarTintColor for "Configure" in "more" in UITabBarController?

I have 10 UINavigationController within a UITabBarController (everything using Interface builder. )

I can easily set the tint color of all UINavigationController's UINavigationBar using Interface builder.

Similarly I also found that we can modify the More's Tint color as follows.

```<code>tBarDashboard.moreNavigationController.navigationBar.tintColor=
[UIColor colorWithRed:30/255.0 green:103/255.0 blue:7/255.0 alpha:1.0];
// here tbarDashboard is my UITabBarController.
</code>```

But TabBarController default allows to configure the arrangement of navigation controllers if we have too many navigation controllers in tabbarcontroller.

My question is "how to modify the tint color of Configure screen?".

答:
oops ! I googled & I found something. I looking towards study it.

http://sugartin.info/2012/01/23/uitabbarcontroller-more-configure-customization/

Yo ! I got it.

```<code>- (void)tabBarController:(UITabBarController *)controller willBeginCustomizingViewControllers:(NSArray *)viewControllers {
    UIView *editView = [controller.view.subviews objectAtIndex:1];
    UINavigationBar *modalNavBar = [editView.subviews objectAtIndex:0];
    modalNavBar.tintColor = [UIColor orangeColor];
}
</code>```

Body:
How to modify the UINavigationBarTintColor for "Configure" in "more" in UITabBarController?

I have 10 UINavigationController within a UITabBarController (everything using Interface builder. )

I can easily set the tint color of all UINavigationController's UINavigationBar using Interface builder.

Similarly I also found that we can modify the More's Tint color as follows.

tBarDashboard.moreNavigationController.navigationBar.tintColor=
[UIColor colorWithRed:30/255.0 green:103/255.0 blue:7/255.0 alpha:1.0];
// here tbarDashboard is my UITabBarController.

But TabBarController default allows to configure the arrangement of navigation controllers if we have too many navigation controllers in tabbarcontroller.

My question is "how to modify the tint color of Configure screen?".

Body:
oops ! I googled & I found something. I looking towards study it.

http://sugartin.info/2012/01/23/uitabbarcontroller-more-configure-customization/

Yo ! I got it.

- (void)tabBarController:(UITabBarController *)controller willBeginCustomizingViewControllers:(NSArray *)viewControllers {
    UIView *editView = [controller.view.subviews objectAtIndex:1];
    UINavigationBar *modalNavBar = [editView.subviews objectAtIndex:0];
    modalNavBar.tintColor = [UIColor orangeColor];
}


问:
How to get $http response and assign to local variable using services?
service.js

```<code>     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}
</code>```

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js

答:
First Create a service

```<code>angular
  .module('app')
  .factory('tableService', tableService);
function tableService($q, $http, $cookies) {
  return {
    tableData: tableData
  };

  function tableData() {
    var d = $q.defer();
    $http({
      method: 'GET',
      url: 'http://localhost:5000/api/studentsList'
    }).success(function(response) {
      d.resolve(response);
    }).error(function(response) {
      d.reject(response);
    });
    return d.promise;
  }
}
</code>```

Note: I created factory, you can do that through service also

Create your controller and call service inside controller

```<code>angular
  .module('app')
  .controller('tableController', tableController);
function tableController($scope, tableService) {
  $scope.tableData = [];
  tableData();

function tableData() {
    tableService.tableData().then(function(response) {
        if (response.success) {
          $scope.tableData = response.data;
        }
    }, function() {
    });
   }
}
</code>```

Body:
service.js

     angular.module('app')
        .service('tableService', [
        '$q',
      tableService
  ]);

  function tableService($q){
    var tableData = [
      {
        issue: 'Vinayak N',
        progress: 100,
       // status: 69,
        class: 'md-accent'
      }
    ];
}

i want to make a call to $http.get('http://localhost:5000/api/studentsList'); and assign the response.data to a local variable tableData in service.js

Body:
First Create a service

angular
  .module('app')
  .factory('tableService', tableService);
function tableService($q, $http, $cookies) {
  return {
    tableData: tableData
  };

  function tableData() {
    var d = $q.defer();
    $http({
      method: 'GET',
      url: 'http://localhost:5000/api/studentsList'
    }).success(function(response) {
      d.resolve(response);
    }).error(function(response) {
      d.reject(response);
    });
    return d.promise;
  }
}

Note: I created factory, you can do that through service also

Create your controller and call service inside controller

angular
  .module('app')
  .controller('tableController', tableController);
function tableController($scope, tableService) {
  $scope.tableData = [];
  tableData();

function tableData() {
    tableService.tableData().then(function(response) {
        if (response.success) {
          $scope.tableData = response.data;
        }
    }, function() {
    });
   }
}


问:
Export html table as an excel sheet excluding hidden elements
I am trying to export html table as an excel. This html table have some hidden properties and I want to remove them when exporting the table. So I tried below.

```<code>if ('undefined' !== typeof module) {

    module.exports = function initExport() {
        var data_type = 'data:application/vnd.ms-excel';;

        $('table *:hidden').attr('data-todelete', 'true');
        var clonedItem = $($('table').html());
        $('table *:hidden').removeAttr('data-todelete');
        clonedItem.find('*:hidden').remove();

        var a = document.createElement('a');
        a.href = data_type + ', ' + clonedItem.wrap("<div />").parent().html();
        a.download = 'exported_table_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
        a.click();

    }
}
</code>```

The excel is exporting but it contains following.

```<code><thead_ngcontent-scg-0=""></thead>
</code>```

EDITED

I use

```<code>a.href = data_type + ', ' + clonedItem.html().replace(/ /g, '%20');
</code>```

instead of

```<code>a.href = data_type + ', ' + clonedItem.html();
</code>```

Then the excel cantains below and this is the HTML structure that I want to export.

```<code>        <thead _ngcontent-xbe-0="">
   <tr _ngcontent-xbe-0="" role="row">
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 9px;">#</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 63px;">Departure Airport</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 72px;">Destination Airport</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 56px;">Modified Time</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 69px;">Availability</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 54px;">Duration</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 63px;">Departure Date</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 24px;">Pax</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 33px;">Total Price</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 48px;">Time(Hours)</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 47px;">Expired Time</th>
      <th _ngcontent-xbe-0="" class="sorting_disabled" rowspan="1" colspan="1" style="width: 59px;">Last Possible Price Changed Time</th>
   </tr>
</thead>

<tbody _ngcontent-xbe-0="">

   <tr _ngcontent-xbe-0="">
      <td _ngcontent-xbe-0="">1</td>
      <td _ngcontent-xbe-0="">ASD</td>
      <td _ngcontent-xbe-0="">ABC</td>
      <td _ngcontent-xbe-0="">2017-06-05 12:34:44</td>
      <td _ngcontent-xbe-0="" style="text-align: center;">true</td>
      <td _ngcontent-xbe-0="" style="text-align: center;">13</td>
      <td _ngcontent-xbe-0="">2017-07-31</td>
      <td _ngcontent-xbe-0="">1_0_0</td>
      <td _ngcontent-xbe-0="" style="text-align: right;">143.01</td>
      <td _ngcontent-xbe-0="" style="text-align: right;">1.00</td>
      <td _ngcontent-xbe-0="" style="text-align: center;">2017-06-05 13:34:44</td>
      <td _ngcontent-xbe-0="" style="text-align: center;">2017-06-05 12:34:44</td>
   </tr>

   <!--data-->

</tbody>
</code>```

Any suggestions are appreciated.

Thank You

答:
I don't really get your data-todelete, you don't seem to use it.

Try using the .clone() JQuery function :

```<code>if (module != null) {

    module.exports = function initExport() {
        var data_type = 'data:application/vnd.ms-excel';;

        $('table *:hidden').attr('data-todelete', 'true');
        var clonedItem = $('table').clone();
        $('table *:hidden').removeAttr('data-todelete');
        $('[data-todelete]',clonedItem).remove();

        var a = document.createElement('a');
        a.href = data_type + ', ' + clonedItem.html();
        a.download = 'exported_table_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
        a.click();

    }
}
</code>```

I tested my own function to save a table to an XLS file, and it works fine with your table structure : https://jsfiddle.net/0qt01rmw/1/

Body:
I am trying to export html table as an excel. This html table have some hidden properties and I want to remove them when exporting the table. So I tried below.

if ('undefined' !== typeof module) {

    module.exports = function initExport() {
        var data_type = 'data:application/vnd.ms-excel';;

        $('table *:hidden').attr('data-todelete', 'true');
        var clonedItem = $($('table').html());
        $('table *:hidden').removeAttr('data-todelete');
        clonedItem.find('*:hidden').remove();

        var a = document.createElement('a');
        a.href = data_type + ', ' + clonedItem.wrap("
").parent().html();
        a.download = 'exported_table_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
        a.click();

    }
}

The excel is exporting but it contains following.

<thead_ngcontent-scg-0="">

EDITED

I use

a.href = data_type + ', ' + clonedItem.html().replace(/ /g, '%20');

instead of

a.href = data_type + ', ' + clonedItem.html();

Then the excel cantains below and this is the HTML structure that I want to export.

      #
      Departure Airport
      Destination Airport
      Modified Time
      Availability
      Duration
      Departure Date
      Pax
      Total Price
      Time(Hours)
      Expired Time
      Last Possible Price Changed Time

      1
      ASD
      ABC
      2017-06-05 12:34:44
      true
      13
      2017-07-31
      1_0_0
      143.01
      1.00
      2017-06-05 13:34:44
      2017-06-05 12:34:44

Any suggestions are appreciated.

Thank You

Body:
I don't really get your data-todelete, you don't seem to use it.

Try using the .clone() JQuery function :

if (module != null) {

    module.exports = function initExport() {
        var data_type = 'data:application/vnd.ms-excel';;

        $('table *:hidden').attr('data-todelete', 'true');
        var clonedItem = $('table').clone();
        $('table *:hidden').removeAttr('data-todelete');
        $('[data-todelete]',clonedItem).remove();

        var a = document.createElement('a');
        a.href = data_type + ', ' + clonedItem.html();
        a.download = 'exported_table_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
        a.click();

    }
}

I tested my own function to save a table to an XLS file, and it works fine with your table structure : https://jsfiddle.net/0qt01rmw/1/


问:
PHP namespace syntax
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}
</code>```

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}
</code>```

But when I run the code I get

```<code>Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php
</code>```

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

```<code>namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}
</code>```

when I run phpcs with this sniff then I get the error

```<code>PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409
</code>```

I hope this makes things clearer

答:
You have to implement an interface, not extend. Try this:</p>

```<code>class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements CodeSniffer_Sniff  {
}
</code>```

Title: PHP namespace syntax

Body:
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}

But when I run the code I get

Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}

when I run phpcs with this sniff then I get the error

PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409

I hope this makes things clearer

Body:
You have to implement an interface, not extend. Try this:

class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements CodeSniffer_Sniff  {
}


问:
Moving gameObject with parent to face another gameObject
I have GameObject A, B, C. B is a child of A. B and C are cubes with one side highlighted.

I want to move and rotate B and his parent A to stick highlighted side of B to highlighted side of C object.

How to do this?

答:
I assume you only wanted to change A's value so that B location remain intact relative to A.

The simple solution would be to create a dummy object that is a child of C (so that its transform is relative to C), set it to the correct position and rotation you want A to be (where highlighted sides stick), then on runtime you could always move A into that location by setting its position and rotation to be the same as dummy's. Since dummy's transform is relative to C, no matter how you alter C's transform, dummy will always stay in correct location and gives you the correct values for A.

Another solution would be by Math. However, I think using complicated calculation functions will be not so efficient (both for the computer and your head lol). Using a dummy object would be better since Unity does the Math for you and it doesn't involve additional computation though. But perhaps it would be something like this:

```<code>public Transform a;
public Transform b;
public Transform c;

public Vector3 b_hl_dir; // highlight direction (e.g. right side would be {1,0,0} and back side would be {0,0,-1})
public Vector3 c_hl_dir;

public float width; // cube's width, assuming b and c has the same width.

public void RelocateA(){
    // #1. Calculate correct position for B
    Vector3 b_pos = c.position + c.rotation * c_hl_dir * width;
    Quaternion b_rot = Quaternion.LookRotation(c.position - b_pos, (Mathf.Abs(Vector3.Dot(c_hl_dir, Vector3.up)) < 1f) ? c.up : c.right) * Quaternion.FromToRotation(b_hl_dir, Vector3.forward);

    // #2. Relocate A according to B's correct position
    a.rotation = b_rot * Quaternion.Inverse(b.localRotation);
    a.position += b_pos - b.position;
}
</code>```

Body:
I assume you only wanted to change A's value so that B location remain intact relative to A.

The simple solution would be to create a dummy object that is a child of C (so that its transform is relative to C), set it to the correct position and rotation you want A to be (where highlighted sides stick), then on runtime you could always move A into that location by setting its position and rotation to be the same as dummy's. Since dummy's transform is relative to C, no matter how you alter C's transform, dummy will always stay in correct location and gives you the correct values for A.

Another solution would be by Math. However, I think using complicated calculation functions will be not so efficient (both for the computer and your head lol). Using a dummy object would be better since Unity does the Math for you and it doesn't involve additional computation though. But perhaps it would be something like this:

public Transform a;
public Transform b;
public Transform c;

public Vector3 b_hl_dir; // highlight direction (e.g. right side would be {1,0,0} and back side would be {0,0,-1})
public Vector3 c_hl_dir;

public float width; // cube's width, assuming b and c has the same width.

public void RelocateA(){
    // #1. Calculate correct position for B
    Vector3 b_pos = c.position + c.rotation * c_hl_dir * width;
    Quaternion b_rot = Quaternion.LookRotation(c.position - b_pos, (Mathf.Abs(Vector3.Dot(c_hl_dir, Vector3.up)) < 1f) ? c.up : c.right) * Quaternion.FromToRotation(b_hl_dir, Vector3.forward);

    // #2. Relocate A according to B's correct position
    a.rotation = b_rot * Quaternion.Inverse(b.localRotation);
    a.position += b_pos - b.position;
}