Why does d-prime of average hit and false alarm rates differ from the average d-prime of individual cases?

Question: I'm reporting d-prime for a set of IDs. After setting a dprime() function, I use it to compute d-prime for each ID based on their hit and false alarm rates, saved as a new variable (d). I checked that the d-prime being given for each ID is correct.
I then need to report average d-prime for all IDs. I would also like to report mean hit and false alarm rates.
Using mean() for the new d variable, I get the value of 2.36.
Using mean() for the hit.rate variable, I get the value of 0.4496053.
Using mean() for the fa.rate variable, I get the value of 0.07.
After looking at this values, I was surprised that the mean d-prime was as high as it was. If I use my dprime() function on average hit and FA rates, then I get a dprime value of 1.349132.
Am I missing something about the way that d-prime works?? I'm very surprised by this. If average d-prime should only be taken when computed from individual cases first, and not after getting an average hit and FA rate, is it bad practice to be reporting these response rates?
Thanks so much for your help!!
data = structure(list(id = structure(1:20, .Label = c("8001", "8002",
                                           "8003", "8004", "8005", "8006", "8007", "8008", "8009", "8010",
                                           "8011", "8012", "8013", "8014", "8015", "8016", "8017", "8018",
                                           "8019", "8020", "8101", "8102", "8103", "8104", "8105", "8106",
                                           "8107", "8108", "8109", "8110", "8111", "8112", "8113", "8114",
                                           "8115", "8116", "8117", "8118", "8119", "8120"), class = "factor"),
           hit.rate = c(1, 0.121052631578947, 1, 0.421052631578947,
                        0.65, 0.613157894736842, 0.478947368421053, 0.178947368421053,
                        0.268421052631579, 0.394736842105263, 1, 0.0184210526315789,
                        0.218421052631579, 0.331578947368421, 0.144736842105263,
                        0.231578947368421, 0.523684210526316, 0.689473684210526,
                        0.436842105263158, 0.271052631578947), fa.rate = c(1, 0,
                                                                           0, 0, 0, 0, 0, 0, 0.0425, 0, 0, 0.00249999999999995, 0.01,
                                                                           0, 0.015, 0, 0.155, 0, 0.05, 0.125)), .Names = c("id", "hit.rate",
                                                                                "fa.rate"), row.names = c(NA, -20L), class = "data.frame")

# set d' function
# Correction applied according to MacMillan & Kaplan, 1985
dprime <- function(hit, fa, n_targets, n_lures) {
  hit = ifelse(hit == 0, 1/(2*n_targets), hit)
  hit = ifelse(hit == 1, 1-(1/(2*n_targets)), hit)
  fa = ifelse(fa == 0, 1/(2*n_lures), fa)
  fa = ifelse(fa == 1, 1-(1/(2*n_lures)), fa)

  qnorm(hit) - qnorm(fa)
}

# add d' column to the data for each ID
data$d = dprime(data$hit.rate, data$fa.rate, 380, 400)
mean(data$d) # mean d' is 2.362759

# get mean hit and FA rates
mean.hit = mean(data$hit.rate) # mean hit.rate for all IDs is 0.4496053
mean.fa = mean(data$fa.rate)   # mean fa.rate for all IDs is 0.07
dprime(mean.hit, mean.fa, 380, 400) # d' is now 1.349132

Answer: d' is transforming from one space to another. The averages of transformed spaces won't be the same as the average of untransformed space that is then transformed.
Consider as a toy example you had one ID with a false alarm rate very close to zero. The qnorm will approach negative infinity! That's definately going to pull your average of d' much more than averaging the FA then including that in a d".
Your last question is a big "it depends". I lean towards d' at the ID level and then summarizing that. However, your milage may vary.


How to prevent nginx redirecting from HTTPS to HTTP on AWS?

Question: I have a website served by nginx behind an AWS ELB Load Balancer. Only HTTPS is enabled on the load balancer.
Requesting individual files, or directories with a trailing slash, work fine. However, requesting directories without a trailing slash don't work.
The reason is, when I request the directory without the trailing slash, nginx does a redirect to the path with the trailing slash (that's OK), but it also changes from HTTPS to HTTP. The load balancer is configured to only allow HTTPS, so that doesn't work (timeout).
On the nginx logfile, I can see that the request reaches nginx, and that it's nginx that responds with the 301 Permanent Redirect (so it's not e.g. a problem with the load balancer setup).
10.100.10.15 - - [24/Nov/2017:15:41:08 +0000] "GET /admin HTTP/1.1" 301 178 "-" "Wget/1.18 (darwin16.0.0)"

When I request the URL via curl I see the redirect:
$ curl -v https://example.com/admin
*   Trying 188.8.131.52...
* TCP_NODELAY set
* Connected to example.com (18.104.22.168) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: example.com
* Server certificate: Amazon
* Server certificate: Amazon Root CA 1
* Server certificate: Starfield Services Root Certificate Authority - G2
> GET /admin HTTP/1.1
> Host: example.com
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Date: Mon, 27 Nov 2017 09:19:05 GMT
< Content-Type: text/html
< Content-Length: 178
< Connection: keep-alive
< Server: nginx
< Location: http://example.com/admin/
< X-UA-Compatible: IE=Edge
<

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx

* Connection #0 to host example.com left intact

My nginx config file is just
server {
    root /var/www;
}

The /etc/nginx/nginx.conf is here.
I have tried server_name_in_redirect off but it did not make any difference.
I would like to avoid putting the hostname in the config file, because this is packed into a Docker image which is then deployed on different hosts (QA, Prod, etc.).
I would like nginx to do this redirect, but stay on HTTPS. What can I do?
Comment: Have you tried `absolute_redirect off;`?
Comment: @RichardSmith - That command failed with `nginx: [emerg] unknown directive "absolute_redirect"` I googled for it in case it was misspelt but I couldn't find anything. Did you mean another command?
Comment: That directive is available from `nginx` version 1.11.8 onwards. It would mitigate the problem by removing the scheme and domain name from the HTTP Location header.
Comment: @RichardSmith - Please write this as an answer, then we can discuss it there.
Comment: I have tried now with nginx/1.13.7 with that command but it makes no difference. I've also tried writing `server_name_in_redirect foo` and indeed it delivers an error, leading me to think the command is not being ignored. I still get `Location: http://example.com/admin/` (i.e. http not https) in the 301 response.
Comment: @RobinSalih - yes, that's what I'm doing, I think that's why nginx believes the client is requesting the resource through HTTP, and thus redirecting to HTTP.
Answer: The best place to fix the problem is where the SSL connection is terminated. If it was running nginx, you would use a proxy_redirect statement to map http to https in the Location header. I don't know AWS ELB so cannot comment on how to fix it there.
Certain circumstances causes nginx to respond with a redirect, and it assumes that the scheme is the same as the scheme used to connect to it (i.e. from AWS ELB). AFAIK there are three ways to mitigate the problem in the back-end nginx server.

1) From version 1.11.8 onwards, the absolute_redirect off; statement will cause the Location header to use a relative URL, which means that the scheme and domain name are missing.
server {
    absolute_redirect off;
    ...
}

See this document for more.

2) Inhibit the behaviour of appending a trailing / to directories by using a try_files statement:
server {
    root /path/to/files;

    location / {
        try_files $uri =404;
    }
    ...
}

See this document for more.

3) Fix the problem with an explicit return statement.
server {
    root /path/to/files;

    location ~ [^/]$ {
        if (-d $request_filename) {
            return 302 https://$host$uri/$is_args$args;
        }
    }

    location / {
    }
    ...
}

See this document for more, and this caution on the use of if.
Comment: jeez, absolute_redirect off is my lifesaver, thanks a lot
Comment: With Chrome 86 (October 2020) an unnoticed https to http redirect can now trigger an "insecure form" page. Having a redirect to https on your loadbalancer does not save you too, because https to http to https will still trigger the warning page on the first redirect. This answer is very helpful to prevent that from happening for nginx servers behind a reverse proxy. `absolute_redirect off` is a saver.
Comment: `absolute_redirect off` did the job for me, thanks!
Answer: Try this
server {
  root /var/www;
  include /etc/nginx/basic.conf;
  try_files $uri $uri/;
}

If it doesn't work please edit your question to include whatever's in basic.conf and nginx.conf. Also do a curl showing the problem, including the response headers and the single corresponding Nginx access log file.
Comment: I have updated my question to include the `nginx.conf`, and removed the `basic.conf` from my config and my question as it didn't make any difference. I added `curl` information to my question. I tried your suggestion, alas when ELB requested "/" it showed `rewrite or internal redirection cycle while internally redirecting to "////////////"`. Thanks in advance for your help.
Answer: You can try to use a "evil if" sentence:
server {
    ...
    if ($http_x_forwarded_proto = 'http' ) {
        rewrite ^ https://$host$request_uri? permanent;
    }
    ...
}

Answer: Not tested on AWS, however I solved with this line in each location block:
proxy_redirect ~^http:(.*)$ https:$1;


Data not being visible in CSV file

Question: I am trying to open .csv file but when I open it Iam not getting any data but only getting headers.

The below is the module file for that particular csv file.The file getting downloaded but when I open the file only headings being visible but not the data.

<?php

define('BIOTWEAKS_AU_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:4;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');
define('BIOTWEAKS_NZ_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:6;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');

