text:
Q: Counting total number of consecutive absent and percentage calculation using mysql query I have two tables; student and attendance:
Student table:
sid            name
-----         --------
s1            nam1
s2            nam2
s3            nam3
s4            nam4
s5            nam5

Attendance table:
sid           status       date           sub_id
-----         --------   ---------        ------
s1            present    2017-05-16       ms100
s2            present    2017-05-16       ms100
s3            absent     2017-05-16       ms100
s4            present    2017-05-16       ms100
s5            present    2017-05-16       ms100

s1            present    2017-05-17       ms100
s2            present    2017-05-17       ms100
s3            absent     2017-05-17       ms100
s4            present    2017-05-17       ms100
s5            absent     2017-05-17       ms100

s1            present    2017-05-16       ms101
s2            present    2017-05-16       ms101
s3            absent     2017-05-16       ms101
s4            present    2017-05-16       ms101
s5            absent     2017-05-16       ms101

Now I want to show on which date students were present or absent also want to  count the total attended class, consecutive absent and percentage of attendance for every student for the subject id ms100.
For consecutive missing/absent i want to to consider only last consecutive missing/absent.For example if among 10 days s1 was present on day 1, 6, 7 then his con_missing will be 3 not 5. If s1 was present on day 9 then his con_missing will be 0 as i want to consider consecutive missing only when a student is absent for more than 1 days.
For example students with sid s1,s2,s4 were present in all the 2 classes of the subject ms100 so their total number of attended class will be 2, as the were present in all classes so their total number of consecutive absent will be 0 and  percentage will be {(total attended class/total class)*100} which is 100 % in this case. On the other hand s3 was absent in all classes so his total number of attended class and percentage will be 0 and total number of consecutive absent will be 2.
For student id s5 the consecutive  absent will be 0 as he is absent just for one day.
I am expecting result like following pattern where each individual class date for the subject ms100 will be shown as column and attendance status(present/absent) of an individual student on that particular date will be shown as value of that column:
sid    name   2017-05-16  2017-05-17 consecutive_absnt  total_atn   %
-----  -----  ----------  ---------   ----------------  ---------  ----
s1     nam1   present     present      0                  2         100
s2     nam2   present     present      0                  2         100
s3     nam3   absent      absent       2                  0          0
s4     nam4   present     present      0                  2         100
s5     nam5   present     absent       0                  1         50

I am using Angularjs as font end and php as back end.This is what i have tried so far
php
$query="
SELECT atn.sid
     , atn.date
     , atn.status
     , s.name
  FROM attendance atn
  join student s
    on atn.sid = s.sid
 where atn.sub_id = 'ms100'
 ORDER
    BY atn.date
     , atn.sid
";
    $result = $mysqli->query($query) or die($mysqli->error.__LINE__);

    $arr = array();
    if($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $arr[] = $row;
        }
    }
    # JSON-encode the response
    $json_response = json_encode($arr);

    // # Return the response
    echo $json_response;

angularjs

sid
name

{{data.date}}

consecutive missing
total attended
%

       {{data.sid}}
       {{data.name}}
       {{data.status}}
        {{data.consecutive}}
        {{data.total_atn}}
        {{data.percentage}}

Getting result like this
sid      name       2017-05-16   2017-05-17  con_missing  totl_atend  %
-----   --------   ---------   ----------    --------     --------   ---
s1      nam1         present
s2      nam2         present
s3      nam3         absent
s4      nam4         present
s5      nam5         present

s1      nam1         present
s2      nam2         present
s3      nam3         absent
s4      nam4         present
s5      nam5         absent

So how can I achieve my expected result through mysql query?

A: Ok this took a while to get together :)
First off we setup a function in the mysql database to get the consecutive number of days:
CREATE FUNCTION `getConsecutive`( _subid varchar(45), _sid varchar(45) ) RETURNS int(11)
BEGIN

    declare ret int;

    select max(consecutive) into ret from (
            select  q.date,
                    q.status,
                    @consecutive :=  CASE WHEN @stop = 1 THEN 0 WHEN q.status = 'absent' THEN @consecutive +1 ELSE 0 END as consecutive,
                    @started :=     CASE WHEN @consecutive > 0 OR @started > 0 THEN 1 ELSE 0 END as started,
                    @stop :=        CASE WHEN @consecutive = 0 AND @started > 0 THEN 1 ELSE @stop END as stop
            from (
                select date, status from Attendance where sub_id = _subid and sid = _sid order by date desc
            ) q,
            (select @consecutive := 0) r,
            (select @started := 0) r2,
            (select @stop := 0) r3
        ) as z;

    RETURN CASE WHEN ret = 1 THEN 0 ELSE ret END;

END

Then we build the sql, but hardcoded to test for 2 columns:
SELECT atn.sid, s.name,
    MAX(IF(atn.date = '2017-05-16', atn.date, null)) `2017-05-16`,
    MAX(IF(atn.date = '2017-05-17', atn.date, null)) `2017-05-17`,
    getConsecutive(atn.sub_id, atn.sid) consecutive_absnt,
    SUM(CASE WHEN atn.status = 'present' THEN 1 ELSE 0 END) total_atn,
    ROUND(100*(SUM(CASE WHEN atn.status = 'present' THEN 1 ELSE 0 END)/count(1)), 2) '%'
  FROM Attendance atn
  join Student s
    on atn.sid = s.sid
 where atn.sub_id = 'ms100'
 GROUP BY atn.sid, s.name;

