text:
Q: How to change Javascript function to PHP where MySQL can work with? Im newbie here.
I would like to ask that Im having a room.php and room.js.
Room.js is the file that contain validations and functionality whereas in room.php is the file that contain the view...
I need to save the data into MySQL where the room choose using Javascript but now Im having difficulty at the validation there..
Room.php

<title>Room Selection</title>

<?php
    error_reporting(0);// Turn off all error reporting
    include('reserveDB.php');//pass the reserveDB.php
    if(!isset($_POST['submitPageTwo'])) {
?>

Room Page

         <form name="room" method="post">

Standard Room

MYR 129 ++

                                                Bed Type: Queen Size Bed or 2 Single Beds

Features: Flat screen TV, Mini-fridge, Wireless internet, Executive desk & Keycard Entry

                                                        No. of rooms:
                                                        <input type="button" class="plusMinusButton" id="minusSTD" value="-">
                                                        <input type="textbox" id="STD" name="STD" onchange="summary()" style="width: 30px; text-align:center;" value="0" readonly>
                                                        <input type="button" class="plusMinusButton" id="plusSTD" value="+">

                                                    <input type="hidden" id="STDHidden" value="129"/>

Deluxe Room

MYR 159 ++

                                                Bed Type: Queen Size Bed or Twin Super Single Bed

Features: Flat screen TV, Mini-fridge, Wireless internet, Executive desk,
Keycard Entry & Pull Out Couch

                                                        No. of rooms:
                                                        <input type="button" class="plusMinusButton" id="minusDLX" value="-">
                                                        <input type="textbox" id="DLX" name="DLX" onchange="summary()" style="width: 30px; text-align:center;" value="0" readonly/>
                                                        <input type="button" class="plusMinusButton" id="plusDLX" value="+">

                                                        <input type="hidden" id="DLXHidden" value="159"/>

Suite Room

MYR 189 ++

                                                  Bed Type: Queen Size Bed or 2 Single Beds

Features:Second flat screen TV, Mini-fridge, Wireless internet,
Executive desk, Keycard Entry, Pull Out Couch, Iron & Ironing Board

                                                     No. of rooms:
                                                     <input type="button" class="plusMinusButton" id="minusSUI" value="-">
                                                     <input type="textbox" id="SUI" name="SUI" onchange="summary()" style="width: 30px; text-align:center;" value="0"readonly>
                                                     <input type="button" class="plusMinusButton" id="plusSUI" value="+">

                                                    <input type="hidden" id="SUIHidden" value="189"/>

SUMMARY

                                Room Selected:

                        <input type="button" class="popUpButton" onclick="closePageOne()" value="Cancel">
                        <input type="button" class="popUpButton" id="nextButton"  name="submitPageTwo" value="Next">

        </form>

//validation where if user did not choose any room will show error on next page but the error msg did not show at all//
<?php
    $STD = $_POST['STD'];
            $DLX = $_POST['DLX'];
            $SUI = $_POST['SUI'];

                if(($_POST['STD']=='0') || ($_POST['DLX']=='0')|| ($_POST['SUI']=='0')){
                    echo 'Please fill in the date
Back To Check Page';
                }
else{
            mysql_query("INSERT INTO `room`(`room_name`, `room_price`, `noRoom`) VALUES ([value-1],[value-2],[value-3],[value-4])");
            Header("Refresh: 1; url = room.php?cid=".$cid."&cod=".$cod."&night=".$night."");
        }
            }
        ?>

room.js
$(document).ready(function() {
    $( "#minusSTD" ).click(function() {
        var STD = $("#STD").val();
        if(STD >= 1){
            STD--;
        }
        $("#STD").val(STD);
        summary();
    });$( "#plusSTD" ).click(function() {
        var STD = $("#STD").val();
        STD++;
        if(STD >= 10){
            STD=10;
        }
        $("#STD").val(STD);
        summary();
    });
    $( "#minusDLX" ).click(function() {
        var DLX = $("#DLX").val();
        if(DLX >= 1){
            DLX--;
        }
        $("#DLX").val(DLX);
        summary();
    });$( "#plusDLX" ).click(function() {
        var DLX = $("#DLX").val();
        DLX++;
        if(DLX >= 10){
            DLX=10;
        }
        $("#DLX").val(DLX);
        summary();
    });
    $( "#minusSUI" ).click(function() {
        var SUI = $("#SUI").val();
        if(SUI >= 1){
            SUI--;
        }
        $("#SUI").val(SUI);
        summary();
    });$( "#plusSUI" ).click(function() {
        var SUI = $("#SUI").val();
        SUI++;
        if(SUI >= 10){
            SUI=10;
        }
        $("#SUI").val(SUI);
        summary();
    });
});