function biotweaks_menu() {
  $items = array();

  $items['admin/upload-product-csv'] = array(
      'title' => 'Upload product CSV file',
      'page callback' => 'drupal_get_form',
          'page arguments' => array('biotweaks_form'),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

  $items['admin/upload-product-csv-download'] = array(
    'page callback' => 'biotweaks_product_csv_download',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function biotweaks_perm() {
    return array('true');
}

function biotweaks_form() {
    $form['description'] = array(
        '#type' => 'markup',
        '#value' => t('Please make sure that the CSV file you upload is in the right format with the columns in the correct order. If you are unsure, please contact the website administrator.'),
    );
    $form['download'] = array(
        '#type' => 'markup',
        '#value' => '
Download a CSV of the current products
',
    );
    $form['csv'] = array(
        '#type' => 'file',
        '#title' => 'CSV file',
    );

    $form['#attributes'] = array('enctype' => "multipart/form-data");

    $form['submit'] = array('#type' => 'submit', '#value' => t('Upload CSV') );
    return $form;
}

function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }

    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');

    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.nid=1452 and n.status = 1 ORDER BY tn.tid";
    $q = db_query($sql);

//print_r(db_fetch_array($q));exit;
    while ($r = db_fetch_array($q)) {

    echo '
';
    //print_r($r);exit;

        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);
        //print '**'.$r['nid'].'**';
        //print_r($q2);

        if (!db_result($q2)) {

            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }echo 'sd';
            //print_r($fields[9]);exit;
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                //put in AU prices
                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                //put in NZ prices
                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {

            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }

        //$fields[22] = $r['status'];

        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

function biotweaks_form_submit($form_id, $form_values) {
    $fieldName = 'csv';

    $dir = variable_get('file_directory_path', 'files');
    if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$fieldName])) {
        // attempt to save the uploaded file
        $file = file_save_upload($fieldName, array(), $dir, FILE_EXISTS_REPLACE);

        // set error if file was not uploaded
        if (!$file) {
          form_set_error($fieldName, 'Error uploading file.');
          return;
        } else {
          _process_csv($file);
        }
    } else {
        form_set_error('Can\'t upload file!');
        return;
    }
}

function _process_csv($file) {

    global $DEBUG_BT_PROCESS;
    $DEBUG_BT_PROCESS = false;

    //set to just test a single product
    global $CHECK_ONE;
    $CHECK_ONE = true;

    if (0) {
    //delete all products
        $sql = "select nid from node where type = 'product'";

        $r = db_query($sql);
        while ($ra = db_fetch_array($r)) {

        }

        print 'all products deleted.';
    }

    //set all products to unpublished
    if (!$DEBUG_BT_PROCESS) {

        if (!$CHECK_ONE) {
            $sql = "update node set status='0' where type='product'";

            db_query($sql);

        }
    }

    function _fix_currency($str) {
        if ($str == "FREE") {
            return "0";
        } else {
            $ret = str_replace('$', '', $str);
            $ret = str_replace(',', '', $ret);
            return $ret;
        }
    }

    function _get_title($fields) {
        $description = $fields[1];
        $size = $fields[2];

        if (!empty($size)) {
            $ptitle = $description . " - ".$size;
        } else {
            $ptitle = $description;
        }
        $ptitle = str_replace("*NEW", "", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        return $ptitle;
    }

    function _update_product_node($nid, $fields) {
        $sku = $fields[0];
        $description = $fields[1];
        $size = $fields[2];
        $pallet_qty = $fields[3];
        $dg_class = $fields[4];

        $ptitle = _get_title($fields);
        $node = node_load($nid);

        $node->title = $ptitle;
        $node->status = 1;
        $node->model = $sku;
        $node->shippable = 1;
        $node->default_qty = 1;

        $tid = $fields[5];
        $term = taxonomy_get_term($tid);

        if (!$term) {
            drupal_set_message('No category id?');

            return;
        }
        $node->taxonomy[$tid] = $term;
        if ($fields[9]) {

            $node->sell_price = _fix_currency($fields[9]);
        }
        if ($fields[17]) {

            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));

            $case_price = _fix_currency($fields[17]);

            $nz_rid = 6;

            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);

            db_query("INSERT INTO uc_price_per_role_prices (vid, nid, rid, price) VALUES (%d, %d, %d, '%f')", $r['vid'], $r['nid'], $nz_rid, $case_price);

            $node->role_prices[$nz_rid] = $case_price;
        } else {
            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));
            $nz_rid = 6;
            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);
            if (isset($node->role_prices[$nz_rid])) {
                unset($node->role_prices[$nz_rid]);
            }
        }

        if ($fields[9] && !$fields[17]) {

            $settings = BIOTWEAKS_AU_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else if ($fields[17] && !$fields[9]) {

            $settings = BIOTWEAKS_NZ_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else {

            db_query("delete from content_access where nid = '%d'", $r['nid']);
        }

        db_query("delete from {uc_product_fees} where nid = '%d'", $nid);

        if (!function_exists('_exclude_discount')) {
            function _exclude_discount($fid, $nid) {

                db_query("delete from uc_product_fees where nid = '%d' and fid = '%d'", $nid, $fid);
                db_query("INSERT INTO {uc_product_fees} (nid, fid, price, is_active) VALUES (%d, %d, '0', '0')", $nid, $fid);
            }
        }

        for ($i = 0; $i<7; $i++) {

            if ($fields[9]) {

                if (!$fields[10 + $i]) {

                    _exclude_discount(1 + $i, $nid);
                }
            } else if ($fields[17]) {

                if (!$fields[18 + $i]) {
                    _exclude_discount(1 + $i, $nid);
                }
            }
        }

        if ($fields[26]) {

            $image_directory = $fields[25] ? $fields[25]."/" : "";
            $filepath = $_SERVER['DOCUMENT_ROOT'].'/sites/default/files/'.$image_directory.$fields[26];

            if (file_exists($filepath)) {

                $field = field_file_save_file($filepath, array(), file_directory_path());
                $node->field_image_cache = array(0 => $field);
            }
        }

$n= db_query("select nid from prod_node_relation where nid=".$sku);

$y = db_fetch_object($n);
if($y->nid)
{
db_query("update node set type='product' where nid=".$y->nid);
db_query("update term_node set tid=".$term." where =".$y->nid);
}
else
{

    node_save($node);
}

db_query("INSERT INTO prod_node_relation (nid, sku) VALUES (%d, %d)", $node->nid, $sku);
    }

    $file_name = $file->filepath;
    $fd = fopen ($file_name, "r");

    drupal_set_message('Importing products');

    $fields = fgetcsv($fd, 4096, ",");
    $count = 0;

    while (($fields = fgetcsv($fd, 4096, ",")) !== FALSE) {

        $sku = $fields[0];

        $sql = "select nid from uc_products where model = '%s'";
        $q = db_query($sql, $sku);
        $r = db_fetch_array($q);

        if ($r) {

            _update_product_node($r['nid'], $fields);
            drupal_set_message('Updated product: '.$sku);

        } else {
            $sql2 = "select nid from node where title = '%s'";
            $q2 = db_query($sql2, $fields[1]);
            $r2 = db_fetch_array($q2);

            if ($r2) {
                _update_product_node($r['nid'], $fields);
                drupal_set_message('Updated product: '.$fields[1]);
            } else {

                drupal_set_message('Create product: '.$sku);
                if ($fields[0]) {

                    if ($DEBUG_BT_PROCESS) {
                        drupal_set_message('Need to create product:'.$fields[0]);
                    } else {
                        $node = (object)array(
                            'uid'=>1,
                            'name'=> 'admin',
                            'type'=> 'product',
                            'title'=> _get_title($fields)   );
                        $contenttype = content_types('product');
                        foreach ($contenttype['fields'] as $fieldname => $field) {
                            if(isset($field['widget']['default_value'])) {
                                $node->$fieldname = $field['widget']['default_value'];
                            }
                        }

                        node_save($node);

                        $nid = $node->nid;

                        _update_product_node($nid, $fields);
                        drupal_set_message('Created and updated product: '.$sku);
                    }
                } else {

                }
            }
        }
        break;
        $count++;
    }
    drupal_set_message('Finished importing.');

}

This is how it is being visible now when I open CSV file

This is frontend
Comment: Can you paste any notices and error which you've in your watchdog during the download? E.g. `drush watchdog-show --tail  `. Do you've the right permissions? Is `biotweaks_product_csv_download()` your main function to perform that action?
Comment: Yes i perform that action through biotweaks_product_csv_download() ,i sort out the issue in query section it's works fine now.Thanks
Answer:
Need to replace below code in place of same action in old code ,it's working fine in our end.

