问:
wireshark lua string:byte() error
I have a string problem when writing my lua dissector. My packet looks like:

```<code>0000   00 00 00 69 00 10 00 01 00 00 00 ed 00 00 00 0c
0010   bf a6 5f ...
</code>```

When debugging, the tvb looks the same

The byte at offset 0x10 is 0xbf, but in my dissector function I got different result, here' my code:

```<code>local str = buf(0x10):string()
local x = string.byte(str, 1)
</code>```

the variable x should be 0xbf, but it's 0xef, and some other offset are also 0xef:

```<code>local str = buf(0x11):string()
local x = string.byte(str, 1) -- also get 0xef, should be 0xa6

local str = buf(11):string()
local x = string.byte(str, 1) -- also get 0xef, should be 0xed
</code>```

Seems big values will always get 0xef as result, like 0xa6/0xbf/0xed...

And small values will be correct, like 0x69/0x5f/0x0c...

I'm using the latest wireshark 2.0, is this a bug?

答:
Assuming that buf refers to the parameter passed to your dissection routine, it is of type Tvb. When you call it (as in, buf(0x10)), you create a TvbRange instance. Both of them are documented here:
https://www.wireshark.org/docs/wsdg_html_chunked/lua_module_Tvb.html

tehtmi is spot on about the reason why you obtain the wrong results, tvbrange:string() returns a string using the ASCII encoding (since the encoding parameter was omitted).

A way to obtain the raw bytes buffer (rather than converting it to a ASCII or UTF-8 string) is:

```<code>local x = buf:raw(0x10, 1)
</code>```

(Using offset 16 and length 1.)

If you ever think about using buf(0x10):raw() directly, note that for some reason this would return the full data source that is backing this Tvb. Maybe a bug or feature... Workaround:

```<code>local bytes = buf(0x10)
local x = bytes:raw(bytes:offset(), bytes:len())
</code>```

Title: wireshark lua string:byte() error

Body:
I have a string problem when writing my lua dissector. My packet looks like:

0000   00 00 00 69 00 10 00 01 00 00 00 ed 00 00 00 0c
0010   bf a6 5f ...

When debugging, the tvb looks the same

The byte at offset 0x10 is 0xbf, but in my dissector function I got different result, here' my code:

local str = buf(0x10):string()
local x = string.byte(str, 1)

the variable x should be 0xbf, but it's 0xef, and some other offset are also 0xef:

local str = buf(0x11):string()
local x = string.byte(str, 1) -- also get 0xef, should be 0xa6

local str = buf(11):string()
local x = string.byte(str, 1) -- also get 0xef, should be 0xed

Seems big values will always get 0xef as result, like 0xa6/0xbf/0xed...

And small values will be correct, like 0x69/0x5f/0x0c...

I'm using the latest wireshark 2.0, is this a bug?

Body:
Assuming that buf refers to the parameter passed to your dissection routine, it is of type Tvb. When you call it (as in, buf(0x10)), you create a TvbRange instance. Both of them are documented here:
https://www.wireshark.org/docs/wsdg_html_chunked/lua_module_Tvb.html

tehtmi is spot on about the reason why you obtain the wrong results, tvbrange:string() returns a string using the ASCII encoding (since the encoding parameter was omitted).

A way to obtain the raw bytes buffer (rather than converting it to a ASCII or UTF-8 string) is:

local x = buf:raw(0x10, 1)

(Using offset 16 and length 1.)

If you ever think about using buf(0x10):raw() directly, note that for some reason this would return the full data source that is backing this Tvb. Maybe a bug or feature... Workaround:

local bytes = buf(0x10)
local x = bytes:raw(bytes:offset(), bytes:len())


来源: stackexchange

问:
Android- How to create 4 square buttons in one row with icons on top of them?
Im trying to create an app which will have 4 square buttons in one row with an icon on top of these buttons. Which is the best way to approach this? I'm trying to do something like this as shown in the image

Thank You

答: Thanks for the solutions everyone. The image i posted was edited on photoshop. Now I did it in android studio using linear layout

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
10401 Order total is invalid ASP.NET C#
I am writing a shop app using ASP.NET(Web-Form) and WingtipToys tutorial from msdn.

I have a problem when I am using paypal button. I have error:

```<code>10401
Transaction refused because of an invalid argument. See additional error messages for details.
Order total is invalid.
</code>```

This is part of code where's something wrong i think:

```<code>public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
{
    if (bSandbox)
    {
        pEndPointURL = pEndPointURL_SB;
        host = host_SB;
    }

    string returnURL = "https://localhost:44317/Checkout/CheckoutReview.aspx";
    string cancelURL = "https://localhost:44317/Checkout/CheckoutCancel.aspx";

    NVPCodec encoder = new NVPCodec();
    encoder["METHOD"] = "SetExpressCheckout";
    encoder["RETURNURL"] = returnURL;
    encoder["CANCELURL"] = cancelURL;
    encoder["BRANDNAME"] = "Shop";
    encoder["PAYMENTREQUEST_0_AMT"] = amt;
    encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
    encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
    encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "PLN";

    // Get the Shopping Cart Products
    using (Shop.Logic.ShoppingCartActions myCartOrders = new Shop.Logic.ShoppingCartActions())
    {
        List<ElementKoszyka> myOrderList = myCartOrders.GetCartItems();

        for (int i = 0; i < myOrderList.Count; i++)
        {
            encoder["L_PAYMENTREQUEST_0_NAME" + i] = myOrderList[i].Produkt.nazwa_produkt.ToString();
           // string tmp = Math.Round(myOrderList[i].Produkt.cena, 2).ToString();
           // encoder["L_PAYMENTREQUEST_0_AMT" + i] = Math.Round(myOrderList[i].Produkt.cena, 2).ToString();
            encoder["L_PAYMENTREQUEST_0_AMT" + i] = "22.50";
            encoder["L_PAYMENTREQUEST_0_QTY" + i] = myOrderList[i].ilosc.ToString();
        }
    }

    string pStrrequestforNvp = encoder.Encode();
    string pStresponsenvp = HttpCall(pStrrequestforNvp);

    NVPCodec decoder = new NVPCodec();
    decoder.Decode(pStresponsenvp);

    string strAck = decoder["ACK"].ToLower();
    if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
    {
        token = decoder["TOKEN"];
        string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
        retMsg = ECURL;
        return true;
    }
    else
    {
        retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
            "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
            "Desc2=" + decoder["L_LONGMESSAGE0"];
        return false;
    }
}
</code>```

Total order is assign permanently (22.50) and still have a problem.

Any tips?

答:
If your computer uses the decimal komma then you should change your assignment to:</p>

```<code>encoder["L_PAYMENTREQUEST_0_AMT" + i] = (myOrderList[i].Produkt.nazwa_price.ToString()).Replace(",",".");
</code>```

Title: 10401 Order total is invalid ASP.NET C#

Body:
I am writing a shop app using ASP.NET(Web-Form) and WingtipToys tutorial from msdn.

I have a problem when I am using paypal button. I have error:

10401
Transaction refused because of an invalid argument. See additional error messages for details.
Order total is invalid.

This is part of code where's something wrong i think:

public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
{
    if (bSandbox)
    {
        pEndPointURL = pEndPointURL_SB;
        host = host_SB;
    }

    string returnURL = "https://localhost:44317/Checkout/CheckoutReview.aspx";
    string cancelURL = "https://localhost:44317/Checkout/CheckoutCancel.aspx";

    NVPCodec encoder = new NVPCodec();
    encoder["METHOD"] = "SetExpressCheckout";
    encoder["RETURNURL"] = returnURL;
    encoder["CANCELURL"] = cancelURL;
    encoder["BRANDNAME"] = "Shop";
    encoder["PAYMENTREQUEST_0_AMT"] = amt;
    encoder["PAYMENTREQUEST_0_ITEMAMT"] = amt;
    encoder["PAYMENTREQUEST_0_PAYMENTACTION"] = "Sale";
    encoder["PAYMENTREQUEST_0_CURRENCYCODE"] = "PLN";

    // Get the Shopping Cart Products
    using (Shop.Logic.ShoppingCartActions myCartOrders = new Shop.Logic.ShoppingCartActions())
    {
        List<ElementKoszyka> myOrderList = myCartOrders.GetCartItems();

        for (int i = 0; i < myOrderList.Count; i++)
        {
            encoder["L_PAYMENTREQUEST_0_NAME" + i] = myOrderList[i].Produkt.nazwa_produkt.ToString();
           // string tmp = Math.Round(myOrderList[i].Produkt.cena, 2).ToString();
           // encoder["L_PAYMENTREQUEST_0_AMT" + i] = Math.Round(myOrderList[i].Produkt.cena, 2).ToString();
            encoder["L_PAYMENTREQUEST_0_AMT" + i] = "22.50";
            encoder["L_PAYMENTREQUEST_0_QTY" + i] = myOrderList[i].ilosc.ToString();
        }
    }

    string pStrrequestforNvp = encoder.Encode();
    string pStresponsenvp = HttpCall(pStrrequestforNvp);

    NVPCodec decoder = new NVPCodec();
    decoder.Decode(pStresponsenvp);

    string strAck = decoder["ACK"].ToLower();
    if (strAck != null && (strAck == "success" || strAck == "successwithwarning"))
    {
        token = decoder["TOKEN"];
        string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout" + "&token=" + token;
        retMsg = ECURL;
        return true;
    }
    else
    {
        retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
            "Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
            "Desc2=" + decoder["L_LONGMESSAGE0"];
        return false;
    }
}

