问:
Show popup modal javascript function not working inside ItemCommand Function
I have a repeater control which displays our Partners Names  as link button,  when  clicking a Link button  I need to show a bootstrap modal to display the clicked Partner Details , I fetch the partner Details from  sql server and bind them to the Modal  repeater in  the ItemCommand function . My problem is that the modal didn't show Up :( there is no error appear in the consol .

please any one can help me ? why the Modal not Showing up is there any error in my javascript code?

```<code>       <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="Partners.aspx.cs" Inherits="MyAPP.AR.Parteners" %>

    <asp:Content ID="DefaultContent" ContentPlaceHolderID="MainContent" runat="server">

     <script src="../Scripts/jquery-1.9.1.min.js"></script>
    <script src="../Scripts/jquery-1.9.1.js"></script>

    <script src="../Scripts/bootstrap.min.js"></script>
    <script src="../Scripts/bootstrap.js"></script>

    <link href="../Content/bootstrap.css" rel="stylesheet" />
    <link href="../Content/SiteStyle.css" rel="stylesheet" />
      <script type="text/javascript">
        function showModal() {
            $("#PModal").modal('show');
        }

        $(function () {
            $("#lnkdetail").click(function () {
                showModal();
            });
        });
    </script>

    <form  runat ="server" >

    <p><strong> Our Partners </strong></p>
    <div class="panel-group" id="Parteners_accordion">
     <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#Parteners_accordion" href="#collapse1">Local Partners </a>
        </h4>
      </div>
      <div id="collapse1" class="panel-collapse collapse in">
        <div class="panel-body">
         <asp:Repeater  runat ="server"  ID="LocalPartners_rptr"   OnItemCommand="Localrptr_ItemCommand" >
         <ItemTemplate>
                       <div >
         <asp:LinkButton runat="server"   CommandName="Show"
          CommandArgument='<%#Eval("Id") %>' ><%#Eval("Name") %> asp:LinkButton>
           </div>
             <br />
        </ItemTemplate>

         </asp:Repeater>
        </div>
      </div>
    </div>

       <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="panel-title">
          <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Glopal Partners</a>
        </h4>
      </div>
      <div id="collapse2" class="panel-collapse collapse">
        <div class="panel-body"></div>
      </div>
    </div>
   </div>
     </form>
    <div id="PModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
    <!-- Modal content-->
        <div class="modal-content">
        <asp:Repeater ID="LocalPartnerInfo_rptr" runat="server" >
        <ItemTemplate>

      <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">×
            </button>
                <h4 class="modal-title"><%#Eval("Name") %></h4>
                 </div>
                <div class="modal-body" style="color :#000000;">
                <div class="container-fluid">

                 <div class="row">
                  <div class="col-md-8"><%#Eval("Descreption")%></div>
                  <div class="col-md-4">Logo</div>
                  </div>
                <div class="row">
                <div class="col-md-4">Empty</div>
                <div class="col-md-4"><%#Eval("WebsiteLink")%></div>
                 <div class="col-md-4">Empty</div>
                 </div>

                </div>

              </div>
                  </ItemTemplate>
                     </asp:Repeater>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              </div>
            </div>

          </div>
        </div>
    </asp:Content>
</code>```

C# Code

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

   namespace MyAPP.AR
   {
    public partial class Parteners : System.Web.UI.Page
    {

    int partnerId = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            BindLocalPartners_Repeater();

        }

    }

    private void BindLocalPartners_Repeater()
    {

        String ConnStr = ConfigurationManager.ConnectionStrings["PalDRM_DB"].ConnectionString;
        SqlConnection cnn = new SqlConnection(ConnStr);
        cnn.Open();
        SqlCommand cmd = new SqlCommand("SELECT  [Id],[Name],[Descreption],[LogoUrl],[WebsiteLink]  FROM  Partners where [Type]='local'  ", cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        LocalPartners_rptr.DataSource = dr;
        LocalPartners_rptr.DataBind();
        cnn.Close();

    }

    protected void Localrptr_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //HiddenField IdField = (HiddenField)e.Item.FindControl("LocalPartner_Id");

       // partnerId = Convert.ToInt32(IdField.Value);

        if (e.CommandName == "Show")
        {
            LinkButton btndetails = (LinkButton)e.CommandSource;

            int Id = Convert.ToInt32(btndetails.CommandArgument.ToString());

            String ConnStr = ConfigurationManager.ConnectionStrings["PalDRM_DB"].ConnectionString;
            SqlConnection cnn = new SqlConnection(ConnStr);
            cnn.Open();
            SqlCommand cmd = new SqlCommand("SELECT  [Name],[Descreption],[LogoUrl],[WebsiteLink]  FROM  Partners where [Id]=" + Id + "", cnn);
            SqlDataReader dr = cmd.ExecuteReader();
            LocalPartnerInfo_rptr.DataSource = dr;
            LocalPartnerInfo_rptr.DataBind();
            cnn.Close();
            //ClientScript.RegisterStartupScript(this.GetType(), "Pop", "showModal();", true);

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showModal();", true);

        }

    }

  }
}
</code>```

答:
I don't see "lnkdetail" in your page. I suppose it's a LinkButton.
Anyway, you could use  or  instead in order to avoid postback.
Move your javascript code at the bottom of the page after repeater control. And in repeater_Itemcommand remove this line ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showModal();", true);</p>

Body:
I have a repeater control which displays our Partners Names  as link button,  when  clicking a Link button  I need to show a bootstrap modal to display the clicked Partner Details , I fetch the partner Details from  sql server and bind them to the Modal  repeater in  the ItemCommand function . My problem is that the modal didn't show Up :( there is no error appear in the consol .

please any one can help me ? why the Modal not Showing up is there any error in my javascript code?

       <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="Partners.aspx.cs" Inherits="MyAPP.AR.Parteners" %>

    <asp:Content ID="DefaultContent" ContentPlaceHolderID="MainContent" runat="server">

    <link href="../Content/bootstrap.css" rel="stylesheet" />
    <link href="../Content/SiteStyle.css" rel="stylesheet" />

    <form  runat ="server" >

 Our Partners

          Local Partners

         <asp:Repeater  runat ="server"  ID="LocalPartners_rptr"   OnItemCommand="Localrptr_ItemCommand" >
         <ItemTemplate>

         <asp:LinkButton runat="server"   CommandName="Show"
          CommandArgument='<%#Eval("Id") %>' ><%#Eval("Name") %> asp:LinkButton>

        </ItemTemplate>

         </asp:Repeater>

          Glopal Partners

     </form>

        <asp:Repeater ID="LocalPartnerInfo_rptr" runat="server" >
        <ItemTemplate>

                  <button type="button" class="close" data-dismiss="modal">×
            </button>

<%#Eval("Name") %>

<%#Eval("Descreption")%>

Logo

Empty

<%#Eval("WebsiteLink")%>

Empty

                  </ItemTemplate>
                     </asp:Repeater>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    </asp:Content>

C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

   namespace MyAPP.AR
   {
    public partial class Parteners : System.Web.UI.Page
    {

    int partnerId = 0;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            BindLocalPartners_Repeater();

        }

    }

    private void BindLocalPartners_Repeater()
    {

        String ConnStr = ConfigurationManager.ConnectionStrings["PalDRM_DB"].ConnectionString;
        SqlConnection cnn = new SqlConnection(ConnStr);
        cnn.Open();
        SqlCommand cmd = new SqlCommand("SELECT  [Id],[Name],[Descreption],[LogoUrl],[WebsiteLink]  FROM  Partners where [Type]='local'  ", cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        LocalPartners_rptr.DataSource = dr;
        LocalPartners_rptr.DataBind();
        cnn.Close();

    }

    protected void Localrptr_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //HiddenField IdField = (HiddenField)e.Item.FindControl("LocalPartner_Id");

       // partnerId = Convert.ToInt32(IdField.Value);

        if (e.CommandName == "Show")
        {
            LinkButton btndetails = (LinkButton)e.CommandSource;

            int Id = Convert.ToInt32(btndetails.CommandArgument.ToString());

            String ConnStr = ConfigurationManager.ConnectionStrings["PalDRM_DB"].ConnectionString;
            SqlConnection cnn = new SqlConnection(ConnStr);
            cnn.Open();
            SqlCommand cmd = new SqlCommand("SELECT  [Name],[Descreption],[LogoUrl],[WebsiteLink]  FROM  Partners where [Id]=" + Id + "", cnn);
            SqlDataReader dr = cmd.ExecuteReader();
            LocalPartnerInfo_rptr.DataSource = dr;
            LocalPartnerInfo_rptr.DataBind();
            cnn.Close();
            //ClientScript.RegisterStartupScript(this.GetType(), "Pop", "showModal();", true);

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showModal();", true);

        }

    }

  }
}


来源: stackexchange

问:
How to capitalise the first letter of each word after reversing a string
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.</p>

```<code>function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}
</code>```

答:
Use toLowerCase() if you need to convert it back to lowercase & css property
text-transform: capitalize will capitalize first letter of every word

function titleCase(str) {
  var reversed = str.toLowerCase().split('').reverse();
  var newArr = [];
  for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
    newArr[i] = (firstLetter + restOfWord).toLowerCase();
  }
  return newArr.join('');
}

document.getElementById('test').innerHTML = titleCase('Hello how are you')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
  text-transform: capitalize
}</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.

function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
        newArr[i] = firstLetter + restOfWord;
 }
 return newArr.join('');
}

Body:
Use toLowerCase() if you need to convert it back to lowercase & css property
text-transform: capitalize will capitalize first letter of every word

function titleCase(str) {
  var reversed = str.toLowerCase().split('').reverse();
  var newArr = [];
  for (var i = 0; i < reversed.length; i++) {
    var firstLetter = reversed[i].charAt(0).toUpperCase();
    var restOfWord = reversed[i].slice(1);
    newArr[i] = (firstLetter + restOfWord).toLowerCase();
  }
  return newArr.join('');
}

document.getElementById('test').innerHTML = titleCase('Hello how are you')

.test {
  text-transform: capitalize
}

<div class="test" id="test"></div>


问:
How to upload multiple image to firebase in react native fetch blob
I have multiple images that are stored in an array (image paths stored in array).
then I use a for loop to upload every image, but only the last image is uploaded.
I use react native fetch blob, and firebase

for(var i = 0; i < this.state.imagesUri;i++){
 Blob.build(RNFetchBlob.wrap(this.state.imagesUri[i].path),{ type : 'image/jpeg' })
            .then((blob) => firebase.storage()
            .ref("userPhoto").child("image"+i)
            .put(blob, { contentType : 'image/png' }).then(()=>{
   var storage =  firebase.storage().ref("userPhoto/").child("image"+i);
              storage.getDownloadURL().then((url)=>{
                var url = url;
              });
            })
          );
        }```