function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }

    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');

    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.status = 1 ORDER BY tn.tid";

    $q = db_query($sql);

    while ($r = db_fetch_array($q)) {

        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);

        if (!db_result($q2)) {

            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }

            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {

                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {

                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {

            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }

        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

Data not being visible in CSV file


Turning on delay of superfish menu

Question: For some reason I cannot find the settings to turn on the delay for my superfish menu. I was able to get to it a couple of weeks, but not any more.
All I see when I go to /admin/config/user-interface/superfish is the ability to change the number of blocks and paths to superfish library.
How do I get to the settings where I can turn on delay?
Answer: The settings for the menu is on the same page as the menu block settings page. You'll find your menu block at /admin/structure/block where you click configure for your menu block, and you'll be able to change the settings.

Turning on delay of superfish menu


Solve in Z. $y^2+y=x^4+x^3+x^2+x$

Question: Solve in Z. $$y^2+y=x^4+x^3+x^2+x$$
In my attempt to solve this, I used the fact that the left side is even.I write the eqyation in the following form: $$(x+1)(x^2+1)=0 \pmod 2$$. This clearly means x must be an odd number, as a result $$4|y(y+1)$$. This is as far as I could go.

Question from Jalil Hajimir
Comment: The right side factors as $x(x+1)(x^2+1)$, not $(x+1)(x^2+1)$, so $x$ need not be odd, as the solution $(x,y)=(0,0)$ confirms.
Comment: THanks,You are right.
Answer: Hint: Bound between 2 squares
For all but finitely many values of $x$, we can bound $(2y+1)^2$ between 2 consecutive perfect squares, hence it is never a perfect square.

 $(2x^2 + x)^ 2 < (2y+1) ^2 = 4y^2 + 4y + 1 = 4x^4 + 4x^3 + 4x^2 + 4x + 1  < 4x^4 + 4x^3 + 5x^2 + 2x + 1 = (2x^2 + x + 1)^2 $

Hence, we only need to check those values when the inequalities fail:
RHS inequality is false when: $x \in [0, 2 ] $.
$x = 0$ yield $ y = -1, 0$.
$x = 1$ yields no integer solution for $y$.
$x = 2$ yield $ y = -6, 5$.
LHS inequality is false when $x \in [-1, -\frac{1}{3} ]$.
$x = -1$ yields $y = -1, 0$.
Comment: Not necessary. It has the same parity as $x$. Note that you are missing the point: Are there any integers that lie strictly between $2x^2+x$ and $2x^2+x+1$?
Comment: Yes, and $2y+1$ is an integer. What integers are there between those 2 consecutive intgers?
Comment: This means $2x^2+x<2y+1<2x^2+x+1$
Comment: $2x^2+x $ is an odd number
Comment: thanks, of corse not.
Comment: Can you please introduce a refrence to get more familiar with this method or another example
Comment: The idea of bounding between two squares (or cubes, or triangle numbers, etc) is pretty common for similar setups, though I don't know of a reference off-hand that focuses just on that. Consider cases where you can get it to look like a square (leading coefficient is even). E.g. When is $n^6 + 24n^3 +192$ a perfect square, or a perfect cube?
Comment: Thank you ver much. My mentor also told me he is not aware of any reference for this method. I was wondering where I can find more information
Comment: Do we consider (n^3+12)^2 and (n^3+13)^2 to find perfect sure?
Comment: Just be careful with positive/negative values. And take a larger range which might simplify some calculations.
Comment: n is integer, not positive integers
Comment: If n is an integer we solve we consider two cases  n>0 and n<0. Am I right
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101668/discussion-between-keon-and-calvin-lin).
Comment: I need help on this

Solve in Z. $y^2+y=x^4+x^3+x^2+x$


My C# form closes and returns the control to the previous form.

Question: I am working on a desktop application in C#. In the code, if have to load a new from. I have used the [dot]ShowDialog() function for the object of the form I want to load. While the new form loads and works just fine, after completion of a function call (button press), the control returns to the parent form automatically however it should have stayed on the child form. Can any one please suggest what I am doing wrong?
Comment: Care to show your code so we can see what's wrong?
Comment: It will happen when your modal form is closed. Please, add the code that runs when this button is pressed.
Answer: I make a wild guess, but this behavior is typical when the button pressed has its property DialogResult set to something different than None.
Usually this happens when you have made a copy/paste of your button from a prexistent button like the OK or Cancel that have their property DialogResult set.


How to create a combination chart with the Charts module if some X-axis values are missing?

Question: I've been searching for a solution to my problem for a while without success so maybe someone here can help me.
I've already looked at the answer to the question about "How to combine 3 line charts in a single chart, using the Views integration of the Charts module?", but that didn't help to solve my issue.
I use the Charts module to create a chart in Views using the "Chart" display format. And I'm using Highcharts as my charting library to draw the number of "Passed" nodes (in green). I also created a chart add-on to represent the number of "Failed" nodes (in red) so that I can have multiple series in the same chart.
At this moment this is the chart that I have with the problem I will describe below:

As you can see in the table above, I have 4 different dates (Run Date and Time). The chart should show the 4 dates. Instead, it only shows 3 dates and this is why: The last date doesn't have "Passed" nodes, so the chart display (the parent) does not have that value on its axis. The chart add-on, representing the 2 Faileds on the last date, is then represented on top of the first display using the 3rd date and not the 4th, giving the error.
It seems that the x-axis values are irrelevant in this module.
The chart that I want should be something like this:

I made this chart in Excel and the difference that I see (that is giving me the wrong results in Drupal) is that I don't have a "0 Passed" or "0 Failed" but instead I have no results at all.
Is there a way to get this working correctly? I tried already many charts modules available and everyone has this problem as far as I know ...
Below is also a screenprint of my view:

Note: for the table below the chart I'm using module Views Merge Rows and it's clear that the top two dates don't show the "0 Failed" or "0 Passed" (as shown in the tabular display of my first screenprint) needed to have a correct chart displayed.
EDIT: I have found the same issue here and here. Hope it helps.
If there's need to have a solution like in the second link, i.e., construct the view in a way that both series will always have all labels, I'm open to it.
Answer: Step 1
Not sure if it's your "only" problem to get your chart right, but part of your problem is, pretty sure, that you have "holes" in your data, similar to what is detailed in Comment nr 12 of Issue nr 2052429.
About the problem
To understand what that issue about "hole" is all about, consider these data to be charted:

Note that for the Types Article and for Webform, there is no row with Published = No (that is, there are no unpublished nodes for these types). So in this scenario we have 2 so called "holes" ... And that's were the trouble start:

Problem 1: a column chart for these data looks like so:

The bar for "Article" (with value 1) is wrong, that bar is actually related to the value 1 for unpublished "Book pages". And the bar for "Book page" (with value 2) should actually be the bar for the 2 unpublished "Basic pages".
Problem 2: a line chart for these data looks like so:

In this case, the line for "unpublished" suffers similar problems. So it doesn't matter what type of chart you're creating, all charts have this issue.

How to solve this problem
Upgrade to the most recent Dev version to start with (which is much better / stable then the current rc1 version). Then apply the patch attached to the issue comment mentioned above, and check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work). Attention: the patch doesn't seem to apply anymore to the most recent dev version. To make it work (again), do not use the above mentioned patch, but instead use the re-rolled patch attached to in Comment nr 31 of Issue nr 2052429.
Here is how the same column chart from above looks like after applying this correction:

And this is its corresponding line chart:

... Which I believe is the chart that exactly matches the tabular data shown above.
Step 2
If upgrading to the most recent dev version and applying the patch is not sufficient, then I'd recommend you to (temporarily) disable that Views Merge Rows module you have enabled. And (temporarily) modify your view to show the values for PASSED and FAILED as 2 separated columns. And then verify if you get the correct results. That way we can verify if this Views Merge Rows module is the culprit (solve support requests is like taking away all possible causes, 1 at a time ...).
Step 3
If step 2 doesn't help either, then I recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.
Step 4
If none of the previous steps helps, then you may want to check the result you get by correcting your view like so:

Create another display in the same view, let's say you name it "Runs Chart (Total)". It should be equal to all the specs of "Runs Chart (Passed)", but without the filter "Content: Test Case Run Status (Passed)". Obviously, it'll reflect the total Runs (both passed and failed). I'd make it a "line chart" (but that's a matter of personal preferences).
Adapt the "Chart settings" of "Runs Chart (Passed)" to have it use  "Runs Chart (Total)" as the parent chart.
Adapt the "Chart settings" of "Runs Chart (Failed)" to have it use  "Runs Chart (Total)" as the parent chart (instead of "Runs Chart (Passed)").