Total order is assign permanently (22.50) and still have a problem.

Any tips?

Body:
If your computer uses the decimal komma then you should change your assignment to:

encoder["L_PAYMENTREQUEST_0_AMT" + i] = (myOrderList[i].Produkt.nazwa_price.ToString()).Replace(",",".");


问:
htmlentities() returns empty values despite UTF-8
So I'm trying to escape a string in PHP using htmlentities().

Problem is, htmlentities returns an empty string.

I'm receiving this string through an html <form>. The page containing the form tag has the following meta tag : <meta charset="utf-8">

My string is encoded in UTF-8, htmlentites() third parameters is 'UTF-8' and I still get an empty string.

Here is my code :

```<code>$str = strtolower(trim($str));
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
</code>```

And here is what var_dump displays :

```<code>// Original string is é-è
// Expected output is é-è
string '�-�' (length=5) // Original string but why is the length 5 ?
string 'UTF-8' (length=5)
string '' (length=0)
string '' (length=0)
string 'ã©-ã¨' (length=28) // WTF ??
</code>```

Anyone know where it's coming from ?

答:
Ok I found out what was wrong.
strtolower is causing the problem.

Please use mb_strtolower

```<code>var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
$str = trim($str);
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
$str = strtolower($str);
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
</code>```

Here is the output :

```<code>// raw string é-è
string 'é-è' (length=5)
string 'UTF-8' (length=5)
string 'é-è' (length=17)
string 'é-è' (length=17)
string 'Ã©-Ã¨' (length=28)
// trim('é-è')
string 'é-è' (length=5)
string 'UTF-8' (length=5)
string 'é-è' (length=17)
string 'é-è' (length=17)
string 'Ã©-Ã¨' (length=28)
// strtolower('é-è')
string '�-�' (length=5)
string 'UTF-8' (length=5)
string '' (length=0)
string '' (length=0)
string 'ã©-ã¨' (length=28)
</code>```

Somehow, strtolower() seems to work only in 'ISO-8859-1', and as you can see in the var_dumps, it transforms Ã into ã

Body:
So I'm trying to escape a string in PHP using htmlentities().

Problem is, htmlentities returns an empty string.

I'm receiving this string through an html <form>. The page containing the form tag has the following meta tag : <meta charset="utf-8">

My string is encoded in UTF-8, htmlentites() third parameters is 'UTF-8' and I still get an empty string.

Here is my code :

$str = strtolower(trim($str));
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));

And here is what var_dump displays :

// Original string is é-è
// Expected output is é-è
string '�-�' (length=5) // Original string but why is the length 5 ?
string 'UTF-8' (length=5)
string '' (length=0)
string '' (length=0)
string 'ã©-ã¨' (length=28) // WTF ??

Anyone know where it's coming from ?

Body:
Ok I found out what was wrong.
strtolower is causing the problem.

Please use mb_strtolower

var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
$str = trim($str);
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));
$str = strtolower($str);
var_dump($str, mb_detect_encoding($str), htmlentities($str), htmlentities($str, ENT_COMPAT, 'UTF-8'), htmlentities($str, ENT_COMPAT, 'ISO-8859-1'));

Here is the output :

// raw string é-è
string 'é-è' (length=5)
string 'UTF-8' (length=5)
string '&eacute;-&egrave;' (length=17)
string '&eacute;-&egrave;' (length=17)
string '&Atilde;&copy;-&Atilde;&uml;' (length=28)
// trim('é-è')
string 'é-è' (length=5)
string 'UTF-8' (length=5)
string '&eacute;-&egrave;' (length=17)
string '&eacute;-&egrave;' (length=17)
string '&Atilde;&copy;-&Atilde;&uml;' (length=28)
// strtolower('é-è')
string '�-�' (length=5)
string 'UTF-8' (length=5)
string '' (length=0)
string '' (length=0)
string '&atilde;&copy;-&atilde;&uml;' (length=28)

Somehow, strtolower() seems to work only in 'ISO-8859-1', and as you can see in the var_dumps, it transforms &Atilde; into &atilde;


问:
SelectListItem properties in view model are not passed back from view to controller
I have this View Model:

```<code>public class UserViewModel
{
    public string ID { get; set; }

    [Required]
    [Display(Name = "Nombre")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Login")]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Contraseña")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-mail")]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Teléfono")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Ciudad")]
    public System.Web.Mvc.SelectListItem City { get; set; }

    [Display(Name = "Empresas")]
    public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }

    [Required]
    [Display(Name = "Perfil")]
    public string Role { get; set; }

    [Display(Name = "Está Vigente")]
    public bool Vigente { get; set; }
}
</code>```

the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:

```<code>    public JsonResult EditUser(UserViewModel model)
    {
          .....
    }
</code>```

Only other properties are passed.

What is the right way to manage this?

EDIT:

this is part of the view:

```<code>            @using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { @class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
            {
                var id = Model == null ? String.Empty : Model.ID;
                <div class="errores col-md-12 col-sm-12 col-xs-12" style="display: none">
                    <div class='validation-summary-errors alert alert-danger alert-white rounded' data-valmsg-summary="true">
                        <div class="icon">
                            <i class="fa fa-times-circle"></i>
                        </div>
                        <p>Debe completar los campos marcados en forma correcta.</p>
                    </div>
                </div>
                @Html.AntiForgeryToken();
                <input type="hidden" value="@id" id="id" name="id" />
                <div class="item col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Nombre, new { @class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })
                    <span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
                </div>
                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Login, new { @class = "form-control has-feedback-left", placeholder = "Login", required = "required" })
                    <span class="fa fa-sign-in form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @{
                        //var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
                        var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
                        object htmlAttributes = null;
                        if (requerido)
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
                        }
                        else
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña" };
                        }
                    }
                    <!-- Para evitar que los password managers llenen los campos -->
                    <input type="text" id="hidUser" style="display: none" />
                    <!-- Para evitar que los password managers llenen los campos -->
                    <input type="password" id="hidPassword" style="display: none" />

                    @Html.PasswordFor(m => m.Password, htmlAttributes)
                    <span class="fa fa-key form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })
                    <span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control has-feedback-left", placeholder = "Teléfono" })
                    <span class="fa fa-phone form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    Está Vigente
                    @Html.CheckBoxFor(m => m.Vigente, new { @class = "flat" })
                </div>
            }
</code>```

答:
Please change the type of City Property in UserViewModal

```<code> public string City { get; set; }
</code>```

Then it will return selected option value to controller for e.g

```<code><select
 <option value="1">Delhi </option>
 <option value="2">Surat </option>
</select>
</code>```

if you select Delhi then it will assign value 1 to property

Body:
I have this View Model:

public class UserViewModel
{
    public string ID { get; set; }

    [Required]
    [Display(Name = "Nombre")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Login")]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Contraseña")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-mail")]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Teléfono")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Ciudad")]
    public System.Web.Mvc.SelectListItem City { get; set; }

    [Display(Name = "Empresas")]
    public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }

    [Required]
    [Display(Name = "Perfil")]
    public string Role { get; set; }

    [Display(Name = "Está Vigente")]
    public bool Vigente { get; set; }
}

the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:

    public JsonResult EditUser(UserViewModel model)
    {
          .....
    }

Only other properties are passed.

What is the right way to manage this?

EDIT:

this is part of the view:

            @using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { @class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
            {
                var id = Model == null ? String.Empty : Model.ID;

Debe completar los campos marcados en forma correcta.

                @Html.AntiForgeryToken();
                <input type="hidden" value="@id" id="id" name="id" />

                    @Html.TextBoxFor(m => m.Nombre, new { @class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })

                    @Html.TextBoxFor(m => m.Login, new { @class = "form-control has-feedback-left", placeholder = "Login", required = "required" })

                    @{
                        //var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
                        var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
                        object htmlAttributes = null;
                        if (requerido)
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
                        }
                        else
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña" };
                        }
                    }

                    <input type="text" id="hidUser" style="display: none" />

                    <input type="password" id="hidPassword" style="display: none" />

                    @Html.PasswordFor(m => m.Password, htmlAttributes)

                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })

                    @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control has-feedback-left", placeholder = "Teléfono" })

                    @Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })

                    @Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })

                    @Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })

                    Está Vigente
                    @Html.CheckBoxFor(m => m.Vigente, new { @class = "flat" })

            }

Body:
Please change the type of City Property in UserViewModal

 public string City { get; set; }

Then it will return selected option value to controller for e.g

<select
 <option value="1">Delhi </option>
 <option value="2">Surat </option>
</select>

if you select Delhi then it will assign value 1 to property


问:
Python: Assign the value of an undefined (but necessary) variable in a python script, from another script
I was wondering if there is a way of doing the following:

I have a program, call it a.py. Here there are some functions and stuff. For some of these functions, there is a variable (is part of the settings of the functions, let's say), call it myvar. This variable is not an argument of them, just a setting! So for instance

def myfunc(arg1, arg2):
         return arg1*arg2 - myvar
This variable hasn't been defined in the program a.py.

Now I want to create another program b.py, here I want to use the output of the above program, but each time I need to change the value of the variable. Something like

import a
list1 = []
for j in range(10):
        myvar = j
        list1.append(a.myfunc(arg1, arg2))

I hope what I want to do is clear. Is there a way to do it?

答:
If you just set a.myvar from b you should be fine. For example:

```<code>a.py
----------------
test = 10

def foo():
    print(test)

b.py
----------------
import a

a.foo()
a.test = 100
a.foo()
</code>```

will output

```<code>10
100
</code>```

Note: Except for very niche applications, you should not be doing this and should very likely be using a function parameter.

Body:
If you just set a.myvar from b you should be fine. For example:

a.py
----------------
test = 10

def foo():
    print(test)

b.py
----------------
import a

a.foo()
a.test = 100
a.foo()

will output

10
100

Note: Except for very niche applications, you should not be doing this and should very likely be using a function parameter.


问:
Connection Strings in the Code and Continuous Deployment
I am trying to setup connection string is my Azure resource deployment project. Which will be triggered via Octopus.We would like to have a clean system with every deployment. We want to accomplish Continuous deployment.  The projects should cope with changes.And the system should be ready for blue green deployments ?

I am thinking about

I.Using a load balancer and configurations point to the load balancer with the connection strings.

II.Have a different database names at every deployment so every resource is unique every time.

What are the challanges I would face ? Do I have to have a tool like ZooKeeper?

Project Structure by TYPE using Azure Resource Project

Parameters & variables focusing to keep them less than 20

答:
I would advise the use of Jenkins in this scenario to achieve continuous deployment. I have implemented this successfully.

There is a feature called poll SCM. This will cause a build when you have a new commit.

After the build, you can use the tool octo.exe to create a release and deploy that release to your specific environment.

I use the following code to create and deploy the release:

Create Release:

```<code>octo.exe create-release --project=%Environment% --server %Server% --apiKey %APIKEY% --version %version% --packageversion %version%
</code>```

My variables are defined at a higher level to provide loose coupling:

%Environment%: Octopus Environment
%Server%: Octopus Server
%APIKEY%: API Key
%Timeout%: Timeout expiry

Deploy Release:

```<code>octo.exe deploy-release --project %Environment% --releaseNumber %version% --deployto %Environment% --server %Server% --apiKey %APIKEY% --progress --deploymenttimeout %Timeout%
</code>```

Jenkins is very flexible and helps a lot in Continuous Deployment. You can have different jobs:

one for green and one for blue

After green is completed, you can trigger one for blue. As for database changes, you can use powershell together with sql cmd to alter your database and/or execute scripts.

Body:
I would advise the use of Jenkins in this scenario to achieve continuous deployment. I have implemented this successfully.

There is a feature called poll SCM. This will cause a build when you have a new commit.

After the build, you can use the tool octo.exe to create a release and deploy that release to your specific environment.

I use the following code to create and deploy the release:

Create Release:

octo.exe create-release --project=%Environment% --server %Server% --apiKey %APIKEY% --version %version% --packageversion %version%

My variables are defined at a higher level to provide loose coupling:

%Environment%: Octopus Environment
%Server%: Octopus Server
%APIKEY%: API Key
%Timeout%: Timeout expiry

Deploy Release:

octo.exe deploy-release --project %Environment% --releaseNumber %version% --deployto %Environment% --server %Server% --apiKey %APIKEY% --progress --deploymenttimeout %Timeout%

Jenkins is very flexible and helps a lot in Continuous Deployment. You can have different jobs:

one for green and one for blue

After green is completed, you can trigger one for blue. As for database changes, you can use powershell together with sql cmd to alter your database and/or execute scripts.


问:
Angular / AngularFire - Merging the Firebase authentication into angular
Firebase provides a great pre built authentication system for email and password. They have posted the sample here: https://github.com/firebase/quickstart-js/tree/master/auth

What I'm struggling to understand is how to integrate this into an Angular/AngularFire application.

Could I copy and paste this into a 'login.component.html/ts' file?

As a standalone solution the code firebase have provided looks great and works really well. It would be fantastic to drop this into an Angular solution if at all possible. An example of the code is provided below. Any help would be fantastically appreciated.

Email Authentication Code provided by Firebase

<!DOCTYPE html>

    <meta charset=utf-8 />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email/Password Authentication Example</title>

    <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <link rel="stylesheet" href="main.css">

Firebase Authentication

Firebase Email & Password Authentication

Enter an email and password below and either sign in to an existing account or sign up

                        <input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="email" name="email" placeholder="Email" />
                        <input class="mdl-textfield__input" style="display:inline;width:auto;" type="password" id="password" name="password" placeholder="Password" />

                        <button disabled class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-in" name="signin">Sign In</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-up" name="signup">Sign Up</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" disabled id="quickstart-verify-email" name="verify-email">Send Email Verification</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-password-reset" name="verify-email">Send Password Reset Email</button>

                            Firebase sign-in status: Unknown

Firebase auth currentUser object value:

                            ```<code id="quickstart-account-details">null</code>```

```

答:
angular-cli based app?

If yes, it's better to include js files in .angular-cli.json

```<code>    "scripts": [
        "../node_modules/firebase/firebase.js"
    ],
</code>```

then in main component app.component.ts (inside contructor) include firebase config

```<code>constructor() {
    const config = {
      apiKey: '',
      authDomain: '',
      databaseURL: '',
      projectId: '',
      storageBucket: '',
      messagingSenderId: ''
    };

    firebase.initializeApp(config);
}
</code>```

from now, when firebase is injected into your SPA, you can use it wherever you want

For example in login.component.html

```<code><button (click)="signinWithGoogle()">
</code>```

in login.component.ts

```<code>public signinWithGoogle() {
    const provider = new firebase.auth.GoogleAuthProvider();

    firebase.auth().signInWithPopup(provider).then((response) => {
        this.router.navigate(['/dashboard']);
    });
}
</code>```

To send email verification

```<code>firebase.auth().onAuthStateChanged((user) => {
    user.sendEmailVerification();
});
</code>```

Body:
Firebase provides a great pre built authentication system for email and password. They have posted the sample here: https://github.com/firebase/quickstart-js/tree/master/auth

What I'm struggling to understand is how to integrate this into an Angular/AngularFire application.

Could I copy and paste this into a 'login.component.html/ts' file?

As a standalone solution the code firebase have provided looks great and works really well. It would be fantastic to drop this into an Angular solution if at all possible. An example of the code is provided below. Any help would be fantastically appreciated.

Email Authentication Code provided by Firebase

<!DOCTYPE html>

    <meta charset=utf-8 />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email/Password Authentication Example</title>

    <link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.orange-indigo.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <link rel="stylesheet" href="main.css">

Firebase Authentication

Firebase Email & Password Authentication

Enter an email and password below and either sign in to an existing account or sign up

                        <input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="email" name="email" placeholder="Email" />
                        <input class="mdl-textfield__input" style="display:inline;width:auto;" type="password" id="password" name="password" placeholder="Password" />

                        <button disabled class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-in" name="signin">Sign In</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-up" name="signup">Sign Up</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" disabled id="quickstart-verify-email" name="verify-email">Send Email Verification</button>
                        <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-password-reset" name="verify-email">Send Password Reset Email</button>

                            Firebase sign-in status: Unknown

Firebase auth currentUser object value:

null

Body:
angular-cli based app?

If yes, it's better to include js files in .angular-cli.json

    "scripts": [
        "../node_modules/firebase/firebase.js"
    ],

then in main component app.component.ts (inside contructor) include firebase config

constructor() {
    const config = {
      apiKey: '',
      authDomain: '',
      databaseURL: '',
      projectId: '',
      storageBucket: '',
      messagingSenderId: ''
    };

    firebase.initializeApp(config);
}

from now, when firebase is injected into your SPA, you can use it wherever you want

For example in login.component.html

<button (click)="signinWithGoogle()">

in login.component.ts

public signinWithGoogle() {
    const provider = new firebase.auth.GoogleAuthProvider();

    firebase.auth().signInWithPopup(provider).then((response) => {
        this.router.navigate(['/dashboard']);
    });
}

To send email verification

firebase.auth().onAuthStateChanged((user) => {
    user.sendEmailVerification();
});


问:
How to find all week numbers that are first week of month in a year python
I want to create a event that falls on Sunday of every first week of months.

This is what I am doing for a particular week number which is first week of june to get date:

```<code>from datetime import datetime
myDate = "2017 22 0"
# here `2017` is year, `22` is week number and `0` =sunday is week day
datetime.strptime(myDate, "%Y %W %w")

#output...
datetime.datetime(2017, 6, 4, 0, 0)
</code>```

So I need a list of all week numbers that are first week of month so I can loop on it and get desire dates.

Adding More information

I want a method which return list of week numbers which are first week of month where first week means week has first sunday.

```<code>def get_week_number(year=2017, day=0):
   #day 0 means sunday
   ...
   ...
   return [1, 5, 9, 13, 18, 22, ...]
</code>```

答:
(Edited, because of error in weekday numbering)

```<code>>>> import datetime
>>> june1 = datetime.datetime(2017,6,1)
>>> june1
datetime.datetime(2017, 6, 1, 0, 0)
>>> june1_weekday = june1.weekday()
>>> if june1_weekday < 6:  # 6 indicates Sunday
        first_sunday_in_june = june1 + datetime.timedelta(days=6-june1_weekday)
else:
        first_sunday_in_june = june1

>>> print(first_sunday_in_june)
2017-06-04 00:00:00
</code>```

Assuming you want ISO weeknumbers, you can then use the isocalendar() method. This gives a tuple (year, weeknumber, weekday). This uses the convention that weeks start with Monday, and the first week of the year is the first week with at least four days in the year (or in other words, the week with the first Thursday).

```<code>>>> first_sunday_in_june.isocalendar()
(2017, 22, 7)
</code>```

If you have another convention for first-day-of-the-week or first-week-of-the-year, you will have to brew your own function to get the week number.

Use the above method in a loop over the months, and you can create the desired list with week numbers.

Body:
I want to create a event that falls on Sunday of every first week of months.

This is what I am doing for a particular week number which is first week of june to get date:

from datetime import datetime
myDate = "2017 22 0"
# here `2017` is year, `22` is week number and `0` =sunday is week day
datetime.strptime(myDate, "%Y %W %w")

#output...
datetime.datetime(2017, 6, 4, 0, 0)

So I need a list of all week numbers that are first week of month so I can loop on it and get desire dates.

Adding More information

I want a method which return list of week numbers which are first week of month where first week means week has first sunday.

def get_week_number(year=2017, day=0):
   #day 0 means sunday
   ...
   ...
   return [1, 5, 9, 13, 18, 22, ...]

Body:
(Edited, because of error in weekday numbering)

>>> import datetime
>>> june1 = datetime.datetime(2017,6,1)
>>> june1
datetime.datetime(2017, 6, 1, 0, 0)
>>> june1_weekday = june1.weekday()
>>> if june1_weekday < 6:  # 6 indicates Sunday
        first_sunday_in_june = june1 + datetime.timedelta(days=6-june1_weekday)
else:
        first_sunday_in_june = june1

>>> print(first_sunday_in_june)
2017-06-04 00:00:00

Assuming you want ISO weeknumbers, you can then use the isocalendar() method. This gives a tuple (year, weeknumber, weekday). This uses the convention that weeks start with Monday, and the first week of the year is the first week with at least four days in the year (or in other words, the week with the first Thursday).

>>> first_sunday_in_june.isocalendar()
(2017, 22, 7)

If you have another convention for first-day-of-the-week or first-week-of-the-year, you will have to brew your own function to get the week number.

Use the above method in a loop over the months, and you can create the desired list with week numbers.


问:
IGrouping, IEnumerable and Pairs
I am having some trouble. I am supposed to implement a definition of GroupBy.
I am not sure how to group the values in Pairs, can someone help me? Can't use LINQ

Definition of Pair:

```<code>class Pair<K, V> {
    public Pair(K key, V value) {
        Key = key;
        Value = value;
    }
    public K Key { get; set; }
    public V Value { get; set; }
}
</code>```

main:

```<code>string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
}
</code>```

Output

```<code>/**
* Output:
* 3: ola, ole
* 5: super, aliba
* 4: isel, mane, xpto
*/
</code>```

答:
The code after the GroupBy (i.e. the Select) will project the data into the Pair class that you are trying to use.

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

namespace Test
{
    public class Program
    {
        class Pair<K, V>
        {
            public Pair(K key, V value)
            {
                Key = key;
                Value = value;
            }
            public K Key { get; set; }
            public V Value { get; set; }
        }

        static void Main(string[] args)
        {
            string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
            var pairs = src.GroupBy(s => s.Length)
                .Select(@group => new Pair<int, IEnumerable<string>>(@group.Key, @group));

            foreach (var pair in pairs)
            {
                Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
            }

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

Title: IGrouping, IEnumerable and Pairs

Body:
I am having some trouble. I am supposed to implement a definition of GroupBy.
I am not sure how to group the values in Pairs, can someone help me? Can't use LINQ

Definition of Pair:

class Pair<K, V> {
    public Pair(K key, V value) {
        Key = key;
        Value = value;
    }
    public K Key { get; set; }
    public V Value { get; set; }
}

main:

string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
foreach (Pair<int, IEnumerable<string>> pair in src.GroupBy(s => s.Length))
{
    Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
}

Output

/**
* Output:
* 3: ola, ole
* 5: super, aliba
* 4: isel, mane, xpto
*/

Body:
The code after the GroupBy (i.e. the Select) will project the data into the Pair class that you are trying to use.

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

namespace Test
{
    public class Program
    {
        class Pair<K, V>
        {
            public Pair(K key, V value)
            {
                Key = key;
                Value = value;
            }
            public K Key { get; set; }
            public V Value { get; set; }
        }

        static void Main(string[] args)
        {
            string[] src = { "ola", "super", "isel", "ole", "mane", "xpto", "aliba" };
            var pairs = src.GroupBy(s => s.Length)
                .Select(@group => new Pair<int, IEnumerable<string>>(@group.Key, @group));

            foreach (var pair in pairs)
            {
                Console.WriteLine("{0}: {1}", pair.Key, string.Join(", ", pair.Value));
            }

            Console.ReadLine();
        }
    }
}


问:
Abstract types and type inference
Suppose I have a module that hides some type:

```<code>module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end
</code>```

And I also have a function that operates on optioms:

```<code>let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"
</code>```

Not surprisingly, when I call do_work on t instance I get a type error:

```<code>let () =
  do_work @@ Test.make_t ()