答:
OK, first of all, you need to cache the length of the array this.state.imagesUri.

This will make your for loop look like so for(var i = 0, length = this.state.imagesUri.length; i < length;i++){, I hope you've noticed that you aren't checking anymore if the i < this.state.imagesUri (This is incorrect since imagesUri is an array).


问:
Cloud Foundry quantum state - organization simultaneously exists and fails to exist
I have a barebones Cloud Foundry instance running on BOSH-Lite, and I am running into an absolutely puzzling situation. Cloud Foundry claims that I have no org. When I try to create the org, Cloud Foundry claims the org already exists. When I try to target the org, Cloud Foundry claims the org doesn't exist. What is Cloud Foundry doing?</p>

```<code>$ cf orgs
Getting orgs as karan...
No orgs found.

$ cf create-org orgname
Creating org orgname as karan...
OK
Org orgname already exists

$ cf target -o orgname
Organization 'orgname' not found.
FAILED
</code>```

答: My guess is that there is an org in the Cloud Controller database named orgname that you do not have access to. For security reasons, if you do not have access to an org, it is exactly the same as it not existing, from your point of view.

Body:
I have a barebones Cloud Foundry instance running on BOSH-Lite, and I am running into an absolutely puzzling situation. Cloud Foundry claims that I have no org. When I try to create the org, Cloud Foundry claims the org already exists. When I try to target the org, Cloud Foundry claims the org doesn't exist. What is Cloud Foundry doing?

$ cf orgs
Getting orgs as karan...
No orgs found.

$ cf create-org orgname
Creating org orgname as karan...
OK
Org orgname already exists

$ cf target -o orgname
Organization 'orgname' not found.
FAILED


问:
String Extraction from Text File
I have a very weird text file that has some data that I need to extract. I really don't know the best approach and I need guide on what would be the best idea how to do it. The text looks like this:

Picture of Data to Extract

Basically the file contains that data. and I would need to extract each parameter AA - FF for each "column" of data. There are some spaces in between each number..

Is it possible to find the word AA, move to after the "--" characters and copy such number until there are spaces.... and repeat through the line?
or,

Is it easier to try to fit that data into a table that is separated by spaces?

No idea how to start this and hence asking for help.
Regards,
DH

答:
I would read each line and separate them on spaces, throwing away empties.
That will leave you with a list of fields. In this sample, I create a list of list of fields in the form of a List(Of List(Of string)). This creates a list of fields for each line and I think it makes it easy to iterate and store them.

Vb.net sample

```<code>Module Module1

    Sub Main()
        Dim fieldsOfEachLine As New List(Of List(Of String))

        Dim reader As IO.StreamReader = New IO.StreamReader("F:\SlyWorkspace\StackOverflow\SpaceSeparatedText_47337929\sampledata.txt")
        Dim currentLine As String

        Do
            currentLine = reader.ReadLine()
            If currentLine IsNot Nothing Then
                fieldsOfEachLine.Add(currentLine.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries).ToList())
            End If
        Loop Until currentLine Is Nothing

        reader.Close()

        'once you have your fields neatly placed in a list, it's up
        'to you to decide what you want to do with them
        'for this sample, I will just spit them back out the screen using a \ to delimit the information I kept
        For Each item As List(Of String) In fieldsOfEachLine
            Console.WriteLine(String.Join("\", item))
        Next

        Console.ReadLine()

    End Sub

End Module
</code>```

Here's a quick c# sample.

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharp_SpaceSeparatedText_47337929
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<string>> fieldsForEachLine = new List<List<string>>();
            string currentLine = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(@"F:\SlyWorkspace\StackOverflow\SpaceSeparatedText_47337929\sampledata.txt"))
            {
                while ((currentLine = sr.ReadLine()) != null)
                {
                    fieldsForEachLine.Add(currentLine.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList());
                }
            }

            foreach (List<string> item in fieldsForEachLine)
            {
                Console.WriteLine(string.Join("/", item));
            }

            Console.ReadLine();
        }
    }
}
</code>```

my datafile contains this

```<code>                           1                      2                     3
                bu                     AU                    BG
