text:
Q: Avaliando a resposta $http do factory para o controller no AngularJS Criei uma Factory para realizar as operações CRUD em uma api REST usando o $http service para fazer um controle de usuários.
Factory
//Listar..Recuperar ..Inserir ...Editar..{...}
usuarioService.Excluir = function (id) {
        var promise = $http({
            method: 'DELETE',
            url: API_URL.url + '/api/v1/usuario/' + id
        })
            .then(function (response) {
                return response.data;
            },
            function (response) {
                return alert(response.statusText + ' ' + response.data.errors + ' ' + response.data.message);
            });
        return promise;
    };

Controller
//Listar..Recuperar ..Inserir ...Editar..{...}
vm.Excluir = function Excluir() {
            usuarioService.Excluir(vm.id).then(function (result) {
                $location.path("/usuario");
            })
        };

Como posso capturar a resposta em casos de erro no meu controller ?

A: Você pode passar diretamente a promessa e usar o .catch para tratar o erro.
Factory:
//Listar..Recuperar ..Inserir ...Editar..{...}
usuarioService.Excluir = function (id) {
  return $http({
      method: 'DELETE',
      url: API_URL.url + '/api/v1/usuario/' + id
  });
};

Controller
vm.Excluir = function Excluir() {
  usuarioService.Excluir(vm.id).then(function(result) {
    console.log(result.data);
    $location.path("/usuario");
  }).catch(function(response) {
    alert(response.statusText + ' ' + response.data.errors + ' ' + response.data.message);
  });
};


text:
Q: Is there a way to make a specific color (white) in an image transparent for a webpage? I want to be able to take my kingdom of loathing signature that has this code:

I want to take the white background of the image and make it transparent. The reason why I can't do this in an image editor is because these signatures update every once in awhile according to what you have been doing in the game.

A: The simple answer is that you can't do this with CSS and HTML.
Adding transparency to the element with CSS like Frank Tudor stated (via opacity) will affect the entire image.
So really you have three options:

*

*Edit the image using design software like Photoshop, removing the
white bg and saving it out as a trans gif or png.

*Utilize CSS opacity, but this will make the entire object transparent. If you're okay with that then this is probably the easiest solution.

*Use a scripting language. As others stated you can technically edit images using certain scripting languages like PHP. This will be the most time-consuming/technical way to perform this task (depending on your coding skills).

Hopefully this helps.

A: If the images are being updated, then it's up to whatever code you are using to dynamically create those images.  You should certainly be able to use transparency when creating the images, regardless of how they are made.
I recommend PNG rather than GIF, but either would work.
Post the code of however you generate the signature images, and someone can help you update it to use a transparent background.

A: There are advanced manipulation functions javascript in one case I remember opacity being used for transparency and in most server-side programming languages you can find image functions.
The problem you face (without an image editor) is that transparency is parameter of the image as it is saved out (and some image types look better than others when it comes to transparency).
You could try this...
Try adding an ID or Class to your IMG tag and this bit of code.
#IDgifThing {
  opacity: 0.5;  /* 50% transparent */
}

I have not tested it, but I hope it helps you or at least puts your mind in the right direction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: should I mix C & C++ style I/O in my C++ program? This question confuses me lot. Because C++ is a superset of C programmer is free to use C's library functions like printf(), scanf() & many others etc. But I usually like C++ 's Object oriented I/O system & I mostly like to use cout & cin. Because iostream is more type safe, less error prone, extensible, flexible & also inheritable. Should I stop using traditional C's I/O functions because of iostream 's advantages or should I modify my program to use ? Which approach is better? Where should I take care when mixing C & C++ I/O. I know that backward compatibility with legacy C programs is necessary, but what should I really do?

A: C++ and C streams are synchronized by default, so you can mix them safely.  This behavior is controlled by std::ios_base::sync_with_stdio.

As to whether you should do it?  Doesn't matter.  C++ does not have a universal style guide.  Some programmers prefer the C++ iostreams interface, some prefer C's methods, some mix them.
Here are some links that discuss the problem better than I can.
Should I switch to C++ I/O streams?
The Duct Tape Programmer - Joel Spolsky


text:
Q: Null homotopic by simplicial approximation If $m<n$ use the simplicial approximation theorem to prove that any map $f:S^m\to S^n$ is null homotopic. Deduce that $\pi_1(S^n)$ is trivial if $n>1$.
we have not covered lot on simplicial approximation. I don't have any reference book ether. If you know any book that has lot of information and solved problems about simplicial map and approximation then please give me the link.
And if you could do this for me then i would be blessed...

A: One particular consequence of simplicial approximation of maps $f:S^m\to S^n$ with $m<n$ is that any such map is homotopic to one which is not surjective: indeed, a simplicial map maps simplice to simplices of no greater dimension, and it follows than any point in the interior of an $n$-dimensional simplex of the codomain is not in the image.
Now it is very easy to show that a non-surjetive map $S^n\to S^m$ (whatever the dimensions) is homotopic to a constant map.

A: If you accept that every map from a contractible space is trivial, notice that{ $S^n -x$} is iso. to $\mathbb R^{n-1}$. Then $f$ can be expressed/"factored" as a composition of maps, one map with domain $\mathbb R^n$. For $\pi_1$ use the same "factorization" of f and functoriality properties of $\pi_1$. EDIT Note we use simplicial approximation , as mentioned by Mariano, to allow for the fact that the map is ( homotopic to a map that is ) not onto.


text:
Q: Where should WSGIPythonPath point in my virtualenv? I have a folder called python2.7 inside of lib in the virtual environment.
After reading half a dozen tutorials, I can't figure out exactly what I'm suppose to point the WSGIPythonPath to. I've seen some pointing to site-packages but some have been a colon : separated list.
Syntax error on line 1019 of /etc/httpd/conf/httpd.conf:
WSGIPythonPath cannot occur within <VirtualHost> section

Where should WSGIPythonPath point in my virtualenv?

A: You are getting the error because WSGIPythonPath Directive cannot be used inside the VirtualHost context. You have to declare it inside your main Apache configuration file. If you still want to point to the directories in your virtualenv inside the VirtualHost context, Use WSGIDaemonProcess Directive instead, it has a python-path option for you to declare your relevant python directories.
For example: your virtual host configuration file should look something like this:
<VirtualHost *:80>
ServerName example.com
CustomLog logs/example.com-access_log common
ErrorLog logs/example.com-error_log

WSGIDaemonProcess example.com python-path=/virtualenvpathto/site-packages:/pathto/exampleprojecthome
WSGIProcessGroup example.com

...
</VirtualHost>

The full colon : is used when you have more than one python directories you want to be added to $PYTHON_PATH environment variable so that say import example.foo works fine. In the above example, there are two directories, they could be more or less depending on how you have setup your project.
If you are on windows, use semicolon ; instead of full colon.
I hope this helps.

A: tl;dr: Use WSGIDaemonProcess python-home=…. The alternatives using either WSGIPythonPath or WSGIDaemonProcess python-path=… (with -path instead of -home!) are no longer recommended.
The old and the new way
As mentioned by @kaykae, WSGIPythonPath cannot be used in a VirtualHost context but WSGIDaemonProcess python-path=… is the equivalent. However while this can still work, it is no longer the recommended way to set up Apache mod_wsgi with virtual Python environments:

Note that prior practice was that these ways of setting the Python module search path [namely WSGIDaemonProcess …python-path=… and WSGIPythonPath] were used to specify the location of the Python virtual environment. Specifically, they were used to add the site-packages directory of the Python virtual environment. You should not do that.
The better way to specify the location of the Python virtual environment is using the python-home option of the WSGIDaemonProcess directive for daemon mode, or the WSGIPythonHome directive for embedded mode. These ways of specifying the Python virtual environment have been available since mod_wsgi 3.0 and Linux distributions have not shipped such an old version of mod_wsgi for quite some time. If you are using the older way, please update your configurations.
(Source: WSGI Docs: User Guides: Virtual Environments)

How to do it the new way
The fact that you try to configure mod_wsgi inside a VirtualHost context shows you use the "daemon mode" configuration version. According to the quote above, the recommended way to include your virtualenv environment into your Python path would then be a section like this in your VirtualHost section (though it can also be defined outside, as it can be referenced with the myapp1 identifier for the daemon process group that you choose):
<IfModule mod_wsgi.c>
  WSGIDaemonProcess myapp1 user=user1 group=group1 threads=5
python-home=/path/to/project/venv
</IfModule>

Note that /path/to/project/venv is the base path of your virtualenv environment. It would be a subdirectory venv in the directory where you called virtualenv venv to create it.
Also note that you can add other paths to your Python path to make your import statements work for packages not managed via PIP or similar. For example you can add python-path=/path/to/project. Just don't use that mechanism to tell wsgi about the whole virtualenv setup – for that they introduced python-home.

A: Here is the official documentation: https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/#using-a-virtualenv

Using a virtualenv¶
If you install your project's Python dependencies inside a virtualenv,
  you'll need to add the path to this virtualenv's site-packages
  directory to your Python path as well. To do this, add an additional
  path to your WSGIPythonPath directive, with multiple paths separated
  by a colon (:) if using a UNIX-like system, or a semicolon (;) if
  using Windows. If any part of a directory path contains a space
  character, the complete argument string to WSGIPythonPath must be
  quoted:

> WSGIPythonPath
> /path/to/mysite.com:/path/to/your/venv/lib/python3.X/site-packages

Make sure you give the correct path to your virtualenv, and replace
  python3.X with the correct Python version (e.g. python3.4).


text:
Q: How to find the lowest and biggest value in a maximum distance between points (SQL) Currently, I have a PostgreSQL database (and a SQL Server database with almost the same structure), with some data, like example below:
+----+---------+-----+
| ID | Name    | Val |
+----+---------+-----+
| 01 | Point A |   0 |
| 02 | Point B | 050 |
| 03 | Point C | 075 |
| 04 | Point D | 100 |
| 05 | Point E | 200 |
| 06 | Point F | 220 |
| 07 | Point G | 310 |
| 08 | Point H | 350 |
| 09 | Point I | 420 |
| 10 | Point J | 550 |
+----+---------+-----+

ID = PK (auto increment);
Name = unique;
Val = unique;

Now, suppose I have only Point F (220), and I wanna to find the lowest value and biggest value with a maximum distance less than 100 between the data.
So, my result must return:

*

*Lowest: Point E (200)

*Biggest: Point I (420)
Step by step explanation (and because english is not my primary language):

*

*Looking for lowest value:
Initial value = Point F (220);
Look for the lower closest value of Point F (220): Point E (200);
200(E) < 220(F) = True; 220(F) - 200(E) < 100 = True;
Lowest value until now = Point E (200)

Repeat

Look for the lower closest value of Point E (200): Point D (100);
100(D) < 200(E) = True; 200(E) - 100(D) < 100 = False;
Lowest value = Point E (200); Break;