</code>```

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

答:
If you don't want to expose your implementation, but you need to make a type compatible with others, write functions to convert to/from these types:

```<code>module Test : sig
  type t
  val make_t : unit -> t
  val to_option : t -> int option (* Signature *)
end = struct
  type t = int option
  let make_t () = Some 42
  let to_option t = t (* Implementation *)
end
</code>```

Then, when you specifically need an int option:

```<code>let () =
  Test.make_t ()
  |> Test.to_option
  |> do_work
</code>```

This way, your type Test.t stays abstract, which means you can change your implementation without changing the interface provided that you do the necessary in the converters to maintain their consistency.

Title: Abstract types and type inference

Body:
Suppose I have a module that hides some type:

module Test : sig
  type t
  val make_t : unit -> t
end = struct
  type t = int option
  let make_t () = Some 42
end

And I also have a function that operates on optioms:

let do_work : 'a option -> unit = function
  | Some x -> Printf.printf "Some\n"
  | None   -> Printf.printf "None\n"

Not surprisingly, when I call do_work on t instance I get a type error:

let () =
  do_work @@ Test.make_t ()

Error: This expression has type Test.t but an expression was expected of type 'a option

In my application I have t more complex than just int option and I don't want to expose its internals outward. However, I want to tell the compiler that t is actually something option. How can I achieve that?

Body:
If you don't want to expose your implementation, but you need to make a type compatible with others, write functions to convert to/from these types:

module Test : sig
  type t
  val make_t : unit -> t
  val to_option : t -> int option (* Signature *)
end = struct
  type t = int option
  let make_t () = Some 42
  let to_option t = t (* Implementation *)
end

Then, when you specifically need an int option:

let () =
  Test.make_t ()
  |> Test.to_option
  |> do_work

This way, your type Test.t stays abstract, which means you can change your implementation without changing the interface provided that you do the necessary in the converters to maintain their consistency.


问:
Node.js pass text as stdin of `spawnSync`
I'd think this would be simple, but the following does not work as expected.

I want to pipe data to a process, say (just an arbitrary command for illustration) wc, from Node.

The docs and other SO questions seem to indicate that passing a Stream should work:

```<code>const {spawnSync} = require('child_process')
const {Readable} = require('stream')

const textStream = new Readable()
textStream.push("one two three")
textStream.push(null)

const stdio = [textStream, process.stdout, process.stderr]
spawnSync('wc', ["-c"], { stdio })
</code>```

Unfortunately this throws an error:

The value "Readable { ... } is invalid for option "stdio"

The relevant bit of code from internal/child_process.js does not immediately reveal what the anticipated valid options are.

答:
To present particular data as stdin data for the child process, you can use the input option:

```<code>spawnSync('wc', ['-c'], { input : 'one two three' })
</code>```

Body:
I'd think this would be simple, but the following does not work as expected.

I want to pipe data to a process, say (just an arbitrary command for illustration) wc, from Node.

The docs and other SO questions seem to indicate that passing a Stream should work:

const {spawnSync} = require('child_process')
const {Readable} = require('stream')

const textStream = new Readable()
textStream.push("one two three")
textStream.push(null)

const stdio = [textStream, process.stdout, process.stderr]
spawnSync('wc', ["-c"], { stdio })

Unfortunately this throws an error:

The value "Readable { ... } is invalid for option "stdio"

The relevant bit of code from internal/child_process.js does not immediately reveal what the anticipated valid options are.

Body:
To present particular data as stdin data for the child process, you can use the input option:

spawnSync('wc', ['-c'], { input : 'one two three' })


问:
Joining 4 tables in mysql giving me duplicate records
I want to join below 4 tables (leads, categories, sales_persons, website_assigns) in mysql query :

Required : i need lead id and lead record  but its not sure that category , sales person exist for that lead,
If they category and sales person exist then come otherwise no required means null.

There is no relation between leads and sales_person direct, they bind with third table which is website_assign

MySql Query:

```<code>SELECT a.id, a.name, b.name, c.first_name, c.last_name
FROM leads a INNER JOIN sales_persons c
LEFT JOIN categories b ON a.category_id = b.id
LEFT JOIN website_assigns d ON a.id = d.lead_id and c.id = d.sales_person_id
</code>```

This above query giving me repeated record of leads, category and sales person table

Tables:

```<code>leads:
id  |   name | category_id
 1      xyz     12
 2      abc     13
 3      def     14
 4      gty     15
 5      wer     16