AA               --      929.2244             1074.4697                 1114.7150
BB               --        1.458             1074.4697              1114.7150
CC           --    456.4584    448.4     584.5
DD  -- 1234.458      789.456                             4898.45
</code>```

My output is this

```<code>1\2\3
bu\AU\BG
AA\--\929.2244\1074.4697\1114.7150
BB\--\1.458\1074.4697\1114.7150
CC\--\456.4584\448.4\584.5
DD\--\1234.458\789.456\4898.45
</code>```

Title: String Extraction from Text File

Body:
I would read each line and separate them on spaces, throwing away empties.
That will leave you with a list of fields. In this sample, I create a list of list of fields in the form of a List(Of List(Of string)). This creates a list of fields for each line and I think it makes it easy to iterate and store them.

Vb.net sample

Module Module1

    Sub Main()
        Dim fieldsOfEachLine As New List(Of List(Of String))

        Dim reader As IO.StreamReader = New IO.StreamReader("F:\SlyWorkspace\StackOverflow\SpaceSeparatedText_47337929\sampledata.txt")
        Dim currentLine As String

        Do
            currentLine = reader.ReadLine()
            If currentLine IsNot Nothing Then
                fieldsOfEachLine.Add(currentLine.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries).ToList())
            End If
        Loop Until currentLine Is Nothing

        reader.Close()

        'once you have your fields neatly placed in a list, it's up
        'to you to decide what you want to do with them
        'for this sample, I will just spit them back out the screen using a \ to delimit the information I kept
        For Each item As List(Of String) In fieldsOfEachLine
            Console.WriteLine(String.Join("\", item))
        Next

        Console.ReadLine()

    End Sub

End Module

Here's a quick c# sample.

using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharp_SpaceSeparatedText_47337929
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<string>> fieldsForEachLine = new List<List<string>>();
            string currentLine = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(@"F:\SlyWorkspace\StackOverflow\SpaceSeparatedText_47337929\sampledata.txt"))
            {
                while ((currentLine = sr.ReadLine()) != null)
                {
                    fieldsForEachLine.Add(currentLine.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList());
                }
            }

            foreach (List<string> item in fieldsForEachLine)
            {
                Console.WriteLine(string.Join("/", item));
            }

            Console.ReadLine();
        }
    }
}

my datafile contains this

                           1                      2                     3
                bu                     AU                    BG
AA               --      929.2244             1074.4697                 1114.7150
BB               --        1.458             1074.4697              1114.7150
CC           --    456.4584    448.4     584.5
DD  -- 1234.458      789.456                             4898.45

My output is this

1\2\3
bu\AU\BG
AA\--\929.2244\1074.4697\1114.7150
BB\--\1.458\1074.4697\1114.7150
CC\--\456.4584\448.4\584.5
DD\--\1234.458\789.456\4898.45


问:
Printing a Square with loops
//college work

Hello, I am trying to print a square by using loops, it also require the user to input the height and width.
The Output should look like this

```....
.  .
....```

any help would be apprciated

```<code>import java.util.Scanner;
public class Ex1 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System. in );
        System.out.print("Please enter the height of the box: ");
        int x = input.nextInt();

        System.out.println("Please enter a width for the box: ");
        int y = input.nextInt();
        drawbox(x, y);

    }

    static void drawbox(int x, int y) {

        for (int j = 0; j < y; j++) {
            System.out.println("*");

            System.out.println();
            for (int i = 0; i < x - 2; i++) {
                System.out.print("*");
                for (int z = 0; z < y - 2; z++) {
                    System.out.print(" ");
                }
                System.out.println("*");

                for (int i = 0; j < y; j++) {
                    System.out.println("*");
                }

            }
        }
    }
}
</code>```

答:
A simple algorithm to draw square by loops</p>

```<code>public void draw(int length){
    for(int i = 0; i < length; i++){
        for(int j = 0;j < length; j++){
            if(i!= 0 && j > 0 && i!= length - 1 && j!= length-1){
                System.out.print(" ");
            }
            else System.out.print("*");
        }
        System.out.println();
    }
}
</code>```

Title: Printing a Square with loops

Body:
//college work

Hello, I am trying to print a square by using loops, it also require the user to input the height and width.
The Output should look like this

....
.  .
....

any help would be apprciated

import java.util.Scanner;
public class Ex1 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System. in );
        System.out.print("Please enter the height of the box: ");
        int x = input.nextInt();

        System.out.println("Please enter a width for the box: ");
        int y = input.nextInt();
        drawbox(x, y);

    }

    static void drawbox(int x, int y) {

        for (int j = 0; j < y; j++) {
            System.out.println("*");

            System.out.println();
            for (int i = 0; i < x - 2; i++) {
                System.out.print("*");
                for (int z = 0; z < y - 2; z++) {
                    System.out.print(" ");
                }
                System.out.println("*");

                for (int i = 0; j < y; j++) {
                    System.out.println("*");
                }

            }
        }
    }
}

Body:
A simple algorithm to draw square by loops

public void draw(int length){
    for(int i = 0; i < length; i++){
        for(int j = 0;j < length; j++){
            if(i!= 0 && j > 0 && i!= length - 1 && j!= length-1){
                System.out.print(" ");
            }
            else System.out.print("*");
        }
        System.out.println();
    }
}


问:
store multiple values in associative array and return that array in php
I have seen a lot of answers (so please don't mark it duplicate) to store  values in associative array but I want to return that array in PHP. Here is my code. It prints all values but only return the first value. I want the whole array returned to use in another function.

Please help

```<code>function xml_parsing($response,$size,$array)
{
    for($k=0;$k<$size;$k++)
    {
        $price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
        $myarray[$k]=explode(',',$array["ItemId"]);
        $update_fields=array('sku','price');
        if($price=='')
        {
            $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
        }
        else
        {
            $price_trimed=ltrim($price,'$');
            $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
            // I store the values here using a loop
        }
    }
    print_r($Col_array);
    return $col_array; //but here it return only first value
                       // But I want to return the whole array**
                       // I can't return it inside loop because it terminates
                       // the loop and the function
}
</code>```

答:
Some pseudocode:

```<code>//first, initialize empty array:
$Col_array = [];

//do the loop thing.
while(...){

    //inside the loop:

    //add to array:
    $Col_array []= array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);

}//loop ends here
print_r($Col_array); //<----- all values.
return $Col_array;
</code>```

notice how one uses []= to append to an array.

Body:
I have seen a lot of answers (so please don't mark it duplicate) to store  values in associative array but I want to return that array in PHP. Here is my code. It prints all values but only return the first value. I want the whole array returned to use in another function.

Please help

function xml_parsing($response,$size,$array)
{
    for($k=0;$k<$size;$k++)
    {
        $price=(string)$response->Items->Item[$k]->ItemAttributes->ListPrice->FormattedPrice;
        $myarray[$k]=explode(',',$array["ItemId"]);
        $update_fields=array('sku','price');
        if($price=='')
        {
            $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>"-1");
        }
        else
        {
            $price_trimed=ltrim($price,'$');
            $Col_array=array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);
            // I store the values here using a loop
        }
    }
    print_r($Col_array);
    return $col_array; //but here it return only first value
                       // But I want to return the whole array**
                       // I can't return it inside loop because it terminates
                       // the loop and the function
}

Body:
Some pseudocode:

//first, initialize empty array:
$Col_array = [];

//do the loop thing.
while(...){

    //inside the loop:

    //add to array:
    $Col_array []= array('sku'=>"".$myarray[$k][$k]."",'price'=>$price_trimed);

}//loop ends here
print_r($Col_array); //<----- all values.
return $Col_array;

notice how one uses []= to append to an array.


问:
How to store selected contacts into an array in IOS 9 using swift
I fetched the contacts details and I want to store them into an array .I have tried but it stores like single contact as one array. but I want to store all of them into one array. how to store them.please guide me.
First it display all the contacts from our phone and I have selected particular contact.That selected contacts should be stored in an array
Thank you</p>

```<code>import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate {
    let contactStore = CNContactStore()
    let amount = 200
    //var selectedContact:CNContact = CNContact()
    //var results:[CNContact] = []
    var res:CNContact = CNContact()
    var a = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
         perform(#selector(contactPicker(_:didSelect:)), with: nil, afterDelay: 0)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)

    }

    @IBAction func contact(_ sender: Any) {
        let cnPicker = CNContactPickerViewController()
        cnPicker.delegate = self
        self.present(cnPicker, animated: true, completion: nil)
        do {
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])) {
                (contact, cursor) -> Void in
                self.res = contact
                ///let data = Data(name: contact.givenName)
                //self.dataArray?.addObject(data)
            }
        }
        catch
        {
            print("Handle the error please")
        }
    }
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            //let storyboard = UIStoryboard(name:"Main",bundle:nil)
            a = [contact.givenName]
            print("name of contacts in array \(a)")
            let n = a.flatMap({$0}).count
            print(n)
            let res = amount/n
            print(res)
            for c in a {
                print ("split money \(c):\(res)")
            }
            //print(a.count)
            let displayViewController = self.storyboard?.instantiateViewController(withIdentifier: "DisplayViewControllerr")as! DisplayViewControllerr
              displayViewController.b = a
            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = displayViewController
            self.navigationController?.pushViewController(displayViewController, animated: true)
            //self.present(displayViewController,animated:false,completion: nil)

            }
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel Contact Picker")
    }

}
</code>```

答:
I got the answer and  successfully stored contacts into array. just modify one line in the program.That is

```<code>func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            a+= [contact.givenName]//I changed at this place
}
print(a)
</code>```

It displays all the selected contacts into array.

Body:
I fetched the contacts details and I want to store them into an array .I have tried but it stores like single contact as one array. but I want to store all of them into one array. how to store them.please guide me.
First it display all the contacts from our phone and I have selected particular contact.That selected contacts should be stored in an array
Thank you

import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate {
    let contactStore = CNContactStore()
    let amount = 200
    //var selectedContact:CNContact = CNContact()
    //var results:[CNContact] = []
    var res:CNContact = CNContact()
    var a = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
         perform(#selector(contactPicker(_:didSelect:)), with: nil, afterDelay: 0)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)

    }

    @IBAction func contact(_ sender: Any) {
        let cnPicker = CNContactPickerViewController()
        cnPicker.delegate = self
        self.present(cnPicker, animated: true, completion: nil)
        do {
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])) {
                (contact, cursor) -> Void in
                self.res = contact
                ///let data = Data(name: contact.givenName)
                //self.dataArray?.addObject(data)
            }
        }
        catch
        {
            print("Handle the error please")
        }
    }
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            //let storyboard = UIStoryboard(name:"Main",bundle:nil)
            a = [contact.givenName]
            print("name of contacts in array \(a)")
            let n = a.flatMap({$0}).count
            print(n)
            let res = amount/n
            print(res)
            for c in a {
                print ("split money \(c):\(res)")
            }
            //print(a.count)
            let displayViewController = self.storyboard?.instantiateViewController(withIdentifier: "DisplayViewControllerr")as! DisplayViewControllerr
              displayViewController.b = a
            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = displayViewController
            self.navigationController?.pushViewController(displayViewController, animated: true)
            //self.present(displayViewController,animated:false,completion: nil)

            }
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel Contact Picker")
    }

}

Body:
I got the answer and  successfully stored contacts into array. just modify one line in the program.That is

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            a+= [contact.givenName]//I changed at this place
}
print(a)

It displays all the selected contacts into array.


问:
How to pass values from one custom cell to another view controller by using global variables for iMessage?
I'm trying to develop an iMessage App and i'm not sure how to pass values from a custom cell to another view controller. I need to make sure that once the button is pressed the value from the cell is copied to the text sending space. Please help me out! Im stuck here :

This is the iMessage Code and instead of "hello world" it needs to put the label text from the cell

```<code>        let layout = MSMessageTemplateLayout()
        layout.caption = "Hello World"

        let message = MSMessage()
        message.layout = layout

        self.activeConversation?.insert(message, completionHandler: nil)