Then we know it works but the main problem is that it is a dynamically number of columns.. so you will need to do is divide this up in parts.
We need a stored procedure that will build and execute our dynamic sql.
CREATE PROCEDURE `getData`(_subId VARCHAR(45))
BEGIN

    select GROUP_CONCAT(CAST(CONCAT('MAX(IF(atn.date = \'', dd, '\', atn.date, null)) `', dd, '`\n') AS CHAR)) INTO @builtSql
    from (
        select distinct str_to_date(date, '%Y-%m-%d') dd from Attendance where sub_id = _subId
        ) q
        ;

  SET @builtSql = CONCAT('SELECT atn.sid,
        s.name,', @builtSql, ',
        getConsecutive(atn.sub_id, atn.sid) consecutive_absnt,
        SUM(CASE WHEN atn.status = \'present\' THEN 1 ELSE 0 END) total_atn,
        ROUND(100*(SUM(CASE WHEN atn.status = \'present\' THEN 1 ELSE 0 END)/count(1)), 2) \'%\'
        FROM Attendance atn
        join Student s on atn.sid = s.sid
        where atn.sub_id = \'', _subId,'\'
        GROUP BY atn.sid, s.name');

    PREPARE stmt FROM @builtSql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

END

To build a dynamic sql is usually a bad idea because of the risk of sql injection, so i advise you to do some checks on the data sent into the stored procedure.
Then you can just call the Stored Procedure to get the result you wanted above.
call getData('ms100')


text:
Q: How to stop code from calculating twice My code is suppose to calculate 5% on to a salary and 10% on a salary. When compiled the outcome is the 5% calculating right but I think the 10% is adding the 5% on top of the 10%. How would I fix this?
#include <cstdlib>

#include <iostream>

using namespace std;

void fivePercentRaise(double &);

void tenPercentRaise(double &);

int main()

{

double salary = 0.0;
cout << "Please enter current salary: ";

cin >> salary;

fivePercentRaise(salary);

tenPercentRaise(salary);

system("pause");

return 0;

}

void fivePercentRaise(double & sal)

{

sal = sal * 0.05 + sal;

cout << "New salary if you receive a 5% raise: " << sal << endl;

}

void tenPercentRaise(double & sal)

{

sal =  sal * 0.10 + sal;

cout << "New salary if you receive a 10% raise: " << sal << endl;

}

A: Your code is:
fivePercentRaise(salary);
tenPercentRaise(salary);

These functions work by taking salary by reference, and modifying it in-place. So you are indeed calculating a 5% raise and then calculating a 10% raise on top of that (compounded).
You have a few options:

*

*Save the value of salary before calling fivePercentRaise and then restore it

*Take the argument by value, and return the updated value

*Take the argument by value, not returning anything since you do not use the value outside the function anyway

A more normal design would be for your function to perform the raise, and then the calling code does the output.  Then you do not need to modify the function if you want to apply the 5% raise in another scenario where you don't want to also print out what happened.

A: You are giving two raises sequentially.
Assume 100 dollar salary:
5 percent raise:  105
10 percent raise (of 105) : 115.50

A: The cause of the problem is the function declaration:
void tenPercentRaise(double & sal)

When you use a reference, with &, you will modify the variable that was used to call the function.
Please read about "pass by reference" and "pass by value."  Understanding that distinction, it should be straightforward to fix the functions.

A: The problem is that you're telling your functions ('fivePercentRaise()','tenPercentRaise()') to take the input variable, salary, by reference instead of by value. When you tell the functions to take the variable by reference,'fivePercentRaise()' will raise the value stored in the value 'salary' by 5%. Then you pass that same variable to 'tenPercentRaise()' who gladly raises the same 'salary' variable by 10%.
Get rid of the ampersands in your pre-processor directives and function definitions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to enable Apache Solr service on Rackspace Ubuntu Server? We have setup Apache Solr on Rackspace dedicated ubuntu server. But, I think because of Firewall this service is not available. I tried adding following line as per Rackspace documentation:
/sbin/iptables -I RH-Firewall-1-INPUT 1 -p tcp --dport 8983  -j ACCEPT
which returns me following result:
iptables: No chain/target/match by that name.
Please find below the result from the command iptables -L -n:
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:443
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:80
fail2ban-ssh  tcp  --  0.0.0.0/0            0.0.0.0/0            multiport dports 22
ufw-before-logging-input  all  --  0.0.0.0/0            0.0.0.0/0
ufw-before-input  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-input  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-logging-input  all  --  0.0.0.0/0            0.0.0.0/0
ufw-reject-input  all  --  0.0.0.0/0            0.0.0.0/0
ufw-track-input  all  --  0.0.0.0/0            0.0.0.0/0

Chain FORWARD (policy DROP)
target     prot opt source               destination
ufw-before-logging-forward  all  --  0.0.0.0/0            0.0.0.0/0
ufw-before-forward  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-forward  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-logging-forward  all  --  0.0.0.0/0            0.0.0.0/0
ufw-reject-forward  all  --  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT)

target     prot opt source               destination
ufw-before-logging-output  all  --  0.0.0.0/0            0.0.0.0/0
ufw-before-output  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-output  all  --  0.0.0.0/0            0.0.0.0/0
ufw-after-logging-output  all  --  0.0.0.0/0            0.0.0.0/0
ufw-reject-output  all  --  0.0.0.0/0            0.0.0.0/0
ufw-track-output  all  --  0.0.0.0/0            0.0.0.0/0

Chain fail2ban-ssh (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-after-forward (1 references)
target     prot opt source               destination

Chain ufw-after-input (1 references)
target     prot opt source               destination
ufw-skip-to-policy-input  udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:137
ufw-skip-to-policy-input  udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:138
ufw-skip-to-policy-input  tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:139
ufw-skip-to-policy-input  tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:445
ufw-skip-to-policy-input  udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:67
ufw-skip-to-policy-input  udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:68
ufw-skip-to-policy-input  all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type BROADCAST

Chain ufw-after-logging-forward (1 references)
target     prot opt source               destination
LOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 10 LOG flags 0 level 4 prefix "[UFW BLOCK] "

Chain ufw-after-logging-input (1 references)
target     prot opt source               destination
LOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 10 LOG flags 0 level 4 prefix "[UFW BLOCK] "

Chain ufw-after-logging-output (1 references)
target     prot opt source               destination

Chain ufw-after-output (1 references)
target     prot opt source               destination

Chain ufw-before-forward (1 references)
target     prot opt source               destination
ufw-user-forward  all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-before-input (1 references)
target     prot opt source               destination
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ufw-logging-deny  all  --  0.0.0.0/0            0.0.0.0/0            state INVALID
DROP       all  --  0.0.0.0/0            0.0.0.0/0            state INVALID
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 3
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 4
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 11
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 12
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0            icmptype 8
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp spt:67 dpt:68
ufw-not-local  all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     udp  --  0.0.0.0/0            224.0.0.251          udp dpt:5353
ACCEPT     udp  --  0.0.0.0/0            239.255.255.250      udp dpt:1900
ufw-user-input  all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-before-logging-forward (1 references)
target     prot opt source               destination

Chain ufw-before-logging-input (1 references)
target     prot opt source               destination

Chain ufw-before-logging-output (1 references)
target     prot opt source               destination

Chain ufw-before-output (1 references)
target     prot opt source               destination
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ufw-user-output  all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-logging-allow (0 references)
target     prot opt source               destination
LOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 10 LOG flags 0 level 4 prefix "[UFW ALLOW] "

Chain ufw-logging-deny (2 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0            state INVALID limit: avg 3/min burst 10
LOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 10 LOG flags 0 level 4 prefix "[UFW BLOCK] "

Chain ufw-not-local (1 references)
target     prot opt source               destination
RETURN     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL
RETURN     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type MULTICAST
RETURN     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type BROADCAST
ufw-logging-deny  all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 10
DROP       all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-reject-forward (1 references)
target     prot opt source               destination

Chain ufw-reject-input (1 references)
target     prot opt source               destination

Chain ufw-reject-output (1 references)
target     prot opt source               destination

Chain ufw-skip-to-policy-forward (0 references)
target     prot opt source               destination
DROP       all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-skip-to-policy-input (7 references)
target     prot opt source               destination
DROP       all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-skip-to-policy-output (0 references)
target     prot opt source               destination
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-track-input (1 references)
target     prot opt source               destination

Chain ufw-track-output (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            state NEW
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            state NEW

Chain ufw-user-forward (1 references)
target     prot opt source               destination

Chain ufw-user-input (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:22 /* 'dapp_OpenSSH' */
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:1111
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:1111
ACCEPT     all  --  174.143.23.0/25      0.0.0.0/0
ACCEPT     all  --  50.56.142.128/26     0.0.0.0/0
ACCEPT     all  --  180.150.149.64/26    0.0.0.0/0
ACCEPT     all  --  69.20.52.192/26      0.0.0.0/0
ACCEPT     all  --  78.136.44.0/26       0.0.0.0/0
ACCEPT     all  --  50.57.61.0/26        0.0.0.0/0

Chain ufw-user-limit (0 references)
target     prot opt source               destination
LOG        all  --  0.0.0.0/0            0.0.0.0/0            limit: avg 3/min burst 5 LOG flags 0 level 4 prefix "[UFW LIMIT BLOCK] "
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

Chain ufw-user-limit-accept (0 references)
target     prot opt source               destination
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0

Chain ufw-user-logging-forward (0 references)
target     prot opt source               destination

Chain ufw-user-logging-input (0 references)
target     prot opt source               destination

Chain ufw-user-logging-output (0 references)
target     prot opt source               destination

Chain ufw-user-output (1 references)
target     prot opt source               destination

Please guide me to the right direction.
Thanks,
Vishal

A: As @lgarzo suggested above, I just fixed the chain and it worked.
Correct command:
/sbin/iptables -I INPUT 1 -P tcp --dport 8983 -j ACCEPT

Also, make sure to save your IPTABLES after this.


text:
Q: How to get web part instance GUID from javascript from within the web part in SP2013? In sharepoint 2013, I have a content editor web part. I have javascript code in it. I want to get a GUID. I want to get the GUID of the instance of the web part. So if I had 2 content editor webparts they should have unique identifiers each. No other content editor web part (even on another page) should have that same GUID.
I was looking at the DOM explorer in dev tools, and see on the web part there is a tag with class ms-WPBody and attribute webpartid="7722f3d5-e8da-4b3b-acc4-3bf3e6f9aba7" (for example). It seems to be different per instance of this web part on the same page too.
If I put the javascript code in the web part (linked to a file option too). I am thinking of doing something like, using jquery's nearest function to get the closest parent div.ws-WPBody and then grabbing the webpartid value.
Is this an ok way, or is there any issues or better ways?
Thanks

A: Typically when you want the ID from inside the web part, it is to ensure uniqueness in included client side script (since you might add the web part more than one time).
For this purpose, ID and ClientID works fine. If you need the GUID you could use string handling to remove the prefix.
protected override void RenderContents(HtmlTextWriter writer)
{
    base.RenderContents(writer);

    writer.Write("WebPart ID: {0}
", this.ID);
    writer.Write("WebPart ClientID: {0}
", this.ClientID);
}

will render similar to this:
WebPart ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3 WebPart ClientID: ctl00_m_g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3
WebPart1 myWebPart = (WebPart1)this.WebPartManager.FindControl(this.ID);
writer.Write("Webpart from WPM: ID: {0}", myWebPart.ID);

Webpart from WPM: ID: g_4620e28f_2e09_49b9_9822_03bb3aa8b2b3


text:
Q: WebApi OData per user security on property I have some entities which have data that must only be accessible for some users.
public class Foo
{
    public virtual Bar { get; set; }
    ...
}

public class Bar
{
    public string Secret { get; set; }
    ...
}

For example Bar.Secret must only be accessible by UserA but not by UserB.
I could so something like this:
public class BarsController : ODataController
{
    [EnableQuery]
    public IHttpActionResult Get()
    {
        if (User.Identity.Name != "UserA")
            return Unauthorized();

        return _db.Bars();
    }
}

Besides that being a bad implementation. It doesn't cover this controller:
public class FoosController : ODataController
{
    [EnableQuery]
    public IHttpActionResult Get()
    {
        return _db.Foos();
    }
}

Which could be called with /odata/Foos?$expand=Bars and then I could view Bar.Secret. I can't just disable $expand on Foo because that query is totally legit for UserA and also needed.
Is there a way to make OData validate the queries against some predicate that involves the requested entities.
Something like
public class SecureEnableQueryAttribute : EnableQueryAttribute
{
    public bool ValidateResult(IEnumerable<T> entities)
    {
        return entities.All(x => x.Secret == UserA.Secret);
    }
}

A: You can validate the query options before the query is executed and fail if the user is not authorized to retrieve the requested data. To do this, derive from EnableQueryAttribute and override ValidateQuery.
public class SecureEnableQueryAttribute : EnableQueryAttribute
{
    public virtual void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)
    {
        base.ValidateQuery(request, queryOptions);

        // Insert custom logic, possibly looking at queryOptions.SelectExpand
        // or queryOptions.RawValues.
    }
}


text:
Q: PPPOE Discovery Stage with Python Sockets Is there any way of implementing PPPOE discovery stage, i.e. sending PADI receiving PADO and all using Python & Sockets? Not allowed to use Scapy module.
I tried to look all over the internet but can't find anything.


text:
Q: MySQL returns data twice I have the following code, simplified heavily while trying to get to the bottom of this:
<?php
  $db_host   = $_ENV['DATABASE_SERVER'];
  $db_pass   = 'dummypassword';
  $db_user   = 'user';
  $db_name   = 'database';
  $db_char   = 'utf8';

  $db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=$db_char", $db_user, $db_pass);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $email = 'david@example.com';

  if (!empty(trim($email)))
    {
      $sql = 'SELECT * FROM staff';
      $query = $db->prepare($sql);
      $query->execute();
      $results = $query->fetchAll();

      echo '<pre>';
      print_r($results);
      echo '</pre>';
    }
?>

When I run this, the query works fine and I get no errors. What I do get however is:
Array
(
    [0] => Array
        (
            [staff_id] => 1
            [0] => 1
            [staff_org] => 1
            [1] => 1
            [staff_email] => david@example.com
            [2] => david@example.com
            [staff_password] => hashyhashy
            [3] => hashyhashy
            [staff_first_name] => David
            [4] => David
            [staff_start_date] => 2014-03-17
            [7] => 2014-03-17
            [staff_leave_date] =>
            [8] =>
        )
)

Personally I don't remember ever seeing it return the data twice like this (i.e. with a named key, and then again without). My question is this... have I lost my mind and this always how results from MySQL have been returned? Or have I done something to make it do this?

A: You are getting both a numeric zero-indexed key and an associative key. If you need just the associative array, you can do:
$results = $query->fetchAll(PDO::FETCH_ASSOC);

and if you just want numeric keys, you do:
$results = $query->fetchAll(PDO::FETCH_NUM);

Check the manual on fetch() for more details.

A: You can pass the optional parameter fetch_style to the fetchAll() method. The default value of this parameter is PDO::FETCH_BOTH so that the result array contains the numeric and the associative keys.
If you only want to get the associative array keys, you have to change
$query->fetchAll();

to
$query->fetchAll(PDO::FETCH_ASSOC);

A: $query->fetchAll(); defaults to the PDO::FETCH_BOTH fetch style, which returns both the numbered array and the named array.
This should get you just the named array:
$query->fetchAll(PDO::FETCH_ASSOC);

Refs:
PHP Man page for fetch_all()
PHP Man page for fetch()


text:
Q: JSON value  of type NSNull cannot be converted to NSString in react native I keep getting this issue when I land on the home screen on my app, I'm not 100% why the issue is happening or what could be the cause. I've tried to google this but haven't found anything helpful that could guide me in the right path.
Screenshot of the error
Think it's happening somewhere in this code:
const InstaagramEmpty = () => <InstagramUsersEmpty text="No matching users found" />

const InstagramUserItem = (props: { onSelect: () => void, user: InstagramUser }) => {

    //TOOD: user button
    return <AccountContainer onPress={props.onSelect}>
        <AccountImage source={{ uri: props.user.photoUrl }} />
        <Text text={props.user.username} />
    </AccountContainer>
}

// Brinds image/text together
const SelectionContainer = styled(Row)`
`

const SelectionClear = styled(ButtonIcon)`
    width:45px;
    height:45px;
`

const InstagramUserSelection = (props: { onSelect: () => void, user: InstagramUser }) => {

    return <Row drop>
        <SelectionContainer>
            <AccountImage source={{ uri: props.user.photoUrl }} />
            <Text text={props.user.username} />
        </SelectionContainer>
        <SelectionClear icon={IconClose} iconTint={Colors.GreyDark} onPress={props.onSelect} />
    </Row>
}

A: When your JSON document contains the value null, then that will be translated to an Objective-C object of class NSNull. NSNull is a singleton class; the class method [NSNull null] always returns the only NSNull object that ever exists. If you are given an object of unknown type, you can check whether it is a JSON null value by comparing it with [NSNull null]. if (myJSONObject == [NSNull null]) ...
So your JSON data contains a null value, which becomes [NSNull null], and [NSNull null] cannot be converted to anything. Handle it the same as nil. For example if (myJSONObject == nil || myJSONObject == [NSNull null]) ...


text:
Q: Git repositories on network drive all showing same error when cloned: "packfile does not match index" I've been trying to solve this for hours and I've had 0 luck. Apologies in advance, I'm fairly novice when it comes to Git.
I have a large amount of Git repositories on a network drive (R: drive). All of these repositories are clones of another repository with different changes made in each one.
For my work, I frequently need to clone 10+ of these repositories to my local machine (C: drive), so I thought I would make a batch script that would automate the process for me.
When I ran my batch script (which was essentially just 10+ git clone R:\INSERT_REPO_HERE C:\INSERT_DIRECTORY_HERE statements), the process took hours, but this was normal, as my connectivity to the R: drive was poor.
The issue:
I was looking into ways to speed up the cloning process, and had found advice to do the following:
git config --global pack.windowMemory "100m"
git config --global pack.SizeLimit "100m"
git config --global pack.threads "1"
git config --global pack.window "0"
git config --global core.compression 0
git config --global core.bigfilethreshold 200K

So, I ran those commands on both R: and C: drive.
Now, whenever I clone any repo from the R: drive to my C: drive, I get the following error:
Cloning into 'C:\Users\games\Documents\BitBucket\Adapt topics\BU11\BU11.3\src\course\en'...
done.
error: packfile C:/Users/games/Documents/BitBucket/Adapt topics/BU11/BU11.3/src/course/en/.git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile C:/Users/games/Documents/BitBucket/Adapt topics/BU11/BU11.3/src/course/en/.git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: unable to read sha1 file of project/bower.json (15bb293aca56d25d07f9372c81d6d008b41f93cc)

error: packfile C:/Users/games/Documents/BitBucket/Adapt topics/BU11/BU11.3/src/course/en/.git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile C:/Users/games/Documents/BitBucket/Adapt topics/BU11/BU11.3/src/course/en/.git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: unable to read sha1 file of project/js/project.js (02dbe8ec5a71541ce175fada7e0d405359124968)

fatal: unable to checkout working tree
warning: Clone succeeded, but checkout failed.
You can inspect what was checked out with 'git status'
and retry with 'git restore --source=HEAD :/'

I have tried --unsetting the global config I set, but it doesn't fix anything. As far as I can see, the repos on the R: drive still have all my files, so I haven't lost any data; but I can't seem to find a way to fix this issue, and re-creating every single repo on the R: drive would take me a very long time too.
Also, running git fsck --full gives this result, regardless of which repository I do it on:
Checking object directories: 100% (256/256), done.
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack cannot be accessed
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
Checking connectivity: 369, done.
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
error: packfile .git/objects/pack/pack-2105520c4dd562760badf1555e89a734a7dddfa3.pack does not match index
broken link from    tree fc7405e6041f547e5845cead57f06a38ed4b814f
              to    blob db3d21c232d266d476e028af6fe640b5447dba14

I'm not even entirely sure what a "pack file" even is. Please, any help would be greatly appreciated!
EDIT:
I don't know if this helps, but looking in the .git/objects/pack folder of each repository in the R: drive shows that the .pack file was last modified on the same day that I ran the git config commands:

A: Never store a Git repository on a networked or cloud-synced drive.
What, "never"?1
Yes, really, never.  Why not?  Because problems like the one you saw will occur.  Just don't do it.

1Obligatory link

A: While not an answer to my original post, I have found a workaround that's appropriate for my specific situation. Basically, I just recreated each repository.
I went into each repository and deleted the ".git" file, then ran
git init
git add .
git commit -m 'PackFix'

This does mean I've now lost all Git commit history for these repositories, but thankfully (for my specific situation), this isn't a big issue.
To anyone reading this in the future, I'd say this thread is more a warning about running --global commands on a network drive (especially if you don't fully understand what they'll do).


text:
Q: Airflow User Access management I am evaluating Airflow as a Job scheduling tool.
1) Can we create few users like admin, developer and readonly user?
2) Can we implement access control to the Airflow UI
3) Can we control access to the dags folder? Is there any dag Deployment mechanism

A: Taken from Airflow read the docs.
This is all functional if your Airflow version is 1.10 or higher. You must set rbac= True in your airflow.cfg file. I believe if you are updating airflow and not installing fresh, you must also run airflow create_user to create the admin user.

*

*
Can we create few users like admin, developer and readonly user?

Yes. There are five roles created for Airflow by default: Public, Admin, Viewer, User, Op.

*

*Public has no permissions at all.

*Admin has the full set of permissions

*Viewer:  for users without DAG ownership. They have read access to DAGs, but cannot perform any action that could potentially change the state of the database.

*User: this is for users with DAG ownership. They have both read and write access to DAGs, therefore can perform actions such as starting/stopping scheduled DAGs, running DAGs ad-hoc, clearing historical DagRuns or marking DagRuns as success/failure, etc.

*Op: this is for devops that handle Airflow deployment and maintain its uptime. They have access to airflow configuration files via the UI, and can modify shared objects like Variables and Connections.

*
Can we implement access control to the Airflow UI?

You can restrict usage to the server Airflow is hosted on, restricting access by SSH authentication. Users then must be tunneled into the server to view the UI.

*
Can we control access to the dags folder?

Yes through user groups on the Airflow server.

*
Is there any dag Deployment mechanism

No not to my knowledge, but this is relatively easy to implement. Commit your updated DAGS to an online repository like SVN/Git. Use a bash script to check for new updates and pull the updated ones down for deployment.
Check out airflow security section for more information.


text:
Q: Javascript button click causing multiple Post I have the following script which is rendering a partial view inside a dialog box:
$(function () {
            $('#addressLookupBtn').click(function () {
            $('#dialog').dialog({
                title: 'Address Lookup Tool',
                modal: true,
                width: '1200',
                height: 'auto',
                resizable: false,
                show: {
                    effect: "fade",
                    duration: 2000
                },
                hide: {
                    effect: "fade",
                    duration: 1000
                },
                open: function (event, ui) {
                    //Load the AddressLookup action which will return
                    //the partial view: _AddressLookup

                    $(this).load("@Url.Action("AddressLookup", new { evpId = Model.EvpId })");

                }
            }).dialog('open');

        });
        });

The problem is, when I submit the partial view, there are 2 POSTS being made to the server, I think the submit for the partial view is also being bound to the $('#addressLookupBtn').click. Can anyone see where I'm going wrong?
more info

Partial view
@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "updatearea" }))
{

            @Html.TextBox("PostCode", null, new { @class = "form-control" })

            <input type="submit" value="Lookup Postcode" class="btn btn-default" />

}

A: It looks like the post is being submitted using both a normal form submit and as a jquery event.
Perhaps change it to a button (instead of submit) and use only the jquery submit, or remove the jquery event and use only the normal form submit.
As per comments - An example of using jquery ajax instead of MS ajax:
The script:
$(document).ready(function() {

  event.preventDefault(); // stop the form from submitting the normal way
  $('#MyForm').submit(function(event) {
    $.post(
        $('#MyForm').attr('action'),
        { 'PostCode' : $('input[name=PostCode]').val() }
    )
    .done(function(data) {
        alert('Post worked, and data was returned. Parse and/or present.');
        $('#updatearea').html(data); //Replace the current contents of "updatearea" with the returned contents
    });
  });

});

The PartialView:
@using (Html.BeginForm("MyAction", "MyController", new { @id = "MyForm" }))
{

        @Html.TextBox("PostCode", null, new { @class = "form-control" })

        <input type="submit" value="Lookup Postcode" class="btn btn-default" />

}

A: It looks like you are calling open, and still have autoOpen set to true (it is true by default). This is causing open event to run twice. Try setting autoOpen to false
$('#dialog').dialog({
    ...
    autoOpen: false,
    ...
});

https://api.jqueryui.com/dialog/#option-autoOpen

A: It turns out I didn't need to change anything other than move the following bundle reference from _Layout to my Edit view:
@Scripts.Render("~/bundles/unobtrusive-ajax")


text:
Q: How do I programmatically login with IdentityServer4 using code So here's my code that I'm trying.
Uri uri = new Uri(_environmentConfiguration.AuthorityLoginRequestUrl);
string content = $@"Username={ userID }&Password={ userPassword }";
var request = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
_httpClient.SetBearerToken(token.AccessToken);
var response = await _httpClient.PostRequest(uri, request);

The response I get back is a status 400: Bad Request.
Obviously there is something wrong with the request. Either headers/cookies and/or query.
Any ideas?


text:
Q: Validate the uploaded file size with jQuery form validation remote method I would like to do a filesize validation as follows. Please see whether this proposal method makes sense or not. This part alone should work.
1> After the user selects a file, I check whether the file has suffix as png, gif etc.
$("#myform").validate({
 rules: {
   fieldForUpload: {
     required: true,
     accept: "png|gif"
   }
 }
});

2> Then I would like to use aJax method to upload the file to server for validation even before the user clicks the submit button.
http://docs.jquery.com/Plugins/Validation/Methods/remote#url
$("#myform").validate({
  rules: {
    fieldForUpload: {
      required: true,
      accept: "png|gif"
      remote: "check-filesize.php"
    }
  }
});

Here is my questions:
1> Is this method valid?
In other words, can I validate the fieldUpload with "accept" + "remote" together?
2> Can I enforce to validate the "accept" first, then validate the "remote"?
3> How to implement this "remote" method?
FYI: I knew how to validate whether an email exists on the DB by using remote.
Do I have to gain some different knowledge in order to achieve this?
Many thanks

A: If you want to use jQuery's validate you can by creating this method:
$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes)
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param)
});