categories:
id  |   name
12      grocery
13      cloths
14      books
15      travel
16      furniture

sales_persons:
id  | first_name | last_name

111     Jack        Soloman
112     Peris       Rock
113     Pull        Cha
114     Tim         shock

website_assigns:
id  | lead_id | sales_person_id
1       1           112
2       1           114
3       2           113
4       2           111
5       3           113
6       3           112
7       3           114
</code>```

Duplicate record screen shot attached:

See repeated id (Lead id) , name (category name), first name and last  name of sales_person coming,

But 4847, 5868 has only sales person assigned.

In screen shot leadsite_assign is same table website_assign.
So ignore the name of table.

答:
Try this :

```<code>SELECT
distinct a.id, a.name, b.name, c.first_name, c.last_name
FROM  leads a
LEFT JOIN
website_assigns d on a.id = d.lead_id
LEFT JOIN
sales_persons c on c.id = d.sales_person_id
LEFT JOIN
categories b ON a.category_id = b.id
</code>```

output :

```<code>id          name   name    first_name   last_name
---         ----  -------  ---------    --------
1           xyz   grocery     Peris      Rock
1           xyz   grocery     Tim        shock
2           abc   cloths      Jack       Soloman
2           abc   cloths      Pull       Cha
3           def   books       Peris      Rock
3           def   books       Pull       Cha
3           def   books       Tim        shock
4           gty   travel      NULL       NULL
5           wer   furniture   NULL       NULL
</code>```

Understanding Join :

We can see that leads and sales_person are connected indirectly through website_assigns table. Hence we have used LEFT JOIN to join these 3 tables together.

LEFT JOIN basically returns every row from the left side table. Non matching rows from right side table are mapped to NULL.

Relation between categories and leads is straight forward as a.category_id = b.id

Body:
I want to join below 4 tables (leads, categories, sales_persons, website_assigns) in mysql query :

Required : i need lead id and lead record  but its not sure that category , sales person exist for that lead,
If they category and sales person exist then come otherwise no required means null.

There is no relation between leads and sales_person direct, they bind with third table which is website_assign

MySql Query:

SELECT a.id, a.name, b.name, c.first_name, c.last_name
FROM leads a INNER JOIN sales_persons c
LEFT JOIN categories b ON a.category_id = b.id
LEFT JOIN website_assigns d ON a.id = d.lead_id and c.id = d.sales_person_id

This above query giving me repeated record of leads, category and sales person table

Tables:

leads:
id  |   name | category_id
 1      xyz     12
 2      abc     13
 3      def     14
 4      gty     15
 5      wer     16

categories:
id  |   name
12      grocery
13      cloths
14      books
15      travel
16      furniture

sales_persons:
id  | first_name | last_name

111     Jack        Soloman
112     Peris       Rock
113     Pull        Cha
114     Tim         shock

website_assigns:
id  | lead_id | sales_person_id
1       1           112
2       1           114
3       2           113
4       2           111
5       3           113
6       3           112
7       3           114

Duplicate record screen shot attached:

See repeated id (Lead id) , name (category name), first name and last  name of sales_person coming,

But 4847, 5868 has only sales person assigned.

In screen shot leadsite_assign is same table website_assign.
So ignore the name of table.

Body:
Try this :

SELECT
distinct a.id, a.name, b.name, c.first_name, c.last_name
FROM  leads a
LEFT JOIN
website_assigns d on a.id = d.lead_id
LEFT JOIN
sales_persons c on c.id = d.sales_person_id
LEFT JOIN
categories b ON a.category_id = b.id

output :

id          name   name    first_name   last_name
---         ----  -------  ---------    --------
1           xyz   grocery     Peris      Rock
1           xyz   grocery     Tim        shock
2           abc   cloths      Jack       Soloman
2           abc   cloths      Pull       Cha
3           def   books       Peris      Rock
3           def   books       Pull       Cha
3           def   books       Tim        shock
4           gty   travel      NULL       NULL
5           wer   furniture   NULL       NULL

Understanding Join :

We can see that leads and sales_person are connected indirectly through website_assigns table. Hence we have used LEFT JOIN to join these 3 tables together.

LEFT JOIN basically returns every row from the left side table. Non matching rows from right side table are mapped to NULL.

Relation between categories and leads is straight forward as a.category_id = b.id


问:
Get value from datetimepicker in code behind c#
I'm doing some Sharepoint webparts and i'm trying to use a jquery datetimepicker, but i can't quite retrieve the value from the datetimepicker in the C# code behind. Here is my script :

```<code>   <input type="hidden" id="StartDateHiddenField" name="StartDateHiddenField" value=""/>
     <script type="text/javascript">
         $(document).ready(function () {
             $(".datepicker1").datepicker({
                 changeMonth: true,
                 changeYear: true,
                 dateFormat: "dd-mm-yy",
                 showButtonPanel: false,
                 onClose: function (dateText, inst) {
                     $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
                     $('#StartDateHiddenField').val($(this).datepicker("getDate"));
                 }

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

In code behind :

```<code> var test = Page.Request.Form["StartDateHiddenField"];
 var startTime = DateTime.Parse(Page.Request.Form["StartDateHiddenField"]);
</code>```

test value according to debugger is, for exemple :

"Sat Jul 01 2017 00:00:00 GMT+0200 (Romance Daylight Time)"

How can i get proper values from DateTime.Parse ?

答: Thanks to ADyson, a solution was to use $(this).datepicker("getDate").toISOString()

Body:
I'm doing some Sharepoint webparts and i'm trying to use a jquery datetimepicker, but i can't quite retrieve the value from the datetimepicker in the C# code behind. Here is my script :

   <input type="hidden" id="StartDateHiddenField" name="StartDateHiddenField" value=""/>

In code behind :

 var test = Page.Request.Form["StartDateHiddenField"];
 var startTime = DateTime.Parse(Page.Request.Form["StartDateHiddenField"]);

test value according to debugger is, for exemple :

"Sat Jul 01 2017 00:00:00 GMT+0200 (Romance Daylight Time)"

How can i get proper values from DateTime.Parse ?


问:
Tinymce html5 placeholder by reading attribute from textarea
For standard textareas I use this plugin to create a placeholder. How can I extend tinymce so that this works in this way also.

E.g the default value is read from the textarea attribute then cleared when a user focuses on the iframe.

Similar to this for CKEditor: http://alfonsoml.blogspot.com.es/2012/04/placeholder-text-in-ckeditor.html

答:
This plugin for TinyMCE seems to be a solution:

https://github.com/mohan/tinymce-placeholder

Hope it helps!


问:
How do next track AVPlayer
I tried for a few days to make a button which includes the next song but I can not

Here is my question

How to put the next екфсл at the click of a button with avPlayer

it is my code

```<code>class ViewControllerAudioDetail: UIViewController {

var avPlayer:AVQueuePlayer?
var status = false
fileprivate let seekDuration: Float64 = 10
fileprivate let seekDurationThirty: Float64 = 30

var mod = [Modal]()

@IBOutlet weak var ImageView: UIImageView!

@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
@IBOutlet weak var sliderSong: UISlider!
@IBOutlet weak var name: UILabel!

@IBOutlet weak var Volume: UISlider!
@IBOutlet weak var iconChange: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    Volume.setThumbImage(UIImage(named:"Play.png"), for: .normal)
    sliderSong.minimumValue = 0
    sliderSong.maximumValue = 1

    name.text = mod[thisSong].AudioName
    ImageView.image = mod[0].ImageViewAudio

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    let _ = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}

@IBAction func sliderSong(_ sender: UISlider) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
        let value = sliderSong.value
        let durationToSeek = Float(duration) * value

        avPlayer?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),avPlayer!.currentItem!.duration.timescale)) { [](state) in

            if (self.iconChange.currentImage?.isEqual(UIImage(named: "Play.png")))! {
                self.avPlayer?.pause()
            } else if (self.iconChange.currentImage?.isEqual(UIImage(named: "Pause.png")))!{
                self.avPlayer?.play()
            }
        }
}

@IBAction func volume(_ sender: UISlider) {

    avPlayer?.volume = sender.value
}

@IBAction func minusThirtySec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDurationThirty

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}
@IBAction func minusTenSec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDuration

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}

@IBAction func plusTenSec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDuration

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}
@IBAction func plusThirtySec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDurationThirty

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}

@IBAction func Next(_ sender: Any) {

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    avPlayer?.insert(playerItem, after: playerItem)
    avPlayer?.advanceToNextItem()

 //        if thisSong + 1 > mod.count {
 //            thisSong = 0
 //        } else {
 //            thisSong += 1
  //        }
  //
  //
  //        if thisSong != mod.count{
  //
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //
 //        }

}
@IBAction func Back(_ sender: Any) {

 //        if thisSong != 0{
 //            thisSong -= 1
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //        }

}

@IBAction func Play(_ sender: Any) {

    if avPlayer?.rate == 0 {
        avPlayer?.play()
        avPlayer?.rate = 1.0
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)

        avPlayer?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: nil, using: {
            (CMTime) -> Void in

            self.updateProgressBar()
        })

    } else {
        avPlayer?.rate = 0.0
        avPlayer?.pause()
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)

    }

}

func player(urlSong:String) {

}

func updateProgressBar(){
    let timeNow = Int(avPlayer!.currentTime().value) / Int(avPlayer!.currentTime().timescale)

    let minutesText = timeNow / 60
    let secondsText = timeNow % 60

    let duration = String(format:"%02d:%02d", minutesText, secondsText)
    startTime.text = duration

}
</code>```

And tableview from here I get the data

```<code>var thisSong = 0

 class TableViewControllerAudioList: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.estimatedRowHeight = 50
    tableView.rowHeight = UITableViewAutomaticDimension

}

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return modalsF.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellAudioList

    cell.name.text = modalsF[indexPath.row].AudioName
    cell.number.text = "\(indexPath.row + 1)"

    thisSong = indexPath.row

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc  = segue.destination as? ViewControllerAudioDetail

    vc?.mod = [modalsF[(tableView.indexPathForSelectedRow?.row)!]]

}
</code>```

答:
In its tableview I added func didSelectRowAt in which I wrote a global counter that received the cell number

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    thisSong = indexPath.row

}
</code>```

And pass the data to the controller through prepareForSegue

```<code> override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier ==  "listToDetail"{
        let vc  = segue.destination as? ViewControllerAudioDetail
        vc?.mod = mod
    }
}
</code>```

In my detailed controller I created two buttons for the previous song and the next one

```<code>var avPlayer:AVPlayer?

var mod = [Modal]()

@IBAction func Next(_ sender: Any) {

    if thisSong == mod.count - 1 {
        thisSong = 0
    } else {
        thisSong += 1
    }

    if thisSong != mod.count{
        avPlayer?.removeTimeObserver(sliderDuration)

        name.text = mod[thisSong].AudioName
        player(urlSong:mod[thisSong].UrlName!)

        Status()

    }

}

@IBAction func Back(_ sender: Any) {

    if thisSong != 0 {
        thisSong -= 1
    } else {
        thisSong = mod.endIndex
    }

        avPlayer?.removeTimeObserver(sliderDuration)
        name.text = mod[thisSong].AudioName
        player(urlSong:mod[thisSong].UrlName!)

       Status()

}
</code>```

And the function determines which was the status of the player and sets the same data

```<code>func Status(){
    if status == true {
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)
        avPlayer?.play()
    } else {
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)
        avPlayer?.pause()
    }

}
</code>```

Here I create a player

```<code>func player(urlSong:String) {

    let url = URL(string: urlSong)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVPlayer(playerItem:playerItem)

     sliderDuration = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}