</code>```

The part which has the details on the cell in a different view controller

```<code>        func configureWithContactEntry(_ contact: ContactEntry) {
        contactNameLabel.text = contact.name
        contactEmailLabel.text = contact.email ?? ""
        contactPhoneLabel.text = contact.phone ?? ""

        return cell
</code>```

This is the CellForRow code

```<code>    let cell = tableView.dequeueReusableCell(withIdentifier:
    "ContactTableViewCell", for: indexPath) as! ContactTableViewCell
    let entry = filteredContacts[(indexPath as NSIndexPath).row]
    cell.configureWithContactEntry(entry)
    cell.layoutIfNeeded()

    return cell
</code>```

Would be great if anybody could help me out!

答:
You can pass your cell data to other controller in your imessage extension in this way. check your cell selected override function its look like

```<code>func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("cell selected at row \(indexPath.row)")
}
</code>```

Get model data on the base of indexPath from your model object, in your case you should get from this function.

```<code>let entry = filteredContacts[(indexPath as NSIndexPath).row]
let name = entry.name
</code>```

After that create Msession object and fill data in it from your entry object.

```<code>let session = MSSession()
        let message = MSMessage(session: session)
        let layout = MSMessageTemplateLayout()
        layout.caption = name

        message.layout = layout

        //save the message in the current conversation context

        self.savedConversation?.insert(message,
                                       completionHandler: { (err) in

                                        print("ERROR \(err.debugDescription)")
        })
</code>```

Also if you want to append image in message then do it this way.

```<code>        layout.image = UIImage(named:"image.png")!
</code>```

Body:
I'm trying to develop an iMessage App and i'm not sure how to pass values from a custom cell to another view controller. I need to make sure that once the button is pressed the value from the cell is copied to the text sending space. Please help me out! Im stuck here :

This is the iMessage Code and instead of "hello world" it needs to put the label text from the cell

        let layout = MSMessageTemplateLayout()
        layout.caption = "Hello World"

        let message = MSMessage()
        message.layout = layout

        self.activeConversation?.insert(message, completionHandler: nil)

The part which has the details on the cell in a different view controller

        func configureWithContactEntry(_ contact: ContactEntry) {
        contactNameLabel.text = contact.name
        contactEmailLabel.text = contact.email ?? ""
        contactPhoneLabel.text = contact.phone ?? ""

        return cell

This is the CellForRow code

    let cell = tableView.dequeueReusableCell(withIdentifier:
    "ContactTableViewCell", for: indexPath) as! ContactTableViewCell
    let entry = filteredContacts[(indexPath as NSIndexPath).row]
    cell.configureWithContactEntry(entry)
    cell.layoutIfNeeded()

    return cell

Would be great if anybody could help me out!

Body:
You can pass your cell data to other controller in your imessage extension in this way. check your cell selected override function its look like

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("cell selected at row \(indexPath.row)")
}

Get model data on the base of indexPath from your model object, in your case you should get from this function.

let entry = filteredContacts[(indexPath as NSIndexPath).row]
let name = entry.name

After that create Msession object and fill data in it from your entry object.

let session = MSSession()
        let message = MSMessage(session: session)
        let layout = MSMessageTemplateLayout()
        layout.caption = name

        message.layout = layout

        //save the message in the current conversation context

        self.savedConversation?.insert(message,
                                       completionHandler: { (err) in

                                        print("ERROR \(err.debugDescription)")
        })

Also if you want to append image in message then do it this way.

        layout.image = UIImage(named:"image.png")!


问:
Why is my function ending (using external library)
I need your help with some error handling. I'm using an external library but have no clue of what's happening with the error.
Here's my code:

```<code>//file name = playground.js
var ccxt = require("ccxt");
    ccxt.exchanges.map(r => {
      let exchange = new ccxt[r]();
      let ticks = exchange
        .fetchTickers()
        .then(res => {
          console.log(res);
        })
        .catch(e => {
          console.log(e);
        });
    });
</code>```

To execute it correctly, you'll need to install the external library: ccxt via npm: npm i ccxt --save
and I get the following error:

```<code>.../node_modules/ccxt/js/base/Exchange.js:407
        throw new NotSupported (this.id + ' fetchTickers not supported yet')
        ^