Step 5
If the work around in step 4 helps as a work around, you may want to further refine the chart settings of "Runs Chart (Total)", by using a color for the line chart that matches the background of your chart (like white?). Possibly something similar for any of it settings like "Legend" (like set it to <code> </code>?
Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.
Comment: Hi Pierre, I already tried those 3 steps. The issue, as I said before is how the module is implemented. The x-axis is always dependent on the number of labels of the parent chart.
Comment: i just added "Step 4" ... curious if that may help to get it working in your case ... Let me know, ok?
Comment: Hi Pierre, Step 4 is a good workaround but it still doesn't solve it all. With this step I don't have "holes" in the data because the parent chart has every x-axis label. But it comes with a price: I have a line that I don't want to show and a legend. Instead of counting the status field I can Sum it and the line doesn't show but still, the legend is there. Conclusion: it's a good workaround, not a solution. Thanks for your support.
Comment: Great news about Step 4! I just did 1 more attempt to have you consider my answer as (more or less) acceptable ... Maybe it also helps to not have your bounty go to the "Drupal.SE waste bin" in a few hours from now?
Comment: Hi again Pierre. About Step 5. Changing the line color is not a solution. The chart heigh adapts to show the line (even if we don't see it) and if we have data labels, they will show. My comment about the workaround is in fact the best solution till now. A final solution for this has to be done by changing the module code, there's no other way. One of the things that should be possible in the future is to have settings for both the parent and the add-on charts. I will accept your solution with the 5 steps anyway as it is the best at the moment.
Comment: "Merci beaucoup" (how good is your French???) for the accept ... And even though you granted the bounty (also "merci" ...), know that I don't "give up" yet on your question here (apart from enhancing the charts module code). Here is yet another attempt for a variation of step 5: how about you use "rewrite results" for that "Runs chart (total)", to just set it to "0" (so that it would NOT adapt the charts height) ... And combine it with a black line chart. Wanna try one more time in your setup?
Comment: I didn't use rewrite. I used SUM aggregation. Because the field is a string, it returned 0. As I said, it's a workaround, it's not completely bad for my needs. The data values (zeros) still show on x-axis tought :(
Answer: I believe that what you need to do is construct the view in a way that both series will always have all labels.
To do this, all you need to do is make sure the "Count the number 0 as empty" field is unchecked. To find this field, click on the field name that you're counting to bring up its config overlay. Select "No Results Behavior" and make sure that the "Count the number 0 as empty" checkbox is unchecked. "Hide if empty" should also be unchecked.
Does that fix your problem? If not, it would be helpful if you exported your view and posted it, or at least the section regarding the field you're counting on.
Comment: Hi Erin, that doesn't solve the problem. Imagine you have 3 nodes like this (x, y): [a, 1] [a, 2] [c, 3]. If you create a chart in views, the "b" label will never show, no matter what. The solution has to be made in charts. If you have the first display of type chart where there is labels a, b, d. Then, if you create a second display of type chart add-on and the data has only labels a, c, d, the final chart will have only 3 labels, defined in the first display. There is a workaround for this problem but implies that you create aditional fields in the db.
Comment: Oh dang, I totally misunderstood the question. Sorry!
Comment: [Here](https://www.drupal.org/node/2314455) is also a good explanation of this issue. Sadly, no solution till now :(
Comment: Unfortunately, it looks like something that's going to need a patch to the module to fix.


Search and sort data from several files

Question: I have a set of 1000 text files with names in_s1.txt, in_s2.txt and so. Each file contains millions of rows and each row has 7 columns like:
ccc245 1 4 5 5 3 -12.3

For me the most important is the values from the first and seventh columns; the pairs ccc245 , -12.3
What I need to do is to find between all the in_sXXXX.txt files, the 10 cases with the lowest values of the seventh column value, and I also need to get where each value is located, in which file. I need something like:
FILE  1st_col  7th_col

in_s540.txt ccc3456 -9000.5
in_s520.txt ccc488 -723.4
in_s12.txt ccc34 -123.5
in_s344.txt ccc56 -45.6

I was thinking about using python and bash for this purpose but at the moment I did not find a practical approach. All what I know to do is:

concatenate all in_ files in IN.TXT
search the lowest values there using: for i in IN.TXT  ;  do sort -k6n $i | head -n 10; done
given the 1st_col and 7th_col values of the top ten list, use them to filter the in_s files, using grep -n VALUE in_s*, so I get for each value the name of the file

It works but it is a bit tedious. I wonder about a faster approach only using bash or python or both. Or another better language for this.
Thanks
Answer: In python, use the nsmallest function in the heapq module -- it's designed for exactly this kind of task.
Example (tested) for Python 2.5 and 2.6:
import heapq, glob

def my_iterable():
    for fname in glob.glob("in_s*.txt"):
        f = open(fname, "r")
        for line in f:
            items = line.split()
            yield fname, items[0], float(items[6])
        f.close()

result = heapq.nsmallest(10, my_iterable(), lambda x: x[2])
print result

Update after above answer accepted
Looking at the source code for Python 2.6, it appears that there's a possibility that it does list(iterable) and works on that ... if so, that's not going to work with a thousand files each with millions of lines. If the first answer gives you MemoryError etc, here's an alternative which limits the size of the list to n (n == 10 in your case).
Note: 2.6 only; if you need it for 2.5 use a conditional heapreplace() as explained in the docs. Uses heappush() and heappushpop() which don't have the key arg :-( so we have to fake it.
import glob
from heapq import heappush, heappushpop
from pprint import pprint as pp

def my_iterable():
    for fname in glob.glob("in_s*.txt"):
        f = open(fname, "r")
        for line in f:
            items = line.split()
            yield -float(items[6]), fname, items[0]
        f.close()

def homegrown_nlargest(n, iterable):
    """Ensures heap never has more than n entries"""
    heap = []
    for item in iterable:
        if len(heap) < n:
            heappush(heap, item)
        else:
            heappushpop(heap, item)
    return heap

result =  homegrown_nlargest(10, my_iterable())
result = sorted(result, reverse=True)
result = [(fname, fld0, -negfld6) for negfld6, fname, fld0 in result]
pp(result)

Comment: hi, thanks

while trying your solution i get the error:

Traceback (most recent call last):
  File "filter.py", line 13, in
    result = heapq.nsmallest(10, my_iterable(), lambda x: x[2])
  File "/usr/lib64/python2.6/heapq.py", line 359, in nsmallest
    result = _nsmallest(n, it)
  File "filter.py", line 10, in my_iterable
    yield fname, items[0], float(items[5])
IndexError: list index out of range
Comment: That means that you have a line that doesn't have enough fields in it. You are responsible for checking that your data is actually in the format that you believe it's in. By the way, why do you have `items[5]` and not `items[6]` in the yield statement?
Comment: thanks a lot, now it works as expected!

I realize that I got some format exceptions on the file that, when checked, give the right results

I will try now to understand your code

thanks

Jose
Answer: I would:

take first 10 items,
sort them and then
for every line read from files insert the element into those top10:

in case its value is lower than highest one from current top10,
(keeping the sorting for performance)

I wouldn't post the complete program here as it looks like homework.
Yes, if it wasn't ten, this would be not optimal
Answer: Try something like this in python:
min_values = []

def add_to_min(file_name, one, seven):
    # checks to see if 7th column is a lower value than exiting values
    if len(min_values) == 0 or seven < max(min_values)[0]:
        # let's remove the biggest value
        min_values.sort()
        if len(min_values) != 0:
            min_values.pop()
        # and add the new value tuple
        min_values.append((seven, file_name, one))

# loop through all the files
for file_name in os.listdir(<dir>):
    f = open(file_name)
    for line in file_name.readlines():
        columns = line.split()
        add_to_min(file_name, columns[0], float(columns[6]))

# print answers
for (seven, file_name, one) in min_values:
    print file_name, one, seven

Haven't tested it, but it should get you started.
Version 2, just runs the sort a single time (after a prod by S. Lott):
values = []
# loop through all the files and make a long list of all the rows
for file_name in os.listdir(<dir>):
    f = open(file_name)
    for line in file_name.readlines():
        columns = line.split()
        values.append((file_name, columns[0], float(columns[6]))

# sort values, print the 10 smallest
values.sort()
for (seven, file_name, one) in values[:10]
    print file_name, one, seven

Just re-read you question, with millions of rows, you might run out of RAM....
Comment: That `min_values.sort()` is very bothersome.  I think this can be reworked to remove that needless sort.  Yes, it's small, but it will be performed millions of times and doesn't seem to help.
Comment: Maybe, but we need to remove the biggest value with the pop, so min_values needs to be sorted. You probably could do it more efficiently but sometimes simpler is better than faster, especially if the code is only going to be run a few times. Let me see if I can come up with something better.
Comment: I think that you don't need to sort to pop the max of 10 minimum values plus one unknown value.  I think you can do something like  `min_values.remove( max(min_values+[seven]) )` to preserve the smallest value.
Answer: A small improvement of your shell solution:
$ cat in.txt
in_s1.txt
in_s2.txt
...
$ cat in.txt | while read i
do
  cat $i | sed -e "s/^/$i /" # add filename as first column
done |
sort -n -k8 | head -10 | cut -d" " -f1,2,8

Comment: with million rows in the files, using bash's while/read, + external commands would be slow on performance.
Answer: If your files are million lines, you might want to consider using "buffering". the below script goes through those million lines, each time comparing field 7 with those in the buffer. If a value is smaller than those in the buffer, one of them in buffer is replaced by the new lower value.
  for file in in_*.txt
    do
        awk -vt=$t 'NR<=10{
            c=c+1
            val[c]=$7
            tag[c]=$1
        }
        NR>10{
            for(o=1;o<=c;o++){
                if ( $7 <= val[o] ){
                    val[o]=$7
                    tag[o]=$1
                    break
                }
            }
        }
        END{
            for(i=1;i<=c;i++){
                print val[i], tag[i] | "sort"
            }

        }' $file
    done

Comment: "to find between all the in_sXXXX.txt files, the 10 cases with the lowest values of the seventh column value"

That's not what your script does. It prints the smallest value for *every* file.
Answer: This might be close to what you're looking for:
for file in *; do sort -k6n "$file" | head -n 10 | cut -f1,7 -d " " | sed "s/^/$file /" > "${file}.out"; done

cat *.out | sort -k3n | head -n 10 > final_result.out

Comment: Oops, forgot a `head` command. Fixed. Thanks for the downvote.
Comment: This gets the ten smallest values from every file and sorts the resulting list of `n*10` values. That's not what was asked for.

Search and sort data from several files


Objeto depois de persistido e retornado inconsistente para uma dropdown list

Question: Olá pessoal boa tarde!
Bem, resumidamente tenho um problema no qual não faço ideia do que pode estar acontecendo. Na minha opnião não faz sentido tal comportamento.
Estou usando Spring MVC + Spring Data para facilitar as operações de CRUD em meu sistema. Tenho uma pagina na qual eu realizo um cadastro de categorias, trata-se de algo simples, apenas um campo "name" e outro para verificar se a categoria esta ou não ativa.
Em seguida tenho uma "Gestão de Destinos", quem tem como objetivo cadastro de novos destinos. Nele tenho uma associação com categoria na qual é populada um componente de dropdown list. Tal relacionanmento e do fator OneToOne unidirecional.
O componente é populado normalmente, abaixo o codigo do mesmo:
View:
<f:select path="categories.idCategory">
    <f:option value="-1" label="-- Selecione uma categoria para associação --"/>
    <f:options items="${categoryDropDown}" itemValue="idCategory" itemLabel="ctName"/>
</f:select>

Controller:
//Entra na tela de cadastro de um novo destino
@RequestMapping("newDestination")
public ModelAndView setnewDestination(Model model, HttpServletRequest req){
    //Inicializa o Componente DropDown de Categoria
    List<Category> category = dashboardFacade.getCategoryList();
    List<Category> activeCategory = new ArrayList<Category>();

    //Verificação de categorias que não estão ativas
    for (Category allCAtegory : category) {
        if(allCAtegory.getCtActive() == 1){
            activeCategory.add(allCAtegory);
        }
    }
    model.addAttribute("categoryDropDown", activeCategory);

    return new ModelAndView("destination/newDestination", "command", new Destination());
}

Facade:
public List<Category> getCategoryList(){
    return categoryRepository.findAll();
}

Repository:
@Repository
public interface CategoryRepository extends BaseRepository<Category, Long>{

    List<Category> findAll();

}

Bem, o que ocorre na realidade é que quando eu vou cadastrar um novo destino e seleciono uma categoria o mesmo e salvo com sucesso na base. Mas quando eu tenho cadastra novamente um destino a minha List<Category> category = dashboardFacade.getCategoryList(); vem com objeto inconsistente. Ou seja, com valores null.
Objeto category populando a dropbox sem sua associação ter sido salva:

[idCategory=1, ctActive=1, ctName=Nacional, tenantId=2],
[idCategory=2, ctActive=0, ctName=Internacional, tenantId=2],
[idCategory=3, ctActive=1, ctName=Cruzeiro, tenantId=2],
[idCategory=4, ctActive=1, ctName=Espacial, tenantId=2],

Salvei um novo destino com a categoria de nome "Nacional". Quando o dropdown ela simplesmente não aparece.
Este é o estado que category é encntrado:

[idCategory=1, ctActive=0, ctName=null, tenantId=null],
[idCategory=2, ctActive=0, ctName=Internacional, tenantId=2],
[idCategory=3, ctActive=1, ctName=Cruzeiro, tenantId=2],
[idCategory=4, ctActive=1, ctName=Espacial, tenantId=2],

Não faço ideia do que pode estar ocorrendo.
Se alguém puder ajudar fico muito grato.
Abraço a todos
EDIÇÃO
Abaixo seguem os mapeamentos:
Destination.java
package br.com.joocebox.model;

import java.io.Serializable;

import javax.persistence.*;

import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.annotations.TenantDiscriminatorColumn;
import org.eclipse.persistence.config.PersistenceUnitProperties;
/**
 * The persistent class for the destination database table.
 *
 */
@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="active")
    private byte dtActive;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

    @Column(name="name")
    private String dtName;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @OneToOne
    @JoinColumn(name="fk_category")
    private Category categories;

//  //bi-directional many-to-one association to Agency
//  @ManyToOne(fetch=FetchType.LAZY)
//  @JoinColumn(name="fk_agency")
//  private Agency agency;

    //Profiles of System. These profiles are all enum type.
    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_economic")
    private EconomicProfile economicProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_general")
    private GeneralProfile generalProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_social")
    private SocialProfile socialProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_trip")
    private TripProfile tripProfiles;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_weather")
    private WeatherProfile weatherprofile;
    //End of Profiles of System.

//  @OneToMany(mappedBy="destination")
//  private Set<Image> images;

    public Destination() {
    }

    public Long getIdDestination() {
        return this.idDestination;
    }

//Getter and Setters
}

Category.java
package br.com.joocebox.model;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.*;

import org.eclipse.persistence.annotations.Multitenant;
import org.eclipse.persistence.annotations.TenantDiscriminatorColumn;
import org.eclipse.persistence.config.PersistenceUnitProperties;
/**
 * The persistent class for the category database table.
 *
 */
@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    public Category() {
    }

    public Long getIdCategory() {
        return this.idCategory;
    }

//Getters and Setters

    @Override
    public String toString() {
        return "Category [idCategory=" + idCategory + ", ctActive=" + ctActive
                + ", ctName=" + ctName + ", tenantId=" + tenantId + "]";
    }

}