*Looking fot the biggest value:
Initial value = Point F (220);
Look for the biggest closest value of Point F (220): Point G (310);
310(G) > 220(F) = True; 310(G) - 220(F) < 100 = True;
Biggest value until now = Point G (310)

Repeat

Look for the biggest closest value of Point G (310): Point H (350);
350(H) > 310(G) = True; 350(H) - 310(G) < 100 = True;
Biggest value until now = Point H (350)

Repeat

Look for the biggest closest value of Point H (350): Point I (420);
420(I) > 350(H) = True; 420(I) - 350(H) < 100 = True;
Biggest value until now = Point I (420)

Repeat

Look for the biggest closest value of Point I (420): Point J (550);
550(J) > 420(I) = True; 550(J) - 420(I) < 100 = False;
Biggest value Point I (420); Break;

A: This can be done using Windows Functions and some working.
In a step by step fashion, you would start by having one table (let's call it point_and_prev_next) defined by this select:
SELECT
    id, name, val,
    lag(val) OVER(ORDER BY id) AS prev_val,
    lead(val) OVER(ORDER BY id) AS next_val
FROM
    points

which produces:
| id |    name | val | prev_val | next_val |
|----|---------|-----|----------|----------|
|  1 | Point A |   0 |   (null) |       50 |
|  2 | Point B |  50 |        0 |       75 |
|  3 | Point C |  75 |       50 |      100 |
|  4 | Point D | 100 |       75 |      200 |
|  5 | Point E | 200 |      100 |      220 |
|  6 | Point F | 220 |      200 |      310 |
|  7 | Point G | 310 |      220 |      350 |
|  8 | Point H | 350 |      310 |      420 |
|  9 | Point I | 420 |      350 |      550 |
| 10 | Point J | 550 |      420 |   (null) |

The lag and lead window functions serve to get the previous and next values from the table (sorted by id, and not partitioned by anything).
Next, we make a second table point_and_dist_prev_next which uses val, prev_val and next_val, to compute distance to previous point and distance to next point. This would be computed with the following SELECT:
SELECT
    id, name, val, (val-prev_val) AS dist_to_prev, (next_val-val) AS dist_to_next
FROM
    point_and_prev_next

This is what you get after executing it:
| id |    name | val | dist_to_prev | dist_to_next |
|----|---------|-----|--------------|--------------|
|  1 | Point A |   0 |       (null) |           50 |
|  2 | Point B |  50 |           50 |           25 |
|  3 | Point C |  75 |           25 |           25 |
|  4 | Point D | 100 |           25 |          100 |
|  5 | Point E | 200 |          100 |           20 |
|  6 | Point F | 220 |           20 |           90 |
|  7 | Point G | 310 |           90 |           40 |
|  8 | Point H | 350 |           40 |           70 |
|  9 | Point I | 420 |           70 |          130 |
| 10 | Point J | 550 |          130 |       (null) |

And, at this point, (and starting with point "F"), we can get the first "wrong point up" (the first that fails the "distance to previous" < 100) by means of the following query:
SELECT
      max(id) AS first_wrong_up
FROM
    point_and_dist_prev_next
WHERE
    dist_to_prev >= 100
    AND id <= 6     -- 6 = Point F

This just looks for the point closest to our reference one ("F") which FAILS to have a distance with the previous one < 100.
The result is:
| first_wrong_up |
|----------------|
|              5 |

The first "wrong point" going down is computed in an equivalent manner.
All these queries can be put together using Common Table Expressions, also called WITH queries, and you get:
WITH point_and_dist_prev_next AS
(
    SELECT
        id, name, val,
        val - lag(val) OVER(ORDER BY id) AS dist_to_prev,
        lead(val) OVER(ORDER BY id)- val AS dist_to_next
    FROM
        points
),
first_wrong_up AS
(
SELECT
    max(id) AS first_wrong_up
FROM
    point_and_dist_prev_next
WHERE
    dist_to_prev >= 100
    AND id <= 6     -- 6 = Point F
),
first_wrong_down AS
(
SELECT
    min(id) AS first_wrong_down
FROM
    point_and_dist_prev_next
WHERE
    dist_to_next >= 100
    AND id >= 6     -- 6 = Point F
)
SELECT
    (SELECT name AS "lowest value"
       FROM first_wrong_up
       JOIN points ON id = first_wrong_up),
    (SELECT name AS "biggest value"
       FROM first_wrong_down
       JOIN points ON id = first_wrong_down) ;

Which provides the following result:
| lowest value | biggest value |
|--------------|---------------|
|      Point E |       Point I |

You can check it at SQLFiddle.

NOTE: It is assumed that the id column is always increasing. If it were not, the val column would have to be used instead (assuming, obviously, that it always keeps growing).


text:
Q: How to get a Tuple for the grouped by result on a Spark Dataframe? I am trying to group entities based on the id, running the following code I have this dataframe:
val pet_type_count = pet_list.groupBy("id","pets_type").count()
pet_type_count.sort("id").limit(20).show

+----------+---------------------+-----+
|        id|            pets_type|count|
+----------+---------------------+-----+
|         0|                    0|    2|
|         1|                    0|    3|
|         1|                    3|    3|
|        10|                    0|    4|
|        10|                    1|    1|
|        13|                    0|    3|
|        16|                    1|    3|
|        17|                    1|    1|
|        18|                    1|    2|
|        18|                    0|    1|
|        19|                    1|    7|
+----------+---------------------+-----+

I want to group the results of the group by on id to now return a list of tuples per id so I can apply the following udf per id:
val agg_udf =  udf { (v1: List[Tuple2[String, String]]) =>
    var feature_vector = Array.fill(5)(0)
    for (row <- v1) {
      val index = (5 - row._1.toInt)
      vector(index) = row._2.toInt
    }
    vector
}

val pet_vector_included = pet_type_count.groupBy("id").agg(agg_udf(col("pets_type_count")).alias("pet_count_vector"))

For which I need to get the following:
+----------+---------------------+-----+
|        id|            pets_type_count|
+----------+---------------------+-----+
|         0|                      (0,2)|
|         1|                      (0,3)|
|          |                      (3,3)|
|        10|                      (0,4)|
|          |                      (1,1)|
|        13|                      (0,3)|
|        16|                      (1,3)|
|        17|                      (1,1)|
|        18|                      (1,2)|
|          |                      (0,1)|
|        19|                      (1,7)|
+----------+---------------------+-----+

I am unable to figure out the how to get tuples after the groupby on id. Any help would be appreciated!

A: You can simply use struct inbuilt function to make pets_type and count columns as one column and use collect_list inbuilt function to collect the newly formed column when grouped by id. And you can orderBy just to order the dataframe by id column.
import org.apache.spark.sql.functions._
val pet_type_count = df.withColumn("struct", struct("pets_type", "count"))
  .groupBy("id").agg(collect_list(col("struct")).as("pets_type_count"))
  .orderBy("id")

this should give you your desired result as
+---+---------------+
|id |pets_type_count|
+---+---------------+
|0  |[[0,2]]        |
|1  |[[0,3], [3,3]] |
|10 |[[0,4], [1,1]] |
|13 |[[0,3]]        |
|16 |[[1,3]]        |
|17 |[[1,1]]        |
|18 |[[1,2], [0,1]] |
|19 |[[1,7]]        |
+---+---------------+

So you can apply the udf function that you have defined (which needs some modifications too) as below
val agg_udf =  udf { (v1: Seq[Row]) =>
  var feature_vector = Array.fill(5)(0)
  for (row <- v1) {
    val index = (4 - row.getAs[Int](0))
    feature_vector(index) = row.getAs[Int](1)
  }
  feature_vector
}

val pet_vector_included = pet_type_count.withColumn("pet_count_vector", agg_udf(col("pets_type_count")))

pet_vector_included.show(false)

which should give you
+---+---------------+----------------+
|id |pets_type_count|pet_count_vector|
+---+---------------+----------------+
|0  |[[0,2]]        |[0, 0, 0, 0, 2] |
|1  |[[0,3], [3,3]] |[0, 3, 0, 0, 3] |
|10 |[[0,4], [1,1]] |[0, 0, 0, 1, 4] |
|13 |[[0,3]]        |[0, 0, 0, 0, 3] |
|16 |[[1,3]]        |[0, 0, 0, 3, 0] |
|17 |[[1,1]]        |[0, 0, 0, 1, 0] |
|18 |[[1,2], [0,1]] |[0, 0, 0, 2, 1] |
|19 |[[1,7]]        |[0, 0, 0, 7, 0] |
+---+---------------+----------------+

I hope the answer is helpful


text:
Q: How can we create multi column table using multi array JSON using d3 and crossfilter javascript frameworks I want to filter using crossfilter and want to create a multi column table using d3. I am having a JSON file to get the datas from table.
My array from JSON is looks like below, I want to group the elements using crossfilter and render the table using d3.
var myJSON = {
    Region [{
        code : New-York,
        id   : 1,
        centre : [{
            name: xxx,
            id : 11
            },{
            name: yyy,
            id : 12,
            },{
            name: zzz,
            id : 13,
            }]
        },
        code : Florida,
        id   : 2,
        centre : [{
            name: aaa,
            id : 21
            },{
            name: bbb,
            id : 23,
            }]
        },
        code : Tennessee,
        id   : 3,
        centre : [{
            name: ccc,
            id : 31
            }, {
            name: ddd,
            id : 32,
            }, {
            name: eee,
            id : 33,
            }, {
            name: fff,
            id : 34,
            }]
        }
    }]
}

HTML page
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>D3: Subselection Example</title>
    <script type="text/javascript" src="d3.js"></script>
    <style type="text/css">

    body {
      font: 13px sans-serif;
  }
  td, th {
    padding: 1px 25px 0px 1px;
    border: 1px black solid;
    width:80px;
}
ul {
  list-style: none;
  font-weight: bold;
}

li {
  margin:  0.2em 0.0em;
  padding: 0.5em 1.0em;
  font-weight: normal;
}

</style>
</head>
<body>
<script type="text/javascript">
d3.json("Udashboard.json", function (error,data) {

function tabulate(data, columns) {
  var table = d3.select('body').append('table')
  var thead = table.append('thead')
  var tbody = table.append('tbody');

// append the header row
thead.append('tr')
.selectAll('th')
.data(columns).enter()
.append('th')
.text(function (column) { return column.id; });

// create a row for each object in the data
var rows = tbody.selectAll('tr')
.data(data.objects)
.enter()
.append('tr');

// create a cell in each row for each column
var cells = rows.selectAll('td')
.data(function (row) {
    return columns.map(function (column) {
      return { column: column.id, value: eval('row.'+column.key) };
  });
})
.enter()
.append('td')
.text(function (d) { return d.value; });

return table;
}

var columnFields = [ { id: "ID", key: "id" },
{ id: "Code", key: "region[0].code" },
{ id: "Name", key: "centre[0].name" } ];

console.log (data);
// render the table(s)
tabulate(data, columnFields); // 2 column table
});

</script>

</body>
</html>

I want to show the results as below in a table.
Regiion  New-York   Florida   Tennessee
  3          3         2          4

