text:
Q: "Can be used only in preamble" when using \DeclareLanguageMapping with BibLaTeX I recently switched to BibLaTeX to realize a multilanguage bibliography. Everything worked out fine -- however I get the error "Can be used only in preamble." when using the command \DeclareLanguageMapping{english}{english-apa} to declare the respective apa-file as the language file for english. Strangly enough it works if I compile the file without the line in question and compile it a second time with the command. Does anyone know how to fix this?
Here is my MWE:
\begin{filecontents}{\jobname.bib}

@article{Grimberg.2012,
 author = {Grimberg, Steffen},
 year = {2012},
 title = "{Sherlock Holmes in der ARD: Gefährliche Gefühle}",
 journal = {taz.de \textnormal{am 17.05.2012}},
 url = {http://www.taz.de/!5093806/},
 urldate = {2015-06-06},
 hyphenation = {english}
}

@book{Weller.1994,
author = {Philip Weller},
year = {1994},
title = "{Alphabetically, My Dear Watson. A Compilation of Canonical Characters. Sherlock Holmes from A to Z}",
edition = {3},
address = {Portsmouth},
publisher = {Sherlock Publications},
}

@incollection{Moriarty.2011,
author = {Moriarty, James},
title = "{The Role of Supervillains in Modern Democracy.}",
pages = {79-107},
publisher = {{Villainy Press}},
editor = {Moriarty, James},
booktitle = {Supervillainy in the 21st Century},
volume = {5},
edition = {3},
year = {2011},
address = {London},
hyphenation = {english},
}
\end{filecontents}
\documentclass[12pt,parskip=half]{scrartcl}

\usepackage[english,ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}

\usepackage{csquotes}
\usepackage[
backend=biber,
style=apa,
natbib=true,
autolang=other]{biblatex}
\DeclareLanguageMapping{ngerman}{ngerman-apa}
\DeclareLanguageMapping{english}{english-apa}

\addbibresource{\jobname.bib}

\begin{document}
\citet{Grimberg.2012, Weller.1994, Moriarty.2011}

\printbibliography
\end{document}

A: The language files are loaded the first time they are "needed". At the first compilation this is when the \cite commands are seen and so in the middle of the document. As \DefineBibliographyExtras is an "only preamble" command you get an error.
At the next compilation the aux files calls the english language and so the language files are loaded earlier.
You can force the early loading of the language files by using
\AtBeginDocument{\selectlanguage{english}\selectlanguage{ngerman}}

Edit
It is imho a bug in the apa-files. It uses DefineBibliographyExtras instead of \DeclareBibliographyExtras. I made a bug report: https://github.com/plk/biblatex-apa/issues/12


text:
Q: Finding the largest prime in sequence 10101... If you consider the (decimal) numbers 10, 101, 1010, 10101... where the 1 and 0 alternate, what is the largest prime number in the sequence?
Thanks in advance for your help, I appreciate it.

A: The only prime in this sequence is $101$.
As @EuYu pointed out, for even n, $k_{2n} = k_{n}(10^{2n}+1)$ is even. This equality can be easily shown by considering multiplication by $10^n$ as appending $n$ zeros to the end of the number in base 10, and noting that $k_{2n}$ has $2n$ digits.
$k_{2 n + 1}$ is divisible by a string of $(2n+1)$ $1$'s. Explicitly, $$\left(\sum_{i=0}^{2n+1} 10^i \right)*\left(1+ \sum_{i=0}^{n} 10^{2 i}*90\right ) = k_{2 n + 1}$$
Algebraically you can bash this out (or throw at Wolfram), but there's a good pen-n-paper way to see this.
Look at $909091*1111111$.
$90*1111111=99999990$.
Adding $1111111$ to this will "overflow" the number to $101111101$, which is of the form $10[1...1]01$
Now add that to $9999999000=9000*1111111$.
Look at the digit-wise sums from right to left: last 3 unchanged because $10^3 | 9000$, then 10s until the first 0 in $101111101$.
Considering the carried "1" at each step, the sum is $1010[1...1]0101$.
Proceed inductively, result = $1010101010101$.

A: Clearly the number cannot end in $0$, so we consider integers of the form
$$k_n=1010101\cdots 01,$$
where $k_n$ is of length $2n-1$. Note that every such integer is of the form
$$k_n = \frac{10^{2n}-1}{99} = \frac{(10^{n}-1)(10^n + 1)}{99}.$$
If $n=1$, then $k_1=1$. If $n=2$, then $k_2 = 101$, which is prime. If $n>2$ and $n$ is even, then
$$k_n = k_{n/2}(10^n+1),$$
so that $k_n$ is composite. Finally, if $n>2$ is odd, then $11\mid (10^n+1)$ and $9\mid (10^n - 1)$ so that again $k_n$ is composite. It follows that in this sequence, only $k_2 = 101$ is prime.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I mock a function from another package without using dependency injection? Somewhat of a golang beginner, but I've worked with testing frameworks before. How do I go about mocking out and faking what a dependent method returns without injecting the dependency? The reason why I don't want to use dependency injection is because there are many external package methods that are being used and injecting all of the methods in the constructor is unwieldy.
I've searched for this online/stackoverflow and the solution is to always use dependency injection. Sometimes that is not a viable option.
Here's what I'm trying to do code-wise:
b/b_test.go
package b

func TestResults(t *testing.T) {
    t.Run("Test", func(t *testing.T) {
        b := NewB()
        // How do I mock out and fake a.DoSomething() to be
        // "complete" instead of whats in the code right now?
        result = b.Results()
        assert.Equal(t, "complete", result)
    }
}

b/b.go
package b

import "a"

type B struct {}

func NewB() B {
    return &B{}
}

func (b B) Results() {
    return a.DoSomething()
}

a/a.go
package a

func DoSomething() {
    return "done"
}

Thanks!

A: One way to do so would be to create a variable with the function you want to call, so include the following in b/b.go:
var doSomething = a.DoSomething
func (b B) Results() {
    return doSomething()
}

Now in b_test.go you can do this:
func TestPrintResults(t *testing.T) {
        origDoSomething := doSomething
        defer func() { doSomething = origDoSomething }
        doSomething = func() {
          // Insert fake implementation here
        }
        b := NewB()

        result = b.Results()

        assert.Equal(t, "complete", result)
}

A: I'm not sure if I don't understand your objection to dependency injection, but interfaces can be used to make dependency injection relatively painless. In particular existing code does not need to be modified.
You could try aliasing the package name to a global variable that implements an interface that matches the external package's functions. This has the advantage of not requiring inline changes where package "a" is used.
The idea revolves around creating an interface for the functions you need from the external package, a pass-through implementation of that interface for the default behavior and a mock implementation for testing. At the beginning of a test just replace the global variable with the mock.
b/a_interface.go
package b

import (
    aa "a" // alias the "a" package
)

// global variable that mimics the external package "a"
var a aType

// internal interface for `a` package functions (i.e. `DoSomething()`)
type aDoer interface {
    DoSomething() string
}

// default implementation of the aDoer interface
type aType struct{}

func (aType) DoSomething() string {
    // just pass-through to package "a"
    return aa.DoSomething()
}

b/b.go - is unmodified other then removing the import:
package b

type B struct{}

func NewB() B {
    return B{}
}

func (b B) Results() string{
    // now `a` is a global variable not a package.
    return a.DoSomething()
}

b/b_test.go
package b

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

// mock implementation of aDoer interface
type aMock struct{}

func (aMock) DoSomething() string {
    return "complete"
}

func TestResults(t *testing.T) {
    a = aMock{}  // <- replace the default with the mock

    b := NewB()

    result = b.Results()
    assert.Equal(t, "complete", result)
}

It's a bit on the sneaky side, so you'll probably want to make clear comments about what's going on.

A: You can use conditional compilation with build tags
a/a.go
// +build !mock

package a
func DoSomething() {
    return "done"
}

a/a_mock.go
// +build mock

package a
func DoSomething() {  // Insert fake implementation here
    return "complete"
}

$ go test -tags mock


text:
Q: SMS Triggered Sends for Long Code Support with multiple countries sms triggered SMS I have a long code that is provisioned for nultiple countries however the locale of the long code shows up in my account as GB. When I try sending to different countries i successfully get a token ID but messages are not sent. Is this even feasible? Locale for long Code is GB. Long code is provisioned for multiple countries. Send SMS triggered message below
Subscribers[
Mobile Number 44...,
Mobile Number 1317....


text:
Q: $\mathbb{T}^4/\mathbb{Z}_2$, $\mathbb{T}^2/\mathbb{Z}_2$, and $\mathbb{CP}^1$ I was stuck by reading this figure:
It looks that $\mathbb{T}^4/\mathbb{Z}_2$, $\mathbb{T}^2/\mathbb{Z}_2$, and $\mathbb{CP}^1$ are somehow related.
Are there some easier explanations from math directly?

It is a figure 2 in this ref: https://link.springer.com/content/pdf/10.1007%2FJHEP07%282017%29088.pdf


text:
Q: ¿Cómo modifico un campo de una base de datos utilizando una Api REST con Springboot? Tengo una Api REST para modificar y ver campos de una base de datos de MySQL server. Supongamos:
{
    "id_accounts": 1,
    "nombre_cliente": "Julio Herrera",
    "numero_cuenta": 2212112,
    "saldo_cuenta": "100.0",
    "estado_cuenta": "Activo"
}

Necesito modificar el "estado_cuenta" a "Inactivo" utilizando @DeleteMapping de Springboot, solo necesito modificar ese campo al llamar el delete.


text:
Q: IndexError: cannot choose from an emty sequence I'm trying to get random numbers from a list, but the numbers are only allowed to go up from the first number that was randomly chosen. It works fine the first time it loops but on the second loop it gives this errors:
Traceback (most recent call last): Num = random.choice(listNum)

and:
raise IndexError('Cannot choose from an empty sequence')

This is the code I use:
import random

listNum = list(range(100))

for n in range(100):
    Num = random.choice(listNum)
    print(Num)
    del listNum[0:Num]
    print(listNum)

A: When you do
del listNum[0:Num]

you delete all elements up to the index Num, except that after the first loop it's not doing exactly what you want, because it doesn't delete up to Num, but deletes Num elements, what you want is :
del listNum[0:listNum.index(Num)]

A: You should add try except, it will catch index error, and do stuff that will help you solve that error
for n in range(100):
    try:
        Num = random.choice(listNum)
        print(Num)
        del listNum[0:Num]
        print(listNum)
    except IndexError:  # this will handle only IndexError, don't use pure except
        break  # stop loop when there are no more numbers

some other smarter solutions would be:
while len(listNum):
   # do same stuff here
   # print number only when list has at least 1 element

also, remeber that your list is getting smaller, so you can not just del [0: Num]


text:
Q: How to set default value in ASP.NET Core? I am learning ASP.NET Core Web API, and it's using the System.Text.Json namespace instead of JSON.NET.
How to set the default value for the model binding?
Someone tells me that the [DefaultValue] attribute is not working anymore, is that correct?
If so what's the alternative option?

A: with latest c# you can do this.
public class Student
{
  public string name { get; set; } = "YourDefaultValue"
}

then you can use System.text.json to serialize. check below example.

A: Below is a demo, you can refer to it.
Student
public class Student
    {
      public string name { get; set; }
    }

ValuesController
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        [HttpGet]
        public string Get(string name="Tom")
        {
            return $"Hello {name}!";
        }
     }

Result:


text:
Q: how to get context of views in view container in angular In the following example, https://stackblitz.com/edit/angular-s8udwh
I have created EmbeddedViews in the ViewContainer. When creating the views, I pass a context object and when deleting the views, I use the context to find index of the view and delete it from the view container. This works fine.
I have added a button which when clicked should print the info of views currently in the container. I can find the length and views in the container using the APIs of ViewContainer but how do I get the context object from the views?
This is the function I am unable to write
printViewInfo(){
    //I want to get all the views which are currently in the container and print their context objects.
    let length = this.vc.length
    for(let i=0;i<length;i++){
      let view = this.vc.get(i);
      //how to get the context back here from view??
    }
  }

What is the way to find context of views in a ViewContainer? I see that get returns a ViewRef and the ViewRef doesn't contain context. But ViewContainerRef doesn't provide APIs which return an EmbeddedViewRef

A: I got this working by typecasting the ViewRef into EmbeddedViewRef<any>. Is this the right way? My concern is that if a ViewContainerRef contains both EmbeddedView and ComponentView then how will I distinguish between them? Or would it be a wrong design to use both EmbeddedView and ComponentView in the same ViewContainer?
printViewInfo(){
    //I want to get all the views which are currently in the container and print their context objects.
    let length = this.vc.length
    for(let i=0;i<length;i++){
      let view = <EmbeddedViewRef<any>> this.vc.get(i);
      //how to get the context back here from view??
      console.log("view.context.option ",view.context.option.description);
    }
  }


text:
Q: Inner Join from group by I have a table countries containing country codes and names:
name            code
FRANCE          FR
JAPAN           JP

And a table of page view stats views:
page_id    code            date    etc...
34         FR              2015-01-01
34         FR              2015-01-02
34         JP              2015-01-02

I'd like to output a list of all the countries that the page was seen in, but with the country name, so the results should say: FRANCE, JAPAN
I can easily get the list of country codes that it runs in:
SELECT code FROM views WHERE page_id = 34 GROUP BY code;

But mapping them across to the names in the countries table is the hard bit. Any ideas?
I've tried this, but it doesn't work:
SELECT
    countries.name as name_from_countries,
FROM
    countries
INNER JOIN name_from_countries ON countries.code = views.code
WHERE
    views.page_id = 34
GROUP BY
    views.code

A: You don't need GROUP BY here. Just use DISTINCT.
SELECT DISTINCT countries.name as name_from_countries
FROM countries
INNER JOIN views ON countries.code = views.code
WHERE
    views.page_id = 34

A: You need to add countries.name to your GROUP BY - I'm assuming you have some aggregates here:
SELECT v.code, c.name AS name_from_countries
  FROM views v INNER JOIN countries c
    ON v.code = c.code
 WHERE v.page_id = 34
 GROUP BY v.code, c.name;

If you don't have any aggregates (e.g., COUNT(*)), then you can get a list of countries with at least one view as follows:
SELECT c.code, c.name AS name_from_countries
  FROM countries c
 WHERE EXISTS ( SELECT 1 FROM views v
                 WHERE v.code = c.code
                   AND v.page_id = 34 );


text:
Q: jQuery regex input name with ascending number When #checkbox-subscribe-everything is clicked, I would like all inputs with names following the pattern below to become checked and unchecked alternately:
name=checkbox-subscribe-game,
name=checkbox-subscribe-game1,
name=checkbox-subscribe-game2,
name=checkbox-subscribe-game3 and so on...
Here's my current jQuery code with NUMBER as a placeholder:
$("#checkbox-subscribe-everything").click(function() {
    var checkBoxes = $("input[name=checkbox-subscribe-gameNUMBER]");
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});

How can I use a regular expression to match all inputs following that naming pattern?
Thanks

A: You can use attribute starts with selector:
$("#checkbox-subscribe-everything").change(function() {
    $("input[name^=checkbox-subscribe-game]").prop('checked', this.checked);
});

Since the selector is not very fast, if you are not creating the elements dynamically, you can also cache the object:
var $checkboxes = $("input[name^=checkbox-subscribe-game]");

$("#checkbox-subscribe-everything").change(function() {
    $checkboxes.prop('checked', this.checked);
});

A: How about something like : name^=checkbox...
cf http://api.jquery.com/attribute-starts-with-selector/

A: This is why I love jQuery selectors. Note the ^ in the name attribute selector.
http://api.jquery.com/attribute-starts-with-selector/
var checkBoxes = $("input[name^='checkbox-subscribe-game']");


text:
Q: change variable value with a dropdown menu I have created a pagination system, that shows 15 colums from a database.
now I want to add a drop down menu with other values, so I can change the pagination variable to 50 or 100.
I have done a javascript, but it wont work as I want to ;)  It only read the last value I give the script, And nothing happends when I change the dropdown.
Some of the script
$per_page = 15; // Shows how many colums it shows per page

My javascript
<script type="text/javascript">
function addit(){
    if(document.getElementById("add").value=="<?php $per_page = 15; ?>")
    {
        document.getElementById("amount").value="10"
    }
    if(document.getElementById("add")."<?php $per_page = 25; ?>")
    {
        document.getElementById("amount").value="25"
    }
    if(document.getElementById("add").value=="<?php $per_page = 50; ?>")
    {
        document.getElementById("amount").value="50"
    }
}
</script>

And the form
<form action=" " method="get">
<select style="width: 60px; font-size: 17px;" name="add" id="add" onChange="addit()">
<option value="X"> views</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</td>
</tr>

</tbody>
</table>
</form>

Any tips ?
thanks

A: You need to understand the different points where PHP Javascript are executed. PHP builds a HTML page on the server and then sends it to the browser, where any Javascript is executed.
Let's look at one line of your code:
if(document.getElementById("add").value=="<?php $per_page = 15; ?>")

The server will execute the PHP part. But $per_page = 15 does not output anything to the HTML result. So if you look at the result in the Browser (use "View Source"), it will look like this:
if(document.getElementById("add").value=="")

All three if statements in you Javascript will look like this, all the same.
Rethink your code from here. If the amount of elements per page is determined in the PHP part, you need to reload the page, somehow passing this parameter to the server, to tell it how many elements to put into the page.

A: PHP has already finished processing at the moment the page is sent to the browser, so you php assignments in your javascript will not do anything except assign a number before the page is sent to the browser.
What you need to do is:

*

*post the value of the changed javascript variable and your pagination variables back to the server / submit the form

*regenerate the page using the new value

*optionally use ajax to refresh only part of your page instead of doing a complete reload.

A: I would suggest your JS function does load the (same?) page with a GET parameter attached, to pass the items per page value. Maybe something like:
function addit(){
    var itemsPerPage = document.getElementById("add").value;
    location.href = 'url of your page' + '?ipp=' + itemsPerPage;
}

Then in your php part, catch the $_GET['ipp'] and use it to render your page according to the viewer's wish.
And then you can get rid of the <form>.

A: I dont think there is any need for Javascript here. You can just try:
Form:
<form action="process.php" method="get">
   <select style="width: 60px; font-size: 17px;" name="add">
        <option value="X" disabled>Views</option>
        <option value="10">10</option>
        <option value="25">25</option>
        <option value="50">50</option>
    </select>
</form>

Process.php could be:
$per_page = $_GET['add'];

//Code to display $per_page number of items..

For sure the PHP variable assigning on Client-side is not going to work ever. Because PHP can not be executed on Client-side. It has already finished executing and outputted the HTML at this point. Or you could use some Javascript Get query building & redirect.


text:
Q: How to put 'maxPadding' in HighCharts grafic with "stacking:percent" in YAxes? I want to put padding left for graphic "percent" in YAxes. I need one space after the bars. Look the code below.
'chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            inverted: true,
            type: 'column'
        },
    title: {
        text: 'Indicatores por Sexo'
    },

    xAxis: {
       categories: [
            'Jan',
            'Fev',
            'Mar',
            'Apr',
            'May',
           'Jun',
           'Jul',
           'Aug',
           'Sep',
           'Oct',
           'Nov',
           'Dez'
       ],
       title: {
           text: 'Meses'
       },
    },

    yAxis: {
        endOnTick: false,
        maxPadding: 5,
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Quantidade de Consultas'
        },
        stackLabels: {
            style: {
                color: 'black'
            },

            enabled: true,
            formatter: function() {
                return "Product A";
            }
        }
    },

    tooltip: {
        formatter: function() {
            return ''+ this.x +'
'+
                this.series.name +': '+ this.y +'
'+
                'Total: '+ this.point.stackTotal;
        }
    },

    plotOptions: {
        column: {
            stacking: 'percent'
        },
        series : {
            pointWidth: 10,
            minPointLength: 3,
        }
    },

    series: [{
        data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], //inclusoesExclusoesChequeFeminino[0]
        color: '#FF0000',
        stack: 0
    }, {
        data: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], //inclusoesExclusoesChequeMasculino[0]
        color: '#3333FF',
        stack: 0
    }, {
        data: [10, 20, 30, 40, 50, 60, 60, 50, 40, 30, 29, 10], //inclusoesExclusoesSPCFeminino[0]
        color: '#FF0000',
        stack: 1
    }]
});'

