text:
Q: Creation of a template class creates major bottleneck I am trying to write a scientific graph library, it works but I have some performance problems. When creating a graph I use a template class for the nodes and do something like
for(unsigned int i = 0; i < l_NodeCount; ++i)
                m_NodeList.push_back(Node<T>(m_NodeCounter++));

Even though in the constructor of the node class almost nothing happens (a few variables are asigned) this part is a major bottleneck of my program (when I use over a million of nodes), especially in the debug mode it becomes too inefficient to run at all.
Is there a better way to simultaneusly create all those template classes without having to call the constructor each time or do I have to rewrite it without templates?

A: If the constructor does almost nothing, as you say, the bottleneck is most likely the allocation of new memory. The vector grows dynamically, and each time it's memory is exhausted, it will reserve new memory and copy all data there. When adding a large number of objects, this can happen very frequently, and become very expensive. This can be avoided by calling
m_NodeList.reserve(l_NodeCount);

With this call, the vector will allocate enough memory to hold l_NodeCount objects, and you will not have any expensive reallocations when bulk-adding the elements.

A: There are things that happen in your code:

*

*as you add elements to the vector, it occasionally has to resize the internal array, which involves copying all existing elements to the new array

*the constructor is called for each element

The constructor call is unavoidable. You create a million elements, you have a million constructor calls. What you can change is what the constructor does.
Adding elements is obviously unavoidable too, but the copying/resizing can be avoided. Call reserve on the vector initially, to reserve enough space for all your nodes.
Depending on your compiler, optimization settings and other flags, the compiler may do a lot of unnecessary bounds checking and debug checks as well.

*

*You can disable this for the compiler (_SECURE_SCL=0 on VS2005/2008, _ITERATOR_DEBUG_LEVEL=0 in VS2010. I believe it's off by default in GCC, and don't know about other compilers).

*Alternatively, you can rewrite the loop to minimize the amount of debug checking that needs to be done. Using the standard library algorithms instead of a raw loop allows the library to skip most of the checks (typically, a bounds check will then be performed on the begin and the end iterator, and not on the intervening iterations, whereas on a plain loop, it'll be done every time an iterator is dereferenced)

A: I would say, your bottleneck is not a template class which has nothing to do with run-time and is dealt with during compilation, but adding an element to vector container (you have tag "vector" in your question). You are performing A LOT of allocations using push_back. Try allocating required total memory right away and then fill elements.

A: you can avoid the templates buy having a list of (void *) to the objects. and cast them later.
but... if you wish to have 1,000,000 instances of the node class. you will have to call 1,000,000 the node constructor.


text:
Q: Video Recorder Tool (Screencast) for Ubuntu 11.10 I was looking at this post How can I record my screen? which mentions some Video Recorders (Screencast) that I was looking for but some of them are more than 8 months old with not one single update made to them. I am looking for a Screencast that is at least update recently and that I know that if I keep using it I could count on it being updated.
The most important part is video recording but sound is good too. Maybe a window area, mouse tracking, etc. But it needs to be up to date and not abandoned or very old.
And of course that works in 11.10 and has in mind to work in 12.04.

A: Here's a recent I answer I just gave: How to record my screen?.
I'm also looking into kdenlive for video editing. See: Video editor to create professional appearance

A: Use Kazam: http://www.twm-kd.com/category/linux/kazam/
It's an up-to-date screencast software with support for modern desktops like Unity and PulseAudio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create new column values by grep on another column, using a vector of patterns I have a data.frame and I want to search in one column Name in order to create a new value in the other column that has the search pattern in it. I can get this to work one by one, but I'm wondering if there is a way to do this more elegantly. Could I make a vector intensities = c("1mW", "5mW", and "10mW") of patterns and then have another vector of replacements? (the same values in this case).
Name    Intensity
file-1mW    1mW
file-1mW    1mW
file-5mW    5mW
file-10mW   10mW
file-1mW    1mW

A: You can use stringr::str_extract for this. The regular expression \w+$ will take the last word from the string, which in this case is delimited by the "-" character.
library(dplyr)
library(stringr)

df <- read.table(text = "
  Name    Intensity
  file-1mW    1mW
  file-1mW    1mW
  file-5mW    5mW
  file-10mW   10mW
  file-1mW    1mW" , header = TRUE, stringsAsFactors = FALSE)

df %>% mutate(new = str_extract(Name, "\\w+$"))

#        Name Intensity  new
# 1  file-1mW       1mW  1mW
# 2  file-1mW       1mW  1mW
# 3  file-5mW       5mW  5mW
# 4 file-10mW      10mW 10mW
# 5  file-1mW       1mW  1mW

An alternate approach could be to split the string using the dash and taking the second element.
df %>% mutate(new = str_split(Name, "-")[[1]][2])

df %>% mutate(new = strsplit(Name, "-")[[1]][2]) # the base option

Which produces the same result.


text:
Q: How to use WHERE clause in SOSL query I am trying to use the existing LWC with some modifications to get records on the basis of RecordType.Id but it's throwing an error instead. System.QueryException: expecting a right parentheses, found 'Y000000Wl0yQAC'.
Apex:
tring searchKeyword = searchTerm + '*';

        String returningQuery = '';
        returningQuery = objectName+' ( Id, '+String.join(fields,',')+' WHERE RecordType.Id = '+recordTypeId+' )';
        String query = 'FIND :searchKeyword IN ALL FIELDS RETURNING '+returningQuery+' LIMIT 20';

The resultant String query is FIND :searchKeyword IN ALL FIELDS RETURNING Account ( Id, Rating,AccountNumber,Name WHERE RecordType.Id = 0120Y000000Wl0yQAC ) LIMIT 20
How to fix this??

A: You need quotes around string values, including ID values:
FIND :searchKeyword
IN ALL FIELDS
RETURNING Account (
  Id, Rating, AccountNumber, Name
  WHERE RecordType.Id = '0120Y000000Wl0yQAC')
LIMIT 20


text:
Q: How slow or fast is Qt mobile for android I would like to know the advantages and disadvantages of Qt mobile. I have heard things, like the performance is better than native apps. However I am not sure if I can trust that.
I am not a c++ developer. In fact I have no experience with c, java, c++..  I am only a web developer. I use phonegap for very simple apps. But I'd like to begin to learn new things in order to delevop better products.
Can you describe the advantages, use cases, time it takes to develop, and what Qt is in general?

A: Native android (NDK) or Qt( based on NDK) have the same speed, but Qt saves you development time in UI, multi-Threading, Graphic, Parser, and Network programming.
For now, Qt for mobile is not working 100% as you may encounter some issues, but it is worth learning, because it works on mac windows linux ios android.  All desktop and all embedded environments.


text:
Q: Swift 5: how to specify a generic type conforming to protocol when declaring a variable I am on Swift 5. I have a protocol:
protocol Pipe {
    associatedtype T
    func await() -> Void
    func yield( to: Any, with listener: Selector ) -> Void
}

And I would like to reference an instance of this protocol somewhere in code. That is, I want foo : , or a variable of generic type T implementing Pipe. Per this documentation: https://docs.swift.org/swift-book/ReferenceManual/GenericParametersAndArguments.html
I tried writing:
var imageSource: <Pipe T>

and any permutation of said symbols, ie imageSource:  but the syntax is wrong across all cases.
In fact, T conform to two protocols, Renderable and Pipe, so I really want:
var imageSource: <Pipe, Renderable T>

Syntax wise this is gibberish, but semantically it's not an uncommon use case.
__________________ EDIT after two answers have been given __________
I tried simplifying the Pipe protocol for this post, but now I realize I simplified it too much. In my code base it's
  protocol Pipe {
        associatedtype T
        func await() -> Void
        func yield( to: Any, with listener: Selector ) -> Void
        func batch() -> [T]
    }

That's why there's a T there. But it's not crucial, I can drop the batch() -> [T] if I am able to write what I want above.

A: This is called a generalized existential, and is not available in Swift. A protocol with an associated type describes other types; it is not a type itself and cannot be the type of a variable, or put into a collection.
This specific protocol doesn't make a lot of sense, since you don't use T anywhere. But what you would need to do is pull this into the containing type:
struct Something<Source> where Source: Pipe & Renderable {
    var imageSource: Source
}

I suspect you really want to redesign this in a different way, however. This looks like a fairly common misuse of protocols. You probably want Pipe and Renderer types that are structs (or even just functions). Without knowing what the calling code looks like, I can't say precisely how you would design it.
If you remove T (which isn't being used here), then Max's answer will address this issue. Protocols without associated types have an implicit existential type, and so you can treat them somewhat as "normal" types (assigning them to variables or putting them in collections).

A: An associated type is used when you want your protocol to work with a variety of types, think a Container protocol that might have several methods all dealing with one contained type.
But your protocol is not that, it doesn't need to know any other types to specify the necessary behavior, so get rid of the associated type.
protocol Pipe {
    func await() -> Void
    func yield( to: Any, with listener: Selector ) -> Void
}

class Foo {
  var imageSource: Pipe & Renderable
}


text:
Q: How do a check if a column or row in a nested list has the same string I need to check if a nested list has a column with the same string
grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", "x", "x"]
]
#if grid has a column or row with the same string (such as the first column and last row) then it will say "yes"

I've only managed to do it for rows:
grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", " ", "x"]
]
print(grid)

row = ['x', 'x', 'x']

if row in grid:
  print("Yes")
else:
  print("no")

A: A simple method to do what you need is to transpose your main grid to check for columns as follows:
gridTranspose = list(zip(*grid))

This will basically reverse rows and columsn in your grid.
Next, save your column as a row (e.g.)
if your grid is:
[
1
1
0
]
just make the variable the same way (column = [1, 1, 0])
then it should work!

A: -1 means not same
grid = [
  ["x", " ", "x"],
  ["x", " ", " "],
  ["x", "x", "x"]
]

row_same = [index if all(map(lambda x: x==i[0], i)) else -1 for index, i in enumerate(grid)]
#[-1, -1, 2]
column_same = [j if all(map(lambda x: x==grid[0][j], [i[j] for i in grid])) else -1 for j in range(len(grid[0]))]
#[0, -1, -1]

A: I have an easy and understandable solution.
So, the basic idea is to take the list of rows and make a new list of columns and then check between them -
num = range(len(grid)) # Just an extra var, so that it is readable

lst_of_columns = [[grid[j][i] for j in num] for i in num]
# This makes a list of columns. Take it slow, print it and understand the logic

for i in num: # These lines check if rows and columns are same
    for j in num:
        if grid[i] == lst_of_columns[j]: # grid[i] = row 1,2,3...
            print('yes')                 # lst_of_columns[j] = columns 1,2,3

        else:
            print('no')

I hope you understand the logic behind this.
Also, this will work for any number of rows and columns


text:
Q: Dynamically setting href attribute using jinja I have a list of url information which are rendered as table using jinja. I am trying to make the url a hyper link so that if i click on the link it will go it that url page.
Sample url List
myData = [["https://www.w3schools.com/",'tutorial site']]

Jinja Code

            {% for value in myData %}

                    <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault">
                    {{ value[0] }}

                {{ value[1] }}

            {% endfor %}

I tried in this way but didnt work. How is it possible to set the value of href value dynamically with jinja code. In the above, if i click on https://www.w3schools.com/ url in the table, that page should open in new tab of the browser

A: Just use . I mean, if you put URLs in myData . Otherwise make MyData contain a list of dictionaries, myData=[{"href": "https://www.w3schools.com/", "title": "tutorial site"} , ] and then you can use .


text:
Q: Parsing negative numbers with argp Is it possible to configure argp to interpret -1, -4, -99, etc as negative number arguments and not switches?  My C program currently allows just one switch (-v).  If I pass my program -4 as a command line argument, argp presents the error message

invalid option -- '4'

Sample code:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <argp.h>

static const char *argpErrors[] = { "OK.", \
                      /* 01 */ "Too few arguments provided", \
                      /* 02 */ "Too many argument provided", \
                      /* 03 */ "Argument 1 must be an integer.", \
                      /* 04 */ "Argument 2 must be an integer.", \
                      /* 05 */ "Argument 3 must be an integer.", \
                      /* 06 */ "Unable to parse command line arguments." };

static struct argp_option options[] = {
    // name, key, argname, flags, doc, group
    {"verbose", 'v', 0, 0, "Produce verbose output"},
    { 0 }
};

struct arguments
{
    int argCount;
    bool verbose;
    int num[3];
};

bool isInteger(char *str)
{
    bool digitFound = false;
    int i;
    int chars = (int)strlen((const char *)str);
    for (i = 0; i < chars; ++i)
    {
        if ((i == 0) && (str[0] == '-'))
        {
            continue;
        }
        if (isdigit(str[i]))
        {
            digitFound = true;
            continue;
        }
        return false;
    }
    return digitFound;
}

void reportArgpError(bool verbose, struct argp_state *state, int errorNumber)
{
    if (verbose)
    {
        argp_failure(state, 1, 0, argpErrors[errorNumber]);
    }
    else
    {
        printf("%d\n", errorNumber);
        exit(-1);
    }
}

static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
    struct arguments *arguments = state->input;
    switch (key)
    {
        case 'v':
            arguments->verbose = true;
            break;
        case ARGP_KEY_NO_ARGS:
            reportArgpError(arguments->verbose, state, 1);
            break;
        case ARGP_KEY_ARG:
            arguments->argCount++;
            if (arguments->argCount > 3)
            {
                reportArgpError(arguments->verbose, state, 2);
            }
            else
            {
                if (isInteger(arg))
                {
                    arguments->num[arguments->argCount - 1] = atoi(arg);
                }
                else
                {
                    reportArgpError(arguments->verbose, state, 2 + arguments->argCount);
                }
            }
            break;
        case ARGP_KEY_END:
            if (arguments->argCount < 3)
            {
                reportArgpError(arguments->verbose, state, 1);
            }
            else if (arguments->argCount > 3)
            {
                reportArgpError(arguments->verbose, state, 2);
            }
            break;
        default:
            break;
    }

    return 0;
}