How can we do this using crossfilter js and d3 js.
Any help would be accepted.
Thanks in advance

A: That's an easy one! :)
Pseudo code:
data = []
for each region
 for each centre
  data.push(one data object like {region: "...", ...})
c = crossfilter(data)
r = c.dimension(function returning region name)
g = r.group(String)
allRegionsHist = g.top(Infinity)
for each allRegionsHist
 construct one column


text:
Q: Limit a ListIterator to the first N elements (optimized) What is a simple and fast way to get an iterator that returns at most N elements from the start of a List?
The simplest versions I could come up with are:
#1:
import com.google.common.collect.Iterators;

// ...

public static <E> Iterator<E> lengthLimitedIterator(Iterable<E> source, int maxLen) {
    return Iterators.partition(source.iterator(), maxLen).next().iterator();
}

#2:
public static <E> Iterator<E> lengthLimitedIterator(List<E> source, int maxLen) {
    return source.subList(0, Math.min(source.size(), maxLen)).iterator();
}

Unfortunately both versions create a temporary List which significantly affects performance as I am calling this method millions of times in a tight loop.
Are there any other library functions I could use for this?

Note: I cannot avoid iterating over the list as I am passing it to a method which takes an iterator as its argument and I cannot modify that class.

A: Seems as if the feature will be added to guava, currently (as of r06) in beta:
public static <T> Iterator<T> limit(Iterator<T> iterator, int limitSize)

A: This is a place where a Decorator works very well: your decorator keeps a count, which is incremented by next(), and used by control hasNext().
Example (intentionally incomplete):
public class LengthLimitedIterator<T>
implements Iterator<T>
{
    private Iterator<T> _wrapped;
    private int _length;
    private int _count;

    public LengthLimitedIterator(Iterator<T> wrapped, int length)
    {
        _wrapped = wrapped;
        _length = length;
    }

    public boolean hasNext()
    {
        if (_count < _length)
            return _wrapped.hasNext();
        return false;
    }

    public T next()
    {
        // FIXME - add exception if count >= length
        _count++;
        return _wrapped.next();
    }

A: Why not simply
list.subList(0, 42).iterator();

I am not sure why you mind about the creation of that temporary list. It doesn't do anything I'd consider expensive. In fact, creating this list is by far cheaper than iterating over it, which I assume you do.

A: The ArrayList.sublist(int,int) method does not create a copy of the original list.  Instead it returns a SubList instance that wraps the original ArrayList.  The iterator returned by the sublist derived from Array doesn't make a copy either.
So my advice is to try using ArrayList as your base list type and the sublist method.  If that is not fast enough, implement your own variant of ArrayList that implements a limitedLengthIterator method.  For example, you should be able to get rid of the code that checks for concurrent modifications.

A: You already know it's a list, so you can just call the List.subList(int fromIndex, int toIndex) method. As per the specification, the subList is backed by the original list, so it's not really creating a full blown List, just some kind of proxy object.

A: If you are concerned about performance, don't use an Iterator, use an index on an array.  This will give much better performance. Getting the first N elements of an array is trivial.

A: This version turns out to be faster than any of the other examples:
public static <E> Iterator<E> lengthLimitedIterator(List<E> source, int maxLen) {
    maxLen = Math.min(maxLen, source.size());
    ArrayList<E> tempList = new ArrayList<E>(maxLen);
    for (int i = 0; i < maxLen; ++ i) {
       tempList.add(source.get(i));
    }
    return tempList.iterator();
}

If the temporary list has to be created anyway, an ArrayList is faster than the decorated lists returned by the other library methods.
My guess is that ArrayList is getting some special treatment within the VM.
Maybe this would be inefficient for very long lists, but my lists are short (nearly always fewer than 50 elements.)


text:
Q: How to generate assembly code from the Abstract syntax tree? I wanted to know how to generate assembly code from the abstract syntax tree?
Thank you!

A: I am not a master in compiler construction. But if you are a beginner, I guess this answer will help.
First of all, assembly is a platform dependant. You have to decide for which platform you are going to generate assembly code. You can refer to the instruction set architecture for this.
After finalizing that, there are two ways you can generate assembly code.

*

*Generate assembly manually

*Using a library

If you are going to generate assembly manually, you should have a good knowledge of instruction set architecture. You have to traverse through the AST and convert nodes into assembly code. You can use a design pattern like Visitor or Listener aka Observer pattern to traverse through the AST.
Also, you can use a library like Asmjit for machine code generation as well.
Godbolt will help you to get some knowledge about assembly code.
Here are few other Stackoverflow answers that may help you.

*

*Compiling an AST to Assembly

*LLVM - How AST can be transformed to IR

*How Does Assembly Code Generation Work?


text:
Q: disprove that f is continuous with use of its components Let $f\colon\mathbb{R}^2\to\mathbb{R}$ be a function. I need to prove/disprove the claim which says:
$f$ is continuous $\iff$ $f(x,\cdot), f(\cdot, y)\colon\mathbb{R}\to\mathbb{R}$ are continuous for every $y,x$ respectively.
I am pretty sure that this claim isn't true, so I'm going with disprove here.
My counter example was the function $f(x,y) = \cfrac{xy}{x^2 + y^2}$ which is continuous for $x$ alone and for $y$ alone, but $\lim_{(x,y)\to(0,0)}f(x,y)$ doesn't exist. Which means $f$ isn't continuous.
However, I'm not sure if what I'm doing is right.

A: Specific example for disproof:  Let $x=y$, then $f(x,y)=\frac{1}{2}$ for all $x$ and $y$.  Therefore $\lim_{x\to 0,y\to 0}=\frac{1}{2}$ in this direction, which differs from letting them $\to 0$ separately, where the limit is $0$.


text:
Q: Laravel Email Confirmation On Registration I need to send an email after a new user is created.
But I don't know how to return to the home page without getting an error.
This is what I am doing right now.
User::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'phone' => bcrypt($data['phone']),
            'confirmation_code' => str_random(30),
        ]);

Email_function();

if (Auth::attempt(['email' => $data['email'], 'password' => bcrypt($data['password']) ])) {
        // Authentication passed...
        return redirect('/');
    }

I keep getting this as my error message.
SErrorException in SessionGuard.php line 439:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /Applications/XAMPP/xamppfiles/htdocs/sniddl/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 63 and defined

Edit:
changed the title to reflect the answer.

A: Here is a modified create function with an added email function for your register controller
Make sure Request is included in the pages top with namespaces being used:
use Illuminate\Http\Request;

Change the create function in your controller:
protected function create(Request $data)
{

    $user                       = new User;
    $user->name                 = $data->input('name');
    $user->username             = $data->input('username');
    $user->email                = $data->input('email');
    $user->password             = bcrypt($data->input('password'));
    $user->phone                = bcrypt($data->input('phone'));
    $user->confirmation_code    = str_random(60);
    $user->save();

    if ($user->save()) {

        $this->sendEmail($user);

        return redirect('VIEWPATH.VIEWFILE')->with('status', 'Successfully created user.');

    } else {

        return redirect('VIEWPATH.VIEWFILE')->with('status', 'User not created.');

    }

}

Create the sendEmail function in the same controller that will use Laravels built in email. Make sure you create and your HTML email:
public function sendEmail(User $user)
{
    $data = array(
        'name' => $user->name,
        'code' => $user->confirmation_code,
    );
    \Mail::queue('EMAILVIEWPATH.HTMLEMAILVIEWFILE', $data, function($message) use ($user) {
        $message->subject( 'Subject line Here' );
        $message->to($user->email);
    });
}

NOTE:
Your going to need to update the VIEWPATH.VIEWFILE and EMAILVIEWPATH.HTMLEMAILVIEWFILE at a minimium in the examples above.
Check the repos below for CONTROLLER :
https://github.com/laravel/laravel/blob/master/app/Http/Controllers/Auth/RegisterController.php
https://github.com/jeremykenedy/laravel-auth/blob/master/app/Http/Controllers/Auth/AuthController.php
REGISTER VIEW(blade) EXAMPLE
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/auth/register.blade.php
EMAIL VIEW THAT RECEIVES VARIABLES:
https://github.com/jeremykenedy/laravel-auth/blob/master/resources/views/emails/activateAccount.blade.php

