text:
Q: width: auto; height: 100; and overflow: hidden does not work as expected I have two sets of images as shown below:

The code for both the images is exactly similar. The difference between images in first block and second block is just the dimensions.
So, I want that all the blocks of Images look exactly same height and width. Without considering the dimensions of the image. I also want that width of the image should be 100% of the available width. And height of the image is auto. After setting height of the image to auto If the image's height is greater than its parent's height than that part of image should be hidden.
Here is my HTML:

Here is my css:
.menu-left-wrapper {
    margin-top: 2px;
    padding-right: 2px;
}

.menu-right-wrapper {
    margin-top: 2px;
    padding-left: 2px;
}

.menu-top-img {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

.menu-left-img {
    border-bottom-left-radius: 10px;
}

.menu-right-img {
    border-bottom-right-radius: 10px;
}

.img-top-wrapper,
.img-left-wrapper,
.img-right-wrapper {
    position: relative;
    width: auto;
    height: 100px;
    overflow: hidden;
}

.menu-top-img,
.menu-left-img,
.menu-right-img {
    position: relative;
    width: 100%;
    height: auto;
}

Here is the JS Fiddle:
https://jsfiddle.net/Vishal1419/s9e8x0pt/

A: I used object-fit in adjusting your css. like so:
You will note that if you adjust the fiddle output window in height (up or down) that the lower images resize in height, in both blocks equally:
Image 1:
Image 2:
See code in fiddle and snippet below

.top-row {
  height: 100vh;
  max-width: 1024px;
  overflow: hidden!important;
}

.menu-left-wrapper {
  display: inline-block;
  margin-top: 2px;
  padding-right: 2px;
}

.menu-right-wrapper {
  display: inline-block;
  margin-top: 2px;
  padding-left: 2px;
}

.menu-top-img {
  display: inline-block;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.img-top-wrapper {
  position: relative;
  max-width: 100%;
  height: 100px;
}

.img-left-wrapper,
.img-right-wrapper {
  position: relative;
  width: 100%;
  height: calc(33.5vh);
  object-fit: cover;
}

.menu-top-img {
  position: relative;
  width: 100%;
  height: 100px;
  object-fit: cover;
}

.menu-left-img,
.menu-right-img {
  position: relative;
  border-bottom-right-radius: 10px!important;
  border-bottom-left-radius: 10px!important;
  width: 100%;
  height: calc(33.5vh);
  object-fit: cover;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

(Updated) fiddle here


text:
Q: Op amp non inverting summing amplifier It seems this question is a bit tricky. I tried to solve it but since the sources do not have any values, so I cannot prove this is a non inverting summing amp.
I wrote the node equations, as follows.

A: You have a small mistake in the KCL equation at \$V_b\$: the denominator on the LHS is \$R_1\$, not \$R\$. This means $$V_b = \frac{R_2}{R_1 + R_2}V_1 + \frac{R_1}{R_1 + R_2}V_2$$
To prove this is a non-inverting summing amplifier, you need the relationship between the inputs and output. You know that \$V_a = V_b\$ so substitute the RHS of the above equation (which is \$V_a\$) into your equation for \$V_3\$:
$$V_3 = \left(\frac{R_f}{R}+1\right)V_a = \left(\frac{R_f}{R}+1\right)\left(\frac{R_2}{R_1 + R_2}V_1 + \frac{R_1}{R_1 + R_2}V_2\right)$$
The output is therefore a sum of \$V_1\$ and \$V_2\$ (each scaled by \$R_1\$ and \$R_2\$), which is then amplified by a factor of \$R_f/R + 1\$. The overall gain is positive (there are no minus signs) so the amplifier is non-inverting rather than inverting.
It may be easier to see this if you assume \$R_1 = R_2\$. Then
$$\begin{align}V_3 &= \left(\frac{R_f}{R}+1\right)\left(\frac{R_1}{R_1 + R_1}V_1 + \frac{R_1}{R_1 + R_1}V_2\right) = \left(\frac{R_f}{R}+1\right)\left(\frac{1}{2}V_1 + \frac{1}{2}V_2\right)\\ &= \frac{1}{2}\left(\frac{R_f}{R}+1\right)(V_1 + V_2)\end{align}$$
Now it is clearly the sum of \$V_1\$ and \$V_2\$ amplified by the (positive) gain $$\frac{1}{2}\left(\frac{R_f}{R}+1\right)$$

A: You actually have worked out the answer almost entirely- just equate the two inputs (Va = Vb for op-amp in balance) and substitute the final equation (fixing the typo of R for R1) for Vb into your equation for V3.
It's a weighted sum of V1 and V2 and a gain, to get an equally weighted sum constrains the ratio of R1 to R2 (equal weighting). If you need a gain of 1 (or any other specific gain) it constrains the ratio of Rf to R .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iphone sms app issue iam making an application where i have to send a same body sms to my contact list . I m using
Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
    if (messageClass != nil)
    {
        MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
        if([MFMessageComposeViewController canSendText])
        {
if ([appdelegate.NumberArray count] > 0) {

            NSString *aa = [appdelegate.NumberArray objectAtIndex:0];
            NSMutableArray *myArray = [aa componentsSeparatedByString:@","];

            NSString *n = [myArray objectAtIndex:0];
            NSString *m=[myArray objectAtIndex:1];
            NSString *new = [appdelegate.globalmsg stringByReplacingOccurrencesOfString: @"forgot" withString:n];
            controller.body = new;
            controller.recipients= [NSArray arrayWithObject:m];
            controller.messageComposeDelegate = self;
                //if([appdelegate.NumberArray count] ==2 ){
                  [self presentModalViewController:controller animated:YES];

im taking out my contact one by one from my mutable array . the problem is that my program sending an sms one at a time, not to the complete list. and if i wanted to send sms to next person i have to click send button again. is there any way i can send sms to everyone without clicking that send button again again?
u can check this app .... http://itunes.apple.com/us/app/automatic-custom-sms/id409247779 in this app last page comes automatically and send everyone from your contact list. ??

A: Ok i fix it. i use a local variable an initialize it in view did load with value 0 and then in view did appear update it to 1 and make making present model view appear till my array finished.


text:
Q: CSS: using font face only on mac @font-face is awesome but it displays quiet hideously on PCs. Only on Macs (don't know about linux) does it display naturally. How can I display a special font only for mac users and fallback to a regular font for PC users?
Thanks!

A: If you don't mind using JavaScript and jQuery, you can detect the OS using the jQuery client plugin and then set the fonts. It seems to be old stuff but it works with jQuery 1.3.2 and I would not be surprised if it works with jQuery 1.6.1.
<script src="./jquery-1.3.2.js"></script>
<script src="./jquery.client.js"></script>
<script type="text/javascript">
    if($.client.os == 'Mac')
        $('body').css('font-family',"'Looks good in Mac'")
    else if($.client.os == 'Windows')
        $('body').css('font-family',"'Looks good in Windows'")
    else if($.client.os == 'Linux')
        $('body').css('font-family',"'Looks good in Linux'")
</script>

You can replace body with any CSS selector, even if it is not supported by the browser, it is likely supported by jQuery.
jQuery is available from jquery.com
Full jquery.client.js
(function() {

    var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i=0;i<data.length;i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {   string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {       // for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            {       // for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS : [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };

    BrowserDetect.init();

    window.$.client = { os : BrowserDetect.OS, browser : BrowserDetect.browser };

})();

A: The jQuery client plugin is very cool. To do the OS sniffing at least with plain JavaScript (which I'm assuming would save some overhead), you can do:
$(document).ready( function () {
    var os = navigator.platform;
    if (os.indexOf("Mac") != -1) {
        $('body').css( 'font-family', '"Lucida Grande"' );
    }
    else if (os.indexOf("Win") != -1) {
        $('body').css( 'font-family', '"Arial"' );
    }
    else if (os.indexOf("iPhone") != -1) {
        $('body').css( 'font-family', '"Helvetica"' );
    }
});

A: As much as I agree with you about Windows, I'm afraid you won't be able to use CSS alone to tell a Mac browser from a Windows browser. You'll need to use a server-side script (or maybe JavaScript?) to sniff that, and decide accordingly whether or not to load @font-face CSS.


text:
Q: How can i use websocket in jasmine framework? I trying to UnitTest using Jasmine framework with websocket. (jasmine-2.4.1 ver.)
websocket send function is fine. but onmessage function has a problem.
result value is undefined.
Here is my code:
var ws;
beforeEach(function() {
    ws = new WebSocket("ws://myaddress:port");
});

describe("Module Test", function() {

    it("first test", function (done) {
        //send to server
        ws.onopen = function(e) {
            ws.send(JSON.stringify({"module":"test","func":"test_func"}));
        };

        var result;
        ws.onmessage = function(e) {
            result = JSON.parse(e.data.rsp);
            console.log(result); // <- this result value is true...
        };

        //server return result value.. and... it is true.....
        //but result value is undefiend....
        expect(result).toBe(true);
        done();
    });
});

A: You're expecting result to be truthy before you receive the message. Forgive me if I've misunderstood the problem, but this should fix your test: -
var ws;
beforeEach(function() {
    ws = new WebSocket("ws://myaddress:port");
});

describe("Module Test", function () {

    it("first test", function (done) {
        ws.onopen = function(e) {
            ws.send(JSON.stringify({"module":"test","func":"test_func"}));
        };

        ws.onmessage = function(e) {
            var result = JSON.parse(e.data.rsp);
            expect(result).toBeTruthy();
            done();
        };
    });
});


text:
Q: Local php.ini Why default timezone is different from Main php.ini On server,
$date
Wed Jan 20 13:28:04 PST 2016

On main php.ini,
The default timezone is set to America/Los_Angeles.
I could confirm that by if I removed local php.ini and print phpinfo().
However, when local  php.ini exists, regardless the file does not have configurations to change default timezone, default timezone will be changed to UTC. It generates this error
You are *required* to use the date.timezone setting or the date_default_timezone_set() function.
In case you used any of those methods and you are still getting this warning,
you most likely misspelled the timezone identifier.

I understand date_default_timezone_set() could make this error resolved.
However, I want to know what is the issue, why is not loading the default timezone correctly. Because I do not want to put this function to scripts.....
Thank your advise!!


text:
Q: Storing Google AppEngine cookie in Android I am developing an Android client with GAE backend and I am using the phone accounts for authentication.
After I retrieve the authentication cookie from GAE, I can make authenticated calls to the server, but as soon as the application is closed, when the app re-launches, I have to run the auth proces again, ask for e new cookie. Is there a way to store that Cookie object and check for it after the first time the auth happens so I don't have to do it every time the app launches?

A: Sounds like a good use for the SharedPreferences
PreferenceManager.getDefaultSharedPreferences().edit().putString("cookie", myCookie).commit();
String myCookie = PreferenceManager.getDefaultSharedPreferences.getString("cookie", null);

A: If you want to leverage functionality of the already implemented provider you should use AccountManager:
AccountManager am = AccountManager.get(MyActivity.this);
Account[] aArray = am.getAccountsByType(ACCOUNT_TYPE);
/* choose correct account from the resulting array */
/* ex. Account a = aArray[0]; */
try {
  String token = am.blockingGetAuthToken(a, Constants.AUTHTOKEN_TYPE, false);
} catch (OperationCanceledException e1) {
  e1.printStackTrace();
} catch (AuthenticatorException e1) {
  e1.printStackTrace();
} catch (IOException e1) {
  e1.printStackTrace();
}

You should override getTokenType() method of your account authenticator to return GAE authentication cookie in the result bundle under the key AccountManager.KEY_AUTHTOKEN. Refer to AccountManager class description for detailed authentication procedure.


text:
Q: access controls inside DetailItemTemplate in radgrid I have a radgrid that contains another one inside its DetailItemTemplate ; as shown in code below :
<telerik:RadGrid ID="Radgrid1" runat="server" AutoGenerateColumns="false"
              OnNeedDataSource="Radgrid1_NeedDataSource" OnItemDataBound="Radgrid1_ItemDataBound">
                    <MasterTableView AutoGenerateColumns="false" DataKeyNames="ID" GroupLoadMode="Client">
                        <Columns>
                      <telerik:GridBoundColumn HeaderText="Name" DataField="NAME" />
                       </Columns>
                        <DetailItemTemplate>
                            <telerik:RadGrid ID="Radgrid2" runat="server" AutoGenerateColumns="false">
                            <MasterTableView AutoGenerateColumns="false" DataKeyNames="Number"
                                                        GroupLoadMode="Client">
                                                        <Columns>
                                                            <telerik:GridBoundColumn HeaderText="Number" DataField="NUMBER" />
                                                          </Columns>
                                                    </MasterTableView>
                                                </telerik:RadGrid>
                                          </DetailItemTemplate>
                    </MasterTableView>
                </telerik:RadGrid>

what's the best method to bind DataTable to radgrid2 as DataSource ??

A: Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
        AllowPaging="true" AllowSorting="true" OnDetailTableDataBind="RadGrid1_DetailTableDataBind">
        <MasterTableView DataKeyNames="ID" CommandItemDisplay="Top">
            <Columns>
                <telerik:GridEditCommandColumn>
                </telerik:GridEditCommandColumn>
                <telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID"></telerik:GridBoundColumn>
            </Columns>
            <DetailTables>
                <telerik:GridTableView Name="Child1">
                    <Columns>
                        <telerik:GridBoundColumn DataField="Name" UniqueName="Name" HeaderText="Name"></telerik:GridBoundColumn>
                    </Columns>
                </telerik:GridTableView>
            </DetailTables>
        </MasterTableView>
    </telerik:RadGrid>

ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    dynamic data1 = new[] {
           new { ID = 1, Name ="Name_1",Customdate = DateTime.Now},
           new { ID = 2, Name = "Name_2",Customdate = DateTime.Now},
           new { ID = 3, Name = "Name_3",Customdate = DateTime.Now},
           new { ID = 4, Name = "Name_4",Customdate = DateTime.Now},
           new { ID = 5, Name = "Name_5",Customdate = DateTime.Now}
       };
    RadGrid1.DataSource = data1;
}

protected void RadGrid1_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
{
    dynamic data1 = new[] {
           new { ID = 1, Name =DateTime.Now.ToString(),Customdate = DateTime.Now},
           new { ID = 2, Name = "Name_2",Customdate = DateTime.Now},
           new { ID = 3, Name = "Name_3",Customdate = DateTime.Now},
           new { ID = 4, Name = "Name_4",Customdate = DateTime.Now},
           new { ID = 5, Name = "Name_5",Customdate = DateTime.Now}
       };
    e.DetailTableView.DataSource = data1;
}


text:
Q: Cannot remove a value from array in Python this might be a very simple mistake but i dont know where my mistake is. i have this code, i'm trying to remove a slot from the array as the user already choose a slot. but it doesn't work. can anyone help?
slot = ['8 AM', '9 AM', '10 AM', '11 AM' , '12 AM' , '2 PM', '3 PM', '4 PM']
print "slot available:" , slot
print 'Choose your slot'
slotchoose = raw_input ("choose:")
if slotchoose == '8 AM' :
    slot.remove ( '8 AM ' )
else :
    if slotchoose == '9 AM' :
        slot.remove ( '9 AM' )
    else :
        if slotchoose == '10 AM' :
            slot.remove ('10 AM')
        else :
            if slotchoose == '11 AM':
                slot.remove ('11 AM')
            else:
                if slotchoose == '12 AM':
                    slot.remove ('12 AM')
                else :
                    if slotchoose == '2 PM' :
                        slot.remove ('2 PM')
                    else :
                        if slotchoose == '3 PM':
                            slot.remove ('3 PM')
                        else :
                            if slotchoose == '4 PM' :
                                slot.remove ('4 PM')

print "Slot aavail :" , slot

here is sample of the output :
slot available: ['8 AM', '9 AM', '10 AM', '11 AM', '12 AM', '2 PM', '3 PM', '4 PM']
Choose your slot
choose:8 AM
Slot aavail : ['8 AM', '9 AM', '10 AM', '11 AM', '12 AM', '2 PM', '3 PM', '4     PM']

the     "8 AM" shouldn't be there

A: Is indeed a simple mistake: you put an extra space.
slot.remove ( '8 AM ' )

should be:
slot.remove ( '8 AM' )

A: replace slot.remove ( '8 AM ' ) with
slot.remove ( '8 AM' )

you can make your code pythonic:
slot = ['8 AM', '9 AM', '10 AM', '11 AM' , '12 AM' , '2 PM', '3 PM', '4 PM']
print "slot available:" , slot
print 'Choose your slot'
slotchoose = raw_input ("choose:")
if slothchoose in slot:
     slot.remove(slothchoose)
print "Slot aavail :" , slot


text:
Q: eslint - vue/script-indent to ignore object fields I have the following ESLint rule setup:
"vue/script-indent": [
    "error",
    4,
    {
        "baseIndent": 1,
        "switchCase": 1,
        "ignores":
        [
            "[init.type=\"ObjectExpression\"]",
            "[init.type=\"ArrayExpression\"]"
        ]
    }
]

However, I would like the indentation to be ignored for the following case (where an object key's value is another object).
This is the output of the linter:
let example =
    {
        example:
            {
                test:
                    "test"
            }
    }

But I want the nested object to be untouched, so it looks like this:
let example =
    {
        example:
        {
            test:
                "test"
        }
    }

So it should be an Object that's inside an Object that should be ignored. I would also like to have Arrays inside Objects to be ignored as well (hence why my ignores have Object and Array)

A: The following rule configures vue/script-indent to ignore nested objects/arrays in .vue:
"vue/script-indent": [
    "error",
    4,
    {
        "baseIndent": 1,
        "switchCase": 1,
        "ignores": [
            // nested objects, excluding top level of exported object (data, methods, computed, etc.)
            "[value.type='ObjectExpression']:not(:matches(ExportDefaultDeclaration, [left.property.name='exports']) > * > [value.type='ObjectExpression'])",

            // nested arrays
            "[value.type='ArrayExpression']"
        ]
    }
],

Caveats

*

*In TypeScript, decorators of class properties (e.g., @Prop private msg!: string) cause a linter bug, where every line afterward is ignored by the linter. (vuejs/eslint-plugin-vue#834) Workaround: Insert an empty method (i.e., _unused() {}) as the first element of the class.

*The order of your object fields could cause the linter to ignore the entire object (vuejs/eslint-plugin-vue#833). Workaround:  Ensure objects have a literal as its first field.


text:
Q: Haskell, creating a structured datatype I would like to create a structure datatype called Structured that can be used to represent String, Int and List. For example, structure is like: [Int, String, Int,[Int]].
Question 1: how to create this datatype?
data Structured = ...

Question 2: A function called Confirm that confirms the input satisfies a restriction, and has the signature type of confirm:: Restriction -> Structure ->Maybe Bool

A: data Structured = Structured Int String Int [Int]

would work.
confirm :: (Structured -> Bool) -> Structured -> Bool

seems a more sensible type, but has a trivial implementation as id.
I don't think you would need to return Maybe Bool from a valudation function - Maybe a is good for when you usually resturn an a, but sometimes don't. (It's good for very simple error handling, for example - give Nothing if there was an error.) In this case, you can always make a conclusion as to whether your input was valid, so you can always give back True or False - no need for the Maybe.
Perhaps you could have something like
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt (Structured int1 string int2 ints) =
       all okInt (int1:int2:ints) && okString string

Here int1:int2:ints is the list that has int1 in front of int2 in front of ints.
A slightly nicer way of defining Structured would be:
data Structured = Structured {
           length ::Int,
           name   ::String,
           width  ::Int,
           somenumbers :: [Int]}

then you'd have
confirm :: (String -> Bool) -> (Int -> Bool) -> Structured -> Bool
confirm okString okInt s =
       all okInt (length s:width s:somenumbers s) && okString (name s)

It does the same job as the first data declaration, but gives you functions for getting at the internals.


text:
Q: Generating triangular/hexagonal coordinates (xyz) I'm trying to come up with an iterative function that generates xyz coordinates for a hexagonal grid. With a starting hex position (say 0,0,0 for simplicity), I want to calculate the coordinates for each successive "ring" of hexagons, as illustrated here:

So far, all I've managed to come up with is this (example in javascript):
var radius = 3
var xyz = [0,0,0];

// for each ring
for (var i = 0; i < radius; i++) {
    var tpRing = i*6;
    var tpVect = tpRing/3;
    // for each vector of ring
    for (var j = 0; j < 3; j++) {
        // for each tile in vector
        for(var k = 0; k < tpVect; k++) {
            xyz[0] = ???;
            xyz[1] = ???;
            xyz[2] = ???;
            console.log(xyz);
        }
    }
}

I know each ring contains six more points than the previous and each 120° vector contains one additional point for each step from the center. I also know that x + y + z = 0 for all tiles. But how can I generate a list of coordinates that follow the sequence below?
    0, 0, 0

    0,-1, 1
    1,-1, 0
    1, 0,-1
    0, 1,-1
   -1, 1, 0
   -1, 0, 1

    0,-2, 2
    1,-2, 1
    2,-2, 0
    2,-1,-1
    2, 0,-2
    1, 1,-2
    0, 2,-2
   -1, 2,-1
   -2, 2, 0
   -2, 1, 1
   -2, 0, 2
   -1,-1, 2

A: This was a fun puzzle.
O(radius2) but with (hopefully) a bit more style than Ofri's solution.  It occurred to me that coordinates could be generated as though you were "walking" around the ring using a direction (move) vector, and that a turn was equivalent to shifting the zero around the move vector.
This version also has the advantage over Eric's solution in that it never touches on invalid coordinates (Eric's rejects them, but this one never even has to test them).
# enumerate coords in rings 1..n-1; this doesn't work for the origin
for ring in range(1,4):
    # start in the upper right corner ...
    (x,y,z) = (0,-ring,ring)
    # ... moving clockwise (south-east, or +x,-z)
    move = [1,0,-1]

    # each ring has six more coordinates than the last
    for i in range(6*ring):
        # print first to get the starting hex for this ring
        print "%d/%d: (%d,%d,%d) " % (ring,i,x,y,z)
        # then move to the next hex
        (x,y,z) = map(sum, zip((x,y,z), move))

        # when a coordinate has a zero in it, we're in a corner of
        # the ring, so we need to turn right
        if 0 in (x,y,z):
            # left shift the zero through the move vector for a
            # right turn
            i = move.index(0)
            (move[i-1],move[i]) = (move[i],move[i-1])

    print # blank line between rings

Three cheers for python's sequence slicing.

A: Not only is x + y + z = 0, but the absolute values of x, y and z are equal to twice the radius of the ring.  This should be sufficient to identify every hexagon on each successive ring:

var radius = 4;
for(var i = 0; i < radius; i++)
{
    for(var j = -i; j <= i; j++)
    for(var k = -i; k <= i; k++)
    for(var l = -i; l <= i; l++)
        if(Math.abs(j) + Math.abs(k) + Math.abs(l) == i*2 && j + k + l == 0)
            console.log(j + "," + k + "," + l);
    console.log("");
}

A:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.textAlign = "center";

const radius = 20;
const altitude = Math.sqrt(3) * radius;
const total = 3;
for (let x = -total; x <= total; x++) {
    let y1 = Math.max(-total, -x-total);
    let y2 = Math.min(total, -x+total);
    for (let y = y1; y <= y2; y++) {
        let xx = x * altitude + Math.cos(1/3*Math.PI) * y * altitude;
        let yy = y * radius * 1.5;
        xx += canvas.width/2;
        yy += canvas.height/2;
        drawHex(xx, yy, radius);
        ctx.fillText(x+","+y, xx, yy);
    }
}

function drawHex(x, y, radius){
    ctx.beginPath();
    for(let a = 0; a < Math.PI*2; a+=Math.PI/3){
        let xx = Math.sin(a) * radius + x;
        let yy = Math.cos(a) * radius + y;
        if(a == 0) ctx.moveTo(xx, yy);
        else ctx.lineTo(xx, yy);
    }
    ctx.stroke();
}
<canvas id="canvas" width=250 height=250>

A: Another possible solution, that runs in O(radius2), unlike the O(radius4) of tehMick's solution (at the expense of a lot of style) is this:
radius = 4
for r in range(radius):
    print "radius %d" % r
    x = 0
    y = -r
    z = +r
    print x,y,z
    for i in range(r):
        x = x+1
        z = z-1
        print x,y,z
    for i in range(r):
        y = y+1
        z = z-1
        print x,y,z
    for i in range(r):
        x = x-1
        y = y+1
        print x,y,z
    for i in range(r):
        x = x-1
        z = z+1
        print x,y,z
    for i in range(r):
        y = y-1
        z = z+1
        print x,y,z
    for i in range(r-1):
        x = x+1
        y = y-1
        print x,y,z

or written a little more concisely:
radius = 4
deltas = [[1,0,-1],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0]]
for r in range(radius):
    print "radius %d" % r
    x = 0
    y = -r
    z = +r
    print x,y,z
    for j in range(6):
        if j==5:
            num_of_hexas_in_edge = r-1
        else:
            num_of_hexas_in_edge = r
        for i in range(num_of_hexas_in_edge):
            x = x+deltas[j][0]
            y = y+deltas[j][1]
            z = z+deltas[j][2]
            print x,y,z

It's inspired by the fact the hexagons are actually on the exterior of a hexagon themselves, so you can find the coordinates of 1 of its points, and then calculate the others by moving on its 6 edges.

A: After trying both the options, I've settled on Ofri's solution as it is a tiny bit faster and made it easy to provide an initial offset value. My code now looks like this:
var xyz = [-2,2,0];
var radius = 16;
var deltas = [[1,0,-1],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0]];
for(var i = 0; i < radius; i++) {
        var x = xyz[0];
        var y = xyz[1]-i;
        var z = xyz[2]+i;
        for(var j = 0; j < 6; j++) {
                for(var k = 0; k < i; k++) {
                        x = x+deltas[j][0]
                        y = y+deltas[j][1]
                        z = z+deltas[j][2]
                        placeTile([x,y,z]);
                }
        }
}

The placeTile method uses cloneNode to copy a predefined SVG element, and it takes approx 0.5ms per tile to execute which is more than good enough. A big thanks to tehMick and Ofri for your help!


text:
Q: How do I make my 6 pictures expand outwards with jQuery? I've been trying to make this menu on my website, and the first step is making it expanding when clicking it. Every picture is separate but in the same div. How should I do this in the best way?

<link rel="stylesheet" type="text/css" href="index.css">

My jQuery so far

$("#prototype").one('click', function(){
    $(this).fadeOut(400).fadeIn(400).fadeOut(400).fadeIn(400).animate({
        'width': '+=400px',
        'height': '+=700px'}, "slow");
});

And then my CSS:
#prototype {
    position: absolute;
    top: 45%;
    left: 47.5%;
}

Unfortunately this is how it ends up looking like.
http://bthem.goerann.com/

A: If you're looking to enlarge/scale your images then would this SO question be helpful?
simple Jquery hover enlarge
snippet from chosen answer:
$('#content img').hover(function() {
    $(this).css("cursor", "pointer");
    $(this).toggle("scale",{
      percent: "90%"
    },500);

}, function() {
    $(this).toggle("scale",{
      percent: "80%"
    },500);

});

Update (in response to comment):
Try .animate as well as scale. Offset the perceived scale movement with a transition to keep the image centered.
$('#div').effect('scale'{
    percent:200
},1000);

$('#div').animate({
    left:100,
    top:100
},1000);


text:
Q: django very simple login or signup code but is_valid always return false my simple code..
view.py
@csrf_protect
def signup(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid(): <<===== Always is_valid return false
            new_user = User.objects.create_user(**form.cleaned_data)
            login(request, new_user)
            return HttpResponseRedirect('/join_ok/')
        else:
            # If is_valid() False then I want see data
            return HttpResponse(form) <<== print data is no problem
    else:
        form = UserForm()
        return render(request, 'join.html', {'form': form})

join.html

Join

<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="join" />
</form>

forms.py
from django import forms
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']

class LoginForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password']

is_valid() always return False
Very basic code.
I just want to test login.
But there was a problem in the very basic part.


text:
Q: Vibe.d rest interface router wrong path matching I'm using vibe.d for my rest API. I have two methods: addUser and getUser. I used @path("/api/v3/users/"), so now the URL should look like this: http://127.0.0.1:8080/api/v3/users/user. The POST method works fine with this URL, but I can't get the GET method to work.
I use the same url (?someParams), but the server responds with 404. I've noticed, that when I use URL http://127.0.0.1:8080/api/v3/users/user/user, it says "Unexpected 'u' when converting from type string to type int", but if I put anything else than user after the /, it throws 404 again.
I'm sure I must've overlooked some dumb mistake :D
Interface:
@path("/api/v3/auth/")
interface IUserAPI
{
    /** Adding a user */
    User addUser(string email, string firstName, string lastName, string password, string locale);
    /** Getting a user by id */
    User getUser(int id);
}
Class:
/** User API */
class UserAPI : IUserAPI {
    /** Testing user */
    User user;
    /** Adding a user */
    @safe
    User addUser(string email, string firstName, string lastName, string password, string locale) {
        user = User(1, 0, email, firstName, lastName, password, locale, 0, false, "","", 0, "");
        return user;
    }
    /** Getting a user by id */
    @safe
    User getUser(int id) {
        logInfo(id.to!string);
        return user;
    }
}<br>

Registering rest interfaces:
router.registerRestInterface(new UserAPI, MethodStyle.camelCase);
router.registerRestInterface(new LogsListAPI, MethodStyle.camelCase);

A: After some digging, I found my answer. When you use id as a parameter, then it puts it directly in the URL. Like http://whatever.com/api/1(id)/user.


text:
Q: Ubuntu 13.04 Slow LAN download I have problem with downloading file between Ubuntu 13.04 and network share on windows 7. When i uploading file from Ubu to Win7 everything is ok, but in other way when downloading from Win7 speed is around 30-40kB/s. Thats sad... Anyone solved this issue ?
Thx for Any help

A: ...Maybe i wrote little wrong.... "When i downloading from Win 7 i mean  sitting on my computer with ubuntu 13.04 and downloading by the LAN a files from computer with windows 7... all thing are when are trying download on Ubuntu any files by LAN speed is around 30-40 kB/s... this is the core of problem :((((


text:
Q: How to disable objects in Silverlight? I want to disable a button in silverlight, does it has a disable property that can bind to a variable?
thanks :)

A: To disable a button, you can use
myButton.IsEnabled = false;

All UIElements have this property.

A: If you have some sort of ViewModel with a bool property
public bool CanDoSomething
{
    get { return _canDoSomething; }
    set
    {
        if (_canDoSomething != value)
        {
            _canDoSomething = value;
            RaisePropertyChanged("CanDoSomething");
        }
    }
}

Then you can bind the Button in XAML with something like
<Button IsEnabled="{Binding Path=CanDoSomething}" />


text:
Q: Confused on a LINQ where clause public ViewResult List(string category, int page = 1)
{
    ProductsListViewModel viewModel = new ProductsListViewModel
    {
        Products = repository.Products
            .Where(p => category == null || p.Category == category)
            ...........

The line : .Where(p => category == null || p.Category == category) is a little confusing to me. The logic is : "If category is null, then only select the selected category".
This is from a book, but is this the best way to write this?
It's saying the category can be "null OR an category value". So if category contains a value, it will use that value to select the items and not null (null selects all items).
I wrote this which is kind of useless but works and makes its clearer :
.Where(p => category == null ? category == null :
                               p.Category == category)

Am I getting this logic right?

A: It's basically allowing the category filter to be optional - if the category parameter is non-null, then it has to match whatever you're looking at. Otherwise, just include all categories.

A: .Where(p => category == null || p.Category == category)

There are two parts here, connected by an OR, which means one of them must be true, to result in true:
category == null

The category given was null
p.Category == category

The category in question matches the category given
So it will select a p, if either the category given was null, or it matched the category of p.

A: .Where(p => category == null || p.Category == category)

will be translated to SQL query something like this (not exactly):
where null is null or Category == null    // When not specified, show all because, null IS null = true
// or
where 'someCategory' is null or Category == 'SomeCategoy'  // filter by some category

Ternary will return a bool, and not a condition to construct SQL query
category == null ? category == null : p.Category == category


text:
Q: Magento - How to add/remove links on my account navigation? I am trying to remove links on my account navigation. I looked at the customer/account/navigation.phtml template. The template grabs links by $this->getLinks(). How do I edit getLinks() method so that I can remove some of links?

A: Its work 100% i am Sure.
Step 1: Go To ( YourTemplate/customer/account/navigation.phtml )
Step 2: Replace This Line: <?php $_count = count($_links); ?>
With:
<?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
unset($_links['account']); /* Account Info */
unset($_links['account_edit']); /* Account Info */
unset($_links['tags']); /* My Tags */
unset($_links['invitations']); /* My Invitations */
unset($_links['reviews']);  /* Reviews */
unset($_links['wishlist']); /* Wishlist */
unset($_links['newsletter']); /* Newsletter */
unset($_links['orders']); /* My Orders */
unset($_links['address_book']); /* Address */
unset($_links['enterprise_customerbalance']); /* Store Credit */
unset($_links['OAuth Customer Tokens']); /* My Applications */
unset($_links['enterprise_reward']); /* Reward Points */
unset($_links['giftregistry']); /* Gift Registry */
unset($_links['downloadable_products']); /* My Downloadable Products */
unset($_links['recurring_profiles']); /* Recurring Profiles */
unset($_links['billing_agreements']); /* Billing Agreements */
unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */

?>

A: Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:
Just duplicate
app/design/frontend/base/default/template/customer/account/navigation

to
app/design/frontend/YOUR_THEME/default/template/customer/account/navigation

and unset the unneeded navigation items before the get rendered, e.g.:
<?php $_links = $this->getLinks(); ?>
<?php
    unset($_links['recurring_profiles']);
?>

A: If you want to selectively remove links without having to copy/edit entire xml files, a nice solution can be found in this post in the magento forums
In this solution, you override the Mage_Customer_Block_Account_Navigation block with a local version, that adds a removeLinkByName method, which you then use in your layout.xml files, like so:
<?xml version="1.0"?>
    <layout version="0.1.0">

    <customer_account>
        <reference name="customer_account_navigation" >

                <action method="removeLinkByName">
                   <name>recurring_profiles</name>
                </action>
                <action method="removeLinkByName">
                   <name>billing_agreements</name>
                </action>
        </reference>
    </customer_account>
</layout>

A: Also, you need to do something like this in config.xml if you are developing a customized module
    <frontend>
        <layout>
            <updates>
                <hpcustomer>
                    <file>hpcustomer.xml</file>
                </hpcustomer>
            </updates>
        </layout>
    </frontend>

A: Open navigation.phtml
app/design/frontend/yourtheme/default/template/customer/account/navigation.phtml

replace
<?php $_links = $this->getLinks(); ?>

with unset link which you want to remove
<?php
$_count = count($_links);
unset($_links['account']); // Account Information
unset($_links['account_edit']); // Account Information
unset($_links['address_book']); // Address Book
unset($_links['orders']); // My Orders
unset($_links['billing_agreements']); // Billing Agreements
unset($_links['recurring_profiles']); // Recurring Profiles
unset($_links['reviews']);  // My Product Reviews
unset($_links['wishlist']); // My Wishlist
unset($_links['OAuth Customer Tokens']); // My Applications
unset($_links['newsletter']); // Newsletter Subscriptions
unset($_links['downloadable_products']); // My Downloadable Products
unset($_links['tags']); // My Tags
unset($_links['invitations']); // My Invitations
unset($_links['enterprise_customerbalance']); // Store Credit
unset($_links['enterprise_reward']); // Reward Points
unset($_links['giftregistry']); // Gift Registry
unset($_links['enterprise_giftcardaccount']); // Gift Card Link
?>

A: The answer to your question is ultimately, it depends. The links in that navigation are added via different layout XML files. Here's the code that first defines the block in layout/customer.xml. Notice that it also defines some links to add to the menu:
<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
    <action method="addLink" translate="label" module="customer"><name>account</name><path>customer/account/</path>Account Dashboard</action>
    <action method="addLink" translate="label" module="customer"><name>account_edit</name><path>customer/account/edit/</path>Account Information</action>
    <action method="addLink" translate="label" module="customer"><name>address_book</name><path>customer/address/</path>Address Book</action>
</block>

Other menu items are defined in other layout files. For example, the Reviews module uses layout/review.xml to define its layout, and contains the following:
<customer_account>

    <reference name="customer_account_navigation">
        <action method="addLink" translate="label" module="review"><name>reviews</name><path>review/customer</path>My Product Reviews</action>
    </reference>
</customer_account>

To remove this link, just comment out or remove the <action method=...> tag and the menu item will disappear. If you want to find all menu items at once, use your favorite file search and find any instances of name="customer_account_navigation", which is the handle that Magento uses for that navigation block.

A: The easiest way to remove any link from the My Account panel in Magento is to first copy:
app/design/frontend/base/default/template/customer/account/navigation.phtml
to
app/design/frontend/enterprise/YOURSITE/template/customer/account/navigation.phtml
Open the file and fine this line, it should be around line 34:
<?php $_index = 1; ?>

Right below it add this:
 <?php $_count = count($_links); /* Add or Remove Account Left Navigation Links Here -*/
        unset($_links['tags']); /* My Tags */
        unset($_links['invitations']); /* My Invitations */
        unset($_links['enterprise_customerbalance']); /* Store Credit */
        unset($_links['OAuth Customer Tokens']); /* My Applications */
        unset($_links['enterprise_reward']); /* Reward Points */
        unset($_links['giftregistry']); /* Gift Registry */
        unset($_links['downloadable_products']); /* My Downloadable Products */
        unset($_links['recurring_profiles']); /* Recurring Profiles */
        unset($_links['billing_agreements']); /* Billing Agreements */
        unset($_links['enterprise_giftcardaccount']); /* Gift Card Link */
        ?>

Just remove any of the links here that you DO want to appear.

A: You can also disable the menu items through the backend, without having to touch any code.  Go into:
System > Configuration > Advanced

You'll be presented with a long list of options.  Here are some of the key modules to set to 'Disabled' :
Mage_Downloadable -> My Downloadable Products
Mage_Newsletter -> My Newsletter
Mage_Review -> My Reviews
Mage_Tag -> My Tags
Mage_Wishlist -> My Wishlist

I also disabled Mage_Poll, as it has a tendency to show up in other page templates and can be annoying if you're not using it.

A: Most of the above work, but for me, this was the easiest.
Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.
http://www.magentocommerce.com/magento-connect/frontend-links-manager.html

A: You can also use this free plug-and-play extension:
http://www.magentocommerce.com/magento-connect/manage-customer-account-menu.html
This extension does not touch any of the Magento core files.
With this extension you are able to:

*

*Decide per menu item to show or hide it with one click in the Magento backend.

*Rename menu items easily.

A: My solution was to completely remove the block in local.xml and create it with the blocks I needed, so, for example
<customer_account>
        <reference name="left">
            <action method="unsetChild">
                <name>customer_account_navigation</name>
            </action>
            <block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
                <action method="addLink" translate="label" module="customer">
                    <name>account</name>
                    <path>customer/account/</path>
                    Account Dashboard
                </action>
                <action method="addLink" translate="label" module="customer">
                    <name>account_edit</name>
                    <path>customer/account/edit/</path>
                    Account Information
                </action>
        </block>
    </reference>
</customer_account>


text:
Q: Angular5, socket.io-client and Ratchet Websocket failed with HTTP 426 error I'm working with an Angular app, that have to communicate with a Websocket server. The ws server is listening on 192.168.1.99:8080 and powered by Ratchet/Websocket (under PHP).
Server is running as expected and allows 'localhost:4200' as trusted client.
On Client side, use a Service that manage connection and message exchange :
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import * as io from 'socket.io-client';

import { Constants } from './../../constants/constants';

@Injectable()
export class WebsocketService {

  private _socket: any;

  constructor() { }

  public sendMessage(messageType: string, message: any){
    this._socket.emit(
      messageType,
      message
    );
  }

  public getMessages(): Observable<any> {
    let observable = new Observable((observer) => {
      this._socket = io(Constants._WS_URL);
      this._socket.on(
        'message',
        (data) => {
          observer.next(data);
        }
      );

      return () => {
        this._socket.disconnect();
      };

    });

    return observable;
  }
}

Nothing special... just a copy/paste of existing code.
My component implements onInit and does the following :
  ngOnInit() {
    // websocket instanciation
    this._wsConn = this.websocketService.getMessages().subscribe((message)
        => {
          this._messages.push(message);
    });
}

When app runs, got :
http://192.168.1.99:8080/socket.io/?EIO=3&transport=polling&t=M8qMAFE 426 (Upgrade header MUST be provided)

(index):1 Failed to load http://192.168.1.99:8080/socket.io/?EIO=3&transport=polling&t=M8qMAFE: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 426.

After hours spent to look for the way to send headers from client, and a lot of coffee, don't find any idea...
Note... Try to communication via Websocket pure Javascript, and all is good :
var conn = new WebSocket('ws://192.168.1.99:8080');
conn.onopen = function(event){
    console.log('Connexion au serveur établie');
}

conn.onmessage = function (event){
    console.log('Message reçu ' + event.data);
}

Websocket server logs...
/mnt/c/webroot/ws_stestex$ php index.php
Initialise le traitement périodique
Nouvelle connexion : 7036

So, my question is... what can i do ? lol...
Well.. I change the service method to :
      this._socket = io('ws://192.168.1.99:8080', {
    transportOptions: {
      polling: {
        extraHeaders: {
          'x-clientid': 'saintesaintex',
          'Sec-WebSocket-Version': '13'
        }
      }
    }
  });

Then i got a 405 HTTP error... Can someone tell me the correct headers ?
Note 2 : when i inspect the network console, see that it's not the ws protocol used but http...


text:
Q: Is there a way to run SQL Reports on a SQLite Database? We used to use TFS, but have recently moved to another bug tracker.  We also have a few reports that we ran on the work items from TFS, and would like to do the same with the new bug tracker that uses SQLite.
EDIT:
The bug tracker is Trac.

A: does an SQLite ODBC Driver solve the problem?  see:
Connect to SQLite using ODBC without register database


text:
Q: Add "start" and "stop" button to bouncing ball in Java I've made a bouncing ball in Java, but now I have to add "start" and "stop" buttons to the animation, but I'm not really sure how to go about that.
This is what I have so far:
 import java.awt.Color;
 import java.awt.Graphics;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;

 import javax.swing.*;
 //import javax.swing.JFrame;
 //import javax.swing.JPanel;
 //import javax.swing.Timer;

 /**
 *
 *
 */
 public class BouncingBall extends JPanel implements ActionListener {

    Timer tm = new Timer(5,this);
    int x = 0, velX = 1;
    int y = 0, velY = 1;

   public void paintComponent(Graphics g)
   {
       super.paintComponent(g);

      g.setColor(Color.yellow);

      g.fillOval(x, y, 50, 50);

      tm.start();
   }

    public void actionPerformed(ActionEvent E)
  {
     if(x < 0 || x > 550)
        velX = -velX;
     if (y < 0 || y > 280)
        velY = -velY;

     x = x + velX;
     y = y + velY;
    repaint();
  }
   public static void main(String[] args) {

      BouncingBall s = new BouncingBall();
      JFrame jf = new JFrame();
      jf.setTitle("Bouncing Ball");
      jf.setSize(600,350);
      jf.setVisible(true);
      jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jf.add(s);
  }

}

Any ideas on how I should implement the start/stop buttons?
Thank you in advance
UPDATE:
I did the following, but I'm getting an error because of this line:
start.addActionListener(this);
It says "non static variable this cannot be referenced from a static context"
 public void actionPerformed(ActionEvent E)
  {
    if (E.getActionCommand().equals("Start")){
      if(x < 0 || x > 550)
         velX = -velX;
      if (y < 0 || y > 280)
        velY = -velY;

     x = x + velX;
     y = y + velY;
     repaint();
    }

    else
    {}

 }

  public static void main(String[] args) {

     BouncingBall s = new BouncingBall();
    JFrame jf = new JFrame();

    JPanel jp = new JPanel();

    JButton start = new JButton("Start");

    start.addActionListener(this);

    jp.add(start);

    jf.add(jp,BorderLayout.SOUTH);

    jf.setTitle("Bouncing Ball");
    jf.setSize(600,350);
    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.add(s);
    }

  }

Can anyone tell me what I'm doing incorrectly? The duplicate question didn't help me a lot.


text:
Q: Error handling for PhpUnit Selenium tests I have a suite of Selenium tests. Sometimes, for example, an 'assertIsElementPresent' will fail. In certain circumstances, this may be because someone broke something and the result of the sequence of UI clicking is an error that has resulted in the site's error page being shown.
How do I check if this has happened for every single failure, without having to implement a call to the below method everwhere?
    $isErrorPage = $selenium->isElementPresent("id=siteErrorPage");
    if ($isErrorPage){
        $html = $selenium->getHtmlSource();
        //send the $html to devs, log it, etc.
    }

The intention is simply to email the html source of the page that's being shown if the page has turned out to be an error page.

A: I looks like you would have to extend the PHPUnit_Extensions_Selenium2TestCase class, and overload onNotSuccessfulTest(). Add your code in there and make all your testcases extend your new class instead of PHPUnit_Extensions_Selenium2TestCase. Make sure to call parent::onNotSuccessfulTest() in your extended version.
I haven't tested this, but from studying the code, this should get you what you want. Looks like the stop() command is sent on session __destruct(), so the session should still be active when you go to try and get your screenshot.


text:
Q: How do you reset an AS3 list component so that nothing is selected (NOT selectedIndex=0) I have a list component on the stage in an AS3 movie. I populate it with values at runtime and the user can select multiple values.
When a button is clicked I want the list to reset to a state where nothing is selected, all I can figure out is to set the selected index to 0 and have the first position on the list either blank or reading "choose from the list" and make the code ignore this if it is selected.
Is there a way to reset list (and combobox components) to nothing selected.
thanks

A: OK I found it:  selectedIndex = -1


text:
Q: The Runner of type Shell don't work: Job failed (system failure): preparing environment: 1- Environment:

*

*Gitlab-CE

*GitLab 13.2.1 (b55baf593e6)

*GitLab Shell 13.3.0

*GitLab Workhorse v8.37.0

*GitLab API v4

*Ruby 2.6.6p146

*Rails 6.0.3.1

*PostgreSQL 11.7

*Debian GNU / Linux 10 server (buster)

2- .gitlab-ci.yml file:
before_script:
  - echo "--------- STARTING WORK ------------"

job_homologacao:
   only:
     - homologation
   script:
     - cd /home/ati/
     - mkdir test
     - echo "got here"

job_producao:
   only:
     - master
   script:
     - cd /home/ati/test/
     - echo "got here"

3- Error presented when the runner is executed:
Running with gitlab-runner 13.2.1 (efa30e33) on runner with Akx_BvYF shell
Preparing the "shell" performer
Using Shell executor ...
Preparing environment
Running on hermes ...
ERROR: Job failed (system failure): prepare environment: exit status 1. Check https://docs.gitlab.com/runner/shells/index.html#shell-profile-loading for more information
4- correction attempts:
I read and executed all the procedures contained in the codumentation:

*

*https://docs.gitlab.com/runner/faq/README.html#job-failed-system-failure-preparing-environment

*https://docs.gitlab.com/runner/shells/index.html#shell-profile-loading

A: I was erroneously editing the file .bash_logout located inside my Home /home/ati/
Gitlab when installing gitlab-runner create a Home for it in /home/gitlab-runner/
I just had to comment on the contents of the /home/gitlab-runner/.bash_logout file for the job to work.

A: First find out home directory for gitlab runner.
$ ps aux | grep gitlab-runner
/usr/bin/gitlab-runner run --working-directory /var/lib/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner

Now, check .bash_logout exist or not.
$ ls -lah /var/lib/gitlab-runner/
total 20K
drwxr-xr-x  4 gitlab-runner root          4.0K Dec  1 02:53 .
drwxr-xr-x 42 root          root          4.0K Nov 11 03:29 ..
-rwxr--r--  1 gitlab-runner gitlab-runner   30 Dec  1 02:53 .bash_logout
drwxr-xr-x  2 gitlab-runner gitlab-runner 4.0K Dec  1 02:26 .terraform.d
drwxrwxr-x  3 gitlab-runner gitlab-runner 4.0K Nov 11 03:23 builds

At last, open .bash_logout file and comment out all lines and save it.
 $ vim /var/lib/gitlab-runner/.bash_logout
 # ~/.bash_logout: executed by bash(1) when login shell exits.

 # when leaving the console clear the screen to increase privacy

 #if [ "$SHLVL" = 1 ]; then
 #    [ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q
 #fi

ps: Originally answer was given by Jonathan Allen
Jonathan Allen (@sc_jallen) on gilab-runner issues.

A: If your runner is on Ubuntu 20.04, check this out: https://gitlab.com/gitlab-org/gitlab-runner/-/issues/26605
Solution:
sudo rm /home/gitlab-runner/.bash_logout

A: After upgrading Ubuntu 18.04 to 20.04, I was also hit by this bug.
Removing .bash_logout worked for me.

A: Did you check these?

*

*Debian users should use APT pinning, because a native package called gitlab-ci-multi-runner is available in Debian Stretch and by default, when installing gitlab-runner, that package from the official repositories will have a higher priority.

*Also, be sure to disable SKEL when installing GitLab Runner: set the environment variable GITLAB_RUNNER_DISABLE_SKEL to true before you install the package.
For details on both, see https://docs.gitlab.com/runner/install/linux-repository.html#apt-pinning


text:
Q: New to AnimationFrames, Need to delete previous image when new one is drawn, how? Hoping you can help me. I'm new to using AnimationFrames (started using to meet business requirements). I have managed to make an animation that changes as you scroll (via very helpful codepens) but the issue i have is that it's just adding a new image, and leaving the previous image behind, leaving a trail. (can be seen here: https://aimtechnologies.com/scrolltest/index). I know there's CancelAnimationRequest but im not sure where to put it in to solve my issue?
See below for the code:
const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");

const frameCount = 148;
const currentFrame = index => (
  `images/1 & 2 Intro & Exploded View_${index.toString().padStart(5, '0')}.png`
)

const preloadImages = () => {
  for (let i = 1; i < frameCount; i++) {
    const img = new Image();
    img.src = currentFrame(i);
  }
};

const img = new Image()
img.src = currentFrame(1);
canvas.width=1158;
canvas.height=770;
img.onload=function(){
  context.drawImage(img, 0, 0);
}

const updateImage = index => {
  img.src = currentFrame(index);
  context.drawImage(img, 0, 0);
}

window.addEventListener('scroll', () => {
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;
  const scrollFraction = scrollTop / maxScrollTop;
  const frameIndex = Math.min(
    frameCount - 1,
    Math.ceil(scrollFraction * frameCount)
  );

  requestAnimationFrame(() => updateImage(frameIndex + 1))
});

preloadImages()```

A: Try this: context.clearRect(0, 0, canvas.width, canvas.height); right before you call drawImage

A: Solved: Use JPG's instead of PNGs
Or if you need to use pngs change
  context.drawImage(img, 0, 0);
}
``` to ```img.onload=function(){
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(img, 0, 0);
}```


text:
Q: Removing relevance data from Marklogic query results With the below query I would like to modify the options so that I am only retrieving the values.  The query returns the path, the relevance as well as values.  I just need the values so I can edit it for reporting purposes.  Can I get some insight on how to accomplish this task?  I am also using the Javascript API within Marklogic 8.
results = jsearch.documentSelect(cts.search($error_details),
                     {namespaces: {//emf:namespace is declared here},
                      extract: {paths: ['//emf:properties/emf:property[@key = "filename"]/.',
                               '//emf:properties/emf:property[@key = "idnumber"]/.',
                               '//emf:properties/emf:property[@key = "error description"]/.',
                               '//emf:properties/emf:property[@key = "error code"]/.']}
                     }).toString();

The query
cts.andQuery([
cts.elementRangeQuery(fn.QName('uri','creation-time'), ">=", $startDate),
cts.elementRangeQuery(fn.QName('uri','creation-time'), "<", $endDate),
cts.elementValueQuery(fn.QName('uri','component-name'), "InvalidFiles" ),
cts.elementValueQuery(fn.QName('uri','category'), "error")
])

A: It sounds like the jsearch.documentSelect() wrapper might not be necessary in this case.
The cts.search() function returns the documents as a ValueIterator in MarkLogic 8.
One easy way to process the documents is to chain the toArray() functions -- as in cts.search().toArray() -- and then chain the standard array map() or reduce() functions to convert the documents into the report.
Footnote:  cts.search() returns a Sequence in MarkLogic 9, but sequences also have a toArray() function.
Hoping that helps,

A: There are multiple search options which allow you to customize your search response. For example, you can disable to return aggregates with this option:
<options xmlns="http://marklogic.com/appservices/search">
  <return-aggregates>false</return-aggregates>
</options>

The query returns the path, the relevance as well as values.

If you mean score, confidence and fitness by "relevance", i dont think there is an option for that.


text:
Q: HTML5 video not playing on certain ipads when SCORM packaged Would anyone know why html5 video would not work only when run from an LMS(Learning management system) on an IPad?
This seems to be device specific.
I've tested 5 ipads, 3 have worked and 2 haven't. I've used two different models, the air and the model before the air(has the lightning port). The version of the OS has varied, but Ive had 7.1.2 produce different results, both of which were the air model.
I've tested 2 LMS systems and the devices that don't work, don't work on both LMSs.
I don't believe the content is at fault. I get the same results when using completely different tools to embed the video. I'm currently using the projector html5 player(hand coding). But this content doesn't work when I use Lectora to publish it. Also I've tested multiple videos encoded from multiple sources, same thing happens...
What really has me stumped is the fact I CAN play the videos on a normal webserver on these devices.
Any suggestions would be great. Even somewhere to start looking with IPad settings. I'm at a loss?
Thanks in advance!
Androo
Oh, could embedded frames affect my results? LMS/SCORM players almost always run content through them.

A: See if you can access the mime types supported by the LMS.  Most likely the server is having issues with newer video formats.  Hopefully if you don't have direct access, you can open a support ticket.  Just let them know what movie types you support.
Pretty common issue on legacy systems.
If thats not it, maybe sample your failover  code for each browser.

A: I have come across this problem and solved it. This can happen either because the Web server has to send the proper Mime type (video/mp4) as @Mark suggested, but also because the web server should stream the video. There are specific ways to stream the video to the client:
If you're serving the file with PHP, then have a look at Resumable downloads when using PHP to send the file?, this has worked for me. If you're serving the file from apache directly, have a look at the xsendfile module for apache, which is great at serving files of any kind, and will also solve this problem.


text:
Q: Sage Accpac Ireport method failed We had a macros developed in our company that used to export files to an Excel format and then inserted those values in the Sage ACCPAC Payroll module. For some reason the code has stopped to respond, and it gives an error: method ireport of accpac.ireport failed
Here is the code:
rpt.NumOfCopies = 1
rpt.Format = PF_NONE
rpt.Destination = PD_FILE
rpt.PrintDir = "[\\hcc-acc\Accpac\Macros\Reports and Macros\Tax\Test]"

rpt.PrintReport

As soon as it comes to rpt.PrintReport, it gives an error. I will be absolutely grateful for  any help.

A: You'll need to include the name of the PDF file in the rpt.PrintDir parameter:
rpt.PrintDir = "[\\hcc-acc\Accpac\Macros\Reports and Macros\Tax\Test\SomeFileName.PDF]"


text:
Q: Сделать динамически формируемый отчет в excel Нужно сделать отчет в excel, который бы загружался по клику на ссылку, использую Spring MVC и JExcel Api. При клике по линку контроллер отлавливает переход и метод формирования отчета в сервисе запускается, однако, в результате в браузере ничего не происходит. Что не так?
Контроллер:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ModelAndView generateScheduleReport(HttpServletResponse response) {
  reportService.createExcelOutputExcel(response);
  return null;
}

Сервис:
@Slf4j
@Service
public class ReportService implements ExcelOutputService{

public WritableWorkbook createExcelOutputExcel(HttpServletResponse response) {
    String fileName = "Excel_Output.xls";
    WritableWorkbook writableWorkbook = null;
    try {
        response.setContentType("application/vnd.ms-excel");

        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        writableWorkbook = Workbook.createWorkbook(response.getOutputStream());

        WritableSheet excelOutputsheet = writableWorkbook.createSheet("Excel Output", 0);
        addExcelOutputHeader(excelOutputsheet);
        writeExcelOutputData(excelOutputsheet);

        writableWorkbook.write();
        writableWorkbook.close();

    } catch (Exception e) {
        log.error("Error occured while creating Excel file", e);
    }

    return writableWorkbook;
}
...
}


text: Q: iphone wont send imessage to another iphone - sends as sms My dad has an iPhone 4. He has his iMessage and group messaging turned on, but when I use iMessage to message him and my mom (who also has an iPhone, as do I), the messages that I send only go through to my mom (i.e. I send a group message to my mom and dad and only my mom gets it). When my mom responds, both my dad and I get the message, so that works normally. I can message my dad directly (not in a group text), but that sends as an SMS (it shows up green vs. blue), even though I have his number stored as an iPhone in my contacts. How can I get it so that I can iMessage him vs send him an SMS? I think once that part of it is fixed I might be able to send him group texts with success.


text:
Q: Regex match strings between asterisks I have a string like this:
var s = "*string1* *string2* *string3*";

I'm trying to create a regex which returns an array of the three strings between *
How can I do that? I tried using this but I'm not sure if it is correctly escaped
s.match("\*(.*)\*")

Thanks

A: You need to use lazy quantifier ? here and also escape \
Like this \*(.*?)\* Regex101 Demo
Without using lazy quantifier you can do something like this.
\*[^*]+\* This will match a * everything until a * *. Regex101 Demo
Use \\ instead of \ in actual code.


text:
Q: MySQL: Selecting most similar value? So I have a table with peoples names.
I need to code a query that selects the person with the name most similar to the given one.
For example:
SELECT * FROM people WHERE name='joen'

'joen' doesnt exist in the table, so it will return John, which exists in the table.
What's the MySQL command for this?

A: You may be looking for SOUNDEX and SOUNDS_LIKE
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

A: The Levenshtein algorithm computes the "distance" between words: Levenshtein MySQL function
You can use it like this if you add that function:
SELECT * FROM people WHERE levenshtein('joen', `name`) BETWEEN 0 AND 4;

A: I'm not an expert on this, but this is no trivial matter. By "similar" do you mean it might be one or 2 letters off, or do you mean "Jon" should match "Jonathan" and "Bill" should match "William"?
If the latter, you might want to find or build a table that maps names/nicknames to eachother, and do a search on that.
If it's misspellings, Levenshtein might be of assistance, but I don't know how you'd integrate that in an SQL query.

A: The LIKE Keyword might help you
SELECT * FROM people WHERE name LIKE 'jo%'

Selects users where name starts with "jo"
If you're programatticaly changing the query, you
can check for the "result" and query the database again
with the new Query by reducing the characters in the
"name" specified.
SELECT * FROM people WHERE name LIKE 'jones%'

SELECT * FROM people WHERE name LIKE 'jone%'

SELECT * FROM people WHERE name LIKE 'jon%'

SELECT * FROM people WHERE name LIKE 'jo%'


text:
Q: Is -Duser.language option is a VM property I am confused of passing -Duser.language option. we can pull this in our application by just calling System.getProperty("user.language), But if we set the Locale.setDefault() to some other language, will it override the user.language which we passed as vm args.
And even if i set the System.setProperty("user.language","someotherlang"), does it overrides user.language which we passed.
Thanks.

A: First of all, all options that you pass to the JVM with -D... are called system properties. As you know, you can access them with System.getProperty(...). You are even allowed (if not having a restrictive security manager) to change these properties by adding, removing, and changing the key-value-pairs.
Regarding the locale settings, have a look at the interesting parts of Locale's implementation (JDK8):
public final class Locale implements Cloneable, Serializable {
    [...]
    private volatile static Locale defaultLocale = initDefault();
    [...]
    private static Locale initDefault() {
        String language, region, script, country, variant;
        language = AccessController.doPrivileged(new GetPropertyAction("user.language", "en"));
        [...] // here other properties are also retrieved
        return getInstance(language, script, country, variant, null);
    }
    [...]
}

So, the first time the class Locale is accessed, it is also initialized, which also means an initialization of the static variable defaultLocale with respect to the above mentioned system property.
If you later change one of these system properties ("user.language" for example) this will not have any effect to the private class variable defaultLocale.
On the other hand, you can (re)set the default locale with calling Locale.setDefault(...). Let's have a look into its implementation:
public static synchronized void setDefault(Locale newLocale) {
    setDefault(Category.DISPLAY, newLocale);
    setDefault(Category.FORMAT, newLocale);
    defaultLocale = newLocale;
}

This calls the other setting method, so let's have a look there also:
public static synchronized void setDefault(Locale.Category category, Locale newLocale) {
    [...]
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) sm.checkPermission(new PropertyPermission("user.language", "write"));
    switch (category) {
    case DISPLAY: defaultDisplayLocale = newLocale; break;
    case FORMAT: defaultFormatLocale = newLocale; break;
    default: assert false: "Unknown Category";
    }
}

As you can see, the private class variable defaulLocale is set to the new locale you want to set, but the system property "user.language" is not touched.
That means, the system properties regarding the locale are used for initialization, and then they are not interesting anymore.
In fact, this is some standard behavior for configuring an application. Even I use this mechanism: Reading system properties for initializing my components (using some default if the system property is not set), but then not touching the system properties anymore.


text:
Q: old toshiba laptop wont boot any OS i install I upgraded an old Toshiba laptop and installing a new SSD, replaced the RAM from 4GB to 8GB, and tried installing a new OS. However, I encountered a  problem, I can't boot any OS I throw-in at the laptop from windows 7, 8, 8.1, and even 10. After booting from the bootable drive, it appears to be stuck and shows weird lines and after pressing any key, it restarts itself and repeats the same process.
The old hard drive is perfectly working but it is really slow, so I decided to switch it to SSD. I even tried to boot and installing a new OS to the HDD just to see if the SSD is the problem but it shows the same issue.
I also check the Secure Boot and it doesn't appear to have one. The bios version is insydeh20 setup utility rev 3.5.
Here is a link just to show the weird lines.
enter image description here
Any help is very much appreciated. Thanks in advance!
rufus settings


text:
Q: Script works from PC but not on server I wrote a small python script to automatically send emails every day at 10 am. The script works fine from my Laptop running Linux Mint 18. But when I deploy the script to my server (droplet taken from DigitalOcean) running Ubuntu 16.04.3 the script gives an STMP authentication error.
Allow less secure apps to sign in and other settings are enabled on my Gmail account.
Here's the script -
import schedule
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

fromaddr = "yadullahabidi@gmail.com"
toaddr = "yadullahabidi@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Attendance for Yadullah Abidi"

body = "Good morning Surender Ji. I reached office at 10:00 AM today."
msg.attach(MIMEText(body, 'plain'))

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr,"password")
text = msg.as_string()
def job():
    server.sendmail(fromaddr, toaddr, text)

schedule.every().day.at("08:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

A: All SMTP actions are blocked with DigitalOcean and you need to create a ticket with Support via the control panel and ask to un-block SMTP. This was implemented  to prevent SPAM.
Your other option is to use a third party mail service that allow port 2525 for mail like mandrill or mailgun if the resolution process is too long.
Reference : https://meta.discourse.org/t/digital-ocean-is-blocking-outgoing-mail/66740/24


text:
Q: Tools for website/web application load testing? Before going into production, our client demands actual numbers of how many users our web application can handle.
We have all kinds of features implemented including asset management (file uploads/downloads), documents import/export, various statistics, web-services etc.
I guess we need tool which could emulate users form submission because documents import/export as far as I noticed is the slowest part of an app because of parsing and generation.
Which tool (or set of tools) could do this?
Application details:

*

*XHTML/jQuery

*Coldfusion 8

*SQL Server 2008

*Windows Server 2008

A: HPs Open Source HTTPerf I like. Just setup the URLS you want to test and let it rip. use a couple of machines to emulate load. You could even parse the output into a DB and do some number crunching.
Also, think about doing HTTPerf runs with profiling on the server side to see what lags and what doesnt. A nice touch is to let a user go on the app, and record all POST/GET requests and use them as a replay set for typical user interactions.
Also, if you are thinking about UX, use firebug or something to check JS imports are being done asynchronously instead of one-at-a-time. Have a ganders at Stackoverflow question 310583/loading-javascript-dependencies-on-demand

A: *

*http://loadimpact.com/

*WebLoad: Professional and open
source load testing from
CFMeetup

A: I like jMeter - free software and does the job quite well.
Few intro screencasts:
http://www.fosscasts.com/screencasts/3-Load-Testing-with-Apache-JMeter
http://vimeo.com/10164982

A: Visual Studio Ultimate edition has great load/stress testing tools, although the ultimate edition can be a bit expensive.

A: m using Full version of JBlitz Professional 5.0 ..
it's very good

A: There are few analytical performance tool out in market(not free) one i came through and works well is New Relic. If you are looking only to test the api then http://locust.io/ is good one and free too.


text:
Q: SQLITE_CORRUPT error on table with UNIQUE index containing COALESCE() using DbVisualizer A colleague created a table with a strange UNIQUE key (to get around NULL handling) by adding a COALESCE to enforce NULL values in the unique constraint. I'm receiving the error below when trying to open the database using DbVisualizer Pro, but it seems to open fine when using SQLite Expert Professional (I'm trialing them both):
SQLITE_CORRUPT: The database disk image is malformed (malformed database schema (ux_test) - near "(": syntax error)
DDL:

CREATE TABLE Test (
  Id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  val1 integer,
  val2 integer,
  val3 integer
);
CREATE UNIQUE INDEX ux_test ON Test(val1, COALESCE(val2, -1), COALESCE(val3, -1));

I asked DbVisualizer support for help regarding this, and was told that it's a SQLite error. Can anyone offer any insight into this? FYI, the COALESCE() is in the Unique key because of the way SQLite handles NULL values; it doesn't see NULL values being equal in the constraint. Additionally, they prefer to use INSERT OR REPLACE INTO if the constraint is hit, so a BEFORE trigger won't work.
Thanks.
EDIT: CL's answer (below) seems to the issue; DbVisualizer Pro is using SQLite version 3.8.11, vs the current version of 3.18.0. I'm trying to see if I can get an update to the dll's used because it's really a great application. Thank you!

A: The documentation says:

The ability to index expressions was added to SQLite with version 3.9.0 (2015-10-14). A database that uses an index on expressions will not be usable by earlier versions of SQLite.

Obviously, your DbVisualizer is horribly outdated.


text:
Q: PHP 5 - xml parsing How to parse below xml (i.e in this xml some tag contains the prefix "soap" ) in php 5? Please any one show me an example?
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <AuthorizationToken xmlns="http://www.avectra.com/OnDemand/2005/">
      <Token>string</Token>
    </AuthorizationToken>
  </soap:Header>
  <soap:Body>
    <AuthenticateResponse xmlns="http://www.avectra.com/OnDemand/2005/">
      <AuthenticateResult>string</AuthenticateResult>
    </AuthenticateResponse>
  </soap:Body>
</soap:Envelope>

A: Have a look at http://php.net/manual/en/book.simplexml.php

A: PHP has a specific library for SOAP:

*

*http://es.php.net/manual/en/book.soap.php
Unluckily, the official documentation doesn't seem to have examples. Here's the first one I found in Google that doesn't seem outdated:

*

*http://www.vankouteren.eu/blog/2009/03/simple-php-soap-example/

A:
See in this link Here is a xml file that is parsed using simple php script no need of external modules

PHP XML Parser


text:
Q: How to boost the performance of a custom shortcut action Handler in Vaadin 7? given an example from the Book of Vaadin (Chapter 5.21 Table Component, Navigation in Editable Mode):
// Keyboard navigation
class KbdHandler implements Handler {
    Action tab_next = new ShortcutAction("Tab",
            ShortcutAction.KeyCode.TAB, null);
    Action tab_prev = new ShortcutAction("Shift+Tab",
            ShortcutAction.KeyCode.TAB,
            new int[] {ShortcutAction.ModifierKey.SHIFT});
    Action cur_down = new ShortcutAction("Down",
            ShortcutAction.KeyCode.ARROW_DOWN, null);
    Action cur_up   = new ShortcutAction("Up",
            ShortcutAction.KeyCode.ARROW_UP,   null);
    Action enter   = new ShortcutAction("Enter",
            ShortcutAction.KeyCode.ENTER,      null);
    public Action[] getActions(Object target, Object sender) {
        return new Action[] {tab_next, tab_prev, cur_down,
                             cur_up, enter};
    }

    public void handleAction(Action action, Object sender,
                             Object target) {
        if (target instanceof TextField) {
            // Move according to keypress
            int itemid = (Integer) ((TextField) target).getData();
            if (action == tab_next || action == cur_down)
                itemid++;
            else if (action == tab_prev || action == cur_up)
                itemid--;
            // On enter, just stay where you were. If we did
            // not catch the enter action, the focus would be
            // moved to wrong place.

            if (itemid >= 0 && itemid < table.size()) {
                TextField newTF = valueFields.get(itemid);
                if (newTF != null)
                    newTF.focus();
            }
        }
    }
}

// Panel that handles keyboard navigation
Panel navigator = new Panel();
navigator.addStyleName(Reindeer.PANEL_LIGHT);
navigator.addComponent(table);
navigator.addActionHandler(new KbdHandler());

Actually the navigator.addCompoent(table) must be replaced with navigator.setContent(table), cause Panel has not an addComponent method, but this is not the point.
The point is that I have noticed that using a custom shortcut action handler lowers the performance of the focus change from a field to the next one when you hold down the action key. The reason of this is because when using this custom Handler implementation, Vaadin makes a request every time one of the shortcut keys is typed (in this example, when TAB, Shift+TAB, Arrow_Up, Arrow_Down and ENTER are typed).
This gives the following result:

Starting from the "Numeric Field" with value "0" I have typed TAB two times and at the same time two requests were made to the server.
In contrast, if using no custom shortcut action Handler, the previous two TABs would result into this:

No unnecessary requests. This is not a problem while the typing is slow, but as I said before, if you hold down the TAB key, hundreds requests will be made, and you will notice the difference. Enhancing the user experience allowing the user easily navigate through the table fields here has a cost in performance from this point of view.
So my question is, is there a way to disable this unnecessary requests when using a custom shortcut action Handler in Vaadin?


text:
Q: "jarsigner error: java.lang.RuntimeException: certificate exception" while trying to manually sign an APK Im suddenly unable to manually sign my application.
It used to work until now.
The only thing I remember changing is android studio to version 2.3.2
I'm getting this error:

jarsigner error: java.lang.RuntimeException: certificate exception:
  Unable to initialize, java.io.IOException: DerInputStream.getLength():
  Redundant length bytes found

This is the command that I run:
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my_keystore.keystore some-unsigned.apk alias

I tried to refer this post:
PKCS#12 : DerInputStream.getLength() exception
but unfortunately I'm getting a different exception
No idea what to do
Thanks in advance

A: Well, I found the solution
The problem is the version of java that installed.
It seems like that there is a problem (at least for me...) with the newest version of java (at that moment of writing: 8u131)
I tried that on another mac which has 8u101 version and it worked, so I downgraded it on my mac and it worked either.
In case it helps anyone...


text:
Q: Move files that are different to another folder OK, so I have a very large iTunes library and recently decided to sort through it and organize it in a much neater way than just throwing all my music in a folder and hoping for the best. So after many hours of moving files in and out or directories and waiting for iTunes to do whatever it is iTunes does, somehow I've ended up with a few missing songs. If it was 1 or 2, so what, i can find them by myself. But I'm missing a little over 30000 so I'm not too keen on the idea of looking for them manually.
So my question is, "Is there a way for me to, in a linux environment, find all of the files that are in 1 directory, that are not in another, and then move them?"
My folder structure looks a little like this:

*

*Parent Directory (External Hard Drive)

*

*Missing Files (there's 4 of these folders

*

*Hundreds of Folders with Artist names (some have .mp3 files here, others have another subfolder, and others have another subfolder again)

*Parent Itunes Directory (Where iTunes keeps Music, Playlist files, Podcasts, etc)

(I'm really bad at lists in these questions^)
So what I need, is to move anything that is in the "Missing Files" directory that isn't in the "iTunes Folder"
Thank you for any help in advance guys, I really appreciate it.
Note: I only want to move the mp3 files from the folders, not the folders themselves.

A: Assuming you have a directory structure like:
music
  |- source
      |- foobar
      |- spamegg
      |- ...
  |- dest

and you need to move all .mp3 files under any level of subdirectories of music/source/ to music/dest/ only if the file not already present in music/dest/.
If that so, running all commands below from music/ directory:

*

*Create an array containing all .mp3 files under music/source, recursive operation:
shopt -s globstar  ## Enables recursive search
source_files=( source/**/*.mp3 )

*Do the same with the music/dest/ directory and strip off the directory portion from file names:
dest_files=( dest/**/*.mp3 )
dest_files=( ${dest_files[@]} )

*Iterate over the source files and check if the file already exist in the destination, if not mv the file to music/dest/:
for i in "${source_files[@]}"; do [[ ! ${dest_files[@]} =~ ${i##*/} ]] && \
         echo mv -i "$i" dest/; done

echo is for doi9ng the dry-run, if satisfied, just remove echo:
for i in "${source_files[@]}"; do [[ ! ${dest_files[@]} =~ ${i##*/} ]] && \
         mv -i "$i" dest/; done

Scripted form:
#!/usr/bin/env bash
shopt -s globstar
source_files=( source/**/*.mp3 )
dest_files=( dest/**/*.mp3 )
dest_files=( ${dest_files[@]} )
for i in "${source_files[@]}"; do [[ ! ${dest_files[@]} =~ ${i##*/} ]] && \
     mv -i "$i" dest/; done

You can obviously use absolute paths, change the relevant paths to meet you need.
Caveats:

*

*All source and destination .mp3 files are put into arrays, needs bit of extra memory, should not be a problem on modern systems

*The membership test takes time, again should not be noticeable on modern systems
Example:
music$ tree
.
├── dest
│   ├── 1.mp3
│   ├── 2.mp3
│   ├── 3.mp3
│   ├── 7.mp3
│   ├── 8.mp3
│   └── 9.mp3
└── source
    ├── bar
    │   ├── 10.mp3
    │   ├── 6.mp3
    │   ├── 7.mp3
    │   ├── 8.mp3
    │   └── 9.mp3
    └── foo
        ├── 1.mp3
        ├── 2.mp3
        ├── 3.mp3
        ├── 4.mp3
        └── 5.mp3

music$ shopt -s globstar

music$ source_files=( source/**/*.mp3 )

music$ dest_files=( dest/**/*.mp3 )

music$ dest_files=( ${dest_files[@]} )

music$ for i in "${source_files[@]}"; do [[ ! ${dest_files[@]} =~ ${i##*/} ]] && echo mv "$i" dest/; done
mv source/bar/10.mp3 dest/
mv source/bar/6.mp3 dest/
mv source/foo/4.mp3 dest/
mv source/foo/5.mp3 dest/

music$ for i in "${source_files[@]}"; do [[ ! ${dest_files[@]} =~ ${i##*/} ]] && mv "$i" dest/; done

music$ tree
.
├── dest
│   ├── 10.mp3
│   ├── 1.mp3
│   ├── 2.mp3
│   ├── 3.mp3
│   ├── 4.mp3
│   ├── 5.mp3
│   ├── 6.mp3
│   ├── 7.mp3
│   ├── 8.mp3
│   └── 9.mp3
└── source
    ├── bar
    │   ├── 7.mp3
    │   ├── 8.mp3
    │   └── 9.mp3
    └── foo
        ├── 1.mp3
        ├── 2.mp3
        └── 3.mp3


text:
Q: Rails: Field 'browser' doesn't contain a valid alias configuration when pushing to Heroku Whenever I try pushing my Rails 6 app to Heroku, I kept getting an error message "Precompiling assets failed". I notice from the traceback that it was complaining of "Field 'browser' doesn't contain a valid alias configuration" for the "@fortawesome/fontawesome-free/js/all" import.
Field 'browser' doesn't contain a valid alias configuration
remote:                      /tmp/build_7682b1717ca625690f7939609cc5a51d/app/javascript/@fortawesome/fontawesome-free/js/all doesn't exist
remote:                    .jsx
remote:                      Field 'browser' doesn't contain a valid alias configuration
remote:                      /tmp/build_7682b1717ca625690f7939609cc5a51d/app/javascript/@fortawesome/fontawesome-free/js/all.jsx doesn't exist
remote:                    .mjs
remote:                      Field 'browser' doesn't contain a valid alias configuration
remote:                      /tmp/build_7682b1717ca625690f7939609cc5a51d/app/javascript/@fortawesome/fontawesome-free/js/all.mjs doesn't exist
remote:                    .js
remote:                      Field 'browser' doesn't contain a valid alias configuration
remote:                      /tmp/build_7682b1717ca625690f7939609cc5a51d/app/javascript/@fortawesome/fontawesome-free/js/all.js doesn't exist
remote:                    .sass
remote:                      Field 'browser' doesn't contain a valid alias configuration
remote:                      /tmp/build_7682b1717ca625690f7939609cc5a51d/app/javascript/@fortawesome/fontawesome-free/js/all.sass doesn't exist
remote:                    .scss
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote:
remote:  !     Push failed

Following some suggestions I tried to modify the FontAwesome import in my project from import "@fortawesome/fontawesome-free/js/all" to ```import "./fortawesome/fontawesome-free/js/all" but this did not work for me.

A: I had to check my package.json file, and I discovered the font awesome package was not included under the dependencies list but the devDependencies list, probably because I used the -save-dev option when installing the package with npm istall.
This was my package.json file before I moved the fontawesome package to the dependencies list.
  "dependencies": {
    "@babel/preset-react": "^7.8.3",
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "^4.4.1",
    "jquery": "^3.5.0",
    "popper.js": "^1.16.1",
    "prop-types": "^15.7.2",
    "toastr": "^2.1.4",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "@fortawesome/fontawesome-free": "^5.13.0",
    "webpack-dev-server": "^3.10.3"
  }

After moving the fontawesome package to the dependencies list, I was able to push my app to Heroku successfully.


text:
Q: Zend framework- how to stop execution and redirect to the error controller I want to catch php errors so i used set_error_handler('handler_function') when i echo the error message , 'Zend_Controller_Response_Exception' with message 'Cannot send headers; headers already sent' is thrown when i used the following lines
$fc=Zend_Controller_Front::getInstance();
$fc->getResponse()->setBody($error);

an error happened 'call to setBody method of a non-object'
i tried to throw an exception from the error handler but this depend on the error occurring before bootstrapping is displayed directly after bootstrapping displayed in errorController
i used $fc->throwExceptions(false) to ensure it will send exceptions to error controller
when i do nothing in the error handler the execution is continued
what i need is to have one place to handle all errors
if there is a way to redirect to the error controller with error in params this will be good

A: IMO best way to handle these errors is to register error handler that will convert any error/fatal error to exception. I guess that response is not created yet. You have to use $fc's setResponse() method to create new response. I would guess that converting to exception should work in any case. Same as exceptions from Zend classes work.


text:
Q: Java - Determine difference between user entering \n and pressing enter in html form Searched the web for this but not sure I'm asking the question correctly. I have a web form with a textarea. Users can type what ever they want (can paste emails, etc). When they submit, I escape things like newline so that when I store in a PostgreSQL db (json column type) it saves correctly. That all works fine. However, if a user type something like c:\foo\bar\notworking.txt the \n is treated like a new line so I end up with
c:\foo\bar
otworking.txt

If I look at the string (user hits enter) coming into the controller (Spring based) I see \n.
Question is, how do I differentiate between someone typing \n and hitting the enter key?

A: easiest solution:
String s = ...;
s = s.replaceAll("\\","\\\\");

Then the opposite after you load it back in

A: In order to insert raw text into a JSON column, you need to encode the text as JSON, meaning:
The following fails «badly»:
  "c:\foo\bar\notworking.txt"

encodes to (assuming non-ASCII needs encoding, which it does if the DB is not UTF-8):
"The following fails \u00ABbadly\u00BB:\r\n  \"c:\\foo\\bar\\notworking.txt\""

Side note: As a Java String literal, that would be:
String json = "\"The following fails \\u00ABbadly\\u00BB:\\r\\n  \\\"c:\\\\foo\\\\bar\\\\notworking.txt\\\"\"";

You will then of course use PreparedStatement or Spring, such that SQL escaping and SQL Injection issues are non-existent.