static char args_doc[] = "num1 num2 num3";
static char doc[] = "Example for StackOverflow";
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char *argv[])
{
    struct arguments arguments;
    arguments.argCount = 0;
    arguments.verbose = false;
    argp_parse (&argp, argc, argv, 0, 0, &arguments);
    if (arguments.verbose)
    {
        puts("Success");
        printf("num1 = %d\n", arguments.num[0]);
        printf("num2 = %d\n", arguments.num[1]);
        printf("num3 = %d\n", arguments.num[2]);
    }
    else
    {
        printf("0 %d %d %d\n", arguments.num[0], arguments.num[1], arguments.num[2]);
    }

    return 0;
}

Sample command:
./a.out -v 33 66 99

Response:
Success
num1 = 33
num2 = 66
num3 = 99

Sample command:
./a.out -v 33 -4 9

Response:
./a.out: invalid option -- '4'
Try `a.out --help' or `a.out --usage' for more information.

A: ./a.out -v -- 33 -4 9 worked.  Thank you nwellnhof.
Replacing the '-' characters with 'n' prior to calling argp_parse() and changing the 'n' back to a '-' in the ARGP_KEY_ARG switch key block also worked.  Source code below:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <argp.h>

static const char *argpErrors[] = { "OK.", \
                      /* 01 */ "Too few arguments provided", \
                      /* 02 */ "Too many argument provided", \
                      /* 03 */ "Argument 1 must be an integer.", \
                      /* 04 */ "Argument 2 must be an integer.", \
                      /* 05 */ "Argument 3 must be an integer.", \
                      /* 06 */ "Unable to parse command line arguments." };

static struct argp_option options[] = {
    // name, key, argname, flags, doc, group
    {"verbose", 'v', 0, 0, "Produce verbose output"},
    { 0 }
};

struct arguments
{
    int argCount;
    bool verbose;
    int num[3];
};

bool isInteger(char *str)
{
    bool digitFound = false;
    int i;
    int chars = (int)strlen((const char *)str);
    for (i = 0; i < chars; ++i)
    {
        if ((i == 0) && (str[0] == '-'))
        {
            continue;
        }
        if (isdigit(str[i]))
        {
            digitFound = true;
            continue;
        }
        return false;
    }
    return digitFound;
}

void reportArgpError(bool verbose, struct argp_state *state, int errorNumber)
{
    if (verbose)
    {
        argp_failure(state, 1, 0, argpErrors[errorNumber]);
    }
    else
    {
        printf("%d\n", errorNumber);
        exit(-1);
    }
}

void replaceIntegerPrefixChar(char *str, char originalChar, char newChar)
{
    int len = (int)strlen(str);
    if (len > 1)
    {
        if ((str[0] == originalChar) && (isInteger(str + 1)))
        {
            str[0] = newChar;
        }
    }

    return;
}

static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
    struct arguments *arguments = state->input;
    switch (key)
    {
        case 'v':
            arguments->verbose = true;
            break;
        case ARGP_KEY_NO_ARGS:
            reportArgpError(arguments->verbose, state, 1);
            break;
        case ARGP_KEY_ARG:
            arguments->argCount++;
            if (arguments->argCount > 3)
            {
                reportArgpError(arguments->verbose, state, 2);
            }
            else
            {
                replaceIntegerPrefixChar(arg, 'n', '-');
                if (isInteger(arg))
                {
                    arguments->num[arguments->argCount - 1] = atoi(arg);
                }
                else
                {
                    reportArgpError(arguments->verbose, state, 2 + arguments->argCount);
                }
            }
            break;
        case ARGP_KEY_END:
            if (arguments->argCount < 3)
            {
                reportArgpError(arguments->verbose, state, 1);
            }
            else if (arguments->argCount > 3)
            {
                reportArgpError(arguments->verbose, state, 2);
            }
            break;
        default:
            //reportArgpError(arguments->verbose, state, false, 13);
            break;
    }

    return 0;
}

static char args_doc[] = "num1 num2 num3";
static char doc[] = "Example for StackOverflow";
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char *argv[])
{
    struct arguments arguments;
    arguments.argCount = 0;
    arguments.verbose = false;

    int i;
    for (i = 0; i < argc; ++i)
    {
        replaceIntegerPrefixChar(argv[i], '-', 'n');
    }

    argp_parse (&argp, argc, argv, 0, 0, &arguments);
    if (arguments.verbose)
    {
        puts("Success");
        printf("num1 = %d\n", arguments.num[0]);
        printf("num2 = %d\n", arguments.num[1]);
        printf("num3 = %d\n", arguments.num[2]);
    }
    else
    {
        printf("0 %d %d %d\n", arguments.num[0], arguments.num[1], arguments.num[2]);
    }

    return 0;
}


