text:
Q: Why doesn't this short OCaml snippet with Printf.printf work? I'm a OCaml newbie. I'm playing around with "hello world" type snippets and came across this situation.
Here's a session with the interpreter with some extra comments:
# let average a b =
  (a +. b) /. 2.;;
val average : float -> float -> float = <fun>
# average 1. 4.;;
- : float = 2.5
# string_of_float (average 1. 4.);;
- : string = "2.5"

(* this fails...*)
# let _ = Printf.printf (string_of_float (average 1. 4.));;
Error: This expression has type string but an expression was expected of type
         ('a, out_channel, unit) format =
           ('a, out_channel, unit, unit, unit, unit) format6

(* yet this works *)
# "hello!";;
- : string = "hello!"
# let _ = Printf.printf "hello!";;
hello!- : unit = ()

(* another failed attempt *)
# let s = string_of_float (average 1. 4.);;
val s : string = "2.5"
# s;;
- : string = "2.5"
# let _ = Printf.printf s;;
Error: This expression has type string but an expression was expected of type
         ('a, out_channel, unit) format =
           ('a, out_channel, unit, unit, unit, unit) format6

(* and this also works?? *)
# let _ = Printf.printf "2.5";;
2.5- : unit = ()

So here's the situation. string_of_float (average 1. 4.) returns a string,
just as "hello!" does. When I give "hello!" into Printf.printf, it works
as expected. When I give string_of_float (average 1. 4.) to Printf.printf it fails and tells
me it expected didn't expect a string but that other weird type. But why do "hello!" and "2.5" work then?
What's going on?

A: Printf.printf "%s" anyStringExpr

will work.  The first argument to printf is somewhat magical.  (Others will fill in the details.)

A: There is a kind of "overloading" of the meaning of string literals in OCaml. At compile time, they can either be interpreted as a string, or as a format (which are completely different things in the type system), depending on what the type-checker thinks. If it decides that it should be a format, then the format string is parsed directly at compile-time (that is why it is able to type-check the arguments to printf at compile time). (Unlike C, which parses the string at runtime.) However, there is no simple way to convert from a string into a format at runtime. So when you see Printf.printf "2.5", the "2.5" is actually not a string, but as a special format type that was parsed at compile-time. That is why you cannot substitute a string for it.
On an unrelated note, if you just want to print a string, you might want to use print_string (or print_endline if you want a newline).


text:
Q: git svn fetch is separating branch's subfolders into their own remote branches I'm trying to migrate my SVN repo into a git repo, with a non-standard layout. I have my trunk and branches in the same folder in the SVN repo. My SVN repository's structure is like so:
branches/
  releases/
    1.0/
      back_end/
      front_end/
    2.0/
      back_end/
      front_end/
    ...
    trunk/
      back_end/
      front_end/

So I'm trying to set the git repo's trunk as the branches/releases/trunk folder, and the branches as each of the versioned folders within the branches/releases/ directory. My commands are:
git svn init -T /branches/releases/trunk --branches="/branches/releases/{1.0,2.0}" [repo_url]
git svn fetch --authors-file=authors.txt

This is almost working as intended, and the trunk looks to be correctly migrated. However the remote branches that are created to mimic the svn branches are divided up into each subfolder (front_end, back_end). Looks like this when running git branch -r:
origin/1.0/front_end
origin/1.0/back_end
origin/2.0/front_end
origin/2.0/back_end
origin/trunk

Does anyone know why the branches might be separated like this?

A: In git svn option --branches doesn't list branches, it lists the parent directory under which Subversion stores subdirectories that imitates branches in SVN. Given the structure above option --branches="/branches/releases/{1.0,2.0}" creates 4 branches: 1.0/front_end, 1.0/back_end, 2.0/front_end, 2.0/back_end. That's exactly what you see.
If you want just 2 branches 1.0 and 2.0 the option should be --branches=/branches/releases/. Then every of these 2 branches will have 2 subdirectories front_end and back_end, exactly like the trunk.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot Post/ in express js I have the following code and also have defined the response for POST/messages but when I go to /bc/add and submit a form it shows that Cannot POST /messages.
Can you please explain me the reason?
Here is my code :
 const express = require("express");
  const bodyParser = require("body-parser");

  const app = express();
  app.use(bodyParser.urlencoded({ extended: false }));

  app.use("/bc/add", (req, res, next) => {
    console.log("In the next middleware !", req.url);
    res.send(
      '<form action="/messages" method="post"><input  type="text" name="message"><button type="submit">Submit </button></form>'
    );

    app.use("/s", (req, res, next) => {
      res.send("hup");
    });

    app.post("/messages", (req, res, next) => {
      console.log(req.body);
      console.log("In the middleware !", req.url);
      res.redirect("/s");
    });
  });

  app.use("/favicon.ico", (req, res, next) => {
    console.log("In the middleware !", req.url);
    res.sendStatus(204);
  });
  app.listen(3000, () => {
    console.log("Server running at port 3000");
  });

A: You are declaring handlers inside a middleware, which isn't how Express works.
The handlers need to be declared at the "top level":
app.use("/bc/add", (req, res, next) => {
  console.log("In the next middleware !", req.url);
  res.send(
    '<form action="/messages" method="post"><input  type="text" name="message"><button type="submit">Submit </button></form>'
  );
}); // end of the "middleware"

app.use("/s", (req, res, next) => {
  res.send("hup");
});

app.post("/messages", (req, res, next) => {
  console.log(req.body);
  console.log("In the middleware !", req.url);
  res.redirect("/s");
});

Besides that, semantically speaking the handlers for /bc/add/ and /s aren't middleware, but route handlers. It's better to declare them as such explicitely, by using app.get() instead of app.use().


text:
Q: Grouped bar-chart in Kibana using Vega-lite From looking at https://vega.github.io/editor/#/examples/vega-lite/bar_grouped it shows example of creating grouped bar chart from a table of data.
In my case since I am getting data from elasticsearch it is not in tabular form.
I can't figure out a way to create two bar chart for each sum metric on a bucket.
"buckets" : [
        {
          "key_as_string" : "03/Dec/2019:00:00:00 +0900",
          "key" : 1575298800000,
          "doc_count" : 11187,
          "deploy_agg" : {
            "buckets" : {
              "deploy_count" : {
                "doc_count" : 43
              }
            }
          },
          "start_agg" : {
            "buckets" : {
              "start_count" : {
                "doc_count" : 171
              }
            }
          },
          "sum_start_agg" : {
            "value" : 171.0
          },
          "sum_deploy_agg" : {
            "value" : 43.0
          }
        },..

I want to create two bars, one representing value of sum_start_agg and another one representing sum_deploy_agg value.
This is what I had for one bar chart.
  "encoding": {
    "x": {
      "field": "key",
      "type": "temporal",
      "axis": {"title": "DATE"}
    },
    "y": {
      "field": "deploy_agg.buckets.deploy_count.doc_count",
      "type": "quantitative",
      "axis": {"title": "deploy_count"}
    }
    "color": {"value": "green"}
    "tooltip": [
        {
        "field": "deploy_agg.buckets.deploy_count.doc_count",
        "type": "quantitative",
        "title":"value"
        }
      ]
  }

A: You can use the Fold Transform to fold your two columns so that they can be referenced in an encoding. It might look something like this:
{
  "data": {
    "values": [
      {
        "key_as_string": "03/Dec/2019:00:00:00 +0900",
        "key": 1575298800000,
        "doc_count": 11187,
        "deploy_agg": {"buckets": {"deploy_count": {"doc_count": 43}}},
        "start_agg": {"buckets": {"start_count": {"doc_count": 171}}},
        "sum_start_agg": {"value": 171},
        "sum_deploy_agg": {"value": 43}
      }
    ]
  },
  "transform": [
    {
      "fold": ["sum_start_agg.value", "sum_deploy_agg.value"],
      "as": ["entry", "value"]
    }
  ],
  "mark": "bar",
  "encoding": {
    "x": {"field": "entry", "type": "nominal", "axis": null},
    "y": {"field": "value", "type": "quantitative"},
    "column": {"field": "key", "type": "temporal"},
    "color": {"field": "entry", "type": "nominal"}
  }
}


text:
Q: Redirect to third party payment gateway using POST authentication I have an almost complete solution for a custom payment method in Magento. I followed [this] http://www.junaidbhura.com/how-to-make-a-custom-magento-payment-extension-for-an-external-gateway/ excellent tutorial on how to do it but I am now stuck with an authentication problem.
I contacted the gateway and an IT representative told me that I must post the correct values to the gateway for authentication. These values must also be sent in XML format:
Testmode Username: ######
Testmode Password: ######
Testmode MerchantID: #####
Testmode TerminalID:#####
BIN = ######1
I've created a system.xml in my the gateway module with the correct fields:
<?xml version="1.0"?>
<config>
  <sections>
    <payment>
      <groups>
        <mygateway translate="label comment" module="mygateway">
          My Module mygateway
          <frontend_type>text</frontend_type>
          <sort_order>0</sort_order>
          <show_in_default>1</show_in_default>
          <show_in_website>1</show_in_website>
          <show_in_store>1</show_in_store>
          <fields>
            <active translate="label">
              Enabled
              <frontend_type>select</frontend_type>
              <source_model>adminhtml/system_config_source_yesno</source_model>
              <sort_order>10</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
            </active>
            <title translate="label">
              My Module mygateway Paymentech
              <frontend_type>text</frontend_type>
              <sort_order>20</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>1</show_in_store>
            </title>
            <order_status translate="label">
              New Order Status
              <frontend_type>select</frontend_type>
              <source_model>adminhtml/system_config_source_order_status</source_model>
              <sort_order>50</sort_order>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
            </order_status>
            <allowspecific translate="label">
              Payment Applicable From
              <frontend_type>select</frontend_type>
              <sort_order>61</sort_order>
              <source_model>adminhtml/system_config_source_payment_allspecificcountries</source_model>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
            </allowspecific>
            <specificcountry translate="label">
              Countries Payment Applicable From
              <frontend_type>multiselect</frontend_type>
              <sort_order>70</sort_order>
              <source_model>adminhtml/system_config_source_country</source_model>
              <show_in_default>1</show_in_default>
              <show_in_website>1</show_in_website>
              <show_in_store>0</show_in_store>
              <depends>
                <allowspecific>1</allowspecific>
              </depends>
            </specificcountry>
            <sort_order translate="label">
              Sort Order
              <frontend_type>text</frontend_type>
            </sort_order>
            <sort_order>100</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>0</show_in_store>
            <test_apiusername translate="label">
                            Test Mode Username
                            <frontend_type>text</frontend_type>
                            <sort_order>6</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </test_apiusername>
                        <test_apipassword translate="label">
                            Test Mode Password
                            <frontend_type>obscure</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>7</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </test_apipassword>
                        <test_MerchantID translate="label">
                            Test Mode MerchantID
                            <frontend_type>text</frontend_type>
                            <sort_order>8</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </test_MerchantID>
                        <test_TerminalID translate="label">
                            Test Mode TerminalID
                            <frontend_type>text</frontend_type>
                            <sort_order>9</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </test_TerminalID>
                        <test_BINNumber translate="label">
                            Test Mode BIN
                            <frontend_type>text</frontend_type>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </test_BINNumber>
                        <test_cgi_url>
                            Test Mode Gateway URL
                            <frontend_type>text</frontend_type>
                        <sort_order>11</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        <comment>Above values should be entered for Test account</comment>
                        </test_cgi_url>
                        <apiusername translate="label">
                            <![CDATA[Production]]> Mode Username
                            <frontend_type>text</frontend_type>
                            <sort_order>12</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </apiusername>
                        <apipassword translate="label">
                            <![CDATA[Production]]> Mode Password
                            <frontend_type>obscure</frontend_type>
                            <backend_model>adminhtml/system_config_backend_encrypted</backend_model>
                            <sort_order>13</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </apipassword>
                        <MerchantID translate="label">
                            <![CDATA[Production]]> Mode MerchantID
                            <frontend_type>text</frontend_type>
                        <sort_order>14</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </MerchantID>
                        <TerminalID translate="label">
                            <![CDATA[Production]]> Mode TerminalID
                            <frontend_type>text</frontend_type>
                        <sort_order>15</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </TerminalID>
                        <BINNumber translate="label">
                            <![CDATA[Production]]> Mode BIN
                            <frontend_type>text</frontend_type>
                        <sort_order>16</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </BINNumber>
          </fields>
        </mygateway>
      </groups>
    </payment>
  </sections>
</config>

I am a unsure about the implementation the POST values needed for authentication into the PaymentController.php
<?php

class Myname_Mygateway_PaymentController extends Mage_Core_Controller_Front_Action {
    // The redirect action is triggered when someone places an order
    public function redirectAction() {
        $this->loadLayout();
        $block = $this->getLayout()->createBlock('Mage_Core_Block_Template','mygateway',array('template' => 'mygateway/redirect.phtml'));
        $this->getLayout()->getBlock('content')->append($block);
        $this->renderLayout();
    }

    // The response action is triggered when your gateway sends back a response after processing the customer's payment
    public function responseAction() {
        if($this->getRequest()->isPost()) {

            /*
            /* Your gateway's code to make sure the reponse you
            /* just got is from the gatway and not from some weirdo.
            /* This generally has some checksum or other checks,
            /* and is provided by the gateway.
            /* For now, we assume that the gateway's response is valid
            */

            $validated = true;
            $orderId = '123'; // Generally sent by gateway

            if($validated) {
                // Payment was successful, so update the order's state, send order email and move to the success page
                $order = Mage::getModel('sales/order');
                $order->loadByIncrementId($orderId);
                $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, 'Gateway has authorized the payment.');

                $order->sendNewOrderEmail();
                $order->setEmailSent(true);

                $order->save();

                Mage::getSingleton('checkout/session')->unsQuoteId();

                Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/success', array('_secure'=>true));
            }
            else {
                // There is a problem in the response we got
                $this->cancelAction();
                Mage_Core_Controller_Varien_Action::_redirect('checkout/onepage/failure', array('_secure'=>true));
            }
        }
        else
            Mage_Core_Controller_Varien_Action::_redirect('');
    }

    // The cancel action is triggered when an order is to be cancelled
    public function cancelAction() {
        if (Mage::getSingleton('checkout/session')->getLastRealOrderId()) {
            $order = Mage::getModel('sales/order')->loadByIncrementId(Mage::getSingleton('checkout/session')->getLastRealOrderId());
            if($order->getId()) {
                // Flag the order as 'cancelled' and save it
                $order->cancel()->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, 'Gateway has declined the payment.')->save();
            }
        }
    }
}

And finally the form which redirects ie redirect.phtml
<?php
// Retrieve order
$_order = new Mage_Sales_Model_Order();
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$_order->loadByIncrementId($orderId);
?>
<form name="mygatewayform" method="post" action="http://www.gateway.com/the_url_they_gave_me">
    <input type="hidden" name="orderid" value="<?php echo $orderId; ?>">
    <input type="hidden" name="grandtotal" value="<?php echo $_order->getBaseGrandTotal(); ?>">
</form>

I was able to run a test order but the gateway only received my order due to IP logging and it was in the incorrect format. I've been searching the Magento forums and Google for nearly three weeks before posting here but I have found no solution. The gateway are unable to help as the have no Magento integration manual available either.
I'd be really grateful for some assistance if its not too much trouble...

A: The instruction that your following is for creating a payment that will redirect to a third party gateway.
The URL that the payment gateway needs to redirect to on your web site after processing the customer's payment (based on the naming we've used in this example) should be: http://www.yourwebsite.com/mygateway/payment/response .
The best way to do what your trying to accomplish is to follow this http://www.excellencemagentoblog.com/magento-create-custom-payment-method-api-based .
Also see

/app/code/core/Mage/Paygate/Model/Authorizenet.php

//create xml and send info to gateway
private function callApi(Varien_Object $payment, $amount,$type){

    //call your authorize api here, incase of error throw exception.
    //only example code written below to show flow of code

    /*
     $order = $payment->getOrder();
    $types = Mage::getSingleton('payment/config')->getCcTypes();
    if (isset($types[$payment->getCcType()])) {
    $type = $types[$payment->getCcType()];
    }
    $billingaddress = $order->getBillingAddress();
    $totals = number_format($amount, 2, '.', '');
    $orderId = $order->getIncrementId();
    $currencyDesc = $order->getBaseCurrencyCode();

    $url = $this->getConfigData('gateway_url');
    $fields = array(
            'api_username'=> $this->getConfigData('api_username'),
            'api_password'=> $this->getConfigData('api_password'),
            ......

            'customer_firstname'=> $billingaddress->getData('firstname'),
            'customer_lastname'=> $billingaddress->getData('lastname'),
            'customer_phone'=> $billingaddress->getData('telephone'),
            'customer_email'=> $billingaddress->getData('email'),
            'customer_ipaddress'=> $_SERVER['REMOTE_ADDR'],
            'bill_firstname'=> $billingaddress->getData('firstname'),
            'bill_lastname'=> $billingaddress->getData('lastname'),
            'Bill_address1'=> $billingaddress->getData('street'),
            'bill_city'=> $billingaddress->getData('city'),
            'bill_country'=> $billingaddress->getData('country_id'),
            'bill_state'=> $billingaddress->getData('region'),
            'bill_zip'=> $billingaddress->getData('postcode'),
            'customer_cc_expmo'=> $payment->getCcExpMonth(),
            'customer_cc_expyr'=> $payment->getCcExpYear(),
            'customer_cc_number'=> $payment->getCcNumber(),
            'customer_cc_type'=> strtoupper($type),
            'customer_cc_cvc'=> $payment->getCcCid(),
            'merchant_ref_number'=> $order->getIncrementId(),
            'currencydesc'=>$currencyDesc,
            'amount'=>$totals
    );

    $fields_string="";
    foreach($fields as $key=>$value) {
    $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = substr($fields_string,0,-1);
    //open connection
    $ch = curl_init($url);
    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
    curl_setopt($ch, CURLOPT_HEADER ,0); // DO NOT RETURN HTTP HEADERS
    curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1); // RETURN THE CONTENTS OF THE CALL
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // Timeout on connect (2 minutes)
    //execute post
    $result = curl_exec($ch);
    curl_close($ch);
    */

    return array('status'=>1,'transaction_id' => time() , 'fraud' => rand(0,1));
}


text:
Q: Raspberry pi 64 bit Os showing Unable to locate package libjasper-dev. how to fix this? I am using a raspberry pi 4.
And I installed a 64-bit (not 32-bit) Raspberry Pi OS.
When I tried to install libjasper-dev using the command
'sudo apt-get install libjasper-dev' as a part of OpenCV.
It is showing "Unable to locate package libjasper-dev".
Does anyone have any idea how to fix this, or how to compile OpenCV correctly on a Rasbian 64Bit ?
For example, this (among other errors) happens when installing the image raspios_lite_arm64-2021-11-08 on an 8GB Raspi4 and trying to follow the instructions on https://www.arducam.com/docs/cameras-for-raspberry-pi/synchronized-stereo-camera-hat/opencv-and-depth-map-on-arducam-stereo-camera-hat-tutorial/:
pi@roverpi:~ $ sudo apt-get install libhdf5-dev libhdf5-serial-dev libatlas-base-dev libjasper-dev libqtgui4 libqt4-test
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Note, selecting 'libhdf5-dev' instead of 'libhdf5-serial-dev'
Package libqtgui4 is not available but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Unable to locate package libjasper-dev
E: Package 'libqtgui4' has no installation candidate
E: Unable to locate package libqt4-test

Anyone know how to fix this


text:
Q: Based On Styling Indesign Javascript Scripting CC I would like to know how I can set (either directly or some other alternative method) the style property of "Based on" using JavaScript within Adobe InDesign CC. If I could also ask for documentation leading to an answer for reference it would be immensely appreciated.
My code:
var myPStyles = app.activeDocument.paragraphStyles;
var myPGroupStyles = app.activeDocument.paragraphStyleGroups;

// paragraph style 0 [No Paragraph Style]
// paragraph style 1 [Basic Paragraph Style]

var masterPGroupStyles = myPGroupStyles.add({name:"Master Fonts"});
var masterFont1 = masterPGroupStyles.paragraphStyles.add({name:"Font1"});
var masterFont2 = masterPGroupStyles.paragraphStyles.add({name:"Font2"});

Goal: To base Font2 on Font1

A: That property is called (not quite surprisingly) basedOn. The following will work to create your masterFont2 style based on masterFont1:
var masterFont2 = masterPGroupStyles.paragraphStyles.add({name:"Font2", basedOn:masterFont1});

Contrary to what you say in your post, not providing a basedOn property will not assign "Basic Paragraph Style", it will always be "No Paragraph Style".

You can find all properties of paragraph styles in the ExtendScript Toolkit Editor that comes with InDesign, in the Object Model Viewer under "Help". Enter 'paragraphStyle' (singular) in the Search field and you will get a list of topics. Then open the panel "Browser" and you'll see ... oh wait, I haven't used the ESTK for so long I actually forgot why I hated it: you will get this not so useful flash card:

All the help is available and I have been told you can actually reach it with this fancy interface, but these days I simply don't bother. Depending on your version of InDesign (actually the differences are only minor), check my cached version at MIT of Class ParagraphStyle for CS6 (older versions are available there as well) or, for CC-and-newer, Gregor Fellenz' InDesign ExtendScript API (10.0) - ParagraphStyle.
Both of these sets of pages are generated from the exact same data that Adobe uses for its own editor, but the data appears in a much friendlier format. The MIT version lacks a search box, but the files can be downloaded from my own site in CHM compiled form. Gregor's site comes complete with nice search fields.
These both are reference sites and assume basic knowledge of Javascript and its interface to InDesign's Document Object Model. For more information on the basics, you can always check Adobe's own list of introductions and tutorials.


text:
Q: Y axis Header in Chart I am creating a chart as a user control in WPF. For the Y axis header I had added a textbox. It is displayed in the vertical direction. User can edit the title. While clicking on the textbox, it should be rendered in horizontal direction over the chart plot area. After user entered the text it should be in the default vertical direction.
How can I achieve this?

A: You can rotate on focus styling your textboxes. Something like
<Style TargetType="{x:Type TextBox}">
                <Setter Property="RenderTransform">
                    <Setter.Value>
                        <RotateTransform Angle="-90"></RotateTransform>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="IsFocused" Value="True">
                        <Setter Property="RenderTransform">
                            <Setter.Value>
                                <RotateTransform Angle="0"></RotateTransform>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>


text: Q: The third person template by unity instantly plays when I click the play button I have tried with other projects but the third person template seems to be the only project that immediately starts the moment I click play. Does the project have a script that does this? It isn't really a problem but confuses me.


text:
Q: Why does it take so long for Android's MediaPlayer to prepare some live streams for playback? I am finding big differences in the time it takes the Android MediaPlayer to prepare for live stream playback with different streams.
The hard data
I added logging between prepareAsync() and the onPrepared(MediaPlayer mp) callback and tested several streams a few times each.  The times for each stream were very consistent (+/- one second), and here are the results:

*

*MPR news stream: 27 seconds (http://newsstream1.publicradio.org:80/)

*MPR classical music stream: 15 seconds (http://classicalstream1.publicradio.org:80/)

*MPR The Current stream: 7 seconds (http://currentstream1.publicradio.org:80/)

*PRI stream: 52 seconds (http://pri-ice.streamguys.biz/pri1)

The tests were performed on a Nexus S with Android 2.3.4 on a 3G connection (~1100 Kbps).
Playing non-streaming MP3 audio files is not an issue.
Here are snippets of how I am playing the streams:
Prepare MediaPlayer:
...
mediaPlayer.setDataSource(playUrl);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
...

Then in onPrepared(MediaPlayer mp):
mediaPlayer.start();

Why does it take so long to prepare some streams but not others?  The above data seems to suggest that it might be based on the amount of data that has been buffered and not the duration of the buffered audio content.  Could this really be?
Update: I have tested live streaming on physical devices with Android 1.6, 2.2 and 2.3.4 and emulators with 1.6, 2.1, 2.2, 2.3.1 and 2.3.3.  I am only seeing the long delay on 2.3.3 and 2.3.4.  The older versions start playback within 5 seconds.

A: Switch MediaPlayer by FFmpegMediaPlayer
 works much betther than the MediaPlayer if you want to test your streams you can do it through the demo that they have.

A: I have recently debugged this same issue with a streaming audio provider. The issue is related to stagefright and streaming sources 32kbps and lower. We stepped through the same streaming measuring the response time at 24, 32, 48, 64 and 128 kbps.

*

*24 -> 46 seconds to start streaming

*32 -> 24 seconds to start streaming

*48 -> 2 seconds to start streaming

*64 -> 2 seconds to start streaming

*128 -> 2 seconds to start streaming

This is from a consistent, wireless connection averaged over 10 attempts at each bit rate. The key, as Travis pointed out, was that stagefright could not figure out how long to buffer the audio. Sometimes i would see a message 'error: 1,-21492389' or so, which seemed to crash the stagefright player silently. I tried to track this down and eventually came to the conclusion that the very slow streams (sub 24 kbps) seemed to cause a buffer overflow because they would buffer until the device ran out of space for the audio stream.
I wanted to add that OnBufferingUpdateListener did not fire at all for me during this entire test. I don't know what it is there for. I think the only way you can tell how loading is going is to proxy the loading, in a similar fashion to the NPR app mentioned above.

A: It does appear that it is buffering a fixed amount of data rather than a fixed amount of time.  For anyone who doesn't know the bitrates of various types of NPR streams off the top of their head, the data looks like:

*

*MPR news stream: 27 seconds (http://newsstream1.publicradio.org:80/), 64 kbps

*MPR classical music stream: 15 seconds (http://classicalstream1.publicradio.org:80/), 128 kbps

*MPR The Current stream: 7 seconds (http://currentstream1.publicradio.org:80/), 128 kbps

*PRI stream: 52 seconds (http://pri-ice.streamguys.biz/pri1), 32 kbps
Apart from the discrepancy between the two 128 kbps streams, there is a very good correlation between bitrate and buffering duration.
In any case, Android is open-source, so you could always look at what it's doing.  Unfortunately, prepareAsync() and prepare() are native methods, and it appears that buffer-related events are dispatched from a native process as well.
Have you tried attaching an OnBufferingUpdateListener to the MediaPlayer to get finer-grained updates about the buffer-state?  It might be interesting to compare the rate at which the events are delivered and by what percentage the buffer fills on each event across the different streams.  You can cross-reference that against the stream bitrates, and if 4 seconds of buffering at 32 kbps fills the buffer the same percentage as 1 second of buffering at 128 kbps then I think you will have found your answer.

A: I've tried this with 10 datapoints, three fast, 7 slow.
It's consistent, that is a fast stream is fast and a slow one is always slow.
I think it's related to the server delivered 'content-length,' Android doesn't know how much to buffer if the content-length isn't properly specified.
Could be wrong, didn't go as far as wiresharking.

A: If you're streaming from Icecast, take a look at the burst-size setting:

The burst size is the amount of data (in bytes) to burst to a client
  at connection time. Like burst-on-connect, this is to quickly fill the
  pre-buffer used by media players. The default is 64 kbytes which is a
  typical size used by most clients so changing it is not usually
  required. This setting applies to all mountpoints unless overridden in
  the mount settings. Ensure that this value is smaller than queue-size,
  if necessary increase queue-size to be larger than your desired
  burst-size. Failure to do so might result in aborted listener client
  connection attempts, due to initial burst leading to the connection
  already exceeding the queue-size limit.

I increased the burst-size to 131072 on my server, and now my Android app based on MediaPlayer plays streams without much delay.

A: When I had this problem I decided to test if stream is available before opening the player. If you make the user to wait for a long time and the music will start it ok (it's not, but let's say it is ok).
The worst case scenario is to make him wait for a long time and the music will never start!
So, we have 2 situations:

*

*The live streaming scenario, like a radio station.

*The recorded mp3 file which is available online.

At the radio scenario we could check if the port is accepting connections (open/close state). If it is open prepare the player for the music, else do not prepare it at all.
public static boolean isLiveStreamingAvailable() {
        SocketAddress sockaddr = new InetSocketAddress(STREAMING_HOST, STREAMING_PORT);
        // Create your socket
        Socket socket = new Socket();
        boolean online = true;
        // Connect with 10 s timeout
        try {
            socket.connect(sockaddr, 10000);
        } catch (SocketTimeoutException stex) {
            // treating timeout errors separately from other io exceptions
            // may make sense
            return false;
        } catch (IOException iOException) {
            return false;
        } finally {
            // As the close() operation can also throw an IOException
            // it must caught here
            try {
                socket.close();
            } catch (IOException ex) {
                // feel free to do something moderately useful here, eg log the event
            }

        }
        return true;
    }

At the mp3 file scenario the things are a little bit different. You should check for the response code which follows after the http request.
public static boolean isRecordedStreamingAvailable() {
        try {
            HttpURLConnection.setFollowRedirects(false);
            // note : you may also need
            //        HttpURLConnection.setInstanceFollowRedirects(false)
            HttpURLConnection con =
                    (HttpURLConnection) new URL(RECORDED_URL).openConnection();
            con.setRequestMethod("HEAD");
            return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


text:
Q: How can I avoid notes to be deleted from the iPhone when I delete them on my Mac Email app? Since the last software update on my iPhone 3 all the notes that I writte on the iPhone appears in the mail.app on my mac as income mails.
When I delete the notes at the Mail.app, they are also deleted at the iPhone.
Do you know how to avoid the notes to be deleted?
Thanks!

A: Turn off notes sync in Settings -> Mail,Calender,Contacts -> select your account and then turn off notes sync.
In Mail if you hit command + comma you can also stop showing notes in the inbox.

A: When you connect your iPhone, you should have the option in iTunes to turn off the syncing of your Notes.
http://support.apple.com/kb/HT4191

A: *

*Go to Preferences in Mail.app on your iMac

*Go to account

*Then, click account that notes hooked in

*See, the show notes in inbox

*Unchecked it

Good luck :D


text:
Q: Does it make sense and is it to acceptable to say ".NET code"? There is C# code, VB.NET code... Can I also say ".NET code" as an umbrella term that covers all the languages you can use with the .NET framework?
I've seen people using it as well as people saying it shouldn't be used...

A: Common Language Infrastructure or CLI is  the executable code and runtime environment that form the core of the Microsoft .NET Framework and the free and open source implementations Mono
Common Language Runtime (CLR) is the virtual machine component of .NET
Common Intermediate Language (CIL, formerly MSIL) is the lowest-level human-readable programming language defined by the Common Language Infrastructure (CLI) specification and is used by .NET

A: A lot of such umbrella terms I've seen, like C/C++ or C++/C#/Java, or C-family, don't work at all. However, in the case of .NET, it's a lot more sane. This is because the Framework imposes a type system, base classes libraries, and such on every .NET language. So strictly, all languages which lower into CLR bytecode must have a fair chunk in common with each other.
You could also argue that .NET code would refer to the CLR's bytecode.

A: C# code could be running via Mono which isn't .NET. Thus something along the lines of CLI (Common Language Infrastructure) Code would be a better way of referring to it. The CLR is Microsoft's implementation of the CLI which is an open standard.

A: I'd say the .Net code term fits binary code (CIL Byte code) allot better then source code - and at that stage you're no longer talking about languages.
With .Net it makes some sense to use an umbrella word for all the languages that could be compiled into CIL targeting the CLR, but .Net languages sounds allot better then .Net code. This expression would of course tell you something about the binary compatibility of the resulting code, and almost nothing about the languages themselves. It's like calling all the languages that can compile code compatible with the Intel x86 a name: There was a time when that was useful, but not any more. There might also have been a time when that could have told you something about the languages themselves (along the lines of: they probably support pointers, they probably support function calls) - but again, not any more.

A: Well I work with .Net for a living and we (as in the organisation) always refer to it as .Net, irrespective of whether the code is written in C#.Net, VB.Net or when writing web front ends aspx.Net
I would have thought this is fairly widespread ussage. Certainly people in other componies use the same language. My current job title is .Net Developer.
So, yes, we call it .Net programming as an umbrella term.

A: Depends on the where the term is being used.  If its marketing blurb about your company product technology then i'd guess it would do, but on your CV, looking for a job its a bad choice.
Think about the recruitment process from the side of the recruiter. They have 50 CV's on their desk and need to shortlist 5 for interview. Assuming you have the legal right to work in the country where the job is based (yep, people apply for jobs they cannot legally do) and have not too many spelling mistakes then the focus goes onto your technical ability.
If you are wanting to join a team of C# developers, and have C# development experience then for heavens sake, say it clearly. If your experience is VB, say that clearly too. The recruiter is then able to make a decision on if they are willing to cross train you.
On the other side, If you just say '.NET' then you create uncertainty. Uncertainty is another way of saying 'risk'. For the person recruiting, they want to interview candidates that are likely to be recruitable for the job. Are there 5 other people out there that have shown clearly how they could have the skills to do the job? If so, you've just missed the cut for interview.


text:
Q: Omit double cloning value passed to function I am writing a file watcher in Rust and I've encountered a problem with double cloning INotify to use it in spawned scope:
fn watch_file(watcher: INotify, path: &String) {
    let mut watcher = watcher.clone();
    let path = Path::new(path);
    let pusher = RedisPusher::new("redis://127.0.0.1/0", "arkona").unwrap();

    info!("Watching `{}`", path.as_str().unwrap());

    spawn(move || {
        let _ = watcher.watch(path, |_, file| {
            info!("Change in `{}`", file.path().as_str().unwrap());
            file.read_to_string().map(|content| pusher.push(content)).ok();
        });
    });
}

fn main() {
    let args = os::args();
    let watcher = INotify::init().unwrap();

    for path in args.tail().iter() {
        watch_file(watcher.clone(), path);
    }
}

I am still learning Rust and I cannot find any way to pass mutable watcher as value to this method. Is it the only (and idiomatic) way or is there any possibility to make it happen at most once?

A: On a side note, if you take ownership of a parameter (i.e. the parameter is not a reference), you don't have to declare the mutability in the function signature:
fn add_thing(things: Vec<uint>) -> Vec<uint> {
    let mut things = things; // We own this, so we can make it mutable
    things.push(1);
    things
}

fn main() {
    let things = vec![3, 2];
    let changed = add_thing(things);
    println!("{}", changed);
}

A: I just solved that by @delnan suggestion:
fn watch_file(mut watcher: INotify, path: &String)


text:
Q: Terraform Fails Intermittently to clone Windows VM using template Details
Terrafrom version - Terraform v0.13.3
VCenter Vsphere Version - vSphere Client version 6.7.0.40000
Once in 3 attempts Terraform executes successfully but Sometimes Fails i.e, VM gets created successfully but fails post task with below error.
Failure
[ERROR] eval: *terraform.EvalApplyPost, err: POST https://192.128.1.1/rest/com/vmware/cis/tagging/tag-association?~action=list-attached-tags: 401 Unauthorized
2020/09/23 18:35:03 [ERROR] eval: *terraform.EvalSequence, err: POST https://192.128.1.1/rest/com/vmware/cis/tagging/tag-association?~action=list-attached-tags: 401 Unauthorized
Troubleshooting Done:
The account has Administrator role in VCenter
Checked the sessions of the user and terminated the account used by Terraform still no luck.
Has anyone faced this before?


text:
Q: How to get and set data to Firebase with Node.js? I'm learning the Firebase and Node.js. I want to get my Tweets from Twitter and send them to Firebase. I can retrieve my tweets from Twitter, but couldn't send these tweets to Firebase.
How can I send these tweets retrieved from Twitter to Firebase?
I've tried the following code:
var firebase = require('firebase');

// Initialize
var app = firebase.initializeApp({
    ServiceAccount: {
       projectId: "******",
       clientEmail: "****@gmail.com",
       privateKey: "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----\n"
    },
   databaseURL: "****.firebaseio.com"
});

// Set Sample Data
firebase.database().ref('/').set({
    username: "test",
    email: "test@mail.com"
});

And I got the following error on console:
 Debugger listening on port 5858
 crypto.js:279
  var ret = this._handle.sign(toBuf(key), null, passphrase);
                         ^

Error: error:0906D064:PEM routines:PEM_read_bio:bad base64 decode
    at Error (native)
    at Sign.sign (crypto.js:279:26)
    at Object.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\node_modules\jwa\index.js:54:45)
    at Object.jwsSign [as sign] (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\node_modules\jws\lib\sign-stream.js:23:24)
    at Object.JWT.sign (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\node_modules\jsonwebtoken\index.js:137:16)
    at authJwt (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:83:16)
    at fetchAccessToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:96:17)
    at app_.INTERNAL.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\auth-node\auth.js:196:14)
    at Zb.getToken (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:28:3496)
    at yh (C:\Users\admin\Desktop\myProject\myProject\node_modules\firebase\database-node.js:195:334)
 Press any key to continue...

Also, this my Firebase rules, I'm using these rules just for test purpose:
{
   "rules":
   {
      ".read": true,
      ".write": true
   }
}

A: I solved my problem. I just downloaded serviceAccount.json file from Firebase Console and inserted it into my project. The 'Service Account' file contains everything that I need.
var firebase = require('firebase');

firebase.initializeApp({
    databaseURL: 'https://*****.firebaseio.com',
    credential: 'myapp-13ad200fc320.json', // This is the serviceAccount.json file
});

Then the code below worked nicely.
firebase.database().ref('/').set({
    username: "test",
    email: "test@mail.com"
});

A: This specific syntax/library for service accounts in node apps is being deprecated. The new method of reaching firebase on a server (that is, not a consumer app, like IoT or desktop) is the firebase admin sdk.
Your initialization code should now go:
var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

You can still manually key in your credentials, but they're now assigned to a diff't property:
admin.initializeApp({
  credential: admin.credential.cert({
    projectId: "<PROJECT_ID>",
    clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com",
    privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n"
  }),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

A: We faced the same problem with AWS Beanstalk. The root cause was because \n was replaced by \\n in the private key variable.
After adding the replace regexp it was fixed:
"private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')

Printing the variables into the log could also help isolating the issue.


text:
Q: C#/.NET: In need of a few (de)compression libraries My Google-Fu seems to be weak today. I've so far been able to find libraries for ZLib and BZip2 (SharpZipLib), and LZMA (7-Zip), but not Huffman, IMA ADPCM, and SPARSE.
Does anyone know of any pure .NET libraries that can handle these compression methods?
Thanks!

A: I've found this for Huffman...


text:
Q: Migrating a Java project to AspectJ (Eclipse AJDT) I'm working on a Java 1.8 project with several modules and one huge cross-cutting concern - logs are present in almost every class, in every module. I recently read about Aspect Oriented Programming (AOP) and I though it would be nice to use AspectJ to make things more modular, just like the guy from this post did. I decided to give it a try...
Since I'm using Eclipse Oxygen and it isn't compatible with the latest AJDT, I've downloaded Eclipse Kepler and the latest AJDT. However, I've noticed that once AJDT was installed, all Java Compiller's settings were set to J2SE-1.4, and I couldn't put it back to 1.8, since this option was not available anymore on the IDE. This caused me a lot of compiler's errors, such as:
Build path specifies execution environment J2SE-1.4. There are no JREs installed in the workspace that are strictly compatible with this environment.

and
'<>' operator is not allowed for source level below 1.7

I have the feeling that AJDT is outdated and incompatible with the latest java versions. However, since this is the first time I'm trying to use AOP, I wonder if I'm not following the correct path...
So, to make it simple and direct, my question is - is it possible to use AJDT with Java 1.8 (maybe manually (directly on a text file) editting some workspace configuration instead of using the IDE's UI, or something like that)? Or, to use AJDT, I'll need to make my project compatible with older Java versions, by "fixing", for instance, the <> operators, among several other things adopted by the latest versions of Java?

A: AJDT has a development build for Eclipse Oxygen (4.7), see https://eclipse.org/ajdt/downloads/

AJDT dev builds for Eclipse 4.7
Update Site URL:http://download.eclipse.org/tools/ajdt/47/dev/update

I just created a HelloWorld test project with aspects in Oxygen, and it runs under Java 8.


text:
Q: Access tablet camera from web/PHP I developing a web based php/mysql/jquery application for a rugged panasonic tablet with windows 10.
And i want to access the camera to take shots.
Tried the html camera web api, usable but no access to flash or default camera functions.
I have two options i think but both not working.
Option one is to use the Panasonic camera program, but can't manage to run the exe from local using php because of shared secure hosting.
Option two is to use the input file upload camera option, but can't get it to work on windows 10.
Any suggestions?


text:
Q: Fetching all remote branches into a bare Git repository I set up a Github post-receive hook, which runs a script on my web server whenever a push is made to my Github repository.
When the script runs, I want it to keep a local bare clone of the repository synchronized with my Github repository. To do this, I have it run this command:
git fetch origin && git reset --soft refs/remotes/origin/master
Then, if from my workstation I push to master on Github, everything works just fine. However, if I push to another remote branch, the changes are not reflected in my server's local bare repository.
I'm assuming there's some way to have the script fetch all of the remote branches, but I don't know how to do this. I know newer versions of git have a --all option for fetch/pull, but I'm using git version 1.6.3.3, which doesn't seem to have this option.
Does anyone know how I can get my script to fetch all remote branches?
Thanks!

A: git fetch origin '*:*' worked for me.

A: Use a shell script perhaps?
#!/bin/sh

for i in `git remote show`; do
    git fetch $i;
done;

Note: Small terminology error in your question: The --all option of git fetch|pull fetches all "remotes", not "remote branches".

A: Figured I'd provide my own solution while I'm at it. I accepted Ramkumar's though, as it was the inspiration for this. The difference is I don't want to fetch from all remotes, but rather each remote branch in "origin"...

#!/bin/bash
REMOTE_BRANCHES=$(git branch -r | awk -F'/' '{print $2}')
for i in $REMOTE_BRANCHES; do
    git fetch origin $i
done

DISCLAIMER: haven't really implemented this yet, but it should be close.

A: git fetch origin *:* worked for me on Windows.
git version 2.29.2.windows.3


text:
Q: Polymorphism Question For the sake of the question I've taken this code from http://www.cplusplus.com/doc/tutorial/polymorphism/
class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
};

class Rectangle: public Polygon {
  public:
    int area()
      { return width*height; }
};

class Triangle: public Polygon {
  public:
    int area()
      { return width*height/2; }
};

int main () {
  Rectangle rect;
  Triangle trgl;
  Polygon * ppoly1 = ▭
  Polygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  return 0;
}

Is it possible to create a Polygon array and store Triangle and Rectangle objects in it and still be possible to access the functions associated with their respective classes?
For example:
Polygon *array[2];
array[0] = new Triangle;
array[1] = new Rectangle;

Is there any way to call area() from the Polygon array?

A: No, the access to the functions is restricted to base class functions only.
But there's easy way to fix this problem, by providing pure virtual function in the base class:
class Polygon {
public:
  virtual int area()=0;
};

Then it'll just work fine.


text:
Q: How can I install packages without starting their associated services? As you're probably aware, by default when you install a package on a Debian or Ubuntu based system, if the package contains a service, that service will generally be enabled and started automatically when you install the package.
This is a problem for me.
I've found myself needing to manage templates for building LXC containers. There are several containers, each corresponding to a Debian or Ubuntu release. (There are also Red Hat-based containers, but they aren't relevant here.)
/var/lib/libvirt/filesystems/debian6_template
/var/lib/libvirt/filesystems/debian7_template
/var/lib/libvirt/filesystems/ubuntu1004_template
/var/lib/libvirt/filesystems/ubuntu1204_template

Occasionally I will find that the templates have a missing package or need some other change, so I will chroot into them to install the package. Unfortunately when I do that, I wind up with several copies of the package's service running!
By way of example, I found the templates didn't have a syslog daemon, so I installed one:
for template in /var/lib/libvirt/filesystems/{debian,ubuntu}*_template; do
    chroot $template apt-get install rsyslog
done

And promptly wound up with four copies of rsyslog running. Not to mention two copies of exim4. Oops!

I read somewhere (though I can't find it again now) that it's not supposed to start services when running in a chroot, but that clearly isn't happening here.
One potentially viable nasty hack calls for temporarily replacing the various commands which actually start services, such as start-stop-daemon and initctl, though this is a lot more work than I really wanted to do. If I have no other choice, though...
The ideal solution here would be for Debian-based systems to stop doing this crap, but failing that, perhaps an obscure or undocumented command line option for apt-get?
In case it wasn't clear, I really want to keep anything related to managing the templates outside the templates, if possible.

A: You can do:
export RUNLEVEL=1
for template in /var/lib/libvirt/filesystems/{debian,ubuntu}*_template; do
    chroot $template apt-get install rsyslog
done
exit

I haven't tested it with chroot, but it should work.
At first it sets RUNLEVEL environment variable, so processes initiated by apt-get will not start any services, because they will "think" system is running in single mode. As environment is modified the way it may affect future commands, it is required to exit shell when modified environment is no longer needed, this is accomplished by exit command at the end.
There may be some (rare?) packages that won't install properly in single mode (but AFAIK this should not be problem in most cases).

A: For debian you can do this with policy-rc.d. Here's one explanation:

A package's maintainer scripts are supposed to only interface with the init system by means of invoke-rc.d, update-rc.d and the LSB init script headers...
invoke-rc.d will, before taking its action, check whether
/usr/sbin/policy-rc.d is executable, will call it with the respective
service name and the current runlevel number on its command line and
act according to its exit code. For example, a return value of 101
will prevent the planned action from being taken. This includes the
automated start of the service upon package installation as well as
the stop of the service on package removal and reduces the
stop-upgrade-restart ritual during package upgrades to just performing
the upgrade which might leave the old version of the service running

Since you don't want any services to ever start, your policy-rc.d script can be simply
#!/bin/sh
exit 101

This is the technique used by tools like pbuilder and Docker's mkimage/debootstrap.
Unfortunately, this technique does not work with Ubuntu chroots. Packages that integrate with the upstart init system call /usr/sbin/initctl instead of invoke-rc.d during installation, and initctl doesn't consult policy-rc.d. According to upstart's author the workaround is to replace  /sbin/initctl with a symlink to /bin/true in a chroot. You can see this in mkimage-debootstrap as well, they do
dpkg-divert --local --rename --add /sbin/initctl
ln -sf /bin/true sbin/initctl


text:
Q: runtime 1004 error, every second time code executes I'll try and keep my query simple, I don't think my code is overly relevant.
I have a sub which changes values on a sheet, some of those changes trip worksheet change event listeners. So that is a bit inefficient maybe, but shouldn't cause me any problems.
Here's the rub: Every other time I run my 1st macro - changing values - my worksheet behaves perfectly. Everytime in between, I hit a 1004 runtime error.
When I hit the error I End code execution. Do the same thing again and it works, fails, works, fails etc.
I am thinking there is some VBA or Excel setting that I need to manually clear to avoid the runtime error. but I have no idea what it could be. I could also re-write my procedures to avoid the cells that trigger the event listeners, but I would really like to understand what is going on.
Edit: ok here is some code, I use this to find my list of invoices by customer and display a userform to select the invoice to display:
Sub Look_for_invs()
Dim cell, invDB As Range
Dim srch_rng As Range
Set invDB = Range("Invoice_DB")

invDB.AdvancedFilter xlFilterCopy, Range("inv_lookup_crit"), Range("inv_lookup_result"), True

Dim length As Integer
On Error GoTo exerr

length = Int(WorksheetFunction.CountA(Range("inv_lookup_result_list").Columns(1)))
Range("inv_lookup_result_list").Cells(1, 1).Offset(length, 0).Value = "NEW"

GoTo exok
exerr:
length = 1
Range("inv_lookup_result").Cells(1, 1).Offset(length, 0).Value = "NEW"
exok:

Set srch_rng = Range("inv_lookup_result_list")

With InvoiceSelection.InvListBox
    .ColumnCount = 4
    .ColumnHeads = True
    .RowSource = "inv_lookup_result_list"
End With

Worksheets("Invoice Entry").Select

InvoiceSelection.Show vbModeless

End Sub

Here is the code for the userform, this takes the invoice number and puts the values into my invoice template, it seems to me like I am unable to access members of Range objects while the userform is active. I disabled events since posting the question to try and see if that would help, it didn't:
Private Sub InvListBox_Click()
Dim invnum, invitems_cnt, invitem As Integer
Dim accnum As String
Dim inv_arrival, inv_depart As Date
Dim invDB, cell, invoice_lines As Range
Dim inv_ent_sht As Worksheet

With Application
    .Calculation = xlCalculationManual
    .EnableEvents = False
    .ScreenUpdating = False
End With

invnum = InvListBox.Value
accnum = Range("invoice_ent_account")
Set invDB = Range("Invoice_DB")
Set invoice_lines = Range("invoice_lines")
Set inv_ent_sht = Worksheets("Invoice Entry")

clear_inv_sheet

If invnum <> "NEW" Then
    'set variables
    inv_depart = WorksheetFunction.VLookup(invnum, invDB.Offset(0, 1), 5, False)
    inv_arrival = WorksheetFunction.VLookup(invnum, invDB.Offset(0, 1), 4, False)
    'transfer header-level invoice details to sheet
    Range("inv_inv_num") = invnum
    Range("inv_depart") = inv_depart
    Range("inv_arrival") = inv_arrival

    'find all items relating to invoice lines and move them to invoice lines area of statement
    For Each cell In invDB.Columns(2).Cells
        If cell.Value = invnum Then
            invitem = Application.WorksheetFunction.CountA(invoice_lines.Columns(1)) + 1
            invoice_lines.Cells(invitem, 1) = cell.Offset(0, 5)
            invoice_lines.Cells(invitem, 2) = cell.Offset(0, 2)
            invoice_lines.Cells(invitem, 5) = cell.Offset(0, 6)
            invoice_lines.Cells(invitem, 6) = cell.Offset(0, 7)
            invoice_lines.Cells(invitem, 7) = cell.Offset(0, 12)
            invoice_lines.Cells(invitem, 8) = cell.Offset(0, 13)
        End If
    Next cell

    'invitems_cnt = WorksheetFunction.CountIf(Range("invoice_DB").Columns(2), invnum)

End If
InvoiceSelection.Hide
With Application
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
    .ScreenUpdating = True
End With

End Sub

A: you might need to re-arrange the data before the vlookup (works only if data is in alphabetical/numeric order).
or, you can maybe use the find function, or match, wich dont need reorganizing the data each time you add cells to it.
You also didn't tell wich line shows the error (hit debug instead of end code).
change the  on error goto exerr, to on error goto 0, so you can find where the code missbehaves.


text:
Q: Initialize or Lazy load an ObservableCollection in a fast and optimized way from IEnumerable records I have an IEnumerable<T> collection of about 30,000 records that are created upon application load time and these records are converted to ObservableCollection<T> by doing (which takes substantial amount to load WPF application):
IEnumerable<Person> enumerablePeople; //Initialized and contains around 30,000 records
ObservableCollection<Person> people = new ObservableCollection<Person>(enumerablePeople);

Is there some different optimized or fast method / way other than newing up I can use or if possible can I use some kind of Lazy loading to initialize it, to convert IEnumerable<Person> to ObservableCollection<Person> so that it loads the collection / application faster.

A: The only method IEnumerable allows to access its contents is to enumerate though them one by one. If your IEnumerable is available as a List it might be able to grab the internal array, though I expect you'll end up having to copy all the contents regardless.
30000 references should not take very long to copy. If it is taking more than a second or two, I'd make sure it's not calling some slow event handlers or updating the UI for every item added.

A: People are trying to help you and you are not listening.
Just how are you "creating" an?
IEnumerable<T>

Can not new an IEnumerable
This syntax fails
IEnumerable<Person> IPeople = new IEnumerable<Person>();

You may be creating a reference to an IEnumerable in the application load.
But you are NOT creating an IEnumerable object as there is no such thing.
IEnumerable is an interface not a collection - it cannot be newed.
See code below.
Created an ObservableCollection of 100,000 from IEnumerable ctor in 16 ms.
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 13 ms
sw.Restart();
ObservableCollection<Person> ocPeople = new ObservableCollection<Person>(iPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 16 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  8 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(ocPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  1 ms
sw.Restart();
List<Person> lPeople = new List<Person>(iPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 10 ms
sw.Restart();
ObservableCollection<Person> ocPeople2new = new ObservableCollection<Person>(lPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  6 ms

public IEnumerable<Person> iPeople
{
    get
    {
        for (int i = 0; i < 100000; i++) yield return new Person(i);
    }
}

public class Person
{
    public Int32 ID { get; private set; }
    public Person(Int32 id) { ID = id; }
}


text:
Q: Flutter SharedPrefs Cubit InitState is ... strange You can see the strange behaviour in this video: https://streamable.com/r5ld2y
The InitValue is the correct one, but when I restart the App it first goes to zero, AFTER loading the Screen OR press a button, it loads the shared prefs...
This is my Cubit (Only with the LoadCounter Func):
class DrinkCubit extends Cubit<DrinkState> {
  DrinkCubit() : super(DrinkState(drinkValue: 0));

  Future<void> loadCounter() async {
    final prefs = await SharedPreferences.getInstance();
    state.drinkValue = (prefs.getInt('counter') ?? 0);
  }
}

And this is my InitFunction in the main window!
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero,()
    {
      BlocProvider.of<DrinkCubit>(context).loadCounter();
    });
  }

So how do I fix this, that the correct value is directly after starting the app showed

A: Try this:
getData(){
  BlocProvider.of<DrinkCubit>(context).loadCounter();
}

@override
void initState() {
  SchedulerBinding.instance.addPostFrameCallback((_) {
    getData();
  });

 super.initState();
}

SchedulerBinding.instance.addPostFrameCallback ensures that code inside run before UI code.
And if it allows me to give you a hint, is better remove SharedPreferences of your Bloc and put in another class.


text:
Q: Expressing knot polynomials as casimirs I always wondered why one writhe unit (read: colored with the irrep of a quantum Lie algebra and evaluated as Reshetikhin-Turaev invariant thereof) is essentially the quadratic casimir of that irrep. (With a proper normalization. Since quadratic casimirs are defined in a complete other way via traces over tensors, I don't know if that's proven at all, and frankly I don't even know whether quantum Lie algebras have casimirs the same way as their "normal" cousins.)
As usual, after a wild generalization everything fell in place:
- A knot without any intersection is a circle (duh) and its Reshetikhin-Turaev invariant is the quantum dimension, i.e. the 0th casimir.
- A knot with one intersection (see above), 2nd casimir (times 0th for the loop itself).
- A Hopf link (colored with same irrep) with two intersections I thus would expect to be expressible with the 4th, 2nd and 0th casimir.
- Trefoil with 6th...and so on.
This wild hypothesis even would give some sense to why the "easy" (skein-relation wise) Lie algebras are those with the smallest ranks: A1, G2, B2.
So is my hypothesis true - the Reshetikhin-Turaev invariant of a knot/link with n crossings colored with an irrep can be expressed in maximally the 2n-th casimirs (maybe also less) of this irrep? Possible even as linear combinations (in the sense e.g. $a*C_4+b*C_2^2+c*C_2$, so you can say the value of the Hopf link is a quartic Casimir, times dimension...i.e. a generalized 4th Dynkin index)?


text:
Q: Join two tables in one SQL Server 2000 I'm stuck with this query, I have the following results from two queries:
Query 1:
SELECT convert(varchar(10), date_creat, 101) as DateCreate, count(distinct packslip) as OrdersPendingPickUp
FROM pickhead
WHERE procstep = '17'
GROUP BY convert(varchar(10), date_creat, 101)
ORDER BY convert(varchar(10), date_creat, 101)

Results Query 1:
DateCreate  OrdersPendingPickUp
2/11/2013   1
2/19/2013   1
2/21/2013   3
2/25/2013   1
2/26/2013   11
2/27/2013   6

Query 2:
SELECT convert(varchar(10), DateCreate, 101) as DateCreate, count(distinct PackSlip) as OrdersPendingInvoice
FROM tblB2B_Orders [to]
INNER JOIN tblTmpLsrType ttlt ON [to].LSRNbr = ttlt.shpno
WHERE
    [to].PackSlip not in (SELECT PackSlip FROM pickhead)
    AND (ttlt.InvcNbr = '' OR ttlt.InvcNbr is null)
GROUP BY convert(varchar(10), DateCreate, 101)
ORDER BY convert(varchar(10), DateCreate, 101)

Results Query 2:
DateCreate  OrdersPendingInvoice
2/25/2013   1
2/26/2013   1

Now I want to combined both results in one, the result should look like this:
DateCreate  OrdersPendingPickUp OrdersPendingInvoice
2/11/2013   1                     0
2/19/2013   1                     0
2/21/2013   3                     0
2/25/2013   1                     1
2/26/2013   11                    1
2/27/2013   6                     0

I did the following but it doesn't work correctly:
SELECT DISTINCT convert(varchar(10), DateCreate, 101) as DateCreate,
    isnull(
        (SELECT count(distinct packslip)
        FROM pickhead
        WHERE procstep = '17' AND (convert(varchar(10), [to].DateCreate, 101) = convert(varchar(10), date_creat, 101))
        GROUP BY convert(varchar(10), date_creat, 101)),0
    ) as OrdersPendingPickUp,
    isnull(
        (SELECT count(distinct [to1].PackSlip)
        FROM tblB2B_Orders [to1]
        INNER JOIN tblTmpLsrType ttlt ON [to1].LSRNbr = ttlt.shpno
        WHERE
            [to1].PackSlip not in (SELECT PackSlip FROM pickhead)
            AND (ttlt.InvcNbr = '' OR ttlt.InvcNbr is null)
            AND [to1].DateCreate = [to].DateCreate
        GROUP BY convert(varchar(10), [to1].DateCreate, 101)),0
    ) as OrdersPendingInvoice
FROM tblB2B_Orders [to]
ORDER BY convert(varchar(10), DateCreate, 101)

This is the result:
DateCreate  OrdersPendingPickUp OrdersPendingInvoice
2/11/2013   1                     0
2/19/2013   1                     0
2/20/2013   0                     0
2/21/2013   3                     0
2/25/2013   1                     0
2/25/2013   1                     1
2/26/2013   11                    0
2/26/2013   11                    1
2/27/2013   6                     0

Any help will be appreciated.

A: This is easily done with a full outer join:
with query1 as (<query1>),
     query2 as (<query2>)
select coalesce(query1.dateCreate, query2.dateCreate) as DateCreate,
       coalesce(query2.OrdersPendingPickup, 0.0) as OrdersPendingPickup,
       coalesce(query1.OrdersPendingInvoice, 0.0) as OrdersPendingInvoice
from query1
     full outer join
     query2
     on query1.datecreate = query2.datecreated

Note that your queries go into the with clause.
You can do the same thing with subqueries:
select coalesce(query1.dateCreate, query2.dateCreate) as DateCreate,
       coalesce(query2.OrdersPendingPickup, 0.0) as OrdersPendingPickup,
       coalesce(query1.OrdersPendingInvoice, 0.0) as OrdersPendingInvoice
from (<YOUR QUERY 1 GOES HERE>) query1
     full outer join
     (<YOUR QUERY 2 GOES HERE>) query2
     on query1.datecreate = query2.datecreated


text:
Q: MS ACCESS Combine Multiple Rows of data based on column I have a database with a table with the following 3 columns of data:

WORKORDER  -  SEQNBR  -  COMMENT
R12345           1       This work was performed on Dec 3
R12345           2       1999 and resulted in the removal
R12345           3       or all similar pumps. All pumps
R12345           4       have been replace or repair

I'm looking to combine or concatnate  all of the COMMENTS for a particular WORKORDER into one column or report text box
Ex: R12345 "This work was performed on Dec 3 1999 and resulted in the removal or all similar pumps. All pumps have been replace or repair.
Is this possible?
Any help would be greatly appreciated!

A: MS-Access (and SQL Server) are a pain when it comes to concatenate data of a group. As said by others, there is no good solution for this problem in MS-Access.
Here is however something that will give you what you expect on your example. It assumes that you have a limited number of elements in your sequence (here, I supposed 4). It's ugly, but sometimes, it's necessary to be humble.
SELECT t1.WORKORDER & " " & t1.COMMENT & " " & t2.COMMENT & " " & t3.COMMENT & " " & t4.COMMENT AS Result
FROM ((your_table AS t1 LEFT JOIN your_table AS t2 ON t1.WORKORDER = t2.WORKORDER)
LEFT JOIN your_table AS t3 ON t2.WORKORDER = t3.WORKORDER)
LEFT JOIN your_table AS t4 ON t3.WORKORDER = t4.WORKORDER
WHERE t1.SEQNBR=1
AND t2.SEQNBR=2
AND t3.SEQNBR=3
AND t4.SEQNBR=4

From this you get one record with one field containing:

R12345 This work was performed on Dec 3 1999 and resulted in the
  removal or all similar pumps. All pumps  have been replace or repair


text:
Q: Create edit link for google drive files in ruby Im using the 'google_drive' gem for ruby. I can create an list google drive files in ruby. Is there a way to set the permissions to {type: 'anyone', role: 'writer'} and create a link in ruby to view or edit the google drive files i created?
Thanks, Andreas

A: Use GoogleDrive::File#human_url
You did not specify how exactly you created your file(s), but each instance of a file has a #human_url - that is the link to the file that allows you to view or edit the file in a web browser.
Sample:
session = GoogleDrive::Session.from_config("config.json")
session.upload_from_file("/path/to/hello.txt", "hello.txt", convert: false)
file_url = session.file_by_title("hello.txt").human_url

UPDATE
For setting permission, use the method #create_permission(file_id, permission_object) specifying the permission object.
Sample:
permission = {type: "user", role: "writer", email_address: "user's email"}
session.drive_service.create_permission(current_user.fileId, permission)

whereby the file id can be retrieved similar to the file URL, with #resource_id .


text:
Q: JavaFX draw pixels with PixelWriter results in gaps I am drawing onto an ImageView in such way:
@FXML
void imgVDrag(MouseEvent event) {  //On Mouse Dragged
    pixelWriter.setColor((int)event.getX(),(int)event.getY(), colPick.getValue());
}

If i move the mouse too fast it results in gaps between the pixels. Do i have to use another event or is there any other solution?


text:
Q: Get and update Defaults parameters on Youtube using Youtube API in Java? I would like to get and update "Upload defaults" parameters from Channel settings (i.e. allow comments for future uploads, users can vote on comments, etc.) of curently logged in user using JAVA Youtube API, but I don't know how.
Could someone please, help me?
Best,
D

A: This is a known feature request and it is filed internally. Feel free to file a feature request on this to be notified when it's fixed.
https://code.google.com/p/gdata-issues/issues/entry?template=YouTube%20(Enhancement%20Request)


text:
Q: .waitForElementVisible() alternative for change in value I've been running some JS tests using nightwatch and find the .waitForElementVisible() function very useful, however, the code I am testing has an element whose value changes after a button click and is always visible.
My issue is that the value change lags behind the button click (slow machine) so I have to put a long this.api.pause() to test the value in these cases.
Is there some sort of alternative function like waitForElementValueChange() that detects a change in the element value the same way waitForElementVisible() detects the element becoming visible?
Open to any creative solutions, cheers!

A: As far as I'm aware there isn't a built in method that can detect element changes because you don't need to.
I will to it like this
const buttonBeforeClick = 'button[value = "Click Me!"]';     // just an example selectors
const buttonAfterClick = 'button[value = "Im Clicked!"]';   // use a page object for those
browser.waitForElementVisible(buttonBeforeClick);
browser.click(buttonBeforeClick );
browser.waitForElementVisible(buttonAfterClick);

There is no reason for it not to work, if an element has 2 "states" in our case "clicked" and "unClicked" you just capture both of them.


text:
Q: Cannot get rid of overscroll in PhoneGap even with config.xml preferences I'm fairly new to PhoneGap/Cordova and I'm trying to build an app for iOS and Android. I've read every page/forum I could find on how to get rid of the overscroll but it's just not working for me. I'm working with OnsenUI and AngularJS if that makes any difference. I have this in my config.xml file already:

<preference name="DisallowOverscroll" value="true" />
<preference name="webviewbounce" value="false" />

I made sure I only have one config.xml in my project. The Cordova version is 3.5.0.
My navigation bars keep scrolling out of view because of this. Anyone tried anything else/have other ideas?


text:
Q: Why is imperative programming preferred over functional programming? Background: I am proponent of functional programming who works at a VB.NET shop where the prevailing mental model is imperative programming.  Being that foundation of our system is WinForms I can understand we're not going to get entirely away from imperative programming, but still I try to use FP (primarily via Linq) wherever possible because I believe in its merits.
Arguments & counter-arguments against FP

*

*One might notice that fluent Linq is less efficient than its imperative counterpart in that this style processes a sequence down to another sequence and repeats that.  Generally, its going to take a few more passes than the imperative approach which can be better optimized to avoid repeat passes over a sequence.  For this reason, the lead couldn't understand why I would choose a functional approach that is clearly "less efficient."

*

*Counter-argument: I argued that while it is sometimes less efficient in terms of CPU cycles, that I felt it is more humanly intelligible and easy to follow since each line does just one thing on its pass over the sequence.  To me this feels like having an assembly line where each person at his station has just one job to do.  I feel that the negligible trade off of efficiency is recompensed by code whose concerns are neatly separated.

*The next argument against FP that I hear in my shop is that it's harder to debug -- which is true.  It's not easy to step over Linq code.  And I do sometimes have to unravel a method chain in order to better follow and dissect issues that I can't immediately spot.

*

*_Counter-argument: For the most part though I don't have issue with this because I think the functional style is more declarative in how it reads and when an error is thrown within a functional chain, I can usually spot the issue immediately.

My Question
I've been trying to promote functional style in our shop and I don't feel like I'm making headway.  I've done both styles of programming and have only recently dabbled in Haskell.  Despite years of imperative experience, now that I'm making routine use of FP in JavaScript, it's grown on me.  It rings a note of rightness in my core when I compare it to what I might have done if I stuck to an imperative style.  I've retrained my brain toward functional thinking, toward functional composition.
What I can't understand is how hard its been to convince others of FP's merits.
For example, the developers in my shop do use Linq, but I think they generally use it in the context of dealing with domain data.  I use it in a more general sense and prefer it anytime I'm dealing with sequences/lists or persistent data structures.  I haven't been able to convince my teammates to expand their use of Linq.
What I'm trying to understand is what causes a developer to not like FP.
I would like to see an answer from someone who has a good deal of experience with FP but decided in favor of the imperative style.  What drove the decision to stay with imperative instead of using functional?

Here's an additional example highlighting the differences between imperative & functional programming.
I wrote the SelectedRows method of our grid in Linq as such:
Public Property SelectedRows() As DataRow() Implements IDataSourceControl.SelectedRows
    Get
        Return Me.ugrBase.Selected.Rows.
            OfType(Of Infragistics.Win.UltraWinGrid.UltraGridRow)().
            Select(Function(ugr) ugr.ListObject).
            OfType(Of DataRowView)().
            Select(Function(drv) drv.Row).
            ToArray
    End Get

However, this style of code makes some of our developers uncomfortable and so our lead rewrote it to the more familiar:
Public Property SelectedRows() As DataRow() Implements IDataSourceControl.SelectedRows
    Get
        Dim plstRows As New List(Of DataRow)
        For Each bugrLoop As Infragistics.Win.UltraWinGrid.UltraGridRow In Me.ugrBase.Selected.Rows
            If bugrLoop.ListObject IsNot Nothing Then
                plstRows.Add(CType(bugrLoop.ListObject, DataRowView).Row)
            End If
        Next
        Return plstRows.ToArray()
    End Get

A: Functional programming is just too complicated for inexperienced programmers. One of the illustrations is this one, where students declared that 30-LOC mess was easier and more intuitive to understand compared to the four lines FP analog.
(This is the original version of the FP example, as the answer in the link has been more recently edited to make it slightly easier to read.)
return this.Data.Products
    .Where(c => c.IsEnabled)
    .GroupBy(c => c.Category)
    .Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));

Functional programming requires a different way of thinking about the way we code and the way this code is executed. This is rarely the way the students are told in college, and once bad habits taken, it's difficult to change them.
Functional programming has also its own specific features which may appear risky in hands of beginners. Lazy evaluation is one of them, and it may take months before one starts to understand why lazy evaluation is an excellent feature, and not an annoyance.
That's also why so many beginners start programming with languages such as PHP and not languages like Haskell.


text:
Q: Lazy loading Angular views and controllers on page scroll I have a microsite that is utilizing Laravel and Angular. It's a one page microsite that is responsive and is broken into 5 sections. I would like to lazy load them to cut down on loading all at once.

1

2

3

4

5

I'm looking to load 1 & 2 on page load then as you scroll down the page load the other view with a nice fade in and then load its interactive items.

A: In this case it is probably not necessary (or efficient) to lazy load your controllers, but it can be done.
There are many things to tackle here, so I'm going to handle it in sections.
Lazy-loading views on scroll (animated).
Live demo here (click).
Markup:

Animation CSS:
.section-animate-enter {
  -webkit-transition: 1.5s linear all;
    transition: 1.5s linear all;
    opacity: 0;
    left: 100%;
}
.section-animate-enter.section-animate-enter-active {
    opacity: 1;
    left: 0;
}

Angular logic:
app.controller('myCtrl', function($scope) {
  $scope.sections = ['top','mid','bottom']; //html files to load (top.html, etc)
  $scope.loadedSections = [$scope.sections[0]]; //loaded html files
});

app.directive('scrollLoad', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var to = scope[attrs.scrollLoadTo]; //$scope.loadedSections
      var from = scope[attrs.scrollLoadFrom]; //$scope.sections

      $window = angular.element(window);
      $window.bind('scroll', function(event) {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
        var scrollPos = scrollTop + document.documentElement.clientHeight;
        var elemBottom = element[0].offsetTop + element.height();
        if (scrollPos >= elemBottom) { //scrolled to bottom of scrollLoad element
          $window.unbind(event); //this listener is no longer needed.
          if (to.length < from.length) { //if there are still elements to load
            //use $apply because we're in the window event context
            scope.$apply(to.push(from[to.length])); //add next section
          }
        }
      });
    }
  };
});

Lazy-loading CONTROLLERS and views on scroll (animated).
Live demo here (click).
Markup:

Angular Logic:
var $appControllerProvider; //see below

var app = angular.module('myApp', []);

app.config(function($controllerProvider) {
  $appControllerProvider = $controllerProvider; //cache this so that we can lazy load controllers
});

app.controller('myCtrl', function($scope) {
  $scope.sections = ['top','mid','bottom']; //html files to load (top.html, etc)
  $scope.loadedSections = [$scope.sections[0]]; //loaded html files
});

app.directive('scrollLoad', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var to = scope[attrs.scrollLoadTo]; //$scope.loadedSections
      var from = scope[attrs.scrollLoadFrom]; //$scope.sections

      $window = angular.element(window);
      $window.bind('scroll', function(event) {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
        var scrollPos = scrollTop + document.documentElement.clientHeight;
        var elemBottom = element[0].offsetTop + element.height();
        if (scrollPos >= elemBottom) { //scrolled to bottom of scrollLoad element
          $window.unbind(event); //this listener is no longer needed.
          if (to.length < from.length) { //if there are still elements to load
            //use $apply because we're in the window event context
            scope.$apply(to.push(from[to.length])); //add next section
          }
        }
      });
    }
  };
});

app.factory('myService', function($http, $q) {
  return {
    getController: function(fileName) {
      return $http.get(fileName+'.js').then(function(response) {
        return response.data;
      });
    }
  }
});

app.directive('lazy', function(myService, $compile, $q) {
  /* I store the directive in a variable then return it later
   * so that I can abstract directive logic into other functions below */
  var directiveReturn = {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var loadName = scope.$eval(attrs.lazy);

      //this is straightforward - see the "addScript" function for explanation
      myService.getController(loadName).then(function(js) {
        return addScript(loadName, js, scope);
      }).then(function() {
        //the controller has been lazy loaded into angular
        //now use "ng-include" to lazy load the view.
        var ngInc = angular.element('')
          .attr('ng-include', "'"+loadName+".html'")
          .attr('ng-controller', loadName+'Ctrl');
          element.append(ngInc);
          $compile(ngInc)(scope);
      });
    } //link
  }; //directive return

  /*
   * This is the magic.
   */
  var scriptPromises = {};
  function addScript(loadName, js, scope) {
    if (!scriptPromises[loadName]) { //if this controller hasn't already been loaded
      var deferred = $q.defer();
      //cache promise (which caches the controller when resolved)
      scriptPromises[loadName] = deferred.promise;

      //inject controller into a script tag
      var script = document.createElement('script');
      script.src = 'data:text/javascript,' + encodeURI(js);
      script.onload = function() {
        //this is how you lazy load a controller
        $appControllerProvider.register(loadName, window[loadName+'Ctrl']);
        //now that the controller is registered with angular, resolve the promise
        //then, it is safe to add markup that uses this controller with ng-controller
        scope.$apply(deferred.resolve());
      };
      //when this script loads, the controller will be registered and promise is resolved
      document.body.appendChild(script);
      return deferred.promise;
    }
    else { //controller already loaded
      return scriptPromises[loadName]; //use cached controller
    }
  }
  return directiveReturn;
});


text:
Q: Allow Administrator Account to execute files when not logged in I have an annoying issue.
I Have made a ASP.NET application that opens winword.exe using the Administrator account since that is the only account I can get to function correctly.
The only issue is when I am not logged in as an administrator it won't work.
How do I make it work everytime?
I have tried to grant access to NETWORK SERVICE and letting it open WINWORD.exe. But it just opens winword and then nothing else happens.
I think the issue might be that winword is beeing run for the first time and some popups blocks the way. So alternatively, is there anyway I can login as NETWORK SERVICE and run winword??
Thanks in advance guys

A: Okay I got it working
It takes the following steps:

*

*Click START-->RUN and enter "dcomcnfg"

*In the "Applications" tab, go down to "Microsoft Word Document"

*Click PROPERTIES button

*Go to the "Security" Tab

*Click "Use custom access permissions", and then click EDIT

*Click ADD and then click SHOW USERS

*Highlight the IIS anonymous user account (usually IUSR_ , click ADD

*Go back to the "Security" tab by hitting OK

*Click "Use custom launch permissions", and the click EDIT

*Click ADD and then click SHOW USERS

*Highlight the IIS anonymous user account (usually IUSR_ , click ADD

*Hit OK, and then hit APPLY.

After that hit the Identity tab.
In here you choose a user that has administrator rights and typ username and password.
You go into Services -> IIS Admin -> Allow it to work with the desktop.
Thank God I am done with this issue. Btw I do not in any way say that this is a secure way to do this. I however don't have any issues doing it since my server is internal.

A: Instead of opening Word interactively you should be using the Office components and creating Word application objects to handle the work.  This will let you avoid any interactive dialogs that Word would prompt you with.


text:
Q: Which date is first using DateTime php I am using the DateTime function and want to find out if a date stored in the database has been passed or is yet to happen.
This is for a banlist.
Currently I attempted to use the -> diff function to get the difference only now realising that it produces an absolute value.
e.g. if the end date for the ban is 16/02/2016 or 20/02/2016 the difference will always be 2 days.
How can I test two dates and see if the date has passed using DateTime?
code I have used and failed with:
if ($stmt = $mysqli->prepare("SELECT start, end, length FROM banlist WHERE user_id = ? AND username = ? AND user_email = ?")) {
    $stmt->bind_param('iss', $user_id, $username, $email);

    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($start, $end, $length);
    $stmt->fetch();

    if($stmt->num_rows != 0) {
        if($length == "inf") {
            return 'Indefinitely';
            $stmt->close();
        }
        else {
            $startDate = new DateTime($start);
            $endDate = new DateTime($end);
            $diff=$now->diff($endDate);
            $seconds = $diff->format('%s');
            $mins = $diff->format('%i');
            $hours = $diff->format('%h');
            $days = $diff->format('%d');
            $months = $diff->format('%m');
            $years = $diff->format('%y');

            if($seconds > 0 || $mins > 0 || $hours > 0 || $days > 0 || $months > 0 || $years > 0) {
                return 'for ' . $length .', starting ' . $startDate->format('d/m/Y') . ' at ' . $startDate->format('H:i:s') . ' and ending on ' . $endDate->format('d/m/Y') . ' at ' .$endDate->format('H:i:s');
                $stmt->close();
            }
            else {
                return 'You haven\'t been banned. Please email an admin for assisstance';
                $stmt->close();
            }
        }
    }
    else {
        return 'You haven\'t been banned. Please email an admin for assisstance';
        $stmt->close();
    }
}

A: I would try and use the difference in seconds instead, between now and the ban end date.
// assuming $endDate and $now are DateTime objects
$diff = $endDate->getTimestamp() - $now->getTimestamp();
if ($diff > 0) {
    // user is still banned
}

A: You can use strtotime instead. It returns the Date in seconds, so if the difference is greater than zero, the first date ($end) is grater than the second one ("now"):
echo ((strtotime($end) - strtotime("now") >= 0) ? "banned" : "not banned";


text:
Q: How to escape imported partial in Nunjucks I would like to escape the HTML code from an imported file in Nunjucks.
{% include "item.html" %}

The file "item.html" contains following code:
bold text

I would like the parent file (which includes item.html) to have the following output:
<strong>bold text</strong>

I tried surrounding the include with an escape filter:
{% filter escape %}
  {% include "item.html" %}
{% endfilter %}

However in that case the file doesn't get included correctly. Any ideas?

A: I tested your snippet on Gulp + gulp-nunjucks-render@2.0.0, it does produce the desired effect:
{% filter escape %}
{% include "partials/test.html"  %}
{% endfilter %}

Output:


text:
Q: How to display input field in Spring MVC list In my Spring Roo project, I have generated an 'Event' domain object, with MVC controllers and views.
I would like to have a feature where the events (which are all string values) are all encrypted and authorised users who have the corresponding key can obtain the decrypted event information.
Currently, when the user presses the "List all events" button, a list of all the events are displayed (all encrypted string values).
I need to add an input field next to each of the events displayed in the event list (list.jspx) where the user enters his key. The controller will then use the input key value to decrypt and display the decrypted event information (in show.jspx).
In the list.jspx file, I added:
<form:create id="fl_au_edu_usyd_latte_experience_domain_Event" modelAttribute="event" path="/events" render="${empty dependencies}" z="">
<field:input path="partialKey" id="l_au_edu_usyd_latte_experience_domain_Event_partialKey"/>
</form:create>

In the EventController_Roo_Controller.aj file, I added:
@RequestMapping(value = "/{id}", produces = "text/html")
public String EventController.show(@PathVariable("id") Long id, Model uiModel, String partialKey) {
    addDateTimeFormatPatterns(uiModel);
    uiModel.addAttribute("partialKey", partial_key);

    uiModel.addAttribute("event", Event.findEvent(id));
    uiModel.addAttribute("itemId", id);
    return "events/show";
}

However, when I run the project I get the error:
org.apache.jasper.JasperException: /WEB-INF/views/events/list.jspx(12,146) The prefix "form" for element "form:create" is not bound.

Is there a way to do this?

A: I think this problem is due to that you have not configured the prefix of the response file. you need to configure a viewresolver in springmvc-servlet.xml:
<bean id="viewresolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

A: I think you don't have the WEB-INF/tags folder which Roo would install in your project. i.e there is no form in the tags folder in your WEB-INF. Please double check it


text:
Q: Delete '\' character from a string I have a string that contains lots of '\'(Backslash) characters. Using a loop I want to delete all these characters from the string. For this I used StringBuffer class and deleteCharAt() method.
This is my code:
public class NewClass33 {
public static void main(String args[]){

String s = ""\"MARY\",\"PATRICIA\",\"LINDA\",\"BARBARA\"";

StringBuffer sb = new StringBuffer(s);
    for(int i=0;i<s.length();i++){
        if(sb.charAt(i)=='\'){
            sb.deleteCharAt(i);
        }
    }
  }
}

For sample, here I have taken a small string.
But the problem is that, it shows an error in if loop. Error message is: "Unclosed character literal".


text:
Q: javascript code making url link undefined I am working on this javascript code and when is goes in the head and I refresh it goes to a 404 page.
Please can someone help.

A: You're trying to register the result of recordOutboundLink() as a click handler, causing the function to run first, evaluating window.href as the page to redirect to. The value of window.href is typically undefined, so the browser will try to redirect to http://undefined or something similar.
Instead, you should only execute the function when something is clicked, like so:
$(document).ready(function () {
    $('#myid').click(function() {
        recordOutboundLink(this, 'regular   xxxxx', 'http://xxxx.example.com');
        return false;
    });

I believe the Google docs mention something like this:
tada click me

Edit
Your locations should always be absolute, i.e. start with http://, https:// or simply //.

A: You need to pass the complete url to the method, ie, with the http:// part
so either use:
.click(recordOutboundLink(this, 'regular   xxxxx', 'http://xxxx.example.com'))

or
.click(recordOutboundLink(this, 'regular   xxxxx', '//xxxx.example.com'))