Obrigado!

filipeportes,
não funcionou. Na verdade não sei mais o que pode ser.
Fiz desta forma:
Category.java:
@Entity
@Table(name="category")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c")
public class Category implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_category")
    private Long idCategory;

    @Column(name="ct_active")
    private int ctActive;

    @Column(name="ct_name")
    private String ctName;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    //Relacionamento com Category
    @OneToMany(mappedBy="categories", fetch=FetchType.LAZY)
    private Set<Destination> destination;

    //Getters and Setters

Destination.java:
@Entity
@Table(name="destination")
@Multitenant
@TenantDiscriminatorColumn(name="tenant_id", discriminatorType=DiscriminatorType.INTEGER, contextProperty=PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
@NamedQuery(name="Destination.findAll", query="SELECT d FROM Destination d")
public class Destination implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_destination")
    private Long idDestination;

    @Column(name="tenant_id", insertable=false, updatable=false)
    private Long tenantId;

    @Column(name="active")
    private byte dtActive;

    @Column(name="appear_website")
    private Boolean dtAppearWebsite;

    @Lob
    @Column(name="description")
    private String dtDescription;

    @Column(name="highlight_website")
    private Boolean dtHighlightWebsite;

    @Column(name="name")
    private String dtName;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_streetview")
    private StreetView streetView;

    @OneToOne(cascade=CascadeType.PERSIST)
    @JoinColumn(name="fk_video")
    private Video video;

    @ManyToOne(cascade=CascadeType.REFRESH)
    @JoinColumn(name="fk_category")
    private Category categories;

    //Getters and Setters

Parece que fica algo em cache, pois quando eu dou um shutdown e subo novamente o server meu objeto vem de forma consistente.
Abraço
Comment: pode adicionar os mapeamentos de suas classes de modelo por favor?
Comment: @filipeportes Editei a pergunta com os mapeamentos correwspondentes. Obrigado!
Comment: não sei se isso tem relação com o problema, mas não vejo necessidade de utilizar o mapeamento OneToOne no seu caso, use ele apenas se precisar do mapeamento inverso, ou seja, de Destination dentro de Category.
Answer: isso pode ter relação com o problema, não vejo necessidade de utilizar o mapeamento @OneToOne no seu caso, use ele apenas se precisar do mapeamento inverso, ou seja, de Destination dentro de Category.
prefira sempre utilizar o @ManyToOne e evite ao máximo mapeamento inverso.
Outra boa prática é utilizar SEMPRE o fetch=FetchType.LAZY, os mapeamentos @OneToOne e @ManyToOne tem como default o fetch EAGER, ou seja, carrega todos os dados mapeados do banco mesmo que não sejam utilizados, isso pode gerar problemas graves de performance.


file unmanaged save upload

Question: I'm moving some existing functionality into a new Drupal site.

Files are uploaded via posted form
Their file names are prefixes with UID
They are then moved to temp holding directory
A cron job on another server SCPs the files in batches
The files are verified copied, then deleted via batch ssh command

I'm looking for a clean way to handle (save) an uploaded file coming from a submitted form with an element of type 'file' without "managing" it. I've browsed over file_save_upload() and like the validation/error handling it offers.
However, I'd rather not have the files exist in the managed file tables. I would need to modify my pulling server's cron job to trigger a managed deletes via web request.
Just as there is a file_save_data() and analogous file_unmanaged_save_data() I'm looking for file_unmanaged_save_upload(). I basically want the first half of file_save_upload() before it touch the database. It seems like something similar or a workaround should already exist but I haven't found one. I trying to avoid reinventing the wheel.
Comment: Not sure about the #4 and #5, but if you still need Drupal to handle the uploaded files (from new SCP'd location), you will need to use `file_save_upload`. Once the files are copied, update the file location to the new one (or go one step ahead and add a new stream wrapper).
Answer: I suggest using file_save_upload() anyway, beacause (as the API docs say):

The file will be added to the {file_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file_save() to save the changes.

So you don't need to worry about having the file "managed" by Drupal as long as you don't change the status of the file to FILE_STATUS_PERMANENT.
Otherwise, if you really don't want this default behaviour (and also no hooks to get invoked), just copy the file in your form_submit() using file_unmanaged_copy() (give it uploaded tmp file as source).
Answer: You may create your own file_unmanaged_save_upload() which won't insert item into Drupal DB file_managed table.
I did. I copied file_save_upload() as file_unmanaged_save_upload() in /Drupal_root/includes/file.inc, and deleted "file_save()" in it, modify the last lines as below:

function file_unmanaged_save_upload(){
.....
if ($file = file_save($file)) {
    // Add file to the cache.
    $upload_cache[$source] = $file;
    return $file;
  }
  return FALSE;
}

It works as expected.

file unmanaged save upload


Double Integration, Fubini's Theorem. Joint Continuity

Question: Could someone please help to show why this function is jointly discontinuous at (0,0). A step-by-step method would be greatly appreciated. Thank you!
[(2xy/(x^2 + y^2)]
Answer: In polar coordinates $(x,y)=(r\cos t,r\sin t)$ your function is
$$\frac{2r^2\cos t\sin t}{r^2}=\sin 2t.$$
So if your point approaches $(0,0)$ on a straight line, the value it
takes depends on the angle of that line.
Comment: $2 \cos t \sin t$ is $\sin 2t$, not $\cos 2t$.


Can the pitcher run to first base

Question: can the pitcher run to first base with the ball and get an out?
Comment: In what circumstances? There's more than just "have the ball and go somewhere".
Answer: Yes. It doesn't matter how the ball gets to the base, if a player touches the base with control of the ball before the runner gets there, the runner is out. The pitcher could throw, kick, or roll the ball to first if they wanted to. On rare occasions, the ball will get stuck in their glove so a pitcher will throw their entire glove (with the ball inside) over to first base!
Answer: If they beat the runner there then yes.
Answer: Yes they can.
This occurs in many instances:
The ball is hit to the pitcher and the pitcher beats the runner to the bag
Pitchers also assist in run downs, and if any defensive player beats the batter to the first base bag, it is an out

Can the pitcher run to first base


Prime numbers $p<q<r$ such that $r^2-q^2-p^2$ is a perfect square.

Question: Find the prime numbers $p<q<r$ such that $r^2-q^2-p^2$ is a perfect square.
I think the only solution is (2,3,7) but i cannot prove it.
The equation would be $r^2-q^2-p^2=k^2$ equivalently
$q^2+p^2+k^2=r^2$ which is somehow a classical diophantine equation (of the pythagorean quadruples) which have a parametrization but how do i use it? The problem is from a magazine at 8 th grade and i don't think the solution is supposed to use the general solution.
Actually the general solution of $q^2+p^2+k^2=r^2$ is given by:
$ q=a^2+b^2-c^2-d^2$
$p=2(mq+np)$
$k=2(nq-mp)$
$r=a^2+b^2+c^2+d^2$
IT would follow that one of the numbers q or p is even and prime, so it is 2.
Comment: Ah, it might be in the [Olympiad Corner](https://www.math.ust.hk/excalibur/v21_n4_20180315.pdf)
Comment: @amarius8312 I have noticed that you haven't accepted any of the 14 questions you've made on MSE. Please consider accepting the answers you like the most ;) PS: You get 2 extra reputation points whenever you accept an answer
Answer: Hint

All prime numbers $p\geq5$ satisfy $p\equiv \pm 1\mod 6$

Therefore, if $p,q,r\geq5$
$$r^2-q^2-p^2\equiv (\pm1)^2-(\pm1)^2-(\pm1)^2\equiv 1-1-1\equiv5\mod 6$$
Observe now, that there's no perfect square with the residue $5$ modulo 6.
This follows from the simple fact that (taking the equations modulo $6$)
$$\begin{array}l 1^2\equiv\color{red}1\\ 2^2\equiv \color{red}4\\ 3^2\equiv9\equiv\color{red}3\\4^2\equiv16\equiv \color{red}4\\5^2\equiv25\equiv \color{red}1 \\6^2\equiv\color{red}0\end{array}$$
Can you end it now?
Answer: Your guess is correct: $(2,3,7)$ is the unique solution. There is a simple proof using two basic and easy to verify facts:

if $m$ is odd, then $m^2\equiv 1\pmod 4$;
if $m$ is not divisible by $3$, then $m^2\equiv 1\pmod 3$.

We proceed as follows.
Write $r^2-p^2-q^2=k^2$ with an integer $k$.
If we had $p>2$, this would imply $p^2\equiv q^2\equiv r^2\equiv 1\pmod 4$, leading to $k^2\equiv r^2-p^2-q^2\equiv 3\pmod 4$, which contradicts the first basic fact above. Thus $p=2$, whence $r^2=q^2+k^2+4$.
If we had $q>3$, this would imply $r^2\equiv q^2\equiv 1\pmod 3$ leading to $k^2\equiv 2\pmod 3$, which contradicts the second basic fact above. Thus $q=3$, and, as a result, $r^2=13+k^2$. Consequently, $(r-k)(r+k)=13$, which is only possible if $r-k=1$ and $r+k=13$. This yields $r=7$, $k=6$.
To summarize, the only solution is $p=2$, $q=3$, $r=7$.


How to turn this Func into an expression?

Question: I am playing around with expression trees and trying to better understand how they work. I wrote some sample code that I'm working with and hopefully someone can help me out.
So I have this somewhat messy query:
///
/// Retrieves the total number of messages for the user.
///
/// <param name="username">The name of the user.</param>
/// <param name="sent">True if retrieving the number of messages sent.</param>
/// <returns>The total number of messages.</returns>
public int GetMessageCountBy_Username(string username, bool sent)
{
    var query = _dataContext.Messages
        .Where(x => (sent ? x.Sender.ToLower() : x.Recipient.ToLower()) == username.ToLower())
        .Count();
    return query;
}

_dataContext is the entity framework data context. This query works beautifully, but it's not easy to read. I decided to factor the inline IF statement out into a Func like this:
public int GetMessageCountBy_Username(string username, bool sent)
{
    Func<Message, string> userSelector = x => sent ? x.Sender : x.Recipient;
    var query = _dataContext.Messages
        .Where(x => userSelector(x).ToLower() == username.ToLower())
        .Count();
    return query;
}

This seems like it would work great, but there is a problem. Because the query is against IQueryable<T> this LINQ expression is being translated into SQL to be executed at the data source. That's great, but because of this it does not know what to do with the call to userSelector(x) and throws an exception. It cannot translate this delegate into an expression.
So now that I understand why it's failing I would like to try and make it work. It's far more work for what I need, but I'm doing it just out of pure interest. How might I turn this Func into an expression that can be translated into SQL?
I tried to do this:
Expression<Func<Message, string>> userSelectorExpression = x => sent ? x.Sender : x.Recipient;
Func<Message, string> userSelector = userSelectorExpression.Compile();

With this however, I get the same error. I think I'm failing to understand expressions. I think all I'm doing with the above code is writing an expression but then turning it into executable code again and then getting the same error. However, if I try to use userSelectorExpression within the LINQ query it can't be called like a method.
Edit
For those interested in the exception, here it is:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

I took this to mean that it could not "invoke" the userSelector delegate. Because, as stated above, it needs to translate it into an expression tree.
When using a real method, you get a slightly more verbose error message:

LINQ to Entities does not recognize the method 'System.String userSelector(Message, Boolean)' method, and this method cannot be translated into a store expression.
Comment: Note: Ultimately it will be far simpler to just use my original query, I know. I am just interested in how expressions work for future reference.
Comment: If you make that a separate method what happens?
Comment: @FlyingStreudel, same error. It is because the query is being translated into an expression tree.
Comment: Oops my bad, didn't notice the EF tag. Yea, sql can't '
Comment: I don't think the problem is that it can't turn it into an expression tree, but instead that it can't turn the resulting expression tree into SQL.
Comment: @Mike, you think so? Because even if I do a simple delegate: `Func addOne = x => x + 1;` I get the same error. A failure to "invoke". Can't really make a simpler delegate than that. But maybe you're right, maybe I'm missing something.
Comment: Sorry, I should elaborate. QueryProviders work by taking an expression tree and translating it into something else. The LINQ to Entities provider translates expression trees to SQL. But there are expression trees that it can't translate. Not everything you can write in code can be translated to SQL. That's what the exception is telling you. It's failing at the translation to sql step not the translation to expression tree step. In this case it isn't smart enough to dig into `userSelector` and figure out what to do with it. But that doesn't mean you got an invalid expression tree
Comment: Hmmmm, so I wonder why the `addOne` delegate fails? My original delegate wasn't very complicated either, is there a way to structure it better so that it can translate the expression?
Comment: @Chevex - RE - the simple delegate. That's really the proof. It can't translate invocations to valid sql. It can't look inside them and figure it out. SQL is such a different language than C#. There just isn't exactly the equivalent of "call this method with these arguments". Sure there are stored procs and user defined functions but you're not asking it to call those. You're asking to execute a C# method that does who knows what.
Comment: Right that's what I said originally, which is why it needs to be represented as an expression and not a compiled delegate, which is what I'm trying to learn how to do. It can't invoke a compiled method, it needs an expression.
Comment: @Chevex. I think it just bails out at invocations. They just didn't try to look inside an invocation during the translation code. Take a look at `ExpressionVisitor` http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx See all the Visit* methods? They just chose to throw an exception in the LINQ to entities implementation of `VisitInvocation`. Design choice. You're stuck with it. Wish there was another way
Comment: Interesting. I will have a look. Thanks Mike.
Comment: Whilst interesting, I'm not sure any of this is making the statement easier to read.
Comment: @Chevex - you may also want to read through this http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx It is an exhaustive but very good walkthrough on building query providers. It won't directly help with this one query but it will help you understand the complexities of expression trees and how providers must try to translate them
Comment: @Jodrell, I specify several times that I am thoroughly aware of that.
Answer: No need to complicate:
return sent
    ? _dataContext.Messages.Count(x => x.Sender.ToLower() == username.ToLower())
    : _dataContext.Messages.Count(x => x.Recipient.ToLower() == username.ToLower());

Answer: Well after playing around a bit, I got what I wanted.
This didn't save me tons of code in this case, but it does make the base query much easier to look at. For more complicated queries in the future this will be awesome! This query logic never gets repeated, but still gets re-used as many times as I need to.
First I have two methods in my repository. One counts the total number of messages (the one I used as the example in my question) and one that actually gets a collection of messages by page number. Here is how they are structured:
The one that gets a total count of messages:
    ///
    /// Retrieves the total number of messages for the user.
    ///
    /// <param name="username">The name of the user.</param>
    /// <param name="sent">True if retrieving the number of messages sent.</param>
    /// <returns>The total number of messages.</returns>
    public int GetMessageCountBy_Username(string username, bool sent)
    {
        var query = _dataContext.Messages
            .Count(UserSelector(username, sent));
        return query;
    }

The one that gets messages and pages them:
    ///
    /// Retrieves a list of messages from the data context for a user.
    ///
    /// <param name="username">The name of the user.</param>
    /// <param name="page">The page number.</param>
    /// <param name="itemsPerPage">The number of items to display per page.</param>
    /// <returns>An enumerable list of messages.</returns>
    public IEnumerable<Message> GetMessagesBy_Username(string username, int page, int itemsPerPage, bool sent)
    {
        var query = _dataContext.Messages
            .Where(UserSelector(username, sent))
            .OrderByDescending(x => x.SentDate)
            .Skip(itemsPerPage * (page - 1))
            .Take(itemsPerPage);
        return query;
    }

Obviously it is the call to UserSelector(string, bool) that is the big deal here. Here is what that method looks like:
    ///
    /// Builds an expression to be reused in a LINQ query.
    ///
    /// <param name="username">The name of the user.</param>
    /// <param name="sent">True if retrieving sent messages.</param>
    /// <returns>An expression to be used in a LINQ query.</returns>
    private Expression<Func<Message, bool>> UserSelector(string username, bool sent)
    {
        return x => ((sent ? x.FromUser : x.ToUser).Username.ToLower() == username.ToLower()) && (sent ? !x.SenderDeleted : !x.RecipientDeleted);
    }

So this method builds an expression to be evaluated and properly gets translated into it's SQL equivalent. The function in the expression evaluates to true if the username matches the username of either the sender or the recipient and deleted is false for either sender or recipient, based on the supplied boolean sent that gets serialized into the expression.
Here is a version of the above, that is closer to the example in my question. It's not as readable since my expression is grotesque but at lease I understand how it's working now:
    public int GetMessageCountBy_Username(string username, bool sent)
    {
        Expression<Func<Message, bool>> userSelector = x => ((sent ? x.FromUser : x.ToUser).Username.ToLower() == username.ToLower()) && (sent ? !x.SenderDeleted : !x.RecipientDeleted);

        var query = _dataContext.Messages
            .Count(userSelector);
        return query;
    }

This is actually pretty cool stuff. Took a lot of time to figure out but this seems really powerful. I now have a new understanding of how LINQ, lambdas, and expressions work :)
Thanks to everyone who contributed to this question! (including you artplastika, I still love you even if I don't love your answer)
Comment: Now I'm trying to clean up the lambda in the expression, if possible. Feel free to contribute: http://stackoverflow.com/questions/6142432/how-might-i-clean-up-this-lambda
Comment: I'm not sure about this but I don't think you need to have `Expresion<...>` in there. The fundamental difference between this and your original lambda is that this returns a bool (a predicate) and can be passed to the `Where` method directly. In the lambda in the question you called a delegate that returned a string inside your predicate. The fix is that you put all the logic in one lambda without calling another. It has nothing to do with `Expression`
Comment: @Mike Two It is required. If I remove it, it still compiles but it fails at runtime. This is because the `sent` boolean is serialized into the expression, but not when it's a plain function. I think... In any case, it fails if I remove it.
Answer: Maybe this could be of use to help you abstract away conditions(predicates):
http://www.albahari.com/nutshell/predicatebuilder.aspx
Comment: He says 'vague references to other code on the web that I must "Google" for' on it))
Comment: At least he linked me to something artplastika. What happened to "Enough of me..."? At any rate, art is right. I just want to understand how to turn this `Func` into an `Expression` to be included in the query. Not how to "abstract away".


Angular 9 cdk Drag cannot select text

Question: For some reason in Angular 9 placing a CDK drag on a mat dialog title div it will make the entire dialog draggable. This will prevent users from selecting text within the dialog box.
In Angular 7 you could only drag the dialog by actually dragging the div that you placed the cdk drag property in.
Is there any way to make the drag action happen only on the title of a mat dialog in Angular 9?

  <mat-icon>drag_handle</mat-icon>

  {{title}}

{{message}}

  <button mat-button (click)="onDismiss()">No</button>
  <button mat-raised-button color="primary" (click)="onConfirm()">Yes</button>

I downloaded the code from this site
https://onthecode.co.uk/how-to-make-angular-material-dialog-draggable-with-cdkdrag/
Comment: did you try to make a div around the code and handle the drag magic there?
Answer: it's only enclose all the dialog in a div with cdkDrag, and add to h1 cdkDragHandle

Hi {{data.name}}

  ...

See stackblitz
Answer: The other answer did not work for me so I ended up creating a directive:
import { Directive, HostListener, AfterViewInit, ElementRef } from '@angular/core';

@Directive({
  selector: '[selectableTextInCdkDrag]'
})
export class SelectableTextInCdkDragDirective implements AfterViewInit {
  constructor(private elementRef: ElementRef) { }

  @HostListener('mousedown', [ '$event' ]) onMouseDown($event: Event): void {
    $event.stopPropagation();
  }

  @HostListener('touchstart', [ '$event' ]) onTouchStart($event: Event): void {
    $event.stopPropagation();
  }

  ngAfterViewInit(): void {
    this.elementRef.nativeElement.style['user-select'] = 'text';
    this.elementRef.nativeElement.style['cursor'] = 'initial';
  }
}

...

...

Angular 9 cdk Drag cannot select text


How to get focus on a subform in LibreOffice Base using tab

Question: The question and answer LibreOffice Base; Tab order from mainform to subform almost solve the issue I have, but not completely.
I have a table mytable (id, name, textfield). I'm displaying id and name in a form with a table layout (table control). I've added the column textfield from the same table as a subform with a text box control (the reason is that I want to enter text with newlines, while being able to navigate the records quickly in the main table). Here's what it looks like in design view:

I've added this Basic macro, based on the two answers linked above:
Sub Main

Dim root_doc As Object
Dim form_container, form_ctrlr As Object
Dim main_frm, sub_frm, tab_target As Object
root_doc = ThisComponent
form_container = root_doc.Drawpage.Forms
form_ctrlr = root_doc.getCurrentController()
main_frm = form_container.getByName("MainForm")
sub_frm = main_frm.getByName("SubForm")
tab_target = sub_frm.getByName("TextField")
form_ctrlr.getControl(tab_target).setFocus()

End Sub

Now, if I add the macro on the event When losing focus of the name column, I do get focus on the textbox when pressing Tab, but on the next row.
If I add the macro to the event On key press of the name column, I get what I want when pressing e.g. Space, but Tab or Enter only take me to the next row in the main form.
Is there a way to get this to work with Tab?
Comment: Also posted at https://ask.libreoffice.org/en/question/190449/how-to-get-focus-on-a-subform-in-libreoffice-base-using-tab/ where an answer is given.
Answer: Options to solve this, from the answers over at ask.libreoffice.org:

Just use the standard Ctrl + Tab to switch focus.
Assign a macro to a custom key combination and use that. Not all combinations work, I settled on Shft + Enter.

And the macro (provided by user Ratslinger):
Sub Main
    Dim oForm, oCtrlr, oField As Object
    oForm = ThisComponent.Drawpage.Forms.getByName("MainForm")
    oCtrlr = ThisComponent.getCurrentController()
    oField = main_frm.getByName("TextField")
    oCtrlr.getControl(oField).setFocus()
End Sub


Converting MySQL to db_select with subquery count

Question: I have an SQL query, with subquery, that returns as set of nodes ordered by referenced nodes... It works fine in a db_query, but I need it to be dynamic, and it feels like a better idea to use Drupal's abstraction layer.
I have got so far, but I am having issues with the subquery. It doesn't appear to having any effect...
I should say I used the Query Coder module to help do the conversion.
SQL:
SELECT n.nid , dest.field_flight_hero_destination_tid  hero_desintation_tid , (
SELECT COUNT( * )
FROM {field_data_field_field_route_matrix} routes
LEFT JOIN  {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE routes.entity_id = n.nid
AND  field_flight_destination_tid
IN (:stopovers_tids)
)total
FROM node n
LEFT JOIN  field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
LEFT JOIN field_data_field_flight_cabin_class class ON n.nid = class.entity_id
WHERE dest.field_flight_hero_destination_tid = :destination_tid AND class.field_flight_cabin_class_tid IN (:class_tid)
ORDER BY total DESC

db_select:
// Subquery.
  $subquery  = db_select('{field_data_field_field_route_matrix}', 'routes');
  $subquery->addExpression('COUNT(*)', 'count');
  $subquery->leftJoin('{field_data_field_flight_destination}', 'destination', 'routes.field_field_route_matrix_target_id = destination.entity_id');
  $subquery->condition('routes.entity_id', 'n.nid');
  $subquery->condition('field_flight_destination_tid', $stopovers);

  // Main query sorted by subquery.
  $query = db_select('node', 'n');
  $query->fields('n', array('nid'));
  $query->fields('dest', array('field_flight_hero_destination_tid'));
  $query->addJoin('', $subquery, 'total');
  $query->leftJoin('field_data_field_flight_hero_destination', 'dest', 'n.nid = dest.entity_id');
  $query->leftJoin('field_data_field_flight_price_matrix', 'prices', 'n.nid = prices.entity_id');
  $query->leftJoin('field_data_field_flight_cabin_class', 'class', 'n.nid = class.entity_id');
  $query->condition('dest.field_flight_hero_destination_tid', $destination);
  if (!empty($cabin_class)) {
    $query->condition('class.field_flight_cabin_class_tid', array($cabin_class), 'IN');
  }
$query->orderBy('total.count', 'DESC');
$result = $query->execute();

Generated output:
[queryString] => SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
node n
 JOIN (SELECT COUNT(*) AS count
FROM
field_data_field_field_route_matrix routes
LEFT OUTER JOIN field_data_field_flight_destination destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = :db_condition_placeholder_1) AND (field_flight_destination_tid IN  (:db_condition_placeholder_2)) ) total
LEFT OUTER JOIN field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT OUTER JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = :db_condition_placeholder_0)
ORDER BY total.count DESC
)