A: Ok so it turns out, by setting User::create as a variable it allows you to login in the user by returning the variable. Like this.
$user = User::create([
            'name' => $data['name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'phone' => bcrypt($data['phone']),
            'confirmation_code' => str_random(30),
        ]);

Email_function();

return $user;


text:
Q: How can I order datetime strings in Javascript? I get from youtube JSON request (after a small parsing of the objects) these strings (which should represents datetime) :
2009-12-16T15:51:57.000Z
2010-11-04T10:01:15.000Z
2010-11-04T14:00:04.000Z
2010-11-04T11:12:36.000Z
2010-11-04T10:24:26.000Z
2010-11-04T12:05:58.000Z
2010-04-30T13:28:08.000Z
2010-11-17T13:57:27.000Z

In fact I need to order these list (descending), for taking the recent video published.
But how can I order those datetime? Is there a native method on JS?

A: An easy way to achieve this would be to put all those into an array of strings and sort that array.
var arr = [ "2", "1", "3" ];
arr.sort(); // this gives [ "1", "2", "3" ]

You can read the full doc there :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/sort

A: You can just use a default sort method for this because the dates are perfectly formatted to do some sorting (year, month, day, hour, minute, second). This would be much more difficult if that was the other way around. Check out sort for example:
var unsortedArray = [
    "2009-12-16T15:51:57.000Z",
    "2010-11-04T10:01:15.000Z",
    "2010-11-04T14:00:04.000Z",
    "2010-11-04T11:12:36.000Z" ];

var sortedArray = unsortedArray.sort();

If you would like to reverse (descending) sorting, add .reverse() to the sorted array.

A: You asked for a descending sort.  A quick way is to use reverse.
http://jsfiddle.net/6pLHP/
a = [
    "2009-12-16T15:51:57.000Z",
    "2010-11-04T10:01:15.000Z",
    "2010-11-04T14:00:04.000Z",
    "2010-11-04T11:12:36.000Z",
    "2010-11-04T10:24:26.000Z",
    "2010-11-04T12:05:58.000Z",
    "2010-04-30T13:28:08.000Z",
    "2010-11-17T13:57:27.000Z"
];
alert(JSON.stringify(a.sort().reverse()));


text:
Q: Is there a site where I can download zipped JDKs? I am specifically looking for JDK 9 I don't have admin rights on my machine. Hence I am looking for a zipped version of JDK 9. Is there any site that can help? Thanks.

A: Which implementation are you looking for?
For adoptopenjdk it's here.
For Oracle.


text:
Q: MarkLogic: Connectors to SPSS I have a question regarding connecting MarkLogic and SPSS Modeler
 - I have my data stored in MarkLogic.
 - I want to do text mining in SPSS using the data stored in MarkLogic.
 - How do I connect SPSS and MarkLogic?

A: Probably with ODBC: http://developer.marklogic.com/products/odbc
It will be up to you to decide how best to map your XML documents to SQL.


text:
Q: Observable sequence with dependencies I want to combine two http get requests.
They should be executed after each other and the second one gets a part of the first ones result as a parameter.
The combined request then should return a list like:
[first result json, seconds result json]
I've already found this on stackoverflow: How to combine two similar http requests returning Rx Observables?
With forkJoin I can combine the two requests.
return forkJoin(
    this.spotify.getSpotifyData(spotifyId),
    this.youtube.getYoutubeData(PARAMETER HERE)
);

How can I take the result from the first as a parameter of the second one?
UPDATE
This question got marked as a duplicate of How to finalize nested Observables? but that solution does not work for me.
Here's my updated code:
return this.spotify.getSpotifyData(spotifyId).pipe(
    switchMap(
        spotifyResult => {
            return this.youtube.getYoutubeData(spotifyResult["name"]).pipe(
                map(
                    youtubeVideoResult => {
                        ({spotifyResult, youtubeVideoResult})
                    })
                )
        }
    )
)

Then I subscribe like this: (note: getDataBySpotifyId method is the one from above)
getDataBySpotifyId(id).subscribe(
    ({data,data2}) => {
        console.log("data: " + data);
    }
)

and I get the following error:
ERROR TypeError: Cannot read property 'data' of undefined


text:
Q: Geopandas - Simply way to count number of x,y pairs I have a geopandas dataframe:
import geopandas as gp
shp = gp.GeoDataFrame.from_file('example_file.shp')
shp.head(1)

SHAPE_LEN, SHAPE_AREA, geometry
21685      1.400       POLYGON ((-94.56994242128158 39.0135784915016, -94.56996218461458 39.01306817553366, -94.57042915800061 39.0130911485529, -94.57226806507019 39.01315884549675, -94.57342610723566 39.0132037014107, -94.57455413213843 39.01325045956409, -94.5744687494557 39.0149606326803, -94.57438658848373 39.01662549877073, -94.57429668454471 39.01829429564054, -94.57420188567131 39.01996471505225, -94.57409920172726 39.02177363299919, -94.57399716984756 39.02357145717905, -94.57389471998749 39.02537842422011, -94.57379374134878 39.02718338530785, -94.5736922385682 39.02899696762881, -94.57358427357126 39.03083007540815, -94.57347404106743 39.03265453494053, -94.5733651179229 39.03445691515196))

Is there a simple way to get the amount of x,y coordinate pairs in the 'geometry' field? Something as simple as using len() throws the following error:
print (len(shp.geometry.iloc[0])) throws the following error:

TypeError: object of type 'Polygon' has no len()

Do I need to convert the type of the 'geometry' column?
Any help much appreciated

A: To get the amount of (x,y) coordinate pairs:
import geopandas as gp

shp = gp.GeoDataFrame.from_file('example_file.shp')

def get_coord(coord):
  return (coord.x, coord.y)

centroidseries = shp['geometry'].centroid
xycoords = map(get_coord, centroidseries)

or if you want two separate lists of x and y coordinates:
x,y = [list(t) for t in zip(*map(get_coord, centroidseries))]


text:
Q: Flood Elevation Setback I have a floodplain layer with elevations assigned to it. Per scope of the project, I need to create a safety setback. The flood elevation is raised by 2 ft. and when the raised point extended horizontally to the ground becomes the setback. How do I create this setback/buffer?

A: You didn't specify a software requirement for your solution (although there is an ArcGIS tag on the question) so I've provided a method below based on the free and open-source GIS Whitebox Geospatial Analysis Tools, for which I am a developer.
Whitebox GAT has a tool called Elevation Above Stream (see image below):

For a given DEM and rasterized stream network...

...the tool will calculate the elevation difference between each location and its nearest downslope stream cell:

You can then threshold using the Raster Calculator, Reclass tool, Less Than tool, or Conditional Evaluation tool. In this example I've simply pulled out each cell in the elevation above stream raster with a value less than 2 ft and vectorized the resulting polygons:

There are your setbacks! I should also note that while I used a stream network as the target in this example, you could easily replace the required input streams file to the tool with a rasterized version of a floodplain polygon. It would work equally well, but would redefine the output as elevation above the floodplain. In fact, this is nearly the exact application that inspired me to develop this tool in the first place. Good luck and let me know if you need any further details.


text:
Q: Dropwizard support for multiple serialization formats It is pretty typical in a RESTful API to see endpoints that can support multiple serialization formats:
// Sends back "fizz" resource that has an id=34 as a JSON object
http://api.example.com/v2/fizz/34.json

// Sends back "fizz" resource that has an id=34 as an XML object
http://api.example.com/v2/fizz/34.xml

// Sends back "fizz" resource that has an id=34 as a binary object,
// say, using Google Protocol Buffers
http://api.example.com/v2/fizz/34.bin

I'm designing a Dropwizard service, and am trying to figure out how to implement multiple format support, but the docs are barren in this regard. Any ideas?

A: Generally support for different format configuration is simply done declaratively in the @Produces and @Consumes annotations. When the client sends data, then the Content-Type request header should be set to the actual type of the data being sent.
For example if the client is sending JSON data, then the client should set the  request header Content-Type: application/json. Jersey will look for a method or class with @Consume("application/json"). If it finds it, then that means the app is configured to support the media type application/json. If not, then the client will get a response back saying the media type is not supported.
Likewise when the client is requesting data, it should set the Accept: application/json request header. Jersey will look for @Produces("application/json"). If it can't find it for the endpoint, then the client will get a message saying it is not an acceptable type.
So we can support different media types for the same endpoint. You can declare the method like
@Produces({"application/json", "application/xml", "application/x-protobuf"})
public Response getFoo() {
    return Response.ok(new Foo());
}

The thing that you need to be concerned about is if there is a MessageBodyWriter for each of those media types that can handle the serialization of the Foo type. See more at JAX-RS Entity Providers.
Alternatively, if the application/json, application/xml, application/x-protobuf media types require different domain types to be serialized, you can have different methods to handle the different types. For example, application/json and application/xml, you can usually get away with using the same Foo domain object, so you can just do
@Produces({"application/xml", "application/json"})
public Response getFooJsonOrXml() {
    return Response.ok(new Foo());
}

But for Protobuf, it requires Protobuf compiled classes. So instead of the Foo domain object, you would return the generated type.
@Produces("application/x-protobuf")
public Response getFooProtobuf() {
    return Response.ok(new ProtobufFoo());
}

As for your use of the .xml, .json extension in your URLs, that is generally not the way for the client to say what type it wants. Usually the set the Accept request header to one of the types that your server supports, as mentioned above.
But there is support for the URL type extension, but it is usually meant for clients that don't have access to setting the headers, for instance a browser. But you need to configure those media type mappings with the UriConnegFilter. For example
Map<String, MediaType> map = new HashMap<>();
map.put("xml", MediaType.APPLICATION_XML_TYPE);
map.put("json", MediaType.APPLICATION_JSON_TYPE);
map.put("bin", ProtocolBufferMediaType.APPLICATION_PROTOBUF_TYPE);
env.jersey().property(ServerProperties.MEDIA_TYPE_MAPPINGS, map);

See Also:

*

*Dropwizard and Protocol Buffers by example

*Limit path media type mappings in Jersey

*JAX-RS Entity Providers


text:
Q: How to set a multi-valued XML attribute using SQLXML modify I'm trying to use the SQLXML modify function to update a multi-value (xs:list) attribute.  I can set multiple values when constructing the XML (from a string), but SQLXML modify doesn't let me set multiple values.
The initial XML:
<AccessControlList xmlns="http://www.acme.com/Authorization/2013/01">
  <AccessControlRecord Permissions="Fullcontrol" />
  <AccessControlRecord Permissions="DenyCreate DenyRead DenyUpdate DenyDelete" />
</AccessControlList>

Setting a SINGLE value works fine:
DECLARE @SingleValue NVARCHAR(100) = 'DenyCreate';
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
UPDATE dbo.Widget
SET ACL.modify('replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1] with sql:variable("@SingleValue") cast as A:AccessPermissions ?')
FROM dbo.Widget;

Setting MULTIPLE values FAILS:
DECLARE @MultipleValues NVARCHAR(100) = 'DenyCreate DenyRead DenyUpdate DenyDelete';
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
UPDATE dbo.Widget
SET ACL.modify('replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1] with sql:variable("@MultipleValues") cast as A:AccessPermissions ?')
FROM dbo.Widget;

with this error:
XQuery: Replacing the value of a node with an empty sequence is allowed only if '()' is used as the new value expression. The new value expression evaluated to an empty sequence but it is not '()'.

The variable is not null or empty.  I also tried other variations, which failed with different errors.
Full SQL to reproduce:
-- Drop table and schema collection
IF OBJECT_ID('dbo.Widget') IS NOT NULL
    DROP TABLE dbo.Widget;
IF EXISTS ( SELECT * FROM sys.xml_schema_collections WHERE SCHEMA_NAME(schema_id) = 'dbo' AND name = 'AccessControlList' )
    DROP XML SCHEMA COLLECTION dbo.AccessControlList;
GO

-- Create schema collection
CREATE XML SCHEMA COLLECTION dbo.AccessControlList AS N'
<xs:schema id="AccessControlList" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.acme.com/Authorization/2013/01" xmlns="http://www.acme.com/Authorization/2013/01">
    <xs:simpleType name="AccessPermissions">
        <xs:list>
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="Create" />
                    <xs:enumeration value="Read" />
                    <xs:enumeration value="Update" />
                    <xs:enumeration value="Delete" />
                    <xs:enumeration value="Execute" />
                    <xs:enumeration value="Fullcontrol" />
                    <xs:enumeration value="DenyCreate" />
                    <xs:enumeration value="DenyRead" />
                    <xs:enumeration value="DenyUpdate" />
                    <xs:enumeration value="DenyDelete" />
                    <xs:enumeration value="DenyExecute" />
                    <xs:enumeration value="FullDeny" />
                </xs:restriction>
            </xs:simpleType>
        </xs:list>
    </xs:simpleType>
    <xs:complexType name="AccessControlRecord">
        <xs:attribute name="Permissions" type="AccessPermissions" use="required" />
    </xs:complexType>
    <xs:complexType name="AccessControlList">
        <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="unbounded" name="AccessControlRecord" type="AccessControlRecord" />
        </xs:sequence>
    </xs:complexType>
    <xs:element name="AccessControlList" nillable="true" type="AccessControlList" />
</xs:schema>
';
GO

-- Create table, insert test data, and display initial state of data
CREATE TABLE dbo.Widget
(
    WidgetId INT PRIMARY KEY IDENTITY(1,1),
    ACL XML(DOCUMENT dbo.AccessControlList)
);
INSERT INTO dbo.Widget
    ( ACL )
VALUES
    ( N'<AccessControlList xmlns="http://www.acme.com/Authorization/2013/01" >
            <AccessControlRecord Permissions="Fullcontrol" />
            <AccessControlRecord Permissions="DenyCreate DenyRead DenyUpdate DenyDelete" />
        </AccessControlList>' );
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
SELECT *
    ,Acr1Permissions = CAST(ACL AS XML).value('(/A:AccessControlList/A:AccessControlRecord)[1]/@Permissions', 'NVARCHAR(128)')
    ,Acr2Permissions = CAST(ACL AS XML).value('(/A:AccessControlList/A:AccessControlRecord)[2]/@Permissions', 'NVARCHAR(128)')
FROM dbo.Widget;

-- Setting a SINGLE value works fine
DECLARE @SingleValue NVARCHAR(100) = 'DenyCreate';
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
UPDATE dbo.Widget
SET ACL.modify('replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1] with sql:variable("@SingleValue") cast as A:AccessPermissions ?')
FROM dbo.Widget;

-- Display values after
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
SELECT *
    ,Acr1Permissions = CAST(ACL AS XML).value('(/A:AccessControlList/A:AccessControlRecord)[1]/@Permissions', 'NVARCHAR(128)')
    ,Acr2Permissions = CAST(ACL AS XML).value('(/A:AccessControlList/A:AccessControlRecord)[2]/@Permissions', 'NVARCHAR(128)')
FROM dbo.Widget;

/* Setting MULTIPLE values *FAILS*
DECLARE @MultipleValues NVARCHAR(100) = 'DenyCreate DenyRead DenyUpdate DenyDelete';
WITH XMLNAMESPACES ( 'http://www.acme.com/Authorization/2013/01' AS A )
UPDATE dbo.Widget
SET ACL.modify('replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1] with sql:variable("@MultipleValues") cast as A:AccessPermissions ?')
FROM dbo.Widget;
*/

I get the same failure when I try to set multiple values using "sql:column".
I found this resource (https://learn.microsoft.com/en-us/sql/xquery/type-casting-rules-in-xquery?view=sql-server-2017) that says casting to or from list types is not allowed; I hope there's a solution or workaround.
Is this possible using SQLXML?  How?
Thanks in advance

A: I must admit, I'd never had to deal with this before...
And I must admit, that I did not find an easy solution. If you find it, please let me know.
Even working with literals leads to the same problem: The string is casted to the enumeration in whole, which does not match one of the allowed values, hence coming back as empty.
But you can do
replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1]
with for $p in ("DenyCreate","DenyUpdate","DenyDelete")
     return $p cast as A:AccessPermissions ?

This will use a XQuery for to run through a list and return each value one-by-one, each casted to the needed type separately.
But the only way I found to use this with an external variable is dynamic SQL. So this works, but is rather ugly:
DECLARE @MultipleValues VARCHAR(100)='DenyCreate DenyUpdate DenyDelete';

DECLARE @cmd NVARCHAR(MAX)=
'WITH XMLNAMESPACES ( ''http://www.acme.com/Authorization/2013/01'' AS A )
 UPDATE dbo.Widget
 SET ACL.modify(''replace value of (/A:AccessControlList/A:AccessControlRecord/@Permissions)[1] with for $p in ("' + REPLACE(@MultipleValues,' ','","') + '") return $p cast as A:AccessPermissions ?'')
 FROM dbo.Widget;';

EXEC(@cmd);


text:
Q: Linux music production workflow without a low-latency kernel I would like to do some music composition on my linux mint pc, but I have run into instabilities while trying to install and use a low-latency kernel (system freezes, possibly due to conflicts with the nvidia proprietary graphics drivers). So as I see it, I have three options:

*

*Either use my current system, i.e. the normal, generic kernel

*Install a dedicated audio distribution like Ubuntustudio

*Install the low-latency kernel on my current system but disable my graphics card.

Option 2 involves repartitioning etc so I'd like to avoid that, and option 3 is pretty ugly and tedious to work with. So I would like to know, if I go with option 1, what am I missing out on by not using a low-latency kernel for music production? (both in general, and w.r.t. the linux toolchain in particular)?
If I choose to use a generic kernel for music production, what side-effects, problems can I expect that a low-latency kernel is supposed to solve? Will I not be able to use JACK effectively? Will I be able to record? Will there be a lag in my recordings? Noise / skips / screetches? Will midi input accuracy via piano keyboard suffer?

PS. This question is crossposted from music.SE as per a comment there suggesting this may be a more appropriate forum. I'd be interested in people's opinion here on whether a linux workflow for music production is a suitable topic for this forum.

A: Your question is unclear but I'll answer some interpretation of it so that you can formulate a better question in future. I think it would make sense not to start morphing this question into something else after the fact.
The low-latency kernel will make it possible to handle interrupts and short tasks with lower latency. It's not using true real time kernel patches on Ubuntu but so called PREEMPT configuration. The idea is that without PREEMPT support, once kernel starts to execute some syscall it will not be interrupted even if hardware request comes in (e.g. MIDI command). With PREEMPT the syscall will be interrupted if needed.
If you run generic kernel which cannot interrupt any syscalls, the maximum latency you can get is the maximum length syscall any process in your system makes. As such, it makes much harder to assume anything about your latency and often the workaround is to use bigger buffers which obviously cause longer delay for your audio processing.
The kernel features needed to make that pre-emption possible cause some overhead (maybe 0-2%) in total CPU usage and that's the reason those features are not enabled in generic kernel. In addition, the pre-emption triggers some yet-unknown programming bugs in kernel more easily. This is because syscalls can get interrupted and incorrectly written kernel code may accidentally only work when that code is never interrupted (e.g. it doesn't acquire memory locks for some shared structure that's cannot be actually shared unless the syscall is interrupted but shared structure can be modified by multiple CPU cores at the same time if syscall is interrupted).
I don't know about the current situation with NVIDIA drivers but for example VirtualBox kernel drivers used to have major problems with low-latency kernels because of multitude of bugs in those drivers. Nowadays VirtualBox kernel drivers appear to work much better with low-latency kernel – I haven't seen any problems in a couple of years.
If you don't have broken device drivers and you want low latency processing for hardware interrupts, you definitely want to use low-latency kernels all the time.
I have a cheap USB attached microphone and use motherboard integrated sound card for audio out and that's enough to get well under 10 ms latency from mic recording audio to soundcard playing it out after the audio passing through the full pulseaudio stack. With better hardware you should be able to get under 2 ms latency, especially with JACK.
TL;DR: low-latency kernel should reduce your latency for all actions but it will increase CPU usage a bit. And without low-latency kernel the maximum latency for incoming data depends on maximum syscall latency of the whole system. If you're not careful about background processes you end up with sound skipping or randomly delayed MIDI behavior. With low-latency kernel the background jobs do not really matter until you run out of RAM. Unless you're doing High-Performance Computing (HPC) or mine crypto-coin you usually want lower latency over maximum CPU throughput for everything so only reason not to use low-latency kernel should be bad device drivers.
If you get audio skipping or latency problems with low-latency kernel, I'd recommend testing with open source GPU drivers (Nouveau drivers for NVIDIA GPUs) and if the problem goes away, you've found the problem.
I've been running low-latency kernel for around a decade on all my systems and I've been much happier with it than with the generic kernel.
And check your memory clocks; low-latency kernel may cause more spikey power demands for your motherboard and if your motherboard or PSU power delivery is not good enough, trying to run memory clocks very high may cause memory errors which will cause all kind of random instabilities. Try running mprime in stress test mode using at least 50% of your RAM in the background while doing other tasks - if it detects any errors your RAM is not working correctly and you shouldn't run neither low-latency nor generic kernel if you  want a stable system. The generic kernel may be less demanding for the hardware and you'll see less errors from faulty memory but be assured that it will cause problems sooner or later even with generic kernel.


text:
Q: Position: "stickyfixed" - possible somehow? This is my HTML structure for my site

        ::before

The header is normally position:fixed but on short viewports it's static so it scrolls out of view as normal.
#container::before has my site's photo background, position:fixed, so that it remains in place while the glass-effect opacity:.9
s scroll over it.  It's maybe a bit old-school, but it's a pleasing effect that I like and want to keep.
It's important to me though, that the background photo starts immediately below , without any of it being cropped off underneath that element.  This is easy enough by modifying the top rule of that pseudo-element to match the (set) height value of the .
...right up until the point where the position:static  scrolls off the page on a short viewport.
What I want to happen
I'd like for the background to scroll up along with the , up until the point that the  is off the screen, and for it to then stick in place, as if it had position:fixed;top:0.
What's my best option so far?
top:0 on the pseudoelement background if the  isn't fixed.  It works once the header is off the top of the screen, but it means an important part of the photo is cropped off when the header is on screen.
I could fix this with a JavaScript on-scroll event, but I know that'll be jerky and unperformant.  Is there some CSS trickery I can pull with my current HTML setup to overcome this?  Even if it's only supported in some browsers, it'd be better than nothing.


text:
Q: React items.map is not a function when items is an array? Loading in an API and I'm getting .map isn't a function. Been looking through every example and followed them exactly but still getting this error. The error is of course happening at the .map in the ul tag
class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=boolean"
    )
      .then(res => res.json())
      .then(json => {
        this.setState({ isLoaded: true, items: json });
      });
  }

  render() {
    var { isLoaded, items } = this.state;

    if (!isLoaded) {
      return
Loading...
;
    } else {
      return (

            {items.map(item => (

{item.results.question}

            ))}

      );
    }
  }
}