function summary() {
     var x = 1; // 1 if it is a number
     //empty the room price and romm name summary
     $('.summaryPrice').empty();
     $('.summaryRoom').empty();

     var intRegex = /^\d+$/;
     var night = $("#noOfDay").val();
     var totalPrice = 0;
     var totalPerNight = 0;
     var priceArray = new Array();

     var STD = $('#STD').val();
     var STDPrice = $('#STDHidden').val();

        if(STD === ''){  STD  = 0;}
        if(intRegex.test(STD)){ if(x === 0){ x=0;}else{x=1;}  }
        else { x=0; }

    var DLX = $('#DLX').val();
    var DLXPrice = $('#DLXHidden').val();
        if(DLX === ''){  DLX  = 0;}
        if(intRegex.test(DLX)){ if(x === 0){ x=0;}else{x=1;}  }
        else { x=0; }

    var SUI = $('#SUI').val();
    var SUIPrice = $('#SUIHidden').val();
        if(SUI === ''){  SUI  = 0;}
        if(intRegex.test(SUI)){ if(x === 0){ x=0;}else{x=1;}  }
        else { x=0; }

     if (x === 0) {//check whether input is number
            // alert('Please insert number instead of text');
        } else {
            //get price list from the webservice here
            STDPrice = STD  * 129;
            totalPerNight = totalPerNight + STDPrice;
            if(STD !=0 && STD > 0){ $(".summaryRoom").append("" + STD + " Standard Room" + "
");
             $(".summaryPrice").append("" + STDPrice + "
")};
            DLXPrice = DLX  * 159;
            totalPerNight = totalPerNight + DLXPrice;
            if(DLX !=0 && DLX > 0){ $(".summaryRoom").append("" + DLX + " Deluxe Room" + "
");
             $(".summaryPrice").append("" + DLXPrice + "
")};
            SUIPrice = SUI  * 189;
            totalPerNight = totalPerNight + SUIPrice;
            if(SUI !=0 && SUI > 0){ $(".summaryRoom").append("" + SUI + " Suite Room" + "
");
             $(".summaryPrice").append("" + SUIPrice + "
")};

             $('.displayRoom').empty();
        }
}
//change to PHP//
/*function submitPageTwo(){
        var x = 0; //0 means no room is selected
        var url = "http://localhost/reserve/app/customer.php?cid="+cid+"&cod="+cod+"&night="+night;

        var STD = $('#STD').val();
        if(STD == 0 && x == 0){  x = 0;}
        else{x = 1;}
        var DLX = $('#DLX').val();
        if(DLX == 0 && x == 0){  x = 0;}
        else{x = 1;}
        var SUI = $('#SUI').val();
        if(SUI == 0 && x == 0){  x = 0;}
        else{x = 1;}

        if (x === 0) {
            alert ("Please select a room!");
        }
        else {
            window.location.href = url;
        }
}*/

function closePageOne() {
    window.location="http://localhost/reserve/app/check.php";
}

If anyone could help, I would appreciate it..
Thanks so much

A: I had changed the structure. Below are the SOLVED codes:

ROOM SELECTION

                    <form name="selectRoom" method="get">

                                    Room Selected:

                                    <select name = "roomName">
                                    <option>Select Room</option>
                                    <option>Standard Room</option>
                                    <option>Deluxe Room</option>
                                    <option>Suite Room</option>
                                    </select>

                                    Number of Room:

                                    <select name = "noRoom">
                                    <option>Number of Room</option>
                                    <?php
                                    for($counter=1;$counter<=5;$counter++){
                                        if($counter < 6)
                                            $prefix = "0";
                                        else
                                            $prefix = "";
                                            print("\n<option>$prefix$counter</option>");
                                    }
                                    ?>
                                    </select>

                            <input type="button" class="popUpButton" onclick="closePageOne()" value="Cancel">
                            <input type="submit" name="roomButton" class="popUpButton" value="Next"/>

                    </form>

<?php
}
else{
    $room_name = $_GET['roomName'];
    $noRoom = $_GET['noRoom'];

    if(($room_name == "Select Room") || ($noRoom == "Number of Room")){
        echo 'Please provide the room type and number of room
Back To Room Page';
    }
    else{
        mysql_query("INSERT INTO `room`(`room_name`, `noRoom`) VALUES ('$room_name','$noRoom')");
        Header("Refresh: 1; url = customer.php");
    }
}
?>


text:
Q: Python unpack binary data, numeric of length 12 I have a file with big endian binaries.  There are two numeric fields.  The first has length 8 and the second length 12.  How can I unpack the two numbers?
I am using the Python module struct (https://docs.python.org/2/library/struct.html) and it works for the first field
num1 = struct.unpack('>Q',payload[0:8])

but I don't know how I can unpack the second number.  If I treat it as char(12), then I get something like '\x00\xe3AC\x00\x00\x00\x06\x00\x00\x00\x01'.
Thanks.

A: I think you should create a new string of bytes for the second number of length 16, fill the last 12 bytes with the string of bytes that hold your number and first 4 ones with zeros.
Then decode the bytestring with unpack with format >QQ, let's say to numHI, numLO variables. Then, you get final number with that: number = numHI * 2^64 + numLO*. AFAIR the integers in Python can be (almost) as large as you wish, so you will have no problems with overflows. That's only rough idea, please comment if you have problems with writing that in actual Python code, I'll then edit my answer to provide more help.
*^ is in this case the math power, so please use math.pow. Alternatively, you can use byte shift: number = numHI << 64 + numLO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syntax to read a file from while-do loop in shell script This shell script contains a while loop:
while IFS = \| read SourceDB db_name Mysql_table hdfsdir libpath
do
    # jobs

done < $/root/SqoopWrapper/InputFile

exit 0

The shell script contains an input file that I want to loop
On execution, am getting

" syntax error near unexpected token `done "

A: Get rid of the spaces in the assignment.
while IFS=\| read SourceDB db_name Mysql_table hdfsdir libpath

You can use ShellCheck to catch these kinds of errors in the future.
$ shellcheck myscript

Line 1:
while IFS = \| read SourceDB db_name Mysql_table hdfsdir libpath
      ^-- SC2162: read without -r will mangle backslashes.
          ^-- SC1068: Don't put spaces around the = in assignments.


text:
Q: print statement executes more times than expected k = 0
while k < 8:
    if k % 2 == 0:
        print('in da loop')
    k = k + 1

OUTPUT:
in da loop
in da loop
in da loop
in da loop

This in da loop was output 4 times.
Because I am thinking in da loop should be only output once.
Subsequent output should be like:
k = 0+1 = 1
since k=1 & greater than 0
There should be no further output.

A: Indented like this
k = 0
while k < 8:
    if k % 2 == 0:
        print('in da loop')
    k = k + 1

If will print "in da loop" four times, when k is 0, 2, 4 and 6.
Indented like this:
k = 0
while k < 8:
    if k % 2 == 0:
        print('in da loop')
        k = k + 1

It will print "in da loop" once and the loop never ends.

A: For this python code (whitespace is important in Python!):
k = 0
while k < 8:
    if k % 2 == 0:
        print('in da loop')
    k = k + 1

There are eight iterations of the loop.
Only four of those numbers are even.
So the print happens four times.
For this code:
k = 0
while k < 8 and k % 2 == 0:
    print('in da loop')
    k = k + 1

The print will happen only once. If you expected your loop only to print once, you meant to also put the other check in the while loop.
Personally, if you expect to only have one print, I would shorten your code to this:
print('in da loop')


text:
Q: Does .NET MVC work when System.Web.Mvc is loaded in the GAC? Is it allowed to put System.Web.Mvc in the GAC? Allowed as in: does it work?
I have done this and all my projects have problems inheriting from System.Web.Mvc.ViewPage...
EDIT
Hope this doesn't scare you:
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE> "c:\WINDOWS\Microsoft.NET\Framework\v3.5\vbc.exe" /t:library /utf8output /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\56b70440\003d6f34_8989c901\EntitySpaces.SqlServerCeProvider.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Abstractions\3.5.0.0__31bf3856ad364e35\System.Web.Abstractions.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\de7cc3b4\0097d136_8989c901\EntitySpaces.LoaderMT.DLL" /R:"C:\WINDOWS\assembly\GAC_32\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\2afa6c79\006aa035_8989c901\EntitySpaces.NpgsqlProvider.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\4a9a547a\006aa035_8989c901\EntitySpaces.OracleClientProvider.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\ea5276d6\0051153a_699ec901\System.Web.Mvc.DLL" /R:"C:\WINDOWS\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\f8843c3a\0097d136_8989c901\EntitySpaces.Web.Design.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\4137948d\003d6f34_8989c901\EntitySpaces.Npgsql2Provider.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\b72019d9\003d6f34_8989c901\EntitySpaces.MySqlClientProvider.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Data.DataSetExtensions\3.5.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_global.asax.hiqvxvcm.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Data.Linq\3.5.0.0__b77a5c561934e089\System.Data.Linq.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\ad4567e4\006aa035_8989c901\EntitySpaces.Loader.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\b543038f\006aa035_8989c901\EntitySpaces.Core.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\701637c6\003d6f34_8989c901\EntitySpaces.VistaDBProvider.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_vpbbzwke.dll" /R:"C:\WINDOWS\assembly\GAC_32\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\66dcb3ba\006aa035_8989c901\EntitySpaces.Web.DLL" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.ServiceModel.Web\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Routing\3.5.0.0__31bf3856ad364e35\System.Web.Routing.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\EC\1.0.0.0__2fce90138e5217ab\EC.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll" /R:"C:\WINDOWS\assembly\GAC_MSIL\System.IdentityModel\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\750052d7\716d39b6_bfd3c901\VandaagLijst.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\d5308498\003d6f34_8989c901\EntitySpaces.MSAccessProvider.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\5ad7a5b5\006aa035_8989c901\EntitySpaces.SqlClientProvider.DLL" /R:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\assembly\dl3\54566418\003d6f34_8989c901\EntitySpaces.Interfaces.DLL" /out:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.dll" /debug- /win32resource:"c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\p7uswgud.res" /define:_MYTYPE=\"Web\" /imports:Microsoft.VisualBasic,System,System.Collections,System.Collections.Specialized,System.Configuration,System.Text,System.Text.RegularExpressions,System.Web,System.Web.Caching,System.Web.SessionState,System.Web.Security,System.Web.Profile,System.Web.UI,System.Web.UI.WebControls,System.Web.UI.WebControls.WebParts,System.Web.UI.HtmlControls,System.Web.Mvc,System.Web.Mvc.Ajax,System.Web.Mvc.Html,System.Web.Routing,System.Linq,System.Collections.Generic,EC /warnaserror- /optionInfer+  "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.0.vb" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.1.vb" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb" "c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.3.vb"

Microsoft (R) Visual Basic Compiler version 9.0.30729.1
Copyright (c) Microsoft Corporation.  All rights reserved.
C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(1) : error BC30456: 'Title' is not a member of 'ASP.views_home_list_aspx'.
        __ctrl.Title = ""
        ~~~~~~~~~~~~

C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(1) : error BC30456: 'InitializeCulture' is not a member of 'ASP.views_home_list_aspx'.
        Me.InitializeCulture
        ~~~~~~~~~~~~~~~~~~~~

C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(1) : error BC30456: 'MasterPageFile' is not a member of 'ASP.views_home_list_aspx'.
        __ctrl.MasterPageFile = "~/Views/Shared/Site.Master"
        ~~~~~~~~~~~~~~~~~~~~~

C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(7) : error BC30456: 'AddContentTemplate' is not a member of 'ASP.views_home_list_aspx'.
        Me.AddContentTemplate("TitleContent", New System.Web.UI.CompiledTemplateBuilder(AddressOf Me.__BuildControlContent1))
        ~~~~~~~~~~~~~~~~~~~~~

C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(11) : error BC30456: 'AddContentTemplate' is not a member of 'ASP.views_home_list_aspx'.
        Me.AddContentTemplate("MainContent", New System.Web.UI.CompiledTemplateBuilder(AddressOf Me.__BuildControlContent2))
        ~~~~~~~~~~~~~~~~~~~~~

C:\Bugging\VandaagLijst\VandaagLijst\Views\home\List.aspx(13) : error BC30451: Name 'Model' is not declared.
       For Each item In Model
                        ~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(42) : error BC30198: ')' expected.
    Inherits System.Web.Mvc.ViewPage(of IEnumerable(of Models.TestClass)
                                                                       ~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(43) : error BC30154: Class 'views_home_list_aspx' must implement 'ReadOnly Property IsReusable() As Boolean' for interface 'System.Web.IHttpHandler'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers.
    Implements System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler
                                                              ~~~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(43) : error BC30149: Class 'views_home_list_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler'.
    Implements System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler
                                                              ~~~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(55) : error BC30311: Value of type 'ASP.views_home_list_aspx' cannot be converted to 'System.Web.Mvc.ViewPage'.
        CType(Me,Global.System.Web.Mvc.ViewPage).AppRelativeVirtualPath = "~/Views/home/List.aspx"
              ~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(57) : error BC30456: 'ReadStringResource' is not a member of 'ASP.views_home_list_aspx'.
            Global.ASP.views_home_list_aspx.__stringResource = Me.ReadStringResource
                                                               ~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(61) : error BC30456: 'GetWrappedFileDependencies' is not a member of 'ASP.views_home_list_aspx'.
            Global.ASP.views_home_list_aspx.__fileDependencies = Me.GetWrappedFileDependencies(dependencies)
                                                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(68) : error BC30456: 'Context' is not a member of 'ASP.views_home_list_aspx'.
            Return CType(Me.Context.Profile,System.Web.Profile.DefaultProfile)
                         ~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(74) : error BC30456: 'Context' is not a member of 'ASP.views_home_list_aspx'.
            Return CType(Me.Context.ApplicationInstance,ASP.global_asax)
                         ~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(193) : error BC30284: sub 'FrameworkInitialize' cannot be declared 'Overrides' because it does not override a sub in a base class.
    Protected Overrides Sub FrameworkInitialize()
                            ~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(195) : error BC30456: 'SetStringResourcePointer' is not a member of 'ASP.views_home_list_aspx'.
        Me.SetStringResourcePointer(Global.ASP.views_home_list_aspx.__stringResource, 0)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(197) : error BC30456: 'AddWrappedFileDependencies' is not a member of 'ASP.views_home_list_aspx'.
        Me.AddWrappedFileDependencies(Global.ASP.views_home_list_aspx.__fileDependencies)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(201) : error BC30284: function 'GetTypeHashCode' cannot be declared 'Overrides' because it does not override a function in a base class.
    Public Overrides Function GetTypeHashCode() As Integer
                              ~~~~~~~~~~~~~~~

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\24f69041\8efa8a35\App_Web_p7uswgud.2.vb(206) : error BC30284: sub 'ProcessRequest' cannot be declared 'Overrides' because it does not override a sub in a base class.
    Public Overrides Sub ProcessRequest(ByVal context As System.Web.HttpContext)
                         ~~~~~~~~~~~~~~

A: It works at runtime. You still need to have a referenced assembly. How are you referencing the assemblies for your build/VS.NET environment?
As you can see from here...
http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx
... the default is to install these assemblies into the GAC and you have to explicity work around this if you want to bin-deploy your MVC assemblies (for example, in a shared hosting situation).


text:
Q: Как удалить приложение с heroku? Я только начал разбираться как работать с heroku и пока разбирался исчерпал лимит в 5 бесплатных приложений (на node.js). Где можно посмотреть url по которым доступны опубликованные мною приложения и их репозитории на GitHub и как можно удалить приложения?

A: Уничтожьте приложение:
heroku apps:destroy --app example

Создайте новое:
heroku create example

Нажмите на него:
git push heroku -u master

A: Вывести список приложений:
heroku apps

Уничтожить приложение:
heroku apps:destroy --app <Apps Name> --confirm <Apps Name>


text:
Q: How to delete non-system apps from android using adb? I am trying to write a script to clean up android devices before some automated tasks. So I'm looking for some way to remove all the non-system apps from the phone, using adb, as I continuously find that people love installing heavy games on those devices. (These are our work devices) :D I couldn't find anything useful till now, as most questions I found were about deleting the system apps.
I am able to list all the installed apps using adb
adb -s <device id> shell pm list packages -f | cut -d '=' -f 2

But that gives all the apps that are installed, including some of these:
com.android.backupconfirm
com.android.packageinstaller
com.android.providers.userdictionary
com.android.providers.downloads.ui
com.android.externalstorage
com.google.android.nfcprovision
com.google.android.apps.docs.editors.docs
com.google.android.apps.cloudprint

I'm afraid, if I accidentally uninstall them, the phone will become useless.
Can someone suggest a way to delete only the applications installed by others ?

A: for pkg in $(adb shell pm list packages -3 | cut -d: -f2); do
  adb uninstall $pkg
done


text:
Q: Principle of relativity and the train and ball example I have a question about the theory of relativity. I took a lesson on brilliant.org, maybe you have heard about this educational platform.
And the example with the ball and the train is completely incomprehensible to me.
Their theory states that if a train that is moving at a speed of 200 km/h collides with a stationary ball, then the ball will move at a speed of 400 km/h from the point of view of the observer.
But I still don't understand why.
It seems to me that the ball would move with such a speed if it also moved at a speed of 200 km / h and then, upon collision, it began to move at a speed of 400 km / h.
I apologize in advance for the stupid question.
link to lesson - https://brilliant.org/courses/puzzle-science/introduction-64/science-rules-3-diagrammar/1/

A: As others have noted, this could be called "classical" or "Galilean" relativity, which is not what the Einstein theory is that most people associate with the word.
Assuming this is an ordinary elastic collision obeying Newtonian mechanics, the ball moves with twice the speed after the train impacts it for the same reason that a falling ball bounces off the ground and returns upward. If there is no energy loss, it bounces upwards with the same speed it impacted the ground, which is a change in velocity of 2 times the initial velocity (velocity is speed with a direction). So, if you go into a frame where the ball is stationary and the ground is moving toward the ball instead, after the impact the ball is moving away with twice the speed of the ground (draw some pictures and convince yourself that is true). In the train example, the train is the earth and the velocity is horizontal rather than vertical, but the principle is the same. A massive object hitting a stationary tiny object elastically causes the tiny object to move with twice the speed of the massive one.
The ability to change reference frames, between the one where the train is moving and the ball stationary and the one where the ball is moving and the train is stationary, is basically "the principle of relativity." However, this version of it is weak, it does not actually preserve all the laws of physics.

A: According to the principle of (classical) relativity, the laws of mechanics are valid for all inertial frames of reference.
The train is moving with constant velocity, so it is an inertial frame. From the train's frame, there is a ball hitting it at 200 km/h. Supposing an elastic collision, the ball will bounce back with the same speed. The recoil of the train is supposed negligible due to its huge mass.
For a ground observer, a ball with a speed 200 km/h bigger than the train has 400 km/h.

A: Evidently your model involves an idealized perfectly elastic collision.  I am all in favor of idealized conditions.
Let's go to the pool table.  The cue ball slams into the 8-ball, perfectly elastic collision.  The cue ball comes to a complete halt, and the 8-ball has takeaway speed EXACTLY equal to original cue ball speed.
Now let a train slam into the 8-ball.  The train is a million times more massive than the 8-ball.  The train hardly slows down at all and the 8-ball has bounce speed just about double train speed.  But not EXACTLY double, even under ideal conditions.
This post has nothing to do with Special Relativity UNLESS you consider speed v = 400 kilometers per hour in relation to speed-of-light c = 1 billion kilometers per hour.  And your problem is v²/c².  It's maybe one part in 10¹³ .


text:
Q: this.props... is not a function react react-redux I have a problem with dispatching a action from componentDidMount...
error is : TypeError: this.props.postDetails is not a function
Action.js
export const postDetails = data => ({
        type: "POST_DETAILS",
        post: data
})

Container/GetDetails.js
import Details from '../components/Details'
import { postDetails } from '../actions'

const mapStateToProps = state => ({ post: state.post });

const mapDispatchToProps = dispatch => bindActionCreators({postDetails}, dispatch);

const GetDetails = connect(
    mapStateToProps,
    mapDispatchToProps
)(Details)

export default GetDetails

Component/Details.js
import React from 'react'
import { postDetails } from '../actions'

class Details extends React.Component {
    constructor(props){
        super(props);
    }

    componentDidMount() {
        console.log("did mount details");
        this.props.postDetails();
    }

    render() {
        return (
            <div>
                Details page
            </div>
        )
    }
}

export default Details;

Can someone help me? Why i have this error?

A: In App.js (or wherever you are importing the Details component), are you using the path to your GetDetails container (not component)?
I moved state from a component to a container and forgot to update the import path which gave me this same error. Updating the import path to the container took care of it.
Edit:
For example, I have an apiLanding folder that has apiLanding.js (the component) and apiLanding-container.js (the container).
In my app.js, I needed to change
import apiLanding from './components/apiLanding/apiLanding';
to
import apiLanding from './components/apiLanding/apiLanding-container';
That way, the app now has access to the redux state and actions. This was a silly mistake and may not be your issue, but wanted to share just in case the import path was overlooked.

A: You have to return an object, where the keys are your props. See docs.
const mapDispatchToProps = dispatch => ({ postDetails: bindActionCreators({postDetails}, dispatch) })

Or, you can use the shorthand notation:
const GetDetails = connect(
    mapStateToProps,
    { postDetails }
)(Details)

A: I don't see bindActionCreator imported. Use eslint to get rid of these errors

A: There are two things which don't really seem right to me. Personally I never used bindActionCreators. I would just create my mapDispatchToProps as following:
const mapDispatchToProps = dispatch => {
  return {
    postDetails: () => dispatch(actions.postDetails)
  };
};

But also your postDetails call expects an argument, which you should add in your function call. So your mapDispatchToProps would look like this:
const mapDispatchToProps = dispatch => {
      return {
        postDetails: (data) => dispatch(actions.postDetails(data))
      };
    };

Also you're importing your action as postDetails. Are you sure that this is just one action? And not a combination of all actions in your file? Note how I added your function as actions.postDetails instead of just postDetails.


text:
Q: magento 1 database migrations rollback I am interested in studding magento migrations.
I know how magento does migration from one module version to another.
But I didn't find a "Rollback" function in each of migration files.
As I see all magento module "install" scripts are simple php scenarios with code:
/** @var $installer Mage_Sales_Model_Entity_Setup */
$installer = $this;
$installer->startSetup();

// do some stuff

$installer->endSetup();

Or event simpler:
$installer = $this;
/* @var $installer Mage_Core_Model_Resource_Setup */

$installer->getConnection()->addColumn($this->getTable('googlebase/types'), 'target_country', "varchar(2) not null default 'US'");

So, how magento knows what to do in case you need to change your version from 1.1.0 to 1.0.9, for example.
And how can I rollback to any version that I need?
Thanks!

A: Rollbacks are manual reversion to a pre-upgrade database version.
Always test the upgrade process on a development environment thoroughly to make sure that the upgrade will be successful, always back up the database before committing live and always have a standard set of tests to run after you do the upgrade.
Standard procedure for an upgrade is to duplicate your live database and upgrade on the duplicate.


text:
Q: Cause a second namespace to choose which third namespace to load Namespace foo defines a set of functions defined in terms of arithmetic operators.  These are either scalar arithmetic operators or matrix arithmetic operators, depending on whether foo requires the scalar-arithmetic or matrix-arithmetic namespace.  (There's not a lot of code in foo.cljc, but it's enough that it would be silly to duplicate it.  I know that core.matrix--which is what matrix-arithmetic is defined in terms of--can handle raw scalars, but in that case it's a lot slower than Clojure's built-in arithmetic, and speed of foo's functions will matter for my application.)
Namespace bar-s needs scalar arithmetic.  Namespace bar-m needs matrix arithmetic.  Both namespaces need the functions defined in namespace foo, but bar-s needs those functions in their scalar versions, while bar-m needs them in their matrix form.  We can assume that I will only load one of bar-m and bar-s in the same session.  (If I don't need this assumption, that's great, but I can live with it.)
I'm trying to figure out the best way for bar-s or bar-m to specify which version of foo to load--that is, how to force foo to load the scalar-arithmetic namespace, or to load the matrix-arithmetic namespace.  (Or: If there's a better, very different way to accomplish what I'm trying to do, I'm happy to rethink it.)
Currently, this is what I'm doing.  It seems to work: I have another namespace, config, in which I define an atom containing a boolean.  In bar-s or bar-m, I reset this atom to a value that will select the arithmetic implementation I want, and then I require foo.  foo checks the atom, and then requires either scalar-arithmetic or matrix-arithmetic, depending on the atom.
This might be the best way to do what I want, but it's a strange method, and I wonder whether there's a better way.  I think that if I only reset the atom at the beginning of a session, I won't have problems, but I'm worried that there are gotchas I don't know about.
Here's a toy version of the setup:
(ns scalar-arithmetic)

(defmacro m* [x y] `(* ~x ~y))
;; Using (def m* *) instead would lose Clojure's special optimizations for *

(defmacro inv [x]  `(/ 1.0 ~x))

;;;;;;;;;;;;;;;;;
(ns matrix-arithmetic
  (:require [clojure.core.matrix :as mx]))

(def m* mx/mmul)     ; matrix multiplication
(def inv mx/inverse) ; matrix inverse

;;;;;;;;;;;;;;;;;
(ns foo
  (require [config]))

(if @config/use-core-matrix
   (require '[matrix-arithmetic :refer [m* inv]])
   (require '[scalar-arithmetic :refer [m* inv]]))

(defn fooey [r s] (m* r (inv s))) ; could have either scalar or matrix meaning

;; The next two namespaces would not both be loaded in the same session.

;;;;;;;;;;;;;;;;;
(ns bar-s
   (require [config]))

(reset! config/use-core-matrix true)
(require '[foo])

;;;;;;;;;;;;;;;;;
(ns bar-m
  (require [foo])) ;; default value of use-core-matrix is false, so this is enough.


text:
Q: More efficient way to build/transfer a large data structure? I'm building a mobile Boggle-type web app with node.js. I'm trying find a more efficient way to load/build a massive dictionary (180,000+ words). I currently have it working but the load time is slightly long. Users have to wait about 15 seconds for the entire thing to build and some users time-out before the entire thing has loaded. I was wondering if anyone has any tips to improve the speed.
The way I'm currently doing this (which is probably completely inefficient):

*

*I broke down the list into 26 arrays, one for each letter, and stuck each array in it's own javascript file.

*When the app loads it runs a recursive function which gets the next js file and loads in the array from it overwriting the previous one. And then, it loops through the entire array and loads each new word into my Trie datastructure.

*The files with the arrays in them combined are around 2mb. After being combined the datastructure itself clocks in at round 12mb, which isn't so bad on a desktop computer, but does weigh down a couple of my users' smartphones.

This needs to be built on the client side to allow instant lookups. The way I'm doing it currently works but I know there has to be a better way.

A: The other other tactic is to convert your recursive code into non-recursive code that uses an explicit stack, saving only the objects you actually need.
Have you tried profiling your code?

A: To answer the question of the fastest loading time, are you doing it in this fashion? (aka, without more code, we can't possibly know)
function LoadFiles(fileArray){
  file = fileArray.slice(); //get the first file.
  $.ajax(file).success(function(data){
    /* yes, my object is a little funky, I'm focused on writing pseudocode */
    wordLibraryAdd(data);

    if (fileArray.length) // on a zero length quit processing
    setTimeout(function(){ LoadFiles(fileArray) }, 50) //a 50 ms buffer between each loading isn't bad.
  })
}


text:
Q: ArcGIS 401 error during initialization of javascript map I have a dumbed-down application to only reference a geometry service, and a feature service.
When the map is being initialized, it sends out a GET request of:
http://my.server.com/ArcGISTEST/rest/info?f=json but when using Chrome debug tools / fiddler I see it is returning HTTP 401 error
when I open this url in its own window/tab it produces the following output:
{"currentVersion":10.02,"soapUrl":"a url is in here","secureSoapUrl":"a url is in here","authInfo":{"isTokenBasedSecurity":false}}
It appears this is an object to determine the status/capability of the arcgis server to assist the javascript api.
Why am I getting this error?  How do I resolve it?  Could this be a symptom of my bigger problem (unable to edit features via javascript api).

A: This is a guess - but, if your viewer is not secured and your services are secured, then the browser might be re-using the HTTP connection (using HTTP keepalive) when the requests for your services are made.
To avoid this, apply the same security to your viewer as what would be used on the ArcGIS server.  Then, the browser will be forced to log in on the first page load and will continue to use the login credentials for subsequent requests.

A: This is one of the cross domain situation as the blow url shows:
https://developers.arcgis.com/javascript/latest/guide/cors/index.html


text:
Q: Trying to edit History or Drafts list when Delete action is visible does nothing Steps to reproduce:

*

*Navigate to the "History" or "Drafts" section of the app.

*Swipe one of the rows in the table to reveal the "Delete" UITableViewRowAction.

*Press the edit button.

Expected behavior:
The table view enters the edit state.
Actual behavior:
Nothing happens.
Additional notes:
I know this is annoying, but you may want to keep track of the current cell that has the UITableViewRowAction visible in order to reset the table view state.  Or reload the row.

*

*App Version: 1.6.1.2

*Device: iPhone 6

*OS Version: Version 9.3.4 (Build 13G35)


text:
Q: Making SQL query more efficient How can I make this SQL query more efficient?
SELECT
  (SELECT COUNT(*) FROM table WHERE price < 10) AS priceUnder10,
  (SELECT COUNT(*) FROM table WHERE price BETWEEN 10 AND 20) AS price10to20,
  (SELECT COUNT(*) FROM table WHERE price > 20) AS priceOver20,
  (SELECT COUNT(*) FROM table WHERE colour = 'Red') AS colourRed,
  (SELECT COUNT(*) FROM table WHERE colour = 'Green') AS colourGreen,
  (SELECT COUNT(*) FROM table WHERE colour = 'Blue') AS colourBlue;

I already have indexes on the price and colour columns, so I am looking for a better way to aggregate the data.
I have looked into using GROUP BY, HAVING, self-joins and window functions, but cannot work out how to achieve the same result.
Any suggestions much appreciated.

A: SELECT
       COUNT(CASE WHEN price < 10 THEN 1 END) AS priceUnder10,
       COUNT(CASE WHEN price BETWEEN 10 AND 20 THEN 1 END) AS price10to20,
       COUNT(CASE WHEN price> 20 THEN 1 END) AS priceOver20,
       COUNT(CASE WHEN colour = 'Red' THEN 1 END) AS colourRed,
       COUNT(CASE WHEN colour = 'Green' THEN 1 END) AS colourGreen,
       COUNT(CASE WHEN colour = 'Blue' THEN 1 END) AS colourBlue
from YourTable
WHERE price IS NOT NULL OR  colour IN ('Red','Green','Blue' )

A: Depending on how your database handles boolean expressions, this:
select sum(price<10),sum(price between 10 and 20)...  from tab;

or this
select sum(case when price<10 then 1 else 0 end),sum(case when price between 10 and 20 then 1 else 0 end)...  from tab;

might help.

A: SELECT count(*) as products,

if(price < 10, 'price band 1',
 if (price between 10 and 20, 'price band 2',
  'price band 3'
 )
) as priceband,
  t.colour

from table t
group by t.colour, pricebrand

That will give you
products    colour    priceband
53          red       price band 1
65          red       price band 2
12          blue      price band 1
23          blue      price band 2

etc.


text:
Q: Transitivity of a flow and its time-1 map Let $M$ be a closed manifold, $f:M\to M$ be a homeomorphism,  and $\phi_t:M\to M$ be a flow. .
The map $f$ is said to be  (point)-transitive if some orbit $\lbrace f^nx:n\in\mathbb{Z}\rbrace$ is dense in $M$.
The flow $\phi_t$ is said to be  (flow)-transitive if some flow line $\lbrace\phi_tx:t\in\mathbb{R}\rbrace$ is dense in $M$.
My first question is:

*

*is there any sufficient condition under which the time-1 map of a transitive flow is still transitive?

In the following we assume $f$ is (point)-transitive and consider a special class of flows: suspensions of $f$.
Let $r\le R$ be positive numbers and $c:M\to[r,R]$ be a continuous suspension function. Let $M_c=\lbrace(x,r):0\le r\le c(x),x\in M\rbrace/\sim$ where $(x,c(x))\sim(fx,0)$, and $f_t:M_c\to M_c$ represented by the time-translation $(x,r)\mapsto(x,r+t)$.
According to our definition, the suspension flow $f_t:M_c\to M_c$ is (flow)-transitive.
If $c\equiv1$, it is easy to see that the time-1 map $f_1$ is not transitive (as a homeomorphism on $M_1$). So my second question is:

*

*is the time-1 map $f_1:M_c\to M_c$ (point)-transitive whenever $c$ is not constant?

Any proof or reference are good. Thank you!

As suggested by Zarathustra, it is worth to point out that the time-1 map of constant suspension flow with $c=\sqrt{2}$ is also (point)-transitive.

A: I think the answer for the second question is no. We can construct a counterexample as follows:
Let $f\colon M\to M$ be an arbitrary transitive homeomorphism and $u\colon M\to\mathbb (0,1/4)$ be an arbitrary non-constant continuous function. Then, let's define $$c(x):=u(x)-u(f(x))+1,\quad\forall x\in M,$$
and consider the flow $f_t\colon M_c\to M_c$ as above.
We claim $f_1$ is not transitive. In fact, given any $x\in M$ and any $t\in (0,1/4)$ it holds:
$$f_1(x,u(x)+t)=(x,u(x)+t+1)=(x,c(x)+u(f(x))+t)=(f(x),u(f(x))+t).$$
That means that every compact set $U_t:=\lbrace (x,u(x)+t) : x\in M\rbrace \subset M_c$ is $f_1$-invariant and hence it cannot be transitive. Notice the function $c$ is not constant because $f$ is transitive $u$ is not constant itself.


text:
Q: How can I change the "From" email address without a non-authenticated SMTP server? All,
I'm writing an application that will allow customers to submit support tickets directly from their desktop. That being said, I'd like the "FROM" email address to be their email address.
I currently have the following code:
public void SendTicketEmail()
    {
        try
        {
            string tEmail = materialListView1.SelectedItems[0].SubItems[1].Text;
            string tPhone = materialListView1.SelectedItems[0].SubItems[2].Text;
            string tUser = materialListView1.SelectedItems[0].Text;

            MailMessage mail = new MailMessage(tEmail, "my email");
            SmtpClient client = new SmtpClient();
            client.Port = 25;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Host = "smtp.simplifymsp.com";
            mail.Subject = "this is a test email.";
            mail.Body = "this is my test email body";
            client.Send(mail);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }
    }

I'm assuming that my resolution at this point is to request that my hosting service enable an option where I can allow smtp outgoing emails without authentication on a specified port?
The alternative here is to have all of the support emails from each customer come from one of my preset email addresses and include a Customer ID in the subject, then create a workflow in my helpdesk ticketing system for each customer that assigns the  customer's information to that ticket. That's more work than I care to do, especially when scaling.
Thank you in advance.

A: For what it's worth, I resolved this issue rather simply. FreshService (the website that I use for my ticketing system) reacts well with the following code:
mail.From = new MailAddress("me@me.com", "customer@customer.com");

Even though the email is coming from "me@me.com," FreshService still reads the ticket as if it came from the customer. Works beautifully.
Thank you all for your time.


text:
Q: Mudar o valor do campo dinamicamente Olá, gostaria de ajuda com meu código, eu queria que quando o usuário clicasse no campo com a lupa:

O valor do campo status:
<?php $status = $dados['status'];
Mudasse, dinamicamente no banco de "N" para "S". Inicialmente o valor salvo para todas publicações é "N" mas eu quero que mude para "S", quando o usuário clicar.
Estou fazendo isso que é semelhante ao whatsapp; ao clicar fica como visualizado, mas é uma aplicação em PHP, um site.
Procurando vi que javascript e ajax já resolveriam isso, mas eu não sei como(vi também que onClick=function() já resolveria); eu montei um if para recuperar os valores depois com refresh.
<?php $status = $dados['status'];
        if  ($status == "N"){
            echo "";}
        else if($status == "S"){
            echo "";
} ?>

A: Eu faria isso usando jQuery. Fiz um fiddle que exemplifica como você deve implementar essa funcionalidade.
Basicamente você pega o evento de clique do elemento e faz uma chamada AJAX para a URL que fará a mudança no banco, nesse caso você precisará de um código simples em PHP para fazer isso. A seguir um exemplo de como seria, você teria que adaptar para o seu caso.
<?php
if (isset($_POST['status']) && isset($_POST['id'])) {
    $status = $_POST['status'];
    $id = $_POST['id'];

    // Atualiza no banco de dados
    $servername = 'localhost';
    $dbport = 123;
    $database = 'nome_db';
    $username = 'root';
    $password = 'senha123';

    $db = new PDO("mysql:host=$servername;port=$dbport;dbname=$database", $username, $password);
    $stmt = $db->prepare("UPDATE mensagem SET status='?' WHERE id='?'");
    $data = array($status, $id);

    if ($stmt->execute($data))
        echo '1'; // sucesso
    else
        echo '0'; // falha
} else {
    echo '0'; // falha
}


text:
Q: Inclusion of plugins in maven pom file conditionally (without profiles) I have got a scenario where I should include some special maven plugins w.r.t. jar signing in my root pom.XML file.
As soon as I include them, build fails for me as these jar signer maven plugins are part of only build server and are not locally.
For me, I am looking for a possibility to conditionally include these maven plugins -> based on supplying of a command line argument (similar to activation of profiles)
Note: I don't want to use profile for this usecase, as already in my pom there are too many profiles and if I use this concept then I will end up duplicating lot of code which is difficult for maintenance


text:
Q: Nueva TextView en Loop : "Variable '...' is already defined in the scope" Saludos estimados amigos,
Quisieras compartirles la siguiente consulta:
Cuando agrego una nueva vista (objeto TextView) como se muestra a continuación
    TextView newTextView = new TextView(this);
    newTextView.setText("Hola");
    numbersLayout.addView(newTextView);

    TextView newTextView = new TextView(this);
    numbersLayout.addView(newTextView);

Obtengo un error. Sin embargo, cuando hago lo mismo dentro de un bucle, el Software si me permite realizarlo.
   int i = 0;
   while (i < numbers.size()){

   TextView numberTextView1 = new TextView(this);

   numberTextView1.setText(numbers.get(i));
   numbersLayout.addView(numberTextView1);
   i++;}

Agradecería su respuesta para encontrar la solución.

A: Es interesante tu pregunta!
En el caso de Java y otros lenguajes de programación no puedes declarar en más de una ocasión el mismo nombre de variable, en este caso newTextView.
En android obtendrás el error:

Variable '...' is already defined in the scope

(La variable '...' ya se encuentra definida en el ámbito)

En este caso si defines la variable newTextView, usa esta misma variable para crear otra instancia.
//Define variable newTextView.
TextView newTextView = new TextView(this);
newTextView.setText("Hola");
numbersLayout.addView(newTextView);

//Define una nueva instancia.
newTextView = new TextView(this);
numbersLayout.addView(newTextView);

//Define una nueva instancia.
newTextView = new TextView(this);
numbersLayout.addView(newTextView);

Ahora en el caso de realizarlo dentro de un bucle (for, while, etc..), es valido realizarlo de esta forma:
int i = 0;
   while (i < numbers.size()){

   TextView numberTextView1 = new TextView(this);

   numberTextView1.setText(numbers.get(i));
   numbersLayout.addView(numberTextView1);
   i++;}

pero es importante analizar el alcance (ámbito o scope) de la variable, en este caso se generan los TextView y se agregan a el Layout, pero no podrás modificar sus propiedades posteriormente ya que solo podras usar esta variable dentro del bucle, lo cual podrá no ser tan útil, ya que en este caso no podrías por ejemplo cambiar alguna propiedad de las vistas que agregaste.
Ejemplos:
Dentro del bucle puedes modificar las propiedades:
int i = 0;
while (i < numbers.size()){
    TextView numberTextView1 = new TextView(this);
    numberTextView1.setText(numbers.get(i));
    numberTextView1.setTag(numbers.get(i));
    numbersLayout.addView(numberTextView1);
    i++;

    //Modificando el Texto del TextView con Tag ...
    TextView myTextView = numberTextView1.findViewWithTag("...");
    if(myTextView != null) {
        myTextView.setText("Roy cambia el texto....");
    }
}

pero fuera del bucle no podrás modificar las propiedades de la vista, ya que no puede encontrar la instancia que definiste dentro del bucle:
int i = 0;
TextView numberTextView1 = null;
while (i < numbers.size()){
    numberTextView1 = new TextView(this);
    numberTextView1.setText(numbers.get(i));
    numberTextView1.setTag(numbers.get(i));
    numbersLayout.addView(numberTextView1);
    i++;
}

//Modificando el Texto del TextView con Tag ...
TextView myTextView = numberTextView1.findViewWithTag("...");
if(myTextView != null) {
    myTextView.setText("Roy cambia el texto....");
}

A: No te esta funcionando porque estas declarando con el mismo nombre de variable la instancia de TextView. El siguiente ejemplo funcionara no puedes declarar en una clase dos variables con el mismo nombre en cambio si lo haces en un bucle con una variable creas múltiples instancias de ella.
 TextView newTextView = new TextView(this);
    newTextView.setText("Hola");
    numbersLayout.addView(newTextView);

    TextView newTextView2 = new TextView(this);
    numbersLayout.addView(newTextView);


text:
Q: com.ibatis.common.jdbc.exception.NestedSQLException: Could not start transaction My jsp site as well as asp site started throwing error messages when the transaction log of the Microsoft database got full. So I went in and shrunk the log file and the asp site started working just fine, bu the jsp site is still throwing error about not being able to start a new transaction. I am new to JSP so still trying to figure it out. The JSP site is running on a tomcat server on a windows machine. What do I need to do to kind of reset the jsp site. I have attached the stack trace:

processloginaction com.ibatis.common.jdbc.exception.NestedSQLException: Could not start transaction. Cause: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction. A transaction is already started. Caused by: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction. A transaction is already started. at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.startTransaction(SqlMapExecutorDelegate.java:728) at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.startTransaction(SqlMapSessionImpl.java:129) at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.startTransaction(SqlMapClientImpl.java:101) at action.ProcessLoginAction.execute(ProcessLoginAction.java:170) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684) at java.lang.Thread.run(Thread.java:619) Caused by: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction. A transaction is already started. at com.ibatis.sqlmap.engine.transaction.TransactionManager.begin(TransactionManager.java:46) at com.ibatis.sqlmap.engine.transaction.TransactionManager.begin(TransactionManager.java:39) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.startTransaction(SqlMapExecutorDelegate.java:726) ... 24 more Caused by: com.ibatis.sqlmap.engine.transaction.TransactionException: TransactionManager could not start a new transaction. A transaction is already started. at com.ibatis.sqlmap.engine.transaction.TransactionManager.begin(TransactionManager.java:46) at com.ibatis.sqlmap.engine.transaction.TransactionManager.begin(TransactionManager.java:39) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.startTransaction(SqlMapExecutorDelegate.java:726) at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.startTransaction(SqlMapSessionImpl.java:129) at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.startTransaction(SqlMapClientImpl.java:101) at action.ProcessLoginAction.execute(ProcessLoginAction.java:170) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684) at java.lang.Thread.run(Thread.java:619)

A: I guess restarting the server did the trick for me. But don't understand why?

A: You have probably started another transaction within a currently running transaction.  If you want to run another transaction within one transaction, try using threads


text:
Q: Why is this APC installation failing so badly? I have multiple instances of APC running on my server with similar configurations (albeit with different cache sizes. However, one of the instances is performing extremely poorly, and I have no idea why (100% cache fragmentation, high miss rate).

The runtime settings I'm using are as follows (pretty much out of the box):
apc.cache_by_default        1
apc.canonicalize            1
apc.coredump_unmap          0
apc.enable_cli              0
apc.enabled                 1
apc.file_md5                0
apc.file_update_protection  2
apc.filters
apc.gc_ttl                  3600
apc.include_once_override   0
apc.lazy_classes            0
apc.lazy_functions          0
apc.max_file_size           1M
apc.mmap_file_mask
apc.num_files_hint          1000
apc.preload_path
apc.report_autofilter       0
apc.rfc1867                 0
apc.rfc1867_freq            0
apc.rfc1867_name            APC_UPLOAD_PROGRESS
apc.rfc1867_prefix          upload_
apc.rfc1867_ttl             3600
apc.shm_segments            1
apc.shm_size                10M
apc.slam_defense            1
apc.stat                    1
apc.stat_ctime              0
apc.ttl                     0
apc.use_request_time        1
apc.user_entries_hint       4096
apc.user_ttl                0
apc.write_lock              1

APC is version 3.1.6, PHP is 5.3.3-1ubuntu9.5. I've tried restarting Apache multiple times, so this isn't a freak instance.
The instance with problems is simply running Wordpress with a few plugins installed. All other instances (~4) on the server are running perfectly fine with almost 100% hit rates and 0% fragmentation; for example this instance is holding a website built using the Symfony framework.
Any help would be much appreciated; I haven't had much experience with APC and was hoping for it to be an out-of-the-box speed boost ;).

A: When using APC one of the things you need to ask yourself how much memory will be allocated to APC. apc.shm_size controls how much memory will be allocated.  All my setups are configured to use 30M (I believe 32M is the default option).  Also, check your "cache full count" to ensure APC is actually working.  This shows how often the cache is at maximum capacity.  If the cache is constantly being filled it will certainly take a heavy hit on your scripts performance.  You could also try allowing PHP to use more memory as a test case


text:
Q: Revenue Prediction Neural Network Python I'm trying to create a neural network. I cut a because I have more than 1000 lists.
I saw a lot of tutorials but I need some help:
Can I use a list of list as my database instead of dic?
# a[0] is the price
# a[1] is the paid value
# a[2] is my result

from sklearn.neighbors import KNeighborsClassifier
from pandas import DataFrame
a = [[0.063807299, 0.71, 0.00071],
     [0.363262854, 0.7, 0.0007],
     [0.836344317, 0.76, 0.00076]]

df = DataFrame(a)
df.columns = ['value1', 'value2', 'result']

X_train, y_train = df['value1'], df['value2']
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train, y_train)
knn.score(X_train, y_train)

knn.predict([[1.2, 3.4]])
>>> 0.025  # This would be my results for example

A: Yes, yes you can. This becomes trivial with the pandas library. First you need to import pandas, then with the following code you can convert your list of lists into a pandas dataframe:
df = DataFrame(a, columns=headers)

then you can set up the training set with:
X_train, y_train = df['value1'], df['value2']

Your value2 column is expected to contain labels for the classifier to work with. Labels cannot be of type float for KNN classifiers, so simply adjusting them to integers will solve the problem.
a = [[0.063807299, 71, 0.00071],
     [0.363262854, 7, 0.0007],
     [0.836344317, 76, 0.00076]]

lab_enc = preprocessing.LabelEncoder()
df = DataFrame(a)
df.columns = ['value1', 'value2', 'result']
X_train, y_train = df['value1'].values.reshape(-1,1), df['value2'].values.reshape(-1,1)

knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(X_train, y_train.ravel())
knn.score(X_train, y_train)

print(knn.predict([[0.7]]))


text:
Q: django HttpResponseForbidden not working I'm excepting this code at is_send_permitted_interceptor if true to stop processing and redirect to forbidden. However, it does not, instead it returns the HttpResponseForbidden object in the function.
How do I actually get HttpResponseForbidden() to run in this context.
@login_required
def process_all(request):
    #If we had a POST then get the request post values.
    if request.method == 'POST':
        batches = Batch.objects.for_user_pending(request.user)

        # Will redirect/cancel request if user does not meet requirements, funds, permissions etc
        is_send_permitted_interceptor(request)
        # stuff here if everything is ok

def is_send_permitted_interceptor(request):
    # Check user has required credits in account to these batches.
    balance = Account.objects.get(user=request.user).get_balance()
    cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
    if balance < cost_of_sending:

        return HttpResponseForbidden()
    else:
        pass

A: You need to add return in the caller, because your check function is going to return to the caller, and its value is what you want to return to the browser.
A better approach would be the following:
def is_send_permitted_interceptor(user):
    # Check user has required credits in account to these batches.
    balance = Account.objects.get(user=user).get_balance()
    cost_of_sending = Batch.objects.batches_cost_pending(user=user)
    return balance < cost_of_sending

Then in your caller:
if request.method == 'POST':
    batches = Batch.objects.for_user_pending(request.user)

    if is_send_permitted_interceptor(request.user):
        return HttpResponseForbidden()

This way its the view method is where all the redirects happen; and you avoid having to pass around request.

A: You don't return the output of the "interceptor" in the process_all view, so it never reaches the user.
Just implement your logic in the interceptor, but only return from the main view, if needed.
def is_send_permitted(request):
    # Check user has required credits in account to these batches.
    balance = Account.objects.get(user=request.user).get_balance()
    cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
    if balance < cost_of_sending:
        return False
    else:
        return True

@login_required
def process_all(request):
    #If we had a POST then get the request post values.
    if request.method == 'POST':
        batches = Batch.objects.for_user_pending(request)

        # Will redirect/cancel request if user does not meet requirements, funds, permissions etc
        if not is_send_permitted_interceptor(request):
            return HttpResponseForbidden()
        # stuff here if everything is ok

You could also raise an Exception here:
from django.core.exceptions import PermissionDenied
raise PermissionDenied()

But it's bad practice to raise exceptions when there is nothing truly exceptional going on.


text:
Q: Optimize regex matching m:n lists (multiple words lists agains multiple lists) I have big word lists which look like this (this data is coming from db):
[
    {
        keyword => 'bmw.*red.*1999',
        owner => 'someone'
        #... other attributes
    },
    {
        keyword => 'toyota.*black.*1999',
        owner => 'someone else'
        #... other attributes
    },
    # and so on ... up to 300 different keywords in a list
]

I have to regularly match "keyword" against many other lists. Because this keyword list is used every time I compile "keyword" to regexp:
map { $_->{_compiled} = qr/$_->{keyword}/i } @keywords;

and compare every keyword with every element in other lists:
foreach my $other in (@other) {
    foreach my $keword (@keywords) {
        if ($other->{name} =~ $keyword->{_compiled}) {
              ## do something with $other and $keyword
        }
    }
}

These operations should run every 10 minutes and there should be around 50 keyword lists (with up to 300 elements) and 50 other lists which are checked against these keywords. And it should grow.
I would like to optimise matching speed as much as possible and I have two ideas/problems:

*

*save compiled regexp ($keyword->{_compiled}) in the database for later usage but I am not sure how much this helps (I did not do any benchmark)

*join all "keywords" or "_compiled" to one big regexp  and compare everything in one step.
code:
my @compiled = grep { $_->{_compiled} } @keywords;

# or is this better?
my $rx = "(".(join "|", grep { $_->{keyword} } @keywords).")";
my $compiled = qr/$rx/i;

foreach my $other in (@other) {
   if ($other->{name} =~ @compiled) {
       ## do something with $other and $keyword
       ##
       ## but now there is no way to get "owner" of matched keyword

   }
}

My "problem" is that I have to be able to use "owner" and other attributes of the matched keyword. If I join everything in one big regexp or put _compiled in an array I am not able to match
Is there "best solution" to regexp-compare large lists with large lists? I am not even sure should I worry about performance problems but lists will grow and I would like to be prepared.

A: You can try to change : bmw.*red.*1999 to
\bbmw\b(?>[^r]++|\Br|r(?!ed))++\bred\b(?>[^1]++|\B1|1(?!999))++\b1999\b

and the same for all keywords. The goal with this change is to fail faster as possible.
Note that the transformation can be automated with 2 successive search/replace (it is always the same)
search: (\w+)
replace: \b$1\b

search: \.\*(?=\\b(\w)(\w+)\\b)
replace: (?>[^$1]++|\B$1|$1(?!$2\b))++

example with the second keyword
toyota.*black.*1999
first replace:
\btoyota\b.*\bblack\b.*\b1999\b
second replace:
\btoyota\b(?>[^b]++|\Bb|b(?!lack\b))++\bblack\b(?>[^1]++|\B1|1(?!999\b))++\b1999\b

Then you store the compiled expression in your database.


text:
Q: Why are std::begin() and std::end() overloaded for std::initializer_list in C++11? In C++11 (quoting N3337), std::begin() and std::end() are specified as (§24.7 [iterator.range]/p2-3)

template <class C> auto begin(C& c) -> decltype(c.begin());
template <class C> auto begin(const C& c) -> decltype(c.begin());

2 Returns: c.begin().
template <class C> auto end(C& c) -> decltype(c.end());
template <class C> auto end(const C& c) -> decltype(c.end());

3 Returns: c.end().

std::initializer_list, however, provides its own overloads for these functions (§18.9.3 [support.initlist.range]):

template<class E> const E* begin(initializer_list<E> il) noexcept;

1 Returns: il.begin().
template<class E> const E* end(initializer_list<E> il) noexcept;

2 Returns: il.end().

It seems that these overloads don't do anything beyond the base template, other than (1) having a noexcept specification and (2) taking their parameter by value. However, copying an initializer_list does nothing special (it just copies a pair of pointers or something equally lightweight), so (2) creates no difference in behavior. Moreover, the begin() and end() member functions of many standard containers are also noexcept, yet no overloads of std::begin()/std::end() are specified for those containers, so it seems unlikely the committee specified these overloads just for (1). Why, then, are these overloads provided?

A: This is explained in N2930, which proposed the change to add the overloads in question.
Emphasis mine:

Summary of proposed changes

*

*Specify range-based for statements without the use of concepts, using argument-dependent lookup of begin and end (which always includes those begin and end functions in namespace std) to provide the iterator to the beginning and ending of the sequence.

*Specify range-based for statements so that arrays and initializer lists have no dependencies on <iterator>.

*Refactor <initializer_list> so that it as no dependencies on other headers and includes no other headers.

*Specify the library headers that are to #include <initializer_list>.

It seems like they didn't explain why they wanted <initializer_list> to have no dependency on <iterator>, but I think a reasonable guess is that the former is supposed to be available in a freestanding implementation whereas the latter might not be (Table 16, §17.6.1.3)


text:
Q: jQuery removes Font Awesome Icon I am using Font Awesome and jQuery in an experiment, after an animation, the jQuery replaces a loading icon in a list by a check, and the text changes too. However, when I remove the jQuery replaceWith method, the icon stays:
HTML:

Downloading

text

text

text

jQuery:
setTimeout(function() {
    $("#ToDo1").removeClass("fa-spin fa-spinner");
    $("#ToDo1").addClass("fa-check-square");
    $("li:first").replaceWith("Download Complete");
    $("#ToDo2").addClass("fa-spin fa-spinner");
}, 2000);

Result:
before:

After jQuery replaceWith

What is the problem?

A: Change out this:
$("li:first").replaceWith("Download Complete");

With this:
$("li:first").html('Download Complete');

In reality though, FlipFloop, you'll want to target your  element and text separately. Put your message into a span you can target independently of your markup replacement, like so:

text

$("li:first i").removeClass("fa-spin fa-spinner").addClass("fa-check-square");
$("li:first span").text("Download Complete");

Hope this helps.

A: The problem is that you replace the complete LI node instead of the inner text node inside it. To be able to address the text, wrap it in a SPAN like this.

Downloading

text

text

text

Then you can change only the text you want like this.
setTimeout(function() {
    $("#ToDo1").removeClass("fa-spin fa-spinner");
    $("#ToDo1").addClass("fa-check-square");
    $("li:first > span").text("Download Complete");
    $("#ToDo2").addClass("fa-spin fa-spinner");
}, 2000);

A: Ah it's because you have i elements inside your li elements
So you'll need to make jQuery prepend an i element after changing the text
So .replaceWith and .text will get rid of the i
So you could do this
$('li:first').html('Download Complete');

A: Try the following snippet :

$(document).ready(function() {
  var time = 500;
  $('.load').each(function() {
    var temp = $(this);
    setTimeout(function() {
      temp.removeClass("fa-spin fa-spinner");
      temp.addClass("fa-check-square");
      temp.next("div").text("Download Complete");
      temp.next("i.load").addClass("fa-spin fa-spinner");
    }, 2000, temp);
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

Downloading

text

text

text

Wrap the text in a span and then change it since replaceWith will replace the complete contents of the li including the icon.


text:
Q: Check if stdout is empty? (Issue with stdout and readline()) The issue is with my code hanging in the for loop of this function. This function is called as a separate thread in a larger main script. After a user input, the main script sets self.kill_switch.
This code works great when stdout has a continuous output. the issue appears when stdout is empty the code hangs at for line in iter(lambda: stdout.readline(), ""): until stdout has a line of data. Once stdout has the information it writes the line of data and checks the kill_switch condition and exits according. How to set a timeout on the for line or check if stdout is empty?
Is there any way to set an if statement to have the code pass if stdout is blank?
def remote_connection(self):
    stdin, stdout, stderr = self.ssh.exec_command('python main_script.py', get_pty=True)
    while not self.kill_switch.is_set():
        for line in iter(lambda: stdout.readline(), ""):
            self.data.put(line)
            break
    self.ssh.exec_command('\x003', get_pty=True)


text:
Q: Creating MultiDimensional Lists during Parsing HTML in Python With the help, I managed to correct my code in the link and enhance it to this:
from bs4 import BeautifulSoup
import re
import os
from os.path import join
from click.termui import pause

BeforeFinalJob = []
TheFinalResultThatUsed = []
ListOfFiles = []

for (dirname, dirs, files) in os.walk('.'):
    for filename in files:
        if filename.endswith('.html'):
            thefile = os.path.join(dirname, filename)
            ListOfFiles += [thefile]
            with open(thefile, 'r') as f:
                contents = f.read()
                soup = BeautifulSoup(contents, 'lxml')
                Initialtext = soup.get_text()
                MediumText = Initialtext.lower().split()

                TokensToClean = [t for t in MediumText
                                if re.match(r'[^\W\d]*$', t)]

                removementWords = ['here', 'than']

                for somewords in range(len(TokensToClean)):
                    if TokensToClean[somewords] not in removementWords:
                        BeforeFinalJob.add(TokensToClean[somewords])
TheFinalResultThatUsed = list( dict.fromkeys(BeforeFinalJob) )

However, the list of files and the words are in the different tables. How might I get the result in the list[a][b], where list[a] are the name file and list[a][b] the words of file list[a]? Additionally, there should not be any doubles in list[a]
For example, list[a] == file
and list[a][b] == some word, which in the file
UPD: There is some HTMLs which is in ZIP file:
https://www94.zippyshare.com/v/vJgy2sk1/file.html

A: The following code makes the structure
'filename.html': {
    'path': 'D:\\folder\\filename.html',
    'words': [
        'one',
        'two'
    ]
}

You can access to data like this
filename = 'filename.html'
print(data[filename]['words'][1])
# two
print(data[filename]['path'])
# D:\\folder\\filename.html

Full code
from bs4 import BeautifulSoup
from os import path, walk
from pprint import pprint
import re

removement_words = ['here', 'than']
source = 'D:\folder'
result = {}

for root, folders, files in walk(source):
    for filename in files:
        if not filename.endswith('.html'):
            continue

        filepath = path.join(root, filename)
        result[filename] = {
            'path': filepath,
            'words': []
        }

        for word in BeautifulSoup(open(filepath), 'lxml').get_text().lower().split():
            if not word in removement_words and re.match(r'[^\W\d]*$', word):
                result[filename]['words'].append(word)

pprint(result)
# 'y2k.html': {'path': 'D:\\folder\\y2k.html',
#              'words': ['the',
#                        'digest',
#                        'rhf',
#                        'joke',
#                        ...


text:
Q: DropdownList.selectedIndex always 0 (yes, I do have !isPostBack) (Scroll down to bottom of post to find solution.)
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called.  The
itemCreatedCommand is responsible for
databinding the dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
protected void DataListProducts_ItemCreatedCommand(object
    source, DataListItemEventArgs e)

 var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
 var item = itemBLL.GetFullItem(itemId);

 var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");

 //Also tried with :
 //if(!isPostBack) {

 DropDownListColor.DataSource = item.ColorList;
 DropDownList.Color.Databind();

 // } End !isPostBack)

    Label1.test = DropDownListColor.SelectedIndex.toString();
 // <- THIS IS ALWAYS 0! *grr*

I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :)    The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
SOLUTION:
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
 protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList dropDownListColor = (DropDownList)sender;
            DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;

            var item = items[dataListItem.ItemIndex];
            var color = item.ItemColor[dropDownListColor.SelectedIndex];

            var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
            LabelPrice.Text = color.Price;
        }

A: When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control.

A: Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record.

A: some MSDN links with C# examples on bubbling
http://msdn.microsoft.com/en-us/library/system.web.ui.control.onbubbleevent.aspx
http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa720044(VS.71).aspx

A: Thank You for your solution
 protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {
     try {
         ModalPopupExtender1.Show();
         if (ViewState["Colors"] != null) {
             FillColors(ViewState["Colors"].ToString());
         }

         DropDownList dropDownListColor = (DropDownList)sender;
         DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;

         Image image = (Image)dataListItem.FindControl("mdlImage");
         Label ProductCode = (Label)dataListItem.FindControl("lblprdCode");
         Label ProductName = (Label)dataListItem.FindControl("lblProdName");
         DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity");
         Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
         Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice");
         //Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
     } catch (Exception ex) {

     }
 }


text:
Q: How can I get row-wise max based on condition of specific column in R dataframe? I'm trying to get the maximum value BY ROW across several columns (climatic water deficit -- def_59_z_#) depending on how much time has passed (time since fire -- YEAR.DIFF). Here are the conditions:

*

*If 1 year has passed, select the deficit value for first year.
(def_59_z_1).

*If 2 years: max deficit of first 2 years.

*If 3 years: max of deficit of first 3 years.

*If 4 years: max of deficit of first 4 years.

*If 5 or more years: max of first 5 years.

However, I am unable to extract a row-wise max when I include a condition. There are several existing posts that address row-wise min and max (examples 1 and 2) and sd (example 3) -- but these don't use conditions. I've tried using apply but I haven't been able to find a solution when I have multiple columns involved as well as a conditional requirement.
The following code simply returns 3.5 in the new column def59_z_max15, which is the maximum value that occurs in the dataframe -- except when YEAR.DIFF is 1, in which case def_50_z_1 is directly returned. But for all the other conditions, I want 0.98, 0.67, 0.7, 1.55, 1.28 -- values that reflect the row maximum of the specified columns. Link to sample data here. How can I achieve this?
I appreciate any/all suggestions!
data <- data %>%
mutate(def59_z_max15 = ifelse(YEAR.DIFF == 1,
                            (def59_z_1),
                            ifelse(YEAR.DIFF == 2,
                                   max(def59_z_1, def59_z_2),
                                   ifelse(YEAR.DIFF == 3,
                                          max(def59_z_1, def59_z_2, def59_z_3),
                                          ifelse(YEAR.DIFF == 4,
                                                 max(def59_z_1, def59_z_2, def59_z_3, def59_z_4),
                                                 max(def59_z_1, def59_z_2, def59_z_3, def59_z_4, def59_z_5))))))

A: Throw this function in an apply family function
func <- function(x) {
first.val <- x[1]
if (first.val < 5) {
return(max(x[2:(first.val+)])
} else {
return(max(x[2:6]))
}
}

Your desired output should be obtained by:
apply(data, 1, function(x) func(x)) #do it by row by setting arg2 = 1

A: An option would be to get the pmax (rowwise max - vectorized) for each set of conditions separately in a loop (map - if the value of 'YEAR.DIFF' is 1, select only the 'def_59_z_1', for 2, get the max of 'def_59_z_1' and 'def_59_z_2', ..., for 5, max of 'def_59_z_1' to 'def_59_z_5', coalesce the columns together and replace the rest of the NA with the pmax of all the 'def59_z" columns
library(tidyverse)
out <- map_dfc(1:5, ~
         df1 %>%
           select(seq_len(.x) + 1) %>%
           transmute(val = na_if((df1[["YEAR.DIFF"]] == .x)*
               pmax(!!! rlang::syms(names(.))), 0))) %>%
  transmute(def59_z_max15 = coalesce(!!! rlang::syms(names(.)))) %>%
  bind_cols(df1, .)%>%
  mutate(def59_z_max15 = case_when(is.na(def59_z_max15) ~
         pmax(!!! rlang::syms(names(.)[2:6])), TRUE ~ def59_z_max15))
head(out, 10)
#   YEAR.DIFF def59_z_1 def59_z_2 def59_z_3 def59_z_4 def59_z_5 def59_z_max15
#1          5      0.25     -2.11      0.98     -0.07      0.31          0.98
#2          9      0.67      0.65     -0.27      0.52      0.26          0.67
#3         10      0.56      0.33      0.03      0.70     -0.09          0.70
#4          2     -0.34      1.55     -1.11     -0.40      0.94          1.55
#5          4      0.98      0.71      0.41      1.28     -0.14          1.28
#6          3      0.71     -0.17      1.70     -0.57      0.43          1.70
#7          4     -1.39     -1.71     -0.89      0.78      1.22          0.78
#8          4     -1.14     -1.46     -0.72      0.74      1.32          0.74
#9          2      0.71      1.39      1.07      0.65      0.29          1.39
#10         1      0.28      0.82     -0.64      0.45      0.64          0.28

data
df1 <- read.csv("https://raw.githubusercontent.com/CaitLittlef/random/master/data.csv")


text:
Q: Banach Space Isomorphism vs Hilbert Space Isomorphism Two Banach spaces $X,Y$ are isomorphic if there is a linear operator $T:X\to Y$ that is also a bicontinuous bijection.  In other words, Banach Space Isomorphism = Linear Homeomorphism.  If $T$ in addition perserves norm, then it is an "isometric isomorphism."
Two Hilbert Sapces $H_1, H_2$ are isomorphic if there is an onto linear operator $U:H_1\to H_2$ such that $(Ux,Uy)_{H_1}=(x,y)_{H_2}$ for all $x,y\in H_1$.  In other words, Hilbert Space Isomorphism = Linear Surjective Isometry.  (I recognise that this is an equivalence relation, but what is the reason for not requiring injectivity?)
I am wondering why the definitions have been chosen as such.  For example, consider $S:L^2\to L^2$ such that $[Sf](x)=2f(x)$.  It is an isomorphism in the Banach sense but not an isomorphism in the Hilbert sense, because it does not preserve the metric.  This is a little confusing.
Naively, I say we can just use the words "linear homeomorphism" and "isometric linear homeomorphism" for Banach isomorphism and Banach isometric isomorphism; and then there won't be any confusion.
Lastly, is there a reason we want to think of Hilbert space not up to equivalent inner products, but think of Banach spaces up to equivalent norms?
This link may be relevant to the reader, though I became more confused after reading it. https://mathoverflow.net/questions/80567/what-is-an-isomorphism-of-banach-spaces
Thanks!


text:
Q: Angular 2 RadioButton Checked With the old forms I could set checked the radio button like this:
<div class="radio" *ngFor="let transport of transports">
  <label>
   <input type="radio" name="transport" [ngModel]="{checked: transport.id == selectedTransport.id}" (change)="onTransportChange(transport)"> {{ transport.name }}
  </label>
</div>

With the new angular forms I couldn't achieve this with [ngModel]="{checked:''}", but I can use [checked], then I tried to do:
<input type="radio" name="transport" [checked]="transport.id == selectedTransport.id"> {{ transport.name }}

And this works, but if I set [ngModel] this doesn't check anymore:
<input type="radio" name="transport" [checked]="transport.id == selectedTransport.id" [ngModel]="transport" (change)="onTransportChange(transport)"> {{ transport.name }}

Edit:
Plunker with old forms:
http://plnkr.co/edit/zu4j9MpALIgCT9JHuIPz?p=preview
Plunker with new forms:
http://plnkr.co/edit/cWCp5d122h3wvSRa8AYQ?p=preview
Anyone can help me with this? Thanks!

A: Try to specify value attributes.
And do not forget that in case of radio buttons Model is not supposed to contain boolean value but should contain radio specific values like:

  <input type="radio" name="food" value="beef" [(ngModel)]="myFood"> Beef
  <input type="radio" name="food" value="lamb" [(ngModel)]="myFood"> Lamb
  <input type="radio" name="food" value="fish" [(ngModel)]="myFood"> Fish

In this case you do not need [checked] attribute.


text:
Q: Internet Explorer 10 in Nokia windows phone not responsive I have used Twitter bootstrap to make my web site responsive. everything works great but IE 10 in Nokia (Lumia 920) windows phone. I searched alot and everybody says if I add @media(max-width:480px){@-ms-viewport{width:320px;} ...} it would solve the problem but the problem still remains. It is not only for my site, but also all other sites. IE 10 in windows phone is not responsive at all. any idea thanks.

A: Have you seen this post from Trent Walton? Wherein he talks about media queries and IE10 in WP8 - http://trentwalton.com/2013/01/16/windows-phone-8-viewport-fix/

A: I had the same problem, I fixed it using this meta tags:
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

better explained in here: http://getbootstrap.com/getting-started/#template
cheers.


text:
Q: Компилятор для языка Пролог в ОС Linux Подскажите, какой компилятор подойдет для изучения языка. Также чтобы по работе с этим компилятором была русскоязычная документация.
Спасибо.
A: Первая же ссылка в гугле.
Любая русская документация к прологу подойдёт.
A: Из книжек по Прологу:

*

*"Программирование на языке Пролог для искусственного интеллекта", Братко И.;

*"Искусство программирования на языке Пролог", Стерлинг Л.


text:
Q: Big-IP F5 irule get uri and store in variable There is my irule config as below :
when HTTP_REQUEST {
switch [HTTP::query] {
    "*NetTest0*" {
         HTTP::respond 200 content "NetTest0()"
    }
    "*NetTest1*" {
         HTTP::respond 200 content "NetTest1()"
    }
    "*NetTest2*" {
         HTTP::respond 200 content "NetTest2()"
    }
    "*NetTest3*" {
         HTTP::respond 200 content "NetTest3()"
    }
}}

Is there any method can get uri as a variable, and replace NetTest0 to NetTest0()?

A: you can use the HTTP::uri command to get and set the URI. Depending on the complexity of your replacements, you can use string map (preferred for performance reasons) or regsub (avoid if possible, but useful if you need it.)
Here are a couple examples of the string map that should help you get started:

*

*https://community.f5.com/t5/technical-forum/variable-in-a-string-map/td-p/263863

*https://community.f5.com/t5/technical-forum/string-map-with-variables-including-quotes/td-p/252969
We recently launched a new platform and engaging on DevCentral is far easier than before, feel free to join us there for future F5-related questions!


text:
Q: Integral in Peskin and Schroeder I'm having a bit of a slow day, and can't see how to do the following integral in Peskin and Schroeder (page 107 for anyone with the book). We've derived in the centre of mass frame the integral over 2 body phase space
$$\int d\Pi_2 =\int \frac{dp_1p_1^2d\Omega}{(2\pi)^3)2E_12E_2}(2\pi)\delta(E_{cm}-E_1-E_2)$$
where $E_1^2=p_1^2+m_1^2,\ E_2=p_1^2+m_2^2$ and $E_{cm}$ is the total initial energy.
Apparently one can then "integrate over the final delta function" to get
$$\int d\Pi_2=\int d\Omega\frac{p_1^2}{16\pi^2E_1E_2}(\frac{p_1}{E_1}+\frac{p_1}{E_2})^{-1}$$
How is this done? I suppose it's some kind of clever change of variables or trick but I can't see it! Apologies if I'm missing something easy! To be honest I'm just puzzled as to why we're left with any factors of $p_1$ after doing the integral, because it's just an integration variable, isn't it?
A clear argument would be very much appreciated, as would some intuition as to why I'm misunderstanding the notation! Many thanks in advace.

A: It is simply a matter of notation. The $p_1$ (and hence $E_1$ and $E_2$) in
$$\int d\Pi_2=\int d\Omega\frac{p_1^2}{16\pi^2E_1E_2}(\frac{p_1}{E_1}+\frac{p_1}{E_2})^{-1}$$
is no longer an integration variable; it has the fixed value that satisfies the delta function $\delta(E_{cm}-E_1-E_2)$ in the previous integral. The factor $(\frac{p_1}{E_1}+\frac{p_1}{E_2})^{-1}$ comes from applying an identity of the delta function: $$\delta(g(x)) = \frac{\delta(x-x_0)}{|g'(x_0)|}.$$