Error: _1broker fetchTickers not supported yet
    at _1broker.fetchTickers (.../node_modules/ccxt/js/base/Exchange.js:407:15)
    at ccxt.exchanges.map.r (.../playground.js:41:6)
    at Array.map (<anonymous>)
    at Object.<anonymous> (.../playground.js:38:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
</code>```

Basically, what the library helps me with is:

Make automatic request to different servers

Organize the responses in uniformed objects

Handle most of the errors that are returned by the servers

In my example, the error returned is related with the fact that the server doesn't support the function I'm using. To put it in simpler words:
I make a request that server1 might be able to handle but that server2 isn't able to respond to yet.

The ccxt.exhanges in the code returns an Array of the differents servers that are being handled by the library.

The problem is not so much that I get the error... I'm OK with not getting info back from every server but that my function literaly stops once it gets to the error. The .map loop doesn't go all the way to the end...

ccxt publishes some information on Error Handling but I'm not sure what I can do with it (noob in the place sorry guys).

I hope my question is clear enough and hasn't been already asked!

Thanks in advance for your help!

答:
Here's a slightly better version of it:</p>

```<code>var ccxt = require("ccxt");
ccxt.exchanges.forEach(r => {

    let exchange = new ccxt[r]();

    if (exchange.hasFetchTickers) { // ← the most significant line

        let ticks = exchange
            .fetchTickers()
            .then(res => {
                console.log(res);
            })
            .catch(e => {
                console.log(e);
            });
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need your help with some error handling. I'm using an external library but have no clue of what's happening with the error.
Here's my code:

//file name = playground.js
var ccxt = require("ccxt");
    ccxt.exchanges.map(r => {
      let exchange = new ccxt[r]();
      let ticks = exchange
        .fetchTickers()
        .then(res => {
          console.log(res);
        })
        .catch(e => {
          console.log(e);
        });
    });

To execute it correctly, you'll need to install the external library: ccxt via npm: npm i ccxt --save
and I get the following error:

.../node_modules/ccxt/js/base/Exchange.js:407
        throw new NotSupported (this.id + ' fetchTickers not supported yet')
        ^

Error: _1broker fetchTickers not supported yet
    at _1broker.fetchTickers (.../node_modules/ccxt/js/base/Exchange.js:407:15)
    at ccxt.exchanges.map.r (.../playground.js:41:6)
    at Array.map (<anonymous>)
    at Object.<anonymous> (.../playground.js:38:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)

Basically, what the library helps me with is:

Make automatic request to different servers

Organize the responses in uniformed objects

Handle most of the errors that are returned by the servers

In my example, the error returned is related with the fact that the server doesn't support the function I'm using. To put it in simpler words:
I make a request that server1 might be able to handle but that server2 isn't able to respond to yet.

The ccxt.exhanges in the code returns an Array of the differents servers that are being handled by the library.

The problem is not so much that I get the error... I'm OK with not getting info back from every server but that my function literaly stops once it gets to the error. The .map loop doesn't go all the way to the end...

ccxt publishes some information on Error Handling but I'm not sure what I can do with it (noob in the place sorry guys).

I hope my question is clear enough and hasn't been already asked!

Thanks in advance for your help!

Body:
Here's a slightly better version of it:

var ccxt = require("ccxt");
ccxt.exchanges.forEach(r => {

    let exchange = new ccxt[r]();

    if (exchange.hasFetchTickers) { // ← the most significant line

        let ticks = exchange
            .fetchTickers()
            .then(res => {
                console.log(res);
            })
            .catch(e => {
                console.log(e);
            });
    }
});


问:
How to write csv file and open in MS.Excel in charset UTF-8
I have detect my value to write is Thai language and I will write to CSV file but when I use fwrite and save .CSV file and open this CSV file in Excel.I see my text about "เธฅเธนเธเธเธฅเธดเนเธ,เธชเธฃเนเธฒเธเธฅเธฒเธข" Below this code

```<code>$xfile =fopen($filename,"w");
foreach( $data as $itm ){
     $outstr="";
     foreach($itm as $key=>$str){
            $val =str_replace("\r\n","",$str);
            val =str_replace("\t\t","",$val);
            $val =str_replace('"',"'",$val);
            $outstr=$outstr.'"'.$val.'"'.$clm;
            //dump(mb_detect_encoding($outstr));die(); --Result UTF-8
     }
$outstr=substr($outstr,0,strlen($outstr)-1);
fwrite($xfile,$outstr."\r\n"); //Newline
fclose($xfile);
</code>```

I feel stupid Or i forgot something. Please help

答:
I use BOM with UTF-8 and insert after value. I see from this link</p>

```<code>$xfile =fopen($filename,"w");
$BOM = "\xEF\xBB\xBF"; // UTF-8 BOM
fwrite($xfile, $BOM);
</code>```

Body:
I have detect my value to write is Thai language and I will write to CSV file but when I use fwrite and save .CSV file and open this CSV file in Excel.I see my text about "เธฅเธนเธเธเธฅเธดเนเธ,เธชเธฃเนเธฒเธเธฅเธฒเธข" Below this code

$xfile =fopen($filename,"w");
foreach( $data as $itm ){
     $outstr="";
     foreach($itm as $key=>$str){
            $val =str_replace("\r\n","",$str);
            val =str_replace("\t\t","",$val);
            $val =str_replace('"',"'",$val);
            $outstr=$outstr.'"'.$val.'"'.$clm;
            //dump(mb_detect_encoding($outstr));die(); --Result UTF-8
     }
$outstr=substr($outstr,0,strlen($outstr)-1);
fwrite($xfile,$outstr."\r\n"); //Newline
fclose($xfile);

I feel stupid Or i forgot something. Please help

Body:
I use BOM with UTF-8 and insert after value. I see from this link

$xfile =fopen($filename,"w");
$BOM = "\xEF\xBB\xBF"; // UTF-8 BOM
fwrite($xfile, $BOM);


问:
How to set character set as "UTF-8" in select statement in Sql server
I am little trouble in my work. I am working on sql server database and I have access only for fetching data from views.

Now, the database contains some information in other language like Ukrainian. So, when I am fetching data using select query and print it on browser then it is showing me question mark (??) instead of actual data.

My query is given below:

    select * from view1;

And the output is something like below:

Please look at the question mark.

Previously I was using the sqlsrv_connect() function to connect with sql server database and this function allows you to set character set (UTF-8) for your work. But the client server is on linux, I have to use mssql_connect() and this function doesn't have any option to set character set.

When I was setting the character set as "UTF-8" then, select query was showing actual data. But, I will do in case of mssql_connect() function.

Is there any collation set to handle this kind of situation? or any other way to change the character set before executing select statement.

Please help me on this issue. I am really frustated. Thanks in Advance

答:
Try to set your database and table collation to utf8_general_ci.
I used that and it displays almost all different kind of languages in my table. But it depends on how much letters and symbols utf8 supports.


问:
Self Referencing Table SQL query
I've table with four columns id, name, designation, manager_id.

Table schema:

```<code>CREATE TABLE "Employee_Information"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    "name" varchar,
    "designation" varchar,
    "manager_id" integer references employee_information(id)
);
</code>```

It is as follows

```<code>ID  Name    Designation   Manager_id
-------------------------------------
1   Raja    CEO
2   Mani    CTO           1
3   Kavi    COO           1
4   Murugan Head          3
5   Alpha   Head(Fin)     4
7   Kannan  Head          4
</code>```

Employee hierarchy is as follows:

```<code>Raja CEO
    Mani CTO
    Kavi COO
               Murugan Head
                       Alpha Head(Fin)
                           Kannan Head
       Beta CFO
       Delta Head
</code>```

I want an SQL query to display all possible manager for particular employee. His Juniors or other sub level employees name are not supposed to be in the results set.

Display all others employees on same level or above.

I'm unable to figure out a solution for this.

答:
Ref: SQLite WITH clause

You need a "Recursive CTE" (common table expression) to traverse the organization hierarchy. Like this:

Query

```<code>WITH RECURSIVE Emp_CTE (ID, Name, Designation, Manager_id, Manager_name)
AS (
    SELECT ID, Name, Designation, Manager_id, cast(NULL as varchar)
    FROM Employee_Information
    WHERE Manager_ID IS NULL
    UNION ALL
        SELECT e.ID, e.Name, e.Designation, e.Manager_id, Emp_CTE.Name
        FROM Employee_Information e
        INNER JOIN Emp_CTE ON Emp_CTE.ID = e.Manager_id
    )
SELECT *
FROM Emp_CTE
</code>```

Result:

```<code>| ID |  Name   | Designation | Manager_id | Manager_name |
|----|---------|-------------|------------|--------------|
|  1 | Raja    | CEO         | null       | null         |
|  3 | Kavi    | COO         | 1          | Raja         |
|  2 | Mani    | CTO         | 1          | Raja         |
|  4 | Murugan | Head        | 3          | Kavi         |
|  5 | Alpha   | Head(Fin)   | 4          | Murugan      |
|  7 | Kannan  | Head        | 4          | Murugan      |
</code>```

Setup:

```<code>CREATE TABLE "Employee_Information" ("id" INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL, "name" varchar, "designation" varchar, "manager_id" integer references employee_information(id));

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (1, 'Raja', 'CEO', NULL)
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (2, 'Mani', 'CTO', '1')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (3, 'Kavi', 'COO', '1')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (4, 'Murugan', 'Head', '3')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (5, 'Alpha', 'Head(Fin)', '4')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (7, 'Kannan', 'Head', '4')
;
</code>```

Demo

Query 2

```<code>WITH RECURSIVE Emp_CTE (ID, Name, Designation, Manager_id, Manager_name, namepath)
AS (
    SELECT ID, Name, Designation, Manager_id, cast(NULL as varchar), name as namepath
    FROM Employee_Information
    WHERE Manager_ID IS NULL
    UNION ALL
        SELECT e.ID, e.Name, e.Designation, e.Manager_id, Emp_CTE.Name
  , Emp_CTE.namepath || '/' || e.Name
        FROM Employee_Information e
        INNER JOIN Emp_CTE ON Emp_CTE.ID = e.Manager_id
    )
SELECT *
FROM Emp_CTE
</code>```

Result:

```<code>| ID |  Name   | Designation | Manager_id | Manager_name |         namepath         |
|----|---------|-------------|------------|--------------|--------------------------|
|  1 | Raja    | CEO         | null       | null         | Raja                     |
|  3 | Kavi    | COO         | 1          | Raja         | Raja/Kavi                |
|  2 | Mani    | CTO         | 1          | Raja         | Raja/Mani                |
|  4 | Murugan | Head        | 3          | Kavi         | Raja/Kavi/Murugan        |
|  5 | Alpha   | Head(Fin)   | 4          | Murugan      | Raja/Kavi/Murugan/Alpha  |
|  7 | Kannan  | Head        | 4          | Murugan      | Raja/Kavi/Murugan/Kannan |
</code>```

Title: Self Referencing Table SQL query

Body:
I've table with four columns id, name, designation, manager_id.

Table schema:

CREATE TABLE "Employee_Information"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    "name" varchar,
    "designation" varchar,
    "manager_id" integer references employee_information(id)
);

It is as follows

ID  Name    Designation   Manager_id
-------------------------------------
1   Raja    CEO
2   Mani    CTO           1
3   Kavi    COO           1
4   Murugan Head          3
5   Alpha   Head(Fin)     4
7   Kannan  Head          4

Employee hierarchy is as follows:

Raja CEO
    Mani CTO
    Kavi COO
               Murugan Head
                       Alpha Head(Fin)
                           Kannan Head
       Beta CFO
       Delta Head

I want an SQL query to display all possible manager for particular employee. His Juniors or other sub level employees name are not supposed to be in the results set.

Display all others employees on same level or above.

I'm unable to figure out a solution for this.

Body:
Ref: SQLite WITH clause

You need a "Recursive CTE" (common table expression) to traverse the organization hierarchy. Like this:

Query

WITH RECURSIVE Emp_CTE (ID, Name, Designation, Manager_id, Manager_name)
AS (
    SELECT ID, Name, Designation, Manager_id, cast(NULL as varchar)
    FROM Employee_Information
    WHERE Manager_ID IS NULL
    UNION ALL
        SELECT e.ID, e.Name, e.Designation, e.Manager_id, Emp_CTE.Name
        FROM Employee_Information e
        INNER JOIN Emp_CTE ON Emp_CTE.ID = e.Manager_id
    )
SELECT *
FROM Emp_CTE

Result:

| ID |  Name   | Designation | Manager_id | Manager_name |
|----|---------|-------------|------------|--------------|
|  1 | Raja    | CEO         | null       | null         |
|  3 | Kavi    | COO         | 1          | Raja         |
|  2 | Mani    | CTO         | 1          | Raja         |
|  4 | Murugan | Head        | 3          | Kavi         |
|  5 | Alpha   | Head(Fin)   | 4          | Murugan      |
|  7 | Kannan  | Head        | 4          | Murugan      |

Setup:

CREATE TABLE "Employee_Information" ("id" INTEGER PRIMARY KEY AUTOINCREMENT
NOT NULL, "name" varchar, "designation" varchar, "manager_id" integer references employee_information(id));

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (1, 'Raja', 'CEO', NULL)
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (2, 'Mani', 'CTO', '1')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (3, 'Kavi', 'COO', '1')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (4, 'Murugan', 'Head', '3')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (5, 'Alpha', 'Head(Fin)', '4')
;

INSERT INTO Employee_Information
    ("ID", "Name", "Designation", "Manager_id")
VALUES
    (7, 'Kannan', 'Head', '4')
;

Demo

Query 2

WITH RECURSIVE Emp_CTE (ID, Name, Designation, Manager_id, Manager_name, namepath)
AS (
    SELECT ID, Name, Designation, Manager_id, cast(NULL as varchar), name as namepath
    FROM Employee_Information
    WHERE Manager_ID IS NULL
    UNION ALL
        SELECT e.ID, e.Name, e.Designation, e.Manager_id, Emp_CTE.Name
  , Emp_CTE.namepath || '/' || e.Name
        FROM Employee_Information e
        INNER JOIN Emp_CTE ON Emp_CTE.ID = e.Manager_id
    )
SELECT *
FROM Emp_CTE

Result:

| ID |  Name   | Designation | Manager_id | Manager_name |         namepath         |
|----|---------|-------------|------------|--------------|--------------------------|
|  1 | Raja    | CEO         | null       | null         | Raja                     |
|  3 | Kavi    | COO         | 1          | Raja         | Raja/Kavi                |
|  2 | Mani    | CTO         | 1          | Raja         | Raja/Mani                |
|  4 | Murugan | Head        | 3          | Kavi         | Raja/Kavi/Murugan        |
|  5 | Alpha   | Head(Fin)   | 4          | Murugan      | Raja/Kavi/Murugan/Alpha  |
|  7 | Kannan  | Head        | 4          | Murugan      | Raja/Kavi/Murugan/Kannan |


问:
Shell script diamond
The question is: Using Shell script programming, create a script that asks the user to enter a number and then prints the following shape. The number of rows is double the columns and user input determine the size of the diamond.

```<code>                *
               * *
              * * *
             * * * *
            * * * * *
           * * * * * *
          * * * * * * *
         * * * * * * * *
          * * * * * * *
           * * * * * *
            * * * * *
             * * * *
              * * *
               * *
                *
</code>```

I've been trying this for days. Any help would bee awesome

Title: Shell script diamond

Body:
The question is: Using Shell script programming, create a script that asks the user to enter a number and then prints the following shape. The number of rows is double the columns and user input determine the size of the diamond.

                *
               * *
              * * *
             * * * *
            * * * * *
           * * * * * *
          * * * * * * *
         * * * * * * * *
          * * * * * * *
           * * * * * *
            * * * * *
             * * * *
              * * *
               * *
                *

I've been trying this for days. Any help would bee awesome

Body:
#!/bin/bash

w=${1-5}
line() { printf "%$(($1+w))s\n" "$(yes "* " | sed ${1}q | tr -d \\n)"; }
for i in $(seq $w) $(seq $((w-1)) -1 1); do line $i; done


问:
Ember JS best way to show a full screen loading screen button press
I'm new with Ember and I would like to show a full screen overlay when a user presses a "get stuff from the server" button.

What is the best way to achieve this?

Does Ember already provide something built-in? Or is it that the only way is to have a piece of HTML in one of my templates, to show/hide it when the promise where I make the AJAX call returns?

答:
You have a few options available to you.

The first concerns a route change.  Conventionally speaking, if the user is hitting a button that transitions to another route, a separate route can be created to handle this in-between loading experience.

To describe this briefly, if you have a route named foo, creating a sibling route named foo-loading with an associated template, will show a "foo-loading" page state while things are being fetched, and then dismiss it once things are good.

Alternatively, as you've hinted, if the call to action for a user intends an updated result on the same route, a loading service could be useful.  In your application template, you could have a loading div that is hidden by default.  Prior to initiating an AJAX request, you could turn the loading state on and reveal the loading div.  Then, once the AJAX call is settled, the finally block could include a call to conceal the loading div.

This latter approach would involve a conditionally loaded block in the primary application template, a loading service handling show and hide, and a loading template.


问:
Trying to concatenate strings and add integers to a sum separately
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected</p>

```<code>l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int
</code>```

答:
"type(i) is 'str'" will never be True.
Try something like isinstance(i, str) instead. Similar for the int check. Actually, type(i) is str will also work. Note that str is not in quotes.

Body:
I posted this earlier and trying to figure out if this works better in terms of presentation. I am trying to concatenate strings and sum the integers from a list separately. For some reason, I am not getting the output I expected

l = ['magical unicorns', 19, 'hello', 98.98, 'world']

comb_str = ''
comb_int = 0

for i in l:
    if type(i) is 'str':
        comb_str = comb_str + 'i'
    elif type(i) is 'int':
        comb_int += i
    else:
        pass

print comb_str
print comb_int


问:
App Crashing after change phone language and relaunch from background
I am developing an android app and facing some strange issue. while App is in background and user change phone language and relaunch app from background then app force stop.

Strange thing is that app crashes only when i change language from english to french but while change from french to english or some other language it will work without any crashing.  below are error log -

Process: com.myapp, PID: 17745
                                                               java.lang.IllegalStateException: Activity has been destroyed
                                                                   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1515)
                                                                   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
                                                                   at android.support.v4.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:621)
                                                                   at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:162)
                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                   at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                   at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                   at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
                                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
                                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
                                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                                                                   at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
                                                                   at android.view.View.measure(View.java:18794)
                                                                   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
                                                                   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                   at android.os.Looper.loop(Looper.java:148)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

答:
This is because when you change the language of the device the new instances of the fragments created, and the app tries to find the new instances.

You need to store your fragments' instance in a List to avoid this type Exception.

If you provide your code where the fragments are added, then it will be more clear .


问:
in which file can I put a script to erase the caches of the Titanium application
I wrote a script that allows you to delete a property in the caches of the application, however I need to run this script only once when I install the application.
someone has an idea, thanks</p>

```<code>var executed = 0;
if(executed === 0){
    Ti.App.Properties.removeProperty("My_Property");
    executed++;
}
</code>```

答:
The only ways you can hold some value across app sessions are Ti.App.Properties or sql database. So you can do it in two ways as below:

Solution 1: Use another property to know that you have deleted the desired property.

```<code>// for first time installation, the default value (or 2nd parameter) will be false as you have not deleted the property yet
var isDeleted = Ti.App.Properties.getBool('My_Property_Deleted', false);

if (isDeleted) {
    Ti.App.Properties.removeProperty("My_Property");

    // since you have deleted it, now set it to true so this 'if' block doesn't runs on any next app session
    Ti.App.Properties.setBool('My_Property_Deleted', true);

} else {
    // you have already deleted the property, 'if' block won't run now
}
</code>```

Solution 2: Create a new database or pre-load a shipped db with your app.

```<code>// Titanium will create it if it doesn't exists, or return a reference to it if it exists (after first call & after app install)
var db = Ti.Database.open('your_db');

// create a new table to store properties states
db.execute('CREATE TABLE IF NOT EXISTS deletedProperties(id INTEGER PRIMARY KEY, property_name TEXT);');

// query the database to know if it contains any row with the desired property name
var result = db.execute('select * from deletedProperties where name=?', "My_Property");

if (result.rowCount == 0) { // means no property exists with such name
    // first delete the desired property
    Ti.App.Properties.removeProperty("My_Property");

    // insert this property name in table so it can be available to let you know you have deleted the desired property
    db.execute('insert into deletedProperties(name) values(?)', "My_Property");

} else {
    // you have already deleted the property, 'if' block won't run now
}

// never forget to close the database after no use of it
db.close();
</code>```

There can be other ways as well, but these 2 will work for what you want. Read more about Ti.Database here

Body:
I wrote a script that allows you to delete a property in the caches of the application, however I need to run this script only once when I install the application.
someone has an idea, thanks

var executed = 0;
if(executed === 0){
    Ti.App.Properties.removeProperty("My_Property");
    executed++;
}

Body:
The only ways you can hold some value across app sessions are Ti.App.Properties or sql database. So you can do it in two ways as below:

Solution 1: Use another property to know that you have deleted the desired property.

// for first time installation, the default value (or 2nd parameter) will be false as you have not deleted the property yet
var isDeleted = Ti.App.Properties.getBool('My_Property_Deleted', false);

if (isDeleted) {
    Ti.App.Properties.removeProperty("My_Property");

    // since you have deleted it, now set it to true so this 'if' block doesn't runs on any next app session
    Ti.App.Properties.setBool('My_Property_Deleted', true);

} else {
    // you have already deleted the property, 'if' block won't run now
}

Solution 2: Create a new database or pre-load a shipped db with your app.

// Titanium will create it if it doesn't exists, or return a reference to it if it exists (after first call & after app install)
var db = Ti.Database.open('your_db');

// create a new table to store properties states
db.execute('CREATE TABLE IF NOT EXISTS deletedProperties(id INTEGER PRIMARY KEY, property_name TEXT);');

// query the database to know if it contains any row with the desired property name
var result = db.execute('select * from deletedProperties where name=?', "My_Property");

if (result.rowCount == 0) { // means no property exists with such name
    // first delete the desired property
    Ti.App.Properties.removeProperty("My_Property");

    // insert this property name in table so it can be available to let you know you have deleted the desired property
    db.execute('insert into deletedProperties(name) values(?)', "My_Property");

} else {
    // you have already deleted the property, 'if' block won't run now
}

// never forget to close the database after no use of it
db.close();

There can be other ways as well, but these 2 will work for what you want. Read more about Ti.Database here


问:
Xamarin C# content page not loading image for Android JVM
I have a problem attempting to load an image for the Android JVM in use on Visual Studio 2017 when debugging. Below is a sample of my code:

```<code>public class ImageDisplayPage : ContentPage
    {
        public ImageDisplayPage()
        {
            Content = new ScrollView
            {
                Content = new StackLayout()
                {
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children =
                    {
                        new Image
                        {
                            IsVisible = true,
                            Aspect = Aspect.AspectFit,
                            Source = ImageSource.FromResource("Resources.a.png")
                        }
                    }
                }
            };
        }
    }
</code>```

I have a folder in my project called "Resources" where the image is supposed to be loaded from, and have followed the path convention used in numerous posts on StackOverFlow and the guide listed here: https://developer.xamarin.com/guides/xamarin-forms/user-interface/images

I use Visual Studio 2017, coding in C# and when I attempt to debug this, the following message is what I get from the debug output:

```<code>Image data was invalid: Xamarin.Forms.StreamImageSource
</code>```

The image in question is an 80kb PNG image.

Thank you in advance for any assistance

答:
You should place your image inside the Resources/drawable folder of your android project and only place the image name and the extension.</p>

```<code>public class ImageDisplayPage : ContentPage
    {
        public ImageDisplayPage()
        {
            Content = new ScrollView
            {
                Content = new StackLayout()
                {
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children =
                    {
                        new Image
                        {
                            IsVisible = true,
                            Aspect = Aspect.AspectFit,
                            Source = "a.png"
                        }
                    }
                }
            };
        }
    }
</code>```

Body:
I have a problem attempting to load an image for the Android JVM in use on Visual Studio 2017 when debugging. Below is a sample of my code:

public class ImageDisplayPage : ContentPage
    {
        public ImageDisplayPage()
        {
            Content = new ScrollView
            {
                Content = new StackLayout()
                {
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children =
                    {
                        new Image
                        {
                            IsVisible = true,
                            Aspect = Aspect.AspectFit,
                            Source = ImageSource.FromResource("Resources.a.png")
                        }
                    }
                }
            };
        }
    }

I have a folder in my project called "Resources" where the image is supposed to be loaded from, and have followed the path convention used in numerous posts on StackOverFlow and the guide listed here: https://developer.xamarin.com/guides/xamarin-forms/user-interface/images

I use Visual Studio 2017, coding in C# and when I attempt to debug this, the following message is what I get from the debug output:

Image data was invalid: Xamarin.Forms.StreamImageSource

The image in question is an 80kb PNG image.

Thank you in advance for any assistance

Body:
You should place your image inside the Resources/drawable folder of your android project and only place the image name and the extension.

public class ImageDisplayPage : ContentPage
    {
        public ImageDisplayPage()
        {
            Content = new ScrollView
            {
                Content = new StackLayout()
                {
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children =
                    {
                        new Image
                        {
                            IsVisible = true,
                            Aspect = Aspect.AspectFit,
                            Source = "a.png"
                        }
                    }
                }
            };
        }
    }


问:
Add copy constructor based on template parameters
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

```<code>template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};
</code>```

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

```<code>// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};
</code>```

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

答:
Can't you use a base class to selectively disable copying? That way you don't need to repeat any of the other functionality of the main class:

```<code>template <bool b>
struct MaybeCopyable {};

template <>
struct MaybeCopyable<false> {
    MaybeCopyable(const MaybeCopyable&) = delete;
    MaybeCopyable& operator=(const MaybeCopyable&) = delete;
};

template<bool IsCopyable>
struct Foo : MaybeCopyable<IsCopyable> {
    // other functionality
};
</code>```

If MaybeCopyable<false> is one of the base classes, the copy constructor of  Foo will be automatically deleted.

Body:
I have a container-like class, that I would like to be move-only if the underlying type is move-only, but copyable otherwise. To make things simple, let's assume copyability is determined by a single bool template parameter:

template<bool IsCopyable>
struct Foo
{
    Foo();
    Foo(const Foo&);    // only include this when IsCopyable is true
    Foo(Foo&&);

    Foo& operator=(const Foo&);  // only when IsCopyable
    Foo& operator=(Foo&&);
};

Now, I can't just SFINAE the copy ctor away, because that requires making it templated and a templated function can't be a copy ctor. Also, I can't just do a static_assert() within the copy ctor. Although this will catch erroneous uses of the copy ctor, it also makes the class inherently copy constructible from the outside (the std::is_copy_constructible type trait will yield true).

By the way, an unfortunate requirement is that it needs to compile in VC++ 2012, so I can't use fancy expression SFINAE, inheriting ctors, defaulted/deleted functions or constexpr if (nevertheless, if you have a neat solution for C++17 I'd still like to hear it :))