export default Login;

A: Your actual data is coming in json.results, so you need to set json.results in state like,
this.setState({ isLoaded: true, items: json.results });

You need to iterate array like,
{ items.map(item => (

{item.question}

))}

Demo


text:
Q: java How to display only visible area in JPanel So I've got JPanel inside JScrollPane. Is there any possible way to display only visible area on JPanel? Right now my piece of code looks like that:
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    for(int i = 0; i < m_xTiles; i++)
    {
        for(int j = 0; j < m_yTiles; j++)
        {
            m_mapTiles.get(i).get(j).DrawImage(g);
        }
    }
}

It's not something that I want because it's display everything and when I want to make a very big map the movment are very slow. I want to get visible rectangle on screan - positions of four pixels and then I will calculate to my own x and y :)

A: Normally the graphic system cares about clipping operations outside the visible bounds so these operation become no-ops and are not expensive. So in most cases you don't need to deal with these information as the graphics operations are the expensive part when painting.
However, sometimes you may encounter the situation that the operations you perform before the calls on the Graphics object become expensive, i.e. if you have a really large but only partially visible component (as you described). In this situation it might be useful to access the clipping information to perform manually skipping, especially if you are tiling your area, thus calculating which items to process is rather easy:
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // I assert equal tiling of the actual size here, otherwise you may define
    // the tile sizes as constants and calculate preferredSize as tileWidth*m_xTiles
    // and tileHeight*m_yTiles, respectively
    final int tileWidth=getWidth()/m_xTiles;
    final int tileHeight=getHeight()/m_yTiles;

    Rectangle clip = g.getClipBounds();

    int firstX, lastX, firstY, lastY;
    if(clip == null) {
        firstX=0; lastX=m_xTiles-1;
        firstY=0; lastY=m_yTiles-1;
    }
    else {
       firstX=clip.x/tileWidth;  lastX=(clip.x+clip.width)/tileWidth;
       firstY=clip.y/tileHeight; lastY=(clip.y+clip.height)/tileHeight;
    }
    // note that the loop condition is <= now to handle partially visible tiles
    for(int i = firstX; i <= lastX; i++)
    {
        for(int j = firstY; j <= lastY; j++)
        {
            m_mapTiles.get(i).get(j).DrawImage(g);
        }
    }
}


