text:
Q: Get state of Angular deferred? With jQuery deferreds I'm used to be able to check the current state like this:
var defer = $.Deferred();
defer.state();  //Returns the state of the deferred, eg 'resolved'

Is there a way to do the same for Angular deferreds? (or even better promises)

A: Update:
Due to refactoring of $q this is now possible although not documented:
promise.$$state.status === 0 // pending
promise.$$state.status === 1 // resolved
promise.$$state.status === 2 // rejected

Original:
Unlike most promise libraries (Bluebird,Q, when, RSVP etc), $q does not expose a synchronous inspection API.
There is no way to achieve this from the outside.
You have to call .then on the promise and code in that handler will run when the promise fulfills.

A: The answer to your question is: yes, there is a way. The other answers nicely cover  the built-in limitations of $q. However, it's easy to add a state property to $q using the $provide service's decorator function.
  $provide.decorator('$q', function ($delegate) {
    var defer = $delegate.defer;
    $delegate.defer = function() {
      var deferred = defer();

      deferred.promise.state = deferred.state = 'pending';

      deferred.promise.then(function() {
        deferred.promise.state = deferred.state = 'fulfilled';
      }, function () {
        deferred.promise.state = deferred.state = 'rejected';
      });

      return deferred;
    };
    return $delegate;
  });

Put this decorator inside of a config block, and all $q-instantiated deferred and promise objects will have a state property with the value pending, fulfilled, or rejected.
Check out this plunk

Skeptical?

you are effectively modifying $q itself, wrapping every deferred with another deferred

Actually this is not the case. $q's original defer() constructor is called exactly one time. It is simply decorated with additional functionality by internally attaching an event handler via then. [Note that an additional defer object is instantiated as a result of the additional then callback which is automatically created with each deferred object... which is to be expected because this is how angular works internally.]

this wouldn't work because promises shouldn't be created with deferred but chained from promises that are returned from apis

Note that this code will decorate every deferred (and thus promise object) which is created by the $q service. This means that any API which utilizes $q will be automatically decorated with the state property. So regardless of how you use $q, whether with some API or on it's own, this solution decorates both the deferred object and the promise, and I have provided the plunk to prove it.

Production-worthy?
This approach is unit testable, it's guaranteed not to break any application already using $q, and it's flexible in the sense that you could later add additional decorators to $q without modifying the old one(s).

A: Updated:
Unfortunately this doesn't looks like its possible with $q. You'll have to put this code inside your then method.
myPromise()
.then(function() {
    // everything in here resolved
},
function() {
    // everything in here rejected
},
function() {
    // everything in here pending (with progress back)
});

Other:
This is for the Q library not angular's $q but similar.
Angular is inspired by the Q library, check out the source, its actually not that scary. https://github.com/kriskowal/q/blob/v1/q.js
You can use myPromise.inspect().state there are ['pending', 'rejected', 'fulfilled']
You also have:
myPromise.isFulfilled();
myPromise.isPending();
myPromise.isRejected();

Check out this JSfiddle and open the console for logged results.
http://jsfiddle.net/S6LzP/
More granular, Looking at the defer function on line 488:
function defer() {
    // if "messages" is an "Array", that indicates that the promise has not yet
    // been resolved.  If it is "undefined", it has been resolved.  Each
    // element of the messages array is itself an array of complete arguments to
    // forward to the resolved promise.  We coerce the resolution value to a
    // promise using the `resolve` function because it handles both fully
    // non-thenable values and other thenables gracefully.
    var messages = [], progressListeners = [], resolvedPromise;

    var deferred = object_create(defer.prototype);
    var promise = object_create(Promise.prototype);

    promise.promiseDispatch = function (resolve, op, operands) {
        var args = array_slice(arguments);
        if (messages) {
            messages.push(args);
            if (op === "when" && operands[1]) { // progress operand
                progressListeners.push(operands[1]);
            }
        } else {
            nextTick(function () {
                resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
            });
        }
    };

    // XXX deprecated
    promise.valueOf = function () {
        if (messages) {
            return promise;
        }
        var nearerValue = nearer(resolvedPromise);
        if (isPromise(nearerValue)) {
            resolvedPromise = nearerValue; // shorten chain
        }
        return nearerValue;
    };

    promise.inspect = function () {
        if (!resolvedPromise) {
            return { state: "pending" };
        }
        return resolvedPromise.inspect();
    };

    if (Q.longStackSupport && hasStacks) {
        try {
            throw new Error();
        } catch (e) {
            // NOTE: don't try to use `Error.captureStackTrace` or transfer the
            // accessor around; that causes memory leaks as per GH-111. Just
            // reify the stack trace as a string ASAP.
            //
            // At the same time, cut off the first line; it's always just
            // "[object Promise]\n", as per the `toString`.
            promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
        }
    }

    // NOTE: we do the checks for `resolvedPromise` in each method, instead of
    // consolidating them into `become`, since otherwise we'd create new
    // promises with the lines `become(whatever(value))`. See e.g. GH-252.

    function become(newPromise) {
        resolvedPromise = newPromise;
        promise.source = newPromise;

        array_reduce(messages, function (undefined, message) {
            nextTick(function () {
                newPromise.promiseDispatch.apply(newPromise, message);
            });
        }, void 0);

        messages = void 0;
        progressListeners = void 0;
    }

    deferred.promise = promise;
    deferred.resolve = function (value) {
        if (resolvedPromise) {
            return;
        }

        become(Q(value));
    };

    deferred.fulfill = function (value) {
        if (resolvedPromise) {
            return;
        }

        become(fulfill(value));
    };
    deferred.reject = function (reason) {
        if (resolvedPromise) {
            return;
        }

        become(reject(reason));
    };
    deferred.notify = function (progress) {
        if (resolvedPromise) {
            return;
        }

        array_reduce(progressListeners, function (undefined, progressListener) {
            nextTick(function () {
                progressListener(progress);
            });
        }, void 0);
    };

    return deferred;
}

Mostly notably the method at the very bottom deferred.notify.
Example usage:
function requestOkText(url) {
    var request = new XMLHttpRequest();
    var deferred = Q.defer();

    request.open("GET", url, true);
    request.onload = onload;
    request.onerror = onerror;
    request.onprogress = onprogress;
    request.send();

    function onload() {
        if (request.status === 200) {
            deferred.resolve(request.responseText);
        } else {
            deferred.reject(new Error("Status code was " + request.status));
        }
    }

    function onerror() {
        deferred.reject(new Error("Can't XHR " + JSON.stringify(url)));
    }

    function onprogress(event) {
        deferred.notify(event.loaded / event.total);
    }

    return deferred.promise;
}

requestOkText("http://localhost:3000")
.then(function (responseText) {
    // If the HTTP response returns 200 OK, log the response text.
    console.log(responseText);
}, function (error) {
    // If there's an error or a non-200 status code, log the error.
    console.error(error);
}, function (progress) {
    // Log the progress as it comes in.
    console.log("Request progress: " + Math.round(progress * 100) + "%");
});

A: I whipped up a solution inspired by Gil and Travis's answers, which decorates the Promise constructor with methods closer to the Q implementation.
Note that this decoration relies on Promise.$$state. This was built for Angular 1.6.4, and theoretically should work all the way down to 1.3.x, but no guarantees on that or future releases:
(function() {
    'use strict';

    angular
        .module('your.module.name.goes.here')
        .config(configBlock);

    /** @ngInject */
    configBlock.$inject = ['$provide'];
    function configBlock($provide) {
        $provide.decorator('$q', ['$delegate', function ($delegate) {
            console.log($delegate);
            var Promise = $delegate.prototype.constructor;

            Promise.prototype.inspect = function () {
                var inspect = {};
                switch (this.$$state.status) {
                    case -1:
                    case 0:
                        inspect.state = 'pending';
                        break;
                    case 1:
                        inspect.state = 'fulfilled';
                        break;
                    case 2:
                        inspect.state = 'rejected';
                        break;
                    default:
                        inpsect.state = 'unknown';
                }
                return inspect;
            };

            Promise.prototype.isFulfilled = function () {
                return this.inspect().state === 'fulfilled';
            }
            Promise.isFulfilled = function (obj) {
                if (obj.constructor !== Promise) {
                    return true;
                }
                return obj.isFulfilled();
            }

            Promise.prototype.isRejected = function () {
                return this.inspect().state === 'rejected';
            }
            Promise.isRejected = function (obj) {
                if (obj.constructor !== Promise) {
                    return false;
                }
                return obj.isRejected();
            }

            Promise.prototype.isPending = function () {
                return this.inspect().state === 'pending';
            }
            Promise.isPending = function (obj) {
                if (obj.constructor !== Promise) {
                    return false;
                }
                return obj.isPending();
            }

            return $delegate;
        }]);
    }
})();


text:
Q: Explanation needed: virtual, override and base Why doesn't the ", Second ID: " string in O.W2() get printed out? I know that the D2 property is empty.
using System;

public class O
{
    public string F { get; set; }
    public string L { get; set; }
    public string D { get; set; }

    public virtual string W()
    {
        return this.W2();
    }

    public virtual string W2()
    {
        return string.Format("First Name : {0}, Last name: {1}, ID: {2}", F, L, D);
    }
}

public class S : O
{
    public string D2 { get; set; }

    public override string W()
    {
        return base.W2();
    }

    public override string W2()
    {
        return base.W2() + string.Format(", Second ID: {0}", this.D2);
    }
}

class Program
{
    static void Main(string[] args)
    {
        O o = new S();

        o.D = "12345678";
        o.F = "John";
        o.L = "Jones";

        Console.WriteLine(o.W());

        // Output: First Name : John, Last name: Jones, ID: 12345678
    }
}

A: Because you called override W() which in turn calls base.W2(). Inside the class, base.W2() is determined statically (at compile time) to be the one in the base class:
public override string W()
{
    // directly calls W2() from the base class, ignores the override
    return base.W2();
}

If you want polymorphism for this scenario, you should omit base and just call W2():
public override string W()
{
    // goes to the override
    return W2();
}

