Q:

How to filter array of objects in MongoDB based on query params?

I've got these documents in my collection:
{
    "header": "Immaterielle eiendeler",
    "headerNum": "10",
    "meta": [{
      "content": "FoU skattemessig formue",
      "contentNum": "1000",
      "details": "Denne kontoen brukes til ervervet forskning og utvikling som er balanseført. Hvis dette ikke skal balanseføres, men kostnadføres, opprett en egen kostnadskonto på dette.",
      "tags": ["forskning", "utvikling", "ervervet", "immaterielle eiendeler"]
    }, {
      "content": "FoU ervervet",
      "contentNum": "1001",
      "details": "For ervervet FoU er det lettere å identifisere eiendelen for balanseføring, ettersom kjøpet forutsetter at eiendelen kan overføres fra selger til kjøper.",
      "tags": [""]
    }, {
      "content": "FoU egenutviklet",
      "contentNum": "1005",
      "details": "For at immateriell eiendel \"Forskning og Utvikling\" skal kunne balanseføres, må eiendelen være identifiserbar og kunne skilles fra Goodwill.",
      "tags": [""]
    }]
},
{
    "header": "Tomter, bygninger og annen fast eiendom",
    "headerNum": "11",
    "meta": [{
      "content": "Forretningsbygg (saldogruppe i)",
      "contentNum": "1100",
      "details": "Her bokføres kjøp av bygninger (dvs balanseføres som selskapets eiendel) Byggeningen føres til anskaffelses-/byggekost, og avskrives deretter. Her føres også andre kostnader.",
      "tags": ["tomter", "bygninger", "eiendom", "forretningsbygg"]
    }, {
      "content": "Bygningsmessige anlegg",
      "contentNum": "1120",
      "details": "Her fører du bygg/anlegg som ikke er fast eiendom. Det kan for eksempel være anleggsbrakker, småbåthavn, anlegg for distribusjon av strøm, anlegg for utvinning av sand o.l.",
      "tags": ["brakker", "midlertidig bygg", "bygningsmessige anlegg"]
    }]
  }

At the moment I'm filtering records by header, headerNum, meta.content, meta.contentNum and meta.tags. Below you can see my aggregation pipeline:
const query = req.query.search;
    const accounts = await Account.aggregate([
      {
        $unwind: {
          path: '$meta.tags',
          preserveNullAndEmptyArrays: true
        }
      },
      {
        $match: {
          $or: [
            { header: { $regex: query, $options: 'i' } },
            { headerNum: { $regex: query, $options: 'i' } },
            { 'meta.content': { $regex: query, $options: 'i' } },
            { 'meta.contentNum': { $regex: query, $options: 'i' } },
            { 'meta.tags': { $regex: query, $options: 'i' } }
          ]
        }
      },
      {
        $sort: { headerNum: 1 }
      }
    ]);

What I would like to achieve is to narrow down the number of items in meta array. If req.query.search = 'forskn' I would like to look for this value in meta.content, meta.contentNum, meta.tags and finally receive something like this:
{
    "header": "Immaterielle eiendeler",
    "headerNum": "10",
    "meta": [{
      "content": "FoU skattemessig formue",
      "contentNum": "1000",
      "details": "Denne kontoen brukes til ervervet forskning og utvikling som er balanseført. Hvis dette ikke skal balanseføres, men kostnadføres, opprett en egen kostnadskonto på dette.",
      "tags": ["forskning", "utvikling", "ervervet", "immaterielle eiendeler"]
     }]
}

Do you have any suggestion on how I can achieve it?

A:

Try this code
Account.aggregate([
{
    $unwind: {
      path: '$meta',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $unwind: {
      path: '$meta.tags',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $match: {
      $or: [
        { header: { $regex: query, $options: 'i' } },
        { headerNum: { $regex: query, $options: 'i' } },
        { 'meta.content': { $regex: query, $options: 'i' } },
        { 'meta.contentNum': { $regex: query, $options: 'i' } },
        { 'meta.tags': { $regex: query, $options: 'i' } }
      ]
    }
  },
  {$group:{_id:'$_id', headerNum:{$first:'$headerNum'},header:
  {$first:'$header'},meta:{$addToSet:'$meta'}}},
  {
    $sort: { headerNum: 1 }
  }
 ])


Q:

jQuery trigger event declared in tag with additional data

I have a select with a change event handler:
<select id="mySelect" onchange="changedMySelect">
   <option value="test1">Test1</option>
   <option value="test2">Test2</option>
</select>

and
function changedMySelect(event, myParam1, myParam2) {
   alert(myParam1);
}

I would like to be able to trigger this event (declared in HTML) passing the additional params (myParam1, myParam2).
$("#mySelect").trigger("change", myParamValue1, myParamValue2);

However myParam1 is undefined, just like when the user clicks (which is expected). How to send the myParamValue1?
Ideally I should not move the onchange declared in HTML to Javascript (that is confirmed to work). We need to keep the onchange in the HTML, but we are able to modify it if necessary.

A:

When you use the onchange="something" attribute, the function that is called will only receive what you put in the attribute. It will not get the event or anything else. So putting onchange="changedMySelect(1, 2)" would call your changedMySelect function with the arguments 1 and 2.
In order for it to receive the event and other parameters, you will have handle the event through javascript instead. Also, jQuery's trigger needs the parameters as an array, not as separate parameters:

function changedMySelect(event, myParam1, myParam2) {
   alert(myParam1 + ' ' + myParam2);
}

// You need to do this instead of using onselect in the HTML
$("#mySelect").on("change", changedMySelect);

$("#mySelect").trigger("change", ["param1", "param2"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="mySelect">
   <option value="test1">Test1</option>
   <option value="test2">Test2</option>
</select>


Q:

What is the benefit of a pub directory in Magento 2

Maybe I'm just not getting it but if my files are already cached then what would be the use of a pub directory in Magento 2? My only educated guess would be that the use of the fallback mechanism could be alleviated somewhat by having a known set of files for the theme.
Through reading the docs I don't a clear understanding of the benefit although I feel I have a strong grasp understanding dynamic, static and cached files.
As I understand it the cache is simply a defined known location of assets which led me to guess that the pub directory is a mechanism which standardizes the place of the files to reduce resources being used on the fallback mechanism.

A:

The pub directory is a security measure in order block public access to your root directory assets, namely the app directory. The reason that index.php is also located in the root directory is presumed to address individuals whose webhost make it difficult or impposible to change your webroot.
When utilizing the pub/index.php the app source folder will not be able to be accessed while it could be it be if index.php was being ran from the root directory. This practice is also seen in Symfony and Zend 2.
This way none of the Magento application configurations, templates, etc are exposed.
Generally, knowledge of the architecture in regards to the pub index.php vs root index.php are not needed for frontend developers on a team but understanding its basics are good to know.

A:

Magento 2 comes with two index.php files where one file is inside root
  folder and another one is inside /pub folder. Magento 2 offers to run
  your application using any one of this file. If you choose to run your
  application using /pub/index.php then it is a good decision for
  security point of view as it restrict unauthorized direct access of
  application files.

As side note it's good to keep in mind that the /index.php file is used when running as developer mode and /pub/index.php is used when running as production mode


Q:

Remembering Anime/cartoon from around 10 years ago

Okay so I remember normal looking people.
Then a kid who was really weird looking, Like a completely different art style and drawn badly.
He went on adventures I think
I remember him chasing a bra. (But that scene could be mixed up with something else)
Other than that all I remember is that I watched all of it because I remember the seasons started over on tv. I watched it when I was around 6 and I am now 17.
I think it was cartoon network but I'm not sure or maybe fox kids this was in the Uk by the way.
Thanks in adanced

A:

It could potentially be a match for Ranma 1/2
It has a character named Happosi.  He's a step below "one of the main characters", so even though the show doesn't revolve around him, you'll see him often.
He's also not a child, He's actually really old, But It is possible to mistake him for a child because he's really short and he acts like one too.  He does look poorly drawn when compared with the rest of the characters.
This is what he looks like


Q:

Is there any disadvantage from non-academic job turn to academic job in math

If you get your PhD in math , and then work for 1 or 2 years in a non-academic institution and then turn to apply for postdoc or tenure-track position in math like usual, is there any disadvantage (I mean for your application for postdoc or tenure-track position)?
An appendix: I just want to make sure whether or not I can't or it is difficult to get reference letter, take conference or give talks (in the future) because you are not in academic institution. This is the most important for someone (like me) who will returen to academic job.(but for some reasons he can't now)

A:

My personal opinion is that such a career path can contribute a lot to mathematics, because such candidates can often be informed by a more practical or utilitarian focus in their mathematical research, providing an important and invigorating perspective. For example, for someone to arrive at hard-core mathematical research in financial mathematics after having actually worked in investment banking would be extremely useful. And surely there is a similar situation with many other areas of applied mathematics. In areas tending towards pure mathematics, however, probably it becomes more difficult to make the case that the time spent away from research mathematics was beneficial.
In any case, a person applying for a position from such a situation would naturally have a disadvantage in terms of publications and research accomplishments in comparison with the competing candidates. If the idea were to take a non-academic position with the goal of eventually returning to academic research, therefore, then it would seem advisable to keep up one's research as best as one can. Even a publication or two would be fairly convincing evidence of one's true mathematical nature.
I do know several examples of people who spent a long time away from academic mathematics and then returned to a successful academic career in pure mathematics (even in set theory!). I know of several mathematians who had entire careers in business or computer software before returning to academic research and becoming tenured professors. So indeed it is possible. But surely this is far from usual, and certainly the more typical pattern is that once someone leaves mathematical research, unfortunately, they do not return.

A:

It's indeed possible [I spent many years in industry building math software, and now I'm a tenured prof, albeit in computer science and software engineering department rather than math; although my research involves building mechanized mathematics systems...].  I started my academic career having previously 'published' 0 academic papers!  I was, however, already well-known within the computer algebra community, and my work was known [so I was able to get many good academic reference letters].  The reason for me to report this is that it is important to be able to convince the academic community that you really have something to contribute, else why would they hire you?  So, if you intend to move back to academia, either write papers or make sure that somehow the community 'knows' you and appreciates your work.
From my experience, I would say that the hardest part is to go from having well-defined goals with precise deadlines, often driven by external pressures, to writing research papers with no deadline.  Getting up to speed on producing papers while being on the 'tenure clock' was most unpleasant.  And, of course, at the beginning teaching courses can (and likely will) swallow all available time.  Unless you're in an enlightened department (I wasn't) where untenured faculty are given a lighter teaching load to allow them the time to get settled into their research career.
If at all possible, get a post-doc in between a non-academic job and a tenure-track position.  This will give you the time needed to 'switch gears'.  I probably would not have done that myself (the salary cut was already substantial enough as it is, I didn't want to make it even worse).  It depends on your personal situation.


Q:

Syntax Error in Inline if … else Syntax in Python

What exactly is wrong with the syntax and why in the following piece of code?
I've counted the parentheses among other things yet am unable to figure it out.
c = ""
 print("Yes") if c else print("No")

Note: It gives a Syntax error like the one below:
print("Yes") if c else print("No")
                            ^
SyntaxError: invalid syntax

A:

This happens because the print function behaves differently in python2 and python3:
Meanwhile in python3 your code works perfectly, in python2 it raises an error.
This happens because in python2, print is actually a statement and not a function; here you can find a more in-depth QA on the difference between functions and statements.
By the way, you can solve your problem importing the python3 print function from the future:
from __future__ import print_function

c = ""

print("Yes") if c else print("No")

OUTPUT:
No


Q:

Strange NSNumberFormatter crash

The code is simple:
static NSNumberFormatter *numberFormatter = nil;

if (numberFormatter == nil) {
    numberFormatter = [[NSDateFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
}

However, it crashes on the last line:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSDateFormatter setNumberStyle:]: unrecognized selector sent to instance 0x5c378d0'

How is it possible?

A:

Because you created an NSDateFormatter, not an NSNumberFormatter.


Q:

Mopidy - exception in HttpFrontend

I installed Mopidy on my Raspbian. When I run mopidy, I get this error:
ERROR    Unhandled exception in HttpFrontend (urn:uuid:7dbd4827-d53d-49aa-9d2b-e12e46e7b196):
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pykka/actor.py", line 200, in _actor_loop
    response = self._handle_receive(message)
  File "/usr/lib/python2.7/dist-packages/pykka/actor.py", line 294, in _handle_receive
    return callee(*message['args'], **message['kwargs'])
  File "/usr/lib/python2.7/dist-packages/mopidy/http/actor.py", line 77, in on_event
    on_event(name, **data)
  File "/usr/lib/python2.7/dist-packages/mopidy/http/actor.py", line 84, in on_event
    handlers.WebSocketHandler.broadcast(message)
  File "/usr/lib/python2.7/dist-packages/mopidy/http/handlers.py", line 93, in broadcast
    loop = tornado.ioloop.IOLoop.current()
AttributeError: type object 'IOLoop' has no attribute 'current'

How do I fix this error?

A:

See https://discuss.mopidy.com/t/mopidy-1-0-1-doesnt-emit-events-over-ws-when-using-tornado-2-3/701/4 - short version is we forgot to test against Tornado 2.3 which is ancient.
I just pushed a fix for this which will be in a 1.0.2 bug fix release fairly soon.


Q:

How to use leftmark in LaTeX in memoir class

I am using document class memoir. I want too use \leftmark to display section headings as headers. Can you give a small sample program how to use \leftmark in LaTeX in memoir. I read the manual but did not understand it. Following is the program
\documentclass[a4paper]{memoir}
\addtopsmarks{headings}{}{
  \createmark{section}{both}{shownumber}{}{. \ }
}
\pagestyle{headings}

\begin{document}

\section*{Introduction}

 same moment it is produced. When you flip a switch, the electric power is there. Behind the scenes, state electricity board employees are hard at work operating and maintaining the comwhich I have learnt at GNDTP 1 in this report. Additional help has been taken from internet which has

\end{document}

A:

As I said it is easy. Please do not make us do your work for you. At least post a minimal example of what you have tried.
\documentclass[a4paper]{memoir}
\addtopsmarks{headings}{}{
  \createmark{section}{both}{shownumber}{}{. \ }
}
\pagestyle{headings}
\usepackage{kantlipsum} % provides sample text
\begin{document}

\section{Test}

\kant

\end{document}


Q:

Servicio AngularJS me devuelve Undefined en return!

He intentado todas las maneras posible de cambiar el orden del código, pero pasa lo mismo una y otra vez, me estoy frustrando, quisiera saber porque devuelve undefined para no volver a toparme con este problema, He realizado las pruebas para saber que la siguiente función no regresa vacía, pero aun así lo hace. Demuestro mi código a continuación:
A continuación defino la aplicación:
var app = angular.module('sonidoambiental', ['ngRoute']).
        config(['$routeProvider', function($routeProvider) {
                $routeProvider.when('/', { templateUrl: 'inicio.html', abstract: true, controller: "InicioController"}).
                when('/listado', {templateUrl: 'listado.html', controller: "ListadoController"})./*
      when('/agregar', {templateUrl: 'plantillas/agregar.html', controller: ControladorAgregar}).*/
        otherwise({redirectTo: '/'});
    }]);

El servicio que me devuelve undefinited es el siguiente:
app.factory('comunicacion', function() {
        return {
        obtenerstring: function(pregunta){
            var retorna;
            $.ajax({
                url: '/json/' + encodeURI(pregunta),
                dataType: 'json',
                method: 'get',
                success: function(datos) {
                    /* Si todo ha ido bien mostramos una alerta con el contenido */
                    if (typeof datos.error !== 'undefined' && datos.error === false) {
                        console.log(datos.mensaje);
                        retorna= datos.mensaje;
                        //alert("Mensaje recibido: " + datos.mensaje);
                    } else {
                        retorna = null;
                    }
                }
            });
            return retorna;
        }
        }
    });

Y la llamo de la siguiente forma:
app.controller("InicioController",['$scope', 'comunicacion',function ($scope, $interval, comunicacion) {
    $scope.primerinicio=function(){
        if (comunicacion.obtenerstring('sinusuarios') === ' ') {
            titulodeformulario = "No hay usuario creado por favor ingrese los datos correspondientes";
                        crearusuario = true;
                        botoningresar = "Crear usuario";
                        $scope.titulodeformulario = titulodeformulario;
                        $scope.botoningresar = botoningresar;
                        $scope.crearusuario = crearusuario;
                        $scope.$apply();
        }
Pues si alguien me aclara este panorama seria de muy grata ayuda, En la parte que dice Console.log(datos.mensaje); me devuelve el valor real y no undefinited, por tanto aseguro que no es un problema de función.

A:

El problema radica en la implementación del factory.
app.factory('comunicacion', function() {
    return {
    obtenerstring: function(pregunta){
        var retorna;
        $.ajax({
            url: '/json/' + encodeURI(pregunta),
            dataType: 'json',
            method: 'get',
            success: function(datos) {
                /* Si todo ha ido bien mostramos una alerta con el contenido */
                if (typeof datos.error !== 'undefined' && datos.error === false) {
                    console.log(datos.mensaje);
                    retorna= datos.mensaje;
                    //alert("Mensaje recibido: " + datos.mensaje);
                } else {
                    retorna = null;
                }
            }
        });
        return retorna;
    }
    }
});

Tienes una declaración de variable
var retorna;

Luego una invocación a un metodo jQuery asincrono.
$.ajax(...)

Para finalmente retornar la variable declarada anteriormente
return retorna;

Lo anterior solo funcionaria si la invocación fuera sincrona. Pero mas importante aun, deberías usar componentes angular como el servicio $http y retornar una promesa como resultado.
Docs del servicio:  https://docs.angularjs.org/api/ng/service/$http


Q:

XML parsing error remedy

during parsing an XML file, i am facing parsing error like [Fatal Error] :293:24: Invalid byte 2 of 2-byte UTF-8 sequence. My XML sample contains some characters like xc3, which is a single character (I mean by pressing delete button once xc3 character deletes at a time. (I tried to paste this character here but this editor is showing other character).
<?xml version="1.0" encoding="utf-8"?>
<issue-info>
<issue-meta>
<date>January 24, 2013</date>
<from>Chris Burton, John Wiley & Sons, Ltd.</from>
<journal>Greenhouse Gases: Science and Technology</journal>
<typesetter>Anju Upadhaya</typesetter>
<volume>3</volume>
<issue>1</issue>
<printer>Markono,</printer>
<cover-date>February 2013</cover-date>
<online-issn>2152-3878</online-issn>
<print-issn>2152-3878</print-issn>
<total-pages>FM – 4; TEXT – 95; EM – 1: TOTAL = 100</total-pages>
<spl-instruction></spl-instruction>
</issue-meta>
<issue-item>
<seq>1</seq>
<ed-ref>OFC</ed-ref>
<aid></aid>
<author></author>
<description>Update from GHG 2_1 cover</description>
<start-page>1</start-page>
<end-page>1</end-page>
<artty></artty>
<category>OFC (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>2</seq>
<ed-ref>IFC</ed-ref>
<aid></aid>
<author>49379Ůpdf</author>
<description>New GHG colour ADVERT</description>
<start-page>2</start-page>
<end-page>2</end-page>
<artty></artty>
<category>IFC (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>3</seq>
<ed-ref>FM1</ed-ref>
<aid></aid>
<author></author>
<description>Table of Contents</description>
<start-page>1</start-page>
<end-page>1</end-page>
<artty></artty>
<category>TOC (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>4</seq>
<ed-ref>FM2</ed-ref>
<aid></aid>
<author></author>
<description>Editorial Board</description>
<start-page>2</start-page>
<end-page>2</end-page>
<artty></artty>
<category>Editorial Board (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>5</seq>
<ed-ref>FM3</ed-ref>
<aid></aid>
<author></author>
<description>Aims and Scope</description>
<start-page>3</start-page>
<end-page>3</end-page>
<artty></artty>
<category>Aims and Scope (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>6</seq>
<ed-ref>FM4</ed-ref>
<aid></aid>
<author></author>
<description>Information Page</description>
<start-page>4</start-page>
<end-page>4</end-page>
<artty></artty>
<category>Information Page (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>7</seq>
<ed-ref></ed-ref>
<aid>GHG1333</aid>
<author>PROD ED</author>
<description></description>
<start-page>1</start-page>
<end-page>2</end-page>
<artty>ED</artty>
<category>Editorial (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>8</seq>
<ed-ref></ed-ref>
<aid>GHG1334</aid>
<author>PROD ED</author>
<description></description>
<start-page>3</start-page>
<end-page>4</end-page>
<artty>XX</artty>
<category>60 Second Interview (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>9</seq>
<ed-ref></ed-ref>
<aid>GHG1335</aid>
<author></author>
<description></description>
<start-page>5</start-page>
<end-page>7</end-page>
<artty>XX</artty>
<category>Feature (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>10</seq>
<ed-ref>GHG-12-0029.R2</ed-ref>
<aid>GHG1313</aid>
<author>PAN, CLODIC, TOUBASSY</author>
<description></description>
<start-page>8</start-page>
<end-page>20</end-page>
<artty>XX</artty>
<category>In the Field (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online>03 Jan 2013</pub-online>
</issue-item>
<issue-item>
<seq>11</seq>
<ed-ref>GHG-12-0023.R1</ed-ref>
<aid>GHG1298</aid>
<author>Peterson, O'Byrne, Endres, Peterson</author>
<description></description>
<start-page>21</start-page>
<end-page>29</end-page>
<artty>XX</artty>
<category>Spotlight (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online>14 Sep 2012</pub-online>
</issue-item>
<issue-item>
<seq>12</seq>
<ed-ref>GHG-12-0033.R2</ed-ref>
<aid>GHG1321</aid>
<author>Begag, Krutka, Dong, Mihalcik, Rhine, Gould, Baldic, Nahass</author>
<description></description>
<start-page>30</start-page>
<end-page>39</end-page>
<artty>XX</artty>
<category>Spotlight (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>13</seq>
<ed-ref>GHG-12-0036.R1</ed-ref>
<aid>GHG1331</aid>
<author>Cunningham, Lauchnor, Eldring, Esposito, Mitchell, Gerlach, Phillips, Ebigbo, Spangler</author>
<description></description>
<start-page>40</start-page>
<end-page>49</end-page>
<artty>XX</artty>
<category>Spotlight (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>14</seq>
<ed-ref>GHG-12-0034.R1</ed-ref>
<aid>GHG1328</aid>
<author>Elliot, Buscheck, Celia</author>
<description></description>
<start-page>50</start-page>
<end-page>65</end-page>
<artty>XX</artty>
<category>Modeling and Analysis (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>15</seq>
<ed-ref>GHG-12-0021.R1</ed-ref>
<aid>GHG1318</aid>
<author>Mazzoldi, Picard, Sriram, Oldenburg</author>
<description></description>
<start-page>66</start-page>
<end-page>83</end-page>
<artty>XX</artty>
<category>Modeling and Analysis (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online>03 Jan 2013</pub-online>
</issue-item>
<issue-item>
<seq>16</seq>
<ed-ref>GHG-12-0031.R1</ed-ref>
<aid>GHG1308</aid>
<author>Eccles, Pratson</author>
<description></description>
<start-page>84</start-page>
<end-page>95</end-page>
<artty>XX</artty>
<category>Modeling and Analysis (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online>26 Oct 2012</pub-online>
</issue-item>
<issue-item>
<seq>17</seq>
<ed-ref>EM1</ed-ref>
<aid></aid>
<author>Join the SCI</author>
<description>NEW COLOUR ADVERT</description>
<start-page></start-page>
<end-page></end-page>
<artty></artty>
<category>Society Ad (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>18</seq>
<ed-ref>IBC</ed-ref>
<aid></aid>
<author>ONLINE OPEN</author>
<description>COLOUR ADVERT</description>
<start-page>1</start-page>
<end-page>1</end-page>
<artty></artty>
<category>IBC (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
<issue-item>
<seq>19</seq>
<ed-ref>OBC</ed-ref>
<aid></aid>
<author>CCUS</author>
<description>NEW COLOUR ADVERT</description>
<start-page>2</start-page>
<end-page>2</end-page>
<artty></artty>
<category>OBC (GHG)</category>
<toc-category></toc-category>
<reprint></reprint>
<color>N</color>
<color-charge>0</color-charge>
<pub-online></pub-online>
</issue-item>
</issue-info>

My Java code for parsing is here below.
       DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setCoalescing(false);
        docBuilderFactory.setXIncludeAware(false);
        docBuilderFactory.setNamespaceAware(false);
        docBuilderFactory.setIgnoringComments(true);
        docBuilderFactory.setExpandEntityReferences(false);

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(rtfXmlIS);
        doc.getDocumentElement().normalize();

How to get rid of such kind of error ([Fatal Error] :16:45: Invalid byte 1 of 1-byte UTF-8 sequence., [Fatal Error] :14:24: The entity "ndash" was referenced, but not declared.)?

A:

That's two different errors.
The first is because the input is not UTF-8.  You will need to decode the input correctly before passing it to the parser.
The second is probably because the input is XHTML and not XML.  If you want to use an XML parser with this input and resolve entities like – you will need to provide a DTD that defines it and any others contained in the input.


Q:

XQuery to display two elements data at a time?

below is the xml file -
<Countries>
  <Country>
    <Name>India</Name>
    <Capital>New Delhi</Capital>
  </Country>
  <Country>
    <Name>USA</Name>
    <Capital>Washington DC</Capital>
  </Country>
  <Country>
    <Name>England</Name>
    <Capital>London</Capital>
  </Country>
  <Country>
    <Name>Japan</Name>
    <Capital>Tokyo</Capital>
  </Country>
  <Country>
    <Name>Srilanka</Name>
    <Capital>Colombo</Capital>
  </Country>
</Countries>

I have stored it in BaseX, an XMLDB. Now like plain DBs if I had stored there, I would have written simple select statement to retrieve the data from table. For example:
select name, capital from country

and got both the rows. Right? How can this be done using XQuery?

A:

If you are expecting the output without elements then try this one
for $x in doc("Country")/Countries/Country
  return string-join( ($x/Name, $x/Capital), " - ")

The output will be -
`India - New Delhi USA - Washington DC England - London Japan - Tokyo Srilanka - Colombo`

If you want them on separate lines then, this is what you will have to use -
for $x in doc("Country")/Countries/Country
  return <li>{string-join( ($x/Name, $x/Capital), " - ")}</li>

Instead of <li> you can use any other relevant tag.


Q:

boost thread worker object re-use after thread has finished

I have a simple thread object which takes care of some execution (a worker):
In the simplest form, an object is created for every single thread:
class worker
{
public:

    worker  (
              boost::atomic<int> & threads,
              boost::mutex & mutex,
              boost::condition_variable & condition
            )
    : threads__(threads), mutex__(mutex), condition__(condition)
    {}

    void run (
                 // some params
             )
    {
        // ... do the threaded work here
        // finally, decrease number of running threads and notify
        boost::mutex::scoped_lock lock(mutex__);
        threads__--;
        condition__.notify_one();
    }

private:
    boost::atomic<int> & threads__;
    boost::mutex & mutex__;
    boost::condition_variable & condition__;
};

The way I use it is within a loop which runs maximum 8 concurrent threads, and waits to be notified if one has finished, in order to spawn the next one:
boost::thread_group thread_group;
boost::mutex mutex;
boost::condition_variable condition;
boost::atomic<int> threads(0);

// Some loop which can be parallelised
for ( const auto & x : list )
{
    // wait if thread_count exceeds 8 threads
    boost::mutex::scoped_lock lock(mutex);
    while ( threads >= 8 )
         condition.wait( lock );

    // Create worker object
    worker _wrk_( threads, mutex, condition );

    boost::thread * thread = new boost::thread( &worker::run, &_wrk_, /* other params */ );
    thread_group.add_thread( thread );
    threads++;
}

This works for most of my scenarios, but now I have a thread object which I need to re-use.
The reason is simple: This tread object contains thrust::device_vector<float> which are expensive to (re)allocate when the object is removed.
Furthermore, those vectors can be re-used as most of their contents won't be changed.
Therefore, I am looking for a mechanism which could re-use the objects created within the loop - in fact, I will allocate 8 of those objects (or as many as my concurrent threads) before hand, and then use them over and over again.
What I am hoping can be done, is something such as this:
boost::thread_group thread_group;
boost::mutex mutex;
boost::condition_variable condition;
boost::atomic<int> threads(0);

// our worker objects to be reused
std::vector<std::shared_ptr<worker>>workers(8,std::make_shared<worker>(threads,mutex,condition));

// Some loop which can be parallelised
for ( const auto & x : list )
{
    // wait if thread_count exceeds 8 threads
    boost::mutex::scoped_lock lock(mutex);
    while ( threads >= 8 )
         condition.wait( lock );

    // get next available thread object from the vector
    auto _wrk_ = std::find_if(workers.begin(), workers.end(), is_available() );

    // if we have less than 8 threads but no available thread object
    if ( _wrk_ == workers.end() ) throw std::runtime_error ("...");

    // Use the first available worker object for this thread
    boost::thread * thread = new boost::thread(&worker::run, &(*_wrk_));
    thread_group.add_thread( thread );
    threads++;
}

I don't know how to signal the is_available(), other than implementing it as a class method (of the worker class).
Second, this appears to me to be too complex for no reason, I'm sure there has to be some kind of other pattern I can use which is more simple and/or elegant.

A:

a very simple way to implement a thread pool is to use boost::asio.
Complete example here, including two types of task (function and object) plus exception handling:
#include <iostream>
#include <vector>
#include <thread>
#include <string>
#include <chrono>
#include <random>
#include <condition_variable>
#include <boost/asio.hpp>

void emit(const char* txt, int index)
{
    static std::mutex m;
    std::lock_guard<std::mutex> guard { m };
    std::cout << txt << ' ' << index << std::endl;
}

struct worker_pool
{
    boost::asio::io_service _io_service;
    boost::asio::io_service::work _work { _io_service };

    std::vector<std::thread> _threads;

    std::condition_variable _cv;
    std::mutex _cvm;
    size_t _tasks = 0;

    void start()
    {
        for (int i = 0 ; i < 8 ; ++i) {
            _threads.emplace_back(std::bind(&worker_pool::thread_proc, this));
        }
    }

    void wait()
    {
        std::unique_lock<std::mutex> lock(_cvm);
        _cv.wait(lock, [this] { return _tasks == 0; });
    }

    void stop()
    {
        wait();
        _io_service.stop();
        for (auto& t : _threads) {
            if (t.joinable())
                t.join();
        }
        _threads.clear();

    }

    void thread_proc()
    {
        while (!_io_service.stopped())
        {
            try {
                _io_service.run();
            }
            catch(const std::exception& e)
            {
                emit(e.what(), -1);
            }
        }
    }

    void reduce() {

        std::unique_lock<std::mutex> lock(_cvm);
        if (--_tasks == 0) {
            lock.unlock();
            _cv.notify_all();
        }
    }

    template<class F>
    void submit(F&& f)
    {
        std::unique_lock<std::mutex> lock(_cvm);
        ++ _tasks;
        lock.unlock();
        _io_service.post([this, f = std::forward<F>(f)]
                         {
                             try {
                                 f();
                             }
                             catch(...)
                             {
                                 reduce();
                                 throw;
                             }
                             reduce();
                         });

    }
};

void do_some_work(int index, std::chrono::milliseconds delay)
{
    emit("starting work item ", index);
    std::this_thread::sleep_for(delay);
    emit("ending work item ", index);
}

struct some_other_work
{
    some_other_work(int index, std::chrono::milliseconds delay)
    : _index(index)
    , _delay(delay)
    {}

    void operator()() const {

        emit("starting some other work ", _index);

        if (!(_index % 7)) {
            emit("uh oh! ", _index);
            using namespace std::string_literals;
            throw std::runtime_error("uh oh thrown in "s + std::to_string(_index));
        }

        emit("ending some other work ", _index);
    }

    int _index;
    std::chrono::milliseconds _delay;
};

auto main() -> int
{
    worker_pool pool;
    pool.start();

    std::random_device rd;
    std::default_random_engine eng(rd());

    std::uniform_int_distribution<int> dist(50, 200);
    for (int i = 0 ; i < 1000 ; ++i) {
        std::chrono::milliseconds delay(dist(eng));
        pool.submit(std::bind(do_some_work, i, delay));
        pool.submit(some_other_work(i, delay));
    }

    pool.wait();
    pool.stop();

    return 0;
}

example output:
starting work item  0
starting some other work  0
starting work item  1
starting some other work  1
starting work item  2
starting some other work  2
starting work item  3
starting some other work  3
uh oh!  0
ending some other work  1
ending some other work  2
ending some other work  3
starting work item  4
uh oh thrown in 0 -1
starting some other work  4
starting work item  5
ending some other work  4
starting some other work  5
starting work item  6
ending some other work  5
starting some other work  6
ending some other work  6
starting work item  7
ending work item  0
starting some other work  7
uh oh!  7
uh oh thrown in 7 -1
starting work item  8
ending work item  1
starting some other work  8
ending some other work  8
starting work item  9
ending work item  5
starting some other work  9
ending some other work  9
starting work item  10
ending work item  7
starting some other work  10
ending some other work  10
starting work item  11
ending work item  4
starting some other work  11
ending some other work  11
starting work item  12
ending work item  3
starting some other work  12
ending some other work  12
starting work item  13
ending work item  10
ending work item  6
starting some other work  13
starting work item  14
ending some other work  13
starting some other work  14
uh oh!  14
uh oh thrown in 14 -1
...


Q:

iPhone Application crashes

When I do the following my application crashes and I get an error (terminate called after throwing an instance of 'NSException') whenever i run the simulation:
for (...)
    [Array1 replaceObjectAtIndex:i withObject: [NSString stringWithFormat:@" Trip %i",i+1]]

OK after writing the problem I have found that the error is "0 is beyond bounds for empty array".

A:

You really really really need to post the type of exception and your code to give us a reasonable chance of solving your problem.  However, I'm going to taker a shot at it anyway.
My guess is your code looks something like this:
Array1 = [[NSMutableArray alloc] initWithCapacity: someNumber];

for (i = 0 ; i < someNumber ; ++i)
{
    [Array1 replaceObjectAtIndex:i withObject: [NSString stringWithFormat:@" Trip %i",i+1]];
}

All arrays start out with 0 objects in them even if you use -initWithCapacity:.  That method only provides a hint to the runtime that the array will grow to the specified size at some point.    You need to use -addObject:.
Edit
Yep, from your edit, I'm sure I am right.  The array has started out empty and you are trying to replace the object at index 0 which isn't there yet.
The code above should be changed as follows:
array1 = [[NSMutableArray alloc] initWithCapacity: someNumber]; // fixed naming convention too :-)

for (i = 0 ; i < someNumber ; ++i)
{
    [array1 addObject: [NSString stringWithFormat:@" Trip %i",i+1]];
}

-addObject: adds the new objects to the end of the array.
If you want something that looks more like a C or Java array, you can prefill the array with NSNull objects
array1 = [[NSMutableArray alloc] initWithCapacity: 6]; // fixed naming convention too :-)

for (i = 0 ; i < 6 ; ++i)
{
    [array1 addObject: [NSNull null]];
}

// Now the following will work
[array1 replaceObjectAtIndex: 4 withObject: @"foo"];


Q:

Android read text file from asset folder using C (ndk)

I need to read text file from asset folder in android, by searching through internet I found that there is asset_manager api available from android 2.3 onwards. As I am targeting only tablet devices this is useful. But as I am not expert in C language I am not able to find any example on how to read/write files using file descriptor. I found many examples using FILE* (file pointers)

My goal is to decrypt a js file from asset folder which is encrypted
  using C (for securing the code), as js code is visible if end user
  decompiled my apk. Because asset folder is inside zip file is it possible to do?

A:

Here is the code I used to read file from android assets folder using asset_manager ndk lib
    AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
    AAsset* asset = AAssetManager_open(mgr, (const char *) js, AASSET_MODE_UNKNOWN);
    if (NULL == asset) {
        __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, "_ASSET_NOT_FOUND_");
        return JNI_FALSE;
    }
    long size = AAsset_getLength(asset);
    char* buffer = (char*) malloc (sizeof(char)*size);
    AAsset_read (asset,buffer,size);
    __android_log_print(ANDROID_LOG_ERROR, NF_LOG_TAG, buffer);
    AAsset_close(asset);

Added following line to my Android.mk
# for native asset manager
LOCAL_LDLIBS    += -landroid

And don't forget the include in source file
#include <android/asset_manager.h>


Q:

How should I store this information I am getting from a file?

Currently I am looking at a file which has information in this format:
header:
  seq: 313
  stamp:
    secs: 1488279773
    nsecs: 788520137
  frame_id: ardrone_base_link
batteryPercent: 58.0
state: 2
magX: 74
magY: -32
magZ: 42
pressure: 90927
temp: 427
wind_speed: 0.0
wind_angle: 0.0
wind_comp_angle: 0.0
rotX: 1.34500002861
rotY: -2.72399997711
rotZ: -4.82999992371
altd: 0
vx: -1.59770445708e-40
vy: -3.68179961114e-40
vz: -0.0
ax: 0.0632314383984
ay: 0.0111897774041
az: 0.982218265533
motor1: 0
motor2: 0
motor3: 0
motor4: 0
tags_count: 0
tags_type: []
tags_xc: []
tags_yc: []
tags_width: []
tags_height: []
tags_orientation: []
tags_distance: []
tm: 590774784.0

Now as you can see, there are multiple sections, with the header seq clearly being an identifier here that can possibly be used in an stl::multimap. However as you can see, I want all the information to be stored, including a way to understand that secs is a subsection of stamp which in turn is a subsection of header. Also, the information I get would vary a fair bit, so I cannot make a struct which would handle this information.
How would I go about this?

A:

Yes. It looks like YAML. For sure.
If you need a private object - you can create something like that:
enum objType {
  OBJ_STRING,
  OBJ_VECTOR,
  OBJ_MAP
}

class DataObj {
public:
   DataObj(const string&, const string&); // Creates object with single name-value data
   DataObj(DataObj *); // Creates object of vector type
   DataObj(const string&, DataObj *); // Created object of map type
   void setObjectKey(const string&);
   void setObjectType(objType);
   void addObject(DataObj *);
   ...
private:
   objType e_type;
   string objData;
   string objKey;
   vector<DataObj *> objVector;
   map<string,DataObj*> objMap;
}

So, you can always change data object from string to vector and then - to map upon file parsing. And then recursively get data until you reach single level string object data.


Q:

Varnish custom html based on User Agent

I want to display different html styles to users based on $_SERVER['HTTP_USER_AGENT']. How can I achieve this with varnish settings, to make it have a specific cache for a specific user agent.
I know I can achieve something similar with JS, but that's not reliable for me I want to do it server side.
The php I will use in my html to detect user agents will look like this;
<?php if($_SERVER['HTTP_USER_AGENT'] == $target):?>
    <style>
      //CSS
    </style>
    <?php endif;?>

How can I setup Varnish so it work neatly with this?

A:

All you need to do is modify the vcl_hash method to add more info to the cache key.
https://varnish-cache.org/docs/trunk/users-guide/vcl-hashing.html
sub vcl_hash {
    hash_data(req.http.User-Agent);
}

Be aware that there are no real standards that are followed for User Agent strings, so the variations are huge even for what are identical browsers. I would expect a 99% cache miss on this technique unless you will be controlling the User Agents yourself (internal system etc.)
If you want a different cache for mobile devices, the following might be more successful as it tries to detect a mobile browser, then uses a normalised cache key value to improve hit rate:
sub vcl_hash {
  if (req.http.User-Agent ~ "mobile") {
    // hash_data
    hash_data("mobile");
  }
}


Q:

More pythonic way to manage a list of callbacks

I'm writing a multi-threaded Python application with serial IO, and I have this construct in the IO class:
def __init__(self):
    # Register these with thread-safe functions having the arguments listed
    self.callbacks_status = [] # args: (pod_index, message, color)
    self.callbacks_conn   = [] # args: (pod_index, message, color)
    self.callbacks_angle  = [] # args: (pod_index, angle_deg)
    self.callbacks_brake  = [] # args: (brake_on)

Then, when one of my updating threads gets a new status, I'm doing something like this every time:
        for func in self.callbacks_conn:
            func(i, "Open", "yellow")

Needless to say, this is ugly and feels non-pythonic. Is there a more elegant way to call a list of functions with the same arguments? Basically I am looking for the map function in reverse.

A:

You might encapsulate this in a special list with the additional method 'fire', so you can just 'fire' the callback list with some args:
class CallbackList(list):
     def fire(self, *args, **kwargs):
         for listener in self:
             listener(*args, **kwargs)

Then, you manage things like this:
def __init__(self):
    self.callbacks_status = CallbackList()
    self.callbacks_conn = CallbackList()
    self.callbacks_angle = CallbackList()
    self.callbacks_brake = CallbackList()

to fire the callback, you'd do:
self.callbacks_conn.fire(i, "Open", "yellow")

Example usage:
>>> def print_double(x):
...     print "%s doubled is %s" % (x, x * 2)
>>> def print_square(x):
...     print "%s squared is %s" % (x, x * x)
>>> cb = CallbackList()
>>> cb.append(print_double)
>>> cb.append(print_square)
>>> cb.fire(8)
8 doubled is 16
8 squared is 64


Q:

How do i convert from map[string] MyStruct to map[string] MyInterface

How do i convert from map[string] MyStruct to map[string] MyInterface, when MyStruct implements MyInterface.
type MyInterface interface {
    Say() string
}

var MyInterfaceMap map[string] MyInterface

type MyStruct struct{
    Message string
}

func (myStruct *MyStruct) Say() string{
    return myStruct.Message
}

func Init() {
    data := []byte(`{"greet":{"Message":"Hello"}}`)
    myStructMap := make(map[string] MyStruct )
    _ = json.Unmarshal( data, &myStructMap)
    MyInterfaceMap = myStructMap
}

A:

Once unmarshalled, copy the map to MyInterfaceMap like below
package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type MyInterface interface {
    Say() string
}

var MyInterfaceMap map[string]MyInterface

type MyStruct struct {
    Message string
}

func (myStruct *MyStruct) Say() string {
    return myStruct.Message
}

func main() {
    data := []byte(`{"greet":{"Message":"Hello"}}`)
    myStructMap := make(map[string]MyStruct)
    err := json.Unmarshal(data, &myStructMap)
    if err != nil {
        panic(err)
    }

    MyInterfaceMap = make(map[string]MyInterface)
    for k, v := range myStructMap {
        MyInterfaceMap[k] = &v
    }
    fmt.Println(reflect.TypeOf(MyInterfaceMap))
    fmt.Println(MyInterfaceMap)
}

And the result would be
map[string]main.MyInterface
map[greet:0x1050c1a0]


Q:

Unable to print the contents of an ArrayList of ArrayLists to a file

I am trying to print the contents of an ArrayList which contains ArrayLists of integers to a CSV file. The code shows the method I use, which received a PrintWriter. Neither the commented out code nor the executable code work. After the program runs, I open the CSV file to find it is empty. I have tested to make sure the ArrayList has contents in it by printing to the console. It does. Not sure what's going wrong here!
static void printCountTrackerFile(PrintWriter out_2) {

//      for(int i =0; i <bustByCount.size(); i++) {
//          out_2.print(bustByCount.get(i) + "\n");
//      }

    for (ArrayList<Integer> each : bustByCount) {
        for(Integer r : each) {
            out_2.print(r + ",");
        }

        out_2.print("last" + "\n");
    }
}

A:

You probably need to call out_2.flush(); so it clears the buffer and writes to the file.


Q:

Another of $\frac{1^2}{1^2}+\frac{1-2^2+3^2-4^2}{1+2^2+3^2+4^2}+\cdots=\frac{\pi}{4}$ type expressable in cube?

Gregory and Leibniz formula
(1)
$$-\sum_{m=1}^{\infty}\frac{(-1)^m}{2m-1}=\frac{\pi}{4}$$
We found another series equivalent to (1)
This is expressed in term of square numbers
$$-\sum_{m}^{\infty}\frac{\sum_{n=1}^{3m-2}(-1)^nn^2
}{\sum_{n=1}^{3m-2}(+1)^nn^2}=\frac{\pi}{4}$$
$$\frac{1^2}{1^2}+\frac{1-2^2+3^2-4^2}{1+2^2+3^2+4^2}+\frac{1-2^2+3^2-4^2+5^2-6^2+7^2}{1^2+2^2+3^2+4^2+5^2+6^2+7^2}+\cdots=\frac{\pi}{4}$$
Is there another series equivalent to (1) but expressable in term of cube numbers?

A:

A proof of mahdi's result:
$$ \sum_{k=1}^{n}k^3 = \frac{n^2(n+1)^2}{4}\tag{1}$$
$$ \sum_{k=1}^{2n}(-1)^{k+1} k^3 = -n^2(4n+3),\qquad \sum_{k=1}^{2n-1}(-1)^{k+1} k^3 = n^2(4n-3)\tag{2}$$
lead to:
$$\begin{eqnarray*}\sum_{n\geq 1}\frac{1^3-2^3+\ldots}{1^3+2^3+\ldots+n^3} &=& \sum_{m\geq 1}\frac{-(4m+3)}{(2m+1)^2}+\sum_{m\geq 1}\frac{(4m-3)}{(2m-1)^2}\\&=&3+\sum_{m\geq 1}\frac{(4m-3)-(4m-1)}{(2n-1)^2}\\&=&3-2\sum_{m\geq 1}\frac{1}{(2n-1)^2}=\color{red}{3-\frac{\pi^2}{4}}.\tag{3}\end{eqnarray*}$$


Q:

How to start java process if it die from script

I have bash script to start java process using below command:
#!/bin/bash
java -jar test.jar

I want to make a script so that if the java process of this jar die it will start again from this script. Do i need a do while loop in my script and what condition should i use to check that is java process of this jar is running or not and if die then fire it up again.

A:

The following will run until test.jar exits with 0 as exit code
while ! java -jar test.jar; do :; done

Breakdown:
while ! java -jar test.jar; do :; done
#     ^ ^                      ^
#     | |                      while loops needs a body, and `:` will do nothing
#     | The command to run, while will check the exit code and continue if its 0 (true)
#     Flip the exit code, so true becomes false and false becomes true

If you are interested to run until test.jar exits will falsy exit code, you can omit the !:
while java -jar test.jar; do :; done


Q:

Como usar LIKE com OR no Oracle?

Tenho a seguinte tabela:
CREATE TABLE DEPENDENTE
(
  IdDependente        number(6),
  Matricula           number(6),
  Nome                char(50) NOT NULL,
  dtNascimento        date,

  constraint pk_IdDependente PRIMARY KEY(IdDependente),
  constraint fk_DEPENDENTE foreign key(Matricula) references FUNCIONARIO(Matricula)
);

Com os INSERTS :
INSERT INTO DEPENDENTE VALUES(1, 1010, 'Francisca', to_date('01/03/1978', 'dd/mm/yyyy'));
INSERT INTO DEPENDENTE VALUES(2, 2935, 'Joana', to_date('10/08/1984','dd/mm/yyyy'));
INSERT INTO DEPENDENTE VALUES(3, 6987, 'Hugo', to_date('01/09/2009','dd/mm/yyyy'));
INSERT INTO DEPENDENTE VALUES(4, 6987, 'Turine', to_date('10/06/2003','dd/mm/yyyy'));
INSERT INTO DEPENDENTE VALUES(5, 1234, 'Augusto', to_date('30/06/2005','dd/mm/yyyy'));

E com o seguinte SELECT :
SELECT 'O dependente ' || InitCap(Nome) || ' é dependente do funcionário de código: ', Matricula FROM Dependente WHERE Nome LIKE ('T%') OR ('A%');

Eu quero selecionar somente os dependentes que tenham no começo do nome as letras T ou A, mas ao usar este SELECT acima, ele não me retorna o que eu quero. Ele retorna nada. Como posso usar de forma correta o operador OR com o LIKE ?

A:

Você precisa ajustar seu SQL para as condições:
SELECT 'O dependente ' || InitCap(Nome) || ' é dependente do funcionário de código: ', Matricula
FROM Dependente
WHERE Nome LIKE 'T%' OR Nome LIKE 'A%';

Sempre que há uma nova condição, você repete a coluna a ser condicionada e coloca o operador. < coluna > < condicao > < referencia >
Exemplo:
WHERE NOME = 'Joaquim' OR NOME <> 'Pedro'

Veja mais: SQL AND, OR and NOT Operators


Q:

Convert to Json format from array values with titles to the laravel view

This is in my Laravel Controller index Method:
if(count($least) == 0)
        {
            $events = DB::table('bookings')
             ->join('events','bookings.event_id','=','events.id')
             ->join(DB::raw('(select S.event_id, sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
             {
                $join->on('bookings.event_id', '=', 'd.event_id');
             })
             ->select('bookings.event_id','events.name', 'd.sum_spaces',
                      DB::raw('COUNT(bookings.event_id) as tb'))
             ->groupBy('bookings.event_id')
             ->get();
        //return $events;

            $occupacy = array();
            $eventname_occupacy = array();

            $least = array();
            foreach($events as $event)
            {
                $occupacy[] = $event->tb / $event->sum_spaces * 100;
                $eventname_occupacy[] = $event->name;

            }
            $least[0] =  min($occupacy);
            $least[1] =  min($eventname_occupacy);
            }
 }

In this method I am getting $least array where first value is going to be percentage and second value is the title of the event.
I need to add custom Title for both array index while converting to Json format.
I tried lot of things like: Json_encode, response()->json() etc. but cant get the format I need.
This is what I have in an array:
[2.7397260273973,"Reflexology Massage"]

And this is what I want :
{ "least":
    {
       "occupacy" : "2.7397..."
       "event_name" : "Reflexology Massage"
    }
}

So that I can access in Laravel view as
$least->event_name and $least->occupacy

Or I dont even mind accessing array values in Laravel like:
$array[0]  // Where this is the occupacy
$array[1]  // and this is event name

Anyway would work until and unless I have the values I need.

A:

Add the names to the values in the array first, then convert to json, like so:
$a = [2.7397260273973,"Reflexology Massage"];
$array['least'] = [
    'occupancy' => $a[0],
    'event_name' => $a[1]
];
$array = json_encode($array);

$array at the end should like you with the json form. So you can access it as an object like so: $array->least->occupancy
Or, if you just want to access like this: $least->occupancy you can do this:
$least = [2.7397260273973,"Reflexology Massage"];
$array = [
    'occupancy' => $least[0],
    'event_name' => $least[1]
];
$least = json_encode($array);


Q:

javax @Pattern validation regex for characters size range

I am implementing server side validation for my REST service. In below class I have imposed javax size validation. The problem is that the size validation fires even when address1 is null or zero length string. I want the size validation to occur only when address1 contains some text, if it is empty then I don't want size validation to come into effect.
    import javax.validation.constraints.Size;
    import javax.xml.bind.annotation.XmlElement;

    public class Address {

        private String address1;

        @XmlElement(name="address1")
        @Size(min=1, max=50, message="address1")
        public String getAddress1() {
            return address1;
        }

        public void setAddress1(String address1) {
            this.address1 = address1;
        }

    }

I am thinking of using @Pattern in place of @size. What is the regex for it?

A:

The regex .{1,50} should work, though I'd suggest sticking with @Size unless you plan on making the validation more complex.


Q:

Consume XML RSS feed using jquery in a predefined template

I want use rss feed to show images on other website using jQuery
XML RSS structure is like
<rss version="2.0">
<channel>
    <title>Gallery</title>
    <link>http://www.example.com</link>
    <description>  Latest Photos</description>

    <item>
        <title>First Title of Photo</title>
        <link >https://www.example.com/image/gallery/1.jpg </link>
        <pubDate>Sun, 17 Dec 2017 00:00:00 GMT</pubDate>
        <description>Description of the image </description>
   </item>

    <item>
        <title>Second Title of Photo</title>
        <link >https://www.example.com/image/gallery/2.jpg </link>
        <pubDate>Sun, 18 Dec 2017 00:00:00 GMT</pubDate>
        <description>Description of the image </description>
   </item>

    <item>
        <title>Third Title of Photo</title>
        <link >https://www.example.com/image/gallery/3.jpg </link>
        <pubDate>Sun, 18 Dec 2017 00:00:00 GMT</pubDate>
        <description>Description of the image </description>
   </item>

</channel>
</rss>

My HTML page has following HTML structure

How can i change below code to work with the above structure..
$(document).ready(function() {
    var url = 'http://www.recruiter.com/feed/career.xml'; //Data in XML format
    $.ajax({
        type: 'GET',
        url: "https://api.rss2json.com/v1/api.json?rss_url=" + url, //For converting default format to JSON format
        dataType: 'jsonp', //for making cross domain call
        success: function(data) {
            alert('Success');
            $("#feed").append(data.feed);
            console.log(data.feed.description);
        }
    });
});

A:

You need to loop through data.items and add target data into html. As shown in bottom
$.each(data.items, function(i, item){
  $("#feed").append('
'+item.thumbnail+'
');
});

So your code should change to:
var url = 'http://www.recruiter.com/feed/career.xml';
$.ajax({
  type: 'GET',
  url: "https://api.rss2json.com/v1/api.json?rss_url=" + url,
  dataType: 'jsonp',
  success: function(data) {
    $.each(data.items, function(i, item){
        $("#feed").append('
'+item.thumbnail+'
');
    });
  }
});

Check result in demo


Q:

UIbutton in UITableViewCell in iPhone?

I'm new to objective-C and strucked at a point ..I'm adding a UILabel(Name),UIbutton(Cancel) in UITableViewCell and when I click on it  UIButton it shows an alertView with two button Yes and No .When I go for Yes I have to get the corresponding UIlabel(Name) value of that cell.But I could not understand how to do it ?
This is the code  Im writing for creating a UILabel and UIButton..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"Cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault    reuseIdentifier:CellIdentifier]autorelease];
    }
    NSMutableDictionary *d = (NSMutableDictionary *) [arr objectAtIndex:indexPath.row];
 UILabel *name=[[UILabel alloc]initWithFrame:CGRectMake(10, 45, 320,15)];
    name .font=[UIFont boldSystemFontOfSize:12];
    [name setTextAlignment:UITextAlignmentLeft];
    [name  setText:[d valueForKey:@"Name"]];
    name.tag=112;
    [cell addSubview:name];
    [name  release];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100.0f, 50.0f, 75.0f, 30.0f);
    [btn setTitle:@"Delete Details" forState:UIControlStateNormal];
    [cell addSubview:btn];
    [btn addTarget:self action:@selector(btnClicked:)
                             forControlEvents:UIControlEventTouchUpInside];

    return cell;
}
- (IBAction)btnClicked:(id)sender

{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Are you sure" message:@"You want to delete Details" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
                          [alert show];
                          [alert release];

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
       [alertView dismissWithClickedButtonIndex:0 animated:YES];

     }
    else
    {
        //I have to get the corresponding cells UILabel value.
     }

A:

Your buttons which you are creating should some how have a variable which points to which cell they are in.
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(100.0f, 50.0f, 75.0f, 30.0f);
    [btn setTitle:@"Delete Details" forState:UIControlStateNormal];
    [cell addSubview:btn];
    [btn addTarget:self action:@selector(btnClicked:)
                         forControlEvents:UIControlEventTouchUpInside];

should be
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // The below line will add a state to each button which you can use to later differentiate in your method: btnClicked
    [btn setTag:indexPath.row];
    btn.frame = CGRectMake(100.0f, 50.0f, 75.0f, 30.0f);
    [btn setTitle:@"Delete Details" forState:UIControlStateNormal];
    [cell addSubview:btn];
    [btn addTarget:self action:@selector(btnClicked:)
                         forControlEvents:UIControlEventTouchUpInside];

   you can set some variable which is global to the class like "selectedRow". You can declare it on the top of the class after the line @implementation. Look for a line called

   @implementation yourClassName

   //Add the below declaration. This is a global variable in your class, which you can set in one method and access in other methods
   int selectedRow;

and in btnClicked
//Add the below line
selectedRow=[sender tag];

and in the final method of alertView clickedAlert at
   // NSLog(@"Name selected is ",[arr objectAtIndex:selectedRow] objectForKey:@"Name"]);


Q:

Проблема с русским в консоли после компиляции

#include <iostream>
using namespace std;
int main()
{
   setlocale(LC_CTYPE,"Russian");
   cout << "Этот текст будет каракулями";
   return 0;
}

Немогу понять, как сделать, чтобы была поддержка OEM.

A:

#include <iostream>
#include <windows.h>
using namespace std;

char* convert(char* str)
{
   char* s;
   CharToOemA(str, s); // Функция и конвертация.
   return s;
}

int main()
{
   cout<<convert("Привет Мир!!!");
   cin.get();

   return 0;
}


Q:

python requests api not posting in-memory zipped file

question: How can I get this to work
I'm trying to use the python requests api to send a zipped file to a server. I saw this method in the docs:
r = requests.post(url, files=open('foo.png', 'rb'))

but the difference between what I'm doing, is that the zipped file that I have is in memory, there's just a python object, no physical zipped version of the file is created:
I'm using the zipfile api, and this is how I'm creating my zip file:
inMemoryOutputFile = StringIO()
outFile = zipfile.ZipFile(inMemoryOutputFile, "w",
        compression=zipfile.ZIP_DEFLATED)

and trying the following (after writing to the zip file):
r = requests.post(url, outFile)

however its not working, looks like the object is not being recognized as a parameter. here's the stack trace
Traceback (most recent call last):   File
"/Users/abdulahmad/Desktop/upload-script-ve/bin/cogs", line 11, in
<module>
    sys.exit(main())   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/cogs/run.py",
line 396, in main
    return run(sys.argv)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/cogs/run.py",
line 384, in run
    return instance()   File "/Users/abdulahmad/Desktop/upload-script-ve//src/ctl.py",
line 53, in __call__
    handler = uploader(self.url, self.file)   File "/Users/abdulahmad/Desktop/upload-script-ve//src/uploader.py",
line 24, in __call__
    response = self.session.post(url, files=payload)

#this is where I'm adding the file (the payload)

File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 511, in post
    return self.request('POST', url, data=data, json=json, **kwargs)   File
"/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 454, in request
    prep = self.prepare_request(req)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/sessions.py",
line 388, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 296, in prepare
    self.prepare_body(data, files, json)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 447, in prepare_body
    (body, content_type) = self._encode_files(files, data)   File "/Users/abdulahmad/Desktop/upload-script-ve/lib/python2.7/site-packages/requests/models.py",
line 150, in _encode_files
    fdata = fp.read() TypeError: read() takes at least 2 arguments (1 given)

actual code:
inMemoryOutputFile = StringIO()

    parentDir, dirToZip = os.path.split(dirPath)
    def trimPath(path):
        archivePath = path.replace(parentDir, "", 1)
        if parentDir:
            archivePath = archivePath.replace(os.path.sep, "", 1)
        if not includeDirInZip:
            archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1)
        return os.path.normcase(archivePath)

    outFile = zipfile.ZipFile(inMemoryOutputFile, "w",
        compression=zipfile.ZIP_DEFLATED)

    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        for fileName in fileNames:
            filePath = os.path.join(archiveDirPath, fileName)
            outFile.write(filePath, trimPath(filePath))
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")

            outFile.writestr(zipInfo, "")
    outFile.close()
    return outFile

A:

You need to pass the StringIO buffer to requests, not the ZipFile. ZipFile.read("somefile.txt") reads an uncompressed file from the archive, it doesn't read the compressed binary stream. That read requires 1 parameter and that's why you got the strange error message. Rewind the file before posting or the POST data will be empty.
This example shows you the workflow.
import zipfile
from cStringIO import StringIO
import requests
import logging

logging.basicConfig(level=logging.DEBUG)

buf = StringIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zippy:
    zippy.write('somefile.txt')
buf.seek(0)

requests.post('http://localhost:8080',
    headers = {'content-type': 'application/octet-stream'},
    data=buf)


Q:

Console component tries to open in subtab when primaryTabId is null

I am working on a visualforce console footer component that displays solutions. If a tab is open, the solution opens as a subtab.  If no primary tab is open, the new page still tries to open in a subtab.
Iḿ using a simple if else statement to evaluate if primaryTabIdxRt === null || primaryTabIdxRt === undefined, but instead it still follows the else path.  The console log clearly shows that primaryTabIdxRt is null, and it keeps going down the wrong path.
Here is the relevant function

The function is called via onClick event
{!s.SolutionName}

Here is the console output when parent Id is null.  Its going down the else path, even though the log shows that the Id is null before the if statement evaluates.
Console Log (id = null):
OpenSolutionInitial = null
OpenInSubtab = null
openSubTab: Invalid ID: null

Interestingly, the solution does open in primary tab when parent ID is undefined (which is the value when I first open or refresh the console), so its just null that isnt evaluating properly.
Console Log (id = undefined):
OpenSolutionInitial = undefined
OpenInPrimaryTab = undefined

Output:

I have tried evaluating == null, i have tried evaluating if(primaryTabIdxRt) and flipping the paths, I renamed primaryTabId to primaryTabxRt in case there was a naming conflict, I tried removing the || and using else if primaryTabxRt === undefined, and none of these had any impact.
Any ideas on what else to try?  I have some other functions running to update primaryTabIdrXt when tab is closed, etc, and its all working reasonably well, but this piece which seems straightforward is not behaving.
Here is the code for the full visualforce page
<apex:page standardController="Solution" recordSetVar="sols">

<apex:variable value="{!LEFT($Api.Partner_Server_URL_260, FIND( '/services', $Api.Partner_Server_URL_260))}" var="instanceURL"/>

<apex:includeScript value="/support/console/39.0/integration.js"/>

        <apex:form >
            <apex:panelGrid >
                <apex:selectList value="{!filterId}" size="1" id="selList">
                <apex:actionSupport event="onchange" rerender="list"  />
                <apex:selectOptions value="{!listViewOptions}"></apex:selectOptions>
                </apex:selectList>
            </apex:panelGrid>

                <apex:dataList var="s" value="{!sols}" id="list" style="padding: 0px;">

           {!s.SolutionName} - {!s.Status}

                </apex:dataList>
           <apex:commandButton onclick="refreshPrimaryTabId();" title="ClickMe" value="Refresh Primary Tab ID" rerender="selList" />
        </apex:form>

</apex:page>

UPDATE
I modified the openSolution function to reflect the changes suggested by Santanu.
Here is the updated function.  I changed from primaryTabIdxRt === null to primaryTabIdxRt == null, and I added window.location.reload();.  For testing I also removed the lines that call openPrimaryTab and openSubtab methods, and am only using alerts to show which path is followed.
As the screenshots of the alerts illustrate, the function still is not following the null path when primaryTabIdxRt is null.  So maybe I need to try a different way to evaluate null?

abcdefg

Actions taken
1. open console
2. open console component
3. click 'refresh primary tab id' button
4. click on the link 'abcdefg'
see screenshots of the alerts below - its following the else / subtab path, instead of the else if / primaryTab path, even though it sees primary tab as null.
1. initial id is null

2. subtab path is followed

A:

I have taken your code done a small change and it is working as expected.
For shake of my testing, rather than solutions, I am opening a hardcoded Lead record.
Before clicking on Click Here url, I am clicking on 'Refresh Primary Tab Id` button so that it can recognize the tab id.
I think, every time your Solution record is opening on Subtab, may be in the Console App configuration you have chosen Solution to open as subtab.
That's why I have taken a lead record which is no way related to any tab defined in my Console App.
<apex:page standardController="Case">
    <apex:includeScript value="/support/console/29.0/integration.js"/>

    <apex:form >
         Click here

      <apex:commandButton onclick="refreshPrimaryTabId(); return false;" title="ClickMe" value="Refresh Primary Tab ID" rerender="selList" />
    </apex:form>
</apex:page>

Update
When primary tab is null javascript actuals returns "null" String. So you have to check like this:
if (primaryTabIdxRt == null || primaryTabIdxRt == 'null')


Q:

Can collaborative filtering be applied to the disease detection?

Browsing through some tutorials on collaborative filtering, I have observed that it is mostly used with movie and book recommendations, with datasets that have users and the items they rate. Definitely, the range for rating per item would be the same (e.g 1-10). But what if I have a dataset that has different ranges. Meaning an entirely different dataset that has nothing to do with how people rate an item but instead, based on medical records of people. I am thinking of using the features in the record like BMI, Weight, Height etc. etc. as the item and the user as the person with that record. Basically at the end of the process, i'd like to determine whether one has a disease or not based from other records that already have pre-determined output. I know that this is usually/can easily be done in Neural Networks. But i just really want to know if this is also possible in collaborative Filtering. Or is it not?

A:

It is not a recommendation problem, this is classical classification, nothing more. Neural Networks are just one of dozens od possible approaches,but once again - it is not collaborative filtering, it is exactly how classification is defined. In collaborative filtering you do not know the correct answer (labels/output) - you simply try to find some common pattern among other. In case of disease detection/forecast you know exactly what should be the output.
Recommender systems could be used here if you have very broad spectrum of possible, correlated diseases, and very small amount of people with it (so it is not possible to actually build training sets for the disseas). Then such "recommendation" which looks for a potential health problem would have sense.In case of labeled, binary output data it is just a classification. Even though, you would probably end up with model: "if you have obessity, then you will probably get a heart attack" etc. So finding correlation between similar diagnoses.


Q:

Api gateway VPC link integration to a EC2 machine through the NLB not working because of the security group issue

I have a service running on the port 8080 of an EC2 machine in a private subnet. My plan is to establish a VpcLink to the private endpoint using a Network load balancer. Now the network load balancer cannot associate a security group of its own, instead the target security group will come into action here (in this case the security group of the EC2 where my service is running). I am a little confused over how does the security group of the ec2 machine looks like. I need to add a custom TCP rule which will allow traffic to port 8080, but I am confused over what IP range I can give in the source. The API gateway has no IP. Also, it is saying that
Recommended Rules
Inbound Source      Port Range        Comment
Client IP addresses instance listener Allow traffic from clients on the instance listener port

VPC CIDR            health check      Allow traffic from the load balancer on the health check port

A:

Based on the comments and from the docs:

Network Load Balancers do not have associated security groups. Therefore, the security groups for your targets must use IP addresses to allow traffic from the load balancer.
If you register targets by IP address and do not want to grant access to the entire VPC CIDR, you can grant access to the private IP addresses used by the load balancer nodes.

Thus, for NLB you either use CIDR range of the subnet where NLB is. Or to be more restrictive you using NLB private addresses. For the IP addresses, you can't get them from CloudFormation. Would have to write custom resources in the CloudFormation to get the IPs from NLB. As a compromise, you could put your NLB in a dedicated subnet, or the same one as instances, and used its CIDR range.


Q:

copy data to new year in sql

I'm working on an old asp app and going to copy data of puplic holiday to new year in the same table. This code below insert Null to my table. I think we should use a temp table but don't know how -I'm a new bie.
Here my code:

<%
if session("Login")<>"YES" then
    Response.Redirect "../login.asp"
end if
%>

<title>Move Holiday Information</title>

<%

    MySql = "Select * From tblHolidayTF Where Year(Holdate)=YEAR(GETDATE())"
    rs.Open MySql, Conn, 2, 2

%>

<%
 if not rs.eof then
rs.AddNew

  rs("OfficeCode")=rs("OfficeCode")
  rs("Descript")=rs("Descript")
  rs("Days")=rs("Days")
  rs("WorkHour")=rs("WorkHour")
rs("HolDate")=dateadd("yyyy",1,GETDATE())
//rs("HolDate")=GETDATE()

  rs("EndDate")=rs("EndDate")
  if request("chkMemoSent")="on" then
        rs("MemoSent")=true
    else
        rs("MemoSent")=false
    end if
rs("Significance")=rs("Significance")
  rs.Update
end if
%>

Holiday
<% if HolID<>"" then %> added
<% else %> updated
<% end if %> successfully...

If this window is not going to close automatically in 5 seconds, please

Click here to return...

A:

You cannot use the same recordset (Rs) for this. By doing an .AddNew, the new record will be the current record in you recordset(like SearchAndResQ already mentioned).
Create a second record set to create the new record:
MySql = "Select OfficeCode, Descript From tblHolidayTF Where Year(Holdate)=YEAR(GETDATE())"

Rs.Open MySql, Conn, 2, 2

If Not Rs.EOF Then
    Dim RsNew: Set RsNew = Server.CreateObject("ADODB.Recordset")

    RsNew.Open "tblHolidayTF", Conn, 2, 2
    RsNew.AddNew
    RsNew("OfficeCode") = Rs("OfficeCode")
    RsNew("Descript") = Rs("Descript")
    RsNew.Update
    RsNew.Close
End If

or (better?), copy the values of your Rs to an array, close the recordset and create a new record. In that case you need to specify the columns in your query to know the sequence.
MySql = "Select OfficeCode, Descript From tblHolidayTF Where Year(Holdate)=YEAR(GETDATE())"

Rs.Open MySql, Conn, 2, 2

If Not Rs.EOF Then
   Dim OldData: OldData = Rs.GetRows()

   Rs.AddNew
   Rs("OfficeCode") = OldData(0,0)
   Rs("Descript") = OldData(1,0)
   Rs.Update
End If


Q:

jQuery convert all images to anchor

I want to convert all images like this:

to:

with jQuery, I tried this:
$("img").replaceWith( "" );

but not worked :(

A:

Try wrap
$("img").wrap(function(){
    return "";
});

DEMO


Q:

How do I account for daylight savings time when retrieving current time in PHP?

When getting the time via PHP script (time()), during Daylight Savings Time it seems to return a time value that is one hour off. Is there any way to get the correct time, accounting for Daylight Savings Time?

A:

time() returns a Unix timestamp and a Unix timestamp is a fixed period of time: number of seconds since the Unix Epoch. It isn't affected by time zones.
Once you have the precise moment, you may want to calculate the local time in a given place:
<?php

$now = time();
echo $now . PHP_EOL;

date_default_timezone_set('Europe/Madrid');
echo date('r', $now) . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
echo date('r', $now) . PHP_EOL;

... will print different local dates for the same timestamp:
1313683738
Thu, 18 Aug 2011 18:08:58 +0200
Fri, 19 Aug 2011 01:08:58 +0900

The same reasoning applies for the opposite operation:
<?php

date_default_timezone_set('Europe/Madrid');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;

date_default_timezone_set('Asia/Tokyo');
$then = mktime(23, 55, 30, 12, 31, 2000);
echo $then . PHP_EOL;

... will print different timestamps:
978303330
978274530


Q:

Creating a curly bracket curve from two points

I'm trying to create a curly bracket in Swift, from two points. The idea works fine, with a straight line, because it's currently not dynamic in anyway. My issue lies in finding the dynamic control points and center depending on the location of p1 and p2 points.
This is my current code:
override func viewDidLoad() {
    super.viewDidLoad()

    let path = UIBezierPath()

    let p1 = CGPointMake(100, 100)
    let p2 = CGPointMake(300, 100)

    let c1 = CGPointMake(150, 80)
    let c2 = CGPointMake(250, 80)

    var midPoint = midPointForPoints(p1, p2: p2)

    var midP1 = midPoint
    midP1.x -= 10

    var midP2 = midPoint
    midP2.x += 10

    midPoint.y -= 20

    path.moveToPoint(p1)
    path.addQuadCurveToPoint(midP1, controlPoint: c1)
    path.addLineToPoint(midPoint)
    path.addLineToPoint(midP2)
    path.addQuadCurveToPoint(p2, controlPoint: c2)

    let shape = CAShapeLayer()
    shape.lineWidth = 5
    shape.strokeColor = UIColor.redColor().CGColor
    shape.fillColor = UIColor.clearColor().CGColor
    shape.path = path.CGPath

    self.view.layer.addSublayer(shape)

}

func midPointForPoints(p1: CGPoint, p2: CGPoint)->CGPoint{
    let deltaX = (p1.x + p2.x)/2
    let deltaY = (p1.y + p2.y)/2

    let midPoint = CGPointMake(deltaX, deltaY)

    return midPoint
}

This doesen't take the degrees of the points into account, so if I were to create the two points as:
let p1 = CGPointMake(100, 100)
let p2 = CGPointMake(300, 300)

It would not find the proper control points and midpoint.
Hope someone can help me in the right direction. The idea is of course in the end to just know the two points (p1, p2) and dynamically create every other points, I just typed in values for the moment, to make it easier for myself. I've added images of the issue to better show you.

A:

The key to the problem is when the figure is rotated your base vectors will rotate. When your figure is axis-aligned your base vectors are u (1, 0) and v (0, 1).
So when you are performing midPoint.y -= 20 you can see it as the same as midPoint.x -= v.x * 20; midPoint.y -= v.y * 20 where v is (0, 1). The results are the same, check for yourself.
This implementation will do what your code does, only axis independent.
let path = UIBezierPath()

let p1 = CGPointMake(100, 100)
let p2 = CGPointMake(300, 100)

let o = p1.plus(p2).divide(2.0) // origo
let u = p2.minus(o)             // base vector 1
let v = u.turn90()              // base vector 2

let c1 = o.minus(u.times(0.5)).minus(v.times(0.2))  // CGPointMake(150, 80)
let c2 = o.plus(u.times(0.5)).minus(v.times(0.2))   // CGPointMake(250, 80)

var midPoint = o.minus(v.times(0.2))

var midP1 = o.minus(u.times(0.2))
var midP2 = o.plus(u.times(0.2))

Note: I set the factors to match the initial values in your implementation.
Also added this CGPoint extension for convenience. Hope it helps.
extension CGPoint {
    public func plus(p: CGPoint) -> (CGPoint)
    {
        return CGPoint(x: self.x + p.x, y: self.y + p.y)
    }
    public func minus(p: CGPoint) -> (CGPoint)
    {
        return CGPoint(x: self.x - p.x, y: self.y - p.y)
    }
    public func times(f: CGFloat) -> (CGPoint)
    {
        return CGPoint(x: self.x * f, y: self.y * f)
    }
    public func divide(f: CGFloat) -> (CGPoint)
    {
        return self.times(1.0/f)
    }
    public func turn90() -> (CGPoint)
    {
        return CGPoint(x: -self.y, y: x)
    }
}


Q:

Kubernetes pod events showing as ""

We are investigating an issue that is related to slow pod startups on Azure Kubernetes Services.  Once the pod startup is complete, we are unable to see historical events.  The latest event log appears as <none>.
Here is an example:
sshuser@sandbox-ubuntu-vm:~$ kubectl get pods
NAME                                            READY   STATUS      RESTARTS   AGE
my-service-58bb6868c-rfrgr               1/1     Running     0          4h51m
sshuser@sandbox-ubuntu-vm:~$ kubectl describe pod my-service-58bb6868c-rfrgr
Name:           my-service-58bb6868c-rfrgr
Namespace:      default
Priority:       0
Node:           aks-myproject-41067869-1/10.0.1.163
Start Time:     Thu, 20 Feb 2020 05:25:36 -0500
Labels:         app.kubernetes.io/instance=my-service
                app.kubernetes.io/name=my-service
                pod-template-hash=58bb6868c
Annotations:    <none>
Status:         Running
IP:             10.0.1.183
IPs:            <none>
Controlled By:  ReplicaSet/my-service-58bb6868c
Containers:
  my-service:
    Container ID:   docker://b366fc6459f7dc03287d62da81c9fb1ed2c30ec0ccb4b601d2eea62e644de9f9
    Image:          myacr.azurecr.io/myproject/microservices/my-service:0.0.48
    Image ID:       docker-pullable://myacr.azurecr.io/myproject/microservices/my-service@sha256:cca04f3499271ac5ae383ddccba8c3f716b8f95cd0c06042ef4d7f69626beb8d
    Port:           3000/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Thu, 20 Feb 2020 05:32:38 -0500
    Ready:          True
    Restart Count:  0
    Liveness:       http-get http://:http/ delay=0s timeout=1s period=10s #success=1 #failure=3
    Readiness:      http-get http://:http/ delay=0s timeout=1s period=10s #success=1 #failure=3
    Environment:
      PORT:                          3000
    Mounts:
      /kvmnt from my-service-kv-volume (ro)
      /var/run/secrets/kubernetes.io/serviceaccount from my-service-token-lbfjg (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  my-service-kv-volume:
    Type:       FlexVolume (a generic volume resource that is provisioned/attached using an exec based plugin)
    Driver:     azure/kv
    FSType:
    SecretRef:  &LocalObjectReference{Name:kvcreds,}
    ReadOnly:   false
    Options:    map[REMOVED]
  my-service-token-lbfjg:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  my-service-token-lbfjg
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:          <none>
sshuser@sandbox-ubuntu-vm:~$ kubectl get events --all-namespaces
No resources found
sshuser@sandbox-ubuntu-vm:~$

Is there a periodic purge for the event logs?  We are able to see events when the pod status is ContainerCreating, but then the events are not visible shortly after (unknown how long) the pod goes to a Running state.
The Kubernetes version is 1.14.8.
Any help is greatly appreciated.
Thanks.

A:

Kubernetes has default time to retain event configured to 1hr in kube-apiserver.
You can configure the ttl of events by setting the flag --event-ttl durations  of kube-apiserver.
Find more on Kube-apiserver Documentation


Q:

 ContentControl DataTemplate using Interface

I've got a wpf application which shows a list of users. clicking on a user will display the details of that user - much like the WaF book library example, etc.
I've done a bit of reading about binding to interfaces, and i can successfully bind a ListView to my interface, but using the same method with a ContentControl doesn't work.
here's what i've got:
domain model - USER (EF entity)
partial class USER : IUser
    {
    }

public interface IUser
    {
        String USERNAME { get; set; }
        String FIRST_NAME { get; set; }
        String SURNAME {get;set;}
        String EMAIL { get; set; }
    }

presentation layer
    public class UserMainContentModel
    {
          public ICollectionView Users { get; private set; }
          public IUser SelectedUser { get; private set; }
          //...
          private void SelectedUserChanged(object sender, EventArgs e)
          {
            SelectedUser = Users.CurrentItem as IUser;
             NotifyPropertyChanged("SelectedUser");
          }
    }

view xaml
<UserControl x:Class="CQMS.Module.Users.Views.MainContent.UsersMainContentView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:models="clr-namespace:CQMS.Module.Users.ViewModels"
             xmlns:interface="clr-namespace:CQMS.Framework.Model;assembly=CQMS.Framework"
             mc:Ignorable="d" >
    <UserControl.Resources>
        <DataTemplate DataType="{x:Type interface:IUser}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                Username
                Name
                Email
                <TextBox AutomationProperties.AutomationId="UsernameTextBox" Grid.Row="1" Grid.Column="0" Text="{Binding interface:IUser.USERNAME}" />
                <TextBox AutomationProperties.AutomationId="NameTextBox" Grid.Row="1" Grid.Column="1" Text="{Binding interface:IUser.FIRST_NAME}" />
                <TextBox AutomationProperties.AutomationId="EmailTextBox" Grid.Row="1" Grid.Column="2" Text="{Binding interface:IUser.EMAIL}" />
            </Grid>
        </DataTemplate>
    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height=".4*"/>
            <RowDefinition Height=".6*"/>
        </Grid.RowDefinitions>
        <ListView Grid.Row="0" AutomationProperties.AutomationId="UserListView" ItemsSource="{Binding Users}"  SelectionMode="Single" Width="Auto" Height="Auto" >
            <ListView.ItemTemplate>
                <DataTemplate DataType="{x:Type interface:IUser}"/>
            </ListView.ItemTemplate>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Username" Width="80"
                         DisplayMemberBinding="{Binding Path=USERNAME}"/>
                    <GridViewColumn Header="First Name" Width="80"
                         DisplayMemberBinding="{Binding Path=FIRST_NAME}"/>
                    <GridViewColumn Header="Email" Width="80"
                         DisplayMemberBinding="{Binding Path=EMAIL}"/>
                </GridView>
            </ListView.View>
        </ListView>
        <Border Grid.Row="1" CornerRadius="4,4,4,4" BorderBrush="#193441" Background="#FCFFF5" BorderThickness="2,2,2,2" Margin="5" Padding="5">
            <ContentControl Content="{Binding SelectedUser}"  Width="Auto" Height="Auto"/>
        </Border>
    </Grid>
</UserControl>

When i select a user from the list, what i want is for the selected user's details to show in the content control, however, all i'm getting is the name of the concrete class being shown in this control. I don't want to expose my concrete class to my view, and i don't really want to have to wrap my IUser object in a Model object...is there a way to do this? have i implemented this correctly?

A:

Are you sure that DataTemplates can be applied implicitly for interfaces instead of classes? Either way, in this case it would not hurt to give the template a key and to reference it in the ContentControl.ContentTemplate.
Also i have never seen bindings like this, shouldn't the path simply be USERNAME instead of interface:IUser.USERNAME?


Q:

In Dark Matter s02e08 (SPOILER ALERT!!), Regarding Jace Corso

In s02e08, in the alternate reality, isn’t Jace Corso supposed to be good? After all, he is

 Derrick Moss

In this episode he seems evil. Why?

A:

We don't know whether this is the real Jace Corso or not but its probably safe to assume it is.
Jace Corso is a real person whose identity was assumed by Derrick Moss (One)
From the Wikia

Jace told them that he was supposed to go with the Raza and its crew to the job on the Mining Colony but wasn't able to make it. He had since learned that he had supposedly boarded the ship, and had then viewed security footage that showed One boarding the ship in his place. He had pursued One ever since.

Perhaps in this alternate reality, he could make it...we just don't know, but again, based on his actions etc, it's safe to assume this is the real Jace and not One.
Syfy seems to indicate that this is in fact Alt-Jace and not Alt-Derrick/One

You can't keep Marc Bendavid away from Dark Matter for too long. One got killed off, Jace Corso got killed off, but now we've got ... Alternate Jace Corso!


Q:

Books/(auto)biographies/references on how mathematicians study/studied (as students)?

As Geoff Pointer commented:

[...] As a composer I've learnt a lot from studying famous composers why wouldn't that also apply to studying maths and mathematicians of note as well? [...]

Are there any (auto)biographies, studies, or references of mathematicians on

how they learn and study,
apprehend new maths,
or how they had done so while they were students?

In the Area 51 page, someone recommended this book, what are some other examples?

A:

Here are two from famous mathematicians who have tried to explain how they approach mathematics:
George Pólya.  This book is actually targeted at introductory students.  It has great examples, and an explanation of a method to approach them.
Terence Tao is one of the best problem solvers of our time.  He explains what I believe you're looking for in great detail.

A:

How Does One Do Mathematical Research? (Or Maybe How Not To), by Lee Lady
Mathematics as a creative art, by Paul Halmos
I Want to Be a Mathematician: an Automathography, by Paul Halmos
Also, this MSE thread ("what is mathematical research like?") might be of interest.

A:

G. H. Hardy's A Mathematician's Apology is a nice read.


Q:

Measuring execution time in the D language

I'm new to the D language and need to measure the execution time of an algorithm. What are my options? Is there already some built-in solution? I could not find anything conclusive on the web.

A:

One way is to use -profile command line parameter. After you run the program, it will create file trace.log where you can find run time for each function. This of course will slow down your program as the compiler will insert time counting code into each your function. This method is used to find relative speed of functions, to identify which you should optimize to improve app speed with minimum effort.
Second options is to use std.datetime.StopWatch class. See the example in the link.
Or even better suited might be to directly use std.datetime.benchmark function.
Don't forget:

When benchmarking use these dmd compiler flags to achieve maximum optimization -release -O -inline -noboundscheck.
Never benchmark debug builds.
Make sure you don't call any library code inside benchmarked functions - You would be benchmarking performance of library implementation instead of your own code.

Additionally you may consider using LDC or GDC compilers. Both of them provide better optimizations / app run speed than DMD.

A:

If your algorithm can be called from the commandline there's a nifty utility written in D that will run your program a number of time and print out the distribution of the average time taken and all sort of other useful numbers.
It's called avgtime and it's here: https://github.com/jmcabo/avgtime


Q:

Insanely large ONE-dimensional arrays in C++

How can I make an one dimensonal array with 256^256 elements?
I've researched big integers, but I haven't found anything about using them as indexes in arrays.
An alternative would be using multidimensional arrays. Anyway, using long 64 bit integers as indexes, it would be needed 32 dimensions. Is there a way to add dimensions to an array after its definition?
EDIT:
I wanted to sort all 256-byte combinations in order of entropy. I may try something more realistic, like 4-byte combinations. But it may be useless. Thanks for help.

A:

As said by others, the universe isn't big enough for such an array. However if it's a sparse array (i.e. not all elements are present only some) then you can use a std::map (or std::unordered_map) with the number being the key (now all you have to do if find a big integer library).

A:

ANY form of array with 256^256 elements would be so insanely big that storing it is impossible. For example, if every element would be 1 bit you would still require
36740182248776144775450662437685823488714166466838246415284567578424520364555850043413103562
12820063739027086844759880875030780674761777060562980339733290193252159652649992960022040932
74368143588572566368203155983301169483668442764631414483329492332706895988986119676188622814
73799459727851572551030506458030134050875026721792761435138532498848299128480137280869346120
26576704260231561001336360572266150611167852685380064696955468929349115301864049308461884866
94145775864907486950525312262263093217864817217361867923249690716116542182574428528882508424
4005613936921626330968666174894520389915236768940032

terabytes of storage.
Perhaps refactoring your algorithm would help.