text:
Q: Why does Compile not make my function faster? I need to speed up a large program that repeatedly calls the module below (I've not trimmed the code for this question to ensure there is enough calculation to show a speed improvement.) The obvious way of making a step change in speed seemed to be use of Compile, so I create the second version show below, however, there is very marginal speed improvement. Am I doing something wrong?
ZrootsAnalytic[A_Real, B_Real] :=
 Module[
  { Zroot1, Zroot2, Zroot3, term1, term2},
  term1 = (-1. + 3. A - 4. B - 10. B^2.);
  term2 = (2. - 9. A + 12. B + 36. A B - 12. B^2. -
     56. B^3. + \[Sqrt](4. term1^3. + (2. - 9. A + 12. B + 36. A B -
          12. B^2. - 56. B^3.)^2.))^(1./3.);

  Zroot1 = (1. - B)/3. - (2.^(1./3.) term1)/(3. term2) +
    1./(3. 2.^(1./3.)) term2;

  Zroot2 = (1. - B)/
    3. + ((1. + I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. - I Sqrt[3.]) term2;

  Zroot3 = (1. - B)/
    3. + ((1. - I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. + I Sqrt[3.]) term2;
  {Zroot1, Zroot2, Zroot3 }
  ]

Compiled version of the code.
ZrootsAnalyticCC = Compile[
  {{A, _Real}, {B, _Real}},

  term1 = (-1. + 3. A - 4. B - 10. B^2.);
  term2 = (2. - 9. A + 12. B + 36. A B - 12. B^2. -
     56. B^3. + \[Sqrt](4. term1^3. + (2. - 9. A + 12. B + 36. A B -
          12. B^2. - 56. B^3.)^2.))^(1./3.);

  Zroot1 = (1. - B)/3. - (2.^(1./3.) term1)/(3. term2) +
    1./(3. 2.^(1./3.)) term2;

  Zroot2 = (1. - B)/
    3. + ((1. + I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. - I Sqrt[3.]) term2;

  Zroot3 = (1. - B)/
    3. + ((1. - I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. + I Sqrt[3.]) term2;
  {Zroot1, Zroot2, Zroot3 }
  ,
  {{ Zroot1, _Complex, 0}, {Zroot2, _Complex, 0}, {Zroot3, _Complex,
    0}, {term1, _Complex, 0}, { term2, _Complex, 0}},
  CompilationTarget -> "C",
  RuntimeAttributes -> {Listable},
  RuntimeOptions -> "Speed",
  CompilationOptions -> {"InlineCompiledFunctions" -> True}
  ]

Is it the use of imaginary no.'s that prevents speedup?
==================
Here is a modified version of the code as suggested by Mark
ZrootsAnalyticCC =
 Compile[
  {{A, _Real}, {B, _Real}},
  Module[{term1, term2, Zroot1, Zroot2, Zroot3},
   term1 = (-1. + 3. A - 4. B - 10. B^2.);
   term2 = (2. - 9. A + 12. B + 36. A B - 12. B^2. -
      56. B^3. + \[Sqrt](4. term1^3. + (2. - 9. A + 12. B + 36. A B -
           12. B^2. - 56. B^3.)^2.))^(1./3.);

   Zroot1 = (1. - B)/3. - (2.^(1./3.) term1)/(3. term2) +
     1./(3. 2.^(1./3.)) term2;

   Zroot2 = (1. - B)/
     3. + ((1. + I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
     1./(6. 2.^(1./3.)) (1. - I Sqrt[3.]) term2;

   Zroot3 = (1. - B)/
     3. + ((1. - I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
     1./(6. 2.^(1./3.)) (1. + I Sqrt[3.]) term2;
   {Zroot1, Zroot2, Zroot3 }
   ]
  ,
  {{ Zroot1, _Complex, 0}, {Zroot2, _Complex, 0}, {Zroot3, _Complex,
    0}, { term1, _Complex, 0}, { term2, _Complex, 0}},
  CompilationTarget -> "C"
  ]

I get no speed up and an error message:
  ZrootsAnalyticCC[1., 1.] // AbsoluteTiming

    CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation. >>

{0.046061, {1.86081 - 2.22045*10^-16 I, -2.11491 - 4.44089*10^-16 I,
  0.254102 + 4.44089*10^-16 I}}

However, the problem goes away when I specify {{A, _Complex}, {B, _Complex}}, the AbsoluteTiming for a single evaluation of ZrootsAnalyticCC is still about the same as the uncompiled version, but there is a 25x speed up when I evaluate it many times in table:
Table[ ZrootsAnalyticCC[1., 1.], {100000}]; // AbsoluteTiming

A: You might think that specifying the types of intermediate expressions as the third argument of Compile[] would make them local, but it does not. You need to put the expression in a Module[] with those variables in the first argument of Module[] as you did in the non-compiled code. Without that, the compiled code is effectively not compiled, since it keeps going back to Mathematica to set the global variables Zroot1, etc.
Your clue could have been that after running the compiled code, those variable names turn from blue to black. (Assuming that your front end works like mine.)
Update:
This is what I did and saw:
ZrootsAnalytic[A_Real, B_Real] :=
 Module[{Zroot1, Zroot2, Zroot3, term1, term2},
  term1 = (-1. + 3. A - 4. B - 10. B^2.);
  term2 = (2. - 9. A + 12. B + 36. A B - 12. B^2. -
      56. B^3. + \[Sqrt](4. term1^3. + (2. - 9. A + 12. B + 36. A B -
            12. B^2. - 56. B^3.)^2.))^(1./3.);
  Zroot1 = (1. - B)/3. - (2.^(1./3.) term1)/(3. term2) +
    1./(3. 2.^(1./3.)) term2;
  Zroot2 = (1. - B)/
     3. + ((1. + I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. - I Sqrt[3.]) term2;
  Zroot3 = (1. - B)/
     3. + ((1. - I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
    1./(6. 2.^(1./3.)) (1. + I Sqrt[3.]) term2;
  {Zroot1, Zroot2, Zroot3}]

For this I copied the Module[] from above, and changed the arguments to _Complex to avoid a numerical error:
ZrootsAnalyticCC =
 Compile[{{A, _Complex}, {B, _Complex}},
  Module[{Zroot1, Zroot2, Zroot3, term1, term2},
   term1 = (-1. + 3. A - 4. B - 10. B^2.);
   term2 = (2. - 9. A + 12. B + 36. A B - 12. B^2. -
       56. B^3. + \[Sqrt](4. term1^3. + (2. - 9. A + 12. B +
             36. A B - 12. B^2. - 56. B^3.)^2.))^(1./3.);
   Zroot1 = (1. - B)/3. - (2.^(1./3.) term1)/(3. term2) +
     1./(3. 2.^(1./3.)) term2;
   Zroot2 = (1. - B)/
      3. + ((1. + I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
     1./(6. 2.^(1./3.)) (1. - I Sqrt[3.]) term2;
   Zroot3 = (1. - B)/
      3. + ((1. - I Sqrt[3.]) term1)/(3. 2.^(2./3.) term2) -
     1./(6. 2.^(1./3.)) (1. + I Sqrt[3.]) term2;
   {Zroot1, Zroot2, Zroot3}], {{Zroot1, _Complex,
    0}, {Zroot2, _Complex, 0}, {Zroot3, _Complex,
    0}, {term1, _Complex, 0}, {term2, _Complex, 0}},
  CompilationTarget -> "C", RuntimeAttributes -> {Listable},
  RuntimeOptions -> "Speed",
  CompilationOptions -> {"InlineCompiledFunctions" -> True}]

Then running it, showing the speed-up:
Timing[Table[ZrootsAnalytic[x, y], {x, 1., 100.}, {y, 1., 1000.}];]

{7.57591, Null}

Timing[Table[ZrootsAnalyticCC[x, y], {x, 1., 100.}, {y, 1., 1000.}];]

{0.369698, Null}

Making the arguments _Complex is a bit of a hammer. It would be better to see where the computation requires complex calculations and to create a complex sub-expression at that point, in order to avoid the added work of complex calculations on real numbers.
You can see what it is compiling to by using:
Needs["CompiledFunctionTools`"]
CompilePrint[ZrootsAnalyticCC]

It will show the expressions so you see where in the calculation possible errors are occurring. It will also alert you if for some reason the code is falling back to Mathematica for some parts, indicated by MainEvaluate[]'s in the compiled code. You want to find a way to get rid of those in order to realize the benefit of compilation.


text:
Q: Installed Windows XP as a dual-boot partition with Windows 7. No drivers will install? I had Windows 7 and have just created a Windows XP partition.  My computer is an HP Pavillion dv6000.  Now, none of the drivers provided on the hp site will install.  The only driver of particular interest to me is my wireless network adapter, but what gives!  Does it have something to do with it being the F drive, rather than the C drive?

A: No - it should not make a difference what so ever (unless they use a custom, very bad installer). Try re-downloading the driver and remember that the Windows 7 and XP drivers will be different.
If you have a problem, try looking up who actually makes the device (Intel, Broadcom, Realtek etc.) and go to their site directly and download the latest drivers.

A: Are you dual booting or have you actually installed two windows systems on two seperate drives in the same machine?
Dual booting would produce no problems because both systems would then see their own 'c:\' drive and have seperate drivers for sound, video, networking, etc.
If you have actually installed the sytems on two drives and try to run them seperatly, each system will find the other's drivers and you will have different conflicts for video, sound, networking, etc.
Check your operating system setup and confirm what you've got and how you're going about it.
Good luck, and hope this helps you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS rendering different template inside ng-repeat using ng-view I would like to apologize that I couldn't provide any code snippet regarding this question, I am a newbie about AngularJS.

Using the code above, would it be possible to render different template which would be dependent on item.type property. I was expecting a result like this:

*

*item.type == "image" returning:

*item.type == "text" returning:

TEXT

As of now I have create a template html for the enumeration of item.type. Is this concern possible using AngularJS? I've recently learned that ng-view accompannied with ng-route.

A: I think one way you can do it is to use 'ng-if' to conditionally include html:

TEXT

A: You can have only one ng-view,
take a look at this answer.
from the documentation for ng-view:
ngView is a directive that complements
the $route service by including the rendered
template of the current route into the main
layout (index.html) file.

Every time the current route changes,
the included view changes with it according
to the configuration of the $route service.

Requires the ngRoute module to be installed.

What you're looking for is ng-include, combined with ng-switch,
take a look at this answer on how to combine the two.
ng-include creates a new child scope, which in turn inherits from the controller.
have a look at this answer for more information about the topic.


text:
Q: Determine that $\Sigma^{\infty}_{n=1}\frac{n!}{n^n}$ is convergent. This is the question from my book.
Is the series $\Sigma^{\infty}_{n=1}\frac{n!}{n^n}$ convergent or divergent?
Actually I know the answer is convergent by plotting but I can't complete the proof.
This is my workings:
$$\lim_{n->\infty}\frac{U_{n+1}}{U_n}=p$$
$$p<1 (convergent) ,p>1(divergent)$$
$$=\frac{\frac{(n+1)!}{(n+1)^{n+1}}}{\frac{n!}{n^n}}$$
$$=\frac{(n+1)n!}{(n+1)^n(n+1)}.\frac{n^n}{n!}$$
$$=\frac{n^n}{(n+1)^n}$$
$$=\left(\frac{n}{n+1}\right)^n$$
This is where I am stuck. Where do I go from here?

A: Note that
$$\left(\frac n{n+1}\right)^n=\left(\left(1+\frac1n\right)^n\right)^{-1}\to e^{-1}<1$$

A: You are correct so far. Now note that $\frac{n}{n+1} = 1-\frac{1}{n+1}$, and use the fact that $(1+\frac{x}{n})^n \to e^x$ as $n \to \infty$.

A: In fact, we can write $$\lim_{n \to \infty} (\frac{n}{1+n})^n = \lim_{n\to \infty} \frac{1}{(1+\frac{1}{n})^n} = \frac{1}{e} < 1$$ Hence, by ratio test the series is convergent. Hope it helps.

A: You can use Stirling's approximation
to obtain
$$
\frac{n!}{n^n} \leq e \frac{n^{n+1/2} e^{-n}}{n^n} = e \frac{\sqrt{n}}{e^n} .
$$

A: The last limit you wrote is known to be equal to $\frac{1}{e}$, so the series converges.
If you want another way to do this, you can use A.M.-G.M. inequality to show that $n!\leq \left(\frac{n+1}{2}\right)^n$, and thus
$$\frac{n!}{n^n}\leq \left(\frac{n+1}{2n}\right)^n\leq \left(\frac{3}{4}\right)^n$$for $n\geq 2$; hence the series is convergent by comparison.

A: You are trying to use the Ratio Test, and your limit converges to $e^{-1}<1$. You can use L'Hospital's Rule to show this. Some traditions even define $e^{-1}$ to be a limit like this.
But here is an alternative. I claim $$\frac{n!}{n^n}<\frac{1}{n^2}$$ for sufficiently large $n$. This is equivalent to $$n!<n^{n-2}$$ $$6\left(\overbrace{4\cdots n}^{n-3\text{ factors}}\right)<n\left(\overbrace{n\cdots n}^{n-3\text{ factors}}\right)$$ Once $n>6$, then what remains to consider on the left is a product of $n-3$ factors. What remains to consider on the right side is also a product of $n-3$ factors, all of which are greater than $1$ and at least as large as any factor on the left.
So you can use comparison with $\sum\frac{1}{n^2}$, a nice $p$-series.

A: Take $$\log \mathcal{l}=\lim_{n\to\infty}n\log\left(\frac{n}{n+1}\right),$$
where $\mathcal{l}=\lim_{n\to\infty}\left(\frac{n}{n+1}\right)^n$, and this remarks make sense if you don't remember how get this limit directly as was showed in a previous answer.
Then write it as a evaluation $\frac{0}{0}$, that is $$\log \mathcal{l}=\lim_{n\to\infty}\frac{\log\left(\frac{n}{n+1}\right)}{1/n},$$ using L'Hôpital's rule, since after you do the calculations, you can get $$\lim_{n\to\infty}\frac{\log\left(\frac{n}{n+1}\right)}{1/n}=\lim_{n\to\infty}\frac{\frac{1}{n(n+1)}}{\frac{-1}{n^2}}=-1.$$
Then by ratio test the series is convergent, since $\mathcal{l}=e^{-1}<1.$


text:
Q: How to transform a JavaScript Date to a different timezone If I run var myDate = new Date('29-06-2016 10:00'), myDate will only contain one thing: a number. The number of milliseconds from 01-01-1970 00:00:00 GMT to 29-06-2016 10:00:00 XXX
XXX being the timezone of the OS. In my case BST (because it is a summer date, in winter would be GMT).
Now... What if I want the milliseconds from 01-01-1970... to 29-06-2016 10:00:00 GMT-7?
I only found methods to tell me what time is in the GMT-7 timezone when in BST timezone is 29-06-2016 10:00:00, but that is not what I am looking for!
Also, to change an environmental variable so the timezone is GMT-7 is not an option.

A: I think you want the date string in the following format
"2016-06-29T10:00:00-07:00"

That lets you set the timezone relative GMT (not 100% sure on the timezone, but it's client side so does depend on their locale).
I had a similar thing where JS was changing the time on date objects and the only way I found was to set up the date and set this.
Bonus info, to get this from a .NET DateTime using the following string format.
"yyyy-MM-ddTHH:mm:sszzz"

A: I think I found a way of doing it, using moment.js as ErikS suggested:
// This code is running in a Node.js server configured to use UTC

// Incorrect date, as it is interpret as UTC.
// However, we do this to get the utcOffset
var auxDate = moment.tz(new Date('2016-6-23 10:15:0'), 'US/Mountain');

// Get the milliseconds since 1970 of the date as if it were interpreted
// as GMT-7 or GMT-6 (depends on the date because of Daylight Saving Time)
var milliseconds = auxDate.valueOf() - auxDate.utcOffset() * 60000;


text:
Q: How to allow people from external network to access my Node.js app via IP address? I tried Google for the last 3 days and also found most of the StackExchange answers for LAN. I found no solution to enable people to access my app from an external network.
I have already enabled access for Node.js to connect anywhere in the internet in my firewall, which should not be a concern, but I am not sure.

A: You can use tunneling library, such as https://ngrok.com/
This will give you a URL where anybody can access your APIs online.

A: *

*Go to your router and set a port-forward-rule

*

*Set the ip to your local ip of your computer

*Set the port to the port your app is running on

*Give your mates your public (external) ip address

Thats it. Your router will forward all traffic from the outsite to the set port on your local computer. No special software needed.
You can google for how to setup port-forwarding for every brand online. In most cases its self explanatory.

A: If your nodejs app ( http server or other ) behind the NAT like a home DSL link and there's no valid ip address assigned to your machine, You need to do Destination NAT/PAT which known as virtual server in most DSL modems. Also you can use online DNAT tools like no-ip or others too.


text:
Q: PowerShell list users in a group linked to folders on file share I have a Specific OU with groups that we use to control access to a few specific folder on a file share, lets says fileshare1, fileshare2 and fileshar3.
OU=example2,OU=example1,OU=Groups,DC=domain1,DC=domain2,DC=example,DC=uk

I need to get a list of users that are members of the groups that are being used on fileshare1... does anyone have a method of being able to do this? whether its to get powershell to loop through the security section of each folder to get the groups being used...
For each group I need to list, the folder name and who has access.
I'm looking on google, but kinda drawing up blanks...

A: You could try something like the following:
$ou = "OU=example2,OU=example1,OU=Groups,DC=domain1,DC=domain2,DC=example,DC=uk"
$groups = Get-ADGroup -Filter * -SearchBase $ou
$fileshare = "\\server\share\"
$folders = Get-ChildItem $fileshare -Directory
foreach($folder in $folders){
    $accessRights =  Get-Acl -Path $folder
    $groupsWithAccess = @()
    foreach($group in $accessRights.Access){
        $groupName = $group.identityReference.value.split("\")[-1]
        $getGroup = $groups | Where-Object {($_.samAccountName -eq $groupName -or $_.name -eq $groupName)}
        if($getGroup){
            $groupsWithAccess += $getGroup
        }
    }
    $memberObject = @()
    foreach($groupWithAccess in $groupsWithAccess){
        $members = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "user")}

        <# Uncomment if you wish to add one layer of nested groups
        $nestedGroups = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "group")}
        foreach($nestedGroup in $nestedGroups){
            $members = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "user")}
                $memberObject += New-Object psobject -Property @{
                fileshare = $accessRights.Path.Split("\")[-1]
                group = $groupWithAccess.name
                members = $members.name -join ";"
            }
        }
        #>

        $memberObject += New-Object psobject -Property @{
            fileshare = $accessRights.Path.Split("\")[-1]
            group = $groupWithAccess.name
            members = $members.name -join ";"
        }
    }
}
$memberObject | Export-CSV -Path "C:\Temp\test.csv" -Delimiter "," -NoTypeInformation

The above will loop through the folders, get the access rights for the folder, match the groups from the ou with access, queries the members, queries the members of nested groups (commented out), than creates an object and outputs it to a csv in C:\Temp\test.csv.
You could also use this for a single folder by removing the Get-Childitem and losing the foreach loop through the folders.
$ou = "OU=example2,OU=example1,OU=Groups,DC=domain1,DC=domain2,DC=example,DC=uk"
$groups = Get-ADGroup -Filter * -SearchBase $ou
$fileshare = "\\server\fileshare1"
$accessRights =  Get-Acl -Path $fileshare
$groupsWithAccess = @()
foreach($group in $accessRights.Access){
    $groupName = $group.identityReference.value.split("\")[-1]
    $getGroup = $groups | Where-Object {($_.samAccountName -eq $groupName -or $_.name -eq $groupName)}
    if($getGroup){
        $groupsWithAccess += $getGroup
    }
}
$memberObject = @()
foreach($groupWithAccess in $groupsWithAccess){
    $members = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "user")}

    <# Uncomment if you wish to add one layer of nested groups
    $nestedGroups = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "group")}
    foreach($nestedGroup in $nestedGroups){
        $members = Get-ADGroupMember -Identity $groupWithAccess.samAccountName | Where-Object {($_.objectClass -eq "user")}
            $memberObject += New-Object psobject -Property @{
            fileshare = $accessRights.Path.Split("\")[-1]
            group = $groupWithAccess.name
            members = $members.name -join ";"
        }
    }
    #>

    $memberObject += New-Object psobject -Property @{
        fileshare = $accessRights.Path.Split("\")[-1]
        group = $groupWithAccess.name
        members = $members.name -join ";"
    }
}
$memberObject | Export-CSV -Path "C:\Temp\test.csv" -Delimiter "," -NoTypeInformation

Please, since you have not showed any code you have tried yourself, make sure to read this code and try to fully understand what is happening. Then adjust it to your needs and finally try and test it out. Good luck!


text:
Q: Perl subroutine arguments like a hash How can I create a subroutine that can parse arguments like this:
&mySub(arg1 => 'value1', arg2 => 'value2' ...);

sub mySub() {
    # what do I need to do here to parse these arguments?
    # no arguments are required
}

A: Simply assign the input array to a hash:
sub my_sub {
    my %args = @_;
    # Work with the %args hash, e.g.
    print "arg1: ", $args{arg1};
}

If you want to provide default values, you can use:
sub my_sub {
    my %args = ( 'arg1' => 'default arg1',
                 'arg2' => 'default arg2',
                 @_ );
    # Work with the (possibly default) values in %args
}

A: Maybe you'll also find very useful the Method::Signatures module, which will allow you to do something like that:
func MySub (Str :$arg1 = 'default arg1', Str :$arg2 = 'default arg2') {
    print "arg1: ", $arg1};
}


text:
Q: Move each column value from the same group to new column SQL Big Query I have faced an issue when trying to transpose rows to columns.
My table looks like this:

And the result table should look like this:

I tried to solve this problem with PIVOT() but then I realized this is not the case.
Can anyone help me with that?
Edit 1: the number of names is not infinite (4 at most).
Edit 2: I've realized I've lost all the rows when there is NULL in name column.
I know I could do it with UNION, but is there more elegant solution to this problem?

Desired result would then be:

A: Consider below option
select * from (
  select *
  from your_table,
  unnest(split(name, ', ')) word with offset
)
pivot (min(word) as name for offset + 1 in (1, 2, 3))

if applied to sample data in your question
with your_table as (
  select 'x1' id, 'yellow' name union all
  select 'x2', 'orange' union all
  select 'x3', 'pink, blue' union all
  select 'x4', 'pink, blue, yellow'
)

output is

A: It depends on how many names you want to split into new columns. With the data that you, shared you can try this query below:
SELECT DISTINCT t1.id, t1.name,
split(t1.name, ', ')[SAFE_offset(0)] as name_1,
split(t1.name, ', ')[SAFE_offset(1)] as name_2,
split(t1.name, ', ')[SAFE_offset(2)] as name_3
from `dataset.table` as t1

This brings the below output:

I use SAFE_OFFSET because if you only use OFFSET the id 1,2,3 wouldn't allow it because they bring nulls.

A:
How can I keep the rows when there is NULL in name column? I appreciate you help!

Consider below
select * from (
  select *
  from your_table
  left join unnest(split(name, ', ')) word with offset
)
pivot (min(word) as name for offset + 1 in (1, 2, 3))

if applied to sample data in your question
with your_table as (
  select 'x1' id, 'yellow' name union all
  select 'x2', 'orange' union all
  select 'x3', 'pink, blue' union all
  select 'x4', 'pink, blue, yellow' union all
  select 'x5', null union all
  select 'x6', null
)

the output is


text:
Q: Installation issues github program: truecrack I am trying to install TrueCrack from github: https://github.com/lvaccaro/truecrack . As the description says I do this:
cd truecrackDirectory
./configure --enable-cpu
make

However, when I do the make, the command ends with this error:
[...]
Common/CpuCore.c:99:3: error: non-void function 'cpu_Core_charset' should return
  a value [-Wreturn-type]
            return;
            ^
[...]
44 warnings and 1 error generated.
make[2]: *** [CpuCore.o] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

Does anyone know what went wrong?

A: On line 68 cpu_Core_charset is declared to return an int (integer). It appears from line 106 the intended error value is 0. Modify line 99 by adding the return value 0:
    else{
        perror("Key derivation function not supported");
        return 0;
    }

The make will complete, albeit with more warnings.


text:
Q: Hibernate infinite loop recursion in many to many relation I want to create bidirectional student-discipline relation. Anything works fine until I've enrolled user to discipline. Now I'm getting infinite recursion.
Classes looks like this:
//Student.java
@Entity
@Table(name = "students")
public class Student {
    @NotNull
    @Id
    @Column(name = "STUDENT_ID")
    private String id;
    private String name;
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name = "students_disciplines", joinColumns = @JoinColumn(name = "STUDENT_ID"), inverseJoinColumns = @JoinColumn(name = "DISCIPLINE_ID"))
    @JsonSerialize(using = NestedDisciplineSetSerializer.class)
    private Set<Discipline> disciplines = new HashSet<>();
    //Getters, Setters
}
//NestedDisciplineSetSerializer.java
public class NestedDisciplineSetSerializer extends JsonSerializer<Set<Discipline>> {
    @Override
    public void serialize(Set<Discipline> value, JsonGenerator jgen, SerializerProvider p) throws IOException, JsonProcessingException {
        jgen.writeStartArray();
        for (Discipline s : value) {
            jgen.writeStartObject();
            jgen.writeStringField("name", s.getName());
            jgen.writeNumberField("id", s.getId());
            jgen.writeBooleanField("recommended", s.isRecommended());
            jgen.writeEndObject();
        }
        jgen.writeEndArray();
    }
}
//Discipline.java
@Entity`enter code here`
@Table(name = "disciplines")
public class Discipline {
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    @Column(name = "DISCIPLINE_ID")
    private int id;
    @NotNull
    private String name;
    @NotNull
    private int credits;
    private String annotation;
    private boolean recommended;
    @ManyToMany(mappedBy = "disciplines", fetch = FetchType.EAGER)
    @JsonSerialize(using = NestedStudentSetSerializer.class)
    private Set<Student> students = new HashSet<>();
    //Getters, Setters
}
//NestedStudentSetSerializer.java
public class NestedStudentSetSerializer extends JsonSerializer<Set<Student>> {
    @Override
    public void serialize(Set<Student> value, JsonGenerator jgen, SerializerProvider p) throws IOException, JsonProcessingException {
        jgen.writeStartArray();
        for (Student s : value) {
            jgen.writeStartObject();
            jgen.writeStringField("name", s.getName());
            jgen.writeStringField("id", s.getId());
            jgen.writeEndObject();
        }
        jgen.writeEndArray();
    }
}

Error appears to be while loading Set after Student s = sDao.findOne(id);
Tried to search here, but was not able to find right solution. Anything made the same result.
Error log

A:
org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:430)
  ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
      at truelecter.practproekt.entity.Discipline.hashCode(Discipline.java:31)
  ~[classes/:na]
      at java.util.HashMap.hash(HashMap.java:338) ~[na:1.8.0_91]
      at java.util.HashMap.put(HashMap.java:611) ~[na:1.8.0_91]
      at java.util.HashSet.add(HashSet.java:219) ~[na:1.8.0_91]
      at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
  ~[na:1.8.0_91]
      at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:327)
  ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
      at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:234)
  ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
      at ... org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:430)
  ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
      at truelecter.practproekt.entity.Student.hashCode(Student.java:29) ~[classes/:na]
      at java.util.HashMap.hash(HashMap.java:338) ~[na:1.8.0_91]
      at java.util.HashMap.put(HashMap.java:611) ~[na:1.8.0_91]
      at java.util.HashSet.add(HashSet.java:219) ~[na:1.8.0_91]
      at java.util.AbstractCollection.addAll(AbstractCollection.java:344) ~

I have the impression that the hashcode() method implementations for Discipline and Student entities use both entities.
Maybe am I wrong, it is not very clear in the stacktrace.
How have you defined equals() and  hashcode() methods for your entities ?
Suppose entity A and entity B with a bidirectional relationship.
If equals()/hashcode() implementation of entity A
invokes equals()/hashcode() on the entity B field that itself invokes equals()/hashcode() on the entity A field, you have a cycle.
Whereas your error.
Besides, even if you cut the cycle by ensuring that only one of both refers the other in equals()/hashcode()/toString(), you should invoke equals()/hashcode()/toString methods of the entity relationships with cautious.
It may have a real impact on the performance. If the Hibernate session is opened, it may indeed execute queries that you don't expect to.

A: Both of the sides have a Eager fetch type. Which means that for each Student you load, Hibernate will load every Discipline related, and for each Discipline, it will load its Students. This is your loop. You could change the fetch type of one side (better both), for FetchType.LAZY. Doing that, the discipline of a student will be load just when you access the list.


text:
Q: Can I get \addlegendimage to print a custom legend draw/line style? Problem
I've created a figure where I plot a line and add a node at the beginning of the line and a diamond at the end of the line by using nodes in my \addplot command like so:
\addplot[red,no markers,] {x} node[pos=0,circle,fill=red,inner sep=2pt,] {} node[pos=1,diamond,fill=red,inner sep=2pt,] {};

I was wondering if there's a way to include a line that looks like this in the legend as well.
I know I can use \addlegendimage to generate custom legend entries, and I know I can use \addlegendimage{red,->} to generate a custom legend entry that's a red arrow, but I don't know how to create a legend entry that's a line with a filled circle at the start and a filled diamond at the end. The following doesn't work, so this is where I got stuck:
\addlegendimage{\draw[red,] (0,0) node[circle,fill=red,inner sep=2pt,] {} -- (1,0) node[circle,fill=red,inner sep=2pt,] {};}

MWE
\documentclass[border=5pt]{standalone}

\usepackage{pgfplots}
\usepackage{tikz}

\usetikzlibrary{shapes}

\pgfplotsset{compat=1.10}

\begin{document}
  \begin{tikzpicture}
  \begin{axis}[%
    legend entries={A,B,C,D},
    legend pos=north west,
  ]

    \addlegendimage{only marks,mark=*}
    \addlegendimage{only marks,mark=diamond*}
    \addlegendimage{no markers,red}
    \addlegendimage{red,->}

    \addplot[red,no markers,] {x} node[pos=0,circle,fill=red,inner sep=2pt,] {} node[pos=1,diamond,fill=red,inner sep=2pt,] {};

  \end{axis}
  \end{tikzpicture}
\end{document}

Output

A: You can define a new legend image style:
\pgfplotsset{
  /pgfplots/line legend with two nodes/.style 2 args={
    legend image code/.code={
      \draw[##1,no markers]
        plot coordinates {
        (0cm,0cm)
        (0.3cm,0cm)
        (0.6cm,0cm)
      }
      node[pos=0,#1]{}
      node[#2]{};%
    }
  }
}

Code:
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}% loads also tikz
\usetikzlibrary{shapes}
\pgfplotsset{compat=1.10}% current version is 1.13

\pgfplotsset{
  /pgfplots/line legend with two nodes/.style 2 args={
    legend image code/.code={
      \draw[##1,no markers]
        plot coordinates {
        (0cm,0cm)
        (0.3cm,0cm)
        (0.6cm,0cm)
      }
      node[pos=0,#1]{}
      node[#2]{};%
    }
  }
}

\begin{document}
  \begin{tikzpicture}
  \begin{axis}[%
    legend entries={A,B,C,D},
    legend pos=north west,
  ]

    \addlegendimage{only marks,mark=*}
    \addlegendimage{only marks,mark=diamond*}
    \addlegendimage{no markers,red}
    \addlegendimage{
      line legend with two nodes={circle,fill,inner sep=1pt}{diamond,fill,inner sep=1pt},
      red}

    \addplot[red,no markers,] {x}
      node[pos=0,circle,fill=red,inner sep=2pt,] {}
      node[diamond,fill=red,inner sep=2pt,] {};

  \end{axis}
  \end{tikzpicture}
\end{document}


text:
Q: How to use itemCount in SliverGrid? Most probably I got the concept my SliverGrid entirely wrong,
What I am trying to do is, UI wise I want the collapsible SliverAppBar which is already available in Flutter. My main content body is set of images coming from API response and already parsed and loaded to a List variable.
Now here is my code:
body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(expandedHeight: 150.0, backgroundColor: Colors.green),
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3
              ),
              delegate: SliverChildBuilderDelegate((BuildContext context, int index){
                return Padding(
                  padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0),
                  child: InkWell(
                    child: Card(
                      elevation: 8.0,
                      child: FadeInImage.memoryNetwork(fit: BoxFit.cover,image: myimagelist[index].thumbnail, placeholder:kTransparentImage,fadeInCurve: Curves.bounceIn,),
                    ),
                  )
                );
              }),
            ),
          ],
        ),

I think this is probably because I can't tell the widget that how long is my data. For GridView.builder itemCount parameter is there, but SliverGrid doesn't have such an option. What do here?

A: SliverGrid widget doesn't have a property named itemCount. However, if you read the docs, you'll see that it's delegate property which takes a SliverChildBuilderDelegate has a property called childCount. You can use this property to set the number of childrens you want in your slivergrid.
delegate: SliverChildBuilderDelegate((BuildContext context, int index){
  return Padding(
    padding: EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0),
    child: InkWell(
      child: Card(
        elevation: 8.0,
        child: FadeInImage.memoryNetwork(fit: BoxFit.cover,image: myimagelist[index].thumbnail, placeholder:kTransparentImage,fadeInCurve: Curves.bounceIn,),
         ),
      )
    );
  },
  childCount: 3, // Your desired amount of children here
),


text:
Q: Does second countablity implies closed (or open) set in $X$ is a countable intersection of open sets in $X$? Is $X$ is second countable implies or equivalent to Every closed(or open) set in $X$ is a countable intersection of open sets in $X$?

I know, metric space implies this by Closed set as a countable intersection of open sets, and Every open set in $\mathbb{R}$ is a countable union of closed sets.  Also I know metric space is 1st countable but not 2nd countable.
If so How one can prove this statement?

A: The natural numbers $\ge 2$ endowed with the topology of the subsets that contain the divisors of each of their elements is second-countable, but not $G_\delta$.

A: The Double Arrow space ($[0,1] \times \{0,1\}$ in the order topology induced from the lexicographer order) is not second countable but is compact, connected and every closed subset is a countable intersection of open sets (it's perfectly normal). So it's not equivalent.


text:
Q: How to return an array of structs from a class in a getter function I have a relatively simple question but I cant seem to find an answer specific for my case and I just may not be approaching this problem the right way. I have a class that looks like this:
struct tileProperties
{
    int x;
    int y;
};

class LoadMap
{
  private:
    ALLEGRO_BITMAP *mapToLoad[10][10];
    tileProperties *individualMapTile[100];

  public:
    //Get the struct of tile properties
    tileProperties *getMapTiles();
};

I have an implementation that looks like this for the getter function:
tileProperties *LoadMap::getMapTiles()
{
    return individualMapTile[0];
}

I have code in the LoadMap class that will assign 100 tile properties for each struct in the array. I want to be able to access this array of structs in my main.cpp file but I just cant seem to find the right syntax or approach. My main.cpp looks like this.
 struct TestStruct
{
    int x;
    int y;
};

int main()
{
   LoadMap  _loadMap;
   TestStruct *_testStruct[100];
    //This assignment will not work, is there
    //a better way?
   _testStruct = _loadMap.getMapTiles();

   return 0;
}

I realize that there are many approaches to this, but I'm trying to keep this implementation as private as possible. If someone could please point me in the right direction I would greatly appreciate it. Thank you!

A: TestStruct *_testStruct;
_testStruct = _loadMap.getMapTiles();

This will get you a pointer to the first element in the array returned. You can then iterate through the other 99.
I would highly recommend using vectors, or another container, and writing getters that don't return pointers to bare arrays like that.

A: First of all, here, why do we need TestStruct, you can use "tileProperties" structure itself...
And imp thing,
tileProperties *individualMapTile[100]; is array of pointers to the structure.
Hence, individualMapTile will have pointers in it.
You have returned the first pointer, hence you can access the first structure only. What about the others????
tileProperties** LoadMap::getMapTiles()
{
  return individualMapTile;
}

int main()
{
   LoadMap _loadMap;
   tileProperties **_tileProperties;
  _tileProperties = _loadMap.getMapTiles();

    for (int i=0; i<100;i++)
{
    printf("\n%d", (**_tileProperties).x);
    _tileProperties;
}
   return 0;
}

A: Use vectors instead of arrays where possible. Also consider an array/vector of TestStruct directly rather than pointers to them. I can't tell if that would be appropriate for you from your code sample.
class LoadMap
{
public:
    typedef vector<tileProperties *> MapTileContainer;

    LoadMap()
        : individualMapTile(100) // size 100
    {
        // populate vector..
    }

    //Get the struct of tile properties
    const MapTileContainer& getMapTiles() const
    {
        return individualMapTile;
    }

    MapTileContainer& getMapTiles()
    {
        return individualMapTile;
    }

private:
    MapTileContainer individualMapTile;
};

int main()
{
    LoadMap _loadMap;
    LoadMap::MapTileContainer& _testStruct = _loadMap.getMapTiles();
}


text:
Q: How can I reduce bloat in my callback based serial communication? I'm communicating with a device that's connected to the computer via com port.
The device accepts certain predefined commands in order to interact with it.
I'm essentially creating a more abstract API on top of the one provided by the device.
I encapsulated the charactersistics of the Commands I use, so that I can just throw those objects at my Connection class, which handles the com port.
connection.Send(new FooCommand());

connection then

*

*shoves the ICommand into an internally used SerialPort object

*listens for SerialPort.DataReceived for the expected result

*sends the next ICommand (if there is one)

So far so good.

For some ICommand, the device returns meaningful values (and does not simply acknowledge the reception). Those can be handled in optional Action<> callbacks, that are passed to the constructor.
connection.Send(new BarCommand(response => Console.WriteLine(response)));

This works ok to just get a value, but becomes complicated for more complex communication that invoves multiple instructions being sent that depend on each other. To illustrate, let's assume the returned value of one command might be necessary to send another one.
The trivial solution is to put the second call into the response callback of the first one.
connection.Send(new BarCommand(response => connection.Send(new BazCommand(response)));

This quickly becomes messy. A more readable solution could be to store the response in a variable.
var baz = new BazCommand();
connection.Send(new BarCommand(response => baz.Parameter = response));
connection.Send(baz)

Now however, BazCommand has to be mutable, because it will be completed (with the necessary value for its parameter property) only after it is passed to the connection.Send() method. It also means that connection.Send() has to evaluate its parameter lazily.
Even in this simple example, the order of operations is a bit obscured already.
It gets worse if sending the BazCommand at all should be dependent on the response. Lambdas are not well suited for such branching code. A method can be used.
connection.Send(new BarCommand(responseHandler));

private void responseHandler(bool response) {
    if(response) connection.Send(baz)

This leads to dozens of methods like responseHandler that essentially handle the different state transitions of my object (not a bad thing in itself), which bloats the code and reduces readability.

I'm not too experienced with C# and need some guidance how to improve the communication code.
Is this a use case for async/await?
Would it allow me to write code like the following?
bool response = connection.Send(new BarCommand);
/* stop here until response is actually set to a value comming from the device */
connection.Send(new BazCommand(response))

or
bool response = connection.Send(new BarCommand);
/* stop here until response is actually set to a value comming from the device */
if (response) connection.Send(new BazCommand())

A:
I'm not too experienced with C# and need some guidance how to improve the communication code. Is this a use case for async/await? Would it allow me to write code like the following?

This is indeed a very applicable scenario for using async/await.
public static class CommandHelper
{
    public static async Task<T> SendAsync<T>(this SerialConnection connection, ICommand command)
    {
        var tcs = new TaskCompletionSource<T>();
        command.DataReceived += (sender, data) => tcs.SetResult((T)data);
        connection.Send(command);
        return await tcs.Task;
    }
}

With this you'll be able to 'await' every serial call and chain them together like so
var welcomeResponse = await connection.SendAsync<WelcomeResponse>(new WelcomeCommand());
var registrationReply = await connection.SendAsync<RegistrationReply>(new RegistrationCommand(welcomeResponse.Name));

You get the idea. Async/await really cleans up these scenarios where you'd otherwise wait for data using an event handler.


text:
Q: identifying key columns/features used by decision tree regression In Azure ML, I have a predictive regression model using boosted decision tree regression and it is reasonably accurate.
The input dataset has over 450 columns and the model has done a good job of predicting against test data sets, without over-fitting.
To report on the result i need to know what features/columns the model mainly used to make predictions but i cant find this information easily when looking at the trained model data.
How do i identify this information? Im happy to import the result dataset into R  to help find this but I just need pointers on what direction to start working in.

A: Mostly, in using Microsoft Azure Machine Learning, when looking at the features that is mainly used to make predictions, it is found on the output of the Train Model module.
But on using Decision Trees as your algorithm, the output of your Train Model module would be the constructed 'trees' of the algorithm, and it looks like this:

To know the features that made impact on predictions while using Decision Trees algorithms, you can use the Permutation Feature Importance module. Look at the sample experiment below:

The parameters of Permutation Feature Importance are Random Seed and Metric for Measuring Performance (in this case, Regression - Coefficient of Determination)
The left input of Permutation Feature Importance is your trained model, and the right input is your test data.
The output of Permutation Feature Importance looks like this:

You can add Execute R Script to extract the Features and Scores from Permutation Feature Importance module.


text:
Q: Three examples of possibly closed and bounded sets involving $\sin\big(\frac{1}{x}\big)$ Assume that we have the following sets of numbers in $\mathbb{R}$.
\begin{equation}
E_1 = \bigg\{ x \in \mathbb{R}:\sin^2\bigg(\frac{1}{x}\bigg) =0\bigg\}
\end{equation}
\begin{equation}
E_2 = \bigg\{ x \in \mathbb{R}:\sin^2\bigg(\frac{1}{x}\bigg) \geq 0.000001x^2\bigg\}
\end{equation}
\begin{equation}
E_3 = \bigg\{ x \in \mathbb{R}:\sin^2\bigg(\frac{1}{x}\bigg) =x^2\bigg\}
\end{equation}
The question is whether these sets are closed and bounded.
I think the first set is closed and bounded since it can be seen that $E_1=\bigg\{x:x=\frac{1}{k\pi}\Big| k \in \mathbb{Z} -\{0\}\bigg\}$. I think that $E_2$ and $E_3$ are bounded since for large values of $x$ $x^2$ is going to be larger that the value on the left hand side. However I can't see if these sets are closed. My intuition is that $E_3$ is closed by looking at the behavior of $\sin^2\big(\frac{1}{x}\big)$ around zero. However I cannot prove this rigorously. Any help/ tips? Thanks!

A: For $E_1$, as you noted we have $\sin(1/x) = 0$ if and only if $x = 1/(k\pi)$. Now we can see that $0$ is not in $E_1$, but $1/(k\pi) \to 0$. This means that $E_1$ is not closed. It is clear that $E_1$ is bounded.
For $E_2$ you can see that for large $x$ the inequality is false. Therefore you have $E_2$ bounded. The same question arises here: is it possible to attain $0$ as a limit point of a sequence in $E$? If this is true, then $E_2$ is not closed, since $0$ is not in $E_2$. Now, let's look at points where $\sin(1/x) = 1$. We need to have $1/x = \pi/2+2k\pi$ so $x_k = 1/(\pi/2+2k\pi)$. It is not difficult to see that $x_k \to 0$ as $k \to \infty$ and moreover, since $\sin(1/x_k) = 1$ we have $$\sin^2(1/x_k) = 1 \geq 0.000001 x_k^2$$
for $k$ large enough. Therefore $x_k \in E$(for large $k$) and $x_k \to 0$. Since $0$ is not a limit point of $E_2$ we conclude that $E_2$ is not closed.
For $E_3$ we see that $x^2$ needs to be between $0$ and $1$, therefore we have boundedness again. We must ask the same question. Can we have a sequence $x_k \in E$ with $x_k \to 0$? If yes, then there's a contradiction. If you imagine the graph of $\sin(1/x)$ you have something which oscillates a lot towards zero. It is not difficult to see that $y=\sin(1/x)$ intersects $y=x$ infinitely often and we can find $x_k \in E$ as close to zero as we want. Since $0$ is not in $E_3$ we conclude that $E_3$ is not closed.
To make this rigorous, you could study the function $\sin(1/x)-x$ around $0$.
In conclusion, you see that all problems occur when we are close to $0$, because $0$ is not in $E$. In fact we know that if $f$ is a continuous function then the sets $\{f(x) = 0\},\{f(x) = x\},\{f(x) = g(x)\}$ with $g$ continuous, are all closed. Since $\sin(1/x)$ is continuous everywhere but in $0$ it is natural to ask what happens in $0$.


text:
Q: Php + mysql insert data securely i'm worried about the security of my form. The idea is to make a form to participate in a contest in facebok. Basically just firstname, lastname, email. I've been searching through topics and there is a lot of info about security but i can't figure out what is enough security?
I know that there will always be a risk that someone finds a way to abuse the security, but i'd like to find a solution, which blocks the most of them. Also if there are obvious mistakes, please let me know.
Here is my code and all help and guidance is appreciated.
<?php
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$firstErr = $lastErr = $emailErr = "";
$first = $last = $email = "";

function test_input($data)
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (empty($_POST["first"])) {
    $firstErr = "Name is required";
    echo "
Firstname: $firstErr
";
  } else {
    $first = test_input($_POST["first"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$first)) {
      $firstErr = "Only letters and white space allowed";
    echo "
Firstname: $firstErr
";
    }
  }

  if (empty($_POST["last"])) {
    $lastErr = "Name is required";
    echo "
Lastname: $lastErr
";
  } else {
    $last = test_input($_POST["last"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$last)) {
      $lastErr = "Only letters and white space allowed";
        echo "
Lastname: $lastErr
";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
    echo "
Email: $emailErr
";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
      echo "
Email: $emailErr
";
    }
  }

    if ($firstErr == false && $lastErr == false && $emailErr == false) {
    $query = "INSERT INTO contactstable (first,last,email)  VALUES(:first,:last,:email)";
    $statement = $dbh->prepare($query);
    $statement->execute(array(
        ':first'=> $first,
        ':last'=> $last,
        ':email'=> $email
    ));
          echo "
Thank you for participating!
";
    }
    else {
        echo "Fix the missing or incorrect lines.";
    }

}

?>

A: You are using PDO, it already implements the security measures for 1st order injection and when the queries are parametrized the 2nd order also prevented(2nd order injection means data has been cycled through the database once before being included in a query).
But there is no harm if you implements validations for the inputs.


text:
Q: Is there any way to make this accesibile without breaking everything I'm trying to solve an accessibility issue without making any breaking changes to an application.
In order to comply, the nav, header and main must be on the same level. Problem is, the nav and a wrapper for the header and main are rows in a flexbox (and have large amounts of custom css), and the header and main are columns in said wrapper.

Is there any simple way to bring everything on the same level without changing the layout? Everything I could think of requires pretty significant changes to the code.

A: You can use grid plus flex and do something like this.

* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}

aside, div, header, main {
  position: relative;
}

.wrapper {
  width: 100%;
  height: 100vh;
  display: grid;
  grid-template-columns: 1fr 3fr;
}

.wrapper aside {
  width: 100%;
  height: 100%;
}

.wrapper aside.left {
  background-color: red;
}

.wrapper aside.right {
  display: flex;
  flex-direction: column;
}

.wrapper aside header {
  width: 100%;
  height: 150px;
  background-color: blue;
}

.wrapper aside main {
  width: 100%;
  height: 100%;
  background-color: green;
}


text:
Q: session management with Flex+Java Servlet using Httpservice I am new to Flex. I am just wondering how to manage session and cookies for logging in, logging off in Flex?
I am using Flex HttpService and Java servlet.
Thanks!

A: When you're using Flex, you have the power of RIA that lets you apply the "Statelessness" REST is fighting for.  Just go stateless, and send the credentials on each request. Keep your session on the client side.


text:
Q: Text File in UTF-8 Encoding format fails to convert into XML Would like to seek advise on how to manage the text file(with fixed length data positioning) which has Encoding UTF-8 format to convert into XML file.
Basically the program fails to convert the Text File to XML because of non-ascii/symbol characters found in some data elements when the encoding was manually changed to ANSI. In effect, those characters impacting the fixed length position of the elements which resulted to the failure of XML file conversion. The source of data is coming from a free text field in SAP application and it was being extracted by the middleware application and sent as EDI file.
See below screenshots for reference.


text:
Q: Listview Scroll End Event I want Listview Scroll End Event that when I have a content then I'll click on that content to load more, then when content will display then bottom should be scrolled.
private void ScrollViewEvent_Scrolled(object sender, ScrolledEventArgs e)
        {
            if (e.ScrollY + ScrollViewEvent.Height >= ScrollViewEvent.ContentSize.Height)
                AtEnd = true;
            else
                AtEnd = false;
        }

        public bool AtEnd
        {
            get
            {
                return m_atEnd;
            }

            set
            {
                if(m_atEnd != value)
                {
                    m_atEnd = value;
                    OnPropertyChanged("AtEnd");

                }
            }
        }

 <ScrollView x:Name="ScrollViewEvent"
                        Scrolled="ScrollViewEvent_Scrolled"
                        VerticalScrollBarVisibility="Never">
</ScrollView>

On content load the bottom part should be scrolled automatically. I don't have to scroll it.

A: For this you will have to write Custom Renderer. I had implemented the same in one of my Apps.
For iOS you need to implement DecelerationEnded Event of UITableViewDelegate.
I am not sure for Android.

A: You can use ListView.ScrollTo Method to scroll to the last item for ListView.

                    <Label Grid.Column="0" Text="Id" />
                    <Label Grid.Column="1" Text="First Name" />
                    <Label Grid.Column="2" Text="Surname" />
                    <Label Grid.Column="3" Text="Date Of Birth" />
                </Grid>
            </ListView.Header>

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Label Grid.Column="0" Text="{Binding Id}" />
                            <Label Grid.Column="1" Text="{Binding FirstName}" />
                            <Label Grid.Column="2" Text="{Binding Surname}" />
                            <Label Grid.Column="3" Text="{Binding Age}" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Button
            x:Name="btn"
            Clicked="Btn_Clicked"
            Text=" Load more items" />
    </StackLayout>

public partial class Page6 : ContentPage
{

    public PersonViewModel p { get; set; }
    public Page6 ()
    {
        InitializeComponent ();
        p = new PersonViewModel();
        this.BindingContext = p;

    }

    private void Btn_Clicked(object sender, EventArgs e)
    {
        personmodel model = p.peoples.Last();
        Device.BeginInvokeOnMainThread(() =>
      listView.ScrollTo(model, ScrollToPosition.End, true));
    }
}

public class PersonViewModel
{
    public ObservableCollection<personmodel> peoples { get; set; }

    public PersonViewModel()
    {
        peoples = new ObservableCollection<personmodel>();
      for(int i=0;i<50;i++)
        {
            peoples.Add(new personmodel() { Id="the "+ i +" item",FirstName="cherry",Surname="Bu",Age=28});
        }

    }
}


text:
Q: adding dynamics tabs jquery I am using a Jquery tabs component like this:

 $("#tabs" ).tabs({
      collapsible: true
    });

And the title of each tab is loaded from DB (php) like this
var mytabs = [<?php  foreach($zersart as $za): ?>{
                     name: "<?php echo $za->art; ?>"},
                 <?php  endforeach; ?>];

    $.each(mytabs, function(indexInArray, myobj) {
          $('#tabs').find('li> a').eq(indexInArray).text(myobj.name);
    });

But this method is fix to have a specific number of tabs. I want that the tabs are created according with the number of elements in the array with the title for each tab, I mean, create dynamics tabs. I tried this:
$.each(mytabs, function(indexInArray, myobj) {
    $('#tabs').append('
'+myobj.name+'
');
 });

And this code was removing the
 components from the
 in the html. But is not working. How is possible to do this?

A: The output of your 'mytabs' array has to be formatted like this:
var mytabs = ['Marc','John','Paul']

So get rid of this '{' and '}'
Loop then trough the items and add the tabs:
$.each(mytabs, function(indexInArray, myobj) {
        console.log(myobj)
        $('#tab').append('
'+myobj+'
');
    });

If you need a working example I will make a fiddle for you, but I think you have got the point now. Merry Christmas.
If you find this answer useful please consider to up vote it. This makes easy for other users to find it. Thank you.
As important note: I just want let you know that you need also to add the tab contents along with the tabs.


text:
Q: Can't get data from fetch I'm trying to make a fetch call and it works but when I try to get the result from another function I always get undefined.
This is my code:
const fetch_output = async (data) => {
await fetch("execute_command", {
    method: "POST",
    credentials: "same-origin",
    headers: {
        "X-CSRFToken": getCookie("csrftoken"),
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
}).then(function(response) {
    return response.json()
}).then(function(response) {
    console.log(response)
    //I get the correct response here
    return response
}).catch(function(ex) {
    console.log("Ha habido algún error: ", ex)
})
}

const write_outputs = async () => {
for (const platform_id of platforms_ids) {

    const data = {
        platform_id:platform_id,
        command:command
    }

    await fetch_output(data).then((resp)=>{
        console.log(resp)
        //I get undefined
    })
}
}

write_outputs()

I've tried everything but I just don't know what am i doing wrong.

A: it is because an async function returns a promise that resolves to the returned value from the function
(async () => {})().then(value => console.log("value = ", value)); // undefined
(async () => {return 1})().then(value => console.log("value =" , value)); // 1

as you are not returning anything from fetch_output, it resolves to undefined
You should return from the fetch_output function instead of using await.
Also, because fetch is already a promise you can use a normal function instead of an async one

A: Because you call await fetch_output() you should not use .then() to retrieve its result. Drop the await.
Why? await replaces  function().then().catch() with result = await function() in the way it handles a Promise or an async function. Use await or .then() but not both.


text:
Q: Getting java.lang.UnsupportedOperationException in List I am getting

java.lang.UnsupportedOperationException

exception in List.
Why does this exception occur?
Code
List<String> smsUserList = new ArrayList<String>();
    if (event.getEventTemplate().equalsIgnoreCase(CommunicationConstants.MEMBER)) {
        String testNumbers = env.getRequiredProperty(CommunicationConstants.TEST_SMS_NUMBRES);
        String[] testSmsNumber = testNumbers.split(",");
        if (null != testSmsNumber && testSmsNumber.length > 1) {
            smsUserList = Arrays.asList(testSmsNumber);

        }

    }
    if (event.getEventTemplate().equalsIgnoreCase(CommunicationConstants.AGENT)) {
        String testNumbers = env.getRequiredProperty(CommunicationConstants.TEST_SMS_NUMBRES);
        String[] testSmsNumber = testNumbers.split(",");
        if (null != testSmsNumber && testSmsNumber.length > 1) {
            smsUserList = Arrays.asList(testSmsNumber);
        }
    }

    Set<SMSCommunicationRecipient> smsRecipientAll = event.getSmsCommunicationRecipient();
    for (SMSCommunicationRecipient smsRecipient : smsRecipientAll) {
        String smsRecipientValue = smsRecipient.getRecipientGroupId().getReferenceTypeValue();
        if (smsRecipientValue.equalsIgnoreCase(CommunicationConstants.MEMBER)) {
            List<String> memberContact = (List<String>) communicationInput
                    .get(CommunicationConstants.MEMBER_CONTACT_NUMBER_LIST);
            if (CollectionUtils.isNotEmpty(memberContact)) {
                for (String smsNumber : memberContact) {
                    smsUserList.add(smsNumber);
                }
            }
        }
        if (smsRecipientValue.equalsIgnoreCase(CommunicationConstants.AGENT)) {
            List<String> agentContact = (List<String>) communicationInput
                    .get(CommunicationConstants.AGENT_CONTACT_NUMBER_LIST);
            if (CollectionUtils.isNotEmpty(agentContact)) {
                for (String smsNumber : agentContact) {
                    smsUserList.add(smsNumber);
                }
            }
        }
    }

A: Arrays.asList(testSmsNumber) returns a fixed sized list, so you cannot add elements to it.
Change
smsUserList = Arrays.asList(testSmsNumber);

to
smsUserList = new ArrayList<>(Arrays.asList(testSmsNumber));

Or, since you are already creating an ArrayList with:
List<String> smsUserList = new ArrayList<String>();

change
smsUserList = Arrays.asList(testSmsNumber);

to
smsUserList.addAll(Arrays.asList(testSmsNumber));

Though if you take this second approach, depending on your logic, you might want to call smsUserList.clear() before smsUserList.addAll() (since there are multiple places in your code that assign to the smsUserList variable, so perhaps you want the List to be cleared each time you make that assignment).


text:
Q: Google Sheets: Obtain hyperlink from =ImportXML while importing title I'm trying to have the title of the website, along with having it hyperlinked to said website in the same cell.
I've tried doing:
ImportXML("https://wwww.example.com/","//title/text()","//a/@href()")

A: Try the following formula:
    =hyperlink("https://www.example.com/",ImportXML("https://www.example.com/","//title/text()"))


text:
Q: How To Fix syntax error unexpected token < , On jQuery.ajaxFileUpload This is my Jquery code
function kirimgambar(chatboxtitle) {

    var file = jQuery( ".pilih" ).val();
    if(file==""){
    jQuery("#chatboxtextarea").focus();
    }else {
    jQuery("#loading")
    .ajaxStart(function(){
        jQuery(this).show();
    })
    .ajaxComplete(function(){
        jQuery(this).hide();
    });

    jQuery.ajaxFileUpload
    (
        {
            url:'http://localhost:8080/diobatin/application/views/chat/chat.php?action=kirimfile',
            secureuri:false,
            fileElementId:'fileToUpload',
            dataType: 'json',
            data:{name:'logan', id:'id', chatboxtitle:chatboxtitle},
            success: function (data, status)
            {
                if(typeof(data.error) != 'undefined')
                {
                    if(data.error != '')
                    {
                        alert(data.error);
                    }else
                    {
                        alert(data.msg);
                    }
                }
            },
            error: function (data, status, e)
            {
                alert(e); //This ouput is "syntax error unexpected token <"
            }
        }
    )
    chatHeartbeatTime = minChatHeartbeat;
    chatHeartbeatCount = 1;
    return false;
    }

}
And in chat.php is
    function kirimfile() {
    $error = "";
    $msg = "";
    $fileElementName = 'fileToUpload';
    if(!empty($_FILES[$fileElementName]['error']))
    {
        $error = 'No file was uploaded..';
    }elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
    {
        $error = 'No file was uploaded..';
    }else
    {
            $upload_path = "./asset/";
            if (!is_dir($upload_path)) {
                mkdir($upload_path);
            }

             $file = $_FILES['fileToUpload']['name'];
             $tmp  = $_FILES['fileToUpload']['tmp_name'];
                // jika $file ada dan tidak kosong
                if ((isset($file)) && ($file != "")) {
                    // handle apabila sudah ada file sama yang terupload, maka akan dibuat copynya
                    $uploadfile = (file_exists($upload_path.$file)) ? $upload_path." copy of ".$file : $upload_path.$file;
                    move_uploaded_file($tmp, $uploadfile);
                    if (chmod($uploadfile, 0775)) {
                        $from = $_SESSION['username'];
                        $to = $_POST['chatboxtitle'];
                        $message =  $_SESSION['username'];
                        $messagesan = sanitize($message);

    if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
        $_SESSION['chatHistory'][$_POST['to']] = '';
    }

    $_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
                       {
            "s": "1",
            "f": "{$to}",
            "m": "{$messagesan}"
       },
EOD;
    unset($_SESSION['tsChatBoxes'][$_POST['to']]);

                        }
            }
    }
    echo '<meta http-equiv="Content-type" content="text/html; charset=UTF-8">';
    echo "{\n";
    echo                "error: '" . $error . "',\n";
    echo                "msg: '" . $msg . "'\n";
    echo "}";
}

This output return on alern is syntax error unexpected token < in chrome
But in mozilla firefox Erro reporting is The character encoding of a framed document was not declared. The document may appear different if viewed without the document framing it.

A: <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> and \n is not JSON.
Replace
echo '<meta http-equiv="Content-type" content="text/html; charset=UTF-8">';
echo "{\n";
echo                "error: '" . $error . "',\n";
echo                "msg: '" . $msg . "'\n";
echo "}";

With
$arr = array(
            'error' => $error,
            'msg'   => $msg
        );

echo json_encode($arr);


text:
Q: php class variables I have a class named MyCart.
Class MyCartClass
{
var $MyCart;

function getCart(){
  return $this->MyCart;
}

function addItem($item){

    if ($this->MyCart){
        $this->MyCart .= ','.$item;
    }
    else{
        $this->MyCart = $item;
    }

}

};

$globalCart = new MyCartClass; // create an instance of the class

The variable "$MyCart" is a string containing all the items in the cart, separated with a comma.
Now, I save this class to a file named "cart.php" and I include it in another file.
HOWEVER, every time I call the function "addItem", the if statement goes to the else branch, which means that the "$MyCart" variable does not contain the current state of the cart.
Do i need to store the state of my cart into a "session" variable?
Cause this way it will be accessible from all files for sure..
I would appreciate any kind of help!
Thanks.

A: Don't use a string to store a list.  It's just a bad idea all around.
Instead, store $items as an array, and define it in the constructor
class Cart {

    function __construct() {
        $this->items = array();
    }

    function add($item) {
        $this->items[] = $item;
    }

    function save() {
        $SESSION["cart"] = $this->items;
    }

    function get_items_string() {
        return join(",", $this->items);
    }

}

My PHP is a little rusty, but that should get you started.

A: If you mean saving it between request then yes you need to put it in $_SESSION.
Otherwise within one request you can use your $globalCart and not lose the contents of your $myCart var.

A: To simplify this just store the data in an array and use serialize and deserialize to store the data:
Class MyCartClass {
    var $MyCart = array();

    public function __construct(){
        $this->MyCart = deserialize($_SESSION['CART']);
    }

    public function __destruct(){
        $_SESSION['CART'] = serialize($this->MyCart);
    }

    function getCart(){
        return $this->MyCart;
    }

    function addItem($item){
        $this->MyCart[] = $item;
    }
}

Please note I just wrote this quickly and didn't run it as I don't have access to run it right now.  :-)

A: your can even serialise all class to $_SESSION[] ... but generally good idea is to store in session some id - as example user id & store all all other data in mysql. Getting it each time, is needed ...


text:
Q: Make the Touch Bar less fancy I got a mbp with Touch Bar and now I'm sure I don't like it. What can I do to make it look and behave less like a Touch Bar? Is it possible to make it hold just two sets of buttons, the function keys and the volume keys (and other keys we use to have when pressing fn)?
Here it looks like every time I switch apps the Touch Bar will show something different. I just want volume up/down and screen brightness up/down there all the time at one click distance. Is this still possible?
To access volume I have to 1st press the volume slider to get access to up/down buttons. I would like to volume up/down in just one click.

A: In System Preferences > Keyboard, set "Touch Bar shows" to "Expanded Control Strip"

A: To access the volume or brightness in just 1 tap, just press on the desired icon and start sliding your finger left or right without raising your finger.
I run my computer with the brightness slider, volume slider, mute, and quick actions. I see them in all of the apps that I'm in at all times. You'll find those default settings in System Preferences -> Keyboard -> Customize Touch Bar..


text:
Q: Preference not changing immediately in Android In the MainActivity.class,
I am changing the value of a preference like so:
    mPrefs = StripedMain.this
                    .getSharedPreferences(SHARED_PREFS_NAME, 0);
            mPrefs.registerOnSharedPreferenceChangeListener(this);
            onSharedPreferenceChanged(mPrefs, null);

public void onSharedPreferenceChanged(SharedPreferences prefs,
                String key) {

                preVal = prefs.getString(key, "st");
if (preVal.equals("a")){
      prefs.edit().putString("name", "Rob").commit();
}

}
This works but the value on the screen itself does not change immediately but only after the settings screen has been closed and opened again.
So why is that and how do I fix it?

A: Hope you have defined an xml for your preferences. Assuming you are having an edittext pref, you should have something like this in pref xml:
<EditTextPreference
         android:summary="@string/summary"
         android:title="@string/textinput"
         android:key="input"
         android:defaultValue= "@string/initialvalue" />

You need to define a default value, if you want to read this value and accordingly do some initialisation when your app starts and even before the user has not done any setting change. This default value will be used until the user stores a new value in this preference.
Your MainActivity should implement OnSharedPreferenceChangeListener
Use the below logic for reading and editing your sharedpref values
SharedPreferences mPrefs = getSharedPreferences(SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, input); // this will initialise with existing pref value

public void onSharedPreferenceChanged(SharedPreferences prefs,
                String key) {

if (key.equals("input")) { // doing a check for key if you want to add more prefs in future
     preVal = prefs.getString(key, "st");
     if (preVal.equals("a")){
      prefs.edit().putString("name", "Rob").commit();
}


text:
Q: urllib2 won't authenticate, curl works fine When I use curl, this works:
curl -v https://example.org:8080/platform/3/zones --insecure --basic -u 'user:password'
* About to connect() to example.org port 8080 (#0)
*   Trying example.org... connected
* Connected to example.org (example.org) port 8080 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* warning: ignoring value of ssl.verifyhost
* skipping SSL peer certificate verification
* SSL connection using TLS_DHE_RSA_WITH_AES_256_CBC_SHA
* Server certificate:
*       subject: E=support@isilon.com,CN=Isilon Systems,OU=Isilon Systems,O="Isilon Systems, Inc.",L=Seattle,ST=Washington,C=US
*       start date: May 15 07:48:59 2014 GMT
*       expire date: May 14 07:48:59 2017 GMT
*       common name: Isilon Systems
*       issuer: E=support@isilon.com,CN=Isilon Systems,OU=Isilon Systems,O="Isilon Systems, Inc.",L=Seattle,ST=Washington,C=US
* Server auth using Basic with user 'root'
> GET /platform/3/zones HTTP/1.1
> Authorization: Basic xxxxxxxxxxxxxxxxxxxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: example.org:8080
> Accept: */*
>
< HTTP/1.1 200 Ok
< Date: Mon, 08 Jan 2018 23:44:18 GMT
< Server: Apache/2.2.31 (FreeBSD) mod_ssl/2.2.31 OpenSSL/1.0.2j-fips mod_fastcgi/2.4.6
< Allow: GET, POST, HEAD
< Transfer-Encoding: chunked
< Content-Type: application/json
<
[data omitted]

So, I'm trying this Python code:
#!/usr/bin/python
import urllib2
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None, 'https://example.org:8080/', 'user', 'password')
opener = urllib2.build_opener(
    auth_handler,
    )
urllib2.install_opener(opener)
r = urllib2.Request('https://example.org:8080/platform/3/zones')
try:
    f = urllib2.urlopen(r)
except urllib2.HTTPError as err:
    print '***', err.code, err.msg
    print err.headers
    print err.read()

and I get this back:
*** 401 Authorization Required
Date: Mon, 08 Jan 2018 23:32:19 GMT
Server: Apache/2.2.31 (FreeBSD) mod_ssl/2.2.31 OpenSSL/1.0.2j-fips mod_fastcgi/2.4.6
WWW-Authenticate: Basic
Last-Modified: Fri, 12 May 2017 09:14:48 GMT
ETag: "2841d-31-54f5023135200"
Accept-Ranges: bytes
Content-Length: 49
Connection: close
Content-Type: application/json

{"errors":[{"message":"authorization required"}]}

It might be that the '--insecure' flag on the curl command is doing something, or perhaps I made a mistake setting up my auth_handler.  If you spot something, let me know.  I'm unfortunately behind a firewall that won't let me get to http://httpbin.org/ so I'll need to move my code elsewhere to test it there.


text:
Q: Thermodynamic 'Work Flow'; Based on relative or absolute pressure? The thermodynamic work flow (energy) is defined as
$$W = \int PdV = \int PQdt$$
The units of $P$ are the same whether $P$ is considered relative (gauge) or absolute pressure. But then what should $P$ be, relative or absolute? Or can it be either, and does that just mean the basis (reference) of work is from vacuum to some finite pressure vs the difference between two non-zero pressures?


text:
Q: Implementing class concept is not working in python Program 1 : function based :-
import xml.etree.ElementTree as ET
import sys
doc       = ET.parse("users.xml")
root      = doc.getroot()
root_new  = ET.Element("users")
for child in root:
    username             = child.attrib['username']
    password             = child.attrib['password']
    # create "user" here
    user    = ET.SubElement(root_new, "user")
    user.set("username",username)
    user.set("password",password)
    #checking attribute for skipping KeyError
    if 'remote_access' in child.attrib:
        remote_access   = child.attrib['remote_access']
        user.set("remote_access",remote_access)
    for g in child.findall("group"):
        # create "group" here
        group     = ET.SubElement(user,"group")
        if g.text != "lion":
            group.text = g.text
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)

This is xml :-
<users>
<user username="admin"  password="admin" remote_access="yes"></user>
<user username="private_user1" password="user1" ><group>group1</group><group>group2</group></user>
<user username="private_user2" fullname="user2" password="user2"><group>group1</group><group>group2</group></user>
</users>

my class implementaion :- fully wrong :(
import xml.etree.ElementTree as ET
import sys

class users_detail (object):

    def __init__( self, xml_path ):
     """bla bla
     """
    try:
        doc = ET.parse("users.xml")
    except:
        print 'xml not found'
        root      = doc.getroot()
        root_new  = ET.Element("users")
        for child in root:
            username             = child.attrib['username']
            password             = child.attrib['password']
            user    = ET.SubElement(root_new, "user")
            user.set("username",username)
            user.set("password",password)
            if 'remote_access' in child.attrib:
                remote_access   = child.attrib['remote_access']
            for g in child.findall("group"):
                group     = ET.SubElement(user,"group")
                if g.text != "lion":
                    group.text = g.text
        tree = ET.ElementTree(root_new)
        tree.write(sys.stdout)
if __name__=='main':
    users_detail()

How to implement this in better way via object oriented concept class. And my class implementaion is not working at all. please help me out. :(
i need to make the above code into a Python Class : thats the requirment :(

A: You have an indentation problem (everything after the print statement is indented one level too far).
And tell your teacher from me that rewriting random code into a "class" is a nonsense requirement. There's no need for a class in Python for code like this.


text:
Q: get_class() expects parameter 1 to be object, string given Laravel Estoy utilizando el paquete yajra/laravel-datatables
Intento utilizar Datatables en laravel para mejorar el tiempo de respuesta, sin embargo
cuando intento enviar la solicitud a la vista me retorna el error get_class() expects parameter 1 to be object, string given
Si hago un DD a la consulta me retorna un archivo JSON o ARRAY(Tanto con los 2 me da el error), lo anexo
//Este es el codigo de mi consulta
        $datas= Referred::where('user_id','=', $referred)->select('slug_id','created_at')->get()->toJson();

cuando hago un DD retorna lo siguiente:
"[{"slug_id":44,"created_at":"2020-11-08 19:52:36"},{"slug_id":74,"created_at":"2020-11-08 19:53:43"}]"

Y eso esta bien, porque me trae los datos de los campos slug_id y created_at para mostrar con DataTables. pero claro, en el
datable de manera ordenada para poder anexarle mas botones, pero eso es otra historia.
sin embargo cuando mando la solicitud asi:
return Datatables::of($datas)->make(true);

Me retorno el error get_class() expects parameter 1 to be object, string given Laravel
Si emito la data sin pasar por JSON, es decir un array, me retorna lo siguiente en la vista:
{"draw":0,"recordsTotal":2,"recordsFiltered":2,"data":[{"slug_id":44,"created_at":"2020-11-08 19:52:36"},{"slug_id":74,"created_at":"2020-11-08 19:53:43"}],"input":[]}

Y sigue estando bien, porque es la data que necesito(slug_id y created_at), pero no logro agregarla al dataTable, asi lo intento hacer funcionar en la vista:

   @extends('layouts.app')

@section('content')

Cliente

                            ID
                            Fecha

    @push('scripts')

@endsection

Doy por hecho que los modelos y las rutas no tienen problemas, porque me redirigen bien. si las necesitan me indican y edito
Sin utilizar dataTables logro enviar la información a la vista y arreglarla con un foreac, pero
quiero utilizar esa tecnologia para dar maor velocidad.
Agradecido por su ayuda.
Saludos

A: Aquien le toque un problema similar, ese error de get_class() expects parameter 1 to be object, string given puede suceder porque tu consulta viene sin datos o mal estruturada(En mi caso ya estaba recibiendo la infomacion y el paquete que utilizo se encarga de lo demas).
Por lo tanto asegúrate con un DD o cualquier log que este recibiendo datos para rellenar el datatable.
Ahora, el error de solo recibir un JSON en la vista. Si quiere utilizar AJAX tienes que tener una ruta declarada para que AJAX consuma los recursos y los muestre en tu vista, así que, declare 1 ruta para el AJAX y el otro para mi vista.
//Vista de Referidos admin
Route::get('ref/list', 'ReferredController@usersList')->name('ref/list');//consulta AJAX
Route::get('referreds', 'ReferredController@index')->name('referreds.index');

Despues en mi controlador solo rellene:
 public function index()
{
   return view('referreds.index');

}

/**
 * Devuelve el listado en JSON de los usuarios
 *
*/
public function usersList(User $user, Request $request)
{

    $data = User::get(['id','email','name','id_slug']);
    return Datatables::of($data)
    ->make(true);
    //dd($referreds);
}

Y al final solo me asegure de tener la cantidad de celdas solicitadas en la respuesta AJAX

Saludos


text:
Q: How to select rows in MySQL between initial trimester/year and final trimester/year? The table have this structure:
code | item | trimester | year
1       rrr      1         2014
2       fff      3         2014
3       ggg      3         2014
4       hhh      4         2015
5       ttt      2         2016
6       fff      3         2016

Now I want to select all items between trimester 3 of 2014 and trimester 1 of 2016, How can you do it?
The result of that query with this example table maybe:
2       fff      3         2014
3       ggg      3         2014
4       hhh      4         2015

A: One method:
where year * 10 + trimester between 20143 and 20161

Alternatively, you could be explicit:
where (year > 2014 or (year = 2014 and trimester >= 3)) and
      (year < 2016 or (year = 2016 and trimester = 1))


text:
Q: Calculus of variations with inequality and non-integral constraints I have a question on solving an optimization problem with calculus of variations.
I am attempting to maximize the functional
$$ J[y] = \displaystyle\int_a^b F(x,y,y') \, \mathrm{d}x,   \tag{1}$$
but my constraint is not in integral form; it is an inequality
$$ 0 \leq g(x,y,y') \leq 1, \tag{2}$$
Is it possible to solve this with calculus of variations?
I have rewritten the constraint to the form of $ g(x,y,y')-g(x,y,y')^2 \geq 0 $ and I think I should use Lagrange multiplier in form of $\lambda(x)$ and $\lambda(x) \geq 0  $  as follows:
$$ L(y)=\int_a^b F(x,y,y')+\lambda(x)(g(x,y,y')-g(x,y,y')^2) \, \mathrm{d}x $$
In this way my problem got very complicated and non-solvable, can anybody guide me to the correct or better solution. Thanks in advance and any suggestion will be appreciated.

A: We can introduce slack functions $s_1, s_2$ such that the inequality constraints $g (x, y, y') \geq 0$ and $g (x, y, y') \leq 1$ can be replaced by the following equality constraints
$$g (x, y, y') - s_1^2 (x, y, y') = 0, \qquad \qquad g (x, y, y') + s_2^2 (x, y, y') = 1$$
The Lagrangian then becomes
$$F (x, y, y') + \lambda_1 (x) \left( g (x, y, y') - s_1^2 (x, y, y')\right) + \lambda_2 (x) \left( g (x, y, y') + s_2^2 (x, y, y') - 1\right)$$
I do not know what the corresponding Euler-Lagrange equations would be, though.


text:
Q: Collection->put() not working in Laravel 5.2 I'm working with Laravel for the first time. I have a scenario where I have a Products table which contains basic details of a Product (Corrugated Box) like length, breadth, height etc. Some other details of the product is computed using the basic details within a function.
My code in the Controller looks like this:
Controller:
$products = DB::table('master_products')
            ->join('part_types', 'master_products.part_type_id', '=', 'part_types.id')
            ->join('box_types', 'master_products.box_type_id', '=', 'box_types.id')
            ->select('master_products.*', 'part_types.part_type', 'box_types.box_type')
            ->get();

    /* Calculate Specs and add them to the collection */
    foreach ($products as $product) {
        $rollSize = $this->calcRollSize($product->height, $product->breadth, $product->ply, $product->part_type_id, $product->box_type_id);
        $products->put('roll_size', $rollSize);
    }

return view('/layouts/masters/products-master', ['products' => $products]);

View:

                    Sl.No.
                    Product Code
                    Part Type
                    Box Type
                    Length
                    Breadth
                    Height
                    Ply
                    Roll Size
                    A-Base
                    A-Flute
                    B-Base
                    B-Flute
                    Top

                @foreach($prod_specs as $prod_spec)

                    <?php echo $i; ?>
                    <?php echo $prod_spec->product_code; ?>
                    <?php echo $prod_spec->part_type; ?>
                    <?php echo $prod_spec->box_type; ?>
                    <?php echo $prod_spec->length; ?>
                    <?php echo $prod_spec->breadth; ?>
                    <?php echo $prod_spec->height; ?>
                    <?php echo $prod_spec->ply; ?>
                    <?php echo $prod_spec->roll_size; ?>
                    <?php echo $prod_spec->gsm_a_base; ?>
                    <?php echo $prod_spec->gsm_a_flute; ?>
                    <?php echo $prod_spec->gsm_b_base; ?>
                    <?php echo $prod_spec->gsm_b_flute; ?>
                    <?php echo $prod_spec->gsm_top; ?>

                <?php $i++; ?>
                @endforeach

I got this exception: Call to a member function put() on a non-object
But according to this stackoverflow question's accepted answer it's supposed to work. What am I missing here ?
Update:
Tried this
foreach ($products as $product) {
    $rollSize = $this->calcRollSize($product->height, $product->breadth, $product->ply, $product->part_type_id, $product->box_type_id);
    $product['roll_size'] = $rollSize;
}

Got an error Cannot use object of type stdClass as array

A: You're getting an array from Query Builder. Laravel collect() helper is your solution:
$products = collect(DB::table('master_products')
            ->join('part_types', 'master_products.part_type_id', '=', 'part_types.id')
            ->join('box_types', 'master_products.box_type_id', '=', 'box_types.id')
            ->select('master_products.*', 'part_types.part_type', 'box_types.box_type')
            ->get());

More info

A: The Query Builder does not return a collection when calling get, it returns an array:

Like raw queries, the get method returns an array of results where each result is an instance of the PHP StdClass object.

If you want an Eloquent collection, you will need to use an Eloquent model or use the collect() helper function as @Martin suggests.

A: The put() method sets the given key and value in the collection:
you are trying to save array object in $rollSize.
In model make roll_size serialize object if you want to store rollSize as array in database.


text:
Q: How to use For Loop in Selenium IDE to loop through pages I would like to see my web pages to change automated from from page 1 to page 200 and i tried using php and javascript but nothing worked for using for loop. is there a way to use for loop in the page?

        clickAndWait
        link=2

        clickAndWait
        link=3

        clickAndWait
        link=4

        clickAndWait
        link=5

    getEval
    link = 6;

    while
    link < 10;

    storeEval
    link
    value

    echo
    link = ${value}

    getEval
    link++;

    endWhile

I wanted the link to be in a for loop from 1 to 100. I appreciate anyone who helps me.so far i tried to echo the page numbers but is there any way to loop through pages?
so far this is the output i got:
[info] Executing: |clickAndWait | link=2 | |
[info] Executing: |clickAndWait | link=3 | |
[info] Executing: |clickAndWait | link=4 | |
[info] Executing: |clickAndWait | link=5 | |
[info] Executing: |clickAndWait | link=6 | |
[info] Executing: |getEval | link = 6; | |
[info] script is: link = 6;
[info] Executing: |while | link < 10; | |
[info] Executing: |storeEval | link | value |
[info] script is: link
[info] Executing: |echo | link = ${value} | |
[info] echo: link = 6
[info] Executing: |echo | {$Value} | |
[info] echo: {$Value}
[info] Executing: |getEval | link++; | |
[info] script is: link++;
[info] Executing: |endWhile | | |
[info] Executing: |while | link < 10; | |
[info] Executing: |storeEval | link | value |
[info] script is: link
[info] Executing: |echo | link = ${value} | |
[info] echo: link = 7
[info] Executing: |echo | {$Value} | |


text:
Q: Do two defined GROUPS of words occur within 25 words of each other? I am trying to evaluate whether two named groups of words occur within 25 words of each other.
Below, I have included a simple way to look for certain words within 25 words of each other, similar to this post (Regular Expression: Find words within 10 words of each other ). However, I would like to reference groups of words, which  contain about 500 word variations each, within the regular expression. I do not want to list each word in the code, if possible.
#What I think I can do:
text = "CompanyA sells Andriods and Robots. Andriods are purchased and then resold by CompanyB."

counter = Counter(re.findall(r'\b(sells|purchased|resold(?:\W+\w+){0,25}?\W+Androids | Androids(?:\W+\w+){0,25}?\W+sells|purchased|resold)\b', text, re.DOTALL))
sumcounter = sum(counter.values())

#Result = 3

#What I want to do:
Group1 = '/b(Androids)/b'
Group2 = '/b(sells|purchases|resold)/b'
#I am not sure I am formatting the groups correctly, but I've tried a few different ways to know avail (e.g., excluding the \b word boundary or creating a list Group2 =  ['sells', 'purchases', 'resold']

counter2 = Counter(re.findall(r'(?P<Group2>)(?:\W+\w+){0,25}?\W+(?P<Group1>) | (?P<Group1>)(?:\W+\w+){0,25}?\W+(?P<Group2>))', text, re.DOTALL))
sumcounter2 = sum(counter2.values())
#error: redefinition of group name 'Group1' as group 3; was group 2 at position 51

#However, this alternative also does not work
counter2 = Counter(re.findall(r'((?P<Group1>)\(?:\W+\w+){0,25}?\W+(?P<Group2>)', text, re.DOTALL))
sumcounter2 = sum(counter2.values())
#This codes appears to capture the number of letters, rather than recognizing different words
#Result = 13

#Other Failed attempts
#counter2 = Counter(re.findall(r'\b(?P<Group2>)(?:\W+\w+){0,25}?\W+(?P<Group1>) | (?P<Group1>)(?:\W+\w+){0,25}?\W+(?P<Group2>)\b', text, re.DOTALL))
#counter2 = Counter(re.findall(r'\b(?P='Group2')(?:\W+\w+){0,25}?\W+(?P='Group1') | (?P='Group1')(?:\W+\w+){0,25}?\W+(?P='Group2')\b', text, re.DOTALL))
#counter2 = Counter(re.findall(r'\b(?P="Group2")(?:\W+\w+){0,25}?\W+(?P="Group1") | (?P="Group1")(?:\W+\w+){0,25}?\W+(?P="Group2")\b', text, re.DOTALL))

Edit: I've also tried the below in response to the following post: Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?
This seems to be getting me closer to my answer, but my main code still receives an error message.
: #The below appears to work:
counter2 = Counter(re.findall(r'((?P<Group1>.*)(?:\W+\w+){0,25}?\W+(?P<Group2>.*)', text, re.DOTALL))
sumcounter2 = sum(counter2.values())
#Result = 1

#However, I'm still receiving an error here:
counter = Counter(re.findall(r'((?P<Group1>.*)(?:\W+\w+){0,25}?\W+(?P<Group2>.*) | (?P<Group2>.*)(?:\W+\w+){0,25}?\W+(?P<Group1>.*))\b', text, re.DOTALL))
sumcounter = sum(counter.values())

#error: redefinition of group name 'Group2' as group 4; was group 3 at position 56


text:
Q: When mixing omniauth and fbgraph gems I am failing to get an access key I am using Rails 3.
I am getting a Rack::OAuth2::Client::Error in SessionsController#create error when I try to get the access key.
I used omniauth to login to facebook and I am getting the param["code"]
Now I try to use fbgraph to get the access code and I am getting the Rac::OAuth2::Client::Error.
  def create
    auth=request.env["omniauth.auth"]
    fb_auth=FbGraph::Auth.new("xxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxx")
    client=fb_auth.client
    client.redirect_uri="http://localhost:3000/facebook/callback/"
    client.authorization_code=params[:code]
    access_token = client.access_token!  # => Rack::OAuth2::AccessToken
    user=User.find_by_provider_and_uid(auth["provider"], auth["id"]) ||User.create_with_omniauth(auth, access_token)
    session[:user_id]=user.id

    redirect_to root_url, :notice => "Signed In!"
  end

The access_token! line is what is returning the error.

A: If you set the redirect_uri on the fb_auth instead of the client it should be fine e.g.
fb_auth = FbGraph::Auth.new(
   "xxxxxxx",
   "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
   :redirect_uri = "http://localhost:3000/facebook/callback"
)
client=fb_auth.client
client.authorization_code=params[:code]
access_token = client.access_token!  # => Rack::OAuth2::AccessToken

You should also check out https://github.com/nov/fb_graph/issues/127#issuecomment-2244499,
then have a read of the fb_graph_sample code and setup your FbGraph debugging.


text:
Q: How to programmatically navigate to screen after validation on click I have inherited a Sketchflow-prototyped WPF application.  I am in the process of adding functionality to the UI.
As it currently is, navigation from screen to screen is defined in XAML as an event as follows:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
    <pi:NavigateToScreenAction TargetScreen="WpfPrototype1Screens.Screen_1_2"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

This works, but the problem is that it doesn't allow me to validate user input before navigating to the new screen.
What I would like to know, is how can I programmatically navigate to the new screen from within the button's click event handler in C#?
For instance:
private void Button1_Click_1(object sender, RoutedEventArgs e)
{
    if (userInputValid)
    {
        NavigateToScreen_1_2();
    }
}

A: This strongly depends on how your next screen is used. If it is a UserControl (View) that is inserted in another part of the application lets say an ContentControl then you can just change the content of the Content control to your new screen.
Take a look at Commands in WPF in combination with MVVM. This can help you with your problem. Instead of having an OnClick event you define an execute function inside your Views ViewModel and have a public property which you can bind to your buttons Command property
like this.
Have a simple class:
public class MainViewModel
{
    public MainViewModel()
    {
        NextViewCommand = new DelegateCommand(NextView);
    }

    public ICommand NextViewCommand {get;set;}
    public UserControl NewView {get;set;}

    public void NextView()
    {
         NewView = new UserControl() //set your NewView property to your new usercontrol
         //Apply validation on all your binded properties you want to validate.
    }
}

DelegateCommands
Wire up the ViewModel to your View using:
this.DataContext = new MainViewModel();

And connect your command to your button using:
<Button content="Next view" Command="{Binding NextViewCommand}"/>

I think this is the best way to go, and helps you.


text:
Q: Spring OAuth2 SSO + Keycloak with Desktop Application I have a Spring framework + Spring security application and using spring-security-oauth2-client for OIDC authentication with Keycloak. On web browser, SSO works great.
I have a Excel Add-in for users to upload data on to the web platform. How can I enable SSO authentication for Excel-Addin(C#, desktop application)


text:
Q: Does anyone know of a php framework that would handle progressive enhancement for Flash/Flex content? Ok, I'm using the term "Progressive Enhancement" kind of loosely here but basically I have a Flash-based website that supports deep linking and loads content dynamically - what I'd like to do is provide alternate content (text) for those either not having Flash and for search engine bots. So, for a user with flash they would navigate to:
http://www.samplesite.com/#specific_page

and they would see a flash site that would navigate to the "specific_page."  Those without flash would see the "specific_page" rendered in text in the alternative content section.
Basically, I would use php/mysql to create a backend to handle all of this since the swf is also using dynamic data. The question is, does something out there that does this already exist?

A: Well, according to OSFlash (the open source flash people) both CakePHP and PHPWCMS can do what you need, although from a first glance at their sites' feature list, it is not entirely obvious.
Let us know if they do work!

A: There's an inherent problem with what you're trying to achieve.
The URL hash (or anchor) is client-side only - that token is not sent to the server. This means the only way (that I know of) to load the content you need for example.com/#some_page is to use AJAX, which can read the hash and then request the page-specific data from the server.
Done?  No.  Because this will kill search engine bots.  A possible solution is to have example.com/some_page serve the same content (in fact, that could easily be a REST service that you've already made to return the AJAX or Flash-requested content), and provide a sitemap.xml which indexes those URIs to help out the search engines.
I know of no existing framework that does specifically these tasks, although it certainly seems like one could be made w/o too much trouble.

A: if you're using SWFAddress with Flash/Flex then you can read in the URL and then split that into an array and do as you wish:
SWFAddress.addEventListener ( SWFAddressEvent.CHANGE, onChange );
private function onChange ( e : SWFAddressEvent ) : void
{
     var ar : Array = SWFAddress.getValue ().split ( '/' );
     trace ( 'Array : ', ar );
}

For your non-flash stuff if you're using code igniter you'd be able to pull the url and convert that into an array as well.
Another alternative is to use FAUST. What you can do with FAUST is have PHP render out the HMTL as valid markup then FAUST will pull the HTML and pass that to Flash via Flash Vars as XML. This method makes search engines really really happy ( see http://www.bartoncreek.com ).
So to answer your question there are tools out there that will help you achieve your goals.