A: The function W2() in the S object is never called!!
Bec when you called W() in S object u made it call the base W2()
Try  like this:
public override string W()
{
    String x = base.W2();
    x = x + this.W2();
    return x;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expectation value of a convolution of probability densities Assume we have a PDF, when we now calculate the convolution of this PDF with itself, what do we get in the end?
For Gaussian PDFs it's clear, we will have again an Gaussian but with $E[X]=2E[X_i]$. But how does this look for general PDFs? Is there any general information?
Best


text:
Q: how to force camelCase response? I am attempting to force a camelCase response with the following line in my ConfigureApp method:
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

The entire method:
        public static void ConfigureApp(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
            appBuilder.UseWebApi(config);
        }

And I'm returning the following response from my controller:
    public object Get()
    {
        var result = new { name = "alex", number = 1, lastname = "smith" };

        return Ok(result);
    }

The response I am getting is:
{"name":"alex","number":1,"lastname":"smith"}

The response I am expecting is:
{"name":"alex","number":1,"lastName":"smith"}

How do I force camelCase response (lastname vs lastName)?


text:
Q: Не работает таймер PHP + MySql Возвращает "время вышло", значит r < 0, но в БД значение у "pohod" больше 0, не как не могу понять в чем дело, исправьте пожалуйста ошибки.
$db_host = "localhost";
$db_user = "root"; // Логин БД
$db_password = ""; // Пароль БД
$db_table = "users"; // Имя Таблицы БД

$db = mysql_connect($db_host,$db_user,$db_password) OR DIE("Не могу создать соединение ");
mysql_select_db("game",$db);

$r=mysql_query("SELECT `pohod` FROM `users`");
list($r)=mysql_fetch_array($r);
$r=$r-time();
if($r>0)
{
  $s=$r%60;$r=(int)($r/60);
  $m=$r%60;$h=(int)($r/60);
  echo ($h<10?'0':'')."$h:".($m<10?'0':'')."$m:".($s<10?'0':'')."$s";
}
else
{
  echo "Время вышло";
}

A: $db_host = "localhost";
$db_user = "root"; // Логин БД
$db_password = ""; // Пароль БД
$db_table = "users"; // Имя Таблицы БД

$db = mysql_connect($db_host,$db_user,$db_password) OR DIE("Не могу создать соединение ");
mysql_select_db("game",$db);

$r=mysql_query("SELECT `pohod` FROM `users`", $db); // тут была ошибка
list($r)=mysql_fetch_array($r);
$r=$r-time();
echo $r."<br/>";
if($r>0)
{
  $s=$r%60;
  $r=(int)($r/60);
  $m=$r%60;
  $h=(int)($r/60);
  echo ($h<10?'0':'')."$h:".($m<10?'0':'')."$m:".($s<10?'0':'')."$s";
}
else
{
  echo "Время вышло";
}


text:
Q: How to combine two animations with a single loop? \documentclass[pstricks,border=15pt,12pt]{standalone}
\usepackage{pst-node,multido}

\begin{document}
\multido{\n=0+1, \i=90+-1}{91}{%
\begin{pspicture}[showgrid=true](5,5)
\psarc{->}(0,0){1}{0}{\n}
\psarc{->}(0,0){2}{0}{\n}
\psarcn{->}(0,0){4}{90}{\i}
\psarcn{->}(0,0){5}{90}{\i}
\end{pspicture}}
\end{document}

\documentclass[pstricks,border=15pt,12pt]{standalone}
\usepackage{pst-node,multido}

\begin{document}
\multido{\n=0+1,\i=90+-1}{46}{%
\begin{pspicture}[showgrid=true](5,5)
\psarc{->}(0,0){3}{0}{\n}
\psarcn{->}(0,0){3}{90}{\i}
\end{pspicture}}
\end{document}

Question:
How to combine two animations above with a single loop?

A:
\documentclass[pstricks,border=15pt,12pt]{standalone}
\usepackage{pst-node,multido}

\begin{document}
\multido{\in=0+1,\i=90+-1}{91}{%
  \begin{pspicture}[showgrid=true](5,5)
  \psarc{->}(0,0){1}{0}{\in}
  \psarc{->}(0,0){2}{0}{\in}
  \psarcn{->}(0,0){4}{90}{\i}
  \psarcn{->}(0,0){5}{90}{\i}
  \ifnum\in>45
    \def\nn{45}
    \def\ii{45}
  \else
    \edef\nn{\in}
    \edef\ii{\i}
  \fi
  \psarc{->}(0,0){3}{0}{\nn}
  \psarcn{->}(0,0){3}{90}{\ii}
  \end{pspicture}%
}
\end{document}

A: Just another idea.
Version 1 (slowed down)
\documentclass[pstricks,border=15pt]{standalone}
\usepackage{multido}

\begin{document}
\multido{\ia=0+1,\ib=90+-1}{91}{%
  \begin{pspicture}[showgrid=true,arrows=->,arrowinset=0](5,5)
  \psarc(0,0){1}{0}{\ia}
  \psarc(0,0){2}{0}{\ia}
  \psarcn(0,0){4}{90}{\ib}
  \psarcn(0,0){5}{90}{\ib}
  \psarc(0,0){3}{0}{!\ia\space 2 div}
  \psarcn(0,0){3}{90}{!45 \ib\space 2 div add}
  \end{pspicture}}
\end{document}

Version 2 (relaunched)
\documentclass[pstricks,border=15pt]{standalone}
\usepackage{multido}

\begin{document}
\multido{\ia=0+1,\ib=90+-1}{91}{%
  \begin{pspicture}[showgrid=true,arrowinset=0,arrows=->](5,5)
  \psarc(0,0){1}{0}{\ia}
  \psarc(0,0){2}{0}{\ia}
  \psarcn(0,0){4}{90}{\ib}
  \psarcn(0,0){5}{90}{\ib}
  \psarc(0,0){3}{0}{!\ia\space 45 gt {\ia\space 45 sub} {\ia} ifelse}
  \psarcn(0,0){3}{90}{!\ib\space 45 lt {\ib\space 45 add} {\ib} ifelse}
  \end{pspicture}}
\end{document}


text:
Q: Lightning in three.js I just discovered this piece of code, which produces a nice Halo effect:
Shader-Halo
I'm planning to remove the texture, and replace the SphereGeometry to a pipe or a line or something which will then act as a part of the lightning (I planing to chain a couple of glowing pipes/lines to appear as a lightning.)
So my question is: how to change this part in the code to draw a pipe/line instead of a sphere:
var ballGeometry = new THREE.SphereGeometry( 120, 32, 16 );
var ball = new THREE.Mesh( ballGeometry, customMaterial );
scene.add( ball );


text:
Q: Where to put business logic that spans multiple models? I have a situation where I can't figure out where to place this business logic.
In rails the best practise is to have fat models and thin controllers.
Now I have a situation where I am interacting (updating mostly) 3-4 model records.
Where should I put this logic?  Should I make a 'service' type class and put it in lib?

A: Trying to get something to backup the evidence, I found this, chapter 1.2.3.

lib/    Library modules

Which is definitely the most logical place to use for trans-model code.
It's basically the place where we put most of our code when writing acts_as_whatever gems.

A: Sometimes it might be worth just creating another class in the models folder that backs to AR based models.  A 'model' doesn't have to be limited to a DB table.


text:
Q: Nuxt.js - How to set API base URL? I'm trying to set the API base URL in Nuxt.js. I've used DreaMinder's answer from this question.
I get no errors but when I try to hit any endpoints from my app I get a 404 error (the endpoints to exist). The only way I can get my code to work is to put the full URL in each axios request.
This is my nuxt.config.js
import pkg from './package'
require('dotenv').config()

let development = process.env.NODE_ENV !== 'production'

export default {
  mode: 'universal',

  /*
   ** Headers of the page
   */
  head: {
    // title: pkg.name,
    title: "AppName",
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
  },

  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#fff' },

  /*
   ** Global CSS
   */
  css: [],

  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    '~/plugins/vue-cookies',
    '~/plugins/vee-validate',
    '~/plugins/moment',
    '~/plugins/vue-truncate-filter',
    '~/plugins/numeral'
  ],

  /*
   ** Axios module configuration
   */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    // baseURL: process.env.API_BASE_URL || 'http://localhost:5000/v1'
    baseURL: development ? 'http://localhost:5000/v1' : 'https://api.appname.com/v1'
  },

  /*
   ** Nuxt.js modules
   */
  modules: [
    '@nuxtjs/dotenv',
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://buefy.github.io/#/documentation
    'nuxt-buefy'
  ],

  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}

Anyone know what I'm doing wrong?