text:
Q: Provide link instead of serializing collection I have two classes:
public class A{
    private String property;

    private Set<B> bs = new HashSet<B>();
}

public class B{
    private String property;

    private A owner;
}

I created a basic JAX-RS + Spring boot application, and I want to return A.
Problem is that A contains a Set<B>, so I get an infinite nested level problem.
I found a solution: provide a link instead of the resource itself, this way I can have this:
{ "property" : "value", "bs" : "http://mywebsite/api/a/2/bs" }

And i don't get any nested level problem, since each level is serialized seperately.
How can I implement such a thing in my JAX-RS application? I found nothing about it but I know it's possible since Spring Data Neo4j REST is using it, and it works well.

A: I can think of the following possible ways how to achieve that.
Convert the set to URI during serialization by using a XmlAdapter
@XmlRootElement
public class A
{
    private int id;

    private String property;

    @XmlJavaTypeAdapter(BsAdapter.class)
    private Set<B> bs = new HashSet<B>();
}

public class BsAdapter extends XmlAdapter<URI, Set<B>>
{

    @Override
    public Set<B> unmarshal(URI v) throws Exception
    {
        return new HashSet<>();
    }

    @Override
    public URI marshal(Set<B> v) throws Exception
    {
        return URI.create(
            Optional.ofNullable(v)
            .filter(b -> !b.isEmpty())
            .map(b -> "/" + b.stream().findFirst().get().getOwner().getId() + "/bs")
            .orElse(""));
    }

}

If the id of A is part of the URI then it can only be retrieved if the set is not empty. The result is a relative URI, since there are no further information available.
As an alternative set the URI manually.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class A
{

    private int id;

    private String property;

    @XmlTransient
    private Set<B> bs = new HashSet<B>();

    @XmlElement(name = "bs")
    private URI bsUri;
}

And set the URL like this:
@Context
UriInfo uriInfo;

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getA()
{
    // ...
    a.setBsUri(UriBuilder.fromUri(uriInfo.getAbsolutePath())
        .path("a")
        .path("{id}")
        .path("bs")
        .build(2));
    return Response.ok().entity(a).build();
}

Or if a link in HTTP Header is also fine, simply do it this way so you do not have to extend class A with the URI.
    return Response.ok().entity(a).link(UriBuilder.fromUri(uriInfo.getAbsolutePath())
        .path("a")
        .path("{id}")
        .path("bs")
        .build(2), "bs").build();


text:
Q: Styles are not getting applied to HTML injected via network call In my angular 8.1.3 application, I am injecting HTML div, I want to apply styles to the classes used in that HTML payload.
But styles are not getting applied unless I put them in root level CSS of the project. (Which I dont want to do)
Sub-component.html

 [innerHTML]="ImagePayload">

here is my Sub-component.ts
 @Component({
      selector: 'SubComponent',
      templateUrl: './SubComponent.html',
      styleUrls: ['./SubComponent.scss'],
      encapsulation: ViewEncapsulation.None
    })

    export class SubComponent implements OnInit, AfterViewInit {
     public ImagePayload: string;

     // Constructros and other functions

    }

here is the parent component which creates an instance of sub-component and injects HTML payload in ImagePayload variable.
       @Component({
       selector: 'parentComponent',
       templateUrl: './parentComponent.html',
       styleUrls: ['./parentComponent.scss'],
       encapsulation: ViewEncapsulation.None
     })
     export class parentComponent implements OnInit, OnDestroy {

    showImage(data: Somedata) {
      const dialog: DialogRef = this.dialogService.open({
       title: 'recognise Image data ',
       content: SubComponent,
    });

      const info = dialog.content.instance;
      info.ImagePayload = data.challenge;
    }
   }

Here is a css style for class used in imagePayload variable.
  input.Image_selection_checkbox {
            width: 15px;
        }

I applied the same style to
1) SubComponent.scss
2) parentComponent.scss
3) app.component.scss
    (of parentCompoent)
4) style.scss of this particular sub-project
    (Project have multiple sub-project as well)
but none of them are getting applied !
But when I put the same style in root style.scss (of the main project directory!)
It is getting applied.
I am having a limited idea about role of encapsulation. Is that a culprit?
what are the other issues?


text:
Q: Why am I getting an Exception when initializing Display d? I am trying to offload my graphics to another class, however when I initialize that class I get:
at java.security.AccessController.getContext(Unknown Source)
at java.awt.Component.<init>(Unknown Source)
at java.awt.Canvas.<init>(Unknown Source)
at Display.<init>(Display.java:11)
at Display.<init>(Display.java:7)

I researched and found something saying that I have to have a constructor with no arguments however the constructor did not seem to solve the problem.
----This is where I initilize my display class----
import java.util.Scanner;

public class Ytube2URL
{

public static void main(String[] args) {
    Display d = new Display();
    d.initGraphics();

    String Userurl = askUserForURL();
    System.out.println(Userurl);
    String Downloadurl = GetYoutubeOnlyURL(Userurl);
}
}

-------This is my Display class------
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Display extends Canvas
{
Display d = new Display();
JFrame f = new JFrame();
JOptionPane jo =new JOptionPane();

public Display()
{

}

public void initGraphics()
{
    f.add(d);
    f.setSize(200,600);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jo.add(f);
    f.pack();
}
}

Thank you for your help and explanations.

A: You are creating a new instance of Display class in itself. So, whenever you create an object of Display type it again creates a new object and this process goes again and again recursively. Don't create new Display type object in Display class.
Working code:    ------ Display class ------
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Display extends Canvas
{
    JFrame f = new JFrame();
    JOptionPane jo =new JOptionPane();

    public void initGraphics()
    {
        f.add(d);
        f.setSize(200,600);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jo.add(f);
        f.pack();
    }
}

A: If you need to add a Display inside the JFrame you can do f.add (this); since this refers to the Display object using the initGraphics method


text:
Q: Passing 2 variables to a function in NASM 32bit assembly I am VERY new to assembly and I know that this problem should be an easy fix. I have hit a dilemma though. I am trying to create a function that will simply print a message that is sent to it on screen. Essentially do,
mov eax, 4 ; sys_write
mov ebx, 1 ; stdout
mov ecx, message
mov edx, message length
int 0x80 ; execute

but some reason the length parameter is not sending right or I am not referencing it right. This should be a simple solution and any help would be great! :D
global _start
section .data
    msg db "Hello, World!"
    msgS equ $ - msg

section .text
_start:

push msg ;The first param. MESSAGE
push msgS ;The second param. MESSAGE SIZE
call print

mov eax, 1 ; sys_exit
mov ebx, 0 ; exit code is 0
int 0x80 ; execute

print:
push ebp ; Push ebp's old location onto the stack.
mov ebp, esp ; set ebp to be esp's current location.

mov eax, 4
mov ebx, 1
mov ecx, [esp+8] ;The first param. MESSAGE (we jump by 8 instead of 4 because we just pushed ebp into the stack.)
mov edx, [esp+4] ;The second param. MESSAGE SIZE
int 0x80

mov esp, ebp ; set esp back to what it was before this function
pop ebp ; set ebp back to what it was before this function
ret ; return back to before this function

When I run this code I do not get any results. I know that it has to be something wrong with the
mov edx, [esp+4]

code snippet because the string is 13 characters long. If I delete [esp+4] and replace it with 13 and than delete the push msgS before I called the function it works and prints the string.
I am very new to assembly and if you guys have any solution for me that would be awesome. I tried to google this, but I can not seem to find any results that work for me. I tried to rewrite and swap orders etc, but still did not work.
If I am doing a bad practice or something inside my code, correction is welcome.
P.S (Not concerning the question whatsoever). If you guys have any references where I can further study assembly (for newbie begineers) that would be great.


text:
Q: App crashing in UIPopoverPresentationController but no explicit popovers? My app (iOS 8 only) has been rejected due to a crash when IAP are attempted. I've tried pretty much every incantation of the purchase process in an AdHoc build but cannot reproduce a crash.  Looking at the crash log that the review team attached, I am seeing a very weird stack trace in the last exception backtrace. The crash looks to be involving UIPopoverController, however my app, though universal, does not explicitly or implicitly display popovers anywhere. Does anyone have any idea what might trigger the activity that is causing this crash? What might cause my app to display popovers when the review team is looking at it only?
Last Exception Backtrace:
0   CoreFoundation                0x186d52084 __exceptionPreprocess + 132
1   libobjc.A.dylib               0x1977a40e4 objc_exception_throw + 60
2   UIKit                         0x18bc0aee0 -[UIPopoverPresentationController presentationTransitionWillBegin] + 2464
3   UIKit                         0x18b7d27d8 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 1324
4   UIKit                         0x18b7d1310 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 212
5   UIKit                         0x18b557388 _applyBlockToCFArrayCopiedToStack + 356
6   UIKit                         0x18b4c8e4c _afterCACommitHandler + 532
7   CoreFoundation                0x186d0a388 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
8   CoreFoundation                0x186d07314 __CFRunLoopDoObservers + 360
9   CoreFoundation                0x186d076f4 __CFRunLoopRun + 836
10  CoreFoundation                0x186c35664 CFRunLoopRunSpecific + 396
11  GraphicsServices              0x18fd435a4 GSEventRunModal + 168
12  UIKit                         0x18b53a984 UIApplicationMain + 1488

A: Not sure if it's the same cause as the original question, but I have the exact same error and the issue was using a UIAlertController with an ActionSheet style, presenting it worked fine on iPhone but iPad requires a sourceview to be set - https://stackoverflow.com/a/24233937/285694

A: This is a just similar situation. I had a crash bug on [UIPopoverPresentationController presentationTransitionWillBegin] on iOS 9+, and turns out that the crash occurred when sourceView was nil.
Example (in Objective-C):
UIViewController *vc = <#instance#>.
vc.modalPresentationStyle = UIModalPresentationPopover;
vc.popoverPresentationController.delegate = self;
vc.popoverPresentationController.sourceView = sourceView; // <--- this MUST NOT be nil.
vc.popoverPresentationController.sourceRect = sourceView.bounds;
[self presentViewController:vc animated:YES completion:nil];

A: It most probable the ActionSheet crash in iPad.
You should have a if condition like:
if let popoverController = alertVC.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []
  }