Devel dpq:
SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
{node} n
 JOIN (SELECT COUNT(*) AS count
FROM
{field_data_field_field_route_matrix} routes
LEFT OUTER JOIN {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = 'n.nid') AND (field_flight_destination_tid IN  ('31', '366')) ) total
LEFT OUTER JOIN {field_data_field_flight_hero_destination} dest ON n.nid = dest.entity_id
LEFT OUTER JOIN {field_data_field_flight_price_matrix} prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = '86')
ORDER BY total.count DESC

Comment: db_select has the curly braces around it '{'... eg: '{field_data_field_field_route_matrix}'.. ??
Comment: Hmm... didn't notice that, but removing them has no effect.
Comment: Just to make sure, you removed them from the left join in your subquery as well?
Comment: did you install the Devel module and do `dpq($query)` to see what output drupal is generating for your `db_select` ?
Comment: Yes. It is as if the subquery wasn't there at all.
Comment: @tenken, I don't have access to Devel (long story) but I have updated the question with the generated query string.
Comment: @tenken, I have managed to get access to Devel and have attached to the question.
Answer: Your adding the subquery via a join. you want the subquery to be run as piece of the outermost Select statement, which Drupal 7 SelectQuery cannot do see:
https://stackoverflow.com/questions/20214014/how-do-i-place-a-sub-query-in-a-select-statement-in-drupal7
The easiest way to do this to use db_query (a string) or maybe hook_query_alter after adding a tag to the db_select query and adding in the subquery via a string  later. If you need additional info passed in and out the hook_query_alter then use the metadata options.
Comment: Thanks @tenken. I added the subquery SQL with `addExpression`, and it appears to have worked wonderfully.