You would use it:
$('#formid').validate({
    rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576  }
    messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

A: Have you considered using a file upload widget?  Normal form validation requires access to the form fields.  It's not possible in most browsers to actually manipulate file upload input fields.
Check out Plupload and SWFUpload, two Flash-based file upload widgets that permit type and file size restrictions without sending the file to the server first.
There's also Ajax Upload and Uploadify, two jQuery plugins that try to use modern browser features to do the same thing.  Older browsers might not have the same level of support.


text:
Q: Making a checkerboard in html/javascript without canvas? I've been trying to create a checkerboard pattern without using canvas. The thing is, I need a 100px by 100px square where each pixel alternates between green [rgb(0, 255, 0)] and yellow [rgb(255, 255, 0)] (like a checkerboard but at the pixel level). I can make this in html with a lot of copying and pasting... [Here] (http://jsfiddle.net/DyEq9/3/).
However, the survey software that I am using does not allow for such long code. The software also doesn't seem to support the canvas function. Any help is appreciated.

A: As Christopher mentioned, you can create a 2x2 image version of the grid and set that as the background image, with repeating. This is probably the best solution by far.
If, for some reason this is not possible, and you have access to CSS3, you could do this:
http://jsfiddle.net/DyEq9/4/
width:100px;
height:100px;
background-size: 2px 2px;
background-position: 0 0, 1px 1px;
background-color:#ff0;
background-image: -webkit-linear-gradient(45deg, #0f0 25%, transparent 25%, transparent 75%, #0f0 75%, #0f0), -webkit-linear-gradient(45deg, #0f0 25%, transparent 25%, transparent 75%, #0f0 75%, #0f0);

A: You could fake it by creating an image 200px x 100px with your green/yellow background and just repeat it.
.chessboard-container {
 background:url('chess-tile.gif') repeat;
}


text:
Q: Failed showing data from controller into view laravel I am using laravel 5.5, and i want to display my data from databases to view.
Here is the code of my controller
public function SUisAlatRusak()
    {
        $fixasetId = 1516;
        $nama_aset = FixAset::where('id_fixasset', $fixasetId)->first();
        $aset = AsetBergerak::where('id_fixasset', $fixasetId)->get();
        foreach($aset as $asets){
            $pengecekan = Pengecekan::where('id_aset_bergerak', $asets->id_aset_bergerak)->get();
            foreach($pengecekan as $cek){
                $item = PengecekanHasItem::where('id_pengecekan', $cek->id_pengecekan)->get();
            }
        }

        $data = (object) ([
            'nama_aset' => $nama_aset->assetname,
            'kode_aset' => $nama_aset->assetcode,
            'tanggal' => $cek->waktu_cek,
            'items' => (object) $item
        ]);
        // return dd($data);
        $pdf = PDF::loadView('SOPControl.Monitoring.pdfKerusakanAlat', compact('data'))->setPaper('A4', 'portrait');
        return $pdf->stream('Laporan_Kerusakan_'.Carbon::now().'.pdf');
}

And i want to show it in the table below

                    No.
                    Nama Item
                    Keterangan
                    Tanggal

                    @php $i=1;@endphp
                    @foreach ($data as $konten)
                    {{$konten->nama_aset}}
                    @endforeach

But it showing an error message
Trying to get property 'nama_aset' of non-object

Can anybody help me? Thanks for helping.

A: The issue is when looping $data, the only time $konten will be an object is on the last iteration, when $kontent is $data->items:
@foreach ($data as $konten)
{{$konten->nama_aset}}
@endforeach

In actually, this loop isn't required, as $data isn't an array of arrays, so you can access the properties of $data directly:
{{ $data->nama_aset }}
{{ $data->kode_aset }}
...

If you need to iterate over items, a simple foreach on $data->items is all you need.
@foreach($data->items AS $item)
...
@endforeach


text:
Q: Add dynamic html for multiple elements to Angularjs form and use it in the scope on button click I have this form:

Now let's break it down. Tell us about the users.

User #1

                User type:
                <input type="radio" name="user-type" value="commercial" checked> Commercial  <input type="radio" name="trial" value="trial"> Trial

                    User Name:
                    <input type="text" name="user-name">
                    Email:
                    <input type="text" name="email">
                    Password:
                    <input type="password" name="password">
                    Name:
                    <input type="text" name="name">
                    <button id="next-user" class="smallbutton">Click here to add another user if applicable….</button>

This will be a part of larger angular form but I want the user to be able to add multiple forms for adding a user within the form. So for example if a user clicks the button with id of next-user I want to display the same fields but then to have distinct values for the new user when the saving operation will be happening.
So basically I have two questions:

*

*How can I add multiple html forms such as this one on button click in angular

*Once the user will click the save button how can I retrieve the data from the multiple forms such as the one above?

A: The pure angular way to do this is to use a controller function to add users and ng-repeat to render the collection of users without resorting to any DOM manipulation in code.  Here's a working plunk
Controller
app.controller('MainCtrl', function($scope) {
  $scope.users = [{
    username: 'jsmith',
    email: 'jsmith@gmail.com',
    password: '123456',
    name: 'John Smith',
    userType: 'commercial'
  }, {
    username: 'asmith',
    email: 'asmith@gmail.com',
    password: '123456',
    name: 'Alice Smith',
    userType: 'trial'
  }, {
    username: 'dsmith',
    email: 'dsmith@gmail.com',
    password: '123456',
    name: 'David Smith',
    userType: 'commercial'
  }];

  $scope.addUser = function() {
    var newUser = {
      username: '',
      email: '',
      password: '',
      name: '',
      userType: 'commercial'
    };
    $scope.users.push(newUser);
  };
});

HTML

User {{$index+1}}

  User type:
  <input type="radio" ng-model="user.userType" value="commercial"> Commercial
  <input type="radio" ng-model="user.userType" value="trial"> Trial

      User Name:
      <input type="text" ng-model="user.username">

      Email:
      <input type="text" ng-model="user.email">

      Password:
      <input type="password" ng-model="user.password">

      Name:
      <input type="text" ng-model="user.name">

   <button class="smallbutton" ng-click="addUser()">Click here to add another user if applicable….</button>


text:
Q: Preserve Line Feeds and Carriage Returns Powershell I have a csv file originated from Linux Server, so they contains \n to mark the ending of a line. Now I process this file through a powershell script and replace it's 'text qualifier' to something else (that I do because I am using SSIS to upload the csv feed to database and for some odd reasons SSIS don't supports 'embedded text qualifiers')
Part of the script which do this replacement looks like this
gc $file.FullName |
    % { if($_.indexOf("|~|") -eq -1) {$_ -replace "`"((?:`"`"|.)*?)`"(?!`")", "|~|`$1|~|" -replace "`"`"", "`""} else {$_ -replace " ", " "}} |
    sc  $temppath

This scripts works fine but that also change the line feed at the end to \r\n That I understand should not have been that big of problem until I realized that my original feed also contains occasional \r in the description column which is also getting replaced with "\r\n" Now SSIS package is unable to identify where' the csv line ends.
I searched and found this is due to Get-Content which work line by line so I changed the command to following.
[System.IO.File]::ReadAllText($file.FullName) |
            % { if($_.indexOf("|~|") -eq -1) {$_ -replace "`"((?:`"`"|.)*?)`"(?!`")", "|~|`$1|~|" -replace "`"`"", "`""} else {$_ -replace " ", " "}} |
            sc  $temppath

That seems to solve my issue but now I am trapped with *"OutOfMemoryException" as some of the csv files are big (about 400-500 MB) *
Any Suggestions what I can possibily do? Perhaps some replacement for ReadAllText() that works for big files?

A: The problem is that by piping the output of Get-Content, you're ripping the file into individual lines, and then Set-Content combines those line into a new file. Since CR/LF is the way lines are separated in Windows, that's what PowerShell cmdlets use to combine lines into a file (you get the same behavior with Out-File, not surprisingly). But you already knew that. Now what's the solution?
One way is to use the -join operator to join all the lines into a single string consisting of the lines separated by LF characters, and pipe that string to Set-Content:
(Get-Content $file | %{
  if ($_.indexOf("|~|") -eq -1) {
     $_ -replace "`"((?:`"`"|.)*?)`"(?!`")", "|~|`$1|~|" -replace "`"`"", "`""
  } else {
    $_ -replace " ", " "
  }
}) -join "`n" | Set-Content  $temppath

Although this joins all the lines into a single string that needs to be stored in memory, I strongly suspect that this will work better for you, because the OutOfMemoryException is unlikely to be a limitation of system resources with 500MB files, so it's probably a limitation the .NET class.
However, if that still gives you memory errors, or it works but is too taxing on system resources, you can add the lines to the file one at a time in each iteration of the pipeline by using System.IO.File's AppendAllText method to append the lines without adding a newline (which piping to Out-File -Append would do), and tacking a "`n" onto each one:
Get-Content $file | %{
  [System.IO.File]::AppendAllText($temppath, $(
    (if ($_.indexOf("|~|") -eq -1) {
       $_ -replace "`"((?:`"`"|.)*?)`"(?!`")", "|~|`$1|~|" -replace "`"`"", "`""
    } else {
      $_ -replace " ", " "
    }) + "`n"
  ))
}

The would be slower, but drastically less memory-intensive.
Note, BTW, that gc $file.FullName is redundant, because a FileInfo object is implicitly converted to a string as its FullName property, so gc $file is sufficient.


text:
Q: How can I find the average of an integer variable that is changed 5 times from a while loop nested inside a for loop? C# Sorry, it was hard to phrase that question.
My console "program" uses a while loop to randomly generate a number between 1 & 6 (like a dice). The goal is to generate (roll) the number 6. It also has a variable inside it called attempts to calculate how many attempts it took to generate (roll) the number 6.
I want to run this console "program" 5 times (I used a for loop) and then calculate the average of the attempts variable from each iteration of the for loop.
My question is, how can I extract the attempts variable from each iteration and then calculate the average of the attempts.
This is the code I have so far:
// creates the random # generator

Random numberGen = new Random();

// Runs the while loop 5 times

for (int i = 0; i < 5; i++) {

//Declares the roll and attempts variables to start at 0

    int roll = 0;
    int attempts = 0;

//Runs the number generator to create a number between 1-6. Prints the output.

    while (roll != 6) {
        roll = numberGen.Next(1, 7);
        Console.WriteLine("You rolled: " + roll);
        attempts++;
}
//Prints the # of attempts after each iteration of the for loop.

Console.WriteLine("Total attempts: " + attempts);

//I was trying to use an if statement to transfer the attempt variable into a different variable after each iteration, however this does not work, my brain is fried at this point.

int attempt1, attempt2, attempt3, attempt4, attempt5;
    if (i == 0) {
        int attempts = attempt1;
    }
    else if (i == 1) {
        int attempts = attempt2;
    }
    else if (i == 3) {
        int attempts = attempt3;
    }
    else if (i == 4) {
        int attempts = attempt4;
    }
    else {
        int attempts = attempt5;
    }

}

Console.ReadKey();

A: Here you go:
Random numberGen = new Random();

// Runs the while loop 5 times

List<int> attemptsList = new List<int>();

for (int i = 0; i < 5; i++)
{

    //Declares the roll and attempts variables to start at 0

    int roll = 0;
    int attempts = 0;

    //Runs the number generator to create a number between 1-6. Prints the output.

    while (roll != 6)
    {
        roll = numberGen.Next(1, 7);
        Console.WriteLine("You rolled: " + roll);
        attempts++;
    }
    //Prints the # of attempts after each iteration of the for loop.

    Console.WriteLine("Total attempts: " + attempts);
    attemptsList.Add(attempts);

}

var avgAttempts = attemptsList.Average();

Console.WriteLine("Average attempts: " + avgAttempts);

A: An average is the sum divided by the count. Declare a variable to accumulate the sum, then divide by 5. Mind your data types!

A: To build on mathis1337's answer, you can do the same thing without a list by summing each term of the arithmetic mean:
    Random numberGen = new Random();

    var mean = 0f;
    const int count = 5;

    for (int i = 0; i < count; i++)
    {

        //Declares the roll and attempts variables to start at 0

        int roll = 0;
        int attempts = 0;

        //Runs the number generator to create a number between 1-6. Prints the output.

        while (roll != 6)
        {
            roll = numberGen.Next(1, 7);
            Console.WriteLine($"You rolled: {roll}");
            attempts++;
        }
        //Prints the # of attempts after each iteration of the for loop.

        Console.WriteLine($"Total attempts: {attempts}" );
        mean += ((float)attempts) / count;

    }

    Console.WriteLine($"Average attempts: {mean}");

This is effectively what MPelletier was suggesting in their answer as well


text:
Q: Exit thread upon deleting static object during unload DLL causes deadlock? I have one instance (global/static object) ClassA inside of my delay-loaded DLL. This object inside has an "Observer" thread which is required to perform graceful shutdown. When I call FreeLibrary I noticed that during deletion of this static object my thread requested to shutdown but hangs on _endthreadex() and causes deadlock. It doesn't matter if I call _endthreadex explicitly or implicitly. It doesn't matter if object is global or static - same result.
This thread wrapped in ClassB (implemented by template with custom message loop). There is a request to shutdown thread (post message) and following WaitForSingleObject which never returns for given thread heandle.
Same "template thread class" used everywhere in the code and shutdown works great. The only issue when deleting static obj. I think there is some lock inside of _endthreadex() which is already locked upon dll unload and deleting of static objects.
Thread started with _beginthreadex.
ps. When I instantiated same static obj inside of App - app closes without any significant issues.
Any ideas why _endtreadex causes deadlock? How to avoid it?

A: This particular case is easy to explain.  The _endthreadex call needs the loader lock so that it can call DllMain with DLL_THREAD_DETACH.  The thread that called FreeLibrary, however, already holds the loader lock, because you're already in the middle of a call to DllMain with DLL_PROCESS_DETACH.
The other way this can break is that if the process exits without explicitly unloading the library, your observer thread will be terminated before the DLL_PROCESS_DETACH call, so when you try to signal it to exit, it won't respond because it isn't running any more.
The best approach is probably to create explicit InitializeLibrary() and UninitializeLibrary() functions for the user to call.


text:
Q: converting a covariance matrix to a data frame with covariance variables A matrix cov_mat stores the covariances between variables:
        a_plane a_boat  a_train b_plane b_boat  b_train c_plane c_boat  c_train d_plane …
a_plane   4.419 -0.583    0.446  0.018  -1.291    3.159  -0.954  0.488    3.111   1.100
a_boat   -0.583  2.636    1.813 -1.511  -0.420   -0.757   1.698  1.668    1.091   0.120
a_train   0.446  1.813    2.668 -0.365  -0.183    1.040   1.347  1.813    0.806  -0.324
b_plane   0.018 -1.511   -0.365  2.498   1.153    1.498  -0.465 -1.157   -0.775   0.133
b_boat   -1.291 -0.420   -0.183  1.153   1.043   -0.194   0.243 -0.361   -0.981  -0.040
b_train   3.159 -0.757    1.040  1.498  -0.194    4.153  -0.208  0.257    1.922   1.434
c_plane  -0.954  1.698    1.347 -0.465   0.243   -0.208   1.791  0.909    0.259   0.394
c_boat    0.488  1.668    1.813 -1.157  -0.361    0.257   0.909  2.290    1.572   0.269
c_train   3.111  1.091    0.806 -0.775  -0.981    1.922   0.259  1.572    4.097   2.001
d_plane   1.100  0.120   -0.324  0.133  -0.040    1.434   0.394  0.269    2.001   2.231
…

final_need is a data frame with a row for each category of transportation (plane, boat, train) and a column for every possible covariance within a given category:
           aa       ab      ac     ad       ba     bb       bc     bd       ca     cb   …   <dd>
plane   4.419    0.018  -0.954  1.100    0.018  2.498   -0.465  0.133   -0.954  -0.465  …
boat    2.636   -0.420   1.668  0.120   -0.420  1.043   -0.361  …
train   …
<…>

To get from cov_mat to final_need, I've converted the file to an edgelist via igraph, then eliminated rows of that edgelist that included out-of-category covariance calculations (e.g.,a_planecovaries witha_boat`, but I could care less). Here's the result:
> head(cov_edgelist_slim)

   from      to covariance
a_plane a_plane      4.419
a_plane b_plane      0.018
a_plane c_plane     -0.954
a_plane d_plane      1.100
b_plane a_plane          …
…       …                …

I then try to use dcast() from reshape2, but am getting stuck on how to use the function to produce the final_need result. Any thoughts? If there's a simpler way than the one I'm heading down, I'm happy to hear it!

A: Here is another approach using base R:

*

*Extract the sub-matrix of covariances for each individual vehicle;

*Expand this sub-matrix to a vector;

*Combine the (row) vectors back into a matrix.

The additional code is to get the right column names for final_need based on pasting together the combinations of the prefixes.
## sort row + colnames in alphabetical order
cov_mat <- cov_mat[sort(rownames(cov_mat)), sort(colnames(cov_mat))]

## unique prefix and vehicle names
prefix <- unique(sub("_\\w+$", "", colnames(cov_mat)))
vehicNames <- unique(sub("^\\w+?_", "", colnames(cov_mat)))

## create final_need
final_need <- t(sapply(vehicNames, function(vehic) {
          indices <- grep(vehic, colnames(cov_mat))
          as.vector(cov_mat[indices, indices])
        }))

## add prefix combinations as column names
colnames(final_need) <- levels(interaction(prefix, prefix, sep = ""))

final_need
#>          aa     ba     ca     ab    bb     cb     ac     bc    cc
#> boat  2.636 -0.420  1.668 -0.420 1.043 -0.361  1.668 -0.361 2.290
#> plane 4.419  0.018 -0.954  0.018 2.498 -0.465 -0.954 -0.465 1.791
#> train 2.668  1.040  0.806  1.040 4.153  1.922  0.806  1.922 4.097

EDIT: the same can be done the other way around, i.e. extract the sub-matrix of covariances for each prefix combination and combine their diagonals back into a matrix (by column).
## create final_need by column
final_need <- apply(expand.grid(prefix, prefix), 1, function(i) {
      row_ids <- grep(sprintf("^%s_", i[1]), rownames(cov_mat))
      col_ids <- grep(sprintf("^%s_", i[2]), colnames(cov_mat))
      cov_mat[cbind(row_ids, col_ids)]
    })

## add row + column names
dimnames(final_need) <- list(vehicNames, levels(interaction(prefix, prefix, sep = "")))

final_need
#>          aa     ba     ca     ab    bb     cb     ac     bc    cc
#> boat  2.636 -0.420  1.668 -0.420 1.043 -0.361  1.668 -0.361 2.290
#> plane 4.419  0.018 -0.954  0.018 2.498 -0.465 -0.954 -0.465 1.791
#> train 2.668  1.040  0.806  1.040 4.153  1.922  0.806  1.922 4.097

A: A tidyverse approach could be to bring rownames as column, convert data to long format. Get the first part of string from both column names as well rownames, keep only those rows where both of them match and convert to wide format.
library(tidyverse)

df %>%
  rownames_to_column() %>%
  pivot_longer(cols =-rowname) %>%
  mutate(key = paste0(sub("_.*", "", rowname), sub("_.*", "", name)),
         rowname = sub(".*_", "", rowname), name = sub(".*_", "", name)) %>%
  filter(rowname == name) %>%
  select(-rowname) %>%
  pivot_wider(names_from = key, values_from = value)

# A tibble: 3 x 17
#  name    aa     ab     ac    ad     ba    bb     bc     bd     ca     cb ....
#  <chr> <dbl>  <dbl>  <dbl> <dbl>  <dbl> <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
#1 plane  4.42  0.018 -0.954   1.1  0.018  2.50 -0.465  0.133 -0.954 -0.465
#2 boat   2.64 -0.42   1.67   NA   -0.42   1.04 -0.361 NA      1.67  -0.361
#3 train  2.67  1.04   0.806  NA    1.04   4.15  1.92  NA      0.806  1.92


text:
Q: Two ARP entries if installing MSI first and then a bundle containing the MSI Why do I get two AddRemoveProgram entries if I install the setup.msi first, and then install the bundle.exe containing the setup.msi. Here is the Chain in my bundle.
<Chain>
  <PackageGroupRef Id="NetFx40Redist"/>
  <MsiPackage SourceFile="$(var.MsiProject.TargetDir)Setup.msi" />
</Chain>

The setup.msi has a hard-coded ProductCode that was extracted from the bundle.exe using dark -x. Shouldn't bundle.exe detect the already installed setup.msi and skip the installation?

A: The first entry is for the MSI; the second for the bundle. An MsiPackage element has a Visible attribute that controls whether Burn causes the package to have its own ARP entry visible or not. The default is "no" so in some cases, but not yours, it would result in the two entries.
Yes, Burn does not reinstall packages that are already installed.
Burn is a package manager so it'll always install/uninstall and register/unregister itself. When multiple bundles contain the same packages, Burn figures out which to leave when uninstalling a bundle. Of course, some, like NetFx40Redist, are marked as permanent so the bundle will never uninstall them.
Again, if you'd rather not see an ARP entry for the MSI, be sure to the MsiPackage/@Visible element isn't set to "yes".


text:
Q: Alterar o css de um elemento pelo id eu tentei o seguinte codigo:
$("#maintenanceRequest").css({"backgroundColor": "black"});

Mas aparece o seguinte erro:
Uncaught TypeError: $(...).css is not a function
    at <anonymous>:1:26

O que estou fazendo de errado?
Obrigada

A: Pelo que estou vendo, você está tentando implementar o css em um jquery, o que não é necessário e aconselho a utilizar uma folha de estilo separada do projeto para melhor organização do seu código.
Possíveis soluções:
Se aderir a utilizar uma folha de estilo, seria assim:
#maintenanceRequest{
   background-color: black;
}

ou se quiser estilizar somente no conteúdo (uma
 por exemplo) basta utilizar a tag


text: Q: How do I edit prebuilt Classes in my project I have a dll file that has three classes in it that somebody else built. I was wondering how I  could edit the classes. I know I can because I accidentally had an error with one of them and it took me to the code of that class but not the one I want to edit. I already have permission to edit them. If you can help please do. Thanks in advance.


text:
Q: Intuition behind learning rate scheduling in AdaDelta To get rid of the problems in AdaGrad, the learning rate is changed from $\frac{\eta}{\sqrt{G_{t, ii}+\epsilon}}$ to include only gradients in a small window size $w$. But as the function approaches the optimal value, won't the denominator become small in the case of AdaDelta because the gradients become small?
Isn't this opposite to the intuition of decreasing the learning rate as the function approaches the optimal value which is followed in other learning rate scheduling techniques?

A: According to the original paper - ADADELTA: An Adaptive Learning Rate Method (and sticking to the notation in the paper), the update rule is:
$$x_{t+1}=x_{t}+\Delta x_{t}$$while $f(x)$ is the function we try to minimize, $x_k$ is its parameter at the $k$-th iteration, and $\Delta x_{t}$ is given by:
$$\Delta x_{t}=-\frac{\text{RMS}\left[\Delta x\right]_{t-1}}{\text{RMS}\left[g\right]_{t}}g_{t}$$
while:

*

*The operations on vectors are entrywise (as in ADAGRAD).

*$\text{RMS}\left[\Delta x\right]_{t-1}=\sqrt{E\left[\Delta x^{2}\right]_{t-1}+\varepsilon}$ is an exponentially decaying root mean square of $\Delta x_{t-1},...,\Delta x_{t-w}$. (And $\varepsilon$ is an hyperparameter.)
Note that the algorithm (see image below) doesn't have any $w$ explicitly in it - it is implicitly determined by the decay constant hyperparameter $\rho$, as $w$ is the lowest natural number such that multiplying a sane value by $\rho^w$ results in a negligible value.)

*$g_{t}$ is the gradient at $x_t$ (it is an approximation, as this is an SGD algorithm, but I would refer to it as "gradient", as everyone does)

*$\text{RMS}\left[g\right]_{t}=\sqrt{E\left[g^{2}\right]_{t}+\varepsilon}$ is an exponentially decaying root mean square of $g_{t},...,g_{t-w+1}$.

Finally, let's talk about your question.
Section 4.3 in the paper explains that when the algorithm approaches the optimal value, both the gradients and the $\Delta x$ values become smaller and smaller.
Consequently, $E\left[g^{2}\right]_{t}$ and $E\left[\Delta x^{2}\right]_{t-1}$ both become much smaller than $\varepsilon$, and so $$\frac{\text{RMS}\left[\Delta x\right]_{t-1}}{\text{RMS}\left[g\right]_{t}}=\frac{\sqrt{E\left[\Delta x^{2}\right]_{t-1}+\varepsilon}}{\sqrt{E\left[g^{2}\right]_{t}+\varepsilon}}$$ approaches $1$, i.e. the learning rate approaches $1$.
This is not as bad as the learning rate getting uncontrollably larger, but the authors of the paper admit that $1$ might be a relatively high learning rate. Thus, they conclude that adding an annealing schedule to ADADELTA might be a good idea.

For your convenience, here is an image of the algorithm from the paper:


text:
Q: Writing a GeoTIFF file that is rotated with respect to a projected coordinate system using Matlab's Mapping Toolbox I've been prototyping some processing techniques for SAR images in Matlab.  This requires importing a GeoTIFF file, and then exporting a file with modified data but the same spatial reference.  I have no issue importing the GeoTIFF file, but when I try to write a GeoTIFF file using the code:
    [input_data, reference] = geotiffread(filename);
    info = geotiffinfo(filename;
    geotiffwrite('output.tif', output_data, reference, 'GeoKeyDirectoryTag', info.GeoTIFFTags.GeoKeyDirectoryTag');

Matlab throws up the following error:

Error using geotiffwrite (line 257)
  The referencing matrix or object supplied to
  function GEOTIFFWRITE specifies that the
  associated raster is rotated or skewed with
  respect to the projected coordinate system.
  Function GEOTIFFWRITE does not support this
  geometry.

It appears that this is caused by the fact that my image is rotated within a UTM coordinate system.  I'm not entirely sure why this would be an issue, given that I experienced no issues with reading the data into Matlab.  I was wondering if anyone knows of any way to resolve this issue or work around this apparent constraint.
UPDATE:
I've tried using Matlab's mapshow function to display my data (I've previously only displayed the image data without georeferencing).  This results in the following figure:

This figure is also not rotated with respect to its UTM coordinate system, which suggests that Matlab isn't accounting for the rotation in its map display functions as well.
SECOND UPDATE:
I've taken a look through the GeoTIFF tags in Matlab, and it does seem that the data needs to undergo an affine transformation, which is where my issue seems to be coming from.  So the transformation is defined in the GeoTIFF file I'm reading into Matlab.  I'm not sure why Matlab can't just copy the tags defining the transformation into the output file, but at the moment, I am exploring two possibilities:

*

*Applying the affine transformation in Matlab, padding it with nodata values, and then saving the transformed data in the GeoTIFF format.  This would require changing some of the other data tags before saving the data.

*Using GDAL to copy the metadata of my imported GeoTIFF file to produce the desired GeoTIFF file.


text:
Q: Get user only posts from wall feed (stream table) in Facebook API I want to get a user's posts in their wall, and I want to limit the number of records I get. I'm doing so using this query:
SELECT post_id, message, attachment, type, place, updated_time FROM stream WHERE source_id = me() AND actor_id = source_id AND type IN (46, 80, 128, 247) LIMIT 10
So far so good. The problem with this is that if I have a total of, for example 100 posts, and in the first 10 I have 5 that meet the ends of my query, when I put LIMIT 10 I only get those 5 results, because the LIMIT filter is applied on the first query conditions, and not on the total results from that table.
As a temporary workaround I changed my query to this: SELECT post_id, message, attachment, type, place, updated_time FROM stream WHERE post_id IN (SELECT post_id FROM stream WHERE source_id = me() AND actor_id = source_id AND type IN (46, 80, 128, 247) LIMIT 100) LIMIT 10
But this isn't bulletproof, since I am only expanding my possible list of wanted results so I have a higher number to select from.
So, how could I query the wanted results?


text: Q: Can I convert a .Net 4.x project/solution to .Net 6 in place I have a WinForms VB app using .NET 4.x and would like to convert to .NET 6.x. I've seen the "oh, just create a new project/solution" answer. Well, that's easier said than done for me, since my work in .NET is limited. I'm not sure why an existing project can't be converted instead of creating a whole new project/solution. I have tried that but it complains about not having various libraries/assemblies/whatever. It seems that with the app.config and various other config files, MS could create a tool to modify those appropriately instead of someone creating a whole new project/solution. Do they not know what is in their own files? Is upgrading a project/solution so difficult that the only way to do it is to start over?


text:
Q: File Not Updating in Laravel I have Laravel 5.5 Application. I am trying to update my post and image is not updating. When I die and dump the following
dd($request->hasFile('image'));

it outputs false
View:

    {{ Form::model($slider, array('route' => array('admin.slider.update', $slider->title), 'method' => 'PUT')) }}

            {!! Form::label('title', 'Title') !!}
            {!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}

            {!! Form::label('content', 'Content') !!}
            {!! Form::textarea('content', null, ['class' => 'form-control', 'placeholder' => 'Content']) !!}

                    {!! Form::label('image', 'Change Image') !!}
                    {!! Form::file('image') !!}

                image )}}" class="img-responsive" width="150">
                {{ $slider->image }}

        {!! Form::submit('Submit', array( 'class'=>'btn btn-info' )) !!}
    {!! Form::close() !!}

Controller:
 public function sliderupdate($slider, Request $request){
    $slider = Slider::where('title', $slider)->firstorfail();
    $slider->title = $request->title;
    $slider->content = $request->content;
    dd($request->hasFile('image'));
    if ($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        $name = $timestamp. '-' .$file->getClientOriginalName();
        $file->move(public_path().'/images/slider/', $name);
        $slider->image = $name;
        $thumb = Image::make(public_path().'/images/slider/' . $name)->resize(1920,1080)->save(public_path().'/images/slider/thumb/' . $name, 90);
    }

    $slider->save();
    return redirect()->route('admin.slider.edit', $slider->title)->with('status', 'Update Success');
}

Route:
Route::put('admin/slider/{slider}', [
    'uses'  =>  'AdminController@sliderupdate',
    'as'    =>  'admin.slider.update'
]);

Something I am missing, but couldn't find out what it is.

A: You are missing the 'files' => true option. You need files option in the array passed to Form::open or Form::model if you are going to accept files.
{{ Form::model($slider, [
    'route' => ['admin.slider.update', $slider->title],
    'method' => 'PUT',
    'files' => true
]) }}

A: Method:
public function slideredit($slider){
    $slider = Slider::where('title', $slider)->firstOrFail();
    return view('admin.slider.edit', compact('slider'));
}

Change your Form to
{!!  Form::model($slider, ['route' => ['admin.slider.post', $slider->title, 'method' => 'PUT', 'files'=>true]])  !!}

      {!! Form::label('title', 'Title') !!}
      {!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Title']) !!}

      {!! Form::label('content', 'Content') !!}
      {!! Form::textarea('content', null, ['class' => 'form-control', 'placeholder' => 'Content']) !!}

      {!! Form::label('image', 'Choose Image') !!}
      {!! Form::file('image') !!}

    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
    {!! Form::submit('Submit', array( 'class'=>'btn btn-info')) !!}

{!! Form::close() !!}


text:
Q: VerifyError when creating an instance of XSSFWorkbook I am using poi-3.7.jar.
I am getting
java.lang.VerifyError: org/apache/poi/xssf/usermodel/XSSFWorkbook

When I am trying to read XSSFWorkbook.
Workbook myWorkBook = new XSSFWorkbook(myInput);

What could be the reason for that?

A: From the Apache POI Components page

Component - Description - Artifact
XSSF - Excel XLSX - poi-ooxml

In order to be able to use XSSF, you need both the poi jar and the poi-ooxml jar, plus their respective dependencies (as detailed on the components page). The main poi jar doesn't have XSSF and friends in it.
Additionally, POI 3.7 is rather old, you'll really want to upgrade to a newer version (eg 3.10.1 or 3.11 beta 2, as of writing)


text:
Q: Is "No significant evidence for $X$" the same as "(Significant?) evidence for (Not $X$)"? In statistical Hypothesis testing, let's say we are testing for a change in a test statistic, for example, the change in proportion of the population that are over 45 years old, although the test statistic could be anything. The test is done from a sample of the population, and the sample proportion is compared to the known proportion of the population.
Let's say the conclusion of the hypothesis test is, "there is no (significant) evidence to support the claim that the proportion of the population that are over $45$ years old has changed". My question is, is this the exact same as saying, "There is (significant?) evidence that the proportion of the population that are over $45$ years old has not changed" ? Or what about, "There is (significant?) evidence that the proportion of the population that are over $45$ years old has not changed by much" ?


text:
Q: show that $\sin{f(n+1)}\ge \sin{f(n)},\forall n\in N $ let $f:N^{+}\to N^{+}$, and such
$$\sin{(f(n))}=\max\{\sin{x}|x\in N^{+},10^{n-1}\le x<10^n,n\in N^{+}\}$$
show that
$$\sin{f(n+1)}\ge \sin{f(n)},\forall n\in N $$
I feel like the problem starts with the density of the sequence?Or consider him in stages

A: Here is a start:
First, define $g(n) = \sin(f(n))$, so $$g(n) = \max\{\sin x\mid x \in \Bbb N, 10^{n-1} \le x < 10^n\}\quad \forall n \in \Bbb N^+$$
and what you want to show is that $g(n+1) \ge g(n), \forall n \in \Bbb N^+$. That removes the first needless complication in the problem statement. There is nothing here that requires $f$ itself, which - unlike $g$ - is not even well-defined by the condition.
Next, note that within $[0,2\pi]$, if $\left|x_1 - \frac\pi 2\right| < \left|x_2 - \frac\pi 2\right|$, then $\sin x_1 > \sin x_2$. So $$g(n) = \sin \left(\underset{10^{n-1} \le x <10^n}{\arg \min}\left|x\bmod 2\pi - \frac \pi 2\right|\right)$$
So, the condition $g(n + 1) \ge g(n)$ holds if and only if there is some integer between $10^n$ and $10^{n+1}$ which is at least as close to a $4k+1$ multiple of $\frac \pi 2$ as any integer between $10^{n-1}$ and $10^n$.


text:
Q: PostgreSQL equivalent of MySQL query variables? Is there a straightforward way to adapt these types of MySQL queries to PostgreSQL:

*

*setting variables in MySQL like
set @aintconst = -333
set @arealconst = -9.999

It seems not.

*Assigning variables from SELECT queries and using those variables subsequently in my SQL like:
 select @pfID := id from platform where bios like '%INTEL%'
 select @clientID := id from client where platformID = @pfID

I'd be very grateful for pointers, especially on (2).

A: PSQL Variables
Since at least version 7.1 PostgreSQL's client has provided this functionality with psql variables
\set aintconst  -333
\set arealconst -9.999

SELECT :aintconst AS aintconst, :arealconst AS realconst;
 aintconst | realconst
-----------+-----------
      -333 |    -9.999
(1 row)

Essentially what you want is the ability to script SQL. PSQL has a conditionals and variables, and the ability to feed back dynamically generated SQL which makes this job easier. This isn't server-side functionality in the PostgreSQL world, and generally I would do this in a client language (like Node.js or Perl rather than in psql).

A: You already answered this yourself: No, there isn't in plain SQL. You can use PL/PgSQL if you want variables, in a function or a DO block.
Most of the uses for query variables in MySQL are satisfied by CTEs (WITH queries), window functions, etc in PostgreSQL.

Well, actually there is, but they're not suitable for general use within queries. You usually access custom GUCs with SET and SHOW, but you can instead use:
regress=> select set_config('a.b', 'c', false);
 set_config
------------
 c
(1 row)

regress=> select current_setting('a.b');
 current_setting
-----------------
 c
(1 row)

GUCs are expensive and it's a bad idea to use this for general purpose queries, but there's very occasionally a valid use. You can only use settings like myapp.variable, too.

A: This is easy to do inside a PL/pgSQL function (or a DO block):
create function myfunc() returns void language plpgsql as $$
  declare
    aintconst constant int = -333;
    arealconst constant real = -9.99;
    pfid int;
    clientid int;
  begin

    select id from platform where bios like '%INTEL%' into pfid;

    select id from client where platformID = pfid into clientid;

  end $$;

You can also use GUC variables:
--set a session variable
set mycustom.var = 'value';

--use it
select * from mytable where some_column = current_setting('mycustom.var');

Or you can use a CTE with a join:
with myvars as (
  select
    -333::int as aint,
    -9.99::real as areal
)

select
  a.*
from mytable a
join myvars on true
where
  a.thing = aint

A: I use WITH statements:
WITH vars as (SELECT -333::double precision as aintconst,-9.999::double precision as arealconst)
UPDATE table SET col1 = (SELECT aintconst FROM vars)

and:
WITH platformx AS (SELECT id FROM platform WHERE bios like '%INTEL%')
SELECT id FROM client WHERE platformID = (SELECT id FROM platformx)

A: For the second example you don't need a variable (neither in MySQL nor in Postgres):
select id
from client
where platformID in (select id
                     from platform
                     where bios like '%INTEL%');

Don't be afraid of sub-queries, Postgres' query optimizer is much smarter than MySQL's.
If the above is too slow, rewriting it into an exists query is sometimes faster:
select c.id
from client c
where exists  (select 1
               from platform p
               where c.platformID = p.id
                 and bios like '%INTEL%');


text:
Q: How to set example for Vector[SomeTrait] in swagger model The api request looks like -
case class SomeRequest(@ApiModelProperty(example = "FirstOption") options: Vector[Option])

sealed trait Option {
  def name: String
}

object Option {

  case object FirstOption extends Option {
    override val name: String = "FirstOption"
  }

}

When example is not set for the parameter, the model is like -
{
  "options" : [
     "string"
  ]
}

and when value is set in example then
{
  "options" : "FirstOption"
}

whereas it should be
   {
      "options" : [
         "FirstOption"
      ]
    }

Have same issue when setting example for Seq[String].
These are the project dependencies.

How can we create the model properly ?

A: Changed to look into a yaml file for model, than setting annotations. Worked perfectly!


text:
Q: Image pixel relocation I have a n x m x 3 matrix where the current locations relate to the source the image came from. I'm trying to map the image to another source. The image is of size n x m and I have the spacial x and y positions of the pixel in the first and second layer respectively, and the intensity value of the pixel in the 3rd layer. I need to somehow reorganize the pixels and display them according to the spatial locations stored in the first two layers.
This means that in img(i,j,:) I have the x position, the y position, and the gray scale pixel value.
Is there any way to go about doing this?

A: i'm not sure i got you right.
1- Get min and max x on the first layer
2- Get min and max y on second layer
3- Get min and max intensity on third layer
4- Create an image large enough too handle all x,y,intensity.
   (this might involve translating / scaling if you have constraints on your image size)
5- then draw all (x,y,i) in your image.


text:
Q: Ionic 3 How to ensure db data fetched before view is loaded I'm using token based authentication and token is already saved on DB.
When app starts, I need to fetch the token from DB and make it available before making API calls.
What is best way to do it:
In Component:
ngOnit() {
storage.get('token').then((val) => {
    Make api call here
});
}

Or in shared service:
getToken() {
    return Promise((resolve, reject)=>{
       #if fetched once save in local var and resolve token
       #or fetch from DB and resolve token
    })
}

// On Component
this.sharedService.getToken().then((token)=>{
  //Make api call
}

Is there any way I can ensure the DB token is fetched and store in shared services before view is loaded? The storage.get is a 'ES6 promise'
Concern is responsibility of loading token before loading view is escalated to any bootstrapping event, so onViewLoad doesn't needs to be defined in each component.

A: I have implemented above use case in this way.
I have created ApiService for CRUD like below.That code is self-explanatory and if you need more info please let me know.
api-service.ts
import { Injectable, } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Headers, RequestOptions, BaseRequestOptions } from '@angular/http';
import { Storage } from '@ionic/storage';
import { Events } from 'ionic-angular';

@Injectable()
export class ApiService {

    constructor(private http: Http, private storage: Storage, private events: Events) { }

    createHeader(headers: Headers) {
        return new Promise((resolve, reject) => {
            this.storage.get('loggedInUser')
                .then((token: any) => {
                    if (token) headers.append('Authorization', 'token ' + token.token);
                    resolve(headers);
                }, err => {
                    resolve(headers);
                });
        });
    }

    get(api) {
        let header = new Headers();
        return Observable.fromPromise(this.createHeader(header))
            .map(() => {
                let options = new BaseRequestOptions();
                options.withCredentials = true;
                options.headers = header;
                return options
            })
            .switchMap((options) => this.http.get(api, options))
            .catch((err: Error | Response) => {
                if (err instanceof Response && err.status === 401) {
                    this.events.publish('token-expiration');
                }
                return Observable.throw(err);
            });
    }

    post(url, params): Observable<any> {
        return new Observable(observer => {
            let header = new Headers();
            this.createHeader(header)
                .then(() => {
                    let options = new RequestOptions({ headers: header });
                    this.http.post(url, params, options)
                        .subscribe(response => {
                            observer.next(response);
                            observer.complete();
                        }, (e) => {
                            observer.error(e);
                        });
                })
        })
    }

    delete(url) {
        return new Observable(observer => {
            let header = new Headers();
            this.createHeader(header)
                .then(() => {
                    return this.http.delete(url, { headers: header, withCredentials: true })
                        .subscribe(response => {
                            observer.next(response);
                            observer.complete();
                        });
                })
        });
    }

}

Here I have created loggedInUser storage when the user logged into the app.It is also a provider as shown below.
social-login.ts
import { Injectable } from '@angular/core';
import { ApiService } from "../providers";
import { LocalCacheServiceProvider } from "../local-cache-service/local-cache-service";
import { UserService } from "../user-provider";
import { Storage } from '@ionic/storage';

@Injectable()
export class SocialLoginProvider {

  constructor(private apiService: ApiService, private localCacheService: LocalCacheServiceProvider, private userService: UserService, private storage: Storage) {
  }

  //login To App
  loginToApp(url: string, data: string) {
    this.apiService.post(url, { access_token: data })
      .map((res: any) => res.json())
      .subscribe(res => {
        this.setUserLocally(res);
      });
  }

  //set User Locally
  setUserLocally(user) {
    this.localCacheService.clearAllKeys().then(() => {
      this.userService.setLoggedInUser(user);
      this.storage.set('loggedInUser', user);
    });
  }
}

After that, I can consume above service (i.e. ApiService) through any of my provider (for CRUD operations) as shown below.
This is the ArticleService.
article-service.ts
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { config } from '../config/config';
import { ApiService } from './api-service';

@Injectable()
export class ArticleService {

    constructor(private apiService: ApiService) {
    }

   getBookById(id) {
        return this.apiService.get(`${config.getBookById}${id}/`).map((res: any) => res.json());
    }
}

Above approach works perfectly fine for me.Hope this approach will help you too.If you need more help please let me know.


text:
Q: Form validation using RegEx for dynamically added controls I am using the Jquery Validation Plugin to validate the webform.
The controls are loaded dynamically depending on the control type. For some controls I need to validate using regular expressions. I need to pass in the RegEx dynamically for each control.
I have the following function but how do I generalise it for all controls that need to be validate using RegEx
            $.validator.addMethod(varcharRegEx, function (value, element) {
              return this.optional(element) || /^[A-Za-z0-9\_]+$/i.test(value);
             }, "Invalid entry, must contain only letters, numbers, or underscore.");

Second is there a way to show the error messages as a summary at the end of the form.
I am a newbie to Jquery. Please help

A: Add a custom data attribute to your controls and populate it with your RegEx. Then you can read that value in the validation function and apply it.
I.e. "decorate" your controls that need validation with some css class, something like:
<input id="control_1" class="to-validate"
     data-regex="^[A-Za-z0-9\_]+$"
     data-error-message="Invalid entry, must contain only letters, numbers, or underscore." />

Then in jQuery attach validators to each:
$(".to-validate").each(function(index, myControl) {

    var regex = $(myControl).data("regex");
    var errorMsg = $(myControl).data("error-message");
    var validatorName = $(myControl).attr("id");

    $(myControl).validator.addMethod(validatorName, function(value, element) {
        return this.optional(element) || new RegExp(regex).test(value);
    }, errorMsg);
});

I have not tested this code, so you might need to adjust it a bit for your exact needs, but I hope this gives you an idea.


text:
Q: Convert smalldatetime datatype to string. "String was not recognized as a valid DateTime" error In my database I've got smalldate data type which look like this: "2014-09-01 19:00:00".
I am trying convert this string to date:
DateTime data2 = DateTime.ParseExact(obiekt.PelnaData, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

I have tried this:
string query = "Select *, Convert(nvarchar, DataMeczu, 104) as formatData, Convert(nvarchar, DataMeczu, 114) as formatData2, Convert(nvarchar, DataMeczu, 120) as formatData3 From MyTable Where MyVar = @MyVar";

SqlDataReader rdr = com.ExecuteReader();
while(rdr.Read())
{
    TerminarzeLigaModel terminarz = new TerminarzeLigaModel();
    terminarz.PelnaData = rdr["formatData3"].ToString();

    or this version:

    string dataA = rdr["formatData"].ToString();
    string dataB = rdr["formatData2"].ToString();
    terminarz.PelnaData = dataA + " " + dataB;
}

but every time I receive this error: "String was not recognized as a valid DateTime". I dont know what I am doing wrong. If I paste the date from the database into a variable:
string dataExample = "2014-09-01 19:00:00";
DateTime data2 = DateTime.ParseExact(dataExample, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

than it works fine. Could You tell what is wrong ?

A: Seems like you're trying to set a string on a DateTime field:
terminarz.PelnaData = rdr["formatData3"].ToString();

The code line where you show the conversion is not inside your while loop, and it works just fine.
Try replacing the line above with:
terminarz.PelnaData = DateTime.ParseExact(rdr["formatData3"].ToString(), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

If it still fails, debug and check the actual value of rdr["formatData3"].

A: This looks like an international issue. Can you debug and see what "formatData3" is returning, is it in yyyy-MM-dd HH:mm:ss or any other format or is a valid month coming back?
That might be your issue.


text:
Q: .htaccess 301 redirection removing white space My site link is containing name with lots of white space in parameter.
file.php?dir=Songs/Bollywood%20Mp3/I%20Dont%20Luv%20U-2013
file.php?dir=Songs/Bollywood%20Mp3/Go%20Goa%20Gone-2013
file.php?dir=Songs/Bollywood%20Mp3/Hum%20Hai%20Raahi%20Car%20Ke-2103

Songs/Bollywood Mp3 are the directory which contain files.
I want to generate friendly url by removing white space between directory name.
Any suggestions?


text:
Q: How to call callback after n epochs but always in the last epoch of training? I want to call a callback after n epochs, but always in the last epoch of training. Here explains how I can call the callback after n epochs.
At the moment I am using the following approach:
class MyCallBack(keras.callbacks.Callback):

    def on_epoch_end(self, epoch, log=None)

        if epoch % 10 == 0:  # <- add additional condition here
            self._do_the_stuff()

    def _do_the_stuff(self):
        print('Do the stuff')

    def on_training_end(self, logs=None):
        self._do_the_stuff()

Is there a simpler way where I add an additional condition to the if statement inside on_epoch_end and don't need on_training_end?

A: As suggested by @Ewran in the comments above, it is possible to access the total number of epochs by `self.params['epochs'].
class MyCallBack(keras.callbacks.Callback):

    def on_epoch_end(self, epoch, log=None)

        if epoch % self.epoch_freq == 0 or epoch == self.params.get('epochs', -1):
            self._do_the_stuff()

    def _do_the_stuff(self):
        print('Do the stuff')

    def on_training_end(self, logs=None):
        self._do_the_stuff()

If other callbacks such as tf.keras.callbacks.EarlyStopping are used, I would continue to use the approach with on_train_end. Otherwise it is not guaranteed that the callback is called after the last epoch.


text:
Q: Defining primary key in spark JDBC write I have a requirement to set a particular column as primary key while writing a dataframe from pyspark to sql using jdbc.
Tried using the function 'createTableColumnTypes'
# Calling the action and writing the results to SQL DB
result.write \
    .format("jdbc") \
    .mode("overwrite") \
    .option("url", jdbcUrl) \
    .option('createTableColumnTypes', 'KEY_IDENTIFER_COLUMN VARCHAR(255) NOT NULL PRIMARY KEY') \
    .option("dbtable","test") \
    .option("user", db_username) \
    .option("password", db_password) \
    .save()

It fails with an error. Any solutions on how this can be done?
Thanks in advance.


text:
Q: PostGIS servers to increase power I am currently working locally on my terminal.
I have Windows 10 x64, 12Go RAM, 428Go SSD, an Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz, 2400 MHz, 2 hearts.
I need to use PostGIS to make some queries and filter my data.
My database contains 39 tables. My biggest table has 4 millions rows.
I run some cross join with my tables.
The trouble I have is that my queries are taking too much time (maximum query took 6h and returned only null values).
I developed a Python script to split my queries and run them each by each instead of all of them in a row, but it also failed.
So I am looking for a way to have more power. I have understood so far that I should use a server to do this, but I do not know any server or service of this kind.
UPDATE 1:
I have created the indices for all my tables. Then I ran the query creating the most trouble, which is:
UPDATE table_1
SET field_1 = liste.my_bool
FROM(
    SELECT T1.id AS name,
        bool_or((ST_Contains(T2.geom, T1.geom) OR ST_Overlaps(T1.geom, T2.geom))) AS my_bool
    FROM table_1 AS T1
    CROSS JOIN table_2 AS T2
    GROUP BY T1.id
 ) AS liste
WHERE table_1.id = liste.name;

The table_1 has 52630 entities and the table_2 2025.
The query returned null values for my field_1 after one hour of loading. I then tried the subquery only and got this error message:
ERROR:  ERROR:  could not write the block 8568766 from temporary file : No space left on device
SQL state: 53100

I want field_1 to be True if the geometry of table_1 shares total or partial surface with any entity of table_2. This is why I need a CROSS JOIN.

A: Building on what @JohnPowell said in the comments, you can make a join that is based on a spatial intersection. If you have a spatial index setup, this should have much better performance than a cross join. If you do not have a spatial indexes, you can create them directly in PostgreSQL using SQL or use the QGIS DB Manager to create them with a GUI.
Example related to the table names in your question:
SELECT DISTINCT T1.id AS name,
       True::boolean AS my_bool
    FROM table_1 AS T1
    JOIN table_2 AS T2
       ON ST_Intersects(T1.geom, T2.geom)


text:
Q: How to solve logical vector "TRUE" in R? The question is: How many households live in area 2, earn more than 20k, and have purchased more than 30 units of pasta over the whole time period?
I tried
pasta  %>%
  filter(AREA=="2") %>% group_by(HHID) %>%
  summarise(buy2= sum(PASTA), INCOME) %>%
  summarise(income2 = INCOME > "20000" && buy2 > "30")

# run and show
  `summarise()` has grouped output by 'HHID'. You can override using the `.groups` argument.
  A tibble: 403 x 2
    HHID income2
   <int> <lgl>
 1    10 TRUE
 2    16 TRUE
 3    17 FALSE
 4    29 TRUE
 5    30 FALSE
 6    31 FALSE
 7    36 TRUE
 8    42 FALSE
 9    47 TRUE
10    60 TRUE
# … with 393 more rows

How can I count the 'TRUE'?

A: If we need to count the logical, use sum.  In addition, replace the && with & and remove the quotes around the numeric values
...
 summarise(Count = sum(INCOME > 20000 & buy2 > 30, na.rm = TRUE),
        .groups = 'drop')