A: First you should check UIPopoverPresentationController available or not.
NSArray *Items = [NSArray arrayWithObjects:emailBody,anImage, nil];

    UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:Items applicationActivities:nil];

    if ([UIPopoverPresentationController class] != nil) {
        UIPopoverPresentationController *popover = activityController.popoverPresentationController;
        if (popover)
        {
            popover.sourceView = sender;
            //popover.sourceRect = sender.bounds;
            popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
        }
    }

    [self presentViewController:activityController animated:YES completion:NULL];


text:
Q: Consulta solo retorna un valor de varios que deberia retornar nuevamente estoy entrampado en una función que llevo 2 dias haciendo y anda que me salga... Tengo una función en mi controlador que recibe 2 parámetros para poder retornan registros a un json), hasta el momento he conseguido que me retorne la información, pero solo me retorna un registro (puede ser uno o mas de uno que deba retornarme).
Para entender el contexto: Debo obtener todos los materiales (Tabla Materials) que estén almacenados en "Bodega Nuevos" (Tabla Bodegas) y que sean de un servicio especifico (Tabla Servicios)
Tengo las relaciones en los modelos y como les comento me trae dato, pero solo uno (en este caso me deberia traer 3 mas que son los que tengo actualmente)
EDIT: Con esta funcion que dejo abajo, me estaria trayendo la informacion, pero tengo el problema que si quiero hacer un select de los campos que necesito, solo trae una fila, las demas no...
public function getMaterialBodegaServicio($bodega_id,$servicio_id){
        /* $materiales_ids = DB::table('materials')->where('servicio_id',$servicio_id)->pluck('id');
        $materiales = DB::table('det_ingreso_materials')->where('bodega_id',$bodega_id)->whereIn('material_id',$materiales_ids)->pluck('material_id');
        $materiales_finales = DB::table('materials')->whereIn('id',$materiales)->get(); */
        $bodegas = Bodega::select('id','nombre_bodega','tipo_bodega')->where('id',$bodega_id)->get();
        $servicios = Servicio::select('id','servicio')->where('id',$servicio_id)->get();
        $materiales_ids = DB::table('materials')->where('servicio_id',$servicio_id)->pluck('id');
        $materiales = DB::table('det_ingreso_materials')->where('bodega_id',$bodega_id)->whereIn('material_id',$materiales_ids)->pluck('material_id');
        $materiales_finales = DB::table('materials')->whereIn('id',$materiales);

        $data = DB::table('det_ingreso_materials')
        ->Join('ingreso_materials','ingreso_materials.id','=','det_ingreso_materials.ingreso_material_id')
        ->Join('materials','materials.id','=','det_ingreso_materials.material_id')
        ->Join('bodegas','bodegas.id','=','det_ingreso_materials.bodega_id')
        ->Join('servicios','servicios.id','=','ingreso_materials.servicio_id')
        ->Join('tecnicos','servicios.id','=','tecnicos.servicio_id')
        //->where('materials.id','det_ingreso_materials.material_id')
        ->where('servicios.id',$servicio_id)
        ->where('bodegas.id',$bodega_id)
        ->where('bodegas.tipo_bodega','Bodega Nuevos')->get();
    /*     //->groupBy(['bodegas.nombre_bodega'])
        ->distinct()
        ->pluck('bodegas.id');
        $bodegas=DB::table('bodegas')->whereIn('tipo_bodega',function ($query) {
            $query->select('tipo_bodega')->from('bodegas')->Where('tipo_bodega','=','Bodega Nuevos');
        }); */

        //dd($data);
        return response()->json(['data' => $data], 200);
    }

Saludos a todos


text:
Q: FBSDKShareButton successfully posting link, but crashing on return to app Here's the function I'm calling:
func showFBInviteView() {
    let content : FBSDKShareLinkContent = FBSDKShareLinkContent()
    let safeURL = "http://mylink.com"
    content.contentURL = URL(string: safeURL)

    let button : FBSDKShareButton = FBSDKShareButton()
    button.shareContent = content
    button.sendActions(for: .touchUpInside)
}

This is the function I have in AppDelegate:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    let handled = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)

    return  handled
}

When I comment out the above function, the crash goes away but the window doesn't close.  Interestingly, if I put a print statement at the beginning of the function, it doesn't get called, so the app is crashing simply from trying to call the function.
Here's the error output:
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x0000000118f072cf libswiftCore.dylib`swift_getObjectType + 47
    frame #1: 0x000000010fe1ac08 MyApp`@objc AppDelegate.application(_:open:sourceApplication:annotation:) at AppDelegate.swift:0
    frame #2: 0x0000000113b8b33f UIKit`__58-[UIApplication _applicationOpenURLAction:payload:origin:]_block_invoke + 1037
    frame #3: 0x0000000113b8ac31 UIKit`-[UIApplication _applicationOpenURLAction:payload:origin:] + 652
    frame #4: 0x0000000116a55cb8 SafariServices`-[SFSafariViewController remoteViewController:hostApplicationOpenURL:] + 205
    frame #5: 0x0000000116a47c28 SafariServices`-[SFBrowserRemoteViewController willOpenURLInHostApplication:] + 68
    frame #6: 0x0000000118491ccc CoreFoundation`__invoking___ + 140
    frame #7: 0x0000000118491b84 CoreFoundation`-[NSInvocation invoke] + 308
    frame #8: 0x0000000119800848 libdispatch.dylib`_dispatch_client_callout + 8
    frame #9: 0x0000000119805e14 libdispatch.dylib`_dispatch_block_invoke_direct + 592
    frame #10: 0x000000011ee9a470 FrontBoardServices`__FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    frame #11: 0x000000011ee9a12e FrontBoardServices`-[FBSSerialQueue _performNext] + 439
    frame #12: 0x000000011ee9a68e FrontBoardServices`-[FBSSerialQueue _performNextFromRunLoopSource] + 45
    frame #13: 0x00000001184b0bb1 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    frame #14: 0x00000001184954af CoreFoundation`__CFRunLoopDoSources0 + 271
    frame #15: 0x0000000118494a6f CoreFoundation`__CFRunLoopRun + 1263
    frame #16: 0x000000011849430b CoreFoundation`CFRunLoopRunSpecific + 635
    frame #17: 0x000000011ada1a73 GraphicsServices`GSEventRunModal + 62
    frame #18: 0x0000000113b820b7 UIKit`UIApplicationMain + 159
  * frame #19: 0x000000010fe1c887 MyApp`main at AppDelegate.swift:18
    frame #20: 0x000000011987d955 libdyld.dylib`start + 1
    frame #21: 0x000000011987d955 libdyld.dylib`start + 1

A: Try to replace this:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

let handled = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)

return  handled

}
with
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    return FBSDKApplicationDelegate.sharedInstance().application(app,
                                                                 open: url,
                                                                 sourceApplication: options[.sourceApplication] as! String,
                                                                 annotation: options[.annotation])
}

Hope this will solve your problem.


text:
Q: operator overloding of insertion operator topic -- reference variable
In c++
This is a program that tells the user what the time is using opps and classes(time class). It runs as I expect it , when I do not pass the time(t) as a reference it throws a garbage value(or whatever the problem is if you want to be more specific) when I pass it as reference variable it works perfectly. I am struggling to understand that why we need to pass reference of time class. Any explanation would be appreciated.
source code---
#include <iostream>
using namespace std;

class time{

    int hh=0,mm=0,ss=0;

public:
  friend  void operator>>(istream &in,time &t);

  friend void operator<<(ostream &out,time &t);

  friend void operator==(time,time);

};

   void operator>>(istream &in,time &t){

          cout<<"enter hours:";in>>t.hh;cout<<endl;
          cout<<"enter minutes:";in>>t.mm;cout<<endl;
          cout<<"enter seconds:";in>>t.ss;cout<<endl;

    }

   void operator<<(ostream &out,time &t){

       out<<"hours :"<<t.hh;out<<endl;
       out<<"minutes :"<<t.mm;out<<endl;
       out<<"seconds :"<<t.ss;out<<endl;

   }

 void operator==(time t1,time t2){

    if (t1.hh == t2.hh && t1.mm == t2.mm && t1.ss == t2.ss)
    {
        cout<<"same time";
    }
    else
        cout<<"different time";

 }

int main(){
  time t1,t2;

  cin>>t1;
  cout<<t1;

  cin>>t2;
  cout<<t2;

  t1 == t2;

 return 0;
}

I am struggling to understand that why we need to pass reference of time class. Any explanation would be appreciated.

A: The only place where you really need reference is where you'd like to modify the value. E.g. in operator>>, you need to be able to set it according to user input.
For optimization reasons, we tend to take const time& instead of time when the object is non-minimal (i.e., not just an int/long/etc.).
However, there are other issues in your code: operator<< and operator>> should return the in and out arguments, respectively (thus they shouldn't be void) as per common practice and you shouldn't have using namespace std; at namespace-level to avoid collision.


text:
Q: getting multidimensional array (object) observable in KnockoutJS I am building an application with Knockout and find it very useful.
Although, I have a problem with getting multidimensional array (object) observable.
At the moment I am using following structure:
    self.form = ko.observableArray(ko.utils.arrayMap(initialData, function(section) {
        var result = {
            name : section.name,
            code : section.code,
            type : section.type,
            fields: ko.observableArray(section.fields)
        };
        return result;
    }));

It works well, but I can't get it working if the initialData is more than two levels.
I tried something like
    self.form = ko.observableArray(ko.utils.arrayMap(initialData, function(block) {
        var result = {
            name : block.name,
            code : block.code,
            type : block.type,
            sections: ko.observableArray(ko.utils.arrayMap(block.sections, function(section) {
                var result = {
                    name : section.name,
                    code : section.code,
                    type : section.type,
                    fields: ko.observableArray(section.fields)
                };
                return result;
            }))
        };
        return result;
    }));

The final array structure looks good, but knockout doesn't updates DOM when I am doing push to sections array:
    self.addField = function( section ) {
        field = {
            code: uid(),
            name: "New Field",
            value: '',
            type: section.type
        };
        section.fields.push(field);
    };

I also tried a knockout.mapping.js plugin (is that a right approach?) looks good first, but after a push in the function above I have my new field element not observable, just object.
The plugin doumentation says:
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);

But I am not sure that it is my case.
If anyone has any ideas, it would be much appreciated.
Thanks.
UPD:
It is not a problem to make 1st and 2nd levels observable, problem is to go deeper.
Here is an example of initialData:
var blocks = [
    {
        "name" : "",
        "sections" : [
            {
                "name" : "Section 1",
                "fields" : [
                    {
                        "name" : "Field A",
                        "type" : "checkbox",
                        "code" : uid()
                    }
                ]
            }
        ]
    }
];

HTML

<button class="btn addField" data-bind="click: $root.addField">Add</button>

A: The mapping plugin is the best way to go.  It will automatically map your objects into observables and observableArrays, so you don't have to do it manually.
Here is a simple fiddle that may give you some pointers: http://jsfiddle.net/jearles/CGh9b/
In this example I create a tree structure and them allow you to add a new entry.  You can see that I am able to continue to add at increasingly deeper levels with no problem, and because the names are observable they can be changed.