The obvious method is to use template specialization. I'd rather not go this route, because in reality Foo has quite a lot of functionality and I don't like to repeat myself. Nevertheless, this seems my only option, and I can implement some code sharing using a base class, like so:

// Base functionality
template<bool IsCopyable>
struct FooBase
{
    FooBase();

    // move ctor and assignment can go here
    FooBase(FooBase&&);
    FooBase& operator=(FooBase&&);

    // some generic conversion ctor and assignment that I happen to need
    template<class T> FooBase(T&& t);
    template<class T> FooBase& operator=(T&&);

    // ... all sorts of functionality and datamembers
};

// Foo<false>
template<bool IsCopyable>
struct Foo : FooBase<IsCopyable>
{
    // can't use inheriting ctors in VS 2012, wrap the calls manually:
    Foo() { }
    Foo(Foo&& other) : FooBase<IsCopyable>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<IsCopyable>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<IsCopyable>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<IsCopyable>::operator=(std::forward<T>(t));
        return *this;
    }
};

// Foo<true>
template<>
struct Foo<true> : FooBase<true>
{
    // add these
    Foo(const Foo&);
    Foo& operator=(const Foo&);

    // wrapping calls because of VS 2012:
    Foo() { }
    Foo(Foo&& other) : FooBase<true>(std::move(other)) { }
    Foo& operator=(Foo&& other)
    {
        FooBase<true>::operator=(std::move(other));
        return *this;
    }