</code>```

Title: How do next track AVPlayer

Body:
I tried for a few days to make a button which includes the next song but I can not

Here is my question

How to put the next екфсл at the click of a button with avPlayer

it is my code

class ViewControllerAudioDetail: UIViewController {

var avPlayer:AVQueuePlayer?
var status = false
fileprivate let seekDuration: Float64 = 10
fileprivate let seekDurationThirty: Float64 = 30

var mod = [Modal]()

@IBOutlet weak var ImageView: UIImageView!

@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var endTime: UILabel!
@IBOutlet weak var sliderSong: UISlider!
@IBOutlet weak var name: UILabel!

@IBOutlet weak var Volume: UISlider!
@IBOutlet weak var iconChange: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    Volume.setThumbImage(UIImage(named:"Play.png"), for: .normal)
    sliderSong.minimumValue = 0
    sliderSong.maximumValue = 1

    name.text = mod[thisSong].AudioName
    ImageView.image = mod[0].ImageViewAudio

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    let _ = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}

@IBAction func sliderSong(_ sender: UISlider) {

        //перемотка аудиозвука
        let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
        let value = sliderSong.value
        let durationToSeek = Float(duration) * value

        avPlayer?.seek(to: CMTimeMakeWithSeconds(Float64(durationToSeek),avPlayer!.currentItem!.duration.timescale)) { [](state) in

            if (self.iconChange.currentImage?.isEqual(UIImage(named: "Play.png")))! {
                self.avPlayer?.pause()
            } else if (self.iconChange.currentImage?.isEqual(UIImage(named: "Pause.png")))!{
                self.avPlayer?.play()
            }
        }
}

@IBAction func volume(_ sender: UISlider) {

    avPlayer?.volume = sender.value
}

@IBAction func minusThirtySec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDurationThirty

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}
@IBAction func minusTenSec(_ sender: Any) {

    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    var newTime = playerCurrentTime - seekDuration

    if newTime < 0 {
        newTime = 0
    }
    let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
    avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

}

@IBAction func plusTenSec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDuration

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}
@IBAction func plusThirtySec(_ sender: Any) {

    guard let duration = avPlayer?.currentItem?.duration else{
        return
    }
    let playerCurrentTime = CMTimeGetSeconds((avPlayer?.currentTime())!)
    let newTime = playerCurrentTime + seekDurationThirty

    if newTime < (CMTimeGetSeconds(duration) - seekDuration) {

        let time2: CMTime = CMTimeMake(Int64(newTime * 1000 as Float64), 1000)
        avPlayer?.seek(to: time2, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)

    }

}

@IBAction func Next(_ sender: Any) {

    let url = URL(string: mod[thisSong].UrlName!)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVQueuePlayer(playerItem:playerItem)

    avPlayer?.insert(playerItem, after: playerItem)
    avPlayer?.advanceToNextItem()

 //        if thisSong + 1 > mod.count {
 //            thisSong = 0
 //        } else {
 //            thisSong += 1
  //        }
  //
  //
  //        if thisSong != mod.count{
  //
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //
 //        }

}
@IBAction func Back(_ sender: Any) {

 //        if thisSong != 0{
 //            thisSong -= 1
 //            name.text = mod[thisSong].AudioName
 //            player(urlSong:mod[thisSong].UrlName!)
 //            avPlayer?.play()
 //
 //
 //        }

}

@IBAction func Play(_ sender: Any) {

    if avPlayer?.rate == 0 {
        avPlayer?.play()
        avPlayer?.rate = 1.0
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)

        avPlayer?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1), queue: nil, using: {
            (CMTime) -> Void in

            self.updateProgressBar()
        })

    } else {
        avPlayer?.rate = 0.0
        avPlayer?.pause()
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)

    }

}

func player(urlSong:String) {

}

func updateProgressBar(){
    let timeNow = Int(avPlayer!.currentTime().value) / Int(avPlayer!.currentTime().timescale)

    let minutesText = timeNow / 60
    let secondsText = timeNow % 60

    let duration = String(format:"%02d:%02d", minutesText, secondsText)
    startTime.text = duration

}

And tableview from here I get the data

var thisSong = 0

 class TableViewControllerAudioList: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.estimatedRowHeight = 50
    tableView.rowHeight = UITableViewAutomaticDimension

}

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return modalsF.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellAudioList

    cell.name.text = modalsF[indexPath.row].AudioName
    cell.number.text = "\(indexPath.row + 1)"

    thisSong = indexPath.row

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc  = segue.destination as? ViewControllerAudioDetail

    vc?.mod = [modalsF[(tableView.indexPathForSelectedRow?.row)!]]

}

Body:
In its tableview I added func didSelectRowAt in which I wrote a global counter that received the cell number

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    thisSong = indexPath.row

}

And pass the data to the controller through prepareForSegue

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier ==  "listToDetail"{
        let vc  = segue.destination as? ViewControllerAudioDetail
        vc?.mod = mod
    }
}

In my detailed controller I created two buttons for the previous song and the next one

var avPlayer:AVPlayer?

var mod = [Modal]()

@IBAction func Next(_ sender: Any) {

    if thisSong == mod.count - 1 {
        thisSong = 0
    } else {
        thisSong += 1
    }

    if thisSong != mod.count{
        avPlayer?.removeTimeObserver(sliderDuration)

        name.text = mod[thisSong].AudioName
        player(urlSong:mod[thisSong].UrlName!)

        Status()

    }

}

@IBAction func Back(_ sender: Any) {

    if thisSong != 0 {
        thisSong -= 1
    } else {
        thisSong = mod.endIndex
    }

        avPlayer?.removeTimeObserver(sliderDuration)
        name.text = mod[thisSong].AudioName
        player(urlSong:mod[thisSong].UrlName!)

       Status()

}

And the function determines which was the status of the player and sets the same data

func Status(){
    if status == true {
        iconChange.setImage(UIImage(named:"Pause.png"), for: .normal)
        avPlayer?.play()
    } else {
        iconChange.setImage(UIImage(named:"Play.png"), for: .normal)
        avPlayer?.pause()
    }

}

Here I create a player

func player(urlSong:String) {

    let url = URL(string: urlSong)
    let playerItem = AVPlayerItem(url: url!)
    avPlayer = AVPlayer(playerItem:playerItem)

     sliderDuration = avPlayer!.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main) { [weak self] (time) in

        let duration = CMTimeGetSeconds((self?.avPlayer!.currentItem!.asset.duration)!)
        self?.sliderSong.value = Float(CMTimeGetSeconds(time)) / Float(duration)

    }

    let duration = CMTimeGetSeconds(avPlayer!.currentItem!.asset.duration)
    let minutesTextOut = Int(duration) / 60 % 60
    let secondsTextOut = Int(duration) % 60
    let strDuration = String(format:"%02d:%02d", minutesTextOut, secondsTextOut)
    endTime.text = strDuration

}


问:
books to recommend to study WPF

Possible Duplicate:

  What WPF books would you recommend?

Is there any good book to recommend for learning WPF?

答: I'd highly recommend Sams Teach Yourself WPF in 24 Hours. </p>

ContentLicense: CC BY-SA 2.5

Title: books to recommend to study WPF


问:
Oracle how to compare subset in a query
I have one table (T1) with 3 columns: id, category, sector

```<code>id, category, sector
1    1         2
10   1         3
10   5         4
20   1         3
20   5         4
20   7         8
</code>```

I want a query that return the ids with a subset of sector and category of the startig id, that is:

```<code>select * from T1 where id=10
</code>```

return 2 records

The query i'm trying to write should return other ids with the same 2 records
even if they have other records. In this example this query should return only the id 20 because is a super set.

Many thanks

答:
Seems you wnat all the rows with category and sectore selected using id 10</p>

```<code>select t1.id from t1
inner join (
  select  category, sector
  from T1 where id=10
) t on t.category = t1.category and t.sector = t1.sector
</code>```

Title: Oracle how to compare subset in a query

Body:
I have one table (T1) with 3 columns: id, category, sector

id, category, sector
1    1         2
10   1         3
10   5         4
20   1         3
20   5         4
20   7         8

I want a query that return the ids with a subset of sector and category of the startig id, that is:

select * from T1 where id=10

return 2 records

The query i'm trying to write should return other ids with the same 2 records
even if they have other records. In this example this query should return only the id 20 because is a super set.

Many thanks

Body:
Seems you wnat all the rows with category and sectore selected using id 10

select t1.id from t1
inner join (
  select  category, sector
  from T1 where id=10
) t on t.category = t1.category and t.sector = t1.sector


答:
Here is one method:

```<code>select t.id
from t join
     (select t2.*, count(*) over (partition by id) as cnt
      from t t2
     ) t2
     on t2.category = t.category and t2.sector = t.sector and
        t2.id = 10