text:
Q: How to make a global variable in the drools file synchronous? I'm working on a Spring Boot application where I created some REST APIs. There is a Readings entity, Alert entity. I'm sending readings via POST method and in the postReadings method of the ReadingsService class I'm checking whether the readings match certain criteria using KIE and wrote the rules in a rules.drl file. I'm creating an Alert object and setting it as a global using session.setGlobal method. Then I'm checking if the Alert object is null and saving it to the Alert Repository. In the drools file I added a print statement to check whether all the alerts are correctly created. All the alerts are correctly printed via the print statement, however, only some of them are being saved to the alert repository. Can anyone please help?
This is the ReadingsService
@Service
public class ReadingsServiceImpl implements ReadingsService{

@Autowired
ReadingsRepository repository;

@Autowired
VehicleRepository vehicleRepo;

@Autowired
private KieSession session;

@Autowired
AlertRepository alertRepo;

@Override
public List<Readings> findAll() {
    return repository.findAll();
}

@Override
public Readings postReadings(Readings readings) {
    Alert alert = new Alert();
    session.setGlobal("alert", alert);
    session.insert(readings);
    session.fireAllRules();
    if(!Optional.ofNullable(alert).map(o -> o.getVin()).orElse("").isBlank()) {
        alertRepo.save(alert);
    }
    return repository.save(readings);
}

This is the drools file
import com.shiva.truckerapi.entity.Readings;
global com.shiva.truckerapi.entity.Alert alert;
rule "EngineCoolantOrCheckEngineLight"
when
    readingsObject: Readings(engineCoolantLow || checkEngineLightOn);
then
    alert.setVin(readingsObject.getVin());
    alert.setPriotity("LOW");
    alert.setDescription("Engine Coolant LOW Or Check Engine Light ON");
    alert.setTimestamp(readingsObject.getTimestamp());
    alert.setLatitude(readingsObject.getLatitude());
    alert.setLongitude(readingsObject.getLongitude());
    System.out.println(alert.toString());
end;

A: There's nothing wrong with your rule. However your save is guarded by an "if" statement that checks for the presence of a non-blank/non-null VIN, so that's likely causing the issue of the missing saves:
if(!Optional.ofNullable(alert).map(o -> o.getVin()).orElse("").isBlank()) {
  alertRepo.save(alert);
}

You can easily write unit tests to verify this behavior -- that if the alert exists (which is always does since you instantiate it earlier in the same method) and there is a VIN, then it saves; and that if the alert exists and there is no VIN that it does not save.

This is a very old-fashioned way of saving the output for rules. These days we generally use actions with side effects in our rules on the right hand side, or use objects to pass back information.
Your current set up even has a logic flaw: you will always have an Alert because you instantiate it before you add it to your session.
If you want to use a global like this, you'll need to add some sort of indicator to the Alert class itself to indicate that the alert has been added. So, for example, if you  simply add a boolean added = false method with appropriate getters, you can update your rule like this:
rule "Engine Coolant Or Check Engine Light"
when
    readingsObject: Readings(engineCoolantLow || checkEngineLightOn);
then
    alert.setAdded(true); // Mark the alert as now being added
    alert.setVin(readingsObject.getVin());
    alert.setPriotity("LOW");
    alert.setDescription("Engine Coolant LOW Or Check Engine Light ON");
    alert.setTimestamp(readingsObject.getTimestamp());
    alert.setLatitude(readingsObject.getLatitude());
    alert.setLongitude(readingsObject.getLongitude());
    System.out.println(alert.toString());
end

And then you can fix your calling method to not key off of the nullability of a non-null object, and instead key off of whether you have added an alert:
public Readings postReadings(Readings readings) {
    Alert alert = new Alert();
    session.setGlobal("alert", alert);
    session.insert(readings);
    session.fireAllRules();
    if(alert.isAdded()) {
        alertRepo.save(alert);
    }
    return repository.save(readings);
}

(I'm assuming, of course, that you've got the appropriate connection and transaction handling in your 'repository' instances.)
If you still need a non-null VIN, you should be checking for that on the rule's left hand side; something like this:
readingsObject: Readings( vin != null,
                          engineCoolantLow || checkEngineLightOn )

Related question: How to return the value from Cosequence of drl file to java

A: Drools evaluates rule in the same (single) thread unless you make additional configuration. Thus postReadings() and drools then block will be invoked by the same thread. But postReadings() can be executed in concurrent context and it uses shared global object reference Alert alert (because of the shared session instance). Drools has nothing to do with the ordinal problem of making your ReadingsServiceImpl thread safe. And there are many ways to achieve this and the very  first antipattern is 'global variables'... Do not use shared object in drools file but use shared thread safe service reference. You can use different synchronization approaches, thread local variables to make your service deal with your inner stuff in a thread safe way but do you really need shared object here at all?
import com.shiva.truckerapi.entity.Readings;
import com.shiva.truckerapi.entity.Alert;

global com.shiva.truckerapi.service.ReadingsService readingsService;

rule "EngineCoolantOrCheckEngineLight"
when
    readingsObject: Readings(engineCoolantLow || checkEngineLightOn);
then
    Alert alert = new Alert();
    alert.setVin(readingsObject.getVin());
    alert.setPriotity("LOW");
    alert.setDescription("Engine Coolant LOW Or Check Engine Light ON");
    alert.setTimestamp(readingsObject.getTimestamp());
    alert.setLatitude(readingsObject.getLatitude());
    alert.setLongitude(readingsObject.getLongitude());
    System.out.println(alert.toString());

    readingsService.onAlert(alert);
end;

Service changes
@PostConstruct
private void postConstruct() {
    session.setGlobal("readingsService", this);
}

@Override
public void postReadings(Readings readings) {
    session.insert(readings);
    session.fireAllRules();
    repository.save(readings);
}

@Override
public void onAlert(Alert alert) {
    // this looks ugly. There should not be produced 'invalid' alert, if vin is empty alert should not be generated by the rule itself
    if(!Optional.ofNullable(alert).map(o -> o.getVin()).orElse("").isBlank()) {
        alertRepo.save(alert);
    }
}


text:
Q: VBA: Store ODBC query result in code, rather than displaying it I have the following macro, which accepts a string argument code which is a SQL query, and executes it against my Teradata server and displays the results.
Dim dest As Range
Set dest = ActiveCell

Dim timestamp As String
timestamp = Format(Now, "yyyyMMdd_h:mm:ss_AM/PM")

Dim queryName As String
queryName = "Query_" & timestamp

ActiveWorkbook.Queries.Add Name:=queryName, formula:= _
    "let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=my-server-name"", " _
    & Chr(34) & code & Chr(34) & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) _
    & "" & Chr(10) & " Source"

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" _
    & queryName & ";Extended Properties=""""" _
    , Destination:=Range(dest.Address)).QueryTable

    .CommandType = xlCmdSql
    .CommandText = Array("SELECT * FROM [" & queryName & "]")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = False
    .Refresh BackgroundQuery:=False
End With

For one report I'm trying to automate, the first step is to query a particular timestamp from the database and make sure it shows today's date before proceeding with the rest of the report. I want to have a macro do that, but have it just return the timestamp value rather than displaying it-- that way I can write it into an If statement to conditionally run the next steps of the report.
Is there a way it can execute the query and store the returned timestamp in a variable rather than displaying it anywhere? Otherwise, I guess I'll just display it somewhere, interrogate the value and then delete it because I don't need it displayed.

A: ADODB Solution
To get data from a query into a variable I would use an ADODB connection and recordset. Recordsets have a method called GetRows which returns the data from the query results.
Below is a function that can be used to query for your data. This takes in your ConnectionString and your SQL Code and returns your data in the form of a two-dimensional array.

For ease of explaining, I made this function late binding. To make Early binding set a reference to the Microsoft ActiveX Data Objects x.x Library.

Private Function QueryDatabase(ByVal ConnectionString As String, ByVal Sql As String) As Variant

    On Error GoTo Catch

    'OPEN CONNECTION TO DATABASE
    Dim Connection As Object
    Set Connection = CreateObject("ADODB.Connection")
    Connection.ConnectionString = ConnectionString
    Connection.Open
    On Error GoTo CloseConnection 'MAKE SURE TO CLOSE CONNECTION ON ERRORS

    'OPEN DATA AND GET RECORDSET
    Dim Rs As Object
    Set Rs = CreateObject("ADODB.Recordset")
    With Rs
        .ActiveConnection = Connection
        .Source = Sql
        .LockType = 1 'adLockReadOnly - MAKES CONNECTION READ ONLY
        .CursorType = 0 'adOpenForwardOnly - FREQUENCY OF CHECKING DATABASE - SET TO ONCE
        .Open
        On Error GoTo CloseRecordset
    End With

    'RETURN QUERY RESULTS BACK INTO A TWO DIM ARRAY (DOES NOT INCLUDE HEADERS)
    QueryDatabase = Rs.GetRows

CloseRecordset:
    Rs.Close

CloseConnection:
    Connection.Close

    'CHECK IF ERROR OCCURED
    If Err.Number <> 0 Then
        GoTo Catch
    End If

    Exit Function
Catch:
    'HANDLE ERRORS HERE...

End Function

Timestamp Validation
For validating your timestamp I would abstract that into its own formula returning a boolean value. Not exactly sure how your data is structured, or how you want to achieve this but below is a blueprint of what you could attempt to do.
Private Function TimestampValid() As Boolean

    Dim QueryName As String
    QueryName = "Query_" & timestamp

    Dim Connection As String
    Connection = "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & QueryName & ";Extended Properties="""""

    Dim Sql As String
    Sql = "SELECT * FROM [" & QueryName & "]"

    'DATA IS A TWO DIM ARRAY (MINUS THE HEADERS)
    Dim Data As Variant
    Data = QueryDatabase(Connection, Sql)

    'DO YOUR VALIDATION HERE...
    '(NOT SURE WHAT YOU ARE RETURNING SO I CAN'T DO IT FOR YOU)...

End Function


text:
Q: Is it possible to encrypt portions of faces-config file? I am working with JSF 2.1 Mojarra.  I have a Managed Bean that is initialized in the faces-config file.  There is some sensitive information in this file that I would like to encrypt.  Is this possible?  Or do I need to manage the object creation through some other mechanism.

A: I would encrypt the data, then convert it to text either as hex or base64 encoding and put thr resulting string into you config - it just text so thee will be no problem.
Have the class that uses the data decode and decrypt the data before using it.


text:
Q: How to generate a proxy class without client suffix for wcf service? when i generate proxy class from WCf service my proxy class name(not file name)is xxxxClient.
i don't want the client suffix for proxy class. Tell me how to generate it.

A: You cannot control that part. The generation is made using svcutil.exe, and it does not expose  options for naming aside from the namespace (which is also available in the GUI in Visual Studio).