Does $(AB)^m = I_n$ imply $(BA)^m = I_n$?

Question: The problem is to prove or disprove that $(AB)^m = I_n$ imply $(BA)^m = I_n$ where $A, B \in M_n(\mathbb{R})$ and $m \in \mathbb{Z}$.
I know that it's true for $m = 1$, and I tried to use the induction on $m$, but could not prove the statement.
Answer: For negative $m$, note that $(AB)^m=I$ implies $[(AB)^m]^{-1}=(AB)^{-m}=I$.
Since $A,B$ are invertible, we get $B\underbrace{(AB)(AB)...(AB)}_{|m|\text{ times}}B^{-1}=BIB^{-1}=I$ and using the associativity of matrix multiplication we get $(BA)^{|m|}=I$.
For negative $m$, this implies $(BA)^{-|m|}=(BA)^m=I$.
Comment: Could you comment on the invertibility? Are you are taking determinants to check it or what ?
Comment: @Thomas Yeah, you can take determinants. Or we can note that $\ker(B)\subseteq\ker(AB)\subseteq\ker((AB)^m)=\{0\}$.
Comment: Perfect thanks!
Answer: From $(AB)^m=I_n$, one obtain $A^{-1}=B(AB)^{m-1}$.
Hence $(BA)^m=B(AB)^{m-1}A=I_n$.