group by t.id
having count(*) = t2.cnt;
</code>```

It first counts the number of rows for each id.  This is important for being sure that you have all of them.

Then, the query does a self-join on category and sector.  It aggregates by the first id and counts the matching rows.  If all match, then you keep the id.

Title: Oracle how to compare subset in a query

Body:
Here is one method:

select t.id
from t join
     (select t2.*, count(*) over (partition by id) as cnt
      from t t2
     ) t2
     on t2.category = t.category and t2.sector = t.sector and
        t2.id = 10
group by t.id
having count(*) = t2.cnt;

It first counts the number of rows for each id.  This is important for being sure that you have all of them.

Then, the query does a self-join on category and sector.  It aggregates by the first id and counts the matching rows.  If all match, then you keep the id.


问:
sqlsrv_num_rows() expects parameter 1 to be resource
I get a error --> sqlsrv_num_rows() expects parameter 1 to be resource

Can anyone figure out whats wrong with the coding, ive been trying for 3 hours now
Thanks in advance :)

```<code><?php
include("config.php");

 username and password sent from form
 $myusername=htmlspecialchars($_POST[username]);
 $mypassword=htmlspecialchars($_POST[password]);

 $sql="SELECT * FROM Login WHERE Username=$myusername and
  Password=$mypassword";
  $result=sqlsrv_query($conn,$sql);
  $count=sqlsrv_num_rows($result);

  if($count==1){
     header("location: something");
  }
 else {
     echo "Wrong Username or Password";

 }
 ?>
</code>```

CONFIG.PHP

```<code> <?php
   $serverName = '';
   $uid = '';
   $pwd = '';
   $databaseName = '';
   $connectionInfo = array( "UID"=>$uid,
                     "PWD"=>$pwd,
                     "Database"=>$databaseName);

   $conn = sqlsrv_connect( $serverName, $connectionInfo);
      if( $conn ) {
            echo "Connection established.<br />";
       }else{
              echo "Connection could not be established.<br />";

        }
        ?>
</code>```

答:
sqlsrv_num_rows() expects parameter 1 to be resource

The issue is $result is false and it is because of:

```<code>$sql="SELECT * FROM Login WHERE Username=$myusername and
  Password=$mypassword";
</code>```

here Username and Password are strings and you to compare with string you have to wrap the values in ' singe quotes like:

```<code>$sql="SELECT * FROM Login WHERE Username='".$myusername."' and
  Password='".$mypassword."'";
</code>```

Note: Your query is vulnerable to sql injections

Body:
I get a error --> sqlsrv_num_rows() expects parameter 1 to be resource

Can anyone figure out whats wrong with the coding, ive been trying for 3 hours now
Thanks in advance :)

<?php
include("config.php");

 username and password sent from form
 $myusername=htmlspecialchars($_POST[username]);
 $mypassword=htmlspecialchars($_POST[password]);

 $sql="SELECT * FROM Login WHERE Username=$myusername and
  Password=$mypassword";
  $result=sqlsrv_query($conn,$sql);
  $count=sqlsrv_num_rows($result);

  if($count==1){
     header("location: something");
  }
 else {
     echo "Wrong Username or Password";

 }
 ?>

CONFIG.PHP

 <?php
   $serverName = '';
   $uid = '';
   $pwd = '';
   $databaseName = '';
   $connectionInfo = array( "UID"=>$uid,
                     "PWD"=>$pwd,
                     "Database"=>$databaseName);

   $conn = sqlsrv_connect( $serverName, $connectionInfo);
      if( $conn ) {
            echo "Connection established.
";
       }else{
              echo "Connection could not be established.
";

        }
        ?>

Body:
sqlsrv_num_rows() expects parameter 1 to be resource

The issue is $result is false and it is because of:

$sql="SELECT * FROM Login WHERE Username=$myusername and
  Password=$mypassword";

here Username and Password are strings and you to compare with string you have to wrap the values in ' singe quotes like:

$sql="SELECT * FROM Login WHERE Username='".$myusername."' and
  Password='".$mypassword."'";

Note: Your query is vulnerable to sql injections


问:
How to compute the conditional probability in R?
Let's suppose I have these two vectors:

```<code>x = rnorm(20)
y = rnorm(20)
</code>```

I want to compute the probability that y > 0 given that x > 0.
In other words, I want the frequency that my y > 0 when x > 0.
Can anyone show me how to code this in R?

答:
To make the results reproducible,  I will  use set.seed

```<code>set.seed(42)
x = rnorm(20)
y = rnorm(20)
</code>```

You can just subset the data to select the ones where x>0  and then count what proportion of those have y>0

```<code>PosX = which(x>0)
sum(y[PosX] > 0)/length(PosX)
[1] 0.6
</code>```

Body:
Let's suppose I have these two vectors:

x = rnorm(20)
y = rnorm(20)

I want to compute the probability that y > 0 given that x > 0.
In other words, I want the frequency that my y > 0 when x > 0.
Can anyone show me how to code this in R?

Body:
To make the results reproducible,  I will  use set.seed

set.seed(42)
x = rnorm(20)
y = rnorm(20)

You can just subset the data to select the ones where x>0  and then count what proportion of those have y>0

PosX = which(x>0)
sum(y[PosX] > 0)/length(PosX)
[1] 0.6


问:
Jenkins "Error cloning remote repo 'origin'" and "Cannot allocate memory"
I have Jenkins running on my server connected with GitHub via webhooks. Unfortunately my builds are failing OCCASIONALLY and I can't figure out why. Sometimes restarting Jenkins (sudo service jenkins restart) solves the problem, sometimes it doesn't. The server is running Ubuntu 16.04 nad Nginx as a proxy. What causes this issue and how can I solve it?

```<code>Started by GitHub push by gaboratorium
Building in workspace /var/lib/jenkins/workspace/kudos.gaboratorium.com
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
Cloning the remote Git repository
Cloning repository https://github.com/gaboratorium/kudos.git
> git init /var/lib/jenkins/workspace/kudos.gaboratorium.com # timeout=10
Fetching upstream changes from https://github.com/gaboratorium/kudos.git
> git --version # timeout=10
> git fetch --tags --progress https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Command "git fetch --tags --progress
https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: error: cannot fork() for fetch-pack: Cannot allocate memory