    template<class T> Foo(T&& t) : FooBase<true>(std::forward<T>(t)) { }
    template<class T> Foo& operator=(T&& t)
    {
        FooBase<true>::operator=(std::forward<T>(t));
        return *this;
    }
};

It's still a bit verbose. Fortunately it gets cleaner once you can use inheriting ctors and defaulted functions. Nevertheless, I was hoping there is a simpler way, ideally by not using a base class.

Body:
Can't you use a base class to selectively disable copying? That way you don't need to repeat any of the other functionality of the main class:

template <bool b>
struct MaybeCopyable {};

template <>
struct MaybeCopyable<false> {
    MaybeCopyable(const MaybeCopyable&) = delete;
    MaybeCopyable& operator=(const MaybeCopyable&) = delete;
};

template<bool IsCopyable>
struct Foo : MaybeCopyable<IsCopyable> {
    // other functionality
};

If MaybeCopyable<false> is one of the base classes, the copy constructor of  Foo will be automatically deleted.


问:
sync/atomic StoreInt32 strange behavior
This code is simplified and describes my problem. It seems that atomic.StoreInt32 not work but I'm not sure why.

```<code>package main
import (
    "fmt"
    "sync/atomic"
)

type slave struct {
    failed int32
}
func NewSlave() slave {
    return slave{0}
}
func (worker slave) Fail() {
    atomic.StoreInt32(&worker.failed, 1) // Here's the problem.
}
func (worker slave) IsFailed() bool {
    failed := atomic.LoadInt32(&worker.failed) == 1
    return failed
}
func (worker slave) FailureReset() {
    atomic.StoreInt32(&worker.failed, 0)
}

func main() {
    s := NewSlave()
    fmt.Println(s.IsFailed())
    s.Fail()
    fmt.Println(s.IsFailed())
    s.FailureReset()
    fmt.Println(s.IsFailed())
}
</code>```