How to open a url using an adress of an application

Question: How to open a URL without webbrowser using Python, but with an address of the application with which I want to open it.
Comment: Take a look at ```urllib``` or ```requests``` libraries
Comment: What exactly are you trying to do? Access an API? Scrape a website?
Comment: Just to be clear: You are trying to open a *non-http/https* URI? For example, ``ms-chat:?ContactID=SomeOne``?
Comment: I was trying to open zoom without opening the webbrowser like using application address as i couldnt find a way i thought of finding a common way
Comment: Maybe that's what you are looking for: [Start a Zoom meeting from the command line](https://superuser.com/questions/1563255/start-a-zoom-meeting-from-the-command-line)
Answer: Try selenium, although you'll have to first download Chromedriver:
from selenium import webdriver from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox() driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body") body.send_keys(Keys.CONTROL + 't')

driver.close()

Answer: There are three ways to do this

Case 1: You just need to open a page. and that is it,

import webbrowser
webbrowser.open("https://yoursite.com")

The above will open https://yoursite.com on your default browser

Case 2: You need to open, as well as do a task eg refresh

from selenium import webdriver
import time
driver = webdriver.Edge("path to your edge driver")
driver.get("https://yoursite.com")
# The command below will refresh your webbrowser after 3 seconds of opening it
time.sleep(3)
driver.refresh()

If you want to use chrome... use driver = webdriver.Chrome("path to your chrome driver")

Case 3:You have already opened your webbrowser (via selenium) and you are in another program and you want to see it without opening it manually

from selenium import webdriver
import time
driver = webdriver.Edge("path to your edge driver")
driver.get("https://yoursite.com")
time.sleep(10)
# this command stores your webbrowser window in a variable
main_page = driver.current_window_handle
# this command moves the webbrowser to the front
driver.switch_to.window(main_page)

Also you have to install a driver for your browser if you are using the selenium thing...

For edge go to https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#:~:text=Microsoft%20Edge%20WebDriver%20for%20Microsoft%20Edge%20will%20work,find%20your%20correct%20build%20number%3A%20Launch%20Microsoft%20Edge. and choose your edge version...

And for chrome go to https://chromedriver.chromium.org/downloads

You will also have to do pip install selenium in the terminal...
Hope this helps ;)


Implement hook_token_info and hook_tokens

Question: I am trying to create custom tokens, but my implementation doesn't work.
I have implemented hook_token_info() and hook_tokens() like this in my .theme file for Drupal 7.
/**
* Implements hook_token_info().
*/
function THEMENAME_token_info() {
  $info = array();

  $info['types'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'name' => t('Commerce Order Billing'),
      'description' => t('Global commerce order billing tokens'),
     ),
  );
  $info['tokens'] = array(
    'commerce-order:commerce-customer-billing' => array(
      'address-info' => array(
        'name' => t('Commerce address information'),
        'description' => t('Token for commerce address information'),
      ),
    ),
  );
  return $info;
}

/**
*
* Implements hook_tokens().
*/
function THEMENAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'commerce-order:commerce-customer-billing') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
      case 'address-info':
        $address_info = theme('nr_commerce_address_information', array('order' => $order));
        $replacements[$original] = $address_info;
        break;
      }
    }
  }
}

When I see the list of available tokens in the interface, my tokens does not show up. Why? Is there anything wrong in my code, or is the reason another one?
Comment: I assume you have cleared your cache? Also, are you sure that noreba module is enabled? Also, D7 or D8?
Answer: I found out. It was because I tried to implement hooks in my template rather than doing it in my module.


TypeError: not all arguments converted during string formatting (python)

Question: Sou novo em programação, estou tentando fazer um programa que verifica se um numero inserido é primo, pra isso estou verificando se o resto da divisão do numero por numeros primos é zero.
def primo():

numero = input("Digite seu numero: ")

    if numero%2 == 0:
        print ("Seu numero não é primo")
    elif numero %3 == 0:
        print ("Seu numero não é primo")
    elif numero %5 == 0:
        print ("Seu numero não é primo")
    elif numero %7 == 0:
        print ("Seu numero não é primo")
    else:
        print ("Seu numero é primo")

mas estou recebendo o erro TypeError: not all arguments converted during string formatting na linha do primeiro "if". O que estou fazendo de errado ?
Answer: Basta converter para inteiro sua entrada
numero = int(input("Digite seu numero: "))

Comment: Muito obrigado, funcionou perfeitamente!
Answer: Acontece que o retorno da função input é sempre uma string:

input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

E no Python o tipo string possui o operador % que faz a formatação. Por exemplo, se você faz '%s %s' % ('Anderson', 'Woss') terá a string final  'Anderson Woss'. Sobre o operador e outras formas formatar uma string ver:

O que utilizar para formatar uma string, % ou format?

Como a intenção é trabalhar com números, basta você criar uma instância de int a partir da sua string:
numero = int(input('...'))

E, assim, o operador % será resto de divisão como esperado e não mais um operador de formatação.


Drupal custom coding checkout redirect not working

Question: I have used custom coding to add a product into a cart.

 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_module_my_form3',1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
function custom_module_my_form3($form, &$form_state,$id) {
global $user;
$product_id=$id;
$product = commerce_product_load($product_id);
$quantity=1;
$line_item = commerce_product_line_item_new($product, $quantity);
$line_item_added = commerce_cart_product_add($user->uid, $line_item);
$order_id=$line_item_added->order_id;
drupal_goto('checkout/'.$order_id);
}

Product added succesfully in the cart but redirecting into checkout page doesn't work.It redirecting into home page.
I have created link for each product like buynow/product_id. I have also created a custom menu path like buynow/%.
After that put the above code in the callback by passing argument.
Comment: why you try use form where there is not any form element in your form !!!!
do it with just menu callback handler, check my answer agian
Answer: Your fault is want using drupal_goto in form builder!!!
Change your code to this
 $items['buynow/%'] = array(
    'title' => t('buynow'),
    'page callback' => 'custom_module_my_form3',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

function custom_module_my_form3() {
   global $user;
   $id=arg(1);
   $product_id=$id;
   $product = commerce_product_load($product_id);
   $quantity=1;
   $line_item = commerce_product_line_item_new($product, $quantity);
   $line_item_added = commerce_cart_product_add($user->uid, $line_item);
   $order_id=$line_item_added->order_id;
   drupal_goto('checkout/'.$order_id);
}

Comment: Thank you for your answer.But this doesn't work for me.
Comment: @Rajeev you're welcome, I think you are in submit handler, I update my answer with another solution.try it
Comment: I have used it.But no use brother.order created and product added cart successfully.still it redirecting to home page.
Comment: @Rajeev you test my code and it redirect you to home page?
Comment: Yes, I have  tested.It's redirecting to home page. Is there any problem in code on adding product to cart
Comment: it is strange , comment every line in function and just let `drupal_goto('testaddress');` , I think there is a rule (or something like it) that redirect user after  a product added to cart
Comment: I think it's the problem of creating cart order.Because when i enter /checkout/26, i am redirecting to home page.
Comment: Is there any option of buy now button with add to cart. I wish to use both buttons.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/32994/discussion-between-rajeev-and-zhilevan).