at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:348)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:545)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1070)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1110)
at hudson.scm.SCM.checkout(SCM.java:495)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
at hudson.model.Run.execute(Run.java:1735)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:405)
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE
</code>```

答: Use df -h or du -sh $JENKINS_HOME to check if there is enough memory for Jenkins to allocate.

Body:
I have Jenkins running on my server connected with GitHub via webhooks. Unfortunately my builds are failing OCCASIONALLY and I can't figure out why. Sometimes restarting Jenkins (sudo service jenkins restart) solves the problem, sometimes it doesn't. The server is running Ubuntu 16.04 nad Nginx as a proxy. What causes this issue and how can I solve it?

Started by GitHub push by gaboratorium
Building in workspace /var/lib/jenkins/workspace/kudos.gaboratorium.com
[WS-CLEANUP] Deleting project workspace...
[WS-CLEANUP] Done
Cloning the remote Git repository
Cloning repository https://github.com/gaboratorium/kudos.git
> git init /var/lib/jenkins/workspace/kudos.gaboratorium.com # timeout=10
Fetching upstream changes from https://github.com/gaboratorium/kudos.git
> git --version # timeout=10
> git fetch --tags --progress https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Command "git fetch --tags --progress
https://github.com/gaboratorium/kudos.git
+refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: error: cannot fork() for fetch-pack: Cannot allocate memory

at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:348)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:545)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1070)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1110)
at hudson.scm.SCM.checkout(SCM.java:495)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
at hudson.model.Run.execute(Run.java:1735)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:405)
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE


问:
Batch file extract string
I know this has been asked numerous times, but I've been researching for like 2 hours and still can't do that.

I need a batch script to extract a string from a file.

The content of the file is this:

C:\Windows\system32\tasks{7D7A0547-0D79-0805-0A11-0B780D08110D}

I want to extract this part:

{7D7A0547-0D79-0805-0A11-0B780D08110D}

I tried it with for /f command and all kinds of options and searches, but I just can't do it.

TIA

答:
```<code>@echo off
for /f "tokens=2 delims={}" %%A in (
  'findstr "{[0-9A-F-]*}" "X:\path\yourfile.ext" '
) Do Echo %%A
</code>```

Title: Batch file extract string


问:
Load a json template with an object from database
I need to fill a JSON where their properties have the same name with the attributes of the object.

MyObject:

```<code>{ idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}
</code>```

MyJSON:

```<code>{ sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: ''
}
</code>```

Only fill properties who match.

Im using a promise to generate a pdf from a template where the fields of the form match with de json properties, here is my code

```<code>TramitePdf.generatePdf = function (idTipoTramite, idCliente, callback) {
var cliente = TramitePdf.app.models.Cliente;
var modeloTipoTramite = TramitePdf.app.models.TipoTramite;
var pathModelo, pathCliente, tipoT, clienteActual;
modeloTipoTramite.findById(idTipoTramite)
  .then(tipoTramite => {
    this.pathModelo = `${__dirname}/../pdf/${tipoTramite.nombre}.pdf`;
    this.pathCliente = `${__dirname}/../pdf/clientes/${idCliente}_${idTipoTramite}_${tipoTramite.nombre}.pdf`;
    this.tipoT = tipoTramite;
    this.clienteActual = cliente.findById(idCliente);
    return this.clienteActual;
  })
  .then(cliente => {
    pdfFiller.fillForm(this.pathModelo, this.pathCliente, JSON.parse(this.tipoT.template), function (err) {
      callback(err, cliente);
    });
  })
  .catch(err => {
    callback(err);
  });
</code>```

};

Any ideas?

答:
Just:</p>

```<code>Object.keys(someJson).forEach(el => {
  if (typeof myJson[el] !== 'undefined') {
    myJson[el] = someJson[el];
  }
});
</code>```

Body:
I need to fill a JSON where their properties have the same name with the attributes of the object.

MyObject:

{ idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}

MyJSON:

{ sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: ''
}

Only fill properties who match.

Im using a promise to generate a pdf from a template where the fields of the form match with de json properties, here is my code

TramitePdf.generatePdf = function (idTipoTramite, idCliente, callback) {
var cliente = TramitePdf.app.models.Cliente;
var modeloTipoTramite = TramitePdf.app.models.TipoTramite;
var pathModelo, pathCliente, tipoT, clienteActual;
modeloTipoTramite.findById(idTipoTramite)
  .then(tipoTramite => {
    this.pathModelo = `${__dirname}/../pdf/${tipoTramite.nombre}.pdf`;
    this.pathCliente = `${__dirname}/../pdf/clientes/${idCliente}_${idTipoTramite}_${tipoTramite.nombre}.pdf`;
    this.tipoT = tipoTramite;
    this.clienteActual = cliente.findById(idCliente);
    return this.clienteActual;
  })
  .then(cliente => {
    pdfFiller.fillForm(this.pathModelo, this.pathCliente, JSON.parse(this.tipoT.template), function (err) {
      callback(err, cliente);
    });
  })
  .catch(err => {
    callback(err);
  });

};

Any ideas?

Body:
Just:

Object.keys(someJson).forEach(el => {
  if (typeof myJson[el] !== 'undefined') {
    myJson[el] = someJson[el];
  }
});


问:
get name from a button click React
Just some context with respect to the code. I currently have an array of objects which populates the label,icon, and id of a button accordingly in a loop. The trouble I am having is targeting the selected button upon click. Everytime I do click a button, i get the following the error:

TypeError: _this2.props.bind is not a function

My code is as follows:

```<code>import React, {Component} from 'react'
import propTypes from 'prop-types'
import Button from 'components/button'
import './segmentedButtons.scss'

class segmentedButtons extends Component {
  onChange = (displayLabels) => {
    console.log(displayLabels)
    //this.props.onChange({ label: displayLabels.label, icon: displayLabels.icon, id: displayLabels.id })
  }

  render() {
    const {displayLabels} = this.props.labels
    const classPrefix = this.props.view
    var renderLabels = [];
    for (var i = 0; i< this.props.labels.length; i++){
        renderLabels.push(<Button
        label={this.props.labels[i].title}
        icon={this.props.labels[i].icon}
        id={this.props.labels[i].id}
        onClick={() => this.onChange(this.props.bind(this,i))}
      />)
    }

    return (
      <div className={classPrefix+"-buttons "+ "segmentedButtons-buttons"}>
          {renderLabels}
      </div>
    )
  }
}

segmentedButtons.propTypes = {
  displayLabels: propTypes.arrayOf(propTypes.shape({
    label: propTypes.string,
    icon: propTypes.string,
    id: propTypes.number,
    onClick: propTypes.func
  })),
}

export default segmentedButtons
</code>```

答:
try this:

```<code>const onChangeGen = (i) => () => this.onChange(i)
</code>```

and then

```<code>onClick={onChangeGen(i)}
</code>```

Title: get name from a button click React

Body:
Just some context with respect to the code. I currently have an array of objects which populates the label,icon, and id of a button accordingly in a loop. The trouble I am having is targeting the selected button upon click. Everytime I do click a button, i get the following the error:

TypeError: _this2.props.bind is not a function

My code is as follows:

import React, {Component} from 'react'
import propTypes from 'prop-types'
import Button from 'components/button'
import './segmentedButtons.scss'

class segmentedButtons extends Component {
  onChange = (displayLabels) => {
    console.log(displayLabels)
    //this.props.onChange({ label: displayLabels.label, icon: displayLabels.icon, id: displayLabels.id })
  }

  render() {
    const {displayLabels} = this.props.labels
    const classPrefix = this.props.view
    var renderLabels = [];
    for (var i = 0; i< this.props.labels.length; i++){
        renderLabels.push(<Button
        label={this.props.labels[i].title}
        icon={this.props.labels[i].icon}
        id={this.props.labels[i].id}
        onClick={() => this.onChange(this.props.bind(this,i))}
      />)
    }

    return (

          {renderLabels}

    )
  }
}

segmentedButtons.propTypes = {
  displayLabels: propTypes.arrayOf(propTypes.shape({
    label: propTypes.string,
    icon: propTypes.string,
    id: propTypes.number,
    onClick: propTypes.func
  })),
}

export default segmentedButtons

Body:
try this:

const onChangeGen = (i) => () => this.onChange(i)

and then

onClick={onChangeGen(i)}


问:
Improving performance of hive jdbc
Does aynyone know how to increase performance for HIVE JDBC connection.

Detailed problem:

When I query hive from Hive CLI, I get a response within 7 sec but from HIVE JDBC connection I get a response after 14 sec. I was wondering if there is any way (configuration changes) with which I can improve performance for query through JDBC connection.

Thanks in advance.

答:
Using Connection pooling helped me increase hive JDBC performance.
As in hive there are many transformations happening while we query so using existing connection objects from connection pool instead of opening a new connection and closing for each request was quite helpful.

Please let me know if any one else if facing same issue will post a detailed answer.

Title: Improving performance of hive jdbc