text:
Q: waiting for ajax to complete before next ajax call I am trying to wait for an ajax call to finish saving a model before saving the next model in the list.  I was googling around and saw some stuff about deferred objects which are new to me, and another answer that had a recursive function do it.  I tried the recursive method because it seemed to make a little more sense than with deferred objects and using $.when.apply($, arrayOfAjaxCalls).then().  So that code (the recursive one, looks like:
    saveModel(index, numRequests) {
        var self = this;

        if (index < numRequests) {
            var sample = self.samplesToSave[index];

            return $.ajax({
                url: model.url,
                contentType: "application/json",
                type: "POST",
                data: JSON.stringify(model),
                crossDomain: $.support.cors,
                xhrFields: {
                    withCredentials: $.support.cors,
                },
                success: function(data) {
                    console.log("JUST SAVED");
                    console.log(data);
                },
                error: function(xhr: any) {
                    console.log(xhr);
                },
            }).then(() => {
                self.saveModel(index + 1, numRequests);
            });
        }
    }

I call this like:
saveModel(0, _.size(myCollection)
It doesn't actually wait for the ajax call to finish in its current state before calling the next saveModel.  It basically just synchronously calls saveModel for each item in the collection in order.  Any thoughts on what I'm missing?  If there's a better solution with $.Deferred, I'm ok with that as well.  Thanks.
Edit: Sorry it meant to say saveModel in the last line of the saveModel function.  Was trying to get rid of parts that were domain specific.  And I'm using typescript, not coffeescript
New attempt:
    saveSampleNew() {
        var d = $.Deferred();
        d.resolve();
        var p = d.promise();
        var self = this;
        self.samplesToSave.forEach(sample => p = p.then(() => self.makeSaveRequest(sample)));

        return p;
    }

     makeSaveRequest(sample) {
        var self = this;

        return $.ajax({
            url:  "samples",
            contentType: "application/json",
            type: "POST",
            data: JSON.stringify(sample),
            crossDomain: $.support.cors,
            xhrFields: {
                withCredentials: $.support.cors,
            },
            success: function(data) {
                console.log("SAVED12");
                console.log(data);
            },
        });
    }

Because this code depends on other async calls from completing, I call this new attempt like this:
this.saveContainers(project).then(() => {

}).done(() => {
    self.saveSampleNew();
});

A: No, it should work this way. If you think it doesn't wait, please provide more information on how you call it and how experience that it does synchronously recurse.
There is one catch however with the recursive call:
.then(function() {
  self.saveModel(index + 1, numRequests);
})

The promise that is returned by then, and subsequently by your saveModel method, does resolve directly with the first ajax call, it does not wait for the recursive chain. The other ajax calls are still happening (sequentially, as expected), but are not being tracked by the resulting promise.
To get that, and properly chain the promises so that it resolves with the result of the last ("innermost") promise, you will need to return the promise from the callback to then:
.then(function() {
  return self.saveModel(index + 1, numRequests);
})

A: I'd probably use a for loop rather than a recursive call here, generally - I find those easier to read in this context.
saveModel() {
     var d = $.Deferred(); d.resolve();
     var p = d.promise(); // to start the chain
     this.samplesToSave.forEach(sample => p = p.then(() => makeSaveRequest(sample));
     return p;
}

makeSaveRequest(sample) {
    return $.ajax({...}); // make request using `sample` as data
}


text:
Q: Split string into doublequoted and non doublequoted sections
I'm currently working on a PHP project with a search engine which requires me to break down a search query to an array of substrings.
I want to support "doublequoting" so that the user is able to search for exact results e.g. "super secret stuff" only gets result with that exact string in their name while the same string without quotes returns results for "super" or "secret" or "stuff".
These quotes are supposed to be escapable.
Let me give you an example:
keyword Monday "Larrys \"House\"" epic

Should return an array of
[keyword, Monday, Larrys "House", epic]

I would like to support escaping of the backslashes too if this isn't too difficult to implement e.g. \\" still counts as a quote, while \\\" doesn't and so on.
Any help is appreciated!

A: There is no need to use regex for this as php provides very good CSV parsing routines. Using str_getcsv:
$input = 'keyword Monday "Larrys \"House\"" epic';

$arr = str_getcsv($input, " ");

// remove \\ from array
$arr = array_map(function($elem) { return str_replace ( '\\\\', '\\', str_replace ( '\\"', '"', $elem ) );}, $arr);

// print resulting array
print_r($arr);

Code Demo
Output:
Array
(
    [0] => keyword
    [1] => Monday
    [2] => Larrys "House"
    [3] => epic
)


text:
Q: jquery ui autocomplete source from json file I can incorporate jquery ui autocomplete with source from database. How, I am trying to get the source from a prepared json file, the content is like this:-
{"data":[{"id":"1","country_name_en":"USA","country_name_hk":"\u7f8e\u570b"},{"id":"2","country_name_en":"China","country_name_hk":"\u4e2d\u570b"},{"id":"3","country_name_en":"British","country_name_hk":"\u82f1\u570b"}]}

I tried to modify the jquery codes as follow:-
<script>
$( "#country" ).autocomplete({
    source: function(request,response) {
      $.getJSON('../../database/country.json',{id: data.id},function(data){
            alert(data);
      })
    }
});
</script>

but I think I do not written the format correctly. How shall I improve the way to extract the data from the json file?

A: The autocomplete won't show anything until you tell it to do so by calling the response function passed to your source method with the allowed autocomplete values. So you should do something like this:
$( "#country" ).autocomplete({
    source: function(request,response) {
        $.getJSON('../../database/country.json',{id: data.id},function(data){
            var choices = [];
            for(var i=0;i<data.data.length;i++) {
                choices.push(data.data[i].country_name_en);
            }
            response(choices);
        })
    }
});

Also just a tip, you're going to confuse yourself by naming everything "data".

A: Ajax can be used for this refer this article which list countries from  geonames.org(contains huge list country,state,regions). This will help you in some way.

A: To get data from json try this..
$("#country").autocomplete({
   source: function(request, response) {
       $.getJSON('../../database/country.json', { id: data.id }, function(data) {
          $.each(data, function(key, value) {
               alert(value.country_name_en); // json data
          });
       });
    }
});

A: The problem is, you need to call the autocomplete callback from the ajax success handler.
$(function() {
    $("#country").autocomplete({
        source : function(request, response) {
            $.getJSON('country.json', {
                id : 1
            }, function(data) {
                var list = $.map(data.data, function(item, index) {
                    return {
                        id : item.id,
                        label : item.country_name_en
                    };
                });
                response(list);
            })
        }
    });
})

Demo: Plunker


text:
Q: Indexing numpy array with list of slices I have a list of slices and use them to index a numpy array.
arr = np.arange(25).reshape(5, 5)
# array([[ 0,  1,  2,  3,  4],
#        [ 5,  6,  7,  8,  9],
#        [10, 11, 12, 13, 14],
#        [15, 16, 17, 18, 19],
#        [20, 21, 22, 23, 24]])

slice_list = list(map(lambda i: slice(i, i+2), [1, 2]))
# [slice(1, 3, None), slice(2, 4, None)]

print(arr[slice_list])
# == arr[1:3, 2:4]
# [[ 7  8]
#  [12 13]]

This works fine but it breaks if I have fewer slices than the number of dimensions
of the array I want to index.
arr3d = arr[np.newaxis, :, :]  # dims: [1, 5, 5]
arr3d[:, slice_list]
# IndexError: only integers, slices (`:`), ellipsis (`...`),(`None`)
#  numpy.newaxis and integer or boolean arrays are valid indices

The following examples work however:
arr3d[:, slice_list[0], slice_list[1]]
arr3d[[slice(None)] + slice_list]
arr3d[:, [[1], [2]], [2, 3]]

Is there a way I can use a list of slices to index an array with more dimensions.
I want to do things like:
arr[..., slice_list]
arr[..., slice_list, :]
arr[:, slice_list, :]

without thinking about the dimensions of the array and figuring out how many [slice(None)]*X
I have to pad on either side of my slice_list.

A: You can do that using tuples of slices and ellipsis objects. Just put all the elements to you want to use for indexing into a tuple and use it as index:
import numpy as np

arr = np.arange(24).reshape(2, 3, 4)
print(arr)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
#
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]
slice_tup = tuple(map(lambda i: slice(i, i+2), [1, 2]))
print(slice_tup)
# (slice(1, 3, None), slice(2, 4, None))
print(arr[slice_tup])
# [[[20 21 22 23]]]

# arr[..., slice_list]
print(arr[(Ellipsis, *slice_tup)])
# [[[ 6  7]
#   [10 11]]
#
#  [[18 19]
#   [22 23]]]

# arr[..., slice_list, :]
print(arr[(Ellipsis, *slice_tup, slice(None))])
# [[[20 21 22 23]]]

# arr[:, slice_list, :]
print(arr[(slice(None), *slice_tup, slice(None))])
# IndexError: too many indices for array


text:
Q: Chrome Browser (on Android) Precise GeoLocation function getLocation() {
    var options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 500
    };

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, error, options);
    } else {

    }
}

I am using the above code to get the location on a webpage.  On an iPhone/Safari browser, I get 14 decimal places but only 7 decimal places on Android/Chrome.  How can I get more precise location on the Andriod?

A: Did some tests in Firefox, on laptop and mobile:
Both of them return various precision, based on my location they differ even in lat & long fields during the same request. Looks to me the precision is rounded when its not relevant.

*

*w3c geolocation test requests

*w3c open geolocation docs
What you have to take in consideration is that the html Geolocation API not necessarily requests coordinates via the GPS module, but often chooses IP routes because of power consumption. Which is also very accurate.
Precision within the 5th decimal point is enough to give you a 10meter resolution.
Strict use of GPS is not really possible, but can be "prioritized". You already did that in your code by requesting with options. More info
what you could do, is notify the user of your app when there's or isn't GPS available.
Or, use a different api, for example: mapquest
Is there a possibility that your phone's GPS location service is disabled, and that you're only connected via Cellular network? That would explain why your location points to 1.5 blocks away. The nearest Cellular tower?


text:
Q: Laravel 5: using bcrypt on same string gives different values I am using Laravel's bcrypt function for hashing passwords. When I do,
bcrypt('secret')

I get
=> "$2y$10$mnPgYt2xm9pxb/c2I.SH.uuhgrOj4WajDQTJYssUbTjmPOcgQybcu"

But if I run it again, I get
=> "$2y$10$J8h.Xmf6muivJ4bDweUlcu/BaNzI2wlBiAcop30PbPoKa0kDaf9xi"

and so on...
So, won't the password matching process fail if I get different values every time?

A: Bcrypt uses a 128-bit salt and encrypts a 192-bit magic value. It takes advantage of the expensive key setup in eksblowfish.
The bcrypt algorithm runs in two phases, sketched in Figure 3. In the first phase, EksBlowfishSetup is called with the cost, the salt, and the password, to initialize eksblowfish's state. Most of bcrypt's time is spent in the expensive key schedule. Following that, the 192-bit value ``OrpheanBeholderScryDoubt'' is encrypted 64 times using eksblowfish in ECB mode with the state from the previous phase. The output is the cost and 128-bit salt concatenated with the result of the encryption loop.

How it works in laravel :
if (! function_exists('bcrypt')) {
    /**
     * Hash the given value against the bcrypt algorithm.
     *
     * @param  string  $value
     * @param  array  $options
     * @return string
     */
    function bcrypt($value, $options = [])
    {
        return app('hash')->driver('bcrypt')->make($value, $options);
    }
}