Thank you!

A: You can add a right margin to the chart, which will provide space for the label
http://api.highcharts.com/highcharts#chart.marginRight
Also - a column chart with 'inverted:true' is identical to a bar chart.  Why not just use type 'bar'?


text:
Q: buffer condition when fread hits eof The manual wasn't clear on the subject.
if I tell fread() to read from file 1 item of 1024 bytes each time (in a loop) and the last block is of size < 1024, I know that fread() will return 0.
But, is the buffer going to contain the remainder?

A: The Standards says:

7.21.8.1 The fread function
If a partial element is read, its value is indeterminate.

The element in this case is of size 1024 bytes and you read one element.
The element, entire block of 1024 bytes, will have an indeterminate value. Reading that value could cause undefined behavior.
And:

The fread function returns the number of elements successfully read, which may be
less than nmemb if a read error or end-of-file is encountered.

If you get a return value of 0, then zero elements were successfully read, another indicator that the element wasn't read correctly, and should not be used, as mentioned before.


text:
Q: Run Ubuntu Desktop 20.10 on Raspberry Pi 4 using OpenSSH I have installed Ubuntu Desktop 20.10 in my Raspberry Pi 4. I don't have any form of display to connect directly to raspberry pi.
I want to use Raspberry Pi using OpenSSH.
Is there a way to enable OpenSSH in the boot volume for Ubuntu Desktop similar to how it works for Ubuntu Server.
I even tried adding a file without an extension and naming it ssh in the boot volume, but still no luck.

A: Ubuntu Desktop does not include an ssh server. There is nothing installed for your magic file to activate.

*

*You must install openssh-server, which cannot be done headlessly on Ubuntu Desktop. It's trivial to install (sudo apt install openssh-server), it's simply not included with Ubuntu Desktop (most desktop users don't need it).
Remember to safely configure your ssh server to use keys. Password-protected ssh servers are strongly discouraged on internet-facing systems.

*Ubuntu Server is different: Server includes the ssh server out-of-the-box, and the new 21.04 server installer even helps you configure the ssh server securely.


text:
Q: Passing map object to javascript function In order to add an offset to the center point in Google maps when a button are pressed, I try this funcion:
function offsetCenter(map, marker) {

var worldCoordinateCenter = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point((100/scale) || 0,(0/scale) ||0)

var worldCoordinateNewCenter = new google.maps.Point(
    worldCoordinateCenter.x - pixelOffset.x,
    worldCoordinateCenter.y + pixelOffset.y
);

var newCenter = map.getProjection().fromPointToLatLng(worldCoordinateNewCenter);

map.setCenter(newCenter);

}

});