->output:

```<code>false 0
false 0
false 0
</code>```

->tested on:

```<code>recolic@RECOLICPC ~/tmp> go version
go version go1.9.2 linux/amd64
recolic@RECOLICPC ~/tmp> uname -a
Linux RECOLICPC 4.13.12-1-ARCH #1 SMP PREEMPT Wed Nov 8 11:54:06 CET 2017 x86_64 GNU/Linux
</code>```

I've read: usage golang atomic LoadInt32/StoreInt32 (64)

答:
You need to make your methods take a pointer receiver. As written, the functions are operating on a copy of your worker, so the worker used to invoke the method is not changed. Define the methods like this:</p>

```<code>func (worker *slave) Fail() {
    // ...
}
</code>```

Title: sync/atomic StoreInt32 strange behavior

Body:
This code is simplified and describes my problem. It seems that atomic.StoreInt32 not work but I'm not sure why.

package main
import (
    "fmt"
    "sync/atomic"
)

type slave struct {
    failed int32
}
func NewSlave() slave {
    return slave{0}
}
func (worker slave) Fail() {
    atomic.StoreInt32(&worker.failed, 1) // Here's the problem.
}
func (worker slave) IsFailed() bool {
    failed := atomic.LoadInt32(&worker.failed) == 1
    return failed
}
func (worker slave) FailureReset() {
    atomic.StoreInt32(&worker.failed, 0)
}

func main() {
    s := NewSlave()
    fmt.Println(s.IsFailed())
    s.Fail()
    fmt.Println(s.IsFailed())
    s.FailureReset()
    fmt.Println(s.IsFailed())
}

->output:

false 0
false 0
false 0

->tested on:

recolic@RECOLICPC ~/tmp> go version
go version go1.9.2 linux/amd64
recolic@RECOLICPC ~/tmp> uname -a
Linux RECOLICPC 4.13.12-1-ARCH #1 SMP PREEMPT Wed Nov 8 11:54:06 CET 2017 x86_64 GNU/Linux

I've read: usage golang atomic LoadInt32/StoreInt32 (64)

Body:
You need to make your methods take a pointer receiver. As written, the functions are operating on a copy of your worker, so the worker used to invoke the method is not changed. Define the methods like this:

func (worker *slave) Fail() {
    // ...
}


问:
Arduino : avrdude: stk500_recv(): programmer is not responding
I'm currently trying to make Controlling an RGB LED With an Android Smartphone Using Arduino and Bluetooth Module. As in below link tutorial.

http://www.instructables.com/id/Controlling-an-RGB-LED-With-an-Android-Smartphone-/

I'm using Arduino Uno.
I made as in tutorial and code and upload to Arduino then It's Show as below Error Messages and cannot upload to Arduino.

```<code>avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/Applications/Arduino.app/
     Contents/Java/hardware/tools/avr/etc/avrdude.conf"

     User configuration file is "/Users/kyawzinwai/.avrduderc"
     User configuration file does not exist or is not a regular file,
     skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 1 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 2 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 3 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 4 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 5 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 6 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 7 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 8 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 9 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 10 of 10: not in sync:
     resp=0x00

     avrdude done.  Thank you.

     Problem uploading to board.  See
     http://www.arduino.cc/en/Guide/Troubleshooting#upload for
     suggestions.
</code>```

答: Finally I can solve the problem. Remove all wire from Arduino Dev Board and Just upload the sketch only to the dev board and when upload done. Reconnect all the wires again and Done.</p>

Body:
I'm currently trying to make Controlling an RGB LED With an Android Smartphone Using Arduino and Bluetooth Module. As in below link tutorial.

http://www.instructables.com/id/Controlling-an-RGB-LED-With-an-Android-Smartphone-/

I'm using Arduino Uno.
I made as in tutorial and code and upload to Arduino then It's Show as below Error Messages and cannot upload to Arduino.

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "/Applications/Arduino.app/
     Contents/Java/hardware/tools/avr/etc/avrdude.conf"

     User configuration file is "/Users/kyawzinwai/.avrduderc"
     User configuration file does not exist or is not a regular file,
     skipping

     Using Port                    : /dev/cu.usbmodem1421
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 1 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 2 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 3 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 4 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 5 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 6 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 7 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 8 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 9 of 10: not in sync:
     resp=0x00
     avrdude: stk500_recv(): programmer is not responding
     avrdude: stk500_getsync() attempt 10 of 10: not in sync:
     resp=0x00

     avrdude done.  Thank you.

     Problem uploading to board.  See
     http://www.arduino.cc/en/Guide/Troubleshooting#upload for
     suggestions.


问:
Is this jQuery statement a mistake: "$( "#content" ).find("h3").eq(2).html("").end()" selectects all h3's?
According to the jQuery tutorial:

jQuery also provides the .end() method to get back to the original
selection should you change the selection in the middle of a chain:

```<code>$( "#content" )
    .find( "h3" )
    .eq( 2 )
        .html( "new text for the third h3!" )
        .end() // Restores the selection to all h3s in #content
    .eq( 0 )
        .html( "new text for the first h3!" );
</code>```

Note the comments

Restores the selection to all h3s in #content

According to the API and Stackoverflow end() resets back to content id selection before the h3's are selected.

Is this just wrong or has jQuery changed the behaviour since this was written. Should I open a pull request?

答:
No it's not a mistake.

.end() undoes the previous selection change, which was .eq(2), therefore back to the same selection returned by .find('h3').

It's maybe easier to understand the example with better line-breaks/indentation/comments

```<code>$("#content") // level 0 - original selection
.find("h3") // level 1 - change of selection
.eq(2) // level 2 - change of selection
.html( "new text for the third h3!" ) // action, but no change of selection
.end() // back to level 1 from level 2
.eq(0) // level2 - chage of selection
.html("new text for the first h3!");  // action, but no change of selection
</code>```

In your other examples (from comments below):

```<code>$("body") // level 0 - original selection
.find("span") // level 1 - change of selection
.css("border", "2px red solid"); // no change of selection - css applies to span

$("body") // level 0 - original selection
.find("span") // level 1 - change of selection
.end() // back to level 0 from level 1
.css("border", "2px red solid"); // no change of selection - css applies to body
</code>```

In the last example, .end() immediately nullifies the effect of .find('span') with no action in between on the spans.

Body:
According to the jQuery tutorial:

jQuery also provides the .end() method to get back to the original
selection should you change the selection in the middle of a chain:

$( "#content" )
    .find( "h3" )
    .eq( 2 )
        .html( "new text for the third h3!" )
        .end() // Restores the selection to all h3s in #content
    .eq( 0 )
        .html( "new text for the first h3!" );

Note the comments

Restores the selection to all h3s in #content

According to the API and Stackoverflow end() resets back to content id selection before the h3's are selected.

Is this just wrong or has jQuery changed the behaviour since this was written. Should I open a pull request?

Body:
No it's not a mistake.

.end() undoes the previous selection change, which was .eq(2), therefore back to the same selection returned by .find('h3').

It's maybe easier to understand the example with better line-breaks/indentation/comments

$("#content") // level 0 - original selection
.find("h3") // level 1 - change of selection
.eq(2) // level 2 - change of selection
.html( "new text for the third h3!" ) // action, but no change of selection
.end() // back to level 1 from level 2
.eq(0) // level2 - chage of selection
.html("new text for the first h3!");  // action, but no change of selection

In your other examples (from comments below):

$("body") // level 0 - original selection
.find("span") // level 1 - change of selection
.css("border", "2px red solid"); // no change of selection - css applies to span

$("body") // level 0 - original selection
.find("span") // level 1 - change of selection
.end() // back to level 0 from level 1
.css("border", "2px red solid"); // no change of selection - css applies to body

In the last example, .end() immediately nullifies the effect of .find('span') with no action in between on the spans.