Supported options for PASSWORD_BCRYPT:
salt (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.
If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation.

Warning The salt option has been deprecated as of PHP 7.0.0. It is now
  preferred to simply use the salt that is generated by default.

cost (integer) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.
If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.
How Bcrypt encryption and decryption works:
Internally bcrypt() use uses PHP's built-in password_hash() function. password_hash() returns different values each time because it appends a random string (a "salt") to the password. The salt is actually contained in the output hash.
If the same password is hashed with the same salt, you will always get the same output. Therefore password_verify() looks at the stored hash, extracts the salt, and then hashes the given password with that same salt.

A: This is how bcrypt is supposed to work. See wikipedia.
Bcrypt generates a random 128-bit salt during hashing. This salt becomes part of the hash, hence we always get a different hash value for the same input string. The random salt is actually used to deter brute-force attacks.
The password matching process won't fail due to different values of hashes.
Try the following in tinker
$hash1 = bcrypt('secret')
$hash2 = bcrypt('secret')

Hash::check('secret', $hash1)
Hash::check('secret', $hash2)

You should get true in both the cases of Hash::check.
So even if the hash values are different, the password matching won't fail.


text:
Q: Rails Bootstrap close modal I'm using a Bootstrap modal in a Rails app. I would like to close the modal in the view.
For instance Bootstrap documentation has:
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

I tried this:
<%= submit_tag 'Cancel', :type => :reset, :class => "btn btn-danger", :input_html => {data-dismiss="modal" aria-hidden="true"} %>

But, I get a syntax error.
I want to use the same technique to close the submit button.
I could close it in jquery, but I'd really like to close it in the form.
Thanks!

A: :input_html => {data-dismiss="modal" aria-hidden="true"}

Your hash is malformed. Try this:
:input_html => {"data-dismiss" => "modal", "aria-hidden" => "true"}

I believe you don't even need the :input_html and can just use the inner hash values right away, like so:
<%= submit_tag 'Cancel', :type => :reset, :class => "btn btn-danger", "data-dismiss" => "modal", "aria-hidden" => "true" %>


text:
Q: PostgreSQL query rows with least null value on columns How can I query rows where the output would be the rows with least null value on the columns?
My data is:
ID         | col1     | col2      | col3      | col4
-----------+----------+-----------+-----------+-----------
 1         | Null     |Null       | with value| with value
 2         |with value|Null       | with value| with value
 3         |with value|Null       | Null      | Null

where the result would be:
 ID         | col1     | col2      | col3      | col4
 -----------+----------+-----------+-----------+-----------
  2         |with value|Null       | with value| with value

Because id 2 is the record with fewest null values.
Any help will be greatly appreciated. Thanks

A: You can:

*

*Order rows by number of nulls (ascending)

*Limit rows to 1 ( LIMIT 1 )

Your code:
SELECT *
FROM your_table
ORDER BY
    CASE WHEN col1 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col2 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col3 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col4 IS NULL THEN 1 ELSE 0 END
LIMIT 1

A: If you want only one row, then you can do:
select t.*
from t
order by ( (col1 is null)::int + (col2 is null)::int +
           (col3 is null)::int + (col4 is null)::int
         ) asc
fetch first 1 row only;

If you want all such rows, I think I would do:
select t.*
from (select t.*,
             dense_rank() over
                 (order by (col1 is null)::int + (col2 is null)::int +
                           (col3 is null)::int + (col4 is null)::int
                 ) as null_ranking
      from t
     ) t
where null_ranking = 1;


text:
Q: Azure Data Factory - Azure Dataflow, json being converted/serialized into a different format string For context I have Azure Dataflow reading from CosmosDB where the table has two "schemas". By this I mean one format has a field called "data" that is a JSON representation of data I need. The other format also has a field called "data" but the field is just a compressed string and I believe this is what causes the issue I'm having.
When dataflow reads the field from the source, the JSON gets turned into a non-json format through some form of serialization because when the projection gets imported, the data field is being read as a string and not a complex object. (Example below) I suspect this is because the two "data" fields have the same name.
I unfortunately cannot change how the data is being stored in CosmosDB so I cannot change one of the field names to another value.
Is there any way to prevent this, I would like to keep it in JSON format with quotes and colons etc, instead of what I have below.
Example of data in CosmosDB:
{
  "Name": "sample",
  "ValueInfo": [
     {
       "Field1": "foo",
       "Field2": "bar"
     }
   ]
}

How it looks in ADF
{
  Name=sample,
  ValueInfo=[
     {
       Field1=foo,
       Field2=bar
     }
   ]
}


text:
Q: Polchinski, Making a good gauge choice I was reading Polchinski book and there he tries to make a gauge choice to fix the redundacies in the Polyakov action.
In order to make this choice, he fixes $$\tau=X^{+}\tag{1.3.8a}$$ and then he says $f=\gamma_{\sigma\sigma}\left(-\det\gamma\right)^{-1/2}$ transforms as $$f'd\sigma'=fd\sigma \tag{1.3.9},$$ under reparameterizations of $\sigma$ where $\tau$ is left fixed.  I would like to show this last equation, but I couldn't. Can you help me?

A: Note that the determinant of the metric behave as a $()_{\sigma\sigma}$ (two lower $\sigma$ indices) under $\sigma$-reparametrizations with $\tau$ held fixed.
$$
\det(\gamma_{ab})=\gamma_{\sigma\sigma}\gamma_{\tau\tau}-\gamma_{\sigma\tau}\gamma_{\sigma\tau}
$$
You can see that from the counting how many $\sigma$ indices there are in each term of the determinant. The square root of it, $\sqrt{\det(\gamma_{ab})}$  will behave as $()_{\sigma}$, just one index. Finally, taking the inverse this will behave as $()^{\sigma}$, just one upper index. Now, $f=\gamma_{\sigma\sigma}(\det(\gamma_{ab}))^{-1/2}$ will behave as $()_{\sigma}$ since $2-1=1$. Knowing that $d\sigma$ behave as $()^{\sigma}$ under $\sigma$-reparametrization you get:
$$
fd\sigma=f'd\sigma'
$$


text:
Q: Tab Item remains selected WPF I am using the Tab_SelectionChanged event of TabControl in WPF. It contains 3 tab items. I have to restrict the user to navigate to other tabs i.e Settings and Schedule while work is in-progress on the home tab. While using the event i am facing an issue i.e. If i clicked on settings tab it shows me a popup "You cannot navigate while work is in progress" and when i clicked on schedule tab after clicking on settings tab it shows me the same popup twice. The reason behind this is the Settings tab remains selected.Here is my code for this:
private void tabMHPC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl tab = (TabControl)sender;
            if (tab.SelectedIndex != -1)
            {
                if (tab.SelectedIndex != 4 && tab.SelectedIndex != 1 && tab.SelectedIndex != 0)
                {
                    if (scanStatus == "fixing")
                    {
                        MessageBox.Show(ApplicationInfo.ApplicationName + " is still busy in fixing issues.Please let the fixation complete.", ApplicationInfo.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                        homeTab.IsSelected = true;
                    }
                    else
                    {
                        MessageBox.Show(ApplicationInfo.ApplicationName + " is still busy scanning issues.Please stop it before you leave the Home tab.", ApplicationInfo.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                        homeTab.IsSelected = true;
                    }
                }

                else if (tab.SelectedIndex == 0)
                {

                }
            }
        }

I want that previous tab item isSelected property gets false when i move on other tabitem.

A: Instead of handling the SelectionChanged event, you should data bind a property of a suitable type to the TabControl.SelectedItem property:
<TabControl SelectedItem="{Binding YourSelectedItemProperty}" ... />

When you do this, you will then be able to stop the TabItem being changed:
public YourDataType YourSelectedItemProperty
{
    get { return yourSelectedItemProperty; }
    set
    {
        if (isOkToChangeTabItem)
        {
            yourSelectedItemProperty = value;
            NotifyPropertyChanged("YourSelectedItemProperty");
        }
    }
}

The final part  of the solution is to set the isOkToChangeTabItem variable to true or false depending on whether it is OK for the user to change the selected TabItem or not.


text:
Q: Android App with XML web service We are planning to develop an android application with web service integration using SOAP . There are some authentication details(user id ,password etc.), which are needed to access the web-service . Is it secure to put this details in application's local database? If you have any alternate options, please share with us.

A: I suggest not to save passwords locally, it's not safe to do that.

A: You can use userid to store in local database.
But i think you don't need to save password in your local database.
So, my suggestion is, if necessary store userid not password or another option is use "preference" for this type of storage.


text:
Q: Can I re-publish links extracted from Stack Exchange data dumps under the public domain? After looking around and finding none, I'm trying to link as many Stack Exchange tags as possible to WikiData entities.  My ultimate goal is to automatically categorize tags on Stack Overflow based on categories in Wikipedia.
I've gone through the steps to create a property on WikiData to hold URLs of equivalent Stack Exchange tags on WikiData entities.  I've manually added a few instances of tags to entities.  Now I'd like to add a few thousand more via a bot, but before I do, I want to make sure I properly follow the license on Stack Exchange data.
The best way I could think of to seed the entity/tag links was to look at the Stack Overflow tag wikis.  From the May data dump I have extracted a few thousand links to Wikipedia articles found in the Stack Overflow tag wikis.  I've manually reviewed them to ensure an approximate one-to-one relationship between the tags and the Wikipedia articles.  I'm very confident in the quality of the links, and now I want to add them to WikiData.
The Stack Exchange data in totality is CC-by-SA 3.0 licensed. WikiData is CC0/Public Domain.  Would the nature of the extraction I've done (pulling out just the links to Wikipedia articles and converting them to WikiData entities) be transformative enough to permit me to use the fair use exemption to publish the derived data under the public domain suitable for use in WikiData?  Or do I need to seek special permission from Stack Exchange?
Or do I have to ask people to construct the links by hand?


text:
Q: Error:  attribute x: Expected length, "NaN" I try to implement a bar chart with D3, but it seems to give me an error like this:

Error:  attribute x: Expected length, "NaN".

This is my code:
let url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";

let margin = {
  left: 80,
  right: 20,
  top: 20,
  bottom: 20
};

let w = 1000 - margin.left - margin.right;
let h = 500 - margin.top - margin.bottom;

d3.json(url).then((json) => {
  let data = json.data;
  let end = data.length - 1;
  let minDate = data[0][0];
  let maxDate = data[end][0];

  let xScale = d3.scaleTime()
    .domain([minDate, maxDate])
    .range([margin.left, w])

  let yScale = d3.scaleLinear()
    .domain([0, d3.max(data, (d) => {
      return d[1];
    })])
    .range([h, 0])

  let yAxis = d3.axisLeft(yScale)
    .ticks(10, "");

  let xAxis = d3.axisBottom(xScale)
    .tickFormat(d3.timeFormat("%Y"), 5)

  let div = d3.select("body").append("div")

  let svg = d3.select("svg").attr('width', w).attr('height', h);

  svg.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("x", function (d) {
      console.log(d[0].length)
      return xScale(new Date(d[0]))
    })
    .attr("y", function (d) {
      return (yScale(d[1]))
    })
    .attr("height", function (d) {
      return (h - (yScale(d[1])))
    })
    .attr("width", function (d) {
      return (Math.ceil(w / 274))
    })

})

A: There are two issues here:

*

*When creating your xScale you are passing strings not Date objects. Instead, you need to make minDate and maxDate instances of Date:
let minDate = new Date(data[0][0]);
let maxDate = new Date(data[end][0]);

let xScale = d3.scaleTime()
  .domain([minDate, maxDate])
  .range([margin.left, w]);

*You are not appending any SVG when doing:
let div = d3.select("body").append("div")

let svg = d3.select("svg").attr('width', w).attr('height', h);

This appends a <div> on the first line and creates an empty selection on the second line as there is not yet—at least in the code you provided— any <svg> to select. You need to create an SVG and keep a reference to that selection:
// Create a div.
let div = d3.select("body").append("div")

// Append the SVG to the above created div and store the reference in svg.
let svg = div.append("svg").attr('width', w).attr('height', h);

Have a look at the following demo:

let url = "https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json";

let margin = {
  left: 80,
  right: 20,
  top: 20,
  bottom: 20
};

let w = 1000 - margin.left - margin.right;
let h = 500 - margin.top - margin.bottom;

d3.json(url).then((json) => {
  let data = json.data;
  let end = data.length - 1;
  let minDate = new Date(data[0][0]);
  let maxDate = new Date(data[end][0]);

  let xScale = d3.scaleTime()
    .domain([minDate, maxDate])
    .range([margin.left, w])

  let yScale = d3.scaleLinear()
    .domain([0, d3.max(data, (d) => {
      return d[1];
    })])
    .range([h, 0])

  let yAxis = d3.axisLeft(yScale)
    .ticks(10, "");

  let xAxis = d3.axisBottom(xScale)
    .tickFormat(d3.timeFormat("%Y"), 5)

  let div = d3.select("body").append("div")

  let svg = div.append("svg").attr('width', w).attr('height', h);

  svg.selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("class", "bar")
    .attr("x", function (d) {
      return xScale(new Date(d[0]))
    })
    .attr("y", function (d) {
      return (yScale(d[1]))
    })
    .attr("height", function (d) {
      return (h - (yScale(d[1])))
    })
    .attr("width", function (d) {
      return (Math.ceil(w / 274))
    })

})
.catch(e => console.log(e));
<script src="https://d3js.org/d3.v5.js"></script>


text:
Q: Nested Isotope layouts possible? I'm trying to use the Isotope layout library to create a visualization of a number of "houses" (represented by boxes) that each can contain a number of "rooms" (represented by a different colour of boxes).  Each room contains a list of person names - some rooms have few names, some have more.
In HTML it looks like this:

    House A

Room A

Name 1

Name 2

Room B ...

...

    House B
    ...

  ...

I'm then trying to use Isotope twice to get this nested effect:
$(document).ready(function() {
  $('.house').isotope({
    itemSelector: '.room',
    layoutMode: 'masonry',
  });

  $('.houses').isotope({
    itemSelector: '.house',
    layoutMode: 'masonry',
  });
});

The CSS looks like this:
  .room { border: 1px solid black; padding: 4px; margin: 5px; background-color: blue }
  .house { padding: 5px; margin: 5px; background-color: red; }
  .houses { padding: 5px; margin: 5px; }

However it is not working - the "houses" collapse and are show as small boxes in the top left corner. The "rooms" are shown as very narrow boxes seemingly randomly laid out on the page, most of them on top of each other (overlapping) in the top of the page.
If I add a fixed width to .house, for example "width: 30%" - everythings looks great. I then get 3 columns of "houses", with "rooms" neatly layout within.
However it is not what I'm looking for, as sometimes 30% of the page is too large a box, and sometimes it is too little. Especially when the page is supposed to be responsive, it is quite a problem.
How can I get the "outer" Isotope instance to respect the widths calculated by the "inner" Isotope instance?
Have I missed an easier way of doing this? - or do I need to look at a different layout library?
I have created a jsfiddle that shows the problem here:
http://jsfiddle.net/Gt8qn/
When you uncomment "width: 30%;" - the boxes layout properly as nested boxes.


text:
Q: How to show array with objects from JSON on page? I have an array in JSON:
[
    {
        "id": 0,
        "type": "phone",
        "model": "Iphone 11"
    },
    {
        "id": 1,
        "type": "phone",
        "model": "Iphone 11 PRO"
    }
]

I have an 'axios' request :
const [phone,setPhone] = useState({}) // react-hook

const getPhones = () => {
      Axios.get('/phones.json').then(({data}) => {
      setPhone(data)
      console.log(data)
    })
  }

So I want to show, for example 'type' and 'model' from 1st and 2d objects? How i can do it?
It doesn't work

{phone.type}

      <button onClick={getPhones}>click</button>

A: Try to loop and print out. like this:

  c1
  ...

{
   phone.map((p,index)=>(

        {p.mtype}
        ...

   )
}


text:
Q: What is the format specifier of error_code? I'm trying to use Microsoft's cpprestsdk. And I was getting an error, and so I wanted to check the error code. But I'm not able to figure out the format specifier of error_code, and I'm getting this warning :

warning: format '%d' expects argument of type 'int', but argument 3
  has type 'const std::error_code' [-Wformat=]
        printf("HTTP Exception :: %s\nCode :: %d\n", e.what(), e.error_code());

How should I print the error code? Although %d works but I wanted to know the actual specifier so that I won't get any warnings.
PS: I saw some of them here : https://msdn.microsoft.com/en-us/library/75w45ekt(v=vs.120).aspx , but I don't think any of them are any help to me.

A: std::error_code is a class and can not be passed as printf argument. But you can pass an int value returned by error_code::value().

A: here's one way:
#include <system_error>
#include <cstdio>

void emit(std::error_code ec)
{
    std::printf("error number: %d : message : %s : category : %s", ec.value(), ec.message().c_str(), ec.category().name());
}

But let's not use printf...
#include <system_error>
#include <iostream>

void emit(std::error_code ec)
{
    std::cout << "error number : " << ec.value()
              << " : message : " << ec.message()
              << " : category : " << ec.category().name()
              << '\n';
}


text:
Q: Weird text wrapping problem (wrapfigure, wraptable) - trying to wrap text around an image and a table I'm pretty new to LaTeX - I've done a few very basic homework assignments but this is my first time trying to publish a lab report. I've sort of mickey-moused a template that works but I'm having trouble wrapping text around two figures, a table and an image, at the same time. It seems to only want to wrap one or the other.
Here is the public project file -
https://www.sharelatex.com/project/56198221357a320e5b8c8d5e
The issue I'm having is getting text to wrap around the second image and the table at the same time. You'll probably notice a weird out of place "c" next to the table - once that is deleted the text skips the table entirely and only wraps around the image at the bottom. I've been screwing around with it all day and I haven't been able to figure it out.
\lipsum
\begin{wraptable}{l}{90mm}
....
\end{wraptable}
\begin{wrapfigure}
....
\end{wrapfigure}

If I put some text between \end{wraptable} and \begin{wrapfigure} then \lipsum wraps fine, albeit with whatever random test I add between the two. When there is no random text, \lipsum either wraps one or the other depending on where it's placed (before or after)

A: Wrapping something should be in a paragraph. Hence critical part of your file should be (corrected in your file now):
\lipsum
\begin{wrapfigure}{l}{.525\textwidth} %this figure will be at the right
    \includegraphics[width=.525\textwidth]{T vs R - tungsten filament.png}
    \begin{center}
Figure 3
\end{center}
\end{wrapfigure}

%\lipsum

(Observe the position of `\lipsum).
BTW: Replacing all text \\'s by blank lines would help (La)TeX to correct dividing paragraphs into lines.
Edit New version:
$\,$
\begin{wrapfigure}{l}{.525\textwidth} %this figure will be at the right
    \includegraphics[width=.525\textwidth]{T vs R - tungsten filament.png}
    \begin{center}
Figure 3
\end{center}
\end{wrapfigure}

\lipsum


text:
Q: Exclusive batch jobs with javax.batch/jsr352 We have an application which does a lot of imports and exports - basically between CSV files and database tables.
Some of the imports and exports are conflicting (you can't execute them simultaneously) for various reasons (like "legacy code").
We were looking into javax.batch. Conceptually it suits very well. But what we really failed to find is the possibility to somehow manage the "exclusiveness" of certain jobs we want to run.
Could someone please provide a pointer on that? How would we implement exclusive batch jobs with javax.batch? Or should we implement our own JobOperator for this?
Update
What I mean by "exclusiveness" is tha ability to define that certain jobs may not be executed in parallel. In the most trivial case this would mean "only execute one an only one job at time". In more complex cases more complex logic like "job of type A can't run with other jobs of type A or B, but C is OK". The "type of job" is, for instance, jobXmlName here (regardless of job parameters).

A: JSR-352 (and Spring Batch) both avoid the topic of orchestration on purpose.  To do so would require a particular approach which prevents the inherent flexibility these batch frameworks offer.  Because of that, the JobOperator in JSR-352 does not have any notion of preventing one job from running while another one is running.
While you could accomplish this via your own custom JobOperator, I wouldn't recommend that approach.  Instead, you'd be better off moving that one layer higher, into whoever is calling the JobOperator so that the logic for that type of orchestration concern is separated from the implementation details of launching a job.  For example, if you're using a scheduler to launch jobs, I'd put the logic there as to what jobs can run in parallel and which ones cannot...not in a custom JobOperator.


text:
Q: how to write multiline string with same indentation in yaml I want to write multiline string, with two lines, which will be equally indentated by 8 spaces. Ideally without need to have those 8 spaces in input, but I'm willing to do that. Anything so that I can have the result. I think i tried whole documentation. ', | > >-, >+, >8 ..., ... Adding 8char indentation which isn't in source is optional extra, but so far it seems, that in yaml you can have anything but what you actually typed.
• What is the combination for actual as-is multiline string without any yaml transformations (or say impossible if it's impossible)?
• What is the combination for actual as-is multiline string uniformly shifted to the right by N spaces (or say impossible if it's impossible)?
EDIT: specific example:
...

    something: |
      @blahblah
      @blahblah
...

I want field somehting to contain 2 line string, each containing @blahblah, each prefixed by 8 spaces. In JSON you would write(I know I can do that in yaml, but I'd like to use yaml way to write yaml file):
{"something": "        @blahblah\n        @blahblah"}

EDIT 2: providing minimal working example.
Java code:
import java.io.InputStream;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

public class Test {
    public static void main(String[] args) {
        Yaml yaml = new Yaml();
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("test.yaml");
        Map<String, Object> obj = yaml.load(inputStream);
        String s = (String) obj.get("a");
        System.out.println(s);
    }
}

for input:
a: |
                                                                @abc
                                                                @def

I will get:
@abc
@def

For input:
a: |2
                                                                @abc
                                                                @def

I will get:
                                                      @abc
                                                      @def

How can this be explained??? If positive number after | should be for removing extra indentation, I understand it, that without number it will remove all indentation. So if someone want preserved indentation of 4 spaces, it seems he needs to do some math, put indentation of 5 and request to remove 1 using |1. No? This is how it should work? What am I missing?

A:
What is the combination for actual as-is multiline string without any yaml transformations (or say impossible if it's impossible)?

--- |2
          droggel
          jug

You'll get the string as-is, without the 2 spaces indentation specified by the indentation indicator. Since the indicator must be at least 1 (you can't give 0), there is no way to do that without indentation. Still, this seems to do what you want.

What is the combination for actual as-is multiline string uniformly shifted to the right by N spaces (or say impossible if it's impossible)?

YAML is not a programming language and can't do any kind of string transformation, so this is impossible.


text:
Q: crafting a real interpreter using c# from AST I know that there are other question about compiler/interpreter technology and also very good code to study like IronPython to Jurassic.
To me is quite clear how to build an AST (Abstract Syntax Tree) from source, writing a top-descent parser (for the moment I prefer writing than using code-generation tool).
Most sources I'm trying to study when used as interpreters compile the program on fly using API like Reflection.Emit.
Now I'd like to know best practices to build a real interpreter that doesn't compile to .NET VM the source.
Once I got the AST how can I execute the code? Should I use interpreter or visitor design patterns? Or doing something different? What's the best or canonical way?
I know that there's already a question like this but I like more information and more specific to a .NET/C# implementation, if possible.
Regards, Giacomo

A:
Should I use interpreter or visitor design patterns?

I think the names give a hint ;-)
Visitors are good for general operations on ASTs but for performing a singular function (execution / interpretation) you just need one method, hence the interpreter pattern.
Here's a very simple example (but it really doesn't get much more complicated than that, even for complex interpreters):
// Holds function scope etc.
class Context {}

abstract class Node {
    public abstract object Execute(Context ctx);
}

class Number : Node {
    private readonly int x;

    public Number(int x) { this.x = x; }

    public override object Execute(Context ctx) { return x; }
}

class Addition : Node {
    private readonly Node left, right;

    public Addition(Node left, Node right) {
        this.left = left;
        this.right = right;
    }

    public override object Execute(Context ctx) {
        // Verification omitted: do the nested expressions evaluate to a number?
        return (int) left.Execute(ctx) + (int) right.Execute(ctx);
    }
}

… and there you have it. A simple interpreter that knows addition. And here's an example of usage:
var ast = new Addition(new Number(23), new Number(42));
Console.WriteLine("Result = {0}", ast.Execute(new Context()));


text:
Q: angular.js building a fully custom $state.go() I've tried to do this in many ways, ui-sref is not working for me ok because data make it undefined by the time it is created.
I'm quite new even programming but fighting a lot with angular these days.
The point is that is this possible to really create a fully custom $state.go?
When I say fully custom is, how can i construct even the key of the parameter?
In:
$state.go(stateName, {key:value}
Thanks
angular.module('app').directive('directive', ['$state', function ($state) {

  function link(scope, elements, attibutes) {
  //variable data coming example
    data = {
      name: 'name',
      params: {
        key: 'id',
        value: 'sidvalue'
      }
    }

    scope.back = function (data) {
      $state.go(data.name, '{' + data.params.key + ':"' + data.params.value + '"}');
    }
  }

  return {
    restrict: 'E',
    link: link,
    templateUrl: 'path.html'
  };

}]);

EDIT: *********
This is the historic factory gathering info from each state with push and getting it from with my logic when is convenient with get:
 angular.module('app').factory('Historic', ['$q', '$state', function ($q, $state) {
var historic = [];
return {
  historic: {
    push: function (key, value) {
      var str, init = 'general.home';
      str = {
        name: $state.current.name,
        params: {
          key: key,
          value: value
        }
      };

      if ($state.current.name === init) {
        historic = [{
          name: $state.current.name,
        }];
      } else if (historic.length <= 0) {
        historic.push({name: init});
      } else if (historic[historic.length - 1].name !== str.name && historic[historic.length - 1].params !== str.params) {
        historic.push(str);
      }

    },

    get: function () {
      var h = historic[historic.length - 2];
      if (historic.length === 1) {
        h = historic[0];
      }
      return $q(function (resolve, reject) {
        resolve(h);
      });
    },
    pop: function () {
      historic.pop();
    },
    status: function () {
      return historic.length;
    }
  }
};
}]);

For getting it I'm using a directive with a bit more code attached.
Publishing only the related to historic part.
angular.module('app').directive('directiveName', ['$state', 'fHistoric', function ($state, fHistoric) {

function link(scope, elements, attibutes) {

  /*
  historic setup
  */

  if (fHistoric.historic.status > 3) {
    scope.home = true;
  }

  function keycomp(data) {
    if (data.params) {
      key = {id: data.params.value};
    } else {
      key = {};
    }
  }

  scope.back = function () {
    fHistoric.historic.get()
      .then(function (data) {
        keycomp(data);
        if (key) {
          $state.go(data.name, key);
        } else {
          $state.go(data.name);
        }
      });
    fHistoric.historic.pop();
  };
}

return {
  restrict: 'E',
  link: link,
  scope: {
    header: '@',
    state: '@'
  },
  templateUrl: 'path.html'
};
}]);

I really don't like the solution proposed, it is working but the problem with the key values made me to wrap some spaguetti code I really don't like to solve the id: coming from the key value.
Open to new ideas. ;)


text:
Q: Passing multiple proxies to send data to influx by telegraf I have to monitor my on-premise mongodb using telegraf. My influxdb which is acting as a metric collector is installed in a private subnet on cloud. For my telegraf to send data to my influxdb, it has to pass through proxy.
One proxy will allow it to send data to internet ( On-premise)
The other one will be pass the data through bastion server which is in public subnet to my influxdb.
How can do this.
My telegraf agent is installed on a windows machine and my influx is on a ubuntu server. My bastion is also a ubuntu server

A: Are you sending the data to two different influxdb instances (or outputs)?
If yes you just need to use two separate "outputs" in the same config
ie output to two different influxdb instances:
#Telegraf Config File
{... Agent, inputs, etc ...}

#output to first db
[[outputs.influxdb]]
  urls = ["__InfluxEndpoint__"]
  http_proxy = "__ProxyUrl__"
  {...}

#output to second db
[[outputs.influxdb]]
  urls = ["__InfluxEndpoint__"]
  http_proxy = "__ProxyUrl__"
  {...}

Sorry if I ask for more details in the reply but I don't have enough reputation to add comments


text:
Q: Prove that $\mathbf{L}$ is almost a normal modal logic.
Suppose we have a logic $\mathbf{L}$ containing all the propositional tautologies and the formula $\square(p\wedge q)\leftrightarrow(\square p \wedge\square q)$, and it is  closed by Modus Ponens, Substitution and the following rule (R): if $\varphi\leftrightarrow\psi\in\mathbf{L}$ then $\square\varphi\leftrightarrow\square\psi\in\mathbf{L}$. Prove that $\square(p\to q)\to(\square p\to\square q)\in\mathbf{L}$.

I'm really stuck with this exercise. I'm used to propositional calculus, where Modus Ponens and Deduction Thereom are the main tools. Any help is appreciated.

A: Since $\mathbf{L}$ contains all propositionnal tautologies, you have
$$ \Big(p \wedge (p \to q) \Big) \longleftrightarrow \Big(p \wedge q \Big) \in \mathbf{L}$$
whence $$ \Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longleftrightarrow \Big(\operatorname{\square} p \wedge \operatorname{\square} q \Big) \in \mathbf{L}$$
Since $\mathbf{L}$ is closed under Modus Ponens, we get the weakening :
$$ \Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longrightarrow \operatorname{\square} q $$
which is logically equivalent to the Distribution Axiom indeed :
$$\Big(\operatorname{\square} p \wedge \operatorname{\square} (p\to q) \Big)  \longrightarrow \operatorname{\square} q \equiv \operatorname{\square} (p\to q) \longrightarrow (\operatorname{\square} p \to \operatorname{\square} q)$$
Hence the conclusion since $\mathbf{L}$ is closed under substitutions.


text:
Q: Composer RunimeException on Windows 7 I'm newbie in composer and was trying to install behat 3.0.6 via composer but when I executed this command inside my project directory:
1) composer require behat/behat='~3.0.6'
The next problem appear on my terminal:
2)  [RuntimeException]
 Could not read C:\ProgramData\ComposerSetup\bin
 file_get_contents(C:\ProgramData\ComposerSetup\bin): failed to open stream:
  Permission denied
3) Then I ran the command diagnose, that was the result:
Checking platform settings: FAIL
The xdebug extension is loaded, this can slow down Composer a little.
Disabling it when using Composer is recommended, but should not cause issues beyond slowness.
Checking git settings: OK
Checking http connectivity: OK
Checking disk free space: OK
Checking composer version: OK
Notes: I have installed composer following the oficial guide: https://getcomposer.org/doc/00-intro.md#using-the-installer
Any idea?
Thanks!


text:
Q: Define a variable in JavaScript as a block In Swift, I can do this to define a variable:
let foo: String = {
    if bar {
        return "42"
    } else {
        return "43"
    }
}()

How can I define a variable like this in JavaScript? I know that you can define a variable as undefined and redefine it in the if block, but that's an ugly syntax IMO, since "foo" would get repeated 3 times instead of 1 in the Swift example:
let foo

if (bar) {
    foo = "42"
} else {
    foo = "43"
}

A: If you're just setting the value conditionally you can use a ternary expression:
const foo = bar ? '42' : '43'

You could use a function for more complex logic:

let bar = true;
const foo = computeFoo(bar);

function computeFoo(bar) {
  if (bar) {
    return "42";
  }
  return "43";
}

console.log(foo); // 42

Or an IIFE:

let bar = true;
const foo = (() => {
  if (bar) {
    return "42";
  }
  return "43";
})()

console.log(foo); // 42

A: If the logic is short enough you could use a conditional operator:
let foo = bar ? "42" : "43"

If the logic is more complicated, then i personally would do the last example you showed. But one other alternative you could consider is using an immediately invoked function expression:
let foo = (() => {
  if (bar) {
    return "42"
  } else {
    return "43"
  }
})()

This creates an anonymous function, calls it immediately, and then whatever it returns gets assigned to foo.

A: You can use ternary operator:
let variable = true ? "A" : "B"

In you case:
let foo = bar ? '42' : '43'

A: Just to add a frisson to the answer set:

const bar = false

let foo = (() => {
  switch(true) {
    case bar:
      return "42"
    default:
      return "43"
  }
})()

console.log(foo) // 43

A: let foo = bar ? '42' : '43'
condition ? exprIfTrue : exprIfFalse


text:
Q: Strip a parent folder from a zip file Given a zip file with the structure:
  /unwantedParentFolder
    /wantedFolder/**/*
    /wanted.files

Is there an easy way to 'restructure' it so that /unwantedParentFolder is stripped. e.g.:
  /wantedFolder/**/*
  /wanted.files

Ideally using Javascript alone, although I could probably make common linux commands work.

For some further information: I am gluing together Gitlab and AWS CodeBuild using a lambda (hence the Javascript). Gitlab have an api to fetch the current repo files as a zip, and CodeBuild can build from a zip. Unfortunately Gitlab takes the view that the repo should be in a folder in the root, while CodeBuild wants the repo to be the root.
At the moment the best I've got is to package up the linux zip utilities, unzip everything into the temp folder, move one folder up and rezip. But it seems a bit hackey and I'm nowhere near a zip expert so I thought I'd put it out there...

A: Despite having found it, I obviously didn't take a hard enough look at the documentation of JSZip (as suggested by @LGSon)!
https://stuk.github.io/jszip/documentation/api_jszip/generate_async.html does exactly this:
const data = fs.readFileSync('file');
const zip = await JSZip.loadAsync(data);
const rerooted = await zip
  .folder('unwantedParentFolder')
  .generateAsync({ type:"nodebuffer" });
fs.writeFileSync('fixed.zip', rerooted);


text:
Q: SUMPRODUCT marginal tax rate formula stops working when using Excel Table I followed this tutorial to calculate marginal tax rate in my Excel sheet: Using SUMPRODUCT() to calculate variable rates and commissions
The magical formula is =SUMPRODUCT(--(A1>threshold), (A1-threshold), dRate) where threshold, dRate are defined ranges. This has worked for me in the past before I converted the data range to an Excel Table, with structured references.
Now instead of A1, I use [Income] which is the column name in my table. And SUMPRODUCT has stopped working.
=SUMPRODUCT(--([Income]>threshold), [Income]-threshold, dRate)
It simply evaluates to #N/A. Any ideas?

A: If it can be reasonably assumed that the SUMPRODUCT function is in a column within your 'table' then you require the @ symbol to reflect the relative row within the [Income] column.
=SUMPRODUCT(--([@Income]>threshold), ([@Income]-threshold), dRate)

See Using structured references with Excel tables for more information.


text:
Q: PHP error Use of undefined constant includes - assumed 'includes' I am trying to roll my own project but I am having some trouble with a an error that I find a bit quirky and my IDE and xDebug are not turning up many options to a novice like myself.
the following code has a couple of issues but the Use of undefined constant includes - assumed 'includes' is annoying me and I don't know whats wrong.
<?php

//Debug Error Reporting Configuration
error_reporting(E_ALL);

/*
    Do Not Change any of these items unless
    you know what they do and you realy
    have to change them
*/

//Global Function to return includes path
function includes($path, $location){
    return $_SERVER['DOCUMENT_ROOT']. "/" .$path. "/" .$location;
}

//Global Function to return single location path
function location($path){
    return $_SERVER['DOCUMENT_ROOT']. "/" .$path;
}

//Global Functions Include
require(includes(includes, 'functions.php'));

//Messaging Array
$messages=array();

//Database Configuration & Connection
$dbhost="localhost";
$dbuser="root";
$dbpass="SaltWater";
$dbname="platform";

connectToDB();

//Session Variable Registration
session_register("f_name");
session_register("user_id");
session_register("company_id");

//Smarty Template Engine Configuration
define('SMARTY_DIR',  includes(includes, smarty));
require(SMARTY_DIR . 'Smarty.class.php');

$smarty = new Smarty();
$smarty->setTemplateDir(location(templates));
$smarty->setCompileDir(location(cache));
$smarty->setCacheDir(location(cache));

function errorsys($type, $detail){

    $smarty->assign('type',$type);
    $smarty->assign('detail',$detail);
    $smarty->display('error.tpl');
}

?>

EDIT:
Is there an easier way that I have not discovered yet to make a smart way to do my includes without the usual drill down in folders, in case this gets deployed onto a different server?

A: require(includes('includes', 'functions.php'));

You need to make sure the path you're passing into your includes function is a string. Without inverted commas, PHP thinks you're passing a constant which has never been declared. The code will still work because PHP will assume you meant a string, but it will issue a warning.

A: Is includes defined somewhere as a Constant? maybe you meant
require(includes(includes, 'functions.php'));  //if constant includes is defined

Or
require(includes($includes, 'functions.php'));  //if path is stored in $includes

Or you meant
require(includes('includes', 'functions.php')); //if path is 'includes/'


text:
Q: Any specific advantages/insights for kernel Ridge-regression in RKHS? By the representer theorem of RKHS, the solution of kernel ridge-regression in RKHS, $$\underset{f\in \mathcal{H}}{\min} \sum_{i=1}^N (f(x_i) - y_i)^2 +\lambda\|f\|_\mathcal{H},$$ where $\mathcal{H}$ is an RKHS, is given by a linear combination of the kernel functions, i.e., $\hat{f} = \sum_{i=1}^N c_i k(\cdot, x_i)$. This seems like finding a function to interpolate $y_i$'s. Is there any specific benefit/insight of such a formulation using reproducing kernel, rather than using other nonlinear functions such as Fourier basis? Or in general, what is the benefit of using kernel methods in RKHS?

A: It is fast because we are effectively solving a linear problem. And yet we get a high performing non linear function. This is crucial for any application (think of an SVM classifying millions of data points). Any minimizer of the functional $$\mathcal F (f) = \frac{1}{n} \sum\limits_{i=1}^{n} l(f(X_i), Y_i) + G(\|f\|^2_{\mathcal H_K})$$ where $l$ is a loss function, $G$ is a strictly non-decreasing function of the squared norm of $f$ in the RKHS with kernel $K$ has the form $$f^*(.) = \sum\limits_{i=1}^{n} \alpha_i K (x_i, . )$$
This is called the representer theorem. In the proof below, we see that what we are actually doing is minimizing over a subspace of ${\mathcal H_K}$, i.e $S= \operatorname{span}\{ K(x_i, .) | 1 \leq i \leq n\}$, and the repesenter theorem guarantees that the minimizer we obtain is the minimizer over the whole space ${\mathcal H_K}$. If you proceed like this with another subspace, say the span of the Legendre polynomials or other Fourier basis, it does not hold in general that the minimizer over that subspace is actually the global minimizer.
The representer theorem has huge implications in practice. Let us look at an example. Let $\mathcal H_K$ be a RKHS with kernel $K$. Suppose we are interested in minimizing a regularization of the squared error risk
$$\hat f_{n,\lambda} = \operatorname{argmin}_{f \in \mathcal H_K} \frac{1}{n} \sum\limits_{i=1}^{n} (f(x_i) - y_i)^2 + \lambda \|f\|_{\mathcal H_K}^2$$
Then we know that any minimizer $f$ has the form
$$ f(.) = \sum\limits_{j=1}^{n} \alpha_j K(x_j,.)$$
Observe that
$$f(x_i) = \sum\limits_{j=1}^{n} \alpha_j K(x_j,x_i) = \sum\limits_{j=1}^{n} \alpha_j K(x_i,x_j)$$
and that
\begin{align}
\|f\| ^2_{\mathcal H_K} &= \langle { f, f }\rangle_{\mathcal H_K} \\
&= \Big\langle { \sum\limits_{i=1}^{n} \alpha_i K(x_i,.), \sum\limits_{j=1}^{n} \alpha_j K(x_j,.) }\Big\rangle_{\mathcal H_K} \\
&= \sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} \alpha_i \alpha_j \big\langle {K(x_i,.), K(x_j,.) }\big\rangle_{\mathcal H_K}
\end{align}
Using matrix notation $\mathbb K_{ij}:=\big\langle K(x_i,.), K(x_j,.) \big\rangle_{\mathcal H_K}$, we get
$$\hat f_{n,\lambda} = \sum\limits_{j=1}^{n} \alpha_j^* K(x_j,.)$$
where
$$\mathbb \alpha^* = \operatorname{argmin}_{\mathbb \alpha} \frac{1}{n} \|{\mathbb Y-\mathbb K \mathbb \alpha}\|^2 + \lambda \mathbb \alpha \mathbb K \mathbb \alpha $$
This is a convex differentiable cost function, we can find its minimum by setting its gradient to zero
$$ - \mathbb K ( \mathbb Y - \mathbb K \alpha^*) + \lambda n \mathbb K \alpha^* = 0 $$
which implies, when matrix $\mathbb K$ is strictly positive definite, that
$$\alpha^* = ( \mathbb K + \lambda n \mathbb I )^{-1} \mathbb Y$$
where $\mathbb I$ is the identity matrix. This is a $n \times n$ linear system. It can be solved numerically by means of Cholesky factorization (complexity of $O(n^3)$).
Once the $\alpha^*$ computed, we can use $\hat f_{n,\lambda}$ on new data
$$\hat f_{n,\lambda} (x_{\text{new}}) = \sum\limits_{j=1}^{n} \alpha_j^* K(x_j,x_{\text{new}}) = \mathbb K_{x_{\text{new}}} \alpha^* = \mathbb K_{x_{\text{new}}}( \mathbb K + \lambda n \mathbb I )^{-1} \mathbb Y$$
This operation has cost  $O(n^2)$ for each new example.
Here is the proof of the representer theorem where we explicitly use the reproducing property.
We project $f$ onto the subspace
$$S= \operatorname{span} \{ K(x_i, .) | 1 \leq i \leq n\}$$
By the orthogonal decomposition theorem in Hilbert spaces, we have $f= f_1 +f_2$, where $f_1$ is the component in $S$ and $f_2$ the one orthogonal to $S$. By Pythagoras theorem, we have
$$ \|f\|^2 \geq \|f_1\|^2$$
Since $G$ is non-decreasing, we have
$$G(\|f\|^2_{\mathcal H_K}) \geq G(\|f_1\|^2_{\mathcal H_K})$$
Notice that (using the reproducing property)
$$f(x_i)= \langle f, K(x_i,.) \rangle = \langle f_1, K(x_i,.) \rangle + \langle f_2, K(x_i,.) \rangle = \langle f_1, K(x_i,.) \rangle = f_1(x_i)$$
This implies that
$$l(f(x_i), y_i) = l(f_1(x_i), y_i)$$
So the loss function only depends on the component in $S$ and $G$ is minimized if $f$ lies in $S$. Hence we can find a minimizer in $S$
$$f^*(.) = \sum\limits_{i=1}^{n} \alpha_i K(x_i,.)$$
As $G$ is strictly non-decreasing, $||f_2||$ must be zero for $f$ to be a minimizer of $\mathcal F (f)$. In conclusion, any minimizer has the above form.


text:
Q: React Admin doesn't list objects when auth middleware is added So i have an API, which is connected to Ract Admin dataProvider with simpleRestProvider. I have firebase authorization in my React Admin application (using react-admin-firebase library).
const dataProvider = simpleRestProvider('http://localhost:5552/api/v1');

Without any middleware, data that arrives is displayed normally.
Data displayed correctly
Now, to add auth middleware, I passed auth token according to documentation:
const AuthUser = async function() {
  const token = await authProvider.getJWTToken();
  return token;
}

const httpClient = (url, options = {}) => {
  AuthUser().then(token => {
    options.user = {
      authenticated: true,
      token: `Bearer ${token}`
  };
  console.log(fetchUtils.fetchJson(url, options))
  return fetchUtils.fetchJson(url, options);
  });
};

const dataProvider = simpleRestProvider('http://localhost:5552/api/v1', httpClient);

And I receive this auth token header in my backend, the auth middleware passes through. This is how middleware looks:
import {Request, Response, NextFunction} from 'express';
import * as admin from 'firebase-admin';
import {ServiceAccount} from 'firebase-admin';

import * as serviceAccount from '../config/admin-panel.json';

admin.initializeApp({
  credential: admin.credential.cert(<ServiceAccount>serviceAccount),
});

export async function checkAuth(req: Request, res: Response, next: NextFunction) {
  const {token} = req;
  if (token) {
    admin
      .auth()
      .verifyIdToken(token)
      .then(() => {
        console.log('verified token');
        next();
      })
      .catch(() => {
        res.status(403).send('Unauthorized');
      });
  } else {
    res.status(403).send('Unauthorized');
  }
}

And the response I get from the backend is exactly the same as with normal dataProvider without passing auth header, but I get an error from React Admin and users do not get displayed, even though in Network you can see the data arrives:
Error appears
I assume there needs to be something wrong in the frontend part, but I can't figure out what. I did everything according to docs available here: https://github.com/marmelab/react-admin/tree/master/packages/ra-data-simple-rest.
Does anyone have an idea what could be wrong?
Edit:
To provide more info, in console I'm getting two errors
TypeError: httpClient(...) is undefined - useDataProvider.ts:118
Error: The dataProvider threw an error. It should return a rejected Promise instead.


text:
Q: Axios - how can I conditionally append fields I have this Axios patch but I only want to include the last three, if the hyperlink_column isn't null. How can I do this?
Thanks,
Mick
  axios.patch('/' + self.table + '/' + self.rowId,{

                name: self.name,
                SQL:self.SQL,
                area_id:self.area_id,
                report_type_id:self.report_type_id,
                mode:self.mode,
                database_connection_id:self.database_connection_id,
                pagination: self.pagination,
                show_export_buttons : self.show_export_buttons,
                filters : self.filters,
                description : self.description,
                category_id : self.category_id,

                hyperlink_column : self.hyperlink_column,
                linked_report : self.linked_report,
                link_parameter : self.link_parameter,

A: Since by the look of it, it looks like the second parameter is an object, so one way of doing it, would be to invoke a function as the second parameter and passing your data inside self as an argument. The function will then check if  self.hyperlink_column exists and then return an object accordingly. like this
Repl
PS : This is done using closure.


text:
Q: Shortcuts with Symfony2 Twig forms : form_widget I would like to replace:
{{ form_errors(form.name) }}
{{ form_widget(form.name, { 'attr': {'placeholder': 'Nom'} }) }}

By:
{{ form.name|field('Nom') }}

How could I do that? I tried to do it in a Twig extension but I don't have access to the form_widget function.
Edit: I could do it with the form.name properties (that include the parent form) but I would repeat symfony code, it would be a very ugly big hack

A: Makes more sense if you ask me to move the attr to your form class:
class SomeForm extends AbstractType {
      //.....
      $builder->add('name', 'text', array('attr' => array('placeholder'=>'Nom')));
}

Since i guess you need some custom rendering for some of your fields you can check:
http://symfony.com/doc/2.0/cookbook/form/form_customization.html#how-to-customize-an-individual-field
You could also create a new type and customize it as explained here:
http://symfony.com/doc/2.0/cookbook/form/form_customization.html#what-are-form-themes
You could even change the default way of rendering and ask symfony to render your placeholder tag by default using the field's label string (the details of enabling the form theme globally are covered by the link referenced above):
{% block text_widget %}
    {% set type = type|default('text') %}
    <input type="text" {{ block('widget_attributes') }} value="{{ value }}" />
{% endblock field_widget %}

{% block widget_attributes %}
  {% spaceless %}
    {% for attrname,attrvalue in attr %}{{attrname}}="{{attrvalue}}" {% endfor %} placeholder="{{ label|trans }}"
  {% endspaceless %}
{% endblock widget_attributes %}

{% block form_row %}
  {% spaceless %}
    <div class="my-class">
        {{ form_errors(form) }}
        {{ form_widget(form) }}
    </div>
  {% endspaceless %}
{% endblock form_row %}

So you would limit yourself to a form_row(form.name) using the theming that symfony provides.
Symfony's aproach looks "very" DRY/DIE to me.
Hope it helps.


text:
Q: To create a VI which removes all numbers from a string and counts them in LabVIEW I need to create a VI which removes all numbers from a string and counts them in LabVIEW.
For example, if there's a string "12Anna33" this VI has to transform it into "Anna" and to count the amount of numbers in the string - 4.
How can I do this in LabVIEW?

A: Here is fixed solution from @Vignesh, which takes into account zeroes + uses conditional terminal for For Loop output:

But, @sweber referred to even easier solution from another thread:

A: As both previous answers given in the comment doesn't have count feature,  this will suit your requirement perfectly.

Drag and drop this Vi Snip to LabVIEW 2017 or Above


text:
Q: Image doesn't add to Gallery after saving I'm using couple of commands from this answer to save my bitmap on SD card and then share it via intent.
and here is my final code:
                    View u = findViewById(R.id.mainL);
                    u.setDrawingCacheEnabled(true);
                    LinearLayout z = (LinearLayout) findViewById(R.id.mainL);
                    int totalHeight = z.getHeight();
                    int totalWidth = z.getWidth();
                    u.layout(0, 0, totalWidth, totalHeight);
                    u.buildDrawingCache(true);
                    Bitmap b = Bitmap.createBitmap(u.getDrawingCache());
                    u.setDrawingCacheEnabled(false);
                    String filePath = Environment.getExternalStorageDirectory()
                            + File.separator + "pics/screenshot.jpeg";
                    File imagePath = new File(filePath);
                    FileOutputStream fos;
                    try {
                        fos = new FileOutputStream(imagePath);
                        b.compress(CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (FileNotFoundException e) {
                        Log.e("GREC", e.getMessage(), e);
                    } catch (IOException e) {
                        Log.e("GREC", e.getMessage(), e);
                    }
                    Uri bmpUri = Uri.parse(filePath);
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("image/jpeg");
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(Intent.createChooser(shareIntent, "Share"));

but now I have two problems.
1)the result Image (screenshot.png) is not reachable with mobile gallery (there is a image file in pics folder in sd card although).
2)when I try to share it via intent, it doesn't send and for example when I send it via Bluetooth the receiver gadget breaks the sending operation.
thanks.

A: ohk just paste this line after adding any pic in the gallery it will refresh your gallery
It worked for me hope will help u :)
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));

A: try this
                //save image into sdcard
                FrameLayout f=(FrameLayout)findViewById(R.id.framelayout);
                f.setDrawingCacheEnabled(true);
                Bitmap bm = f.getDrawingCache();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte[] imageInByte1 = stream.toByteArray();

                String  path = Environment.getExternalStorageDirectory().toString();
                File  imgDirectory = new File(Environment.getExternalStorageDirectory()+"/images/");
                imgDirectory.mkdirs();
                OutputStream fOut = null;
                File file = null;
                file = new File(path,"/images/"+etcardname.getText().toString()+ ".png");
                Toast.makeText(getBaseContext(), "saved at: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                fOut = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                fOut.close();

              //share  image
               Intent share = new Intent(android.content.Intent.ACTION_SEND);
               share.setType("image/*");
               share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file));
               startActivity(Intent.createChooser(share, "Share image using"));


text:
Q: Get all role names in ASP.NET MVC5 Identity system MVC5 uses a new Identity System. How can I get all role names?
I try do access it via IdentityStore but without success.

A: There's currently no way to do enumeration style methods via the identity interfaces, that will be coming in a future update targeting administration scenarios(post 1.0 RTM), so there's no way to enumerate all users or roles via the Identity APIs.  That said, you can always drop down to EF or whatever the store implementation is to directly enumerate the roles/users.

A: This is a bit more intuitive
var roles = dbContext.Roles.OrderBy(x => x.Name);

A: I've found that you can use the DbContext via the IdentityStore instance and use the well-known method .Set<T>().
This works for me:
var identityStore = new IdentityStore();
foreach (var role in identityStore.DbContext.Set<Role>())
{
    Debug.WriteLine(role.Name);
}


text:
Q: Could not establish trust relationship for the SSL/TLS secure channel with authority while accessing web service (.asmx) I am getting "Could not establish trust relationship for the SSL/TLS secure channel with authority" error while accessing web service (.asmx).
This error is not coming for every request. We receive this error every 4 out of 10 requests and its random.
Need help here as We are stuck with this from couple of days.


text:
Q: Linear boundary value problem $ a(x)u''(x) + b(x)u'(x) = f(x)$ I'm trying to solve this boundary value problem and need help.

Let $a,b,f \in L^{\infty}((0,1))$. Assuming that a $\gamma >0$ exists so that $a(x) \geq \gamma $ for almost all $x \in (0,1)$, solve
  $$a(x)u''(x) + b(x)u'(x) = f(x) \quad\forall x \in (0,1)$$
$$u(0)=0,\quad u(1)=1$$
Note: You should be able to use the identity $h''-g'h' = e^g (e^{-g} h')'$.

How to start? I think you're meant to use the identity at the start and I'm not sure how because the problem doesn't have that form.


text:
Q: mongoDB sort by percentage I know this can be done, but the issue I face is all my attempts I can't get it to work.
The percents are saved as 0.03 or 0.05 or 0.10
I tried to sort them by
$cursor->sort(array("offers"=>array("percentage"=>0)));

I have also tried
$cursor->sort(array("offers"=>array("cashback"=>1)));

but no changes.
Here is a sample collection
array (
  '_id'▼ => new MongoId("50513d8338fc5de706000000"),
  'test' => new MongoInt32(1),
  'offers' =>
  array (
    '0' =>
    array (
      'minspend' => '50.00',
      'cashback' => '1.50',
      'percentage' => '0.03',
    ),
    '1' =>
    array (
      'minspend' => '100.00',
      'cashback' => '3.00',
      'percentage' => '0.03',
    ),
  ),
)

A: Russell,
Sort is used to arrange the order of whole documents. Form this you look to be attempting to sort arrays within a single document.
To accomplish this you will need to retrieve the whole document and then need to write your own sort function client (PHP) side.
Please have a look at using the usort function in PHP.
http://php.net/manual/en/function.usort.php


text:
Q: PhpStorm does not process functions return type Say I have the following code:
/**
 *
 * @return {string}
 */
function f() {
    return '';
}

f().toFixed();

toFixed is not highlighted with an error of incorrect method. It only works if I do the following:
/** @type {string} */
var a = f();
a.toFixed();

Does not PhpStorm support processing return variables or do I code something wrong?
Edit 1:
I add a screenshoot of how I see this cose in PhpStorm:

Add I must say that PhpStorm really at first offers methods from String#. It is good. My concern is that does not mark toFixed as an error when I specify string type on a var. See the following image:


text:
Q: Responsive inline-block not shrinking in Mozilla (alternate CSS method?) I'm trying to display a responsive (resizes with browser as it shrinks but maxes out at it's own maximum pixels) with a caption. I thought I had come up with a solution using
display:inline-block

on the parent div to the caption but then realized it does not work in Mozilla.
Here is my working solution (is not responsive in Mozilla - image never shrinks):
http://jsfiddle.net/eBy9H/2/
Here is it without "inline block" and not displaying properly (when browser is wider than image the caption div "cappic" runs 100% of the parent div:
http://jsfiddle.net/eBy9H/1/
Is there a way to "shrink wrap: the caption div inside of it's parent so that it doesn't overflow without using inline-block (since it appears inline-block is not responsive in Mozilla)? Thank you!

A: You don't have max-width: 100% on .picwrap. See fiddle.


text:
Q: bash script to find out largest git tag name Say below command list all git tags, how to modify it to get the largest tag?
git tag

Current output is:

    V1.0.0
    V1.0.1
    V1.0.2
    ...
    V1.0.23

I expect the output is V1.0.23 for this example

A: Have Git sort them for you, by version, descending, and pick just the first one:
git tag --list --sort='-version:refname' | head -n1

Or pipe the tags to a sort that knows version sort (such as GNU sort):
git tag | sort -rV | head -n1


text:
Q: Apache Server on Ubuntu 18.04 serves site to elastic IP but not to domain ERR_CONNECTION_REFUSED I created an Apache2 web server on an ec2 Ubuntu 18.04 instance on AWS. I have a domain purchased from a third party register (Porkbun) that I wish to connect to my ec2 instance. I have taken the NS from AWS Route 5S and copied them over to Porkbun, so they should be pointed to AWS Route 5S. On Route 5S I have created A records for *<domain_name>, www<domain_name> and @<domain_name> to the elastic IP of my ec2 instance. When using nslookup <domain_name> it returns the elastic IP.
When I put the elastic IP in the web browser it returns the apache default page with no issue when trying http://<domain_name> it returns ERR_CONNECTION_REFUSED. My inbound/outbound rules on AWS allow http/https from anywhere with the only restriction is on SSH to my personal private IP address. I even disabled ufw to see if that was causing an issue - with the same result.
When using a network sniffer I can see the hits when refreshing the browser on the http:<elastic_IP>, but nothing when I browse http:<domain_name>
Any help would be greatly appreciated.
Virtual host for http traffic
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName <domain_name>
    ServerAlias www.<domain_name>
    DocumentRoot /var/www/<domain_name>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory />
        Require all granted
    </Directory>
</VirtualHost>

A: I used Certbot to create an SSL certificate for <domain_name> and after the successful creation of the certificate accessing the domain worked! When I was attempting to connect to my domain I was specifically trying http://<domain_name> in my browser since I had not created a Virtual Host for 443 traffic. I am guessing Apache was forwarding traffic to the https site - which would explain why I was receiving ERR_CONNECTION_REFUSED when attempting to access the content.