I call that funcion from infoWindows where map and marker are defined:
       (function(marker, data) {
              google.maps.event.addListener(marker, "click", function() {

            info = '
' + data.nombre + '

'+ data.offerta+'

'+ data.horario+'

Web
'
+ '<input type="button" class = "launchConfirm" onclick="offsetCenter(\''+map+'\', \''+marker+'\');" value='Reset center'></input>'  //this is the button inside the infowindos to re-set the map center with an offset
        ;

        infoWindow.setContent(info);
        infoWindow.open(map, marker);

        map.setCenter(marker.getPosition());   //center the map to marker
        map.setZoom(16);                       //zoom to marker

         });
      }

But marker and map object are not defined inside the offsetCenter function.
How can pass a map object and marker to that function?

A: *

*make sure your 'map' variable and your marker manager are in scope >= function scope.  this way you will not need to pass in the map.

*Use a marker manager to manage your makers. you can then add a unique id to some attribute on your link. when the click comes in you can access the object to get the id, which will allow you to retrieve the maker from the manager. so the code would look something like this:
Info Window Content(shortened for brevity):
var info = '
' + data.nombre + '
'<input type="button" data-markerId="' + SomeMarkerManager.getMarkerId() '" onclick="offsetCenter(this);" value='Reset center'></input>'

var offsetCenter = function (element) {
  // get the marker Id
  var markerId = $(element).attr("data-marker-id");

  // use the markerId to find your marker
  var marker = SomeMarkerManager.getMarkerById(markerId);

  // now you have access to your map and the clicked marker
}

P.S.
marker managers are out of the scope of this answer.  Just search for google maps marker managers.


text:
Q: how to find tab close and clear local storage I am using onbeforeunload function in javascript but problem is that if browser is refresh then also clear local storage . I want to only clear local storage when browser close not refresh browser
window.onbeforeunload = function(e) {
        localStorage.setItem('isLoggedIn', 'false');
      };

A: You can use sessionStorage instead. It is automatically cleared when the browser is closed.
Example:
sessionStorage.setItem("isLoggedIn","true"); // Value will be set to null when browser is closed

A: You can be needed to learn about local storage, session storage, and Cookies. there are 3 options use for store data but it's one of the different another concept.

*

*local storage store locally and it's permanent if you not remove this or clear browser.

*session storage use for containing a status or a token or a user some information.

*when you close the browser then session storage remove automatically. (note: if you went any running time you can change it like as logout).

*Cookies is another powerful way to store data in the browser or client site. it also allows the time schedule or date. when expiring time or date then it's destroyed automatically.

there are 3 storage are the different their concept and work it's also different storage capacity each other.

Session storage operation:
sessionStorage.SessionName = "SessionData" ,

sessionStorage.getItem("SessionName") and

sessionStorage.setItem("SessionName","SessionData");

Cookie example simple operation:

you can also learn about more:
https://www.quora.com/What-is-the-difference-between-sessionstorage-localstorage-and-Cookies
https://developer.mozilla.org/en-US/docs/Mozilla/Gecko/DOM_Storage_implementation_notes
https://www.w3schools.com/js/js_cookies.asp
=== Thanks ===


text:
Q: Prevent viewcontroller being reset - UINavcontroller + Storyboard + Segue's I need some help in picking the 'right' solution for the following 'problem'.
I use the new storyboard feature to link all the screens of my application together. Basically the structure drills down to:
[Navigation Controller] => [View Controller #1] => [Tabbar Controller] => [View Controller #2]*
**(and some other tabs which are for now not important)*
I have attached a segue (push) from the first View Controller (#1) to the View Controller behind the Tab Bar Controller. This push is triggered when the users presses something on the first controller and works fine.
// Execute preset segue
[self performSegueWithIdentifier:@"segueEventDetail" sender:self];

When the user (which is now in the View Controller #2) presses the back button in the navbar the user goes back. Suppose he now triggers the segue again, the second view controller is shown again but is now 'resetted' (empty). (I believe after reading several fora and articles this is standard behavior when using segue's because these destroy and reinitiliaze the view controller's every time?)
This (the view controller being resetted) poses a problem because the contents of the second view controller is dynamic (depend on a JSON response from the server) and thus it is 'needed' that the view controller remains intact (or is restored) when the user comes back.
I have found several sources (see bottom) describing the same issue, but the solutions vary and I need some help picking the right one.
Summarize:

*

*How can I 'retain'/save the state of a View Controller when the users presses back, while preserving the use of Storyboard & preferably also Segue's

Own Thoughts:
#1 I'm now thinking of caching the JSON Response to my singleton class (and from there to a PLIST) and checking within the second view controller if this data is present and than rebuild the view after which I check for any new data (resume normal operation).
#2 Another one I'm thinking of is 'bypassing' the segue and manually handle the switch of views , partially explained in (Storyboard - refer to ViewController in AppDelegate) - Is this also possible?
But maybe there is an easier/better option?
http://www.iphonedevsdk.com/forum/iphone-sdk-development/93913-retaining-data-when-using-storyboards.html
Storyboard - refer to ViewController in AppDelegate
How to serialize a UIView?

A: Yess!! I got the solution. Do the following:
In you're .h file:
@property (strong, nonatomic) UITabBarController *tabController;

In you're .m file:
@synthesize tabController;

tabController = [self.storyboard instantiateViewControllerWithIdentifier:@"tabbar"];

The selected index is the tab you want to go
tabController.selectedIndex = 1;

[[self navigationController] pushViewController:tabController animated:YES];

A: For anyone coming across this (my) question in the future, this is how I ended up 'coding' it.

*

*Open the storyboard and select your 'Tab Bar Controller' and open the Attributes Inspector

*Fill in an 'identifier' in the field

*With the first view controller (see scenario in original post) I create an global reference to the viewcontroller:
firstviewcontroller.h
@interface YourViewController : UIViewController {

    UITabBarController *tabController;

}

firstviewcontroller.m
//Fill the reference to the tabcontroller using the identifier
tabController = [self.storyboard instantiateViewControllerWithIdentifier:@"tabbar"];

Now to switch from the firstviewcontroller the following line can be used:
[[self navigationController] pushViewController:tabController animated:YES];

A: This might be even more simple solution (without using properties - in fact, all your class instances don't need to know about their destination controllers, so just save it as static in the pushing function):
static UIVewController *destController = nil;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
if (!storyboard) {
    DLog(Storyboard not found);
    return;
}
if (destController == nil) { //first initialisation of destController
    destController = [storyboard instantiateViewControllerWithIdentifier:@"{Your Destination controller identifyer}"];
    if(!destController) {
        DLog(destController not found)
        return;
    }
}
//set any additional destController's properties;
[self.navigationController pushViewController:destController animated:YES];

p.s. DLog is just my variation of NSLog.
But it's really interesting how to do this with segue?


text:
Q: jQuery Confirm box to leave or remain on a page I have an MVC2 C#.Net web app. When a user attempts to leave a view, I want to pop up a confirm box to alert them that they have made changes but not yet saved.
In a previous .Net 3.5 app, I used window.onbeforeunload. That doesn't seem to work in MVC3. What would be an appropriate place or event to call to do this type of activity?

A: Here's the answer I came up with.  When I first ran the below code, I got two pop ups; one for my confirm box and one for the standard windows OK/Cancel box.  That was a case of me not knowing how the event worked:

    window.onbeforeunload = function () {
        if (document.title.indexOf("*") != -1) {
            confirm("You have unsaved changes...");
        }
    }

After this I tried the following code.  What happened was the standard windows OK/Cancel box showed with the "You have unsaved changes..." prompt.  This is a satisfactory solution
window.onbeforeunload = function () {
    if (document.title.indexOf("*") != -1) {
        return "You have unsaved changes...";
    }
}


text:
Q: R: Error: new columns would leave holes after existing columns When running this code, I get the following error:
Error in `[<-.data.frame`(`*tmp*`, , i, value = list(x = 0.0654882985934691,  :
new columns would leave holes after existing columns

I am trying to populate a data.frame with i number of columns, which with the output of the posted for loop should look like something like this (Excel example for convenience only):

The aim is to store the output of the loop in such a way that I can get the average of each column at a later stage.
What can be done to achieve this?
library(plyr)
library(forecast)
library(vars)

x <- rnorm(70)
y <- rnorm(70)

dx <- cbind(x,y)
dx <- as.ts(dx)

# Forecast Accuracy
j = 12  #Forecast horizon
k = nrow(dx)-j #length of minimum training set

prediction <- data.frame()

for (i in 1:j) {
  trainingset <- window(dx, end = k+i-1)
  testset <- window(dx, start = k+i, end = k+j)
  fit <- VAR(trainingset, p = 2)
  fcast <- forecast(fit, h = j-i+1)
  fcastmean <- do.call('cbind', fcast[['mean']])
  fcastmean <- as.data.frame(fcastmean)

  prediction[,i] <- rbind(fcastmean[,1])
 }

Edit
As per the comment below, I have edited the above code to specify the first variable of fcastmean.
The error I get has however changed as a result, now being:
Error in `[<-.data.frame`(`*tmp*`, , i, value = c(-0.316529962287372,  :
  replacement has 1 row, data has 0

Edit 2
Below is the minimum replicable version without any packages as requested in the comments. I believe that should be equivalent in terms of the question posed.
x <- rnorm(70)
y <- rnorm(70)

dx <- cbind(x,y)
dx <- as.ts(dx)

j = 12
k = nrow(dx)-j

prediction <- matrix(NA,j,j)

 for (i in 1:j) {

  fcast <- as.matrix(1:(j-i+1))
  fcastmean <- fcast

  prediction[,i] <- (fcastmean)
}

A: For your new example, try
sapply(1:j, function(i) `length<-`(1:(j-i+1), j))

The result is
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
 [1,]    1    1    1    1    1    1    1    1    1     1     1     1
 [2,]    2    2    2    2    2    2    2    2    2     2     2    NA
 [3,]    3    3    3    3    3    3    3    3    3     3    NA    NA
 [4,]    4    4    4    4    4    4    4    4    4    NA    NA    NA
 [5,]    5    5    5    5    5    5    5    5   NA    NA    NA    NA
 [6,]    6    6    6    6    6    6    6   NA   NA    NA    NA    NA
 [7,]    7    7    7    7    7    7   NA   NA   NA    NA    NA    NA
 [8,]    8    8    8    8    8   NA   NA   NA   NA    NA    NA    NA
 [9,]    9    9    9    9   NA   NA   NA   NA   NA    NA    NA    NA
[10,]   10   10   10   NA   NA   NA   NA   NA   NA    NA    NA    NA
[11,]   11   11   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA
[12,]   12   NA   NA   NA   NA   NA   NA   NA   NA    NA    NA    NA

`length<-`(x, j) pads x with NA until it reaches a length of j.

You can replace 1:(j-i+1) with whatever function of i you want. In the OP's original example, I am guessing something like this will work (untested):
sapply(1:j, function(i){

  trainingset <- window(dx, end = k+i-1)
  # testset   <- window(dx, start = k+i, end = k+j)
  # ^ this isn't actually used...

  fit         <- VAR(trainingset, p = 2)
  fcast       <- forecast(fit, h = j-i+1)
  `length<-`(fcast$mean, j)

})

function(i){...} is called an anonymous function and can be written like any other.


text:
Q: You must feed a value for placeholder tensor I am trying to implement an lstm nn using tesorboarb and I am receiving this error message: You must feed a value for placeholder tensor 'performance_1/loss_summary'.
I have already searched for an answer in many question without result.
with tf.name_scope('performance'):
loss = tf.placeholder(tf.float32,shape=None,name='loss_summary')
    tf_loss_summary = tf.summary.scalar('loss', loss)
    tf_accuracy_ph = tf.placeholder(tf.float32,shape=None, name='accuracy_summary')
    tf_accuracy_summary = tf.summary.scalar('accuracy', tf_accuracy_ph)

# Gradient norm summary
for g in gradients:
for var in v:
    if 'hidden3' in var.name and 'w' in var.name:
        with tf.name_scope('Gradients'):
            tf_last_grad_norm = tf.sqrt(tf.reduce_mean(g**2))
            tf_gradnorm_summary = tf.summary.scalar('grad_norm', tf_last_grad_norm)
            break

# Merge all summaries together
performance_summaries = tf.summary.merge([tf_loss_summary,tf_accuracy_summary])

The other part of the code in which I get the error is:
for ep in range(epochs):

for step in range(train_seq_length//batch_size):

    u_data, u_labels = data_gen.unroll_batches()

    feed_dict = {}
    for ui,(dat,lbl) in enumerate(zip(u_data,u_labels)):
        feed_dict[train_inputs[ui]] = dat.reshape(-1,1)
        feed_dict[train_outputs[ui]] = lbl.reshape(-1,1)

    feed_dict.update({tf_learning_rate: 0.0001, tf_min_learning_rate:0.000001})

    _, l = session.run([optimizer, loss], feed_dict=feed_dict)

    average_loss += l

if (ep+1) % valid_summary == 0:

    average_loss = average_loss/(valid_summary*(train_seq_length//batch_size))

  # The average loss
    if (ep+1)%valid_summary==0:
        print('Average loss at step %d: %f' % (ep+1, average_loss))

    train_mse_ot.append(average_loss)

    average_loss = 0 # reset loss

    predictions_seq = []

    mse_test_loss_seq = []

Thank you in advance.

A: loss is a placeholder, so you have to give a value to it. You probably didn't notice it and overrode your actual loss function. Usually summaries are not placeholders, so you have a misunderstanding of your variables and the flow in you code.

A: Initiliaze loss as a variable. When you define something as a placeholder, you have to feed it's value when running the graph dependent on it.


text:
Q: PostgreSQL query select records with highest count I have a table we will call authors.
authors has many blog_posts and has many articles.
Both blog_posts and articles have a column state
I need to write a query that gets the top x amount of authors by the highest total blog_posts and articles combined where the state is equal to open
I've come up with this so far
WITH blog_post_count AS (
    SELECT author_id, count(id) as num_open_blog_posts
    FROM  blog_posts
    WHERE state = 'open'
    GROUP BY author_id
),
article_count AS (
    SELECT author_id, count(id) as num_open_articles
    FROM articles
    WHERE state = 'open'
    GROUP BY author_id
)
SELECT *, (
            CASE WHEN num_open_blog_posts IS NULL THEN 0 ELSE num_open_blog_posts END
            + CASE WHEN num_open_articles IS NULL THEN 0 ELSE num_open_articles END) as total_postings
    FROM authors
    LEFT OUTER JOIN blog_post_count ON blog_post_count.author_id = authors.id
    LEFT OUTER JOIN article_count ON article_count.author_id = authors.id
    ORDER BY total_postings DESC
    LIMIT 25 -- could be any value

^works but I'm sure it could be improved alot

A: How about using UNION ALL ?
WITH total_post_count AS (
  SELECT
    author_id
  FROM
    blog_posts
  WHERE
    state = 'open'
  UNION ALL
  SELECT
    author_id
  FROM
    articles
  WHERE
    state = 'open'
)
SELECT
  author_id,
  count(*) as total_posts
FROM
  total_post_count
GROUP BY
  author_id
ORDER BY
  total_posts DESC
LIMIT 25


text:
Q: Getting strange filenames when cloning a repository using TortoiseGit Hi I've been using Tortoise to clone a repository from a friends site - For some reason even though I can see all the files they are 0kb and all end in .i - so for instance index.php is now index.php.i
Can anyone explain what has happened with the clone - did I make a mistake on setting it up?

A: Fixed : deleted & re-cloned and all seemed to work with the files.


text: Q: Highlight text using query value in Griddle table I have data in griddle table. I am entering search string through custom filter box. I want to highlight search string value in griddle columns . How is it possible ? I want to achieve this in reacthttps://jsfiddle.net/julmot/buh9h2r8/"


text:
Q: Symfony 3.4 : how to log the history of user actions? I want to store in my database all the user actions done about an entity.
For example, for 1 entity, I want to store :

*

*Created by (= author)

*Updated by

*Date of creation

*Date of update

I want to store the history of the actions of a user, not the last ones. I thought I could create a table with these columns :

*

*log_id

*user_id

*entity_id

*action (= "create" or "update" or something else)

*date

And then, I could easily get the last update of my entity and display the date and the user who did it.
Is there a Symfony bundle to do this ? Should I use Monolog ?
I will do this for many entities and I'm not sure if this is the correct way to do...
Is it possible to create only one logs table to store each log about each entity ? It bothers me to create 1 logs table per entity.

A: Since Doctrine is event based, it's easy:

*

*Either use an extension, like Gedmo Loggable

*Or hook into Doctrine's events and log, using Monolog, everything that happens in your app.
Personally I would prefer option 2 since I'm a control maniac, it's a little more complex though. Personally I would also use Monolog so I could abstract away the way how and where the log entries are stored.
When you decide how to approach this and you will need any assistance along the way, please ask another question.
Good luck.

A: I don't know if that would fit what you need, but you could easily add a Listener to the symfony kernel to log every controller used.
Something like this :
class UserLogListener {

    protected $authChecker;
    protected $tokenStorage;
    protected $entityManager;

    public function __construct(TokenStorageInterface  $tokenStorage, AuthorizationChecker $authChecker, EntityManager $entityManager)
    {
        $this->authChecker = $authChecker;
        $this->tokenStorage = $tokenStorage;
        $this->entityManager = $entityManager;

    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if( $this->tokenStorage->getToken() != null){
            $user = $this->tokenStorage->getToken()->getUser();
            $currentDate = new \Datetime();
            $action = $event->getRequest()->attributes->get('_controller');
            $method =  $event->getRequest()->getMethod();
            $userIp =  $event->getRequest()->getClientIp();
            $userLogRepository = $this->entityManager->getRepository(UserLog::class);

            if($user instanceof User){
                $userLog = new UserLog();
                $userLog->setUser($user);
                $userLog->setIp($userIp);
                $userLog->setAction($action);
                $userLog->setMethode($method);
                $userLog->setDate($currentDate);
                if($event->getRequest()->request && $methode=='POST'){
                    $userLog->setData(json_encode($event->getRequest()->request->all()));
                }else{
                    $userLog->setData($event->getRequest()->getPathInfo());
                }
                $this->entityManager->persist($userLog);
                $this->entityManager->flush();
            }
        }

    }
}

What it does is add to the database (with an entity called UserLog) information about every page called. So you can know which action is made by knowing which controller is called, and you can also log the request data so you can find out what modification/creation the user did.


text:
Q: Count variable in one data.table for each category in a different data.frame R If I have a data.table:
  a <- data.table("NAME" = c("A", "B", "A"),
                  "PASS_FAIL" = c("F", "P", "P"))

And a data.frame (which is a frequency table for number of times each unique NAME shows up in table a:
b <- aggregate(data.frame(Count = a$NAME), list(Name = a$NAME), length)

So b looks like this:
> b
  Name Count
1    A     2
2    B     1

How do I now add a new column to table b that counts the number of F for each unique NAME? Expected output:
> b
  Name    Count    FailCount
1 A       2        1
2 B       1        0

I know I need something to the effect of a$PASS_FAIL == "F".

A: With data.table, grouped by 'NAME', get the count of rows with .N and sum of the logical expression (PASS_FAIL == "F") for the number of fail cases
library(data.table)
a[, .(Count = .N, FailCount = sum(PASS_FAIL=="F")), NAME]
#    NAME Count FailCount
#1:    A     2         1
#2:    B     1         0

If we need a base R method
merge(b, aggregate(cbind(FailCount = PASS_FAIL == "F") ~ NAME, a, sum),
             by.x = 'Name', by.y = 'NAME')


text:
Q: Cannot load a User Control to Tool Box When we add a user control dll to the Tool Box of Visual Studio, We are getting the following error message. The issue occurs in WinXP 64 bit. The user control refers a module named ICEConnect200Bridge. The assembly ICEConnect200Bridge is a C++ CLI module. The user control was built using 'Any CPU' platform.
What build option should I give for ICEConnect200Bridge?
What should I do to identify the exact cause of the issue?
Could not load file or assembly 'ICEConnect200Bridge, Version=1.2.6.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format

A: When building ICEConnect200Bridge, put the target specifically to x86 instead of Any CPU. Visual Studio is compiled for x86 and installed in Program Files (x86) and does not accept controls in its toolbox that are not explicitly compiled for the same target.


text:
Q: Linking a Webpage to a Button in Android I am making an android project.. and I want to be able to click a button and it will bring me directly to a webpage.
Sorry for the little information, but I really have no idea how to do it.
For the button, this is the xml code I have..
I'm not sure If I have to code in the xml or the MainActivity file..
<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="30dp"
    android:text="@string/socs_button"
    android:textColor="#0000CD"
    android:textSize="20sp"/>

A: Add the following to your button xml
android:onClick="openSite"

In the controlling actvity Java
public void openSite(View v){
    Uri uri = Uri.parse("http://myurl");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

A: Try this..
Button button2 = (Button) dialog.findViewById(R.id.button2);
    button2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("your site name"));
            startActivity(intent);
        }
    });


text:
Q: nlme::lmList and stargazer? I'm trying to use stargazer to format output from the lmList function in the nlme package. I can get stargazer to work if I manually index each list element, but not if I just pass stargazer the full list. Any suggestions for how I can get stargazer to recognize the lmList output?
library(nlme)
library(stargazer)
data("iris")
m <- lmList(Sepal.Length ~ Sepal.Width | Species, data = iris)
stargazer(m, type = "text") # "% Error: Unrecognized object type.
stargazer(m[[1]], m[[2]], m[[3]], type = "text")

A: You need to package all arguments to stargazer as a list and then get stargazer to accept a list of arguments. The magic function to do this is do.call.
do.call's first argument is the function and the second argument is the list of arguments to pass to that function in the first argument.
So something like this should work:
do.call(stargazer, c(m, type = "text"))

Also FYI the tidyverse version of do.call is invoke so this is the same.
invoke(stargazer, c(m, type = "text"))

Invoke will be nicer because you can pass additional arguments (like type above) without putting them in the list.


text:
Q: can netbeans learn php custom function arguments of class? I have:
class myClass {
  function test($arg1,$arg2) {
    echo $arg1 & $arg2;
  }
}

$m = new myClass();
//can I use any kind of annotation to get argument-list of
$m->test(|

//ADD//
I guess Netbeans doesn't natively understand that m = myClass, so something like
$m = newClass();
/* @ var m = class newClass */
/* now nb can list the args when typing.. */
$m->test(

regards

A: If you want notes for each of the arguments, use phpdoc commenting (which NetBeans completes for you automagiaclly):
Just type
/**

on the line above your function definition and hit the enter key. NetBeans will automatically write your phpdoc comments in the space above your function. If you have a return in your function, phpdoc will be written for that as well:
/**
 *
 * @param type $arg1
 * @param type $arg2
 * @return type
 */
function myFunc($arg1, $arg2) {
    $test = "";
    return $test;
}

Then you just replace type with the data type of the parameter, and add notes after the parameter name.

A: found [ctrl] + [space] down the road, at
$m->test|


text:
Q: DeleteItemAsync is not returned the item being deleted Container.DeleteItemAsync returns an ItemResponse<T> that holds a Resource property. This implies that the call will return the document that is actually deleted.
But the Resource property is always null and the status is set to NoContent, so it seems that this call never returns the document that is actually deleted. Why would it return a typed response, when it never returns an instance of the type. Also this MS blog describes how the response can explicitly be disabled when deleting documents. This also implies that the item should be deleted.
I have checked the database, but the document is actually being deleted. Trying to delete a non-existing document results in a NotFound status and raises an exception.
I have also tried setting EnableContentResponseOnWrite = true, but this doesn't do anything. I tried Microsoft.Azure.Cosmos v3.14 and v3.19. Both had the same result...

A: The DeleteItemAsync return type is a bit misleading given that ItemResponse<T> suggests a populated T with the deleted item but is actually null.
Perhaps a clearer approach is to use DeleteItemStreamAsync and inspect the response code, like this:
using ResponseMessage response = await container.DeleteItemStreamAsync(itemId, new(partitionKey), options);
if (response.StatusCode == HttpStatusCode.NoContent)
{
    // Success
}
else
{
    // Failed
}

Now you avoid exception-throwing overhead, and the code doesn't mislead about content being non-null.


text:
Q: how to increase the size of existing rootfs folder in Google Compute Engine disk How to increase the size of the disk in Google Compute Engine after instance is crested .
We have created the instance of VM with 10gb hard disc.Later to increase the disk size we have added a new disk with 200gb to the previous 10gb disk which is up and running.
we have mounted the 200gb with 10gb disk and it is shown in as /dev/sdb when df -h command is given.
When we tried to run a software , it has filled the rootfs folder of 10 gb  and the installation failed due to low disk space ( the rootfs folder is occupied 100%).
We tried to run resize2fs command, but it says that the size is already reached.
the command trace is as below :
xxxxxxxxx_gmail_c@pgg-2:/home/xxxxx/opt/pgg/scripts$ sudo resize2fs /dev/sdb
resize2fs 1.42.5 (29-Jul-2012)
The filesystem is already 52428800 blocks long.  Nothing to do!
xxxxxxxxx_gmail_c@pega-2:/home/xxxxx/opt/pgg/scripts$ sudo resize2fs /dev/sdb 20G
resize2fs 1.42.5 (29-Jul-2012)
Filesystem at /dev/sdb is mounted on /mnt/pd1; on-line resizing required
resize2fs: On-line shrinking not supported
Help required in incresing the rootfs size so that we can continue the installation.
Also Can we merge the two disks so that it will treated as 210gb (logically) instead of 10gb + 200gb.

A: In this case, since the VM instance is in production and there are some files and data that need to be protected, the first step is taking a snapshot of the disk. This will create a backup of the disk and can be useful for recreating a persistent disk that might have been damaged or lost.
Creating a disk snapshot can be easily done though Google Developer Console or using the command below:
$ gcloud compute disks snapshot DISK

After creating snapshot, you can create a larger disk (as an example 200GB) from the snapshot by the command below:
$ gcloud compute disks create <newdiskname> --source-snapshot=<my-data-disk-snapshot> --size=200GB

Now you can re-partition the new disk by going through 'Step 3' to 'Step 15' of 'Repartitioning a root persistent disk' artcile. Manual re-partitioning may not be needed for the GCE operating systems which support automatic resizing.

A: You need to choose a directory to mount the new disks filesystem at.  You'll probably need to position and format the disk first, then mount the new filesystem and chippy file from the existing drive to the new drive.
Here's a guide on how to do that:
https://muffinresearch.co.uk/adding-more-disk-space-to-a-linux-virtual-machine/
Depending, you might also want to start over with a larger root drive by following these instructions:
https://cloud.google.com/compute/docs/disks#repartitionrootpd

A: just follow these steps
https://developers.google.com/compute/docs/disks#creatingrootpd
I hope it helps.


text:
Q: which tokenizer is better to be used with nltk I have started learning nltk and following this tutorial. First we use the built-in tokenizer by using sent_tokenize and later we use PunktSentenceTokenizer. The tutorial mentions that PunktSentenceTokenizer is capable of unsupervised machine learning.
So does that mean it is better than the default one? Or what is the standard of comparison among various tokenizers?

A: Sentences and words are often manually tokenized. There exist various corpora that deal with POS tagging for words according to the sentence contexts. PunktSentenceTokenizer is employed when your data(sentences and words) needs to be trained to achieve a uniform understanding of how the words should be tagged contextually. It could be possible that the data scientist manually annotates words tags for a whole bunch of sentences and then tells the machine to learn them(supervised learning). However, PunktSentenceTokenizer employs ML algorithms to learn these tags on its own (unsupervised).You just choose which data it trains upon.
Depending on the data you are the working with, the results of sent_tokenizeand consequently word_tokenize may not be that different from PunktSentenceTokenizer. Choosing between tokenizers is left upto the data scientist but the standard is always compared against manually annotated tags(because they are the most correct tags).

A: Looking at the source code for sent_tokenize() reveals that this method currently uses the pre-trained punkt tokenizer, so it is the equivalent to PunktSentenceTokenizer. Whether or not you will need to retrain your tokenizer depends on the nature of the text you are working with. If it is nothing too exotic, like newspaper articles, then you will likely find the pre-trained tokenizer to be sufficient. Tokenizing boils down to a categorization task, and thus different tokenizers could be compared by using the typical metrics such as precision, recall, f-score etc. on labelled data.
The punkt tokenizer is based on the work published in the following paper:
http://www.mitpressjournals.org/doi/abs/10.1162/coli.2006.32.4.485#.V2ouLXUrLeQ
It is fundamentally a heuristic based approach geared to disambiguating sentence boundaries from abbreviations - the bane of sentence tokenization. Calling it a heuristic approach is not meant to be disparaging. I have used the built-in sentence tokenizer before and it worked fine for what I was doing, of course, my task did not really depend on accurate sentence tokenizing. Or rather, I was able to throw enough data at it where it did not really matter.
Here is an example of a question on SO where a user found the pre-trained tokenizer lacking, and needed to train a new one:
How to tweak the NLTK sentence tokenizer
The text in question was Moby Dick, and the odd sentence structure was tripping up the tokenizer. Some examples of where you might need to train your own tokenizer are social media (e.g. twitter) or technical literature with lots of strange abbreviations not encountered by the pre-trained tokenizer.


text:
Q: How to read timestamp from uint64 I want to read and display a timestamp in mseconds since epoch , which was send from a client application. My code looks like this:
QDateTime timestamp;

timestamp.fromMSecsSinceEpoch(dataBody.timeStamp);
out << "Time Stamp:" + timestamp.toString(Qt::SystemLocaleShortDate) + "\n";

However, the output is "Time Stamp:", and system says that timestamp is invalid.
What is wrong with my code?

A: Your code shouldn't even compile because QDateTime::fromMSecsSinceEpoch is a static function. Correct usage:
QDateTime timestamp = QDateTime::fromMSecsSinceEpoch(dataBody.timeStamp);


text:
Q: android list all folders that has an image As part of my app i need to have file browser that lists only specific folders.
For eg list only those folders in the path that an image file in any of its subfolders in any level.
I could do it using recursion. But it affects performance. Especially finding folders at top level need many recursive calls. Is there a better way to do it
Please see my code below
public List<GeneralFileItem> getGridItemsList(String root) {
    List<GeneralFileItem> gridItemsList = new ArrayList<GeneralFileItem>();
    File file;
    file = new File(root);
    File list[] = file.listFiles();
    if (list.length == 0) {
        return null;
    }
    for (int i = 0; i < list.length; i++) {
        GeneralFileItem item = new GeneralFileItem();
        File temp_file = new File(file.getAbsolutePath(), list[i].getName());
        if (hasPhoto(temp_file)) {
            item.setPath(file.getAbsolutePath() + "/" + list[i].getName());
            item.setName(list[i].getName());
            if (temp_file.listFiles() != null) {
                item.setType(GeneralFileItem.DIRECTORY_TYPE);
            } else {
                item.setType(GeneralFileItem.FILE_TYPE);
            }
            gridItemsList.add(item);
            //Log.i(TAG,"added"+list[i].getName());
        }
    }
    return gridItemsList;

}

private boolean hasPhoto(File temp_file) {
    //Log.i(TAG,temp_file.getName());

    if (temp_file.listFiles() == null) {
        if (temp_file.getName().toUpperCase().endsWith(("JPG"))) {
            //Log.i(TAG,temp_file.getName()+ "is a photo");
            return true;
        } else
            return false;

    }
    else{
        File list[] = temp_file.listFiles();

        for (int i = 0; i < list.length; i++) {
            if(hasPhoto(list[i]))
                return true;
        }

    }

    return false;
}

I want to know if there is any other way than recursive search. How are the files maintained in Android.  I know that various file systems are supported and it varies from hardware manufaturer . I would like to know if there is a way like if there is FileTable from which i can get all .jpg files .

A: use FilenameFilter to search for specirfic type of files.
presently you are checking only current directory.However if you wish to search recursively then you will have to check if each file found is a directory or not
Your algo would be something like
File file;
file = new File(root);
File list[] = file.listFiles();
if (list.length == 0) {
    return null;
}
for (int i = 0; i < list.length; i++) {
     if(list[i].isDirectory()){
        //Then go inside it to search for specific file
        File subList[] = list[i].listFiles();
        //search for jpg..
        }else if("is this jpg"){
         //Add to list
        }
     }

To simplify this you could segregate these into methods as per your requirement.

A: Here's something I came up! It works like a charm!
First you must create a File, this one is root of SD card
File = rootPrimary = new File(Environment.getExternalStorageDirectory());

than you must list all the files in to a File []
File[] fileArray = rootDirectory.listFiles();

Then you create a ArrayList and set it equal to a method i've created and pass the File[] in.
ArrayList<File> alFolders = new ArrayList<File>();
        alFolder = putImgFldr(fileArray);

This method will add all dorectoryes that contain images with .jpg and .png extension.
private ArrayList<File> putImgFldr(File[] fileArray) {
        // TODO Auto-generated method stub
        ArrayList<File> a = new ArrayList<File>();

        for (int i = 0; i < fileArray.length; i++) {
            if (fileArray[i].isDirectory()) {
                //if file is folder pass that file trough this method
                a.addAll(putImgFldr(fileArray[i].listFiles()));
            } else if (fileArray[i].getAbsolutePath().endsWith(".jpg") || fileArray[i].getAbsolutePath().endsWith(".png")) {
                // if file is img ad it's parent, folder to ArrayList
                a.add(fileArray[i].getParentFile());
                // this finishes the file searching
                // because the image has allready bean found
                i = fileArray.length + 1;
            }
        }
        return a;
    }

now You can add another File [] to alFolders if nessesery
alFolders.addAll(putImgFldr(secFileArray));

A: One more example of listing files and directories using Java 8 filter. For instance, here I am using just jpeg images
public static void main(String[] args) {

System.out.println("Files!!");
        try {
            Files.walk(Paths.get("."))
                    .filter(Files::isRegularFile)
                    .filter(c ->
                            c.getFileName().toString().substring(c.getFileName().toString().length()-4).contains(".jpg")
                            ||
                            c.getFileName().toString().substring(c.getFileName().toString().length()-5).contains(".jpeg")
                    )
                    .forEach(System.out::println);

        } catch (IOException e) {
        System.out.println("No jpeg or jpg files");
        }

        System.out.println("\nDirectories!!\n");
        try {
            Files.walk(Paths.get("."))
                    .filter(Files::isDirectory)
                    .forEach(System.out::println);

        } catch (IOException e) {
            System.out.println("No Jpeg files");
        }
}


text:
Q: PHP script to extract artist & title from Shoutcast/Icecast stream I found a script which can extract the artist & title name from an Icecast or Shoutcast stream.
I want the script to update automatically when a song changed, at the moment its working only when i execute it. I'm new to PHP so any help will be appreciated.
Thanks!
define('CRLF', "\r\n");

class streaminfo{
public $valid = false;
public $useragent = 'Winamp 2.81';

protected $headers = array();
protected $metadata = array();

public function __construct($location){
    $errno = $errstr = '';
    $t = parse_url($location);
    $sock = fsockopen($t['host'], $t['port'], $errno, $errstr, 5);
    $path = isset($t['path'])?$t['path']:'/';
    if ($sock){
        $request = 'GET '.$path.' HTTP/1.0' . CRLF .
            'Host: ' . $t['host'] . CRLF .
            'Connection: Close' . CRLF .
            'User-Agent: ' . $this->useragent . CRLF .
            'Accept: */*' . CRLF .
            'icy-metadata: 1'.CRLF.
            'icy-prebuffer: 65536'.CRLF.
            (isset($t['user'])?'Authorization: Basic '.base64_encode($t['user'].':'.$t['pass']).CRLF:'').
            'X-TipOfTheDay: Winamp "Classic" rulez all of them.' . CRLF . CRLF;
        if (fwrite($sock, $request)){
            $theaders = $line = '';
            while (!feof($sock)){
                $line = fgets($sock, 4096);
                if('' == trim($line)){
                    break;
                }
                $theaders .= $line;
            }
            $theaders = explode(CRLF, $theaders);
            foreach ($theaders as $header){
                $t = explode(':', $header);
                if (isset($t[0]) && trim($t[0]) != ''){
                    $name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
                    array_shift($t);
                    $value = trim(implode(':', $t));
                    if ($value != ''){
                        if (is_numeric($value)){
                            $this->headers[$name] = (int)$value;
                        }else{
                            $this->headers[$name] = $value;
                        }
                    }
                }
            }
            if (!isset($this->headers['icymetaint'])){
                $data = ''; $metainterval = 512;
                while(!feof($sock)){
                    $data .= fgetc($sock);
                    if (strlen($data) >= $metainterval) break;
                }
               $this->print_data($data);
                $matches = array();
                preg_match_all('/([\x00-\xff]{2})\x0\x0([a-z]+)=/i', $data, $matches, PREG_OFFSET_CAPTURE);
               preg_match_all('/([a-z]+)=([a-z0-9\(\)\[\]., ]+)/i', $data, $matches, PREG_SPLIT_NO_EMPTY);
               echo '
';var_dump($matches);echo '
';
                $title = $artist = '';
                foreach ($matches[0] as $nr => $values){
                  $offset = $values[1];
                  $length = ord($values[0]{0}) +
                            (ord($values[0]{1}) * 256)+
                            (ord($values[0]{2}) * 256*256)+
                            (ord($values[0]{3}) * 256*256*256);
                  $info = substr($data, $offset + 4, $length);
                  $seperator = strpos($info, '=');
                  $this->metadata[substr($info, 0, $seperator)] = substr($info, $seperator + 1);
                    if (substr($info, 0, $seperator) == 'title') $title = substr($info, $seperator + 1);
                    if (substr($info, 0, $seperator) == 'artist') $artist = substr($info, $seperator + 1);
                }
                $this->metadata['streamtitle'] = $artist . ' - ' . $title;
            }else{
                $metainterval = $this->headers['icymetaint'];
                $intervals = 0;
                $metadata = '';
                while(1){
                    $data = '';
                    while(!feof($sock)){
                        $data .= fgetc($sock);
                        if (strlen($data) >= $metainterval) break;
                    }
                    //$this->print_data($data);
                    $len = join(unpack('c', fgetc($sock))) * 16;
                    if ($len > 0){
                        $metadata = str_replace("\0", '', fread($sock, $len));
                        break;
                    }else{
                        $intervals++;
                        if ($intervals > 100) break;
                    }
                }
                $metarr = explode(';', $metadata);
                foreach ($metarr as $meta){
                    $t = explode('=', $meta);
                    if (isset($t[0]) && trim($t[0]) != ''){
                        $name = preg_replace('/[^a-z][^a-z0-9]*/i','', strtolower(trim($t[0])));
                        array_shift($t);
                        $value = trim(implode('=', $t));
                        if (substr($value, 0, 1) == '"' || substr($value, 0, 1) == "'"){
                            $value = substr($value, 1);
                        }
                        if (substr($value, -1) == '"' || substr($value, -1) == "'"){
                            $value = substr($value, 0, -1);
                        }
                        if ($value != ''){
                            $this->metadata[$name] = $value;
                        }
                    }
                }
            }
            fclose($sock);
            $this->valid = true;
        }else echo 'unable to write.';
    }else echo 'no socket '.$errno.' - '.$errstr.'.';
}

public function print_data($data){
    $data = str_split($data);
    $c = 0;
    $string = '';
    echo "
\n000000 ";
    foreach ($data as $char){
        $string .= addcslashes($char, "\n\r\0\t");
        $hex = dechex(join(unpack('C', $char)));
        if ($c % 4 == 0) echo ' ';
        if ($c % (4*4) == 0 && $c != 0){
          foreach (str_split($string) as $s){
            //echo " $string\n";
            if (ord($s) < 32 || ord($s) > 126){
              echo '\\'.ord($s);
            }else{
              echo $s;
            }
          }
          echo "\n";
          $string = '';
          echo str_pad($c, 6, '0', STR_PAD_LEFT).'  ';
        }
        if (strlen($hex) < 1) $hex = '00';
        if (strlen($hex) < 2) $hex = '0'.$hex;
          echo $hex.' ';
        $c++;
    }
    echo "  $string\n
";
}

public function __get($name){
    if (isset($this->metadata[$name])){
        return $this->metadata[$name];
    }
    if (isset($this->headers[$name])){
        return $this->headers[$name];
    }
    return null;
 }
}

$t = new streaminfo('http://64.236.34.196:80/stream/1014'); // get metadata

echo Meta Interval: $t->icymetaint;
echo Current Track: $t->streamtitle;

A: You will need to constantly query the stream at a set interval to find when the song changes.
This can be best done by scheduling a cron job.
If on Windows, you should use the Windows Task Scheduler

A: If you want to run the PHP script to keep your meta data up to date (I'm assuming you're making a website and using html audio tags here) you can use the ontimeupdate event with an ajax function. If you're not you probably should look up your audio playback documentation for something similar.
<audio src="http://ip:port/;" ontimeupdate="loadXMLDoc()">

You can find a great example here http://www.w3schools.com/php/php_ajax_php.asp
You want to use the PHP echo function all the relevant information at once using one php variable at the very end of your script.
<?php ....
$phpVar=$streamtitle;
$phpVar2=$streamsong;
$result="I want my string to look like this:
 {$phpVar} {$phpVar2}";
echo $result;
?>

and then use the function called by the .onreadystatechange to modify the particular elements you want on your website by using the .resonseText (this will contain the same content as your PHP script's echo).

A: After SCOURING the web for 4 hours, this is the only Shoutcast metadata script I've found that works! Thankyou.
To run this constantly, why not use a setInterval combined with jQuery's AJAX call?

Also your last couple 'echo' lines were breaking the script for me. Just put quotes around the Meta Interval, etc....


text:
Q: Solve a particular differential equation I am quite new to differential equations and I have to solve the following $a(t)+b(t)C(t)+s a(t)C'(t)=0$, where $s$ is some constant. I read about differential equations and at this moment my main difficulty is that $C'(t)$ is multiplied by $s a(t)$ (the examples of differential equations I have seen so far have $s a(t)=1$). Does anyone have a hint about this equation (maybe it turns out to be a "famous" equation and I am not aware about it) and how to solve it?

A: What you did in your comment is correct up to (except a negative sign)
$$\exp{K(t)}\frac{b(t)C(t)}{sa(t)}+\exp{K(t)}C'(t)=-\exp{K(t)}s^{-1}$$
After that
$$\left(\exp{K(t)}C(t)\right)'=-\exp{K(t)}s^{-1}$$
Integrate both sides
$$\exp{K(t)}C(t)=-s^{-1}\int\exp{K(t)}\,dt+D\\
C(t)=-s^{-1}\exp{(-K(t))}\int\exp{K(t)}\,dt+D\exp{(-K(t))}$$
where $D$ is a constant.


text:
Q: Dealing with Android devices that lie about having a camera flash? I'm building a flashlight app and I've learned that when I call
this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH),
the Nexus 7 returns true and when asking for the FlashModes() the size is 1 and the option is called "off." So when I check whether or not flash exists on devices, if the device lies about it, I can run into trouble. I've added !android.os.Build.MODEL.equals("Nexus 7") to my if statement to prevent crashing my app while testing on my Nexus 7.
If there are other devices that lie about having a flash, my app will likely crash on them. How can I avoid this?

A: you can implement a double check
after calling
this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

check if
getSupportedFlashModes() returns null

if no
check if
flash modes only contains one entry  "off"


text:
Q: Aren't roots of polynomial equations smooth functions of their parameters? I am trying to find the solution of cubic equation as a function of $kz$
-1.05976 + λ (-4.3872 + (-3.9 -
       1. λ) λ) + (1.10144 + 0.624 λ) Cos[
   1.31 kz] + 0.035152 Cos[2.62 kz]==0

{e1[kz_], e2[kz_],
  e3[kz_]} = λ /.
   NSolve[-1.05976 + λ (-4.3872 + (-3.9 -
       1. λ) λ) + (1.10144 + 0.624 λ) Cos[
   1.31 kz] + 0.035152 Cos[2.62 kz]==0, λ] // FullSimplify

If I plot e1[kz] as function of kz,
Plot[e1[z], {z, 0, π/1.31}]

I get a function that is not smooth. However, if I plot another solution alongside then it seems two solution got mixed up.
Plot[{e1[z], e3[z]}, {z, 0, π/1.31}]

Does anyone know why is this the case? Also, can you fix this?

A: With a tip of the hat to @MichaelE2 (from whom I learned this trick), we can differentiate the implicit relation between $\lambda$ and $k_z$ and then solve it as an ODE:
neweq = eq /. λ -> λ[kz];
startkz = π/6;
startval = λ[startkz] /. Solve[neweq /. kz -> startkz, λ[startkz]]
soln = NDSolve[{D[neweq, kz], λ[startkz] == startval}, λ, {kz, 0, π/1.31}, Method -> "StiffnessSwitching"]
Plot[Evaluate[Table[Indexed[λ[kz] /. First[soln], i], {i, 1, 3}]], {kz, 0, Pi/1.31}]

This method may not be entirely robust, but it does seem to work in this case.  Notes:

*

*The initial values for the ODE are specified at startkz = Pi/6 in order to ensure that all three roots are distinct at that point and therefore that Mathematica produces three different solutions.

*The StiffnessSwitching option is necessary to integrate past the points where the roots cross.

*The use of Table and Indexed is required because Mathematica is returning a vector-valued InterpolatingFunction, and some chicanery is needed to get Plot to plot the three components with distinct colors (among other things you might want to do with the result.)

A: Clear["Global`*"]

The equation can be solved exactly
eqn = -1.05976 + λ (-4.3872 + (-3.9 -
          1. λ) λ) + (1.10144 + 0.624 λ) Cos[
      1.31 kz] + 0.035152 Cos[2.62 kz] == 0;

sol[kz_] =
  Solve[eqn // Rationalize // Simplify, λ, Reals] // Simplify;

EDIT: For the revised plot range,
Plot[Evaluate[λ /. sol[kz]], {kz, 0, Pi/1.31},
 Frame -> True,
 FrameLabel -> (Style[#, 12, Bold] & /@ {kz, λ}),
 PlotLegends -> Placed[{λ1, λ2, λ3}, {.25, .5}]]

Looking at only the first two solutions
Plot[Evaluate[Most[λ /. sol[kz]]], {kz, 0, Pi/1.31},
 Frame -> True,
 FrameLabel -> (Style[#, 12, Bold] & /@ {kz, λ}),
 PlotLegends -> Placed[{λ1, λ2}, {.25, .6}]]

From the condition in the ConditionalExpression of the second root, the switchover occurs at
{so = Reduce[{sol[kz][[2, 1, -1, -1, 2]], 1 < kz < 2}, kz][[1, -1]], so // N}

(* {200/131 ArcTan[(33 Sqrt[3/23])/7], 1.58739} *)

EDIT: Alternatively, to find the switchover use
{so = kz /.
   Solve[{Equal @@ (λ /. Most[sol[kz] // Normal]), 1 < kz < 2},
     kz][[1]], so // N}

(* {200/131 ArcTan[(33 Sqrt[3/23])/7], 1.58739} *)

Using Piecewise, the smooth curves are then
Format[lambda[n_]] = Subscript[λ, n];

lambda[1][kz_] = Piecewise[{
    {λ /. sol[kz][[1]], kz <= so},
    {λ /. sol[kz][[2]], so < kz < Pi/1.31}}];

lambda[2][kz_] = Piecewise[{
    {λ /. sol[kz][[2]], kz <= so},
    {λ /. sol[kz][[1]], so < kz < Pi/1.31}}];

Plot[{lambda[1][kz], lambda[2][kz]}, {kz, 0, Pi/1.31},
 Frame -> True,
 FrameLabel -> (Style[#, 12, Bold] & /@ {kz, λ}),
 PlotLegends -> Placed[{lambda[1], lambda[2]}, {.25, .6}]]


text:
Q: developing applications for windows mobile,c# i work on visual studio 2008,now i want to create applications for windows mobile in c#.
what r d requirements and how to build them???
Do i need any kind of simulators

A:
Answering your question with right degree of detailing that it deserves
  is beyond the scope here. So I
  recommend you to start from
  here!

Windows Mobile Developer Center

A: There is a Windows Mobile SDK available for free from Microsoft, however you must use a full version of Visual Studio (not an Express edition).

A: You can now use Visual Studio 2010 express mobile edition as well.  This is nice because it seems to be the only one that is actually one stop shopping: no dumb SDK's, no extra vs project template plug-ins, etc...  Everything you need is in that one free DL.  Unfortunately WinMo7 is radically different from the previous versions so backwards compatibility will be be difficult.  The new environment is built on top of WPF tho which is nice to work with.

A: The Windows Mobile SDK includes a simulator, but it is always sensible to debug/test on a device before release. This is really smooth using Visual Studio 2008 and USB connection to the device.
The .NET compact framework is a subset of the .NET framework. MSDN is good for telling you what's missing.


text:
Q: Exercise on Compact space of R^2 Given $n\in \mathbf{N}$, consider subspace $A_n$ of $\mathbf{R}^2$ defined by
$$A_n:=\left\{(x,y) \in \mathbf{R}^2: x^2+(y-1)^2=\frac{1}{n^2}\right\}$$
and define $\displaystyle X:=\bigcup_{n\in \mathbf{N}} A_n.$
Let
$$C^+:= \left\{(x,y) \in \mathbf{R}^2:y\geq\frac{1}{2}\right\}$$ and
$$C^-:= \left\{(x,y) \in \mathbf{R}^2:y\leq\frac{1}{2}\right\}.$$

Verify whether $X\cap C^+$ and $X\cap C^-$ are compact topological spaces.

I know that only accumulation point's of $X$ is $(0,1)$, since $X\cap C^+$ and $X\cap C^-$ are limited, I concluded that $X\cap C^+$ is not compact because it is not closed and $X\cap C^-$ is compact because it is closed. Is it right?

A: I have one minor criticism, but otherwise I agree with your argument (including its conclusion):

I know that the only accumulation point of $X$ is $(0, 1)$

Considered as a subset of $\Bbb{R}^2$, $(0, 1)$ is not the only accumulation point of $X$. Recall that accumulation point $x$ of a set $C$ satisfies $x \in \overline{C \setminus \{ x \}}$. In a metric space like $\Bbb{R}^2$, this is equivalent to the existence of a sequence $x_n \in C \setminus \{x\}$ that converges to $x$. As an example, the points
$$(\cos(1/n), 1+ \sin(1/n))$$
belong to $A_1$, and hence $X$. They converge to the point $(1, 1)$, but no point in the sequence is equal to $(1, 1)$. Thus, $(1, 1)$ is also an accumulation point of $X$ in $\Bbb{R}^2$ (and similar constructions can be used to show the same is true for any point in $X$).

Is $(0,1)$ an accumulation point's of $X \cap C^−$??

No. The point $(0, 1)$ does not lie in $\overline{X \cap C^- \setminus\{(0, 1)\}}$. To prove this, consider an open ball around $(0, 1)$ of radius $\frac{1}{2}$. For $(x, y)$ in this ball, we have
\begin{align*}
\|(x, y) - (0, 1)\| < \frac{1}{2} &\implies |y - 1| \le \sqrt{x^2 + (y - 1)^2} < \frac{1}{2} \\
&\implies -\frac{1}{2} < y - 1 < \frac{1}{2} \\
&\implies \frac{1}{2} < y < \frac{3}{2} \\
&\implies (x, y) \notin C^- \\
&\implies (x, y) \notin X \cap C^- \setminus \{(0, 1)\}.
\end{align*}
So, $(0, 1)$ lies in the interior of the complement of $X \cap C^- \setminus \{(0, 1)\}$, and hence not in $\overline{X \cap C^- \setminus \{(0, 1)\}}$, showing it's not a limit point of $X \cap C^-$.


text:
Q: Clang Static Code Analyzer Output Format for Xcode project I am trying to run inbuilt Xcode Clang static analyzer on ObjectiveCProject. I want to know if it is possible to transform the Obj-C Analyzer output into a another format that sonar plugin can consume. Since there is no Sonar plugin yet for objectiveC that has full features.

A: This is the command you can use to run clang for the iOS application:
scan-build -o static_analyzer_results xcodebuild -configuration Debug -sdk iphonesimulator

This creates the html reports in static_analyzer directory. Check this for reference:
http://clang-analyzer.llvm.org/scan-build.html
Not sure if you can feed them into Sonar but they are well formatted.


text:
Q: Searching for a better solution for aligning and centering the equations at the same time \begin{gather*}
A^S_{\text{M.P.}} = \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} = \frac{0,66 \si{Bq}}{2,88 \cdot 10^{-3} \si{kg}} \approx 229,167 \si{Bq/kg} \\
\begin{align*}
\Delta A^S_{\text{M.P.}} &= \abs{\frac{\partial A^S_{\text{M.P.}}}{\partial A_{\text{M.P.}}}} \Delta A_{\text{M.P.}} + \abs{\frac{\partial A^S_{\text{M.P.}}}{\partial m_{\text{M.P.}}}} \Delta m_{\text{M.P.}} \\
                         &= \frac{\Delta A_{\text{M.P.}}}{m_{\text{M.P.}}} + A_{\text{M.P.}} \cdot m^{-2}_{\text{M.P.}} \cdot \Delta m_{\text{M.P.}} \\
                         &= \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} \cdot \frac{\Delta A_{\text{M.P.}}}{A_{\text{M.P.}}} + \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} \cdot \frac{\Delta m_{\text{M.P.}}}{m_{\text{M.P.}}} \\
                         &= A^S_{\text{M.P.}} \qty(\frac{0,14}{0,66} + \frac{\Delta 0,03}{2,88})
\end{align*}
\end{gather*}

With the code above, I get this

The value (the first row) is now in the middle of the page. Its error is aligned but not centered. I would like to put the error also in the middle of the page, so I have used three times \qquad.
\begin{gather*}
A^S_{\text{M.P.}} = \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} = \frac{0,66 \si{Bq}}{2,88 \cdot 10^{-3} \si{kg}} \approx 229,167 \si{Bq/kg} \\
\begin{align*}
\Delta A^S_{\text{M.P.}} &= \abs{\frac{\partial A^S_{\text{M.P.}}}{\partial A_{\text{M.P.}}}} \Delta A_{\text{M.P.}} + \abs{\frac{\partial A^S_{\text{M.P.}}}{\partial m_{\text{M.P.}}}} \Delta m_{\text{M.P.}} \qquad \qquad \qquad \\
                         &= \frac{\Delta A_{\text{M.P.}}}{m_{\text{M.P.}}} + A_{\text{M.P.}} \cdot m^{-2}_{\text{M.P.}} \cdot \Delta m_{\text{M.P.}} \\
                         &= \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} \cdot \frac{\Delta A_{\text{M.P.}}}{A_{\text{M.P.}}} + \frac{A_{\text{M.P.}}}{m_{\text{M.P.}}} \cdot \frac{\Delta m_{\text{M.P.}}}{m_{\text{M.P.}}} \\
                         &= A^S_{\text{M.P.}} \qty(\frac{0,14}{0,66} + \frac{\Delta 0,03}{2,88})
\end{align*}
\end{gather*}

(At the end of the 4th row there are three more \qquad.)
Now I get this

But are there any "automatic" ways to center those equations in this case?

A: You need an aligned block to within your gather* if you want a centered alignment:

\documentclass{article}

\usepackage{amsmath,siunitx}

\begin{document}

\begin{gather*}
  f(x) = ax^2 + bx + c \\
  \begin{aligned}
    g(x) &= a_0 + a_1 x + a_2 x^2 + a_3 x^3 + \dots \\
         &= a_0 + a_1 x + a_2 x^2 + a_3 x^3 + \dots
  \end{aligned}
\end{gather*}

\end{document}


text:
Q: While loop to increase number until higher or equal with target Essentially what I want to do is have a while loop in my code, add one to a score until it hits a target which I've found can be done quite easily with a basic while loop. However, In my version of this, it will be slightly different, as you will see in the code below.
What I'm doing is having the user input 4 numbers: Target, Promoters, Neutrals, and Detractors.
For every promoter they enter that gives 100 points, neutrals give 0, and detractors are -100. Then a final average is taken which will be compared to the target they entered at first, this is where I want the while loop to come in, I want the loop to automatically tell the user how many promoters they need to achieve the target.
So, in the example of the user having a target of 75, and them having 3 promoters, 2 neutrals, and 1 detractor. This would give them an average of 33.33 (200/6). And, I've manually worked out they would need 10 more promoters for the score to become 75, therefore, hitting the target they assigned.
I've been playing around with loads of different while loops over the last few days and have come up with nothing so that's why I'm turning to you guys, the experts.
The code is below. This is just the final piece of the puzzle for me now to finish this.
Here is my HTML and JavaScript.

/* eslint-env browser */
// eslint.rc
{
  "no-unused-vars" [2, {"args": "none"}]
}
"use strict";

$(document).ready(function () {

     $('#target, #proNum, #neuNum, #detNum').change(function () {

var target = $('#target').val();
var proNum = $('#proNum').val();
var neuNum = $('#neuNum').val();
var detNum = $('#detNum').val();

         console.log("target is equal to " + target);
         console.log("promitors is equal to " + proNum);
         console.log("neutrals is equal to " + neuNum);
         console.log("detractors is equal to " + detNum);

var targetTot = (target*10);
var prosTot = (proNum*100);
var neusTot = (neuNum*0);
var detsTot = (detNum*-100);

         console.log("Target is " + targetTot);

var scoresQuant = +proNum + +neuNum + +detNum;
var scoresTot = prosTot+neusTot+detsTot;
var preCurrent = scoresTot/scoresQuant;

var current = Math.round(preCurrent*100)/100;

         console.log("scoresQuant is equal to " + scoresQuant);
         console.log("scoresTot is equal to " + scoresTot);
         console.log("preCurrent is equal to " + preCurrent);
         console.log(current);

$('#current').text(current);

var hypPro = 0;
var scoresTotLoop = scoresTot/100;
var targetLoop = target/10;

 while (scoresTotLoop/scoresQuant+hypPro<=targetLoop)  {
    hypPro++;
}
  console.log("hypPro is equal to " + hypPro);

$('#prosToTarget').text(hypPro);
        });

});
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>NPS Calculator</title>

        <link rel="stylesheet" type="text/css" href="css/style.css">

        <link href="https://fonts.googleapis.com/css?family=Nunito+Sans:300,400,700" rel="stylesheet">

NPS Calcultor

This site will help you work out the total number of promoters you need to achieve your target this month.

Target NPS

                        <input type="text" class="IO" id = "target"/>

Promoters

Neutrals

Detractors

                        <input type="text" class="IO" id = "proNum"/>

                        <input type="text" class="IO" id = "neuNum"/>

                        <input type="text" class="IO" id = "detNum"/>

Current NPS

0

Promitors to Target

0

A: Consider x for total promotors required (10+3), p for input promotors (3), n for input neutrals (2) and d for input detractors (1).
So, we have following equation-
(100x + 0n - 100d)/(x+n+d) = 75
or, 100(x - d)/(x+n+d) = 75
or, x-d = 0.75(x+n+d)
Or, x-0.75x = 0.75n + 0.75d +d
Or, 0.25x = 0.75n + 1.75d
Or, x = (75/25)n + (175/25)d  -------(1)
Or, x = 3n + 7d
As n and d are already there, 2 and 1,
x = 3*2 + 7*1 = 13 and
x-p = 13 - 3 = 10 promotors are required.
How do you implement this in code? As you can see in equation (1)

*

*Multiply n by (target/(100-target))

*Multiply d by (100+target)/(100-target)

*Add them to get total promotors

*Subtract input promotors to get required promotors.

No need of loop. Here it is assumed that target is always achievable by adding promotors only.

A: I've managed to solve the problem, by using the idea of treating it as an equation from above. Here is the solution I found, what I did is took the equation posted by @psinaught and assigned the target as y, combined pros as x, neutrals as n, detractors as d, and then solved for y. Which then produces the equation below which I swapped the correct variables into.
var preProsToTarget = ((detNum*target)+(neuNum*target)+(100*detNum))/(-target+100);
var prosToTarget = Math.max(0,preProsToTarget-proNum);

A: as psinaught already stated, the solution would not be a while loop, but an equation.
the posted solution is already heading in the right direction - but as far as i can see only works, when pVal and dVal have the same absolute value.
another downside is, since your example has the value 0 for neutrals, the neutral value was removed while simplifying his equation. so as soon, as neutrals get a value different then 0, it will not work anymore...
if everything (counts and values) could be generic, the equation would be:
x = ( n * ( target - nVal ) + d * ( target - dVal) ) / ( pVal - target )

additionally you would want to check, if the target does not be greater than pVal, because of the target being an average, it will not be reachable anymore.
here's the link to my working fiddle: http://jsfiddle.net/bq1f02pk/2/
you can adjust all numbers, regardless of being count or values.
what have i done within the js part:
first i bound an 'onChange' event to all input fields, so the function gets executed, everytime you change a number
$("input").on("change", function() {

next, to make the mathematical part work and get rid of the jquery selectors, i extracted all input values into variables:
  var target = parseInt($("#target").val());
  var proms = parseInt($("#p").val());
  var pVal = parseInt($("#pval").val());
  var neuts = parseInt($("#n").val());
  var nVal = parseInt($("#nval").val());
  var dets = parseInt($("#d").val());
  var dVal = parseInt($("#dval").val());

following are some checks, for input validity:
   if (target == pVal) { // only achievable without n's and d's
      return false;
    } else if (target > pVal) { //not reachable
      return false;
    } else if( neuts == 0 && dets == 0){ //no calculation needed
      return false;
    }

in my fiddle, those three if's also prints description texts to the user, otherwise one if with || would have been sufficient.
now finally, we have the calculation:
var totals = var totals = ( neuts * ( target - nVal ) + dets * ( target - dVal ) ) / ( pVal - target );
var remaining = totals - proms;

and to help the user understand his problem, you can additionally create a long text to explain the results:
$("#result").text("to reach your target of " + target + " you need " + totals + " promoters in total. you already have " + proms + " promoters, so you need " + remaining + " more promoters!");


text:
Q: Why is this constexpr static member function not seen as constexpr when called? Why is this constexpr static member function, identified by the //! Nah comment, not seen as constexpr when called?
struct Item_id
{
    enum Enum
    {
        size, position, attributes, window_rect, max_window_size, _
    };

    static constexpr int n_items_ = _;                          // OK
    constexpr auto member_n_items() const -> int { return _; }  // OK
    static constexpr auto static_n_items() -> int { return _; } // OK
    static constexpr int so_far = n_items_;                     // OK
    #ifndef OUT_OF_CLASS
        static constexpr int bah = static_n_items();            //! Nah.
    #endif
};

constexpr auto n_ids() -> int { return Item_id().member_n_items(); }    // OK

auto main() -> int
{
    #ifdef OUT_OF_CLASS
        static constexpr int bah = Item_id::static_n_items();   // OK
    #endif
}

MinGW g++ 5.1 reports

constexpr.cpp:12:46: error: 'static constexpr int Item_id::static_n_items()' called in a constant expression
     static constexpr int bah = static_n_items();                //! Nah.

Visual C++ 2015 reports

constexpr.cpp(12): error C2131: expression did not evaluate to a constant
constexpr.cpp(12): note: failure was caused by call of undefined function or one not declared 'constexpr'
constexpr.cpp(12): note: see usage of 'Item_id::static_n_items'

My text editor insists that the name in the call is the same as the name in the function definition.
It appears to have something to do with incomplete class, because with OUT_OF_CLASS defined it compiles nicely.
But then why does the n_items_ data work, and, why such a rule (doesn't make sense to me)?

A: [class.mem]/2

Within the class member-specification, the class is regarded as complete within function bodies, default arguments, exception-specifications, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

In the initializer of a static data member of a class, the class is incomplete. The initializer can only see the declarations of members which precede it, and any member functions it can see are considered declared but not defined. A call to a function that is declared but not defined can not be a constant expression.

A: From memory, member function bodies are evaluated only once the class has been completely defined.
static constexpr int bah = static_n_items();

forms part of the class definition, but it's referring to a (static) member function, which cannot yet be defined.
Solution:
defer constant expressions to a base class and derive from it.
e.g.:
struct Item_id_base
{
    enum Enum
    {
        size, position, attributes, window_rect, max_window_size, _
    };

    static constexpr int n_items_ = _;                          // OK
    constexpr auto member_n_items() const -> int { return _; }  // OK
    static constexpr auto static_n_items() -> int { return _; } // OK
    static constexpr int so_far = n_items_;                     // OK
};

struct Item_id : Item_id_base
{
    #ifndef OUT_OF_CLASS
        static constexpr int bah = static_n_items();            // now OK
    #endif
};

constexpr auto n_ids() -> int { return Item_id().member_n_items(); }    // OK

auto main() -> int
{
    #ifdef OUT_OF_CLASS
        static constexpr int bah = Item_id::static_n_items();   // OK
    #endif
}

Why do you think the standard disallows it?

Because this is illegal:
struct Item_id
{
    // ... etc.

    #ifndef OUT_OF_CLASS
        static constexpr int bah;// = static_n_items();            //! Nah.
    #endif
};

constexpr int Item_id::bah = static_n_items();

And a constexpr must have a constexpr definition. The only place we can define it is during its declaration...
... so by deduction it cannot refer to any function who's body is not yet defined.
I am at a loss to know where to look in the standard for all that. Probably 5 different, seemingly unrelated clauses :)


text:
Q: Labels on the QGIS WMS layers are not drawn according to the style definition I have an issue regarding the styling of labels of WMS layers using QGIS server. I can't seem to get them to display how I want.
What I did:

*

*create a QGIS project (2.2 on Mac) with a layer from a database

*style the layer, including the labels on QGIS desktop

*save project on the server (Ubuntu) to create the WMS

What I get:

*

*my WMS layer, nicely showing up

*except for the labels that seem to use a default symbolization, whatever the changes I make in the project (understand big black labels)

What I wished:

*

*control the size and maybe also the font of the labels.

Is there a nifty parameter that I forgot somewhere or is the labeling engine not working propoperly with WMS? Any hints or similar experiences welcome.

A: Based on the request of @Ahsan Mukhtar, I went to check again my latest project running on QGIS 2.14 (Windows Server):
Controlling the size, color, style and halo of the labels work.
On the previous settings I had (Ubuntun - QGIS 2.2), I cannot tell you anymore what happened.
My advice:

*

*check that the fonts you are using are also present on the server installation

*make sure you are creating your project in the same desktop version of QGIS as the one you are using for the server