A: I had same errors.
But I fixed it to use proxy.
Please try it.
Here is my nuxt.config.js.
... ... ...
 modules: [
    ... ... ...
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
axios: {
    // See https://github.com/nuxt-community/axios-module#options
    // baseURL: process.env.API_URL || 'http://localhost:3000/',
    proxy:true,
  },
 proxy:{
    '/api/': { target: [your base url], pathRewrite: {'^/api/': ''}, changeOrigin: true }
  },
... ... ...

And You can call the endpoint using this.
let data= await this.$axios.get(
          '/api/[your endpoint url],
          {
            params: {
              ... ... ...
            },
            headers: {
              ... ... ...
            },
          }
        );

You need to install @nuxtjs/proxy npm module.
Please try use this.


text:
Q: CakePHP Validate Masked Credit Card With Regex I am creating an update billing information section for my users. I am currently passing a masked credit card number to the form. I do not want the user to have to update their credit card information if they only want to update say their billing address.
I am attempting to use regex to match the masked credit card, but I have not been able to get ANY regex patterns to match... Even 100% wildcards...
Here are couple of examples of what I have tried...
================================================================
The Masked Credit Card Value Is XXXXXXXXXXXX0012
================================================================
'creditcard' => array(
         'creditcard' => array(
            'rule' => array('cc', 'all', false, '^[.]+$'),
            'message' => 'Required',
            'allowEmpty' => false,
            'required' => true,
            ),
    ),

================================================================
    'creditcard' => array(
        'creditcard' => array(
            'rule' => array('cc', 'all', false, '/^[X]+[0-9](4,)$/'),
            'message' => 'Required',
            'allowEmpty' => false,
            'required' => true,
            ),
    ),

================================================================
    'creditcard' => array(
        'creditcard' => array(
            'rule' => array('cc', 'all', false, '/^[x]+[0-9]+$/i'),
            'message' => 'Required',
            'allowEmpty' => false,
            'required' => true,
            ),
    ),

Any Ideas Are Greatly Appreciated!
Thank You!!

A: Not a complete answer but in your first example, a period inside [ ] actually matches the character . not anything. So if you change that one to:
/^.+$/

it will probably work better.
In the second example you should use curly braces { } instead of parenthesis to designate length. Like so:
/^[X]+[0-9]{4,}$/

The last one looks good though. But by fixing the first two you might get started on finding the source of the problem at least!

A: The ^ and $ match the beginning and end, respectively, of the whole string, not just of individual lines.

A: Can't see why you need regex for this, unless I'm missing something.
Perhaps one way to do this would be to output the masked card number as just plain text, and provide a text box for the new card number.
When the form is submit, if this field is empty, then just unset the array key before saving, so the existing card value remains untouched.
If there is a new number, you can update as needed.


text:
Q: Parse data of size about 3MB using json in ANDROID? I have to parse data by HTTP request of size about 3MB, through JSon, but the parser that I am using is unable to do so. here is the JSon parser:
public static JSONObject getJSONfromURL(String url){

    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    }catch(Exception e){
          //  Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),102400);

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();

    }catch(Exception e){
           // Log.e("log_tag", "Error converting result "+e.toString());
    }

    try{

        jArray = new JSONObject(result);
    }catch(JSONException e){
           // Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return jArray;
}

Any help will really be appreciated. THANKS

A: You're parsing whole 3MB string in memory. It causes out of memory exception. Parse large data in stream:

*

*JsonReader since API level 11

*Android JSON library or for large data Jackson Streaming API


text:
Q: How do I convert .bin and .cue files to .iso for FREE on a Mac? I have some .bin & .cue files I'd like to convert .iso. I'm looking for a freeware program that will do this. Any suggestions.
NOTE I'm aware that VLC is supposed to be able to open these types of files but for some strange reason it's not working for me.

A: sudo port install bchunk
bchunk IMAGE.bin IMAGE.cue OUTPUTIMAGE.iso

I don't this is what you are looking for though.
VLC should have support for SVCD and VCD files, but are you certain that these files are SVCD and VCD?

A: On a Mac, you can mount an iso/dmg file and then "open disc" from VLC to view it (Assuming the image is a DVD/VCD). bin/cue specifically should be converted like sheepz said with bchunk.
FYI to mount an iso, use the disc utility app or from the command line - 'hdiutil mount myiso.iso'.


text:
Q: Complex Number Geometry 5 Let S be the set of complex numbers z such that the real part of 1/z is equal to 1/6. This set forms a curve. Find the area of the region inside the curve.
Can someone explain this problem to me?

A: Let $z=a+bi$. Then we have that $$\frac{1}{z} = \frac{1}{a+bi} = \frac{a-bi}{(a+bi)(a-bi)}= \frac{a}{a^2+b^2} - \frac{b}{a^2+b^2}i$$ The real part is equal to $1/6$, so we have $$\frac{a}{a^2+b^2} = \frac{1}{6}$$ Plot this on a a-b plane and you'll get a nice circle. The area is what you're looking for. $$\frac{a}{a^2+b^2} = \frac{1}{6} \Rightarrow a^2+b^2=6a \\ \Rightarrow (a-3)^2+b^2=3^2$$ This is a circle with radius $3$, thus the area is simply $\pi (3)^2 = 9\pi$.


text:
Q: In a $\Delta ABC$ whose sides are $a,b,c$, if $\tan A/2=\frac 56, \tan B/2 =\frac 25$, then prove that $a,b,c$ are in a geometric progression Using
$$\tan \frac A2 +\tan \frac B2 +\tan \frac C2=1-\tan \frac A2 \tan \frac B2 \tan \frac C2$$
Substituting the given values
$$\frac 56 +\frac 25  +\tan \frac B2=1-\frac 56 .\frac 25 \tan \frac B2$$
$$\tan \frac B2=\frac{-7}{40}$$
But I don't know what to do with this information. How do I prove they are in GP?

A: Your question appears to be wrong. Or my arithmetic could be, but I keep staring at it looking for the reason why.
Since $\sin A=\frac{2\times\frac56}{1+\frac{25}{36}}=\frac{60}{61}$ and similarly $\sin B=\frac{20}{29},\,\cos A=\frac{11}{61},\,\cos B=\frac{21}{29}$,$$\sin C=\sin(A+B)=\sin A\cos B+\cos A\sin B=\frac{1480}{61\times 29}.$$By the sine rule, what matters is whether the sines of $A,\,B,\,C$ are in geometric progression. Well, they're not.

A: From the given $\tan \frac A2 = \frac56$ and $\tan \frac B2 = \frac25$, we have
$$\sin A = \frac{2\tan \frac A2}{1+\tan^2 \frac A2}=\frac{60}{61}, \>\>\>\>\>\cos A = \frac{11}{61}$$
$$\sin B = \frac{2\tan \frac B2}{1+\tan^2 \frac B2}=\frac{20}{29}, \>\>\>\>\>\cos B = \frac{21}{29}$$
Then,
$$\frac{a+b}{2c}=\frac{\sin A +\sin B}{2\sin (A+B)}
=\frac{\sin A +\sin B}{2(\sin A\cos B + \cos A\sin B)}$$
$$=\frac{\frac{60}{61} +\frac{20}{29}} {2(\frac{60}{61}\cdot\frac{21}{29}+ \frac{11}{61} \cdot\frac{20}{29})}=\frac{60\cdot29+61\cdot20 }{2(60\cdot21+11\cdot20)}=1$$
Thus, $a$, $b$ and $c$ are in arithmetic progression (not geometric).

A: Use $$\tan(\alpha/2)=\sqrt{\frac{(s-b)(s-c)}{s(s-a)}}$$
$$\tan(\beta/2)=\sqrt{\frac{(s-a)(s-c)}{s(s-b)}}$$
since we have
$$\tan(\pi/2-\frac{\gamma}{2})=\frac{\frac {5}{6}+\frac{2}{5}}{1-\frac{5}{6}\times\frac{2}{5}}$$ we get
$$\cot(\gamma/2)=\frac{20}{37}$$ so
$$\tan(\gamma/2)=\sqrt{\frac{(s-a)(s-b)}{s(s-c)}}$$
Solving this system for $a,b,c$ we get
$b=\frac{61}{87}a,c=\frac{74}{87}a$

A: $Cos A=\frac{1- tan^2(A/2)}{1+tan^2(A/2)}=\frac{11}{61}$
$Cos B=\frac{1- tan^2(B/2)}{1+tan^2(B/2)}=\frac{21}{29}$
$$ a^2=b^2+c^2-2bc Cos A$$
$$ b^2=a^2+c^2-2ac Cos B$$
Summing these relations we get:
$$2 c^2=2ac Cos B +2bc Cos A$$
Plugging values of (Cos A) and (cos B) we get:
$$1189 c=319 b+ 1281 a$$
It does not show any geometric progression.

A: I would like to derive how the values of $\tan\dfrac A2,\tan\dfrac B2$ are decided
Method$\#1:$
Like Quanto's method $$\dfrac{a+b}{2c}=\dfrac{\sin A+\sin B}{2\sin C}=\dfrac{2\sin\dfrac{A+B}2\cos\dfrac{A-B}2}{4\sin\dfrac C2\cos\dfrac C2}=\dfrac{\cos\dfrac{A-B}2}{2\cos\dfrac{A+B}2}=\dfrac{\cos\dfrac A2\cos\dfrac B2+\sin\dfrac A2\sin\dfrac B2}{2\left(\cos\dfrac A2\cos\dfrac B2-\sin\dfrac A2\sin\dfrac B2\right)}$$
If this $=1,$ $$3\sin\dfrac A2\sin\dfrac B2=\cos\dfrac A2\cos\dfrac B2\iff\tan\dfrac A2\tan\dfrac B2=\dfrac13$$
Method$\#2:$
Here In a triangle, if $\tan(A/2)$, $\tan(B/2)$, $\tan(C/2)$ are in arithmetic progression, then so are $\cos A$, $\cos B$, $\cos C$,
we have derived $\sin A,\sin B,\sin C$ will be in Arithmetic Progression iff $\cot\dfrac A2,\cot\dfrac B2, \cot\dfrac C2$ are so.
Using In a triangle ABC, prove that cot(A/2)+cot(B/2)+cot(C/2) =cot(A/2)cot(B/2)cot(C/2),
$$\cot\dfrac A2+\cot\dfrac B2+\cot\dfrac C2=\cot\dfrac A2\cot\dfrac B2\cot\dfrac C2$$
Now if $\cot\dfrac A2+\cot\dfrac B2=2\cot\dfrac C2,$
$$3\cot\dfrac C2=\cot\dfrac A2\cot\dfrac B2\cot\dfrac C2$$
As $\cot\dfrac C2\ne0,$ the result follows.


text:
Q: Why is finding the factors of a number an algorithm with exponential time complexity? Why does this algo have an exponential time complexity?
I understand that "Modulus" is a bitwise operator and operates on individual bits. Hence In the worst case, we need to perform sqrt(2^n) divisions. So this is an exp time algorithm.
If that is true, won't all algo become exponential time? Please explain.
Find-Factor(X)
1: if X is even then
2: return "2 is a factor"
3: end if
4: for i = 3 to Sqrt(X) by +2 do
5:    test if X%i = 0, if yes, output "i is a factor"
6: end for
7: return "X is a prime."

A: Exponentiality comes from the number of iterations. In the worst case (which is the case number is prime) You have to do X / 2 iterations (in this algorithm and it is not a good one, for instance you can limit the loop with sqrt(X) instead of X). And this is exponential with the number of bits in your input = ln(X). Not with number X.
By the way, there are probabilistic checks which determines whether a given number is prime or not very quickly. And also there is a rather complicated algorithm which does the same job deterministically. You can google and find them.

A: They're exponential in the length of the number's representation because the representation itself is exponential, the next digit is 10n+1 or 2n+1 or whatever.  The linear search just has that much more to search through, that's all.


text:
Q: Why does the USACO grader not accept my solution to "Prime Cryptarithm"?(Output difference between my computer and the online grader) I am programming a solution to the problem http://acmph.blogspot.com/2010/12/usaco-prime-cryptarithm.html
and when I run it on my computer, given the input data
7
4 1 2 5 6 7 3

My computer gives me an answer of 384 which is the right answer.  But when I upload it to USACO site, it says that my program outputs 1.  Why does this happen?
Here is my code:
/*
ID: harry47341
PROG: crypt1
LANG: C++
*/
#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> digits;
int a, b, c, d, e, abc, de;
bool oneof1(int n) {
    int count1 = 1;
    while (true) {
        if (count1 > n)break;
        else {
            count1 = count1 * 10;
            int digit = n%count1 / (count1 / 10);
            if (!count(digits.begin(), digits.end(), digit) ){
                return false;
            }
            n = n - n%count1;

        }

    }
}
bool check() {
    int n = abc*e;
    int n1 = abc*d;
    if (n > 999 || n < 100)return false;
    if (n1 > 999 || n1 < 100)return false;

    if ((n1 * 10 + n) > 9999 || (n1 * 10 + n) < 1000)return false;
    if (oneof1(n) && oneof1(n1) && oneof1(n1 * 10 + n)) {
        return true;
    }

}

int main() {
    ofstream fout("crypt1.out");
    ifstream fin("crypt1.in");
    int count = 0;
    int n;
    fin >> n;
    for (int i = 0; i < n; i++) {
        int f;
        fin >> f;
        digits.push_back(f);
    }

    for (int i = 0; i < n; i++) {
        a = digits[i];
        for (int i1 = 0; i1 < n; i1++) {
            b = digits[i1];
            for (int i2 = 0; i2 < n; i2++) {
                c = digits[i2];
                for (int i3 = 0; i3 < n; i3++) {
                    d = digits[i3];
                    for (int i4 = 0; i4 < n; i4++) {
                        e = digits[i4];
                        abc = a * 100 + b * 10 + c;
                        de = d * 10 + e;
                        if (check()) {
                            count++;
                        }
                    }
                }
            }
        }

    }
    fout << count << endl;
    return 0;
}

A: In your oneof1 and check functions, you do not return a value for all the return paths in the function.  Thus your program exhibits undefined behavior, since returning nothing from a function that returns a value is UB.  That's why you were getting different answers when run on a different computer / system.
To fix the issue, return true in the oneof1 function, and return false for the check function:
bool oneof1(int n) {
    int count1 = 1;
    while (true) {
        if (count1 > n)break;
        else {
            count1 = count1 * 10;
            int digit = n%count1 / (count1 / 10);
            if (!count(digits.begin(), digits.end(), digit) ){
                return false;
            }
            n = n - n%count1;
        }
    }
    return true;  // this was missing
}

 bool check() {
    int n = abc*e;
    int n1 = abc*d;
    if (n > 999 || n < 100)return false;
    if (n1 > 999 || n1 < 100)return false;

    if ((n1 * 10 + n) > 9999 || (n1 * 10 + n) < 1000)return false;
    if (oneof1(n) && oneof1(n1) && oneof1(n1 * 10 + n)) {
        return true;
    }
    return false;  // this was missing
}

Most compilers have a warning when you write a function that doesn't return a value for all return paths.  Please set your warnings to at least to the level that gives this information (or if you did, read the warnings that your compiler is giving you).


text:
Q: Xgboost not running with Callibrated Classifier I am trying to run XGboost with with calibrated classifier, below is the snippet of code where I am facing the error:
from sklearn.calibration import CalibratedClassifierCV
from xgboost import XGBClassifier
import numpy as np

x_train =np.array([1,2,2,3,4,5,6,3,4,10,]).reshape(-1,1)
y_train = np.array([1,1,1,1,1,3,3,3,3,3])

x_cfl=XGBClassifier(n_estimators=1)
x_cfl.fit(x_train,y_train)
sig_clf = CalibratedClassifierCV(x_cfl, method="sigmoid")
sig_clf.fit(x_train, y_train)

Error:
TypeError: predict_proba() got an unexpected keyword argument 'X'"

Full Trace:
TypeError                                Traceback (most recent call last)
<ipython-input-48-08dd0b4ae8aa> in <module>
----> 1 sig_clf.fit(x_train, y_train)

~/anaconda3/lib/python3.8/site-packages/sklearn/calibration.py in fit(self, X, y, sample_weight)
    309                 parallel = Parallel(n_jobs=self.n_jobs)
    310
--> 311                 self.calibrated_classifiers_ = parallel(
    312                     delayed(_fit_classifier_calibrator_pair)(
    313                         clone(base_estimator), X, y, train=train, test=test,

~/anaconda3/lib/python3.8/site-packages/joblib/parallel.py in __call__(self, iterable)
   1039             # remaining jobs.
   1040             self._iterating = False
-> 1041             if self.dispatch_one_batch(iterator):
   1042                 self._iterating = self._original_iterator is not None
   1043

~/anaconda3/lib/python3.8/site-packages/joblib/parallel.py in dispatch_one_batch(self, iterator)
    857                 return False
    858             else:
--> 859                 self._dispatch(tasks)
    860                 return True
    861

~/anaconda3/lib/python3.8/site-packages/joblib/parallel.py in _dispatch(self, batch)
    775         with self._lock:
    776             job_idx = len(self._jobs)
--> 777             job = self._backend.apply_async(batch, callback=cb)
    778             # A job can complete so quickly than its callback is
    779             # called before we get here, causing self._jobs to

~/anaconda3/lib/python3.8/site-packages/joblib/_parallel_backends.py in apply_async(self, func, callback)
    206     def apply_async(self, func, callback=None):
    207         """Schedule a func to be run"""
--> 208         result = ImmediateResult(func)
    209         if callback:
    210             callback(result)

~/anaconda3/lib/python3.8/site-packages/joblib/_parallel_backends.py in __init__(self, batch)
    570         # Don't delay the application, to avoid keeping the input
    571         # arguments in memory
--> 572         self.results = batch()
    573
    574     def get(self):

~/anaconda3/lib/python3.8/site-packages/joblib/parallel.py in __call__(self)
    260         # change the default number of processes to -1
    261         with parallel_backend(self._backend, n_jobs=self._n_jobs):
--> 262             return [func(*args, **kwargs)
    263                     for func, args, kwargs in self.items]
    264

~/anaconda3/lib/python3.8/site-packages/joblib/parallel.py in <listcomp>(.0)
    260         # change the default number of processes to -1
    261         with parallel_backend(self._backend, n_jobs=self._n_jobs):
--> 262             return [func(*args, **kwargs)
    263                     for func, args, kwargs in self.items]
    264

~/anaconda3/lib/python3.8/site-packages/sklearn/utils/fixes.py in __call__(self, *args, **kwargs)
    220     def __call__(self, *args, **kwargs):
    221         with config_context(**self.config):
--> 222             return self.function(*args, **kwargs)

~/anaconda3/lib/python3.8/site-packages/sklearn/calibration.py in _fit_classifier_calibrator_pair(estimator, X, y, train, test, supports_sw, method, classes, sample_weight)
    443     n_classes = len(classes)
    444     pred_method = _get_prediction_method(estimator)
--> 445     predictions = _compute_predictions(pred_method, X[test], n_classes)
    446
    447     sw = None if sample_weight is None else sample_weight[test]

~/anaconda3/lib/python3.8/site-packages/sklearn/calibration.py in _compute_predictions(pred_method, X, n_classes)
    499         (X.shape[0], 1).
    500     """
--> 501     predictions = pred_method(X=X)
    502     if hasattr(pred_method, '__name__'):
    503         method_name = pred_method.__name__

TypeError: predict_proba() got an unexpected keyword argument 'X'

I am quite surprised by this, as it was running for me till yesterday, same code is running when I use some other Classifier.
from sklearn.calibration import CalibratedClassifierCV
from xgboost import XGBClassifier
import numpy as np

x_train = np.array([1,2,2,3,4,5,6,3,4,10,]).reshape(-1,1)
y_train = np.array([1,1,1,1,1,3,3,3,3,3])

x_cfl=LGBMClassifier(n_estimators=1)
x_cfl.fit(x_train,y_train)
sig_clf = CalibratedClassifierCV(x_cfl, method="sigmoid")
sig_clf.fit(x_train, y_train)

Output:
CalibratedClassifierCV(base_estimator=LGBMClassifier(n_estimators=1))

Is there a problem with my Xgboost installation?? I use conda for installation and last I remember I had uninstalled xgboost yesterday and installed it again.
my xgboost version:

1.3.0

A: I believe that the problem comes from XGBoost.
It's explained here: https://github.com/dmlc/xgboost/pull/6555
XGBoost defined:
predict_proba(self, data, ...
instead of:
predict_proba(self, X, ...
And since sklearn 0.24 calls clf.predict_proba(X=X), an exception is thrown.
Here is an idea to fix the problem without changing the version of your packages: Create a class that inherits XGBoostClassifier to override predict_proba with the right argument names and call super().

A: It's fixed now, seems like there is a bug in scikit-learn= 0.24
I downgraded to 0.22.2.post1 and it was fixed!

A: Th best way is to upgrade your xgboost
run the following from the jupyter notebook
pip install xgboost --upgrade


text:
Q: Change the output/projection format of search query in a node js app with mongodb and mongoose I'm implementing a search function for a node app with mongoose. I'm fairly new to node.js and mongoose. I implemented a search function following this answer. It works and gives me the results.
But the problem is it gives an array of whole objects. All I need is titles and IDs. Could anyone please suggest me how to get those.
this is my code
Model.find(
    { $text : { $search : req.params.searchtext }},
    {score : { $meta: "textScore" }}
)
.sort({ score : { $meta : 'textScore' } })
.exec(function(err, results) {
    if (err) {
      throw err;
      return res.status(403).send({success: false});
    } else{
      res.json({success: true, results: results});
    }

});

this is another code where I'm finding a similar list.
Model.find({
        'createdBy.id' : user._id
      },'title _id' ,function(err, result) { #callback};

but I cannot use 'title _id' in the search function since the $meta sort key needs to be there for sort  the results.

A: I could get the change the output by using mongoose query api.
Model.find(
    { $text : { $search : req.params.searchtext }},
     {score : { $meta: "textScore" }}
)
.limit(20)
.select('textScore title _id description')
.sort({ score : { $meta : 'textScore' } })
.exec(function(err, results) {
    if (err) {
      throw err;
      return res.status(403).send({success: false});
    } else{
      res.json({success: true, results: results});
    }

});

all I had to do is just adding select('textScore title _id description') line.


text:
Q: How to switch on an LED when I press mouse button using a transistor instead of a coin cell I have been asked to modify an optical mouse so that an LED switches on when one of the mouse buttons is pressed. I've found some information online where a coin cell is used, this appears to be because the logic in the mouse can't provide enough current to drive the LED and when the mouse button is pressed it pulls the input to the ic low (?).
While I don't really understand electronics enough to design a circuit and select the correct component values, I'm sure this can be done with a simple transistor circuit instead of using a battery.
The optical sensor is a PixArt PAW3552DB which I have been able to find a basic datasheet on but it didn't seem to have any useful information.
It's a USB mouse and I only need to switch on the LED when the left button is pressed.
Please can someone help?

A: Is that J1 connector a USB from your computer? Just use an output of your IC to drive a transistor from USB 5V power. In the below circuit you need to calculate the values of the resistor accordingly to the currents you expect to go through your LED (usually 330 ohm) and IC. Use their respective datasheets to do so.
Edit: In case that you want to wire the LED directly to the button, just connect in series the button, 330 ohm resistor, LED and 5V power.

Image source: Figure 9: Driving an LED via a transistor (NPN) driver. from - Pont, Michael & Ong, Royan & Parikh, Chinmay & Kureemun, Ridwan & Wong, Chen & Peasgood, William & Li, Yuhua. (1999). A SELECTION OF PATTERNS FOR RELIABLE EMBEDDED SYSTEMS.

A:
simulate this circuit – Schematic created using CircuitLab
Looking at the photos, I believe your switch can handle 10mA  to ground and the supply side might be on the other side of the R10 resistor.  (Verify)

A:
I'm sure this can be done with a simple transistor circuit instead of using a battery.

Based on the second photo - maybe.
It takes both.  You need a 1-transistor amplifier (in this case, operating as a saturated switch) to amplify the very low signal currents in a mouse circuit up to a current value that is high enough to power an LED.  You also need a power source for the added LED.
From the photos, it looks like you are working with a wired USB mouse.  If so, then 5 V available in there with more than enough extra current capacity to power the added LED.


text:
Q: An application of Itô's formula to an SDE on a Lie group I'm trying to understand a calculation in this paper (equation (3.8)). With some details removed, the setup is as follows.
Let $G$ be a Lie group, and $g(t)$ a curve in $G$ satisfying the SDE
$$dg(t) = T_e L_{g(t)}H_1 dW_t + T_e L_{g(t)}H_2 dt + T_e L_{g(t)}u(t) dt,$$
where $H_1,H_2$ are elements of the Lie algebra, $u(t)$ is a curve in the Lie algebra, and $W_t$ is a real-valued brownian motion. The SDE / stochastic integrals are in the Stratonovich sense. My knowledge of processes and SDE's on manifolds are from Elton Hsu's book. According to the construction in this book, a solution to an equation such as the above is defined by being a solution to the following euclidean SDE, for every smooth real-valued function f on G,
$$df(g(t)) = (T_e L_{g(t)}H_1)f\hspace{1mm} dW_t + (T_e L_{g(t)}H_2)f\hspace{1mm}dt + (T_e L_{g(t)}u(t))f \hspace{1mm} dt.$$
In the paper, they then consider a sort of perturbation of the curve g; $g(t)e_{\epsilon}(t)$, where e_{\epsilon}(t) is another curve in G. I don't think it is important to my question, but $e_\epsilon (t)$ is defined by a set of ODE's, equation (3.2) in the paper.
They then state that 'by Itö's formula' $g_\epsilon(t) := g(t) e_\epsilon(t)$ fulfills the SDE
$$dg_\epsilon(t) = T_e L_{g_\epsilon(t)}Ad_{e_{\epsilon}^{-1}(t)}(H_1) dW_t + T_e L_{g_\epsilon(t)}Ad_{e_{\epsilon}^{-1}(t)}H_2 dt + T_e L_{g_\epsilon(t)}Ad_{e_{\epsilon}^{-1}(t)}u(t) dt + T_e L_{g_\epsilon(t)} (T_{e_\epsilon (t)} L_{e^{-1}_\epsilon(t)}\dot{e}_\epsilon(t) dt $$
which (my calculation) is equivalent to
$$d(g(t) e_\epsilon (t)) = T_e (L_{g(t)}\circ R_{e_\epsilon (t)})H_1\hspace{1mm} dW_t + T_e (L_{g(t)}\circ R_{e_\epsilon (t)})H_2\hspace{1mm}dt + T_e (L_{g(t)}\circ R_{e_\epsilon (t)})u(t)  \hspace{1mm} dt + T_{e_\epsilon (t)} L_{g(t)} \dot{e}_\epsilon(t) dt\hspace{1mm}$$
I haven't been able to verify this, or find hints elsewhere. I have a feeling that I'm missing (or lack knowledge of) something very simple. Any hints would be greatly appreciated. Even if only for the deterministic case ($H_1 = 0$).

A: To understand (3.8), I think it helps to write down (2.4) and (3.2) from that paper. From (3.2), note that $e_{\epsilon}(t)$ satisfies the ODE $$
\dot e_{\epsilon}(t) = \epsilon T L_{e_{\epsilon}(t)} \dot v(t) \;. \tag{1}
$$
By the Euclidean Itô-Stratonovich conversion formula applied in the Lie algebra, note from (2.4) that $g(t)$ satisfies the Itô SDE $$
d g(t) = T L_{g(t)} \left( \sum_i H_i dW^i_t + u(t) dt \right)  \;. \tag{2}
$$
Note also that the product rule for Itô processes applied to $g_{\epsilon}(t) = g(t) e_{\epsilon}(t)$ reduces to the standard product rule because $e_{\epsilon}(t)$ has finite variation.
Hence, from (1), (2), and the product rule, \begin{align}
d g_{\epsilon}(t)  &=  T R_{e_{\epsilon}(t)} d g(t)  + T L_{g(t)} \dot e_{\epsilon}(t) \\
&= T L_{g_{\epsilon}(t)} \left( \sum_{i} \operatorname{Ad}_{e_{\epsilon}(t)^{-1}} H_i dW^i_t +  \operatorname{Ad}_{e_{\epsilon}(t)^{-1}} u(t) dt \right) + \epsilon T L_{g_{\epsilon}(t)}  \dot v \tag{3}
\end{align}
where we used the identities \begin{align}
T R_{e_{\epsilon}(t)} \; T L_{g(t)} = T L_{g(t)} \; T R_{\epsilon(t)} = T L_{g_{\epsilon}(t)} \; \operatorname{Ad}_{e_{\epsilon}(t)^{-1}} \;, \qquad
T L_{g(t)} \dot e_{\epsilon}(t)  = \epsilon T L_{g_{\epsilon}(t)} \dot v(t) \;.
\end{align}
Up to an Itô-Stratonovich correction term, (3) is exactly (3.8) in that paper.


text:
Q: Convert VARCHAR date to datetime on MySQL Database I currently have about 100 dates stored as mm/dd/yyyy that I need converted to default datetime format for a mysql server. YYYY-MM-DD 00:00:00
I've simply tried to change the type to datetime, and no luck, as I would figure, not really sure where to start.

A: Thank you guys, I did not know about the STR_TO_DATE function
UPDATE my_table SET column_name=str_to_date(column_name, '%m/%d/%Y');
Worked just perfect!

A: Use STR_TO_DATE
select str_to_date(your_date_column, '%m/%d/%Y')
from your_table


text:
Q: URI is not hierarchical - but I need a File object I need to get a File object (not a Stream) to pass to a library. I am getting "URI is not hierarchical". I have seen some solutions but they either are rather inefficient or use external libraries.

File myFile = new File(MyClass.class.getClassLoader().getResource(dir).toURI())

By the way, I need the object to pass to

Lucene FSDirectory.open(myFile)

Any idea?

A: URI not hierarchical need to use File class for a method
may be a possible solution. Essentially just copies the file to a temp file then uses that. I was getting this error since I was using a JAR.


text:
Q: How can i deploy my angular universal app on Namcheap hosting I just build an angular universal app and i now want to deploy it to namecheap hosting. I have copied the dist folder to public_html directory on the server i have created node app in same directory but now i dont know what next i should do. I am stucked

A: if your backend have in node.js then it is not possible to deploy in shared server. You need to deploy on VPS or any private server. And you have to run your Angular app by using node.js.
And your app have to setup like this. enter link description here
and just run server.js using PM2 on VPS


text:
Q: automatically add centesimal point on input field I have a quantity field that I want to have initial value as 0.00 and as you type you would be replacing the natural numbers, for example, inserting 10 would result 10.00, and inserting 10.5 or 10,5 would result 10.50.
Any ideas?
example code:
 Product Code:<input size=10 /><br />
 Amount Needed:<input size=10 placeholder="0.00"/> Unity:<select>
                              <option value="gr">gr</option>
                              <option value="kg">kg</option>
                              <option value="ml">ml</option>
                              <option value="li">li</option>
                            </select>

A: You can try this

$('#in').change(function() {
  $(this).val(parseFloat($(this).val()).toFixed(2));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="in">


text:
Q: Array Extend without custom method? Is it possible to use Array.push to add multiple values from a list? For example, currently what I'm having to do is:

Array.prototype.extend = function(arr) {
    for (let elem of arr) {
        this.push(elem);
    }
}
let x = [1,2,3];
let y = [4,5,6];
let z = [7,8,9];
x.push(y);
x.extend(z)
console.log(x);

Or, is there some way to pass the array as a single argument to the push method, or perhaps there's another Array method entirely that does this instead?

A: It's usually bad practice to Extend Native Types with Custom Methods. So instead of adding custom ones to the Array prototype you could:

*

*Push values of another Array using the Spread Syntax ...

const x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(y);
x.push(...z)
console.log(x);

*

*Concatenate, using the Array.prototype.concat()

let x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(y);
x = x.concat(z);
console.log(x);

The difference being - .concat() does not directly modify the original Array, therefore the x = x.concat( assignment syntax, and the Original x array being set as a let variable.

A: You can push multiple arguments to Array.prototype.push and they'll all be pushed to our result array, so we can "convert" our array into multiple arguments using the ES6 spread syntax.

let x = [1,2,3];
let y = [4,5,6];
x.push(...y);
console.log(x);

A: you can spread the array element like this
const x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(...y);
x.push(...z)
console.log(x);


text:
Q: What does it mean that gravity is '"local"? What is "local" defined to be? Why don't larger systems affect smaller ones? ie. Don't we need to consider the gravitational pull from all other objects in the universe? Is this "canceled" out somehow or do other objects just play such a small effect we don't consider them?

A: It's a bit difficult to give an all-encompassing definition of locality which isn't hopelessly broad, but we can phrase it in terms of your example.
In particle mechanics, a theory is local if the time-evolution of a particle is determined entirely by influences in its immediate neighborhood.  For example, if we say that every pair of particles in the universe exerts an attractive gravitational force on each other, then this is a non-local theory because the force on me cannot be deduced from my immediate surroundings.
However, we can modify this theory to make it local by introducing the concept of a gravitational field which exists at every point in space.  Even though the value of that field is determined by masses which may be very far away, it is the gravitational field at my precise location which exerts the force on me, making the theory local.
The difference between the local and non-local theories are more than superficial - the tangible existence of this local gravitational field introduces the possibility that it could carry momentum and energy in a way which could not reasonably be explained by the non-local "action-at-a-distance" which characterizes the non-local model.


text:
Q: VB Net access to form control by their variable names From a FormName2, and I need to set a text in a TextboxName1 that is in a FormName1, by their string names.
Then, from FormName2, I should set the text like FormName1.TextboxName1.text = "test".
However, I need to achieve it with string names of the controls.
stringFormName.stringTextboxName.text ="test"

How to reach it?

A: You could retrieve all the opened instances of your forms in the Application.OpenForms collection.
Using that collection you can retrieve the form with the specified name
Dim aForm = Application.OpenForms.Item("FormName1")

At this point, you can scan the controls of this form with the same pattern for a control with a specific name
If aForm IsNot Nothing Then
   Dim aControl = aForm.Controls.Item("TextBoxName1")
   if aControl IsNot Nothing then
      aControl.Text = "test"
   End If
End If

The only problem with this search for a control is the possibility of the control to be contained in a control container different from the top level form. For example the control could be inside a GroupBox or a Panel. In this case you need to use the Find method from the Control collection with the second parameter set to true to search all the control hierarchy
  Dim aControl = aForm.Controls.Find("TextBoxName1", True)

A: Use FindControl:
Private Sub Button1_Click(sender As Object, MyEventArgs As EventArgs)
    Dim myControl1 As Control = FormName1.FindControl("stringTextboxName")
    If (Not myControl1 Is Nothing)
       ' Get control's parent.
       Dim tb as TextBox= CType(myControl1, TextBox)
       tb.text="test"
    Else
       Console.WriteLine("Control not found.....")
    End If
    End Sub

If you have nested elements you may need to call find control recursively.


text:
Q: Async Program still freezing up the UI Hello I'm writing a WPF program that gets has thumbnails inside a ThumbnailViewer. I want to generate the Thumbnails first, then asynchronously generate the images for each thumbnail.
I can't include everything but I think this is whats relevant
Method to generate the thumbnails.
public async void GenerateThumbnails()
{
   // In short there is 120 thumbnails I will load.
   string path = @"C:\....\...\...png";
   int pageCount = 120;

   SetThumbnails(path, pageCount);
   await Task.Run(() => GetImages(path, pageCount);
 }

 SetThumbnails(string path, int pageCount)
 {
    for(int i = 1; i <= pageCount; i ++)
    {
        // Sets the pageNumber of the current thumbnail
        var thumb = new Thumbnail(i.ToString());
        // Add the current thumb to my thumbs which is
        // binded to the ui
        this._viewModel.thumbs.Add(thumb);
    }
  }

  GetImages(string path, int pageCount)
  {
       for(int i = 1; i <= pageCount; i ++)
       {
            Dispatcher.Invoke(() =>
            {
                var uri = new Uri(path);
                var bitmap = new BitmapImage(uri);
                this._viewModel.Thumbs[i - 1].img.Source = bitmap;
            });
        }
  }

When I run the code above it works just as if I never add async/await/task to the code. Am I missing something? Again What I want is for the ui to stay open and the thumbnail images get populated as the GetImage runs. So I should see them one at a time.
UPDATE:
Thanks to @Peregrine for pointing me in the right direction. I made my UI with custom user controls using the MVVM pattern. In his answer he used it and suggested that I use my viewModel. So what I did is I add a string property to my viewModel and made an async method that loop though all the thumbnails and set my string property to the BitmapImage and databound my UI to that property. So anytime it would asynchronously update the property the UI would also update.

A: The Task that runs GetImages does virtually nothing but Dispatcher.Invoke, i.e. more or less all your code runs in the UI thread.
Change it so that the BitmapImage is created outside the UI thread, then freeze it to make it cross-thread accessible:
private void GetImages(string path, int pageCount)
{
    for (int i = 0; i < pageCount; i++)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.UriSource = new Uri(path);
        bitmap.EndInit();
        bitmap.Freeze();

        Dispatcher.Invoke(() => this._viewModel.Thumbs[i].img.Source = bitmap);
    }
}

You should also avoid any async void method, excpet when it is an event handler. Change it as shown below, and await it when you call it:
public async Task GenerateThumbnails()
{
    ...
    await Task.Run(() => GetImages(path, pageCount));
}

or just:
public Task GenerateThumbnails()
{
    ...
    return Task.Run(() => GetImages(path, pageCount));
}

A: An alternative that altogether avoids async/await is a view model with an ImageSource property whose getter is called asynchronously by specifying IsAsync on the Binding:
<Image Source="{Binding Image, IsAsync=True}"/>

with a view model like this:
public class ThumbnailViewModel
{
    public ThumbnailViewModel(string path)
    {
        Path = path;
    }

    public string Path { get; }

    private BitmapImage îmage;

    public BitmapImage Image
    {
        get
        {
            if (îmage == null)
            {
                îmage = new BitmapImage();
                îmage.BeginInit();
                îmage.CacheOption = BitmapCacheOption.OnLoad;
                îmage.UriSource = new Uri(Path);
                îmage.EndInit();
                îmage.Freeze();
            }

            return îmage;
        }
    }
}

A: Rather than involving the the dispatcher and jumping back and forth, I'd do something like this:
private Task<BitmapImage[]> GetImagesAsync(string path, int pageCount)
{
    return Task.Run(() =>
    {
        var images = new BitmapImage[pageCount];
        for (int i = 0; i < pageCount; i++)
        {
            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.UriSource = new Uri(path);
            bitmap.EndInit();
            bitmap.Freeze();
            images[i] = bitmap;
        }
        return images;
    }
}

Then, on the UI thread calling code:
var images = await GetImagesAsync(path, pageCount);
for (int i = 0; i < pageCount; i++)
{
    this._viewModel.Thumbs[i].img.Source = images[i];
}

A: It looks as though you've been mislead by the constructor of BitmapImage that can take a Url.
If this operation really is slow enough to justify using the async-await pattern, then you would be much better off dividing it into two sections.
a) Fetching the data from the url. This is the slow part - it's IO bound, and would benefit most from async-await.
public static class MyIOAsync
{
    public static async Task<byte[]> GetBytesFromUrlAsync(string url)
    {
        using (var httpClient = new HttpClient())
        {
            return await httpClient
                       .GetByteArrayAsync(url)
                       .ConfigureAwait(false);
        }
    }
}

b) Creating the bitmap object. This needs to happen on the main UI thread, and as it's relatively quick anyway, there's no gain in using async-await for this part.
Assuming that you're following the MVVM pattern, you shouldn't have any visual elements in the ViewModel layer - instead use a ImageItemVm for each thumbnail required
public class ImageItemVm : ViewModelBase
{
    public ThumbnailItemVm(string url)
    {
        Url = url;
    }

    public string Url { get; }

    private bool _fetchingBytes;

    private byte[] _imageBytes;

    public byte[] ImageBytes
    {
        get
        {
            if (_imageBytes != null || _fetchingBytes)
                return _imageBytes;

            // refresh ImageBytes once the data fetching task has completed OK
            Action<Task<byte[]>> continuation = async task =>
                {
                    _imageBytes = await task;
                    RaisePropertyChanged(nameof(ImageBytes));
                };

            // no need for await here as the continuations will handle everything
            MyIOAsync.GetBytesFromUrlAsync(Url)
                .ContinueWith(continuation,
                              TaskContinuationOptions.OnlyOnRanToCompletion)
                .ContinueWith(_ => _fetchingBytes = false)
                .ConfigureAwait(false);

            return null;
        }
    }
}

You can then bind the source property of an Image control to the ImageBytes property of the corresponding ImageItemVm - WPF will automatically handle the conversion from byte array to a bitmap image.
Edit
I misread the original question, but the principle still applies. My code would probably still work if you made a url starting file:// but I doubt it would be the most efficient.
To use a local image file, replace the call to GetBytesFromUrlAsync() with this
public static async Task<byte[]> ReadBytesFromFileAsync(string fileName)
{
    using (var file = new FileStream(fileName,
                                     FileMode.Open,
                                     FileAccess.Read,
                                     FileShare.Read,
                                     4096,
                                     useAsync: true))
    {
        var bytes = new byte[file.Length];

        await file.ReadAsync(bytes, 0, (int)file.Length)
                  .ConfigureAwait(false);

        return bytes;
    }
}


text:
Q: how to give user server name instead of ip when connecting through SSH? I have a virtualbox on which I have installed ubuntu 12.04. My host computer is Mac OS (mavericks). I did a SSH key copy to my remote (which is ubuntu server and I call it myubuntu).
when I did
ssh username@myubuntu
ssh: Could not resolve hostname ubuntuhadoop: nodename nor servname provided, or not known

but when I tried:
ssh username@66.90.115.178

I was able to log in to the remote server (which is myubuntu).
why is it need that I give IP address it connects properply but not the servername.
I am not sure if this is possible. But I found in one of youtube tutorials.
ssh myubuntu (NOT username@myubuntu)
and logged onto the remote server, without username. is this possible?

A: You have a few options.
If you need access from only a few locations, or a single location, update /etc/hosts
sudo nano /etc/hosts

Add an entry for your server
66.90.115.178 myubuntu

Second, purchase or find a free DNS service, http://www.noip.com/free/ or similar.
Third, ssh uses your current user name by default, so if you have the same user name on both client and server, just ssh server_name
ssh your_server

You only need to specify a user name if the names are different or you want a new user
ssh new_user@your_server

A: I also had this problem. I had defined another host as below (in /etc/hosts):
hostname1 IP1
hostname2 IP2

I changed it to:
IP1 hostname1
IP2 hostname2


text:
Q: Why does this script not reliably log the latest file? This script fails sometimes and succeeds sometimes (a very annoying situation):
#!/bin/bash
set -Eeuxo pipefail

test_dir="$(mktemp -d)"
touch "$test_dir/file"{001..312}
latest_file="$(find $test_dir -type f | sort -r | head -n1)"
echo $latest_file

When it succeeds, it logs something like this:
++ mktemp -d
+ test_dir=/tmp/tmp.yWelcpBYB7
+ touch /tmp/tmp.yWelcpBYB7/file001 /tmp/tmp.yWelcpBYB7/file002 ... /tmp/tmp.yWelcpBYB7/file312
++ find /tmp/tmp.yWelcpBYB7 -type f
++ head -n1
++ sort -r
+ latest_file=/tmp/tmp.yWelcpBYB7/file312
+ echo /tmp/tmp.yWelcpBYB7/file312
/tmp/tmp.yWelcpBYB7/file312

When it fails, it logs something like this:
++ mktemp -d
+ test_dir=/tmp/tmp.VzTqmgpZyG
+ touch /tmp/tmp.VzTqmgpZyG/file001 /tmp/tmp.VzTqmgpZyG/file002 ... /tmp/tmp.VzTqmgpZyG/file312
++ find /tmp/tmp.VzTqmgpZyG -type f
++ sort -r
++ head -n1
+ latest_file=/tmp/tmp.VzTqmgpZyG/file312

Notice that echo $latest_file line is not executed here even though it appears in xtrace
I cannot get a successful run if I use 10,000 files, so I suspect it has something to do with head stopping find early.
#!/bin/bash
set -Eeuxo pipefail

test_dir="$(mktemp -d)"
touch "$test_dir/file"{0000..9999}
latest_file="$(find $test_dir -type f | sort -r | head -n1)"
echo $latest_file

If I suppress stop on error (using set +e), it succeeds:
#!/bin/bash
set -Eeuxo pipefail

test_dir="$(mktemp -d)"
touch "$test_dir/file"{0000..9999}
set +e
latest_file="$(find $test_dir -type f | sort -r | head -n1)"
set -e
echo $latest_file

Why does this script not reliably log the latest file?

A: The problem is the -e. Why? -e makes bash abort in case a process exits with a non-zero exit code (the full rules are a bit more complicated). If there is a pipe, just the last command counts.
Your head -n1 creates an error situation, internally, because it has to kind of break the pipe (you can check it with strace) to ignore the rest of the output from sort.
So, to make your script work reliably with -e, you can add a cat to the end of the pipe. head will still break the pipe, but since it no longer is the last command in it, it will not be taken into account by -e. cat is a no-op for the pipe:
#!/bin/bash
set -Eeuxo pipefail

test_dir="$(mktemp -d)"
touch "$test_dir/file"{0000..9999}
latest_file="$(find $test_dir -type f | sort -r | head -n1 | cat)"
echo $latest_file

Please check Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected? to know why -e is such an unstable feature and the kind of problems it might bring about. There are many examples at the end. My favorite:
#!/bin/bash

set -e
foo=$(expr 1 - 1)
echo survived

It will not print survived, that line will not be executed. But, if you had foo=$(expr 2 - 1), then the echo would be executed!
You'd be better off implementing your own error checking, -e isn't the best solution out there.


text:
Q: How to fire event on Unity after an interstitial ad close? I'm using the last AdMob plugin into Unity3d.
I know there are these kind of requests for AdMob:
// Called when an ad request has successfully loaded.
bannerView.AdLoaded += HandleAdLoaded;

// Called when an ad request failed to load.
bannerView.AdFailedToLoad += HandleAdFailedToLoad;

// Called when an ad is clicked.
bannerView.AdOpened += HandleAdOpened;

// Called when the user is about to return to the app after an ad click.
bannerView.AdClosing += HandleAdClosing;

// Called when the user returned from the app after an ad click.
bannerView.AdClosed += HandleAdClosed;

// Called when the ad click caused the user to leave the application.
bannerView.AdLeftApplication += HandleAdLeftApplication;

But I need to fire an event after the user clicked the (X) button to close the interstitial Ad. How should I do that?
The ad loads after the level is finished, than I want to load the next level with "Application.LoadLevel(something)".
I've been trying to do this for hours, thanks

A: the .AdClosed worked just right after I figured out what was wrong.
You have to use:
using System;

or EventArgs wont work


text:
Q: Reinterpret 2d array as pointer Assume I have an array like this:
unsigned char a[10][10];

and I want to use fread to read bytes into this array (row-major order):
FILE *f = fopen("xxx.bin", "rb");
fread((unsigned char *)a, 1, 10 * 10, f);
fclose(f);

As the first parameter of fread is of type void *, is there a standard way to convert unsigned char a[10][10] to void *? Should I use static_cast or reinterpret_cast or? As 2d-arrays in c++ are allocated consecutively, I think it is reasonable to reinterpret it as pointers.

A: In order to get a void* pointing at a, just take its address (&a) and let the compiler do the implicit conversion to void*:
fread(&a, sizeof a, 1, f);

There are a few caveats/notes:

*

*Firstly, you take the pain to close the file, but you fail to check for read errors.

*Whenever you use reinterpret_cast, the only way to use the result is to reinterpret_cast it back to the exact former type. In general, you don't use reinterpret_cast therefore, unless you need to e.g. store a pointer in an integer. static_cast is the way to go, as others mentioned.

*Never use C-style cast. They are dangerous and they don't document what's going on at all. FWIW, you could const-decorate your array and your code would happily compile and break at runtime, because you overrode the safety-switch of the compiler.

*I wouldn't count on having no padding between the rows of the matrix, i.e. its size wouldn't be just 100. You can only solve that using separate read operations for each row. I'm not sure about this point though, it could well be that its size is guaranteed to not include any padding.

A: The following works in gcc 4.8.2:
FILE *f = fopen("xxx.bin", "rb");
fread(a, sizeof(unsigned char), 10 * 10, f);
fclose(f);

If you prefer explicit casts, then standard way is to use static_cast. It should be used because it preserves address when casting to void*.
FILE *f = fopen("xxx.bin", "rb");
fread(static_cast<void*>(a), sizeof(unsigned char), 10 * 10, f);
fclose(f);

reinterpret_cast only guarantees that if you cast something to void* and then cast back to your type, then you will get the same value.


text:
Q: How do I save an image in a SQL Server Database? I want to save images that are uploaded with httppostedfilebase into a database.
How do I do this? How do I structure the database fields? What code do I write to save it to the database?

A: if(uploadedImage == null || uploadedImage.ContentLength == 0)
{
    // no image
}

var image = new Image();
image.Name = uploadedImage.FileName;
image.ContentType = uploadedImage.ContentType;
int length = uploadedImage.ContentLength;
byte[] buffer = new byte[length];
uploadedImage.InputStream.Read(buffer, 0, length);
image.Data = buffer;

Image class is database entity, so you need Name, ContentType and Data in your database. uploadedImage is HttpPostedFileBase.

A: We use datatype varbinary(max) for storing images and other files in a SQL database.
For an example of how to work with this data type, see: http://msdn.microsoft.com/en-us/library/a1904w6t(VS.80).aspx

A: First of all, storing images in a database is a controversial subject, so make sure to consider whether this is really what you want. For an elaborate discussion see:
Storing Images in DB - Yea or Nay?
The next thing to consider is what technology to use. Will you be using Linq2SQL, NHibernate, Entity Framework or plain ADO.NET? When choosing technology you should take the overall application architecture into account and not just focus on storing images (unless that is all your app does). Once that is settled, check out how the chosen technology handles binary data.
You can get to the binary data through HttpPostedFileBase.InputStream.

A: [HttpPost]
    public ActionResult SaveImage(HttpPostedFileBase image)
    {
       Foo foo=new Foo();
       if (image != null)
            {
                foo.ImageMimeType = image.ContentType;//public string ImageMimeType { get; set; }
                foo.ImageData = new byte[image.ContentLength];//public byte[] ImageData { get; set; }
                image.InputStream.Read(product.ImageData, 0, image.ContentLength);
            }
            fooRepository.Save(foo);
        }
    }


text:
Q: Scanf assigns "junk" values to variavels I tried to write a simple c program that does something with derivatives, but that's not the point of the question:
When I run the program, It asks me to input a bunch of floating point values, but it doesn't matter what I input the scanf function will always assign "junk" values to the variables, here's the code:
double a, b, c, d, x, h;
printf("Please enter the coefficient of X cubed: ");
scanf("%3f", &a);
printf("\nPlease enter the coefficient of X squared: ");
scanf("%3f", &b);
printf("\nPlease enter the coefficient of X: ");
scanf("%3f", &c);
printf("\nPlease enter the free coefficient: ");
scanf("%3f", &d);
printf("\nPlease enter x: ");
scanf("%3f", &x);
printf("\nPlease enter the offset: ");
scanf("%3f", &h);

printf("%.3f %.3f %.3f %.3f %.3f %.3f", a,b,c,d,x,h);

I enter the values for a, b, c, d, x and h, but the printf function shows really weird values - completely different from what I entered.
I googled it in every possible way I thought of, and I can't seem to find the reason it happens.
Can someone try to figure out why it happens?

A: Use lf conversion specifier to read double values and not f conversion specifier which is specifief to read float values. fscanf and fprintf functions are not symmetrical in that respect.

A: You have to use %lf or %g to extract doubles, not %f.


text:
Q: Bunny::NoFinalOctetError after some time without message Using a rabbit mq installed with official docker image my worker fail with the exception Bunny::NoFinalOctetError after some time (around 40s) .
My worker code is :
require 'bunny'
require 'securerandom'

#TODO set host as parameter
rabbit_conn = Bunny.new
rabbit_conn.start

ch   = rabbit_conn.create_channel
q    = ch.queue("task", :durable => true)
ch.prefetch(1)

begin
  q.subscribe(:manual_ack => true, :block => true) do |delivery_info, properties, body|
        pp body
    ch.ack(delivery_info.delivery_tag)
  end
rescue Interrupt => _
  rabbit_conn.close
end

I send data via the following code :
require "bunny"

conn = Bunny.new
conn.start

ch   = conn.create_channel
q    = ch.queue("task", :durable => true)

[
    'titi',
    'toto',
    'tata'
].each do |d|
    q.publish(d, :persistent => true)
end

sleep 1.0
conn.close

and after arround 40s I get the folllowing output in my worker
"titi"
"toto"
"tata"
E, [2017-10-18T15:56:55.938661 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>: Exception in the reader loop: Bunny::NoFinalOctetError: Frame doesn't end with � as it must, which means the size is miscalculated.
E, [2017-10-18T15:56:55.938890 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>: Backtrace:
E, [2017-10-18T15:56:55.939037 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>:     /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/transport.rb:255:in `read_next_frame'
E, [2017-10-18T15:56:55.939114 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>:     /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/reader_loop.rb:68:in `run_once'
E, [2017-10-18T15:56:55.939175 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>:     /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/reader_loop.rb:35:in `block in run_loop'
E, [2017-10-18T15:56:55.939233 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>:     /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/reader_loop.rb:32:in `loop'
E, [2017-10-18T15:56:55.939288 #28583] ERROR -- #<Bunny::Session:0x56182de41e48 guest@127.0.0.1:5672, vhost=/, addresses=[127.0.0.1:5672]>:     /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/reader_loop.rb:32:in `run_loop'
Traceback (most recent call last):
        5: from worker2.rb:21:in `<main>'
        4: from /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/queue.rb:196:in `subscribe'
        3: from /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/consumer_work_pool.rb:77:in `join'
        2: from /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/consumer_work_pool.rb:77:in `each'
        1: from /home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/consumer_work_pool.rb:77:in `block in join'
/home/gg/.rvm/gems/ruby-head/gems/bunny-2.7.1/lib/bunny/consumer_work_pool.rb:77:in `join': caught an unexpected exception in the network loop: Frame doesn't end with � as it must, which means the size is miscalculated. (Bunny::NetworkFailure)

Update about the network
I sniffed the network as it seems to be a malformed network packet. And indeed, the error is trigger after receiving a spécific packet.
Whireshark capture below, the error occur when receiving the packet 299.

Yet I have no idea what this packet is, nor why it is not handled by bunny.
Update Github Ticket
I opened a ticket here

A: Turn out to be an issue on packet parsing.
The bug can be followed her


text:
Q: PDO INNER JOIN returning 0 rows with proof of existing overlap I am querying my database and trying to put together an inner join statement.  For some reason I can get a return value for $query and $query1, but $joinQuery turns up empty.  I'm not getting any errors when I run, so I don't understand how this is happening.
I think I read somewhere that capital letters in tables is an issue, but I have a similar query from another database on the same server which uses capital letters and is working great.(see $workingQuery)
Any ideas?  Please let me know if I should provide more information.
$query1 = $db->prepare("SELECT productName, unitRetailPrice, styleIDs, shippingWeight, styleNumber
                       FROM productImports
                       WHERE styleNumber = 1145") or die("could not display products");
$query = $db->prepare("SELECT productID, description, styleCode, colorID, sizeID, manID, imageFile, availableQuantity
                       FROM products
                       WHERE styleCode = 1145
                       ORDER BY productID $limit") or die("could not display products");

$joinQuery = $db->prepare("SELECT products.productID, products.description, products.styleCode, products.colorID, products.sizeID, products.manID, products.imageFile, products.availableQuantity, productImports.productName, productImports.unitRetailPrice
                           FROM products
                           INNER JOIN productImports ON products.styleCode = productImports.styleNumber
                           ORDER BY productID");

$workingQuery = $db->prepare("SELECT workoutBasket.exID, workoutBasket.setIndex, workoutBasket.setCount, workoutBasket.durationPlan, workoutBasket.repsPlan, workoutBasket.weightPlan, workoutBasket.adaptationID, exercises.exName, exercises.exTypeID
                                FROM workoutBasket
                                INNER JOIN exercises ON workoutBasket.exID = exercises.exID
                                WHERE workoutBasket.workoutID = '$workoutID' ORDER BY exID ASC, setIndex ASC") or die("could not query workoutBasket");


text:
Q: I can't download macOS Sierra I do not have "Install macOS Sierra.app" anywhere on my computer yet when I open the app store the button on macOS Sierra reads "open" instead of download. After I click open, nothing happens. I removed the cache folders of the app store and restart, the problem sticks.

A: after I logged off and logged back in with my Apple account it worked...


text:
Q: How to execute a php file when a cron job is created I want one of my PHP file to be executed when the cron job is executed. I want to do this for updating the database of every users. It is a Banking application project and I need to update every user's account with interest amount. Any other possible approach/suggestion welcomed.

A: Since there is no standard "A cron job has been created" hook, this would be  somewhat non-trivial.
I suppose you could hack cron and run your own custom build of it that would keep a history of the jobs it had seen and run the PHP script if it saw a new one.
Alternatively you could watch for changes to the various files/directories that cron jobs are stored in (e.g. /var/spool/cron/ and /etc/cron.*/) using either Inotify or its equivalent on your OS or a cronjob that looks for changes every few minutes.


text:
Q: Compiling into CommonJS does not produce files usable by NodeJS Given the syntax provided here (standard ES6 modules with import/export), and the files below, the typescript compiler (tsc) builds files which will throw Error: Cannot find module when used with NodeJS.
Here's a stripped down example:

Input files
src/main.ts
import {Example} from 'example';
let e = new Example();

src/example.ts
export class Example {}

Compilation
Note, using the tsc from npm install -g typescript, version 1.5.0-beta, from a windows machine.
tsc --rootDir src --outDir bin

Output files
bin/main.js
var example_1 = require('example');
var e = new example_1.Example();

bin/example.js
var Example = (function () {
    function Example() {
    }
    return Example;
})();
exports.Example = Example;

Am I doing something incorrectly? I expected main.js to include something like require('example.js') instead.

A:
import {Example} from 'example';

You're importing a module here, not a file. Try
import {Example} from './example';


text:
Q: Why does Ctrl + V not paste in Bash (Linux shell)? When I copy something to the clipboard and press Ctrl + V in Bash, nothing happens; However, right clicking and selecting Paste does the job.
Why? Is there any reasonable issue (I'm sure there is) behind this behavior in Linux?

A: Use CtrlShiftV for pasting.
Ctrl with other chars is usually used by the shell for special functions.

A: To me, the simplest way to copy paste in the shell is:
Select the code you want and then past it by clicking the mouse-middle-key

A: In the days of physical terminals, session-wide clipboards did not exist, only few programs supported internal copy/paste – often under the name of "buffers" or "kill rings" – and used various different keystrokes. For example, the bash shell uses CtrlK or CtrlU to "kill" (cut), CtrlY to "yank" (paste); this comes from the emacs editor.
CtrlC almost everywhere in Unix was the "interrupt" key, used to cancel the current program or operation. The CtrlV key often meant "verbatim insert" – that is, insert the following character literally without performing any associated action. For example, a normal Esc switches to command mode in the vi editor, but CtrlV, Esc will insert the ESC character into the document.
The use of CtrlC to copy and CtrlV to paste from session-wide clipboard was introduced by Mac OS in 1983 and Microsoft Windows 3.x in 1990. (Earlier Windows versions (1.x and 2.x), as well as IBM OS/2, only supported the IBM CUA keys CtrlIns to copy and ShiftIns to paste; these shortcuts remain supported by all Windows versions.)
When GUIs with clipboard support finally reached Unix, the Ctrl keypresses were already in use by many terminal programs. In addition, the X graphical interface had somewhat different mechanisms: "selections" and "cut buffers". Even now you can select text in one program and insert it using the middle mouse button, without any explicit copy action.
In short, by the time Xterm and GNOME Terminal were written (I'm guessing you use the latter), CtrlV already had a completely different meaning for many years and could not be changed. In addition, an alternative method of copying text – the "selection" – was already present in X11, so explicit copy/paste action was probably considered not as important as it would be in Windows. This means that different keyboard shortcuts had to be selected – for example, most modern terminal programs, like GNOME Terminal, use CtrlShiftC and CtrlShiftV. (If you use Xterm, the same shortcuts can be added manually using the XTerm*vt100*translations Xresource. Rxvt does not have such an option.)
(Most X11 toolkits also support the CUA "copy" and "paste" keys, which do not conflict with terminal programs. Unfortunately, the implementations are rather inconsistent – CtrlIns copies to the "clipboard" in most programs (GTK, Qt4, but ignored by Xaw); however, ShiftIns pastes from the "primary selection" in most GTK and Qt4 programs, but from "clipboard" in Firefox, and from the now-obsolete cut-buffers in the now-obsolete Xaw.)

All that said, some terminals or consoles (in particular, the Windows 10 console) do support these keys. As the Windows console always had a separate "mark/select" mode, CtrlC now also has two meanings based on context – in regular mode it sends an interrupt, in select mode it copies to clipboard (just like Enter used to).
Meanwhile, Windows command-line tools never really used CtrlV for anything, so it was bound to "paste" without disturbing much anything. Doing the same on Unix-like terminals however would be more problematic.

A: Here's your general-purpose copy paste settings with popular terminals:
gnome-terminal (most popular on Linux)
Copy: CtrlShiftC
Paste: CtrlShiftV
Note: Select-to-copy and middle-click to paste also works, but it uses an alternate clipboard.
PuTTY (most popular terminal in Windows)
Copy: (select with mouse, no keyboard interaction)
Paste: Right-click  (or more reliably: shiftRight-click)
Note: Apps that take mouse input (like vim and links) can steal Right-click -- shiftRight-click will always work in any app.
OSX Terminal
Copy: AppleC
Paste: AppleV
Note: Apps that take mouse control (like vim and links) may override what it means to select text, in which case copy won't work the way you expect it to. In those cases, hold down Control while you drag the mouse to select. Mouse interaction with apps is disabled by default in your terminal settings, so most people won't even know about this.

A: We can use insert keyboard button to do copy and paste(In old keyboards it can be missing)
Copy: CtrlInsert
Paste: CtrlShiftInsert

A: It is a deep rooted tradition that the Ctrl key together with a letter generates ASCII control characters found by subtracting 64 from the upper case letter's ASCII value. This calculation maps Ctrl-A to 1, and so on. For instance Ctrl-I is Tab and Ctrl-J is linefeed.
There is no similar tradition for Ctrl-Shift.  Ctrl-Shift-V is not expected to produce any specific character.
Terminal emulators must support tradition by transparently passing through the Ctrl convention, letting it appear as character input to the programs being operated through that terminal window.  Terminal-based programs map control keys to commands. For example, Bash uses Ctrl-V as a command which means "take the next character literally". This allows you to embed a control character in the command line. If the terminal steals control keys for its own use, such commands become unavailable. So intercepting Ctrl-V for a meta-function is out of the question (at least in a default configuration).
However, terminal emulators are free to intercept Ctrl-Shift-V which isn't expected to generate a character. Ctrl-Shift-V isn't a standard; it's a Gnome Terminal thing (which may be in some other terminals).
On X-based Unix desktops the convention is that no command is needed to copy. You just select the text. And the middle button pastes that text elsewhere. You will find that it works in Xterm, Gnome Terminal and Firefox alike.
Ctrl-V is a Microsoft Windows convention, which is an imitation of Apple-V from the Macintosh.

A: you can also use the middle button an a mouse if you are feeling lazy and select a command from either a text document, script or web or forum. once you've selected the intended command simply move to your terminal and click the middle button on the mouse. I use this method as I use puppy linux which doesnt seem to support the normal behaviour of right click and paste. it does in a file handler window, just not in a terminal window. dont know why but I'm quiet pleased I found out about the middle button method, very handy! ;-)


text:
Q: Displaying the result of an update based on a case statement I would like to show the number of rows updated affected by the following code;
UPDATE [document]
SET CalculatedTime = CASE WHEN DATEPART(hh, PrimaryDate) < 9
                             THEN 'Pre-9AM'
                             ELSE CASE WHEN datepart(hh, PrimaryDate) >= 9 AND datepart(hh, PrimaryDate) <= 18
                                          THEN 'Between 9AM-6AM'
                                          ELSE CASE WHEN datepart(hh, PrimaryDate) > 18
                                                       THEN 'Post-6PM'
                                                       ELSE ''
                                               END
                                  END
                     END

The output should be:
TimeCalculation Count
---------------------
Pre-9AM           10
Between 9AM-6AM  583
Post-6PM           0

Any help is appreciated!

A: First of all there is no need for nested CASE
update [document]
SET CalculatedTime =
       case when DATEPART(hh,PrimaryDate) < 9 then 'Pre-9AM'
            when datepart(hh,PrimaryDate) >= 9
                 AND datepart(hh,PrimaryDate) <= 18 then 'Between 9AM-6AM'
            when datepart(hh,PrimaryDate) > 18 then 'Post-6PM'
            else ''
       end ;

Second if you want count per each case you could use:
SELECT CalculatedTime, COUNT(*)
FROM [document]
GROUP BY CalculatedTime;

It will work because you update entire table.

Using MERGE:
SELECT CalculatedTime, COUNT(*) AS count
FROM (
MERGE [document] trg
USING (SELECT 1 AS c) src
  ON trg.id = trg.id
WHEN MACHED THEN
   UPDATE SET CalculatedTime =
       case when DATEPART(hh,PrimaryDate) < 9 then 'Pre-9AM'
            when datepart(hh,PrimaryDate) >= 9
                 AND datepart(hh,PrimaryDate) <= 18 then 'Between 9AM-6AM'
            when datepart(hh,PrimaryDate) > 18 then 'Post-6PM'
            else ''
       end
OUTPUT $action, inserted.CalculatedTime
) s(action, CalculatedTime)
WHERE action = 'UPDATE'
GROUP BY CalculatedTime

A: You can use UPDATE OUTPUT into a table.
Declare @document table (CalculatedTime varchar(50));

    UPDATE [document]
        SET CalculatedTime =
               Case when DATEPART(hh,PrimaryDate) < 9 then 'Pre-9AM'
                    when datepart(hh,PrimaryDate) >= 9
                         AND datepart(hh,PrimaryDate) <= 18 then 'Between 9AM-6AM'
                    when datepart(hh,PrimaryDate) > 18 then 'Post-6PM'
                    else ''
               End
            OUTPUT INSERTED.CalculatedTime INTO @document

    SELECT CalculatedTime as TimeCalculation, COUNT(*) as Count
        FROM @document
            GROUP BY CalculatedTime;


text:
Q: WP_query paged pagination with excluded category still counts it So im making a custom WP_query loop with paged navigation. I want to show 4 posts per page in a specific category.
This is working fine, except the next_post_link() seems to still count the excluded catoegories when determining to show the link or not. How do i make sure that the post count is excluding the others categories, so that the next link only shows up if there is more then the 4 shown posts in that specific category?.
my code:

        <?php

            $args = array ('post_type' => 'post','category__in' => array( 1 ), 'posts_per_page'=> 4, 'paged' => get_query_var('paged'),);
            $posts_query = new WP_query( $args );
        ?>

        <?php //Starts the news loop ?>
        <?php if ( $posts_query->have_posts() ) : while ( $posts_query->have_posts() ) : $posts_query->the_post(); ?>

                <?php //get the posts featured image in the right size = "featured-image" ?>
                <?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'newsbox-image'); ?>
                <img src="<?php echo $image[0]; ?>" alt="Post image" width="700" height="400" />

<?php the_title(); ?>

<?php the_time('j F, Y'); ?>

                <a class="read-more" href="<?php the_permalink() ?>">

        <?php endwhile; else: endif;?>

        <?php previous_posts_link('Nyere'); ?><?php next_posts_link('Ældre'); ?>

    <?php wp_reset_postdata(); ?>

Any help in understanding this is much appreciated

A: Okay found a solution as soon as i posted this. Typical google-syndrome huh? - i had to pass the WP_query variable to the max_num_pages var in my next_posts_link, so it looks like this:
<?php next_posts_link('Ældre', $posts_query->max_num_pages); ?>

guess same thing goes for the previous_posts_link


text:
Q: How can I access an xpath with a colon in the name? I am trying to access the contents of the path below:
/newsMessage/itemSet/newsItem[2]/contentSet/remoteContent[3]/rtr:altId

However, the path is not being accepted due to the colon, is there any way to escape this character or make the contents of this path accessible.
I have tried using something similar to this:
/*[name()='rtr:altId']

however I'm unsure where I would put this in the CSS and if I have formatted correctly.

A: Try this:
/newsMessage/itemSet/newsItem[2]/contentSet/remoteContent[3]/*[name()="altId"]

or
/newsMessage/itemSet/newsItem[2]/contentSet/remoteContent[3]/*[local-name()="altId"]


text:
Q: How to remove extra parameters from powershell output I have below script to fetch all users in a domain and their group membership. In the output if you see I have group names but they are in the format of CN, i want to format the output and just get group names.
Get-ADUser -Server "dc.domain.com" -Properties * | select-object -property Name,samAccountName,@{N="MemberOf";E={$_.MemberOf -join ","}},@{N="PrimaryGroup";E={$_.PrimaryGroup -join ","}} | export-csv C:\Temp\userdetails.csv

"Name","samAccountName","MemberOf","PrimaryGroup"
 "Administrator","Administrator","CN=Group Policy Creator Owners,CN=Users,DC=SMSNOW,DC=COM,CN=Domain Admins,CN=Users,DC=SMSNOW,DC=COM,CN=Administrators,CN=Builtin,DC=SMSNOW,DC=COM","CN=Domain Users,CN=Users,DC=SMSNOW,DC=COM"

To be clear I want output like
"Name","samAccountName","MemberOf","PrimaryGroup"
"Administrator","Administrator","Group Policy Creator Owners,Users,Domain Admins,Users,Administrators,Builtin,","Domain Users,Users"

Help is very much appreciated!!

A: You do not say what version of PoSH you are on, but is all you want use Groups and members,
Try this...
# Get all AD groups and the members
 ForEach ($GroupName in (Get-ADGroup -Filter *))
 {
 "The AD Group $GroupName.Name members are:"
 Get-ADGroupMember -Identity $GroupName.Name | Select Name
 "`n"
 }

Results...
The AD Group CN=WinRMRemoteWMIUsers__,CN=Users,DC=contoso,DC=com Name members are:

The AD Group CN=Administrators,CN=Builtin,DC=contoso,DC=com Name members are:

Name
----
Domain Admins
Enterprise Admins
Administrator

The AD Group CN=Users,CN=Builtin,DC=contoso,DC=com Name members are:

Name
----
Domain Users
Authenticated Users
INTERACTIVE
Labadmin
...

Depending on you PoSH version you could just use this...
# Get users and their groups memberships
 (Get-ADUser -Filter *) | % {
 "`nThe user " + $_.SamAccountName + ', is in the following AD Groups: '
 Get-ADPrincipalGroupMembership $_.SamAccountName |
 Select Name,GroupCategory,GroupScope } |
 Format-Table -AutoSize

Results ...
The user Administrator, is in the following AD Groups:

Name                                   GroupCategory  GroupScope
----                                   -------------  ----------
Domain Users                                Security      Global
Administrators                              Security DomainLocal
Schema Admins                               Security   Universal
Enterprise Admins                           Security   Universal
Domain Admins                               Security      Global
...

The user Guest, is in the following AD Groups:
Domain Guests                               Security      Global
Guests                                      Security DomainLocal

The user krbtgt, is in the following AD Groups:
Domain Users                                Security      Global
Denied RODC Password Replication Group      Security DomainLocal
...

A: To make the answer short: You can extend your calculated property with a foreach loop to extract each single group name like this:
Get-ADUser -Server "dc.domain.com" -Properties * |
    Select-Object -Property Name,samAccountName,@{Name="MemberOf";Expression={$_.MemberOf | ForEach-Object {Get-ADGroup -Identity $_ | Select-Object -ExpandProperty Name}}},@{Name="PrimaryGroup";Expression={$_.PrimaryGroup -join ","}} |
        Export-Csv  -Path C:\Temp\userdetails.csv