text:
Q: Returning the matched string from a grepl match of multiple strings, rather than the logical Currently I'm using nested ifelse functions with grepl to check for matches to a vector of strings in a data frame, for example:
# vector of possible words to match
x <- c("Action", "Adventure", "Animation")

# data
my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.")
my_text <- as.data.frame(my_text)

my_text$new_column <- ifelse (
  grepl("Action", my_text$my_text) == TRUE,
  "Action",
  ifelse (
    grepl("Adventure", my_text$my_text) == TRUE,
    "Adventure",
    ifelse (
      grepl("Animation", my_text$my_text) == TRUE,
      "Animation", NA)))

> my_text$new_column
[1] "Animation" NA          "Adventure"

This is fine for just a few elements (e.g., the three here), but how do I return when the possible matches are much larger (e.g., 150)? Nested ifelse seems crazy. I know I can grepl multiple things at once as in the code below, but this return a logical telling me only if the string was matched, not which one was matched. I'd like to know what was matched (in the case of multiple, any of the matches is fine.
x <- c("Action", "Adventure", "Animation")
my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.")
grepl(paste(x, collapse = "|"), my_text)

returns: [1]  TRUE FALSE  TRUE
what i'd like it to return: "Animation" ""(or FALSE) "Adventure"

A: Following the pattern here, a base solution.
x <- c("ActionABC", "AdventureDEF", "AnimationGHI")

regmatches(x, regexpr("(Action|Adventure|Animation)", x))

stringr has an easier way to do this
library(stringr)
str_extract(x, "(Action|Adventure|Animation)")

A: Building on Benjamin's base solution, use lapply so that you will have a character(0) value when there is no match.
Just using regmatches on your sample code directly, will you give the following error.
    my_text$new_column <-regmatches(x = my_text$my_text, m = regexpr(pattern = paste(x, collapse = "|"), text = my_text$my_text))

    Error in `$<-.data.frame`(`*tmp*`, new_column, value = c("Animation",  :
  replacement has 2 rows, data has 3

This is because there are only 2 matches and it will try to fit the matches values in the data frame column which has 3 rows.
To fill non-matches with a special value so that this operation can be done directly  we can use lapply.
my_text$new_column <-
lapply(X = my_text$my_text, FUN = function(X){
  regmatches(x = X, m = regexpr(pattern = paste(x, collapse = "|"), text = X))
})

This will put character(0) where there is no match.
Table screenshot
Hope this helps.

A: This will do it...
my_text$new_column <- unlist(
                         apply(
                             sapply(x, grepl, my_text$my_text),
                             1,
                             function(y) paste("",x[y])))

The sapply produces a logical matrix showing which of the x terms appears in each element of your column.  The apply then runs through this row-by-row and pastes together all of the values of x corresponding to TRUE values.  (It pastes a "" at the start to avoid NAs and keep the length of the output the same as the original data.)  If there are two terms in x matched for a row, they will be pasted together in the output.


text:
Q: Which weapons have extended magazines available for unlock? For example most of the LMG's do. Some SMG's do. Has anybody compiled a list?

A: By going through all the weapons in battlelog, the following weapons can have extended magazines attached to them.

*

*All Support weapons (except for the QBB-95 and MG-36).

*The PP-2000, PDW-R, MP7, AS Val and M5K.

*All Shotguns.
So not many at all, and all of the ones that can are either a LMG, SMG, or a Shotgun.

A: In all of the weapon classes I have come to see, every gun uses a secondary slot for extended mags except for three weapons in the support class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sketch level curves of the form $f(x,y)= |x|+|y|$? I'm struggling to sketch the level curves of the equation $f(x,y)= |x|+|y|$
I know for finding the level curves you have to set $f(x,y) = C$ (with c a constant). But then I have the equation $|x|+|y|=C$.
So lets say $C=0$, then $|x|+|y|=0$, but how can I sketch this. Because both x and y are greater then zero, and they have to add up to 0, therefore x and y needs to be zero, but then I can't draw anything.
So lets say $C=1$,then $|x|+|y|=1$, but how can I sketch this. Can I say that $x + y= \pm1$, therefor $y=1-x$ and $y = 1+x$ (but $x$ can't be negative, so I don't know how do this problem.)
If you know the answer, it would be very much appreciated to help me
Thank you in advance.

A: If $|x|+|y|=1$, consider four possibilities:

*

*$x,y\geqslant0$: then you just have $x+y=1$;

*$y\leqslant0\leqslant x$: then you just have $x-y=1$;

*$x,y\leqslant0$: then you just have $-x-y=1$;

*$x\leqslant0\leqslant y$: then you just have $-x+y=1$.

So, your curve is a square, expressed as the union of $4$ line segments. To be more precise: it's the square whose vertices are $(\pm1,0)$ and $(0,\pm1)$.

A: I just add a comment to the already proposed solutions.
Since $f(x,y) = f(-x, y) = f(x, -y) = f(-x, -y)$, the level sets of $f$ are symmetric w.r.t. the reflections about the axes $(x,y) \mapsto (-x,y)$ and $(x,y) \mapsto (x,-y)$,
and w.r.t. the symmetry about the origin $(x,y) \mapsto (-x, -y)$.
Given that, it is enough to draw the level set for example in the quadrant $x\geq 0$, $y\geq 0$, and then you get the whole picture using the above symmetries.


text:
Q: Display or hide elements on window resize using jQuery I'm a bigger in jQuery and trying to build a hamburger menu when the window is smaller than 750px and it works how it suppose to. The problem is that when I resize the window to be more than 750px the hamburger doesn't change back to a regular menu. I tried $(window).resize but it doesn't do what I want it to.
My jQuery Code
$(document).ready(function () {
    var width = $(window).width();
if (width <= 750) {
    //Variables
    var ham = $('.hamburger');
    var nav = $('nav')

    //Hamburger Function
    ham.show();
    ham.click(function() {
        $('.menu').toggle();
    });

    //Navigation Menu Function
    nav.hide();

} else {
    $('p').append('Bigger than 750');
}

});
http://jsfiddle.net/IrvinBurciaga/0vn00oLh/

A: $(window).resize should be the correct function but you also need to call the function to check initially to ensure the menu is shown correctly
//initialize the hamburger menu once on ready
$(document).ready(function() {
     var ham = $('.hamburger');

    //Hamburger Function
    ham.show();
    ham.click(function() {
        $('.menu').toggle();
    });

    //call the checkWindowWith by yourself on ready
    checkWindowWidth();
});

//register the resize function
$(window).resize(checkWindowWidth);

function checkWindowWidth() {
    var width = $(window).width();

    if (width <= 750) {
        $('.hamburger').show();
        $('.nav').hide();
    } else {
        $('.hamburger').hide();
        $('nav').show();
    }
}

jsfiddle demo


text:
Q: Loading Bootstrap modal after delay not working I'm working on a cratejoy site, and my client needs a modal to popup after a set amount of time. I added the modal and when I use this it works fine:
$('#myModal').modal('show');

But when I try to use either of these answers from this page, it get a Uncaught TypeError: $(...).modal is not a function error and the modal does not popup. You can see it not working here.

A: First of all you need to have link to bootstrap.js in your page and loaded after jquery.
Second you have to place the script in a script tag before the end body tag
$(document).ready(function(){
   $('#myModal').modal('show');
});

In order to delay the modal you can do this:
setTimeout(function(){
    $('#myModal').modal('show');
}, 5000)

A: You have multiple versions of jQuery being loaded
Apart from the obvious version with it's own script tag your main.js file also includes it.
Since it loads after bootstrap.js it overwrites the whole jQuery object and removes reference to bootstrap in original version. That is why you get the error shown
Choose which version of jQuery you want to use and remove the other.
Make sure boostrap.js loads after the selected choice


text:
Q: What is the general name for equations of the form $x\cdot{A}^{x}=B$? What is the general name for equations of a single variable which appears both as a multiplier and as an exponent?
For example: $\large{x}\cdot{A}^{x}={B}$
I couldn't find the answer to that on Wikipedia.
Thanks...


text:
Q: Functional dependency - adding any attribute to X will still yield a FD? I have heard my professor saying that when X → Y is a functional dependency, adding any attribute to X or removing any attribute from Y will still yield a functional dependency. I do not understand how this could be true? If I add any attribute into X, how could it imply the same Y?

A: Informally, this is because if we know that the values of a set of attributes $X$ uniquely determine the values of a set of attributes $Y$, then obviously the values of some set $X' \supset X$ of attributes also determines the values of attributes $Y$ uniquely. And if the values of all attributes in $Y$ are determined uniquely, so are, of course, the values of all attributes in $Y' \subset Y$.
Formally, if $X$ of $n$-tuples, functional dependency $$
  (x_1,\ldots,x_k) \to (x_{n-l+1},\ldots,x_n)
$$
means that whenever two tuples in $X$ have the same first $k$ components, they also have the same last $l$ components, i.e. that $$
  \text{For all }x,y\in X \,:\, x_1=y_1,\ldots,x_k=y_k \,\Rightarrow\, x_{n-l+1}=y_{n-l+1},\ldots,x_n=y_n
$$
Now, if we replace $k$ by $k' \geq k$ and $l$ by $l' \leq l$, which amounts to adding attributes to the left-hand side and removing attribute from the right-hand side of the function dependency, that statement remains true. Observe that obviously $$\begin{eqnarray}
  x_1&=&y_1,&\ldots&,x_{k'}&=&y_{k'} &\Rightarrow&
  x_1&=&y_1,&\ldots&,x_k&=&y_k &\text{ if $k \leq k'$} \\
  x_{n-l+1}&=&y_{n-l+1},&\ldots&,x_n&=&y_n &\Rightarrow&
  x_{n-l'+1}&=&y_{n-l'+1},&\ldots&,x_n&=&y_n &\text{ if $l' \leq l$,}
\end{eqnarray}$$
and by combining that with the definition of functional dependency above, we get (again assuming $k \leq k'$, $l' \leq l$) that $$
\begin{eqnarray}
  \text{For all }x,y\in X \,:&
  x_1=y_1,\ldots,x_{k'}=y_{k'} \\
  \Rightarrow& x_1=y_1,\ldots,x_k=y_k \\
  \Rightarrow& x_{n-l+1}=y_{n-l+1},\ldots,x_n=y_n \\
  \Rightarrow& x_{n-l'+1}=y_{n-l'+1},\ldots,x_n=y_n \text{.}
\end{eqnarray}
$$
Leaving out the middle part of the chain of implications yields exactly what we wanted $$
  \text{For all }x,y\in X \,:\,
  x_1=y_1,\ldots,x_{k'}=y_{k'}
  \,\Rightarrow\, x_{n-l'+1}=y_{n-l'+1},\ldots,x_n=y_n \text{.}
$$


text:
Q: Passing variable from another class as input but not getting value back I have a class where I hold some variables :
public class PreviousCalls
{
    private static int bot1Call;
    public static int previousBot1Call
    {
        get { return bot1Call; }
        set { bot1Call = value; }
    }

    private static int bot2Call;
    public static int previousBot2Call
    {
        get { return bot2Call; }
        set { bot2Call = value; }
    }

    private static int bot3Call;
    public static int previousBot3Call
    {
        get { return bot3Call; }
        set { bot3Call = value; }
    }

    private static int bot4Call;
    public static int previousBot4Call
    {
        get { return bot4Call; }
        set { bot4Call = value; }
    }

    private static int bot5Call;
    public static int previousBot5Call
    {
        get { return bot5Call; }
        set { bot5Call = value; }
    }
}

I need to pass those variables as parameters to a lot of methods in my other class here's how I do it :
void AI(... , int previous)
AI(... , PreviousCalls.previousBot1Call);

So the parameter previous is changing the way it should but the variables from class PreviousCalls are not changing at all, why is that ?

A: int is value type, so there is a copy of 'previous value' passed to method body. So changing a variable inside method doesn't cause the original value change:
public void Test(int a)
{
   a = 10;
}

int t = 11;
Test(t);
//t is still 11, because Test method operates on copy of t

To change original value you must use ref or out:
void AI(..., ref int previous) { ... }

int param;
AI(..., ref param); //when ref is used, original variable wil be changed.
PreviousCalls.previousBot1Call = param;

Unfortunately, you cannot use it like this:
AI(... , ref PreviousCalls.previousBot1Call); // compile-time error
                                              // member-access is forbidden wtih out/ref
AI(,.., ref 10); // compile-time error

Another attempt:
    interface IAIParam
    {
         int Previous { get; set; }
         // other params
    }

    void AI(IAIParam p)
    {
       p.Previous += 1;
       //....
    }

And then implementaiton:
internal class MyBotProxy : IAIParam
{
    public int Previous
    {
        get { return PreviousCalls.previousBot1Call; }
        set { PreviousCalls.previousBot1Call = value; }
    }
}

usage:
var myProxy = new MyBotProxy();
AI(myProxy);

A: Most commonly methods do not change any values outside of their method scope, instead they return a new value. Only methods that accept the parameter by reference instead of value can change the value of the parameter in the calling context.
This article on MSDN is a great starting point for understanding how to pass parameters by reference instead of value.
Please note that you will not be able to pass a class member as a ref or out parameter. If you wish to update part of a class via reference, you will need to pass the entire class object as the reference.


text:
Q: Kids'/Young Adult Book - TV set that shows tomorrow's news Trying to remember the title of a popular kids'/young adult book from the '70s - it had a Motorola television set that showed tomorrow's news. Kind of like shows like "Early Edition," where the guy gets tomorrow's newspaper each day.

A: Could this be A Billion for Boris by Mary Rodgers?

When Ape Face fixes a broken-down television set Boris sold to him, something unusual happens. Instead of regularly scheduled programs, this TV shows the future -- one day in advance! They get tomorrow's shows, tomorrow's movies, and tomorrow's news. Annabel thinks they should use their new TV with ESP to help people, but Boris has plans of his own ...

One of the reviews on Goodreads mentions a motorola TV.

"Worth reading just for the passing references to The Partridge Family and Motorola tvs."


text:
Q: Keeping a CCLayer on top when using CCGrid3D I've been playing around with Cocos2d for a couple of days and got a little bit confused regarding depths (z and vertexz props).
My test app is using CCActionPageTurn3D to create a page-flip action on a CCLayer and everything works fine. But when I try to keep a couple of GUI buttons (A CCLayer with a CCMenu in it) on top of everything they end up behind the CCLayer where the action is performed. It doesn't matter that z-value i set the GUI to, but if I sets its vertexZ to a higher value it stays on top (but gets scaled which I don't want it too). Does anyone have a solution to this?

A: Solved it myself by overriding the visit method in my GUI class using glDepthFunc:
-(void) visit {

    glDepthFunc(GL_ALWAYS);
    [super visit];
    glDepthFunc(GL_LEQUAL);

}


text: Q: Appropriate Time Series Model for Data with Shifting Mean? I have a daily data of sales. However, as seen on the graph, there is a clear shift in the mean values starting 2010. What could be the best prediction model to use in this case? I tried using several classical time series models like SARIMA and TBATS via Python but prediction performance is not satisfactory. Thank you.


text:
Q: Python module importation error with pytest in a venv I have a package which contains several modules and a cython extension. I am able to install the package with the standard pip install command in virtual environments, it compiles my cython extension and so on. Everything works great. Now, I would like to test all of those with pytest. Here again, everything works great locally (or when I install the package on any other machine). However, when I use a docker image (the one from circleci) the compiled cython extension is not found when I run my tests with pytest.
The structure of my package is as follow
/home/circleci/dspt
├── dspt
│   ├── connection
│   ├── data
│   └── sp
│       ├── bilateral
│       │   ├── filters.pyx
│       └── signal_processing.py
├── setup.py
├── tests
│   └── test_data.py

I install this package in a virtual environment /home/circleci/dspt/myvenv. So, under this venv, I tried theses:
(myvenv) /home/circleci/$ python
>>>import dspt.sp.filters  # ok!

but if I change the directory
(myvenv) /home/circleci/dspt$ python
>>>import dspt.sp.filters  # ModuleNotFoundError: No module named 'dspt.sp.filters'

I got the same error with pytest
(myvenv) /home/circle$ pytest dspt/tests/test_data.py
================================================= test session starts ==================================================
platform linux -- Python 3.6.7, pytest-5.0.1, py-1.8.0, pluggy-0.12.0
rootdir: /home/circleci/dspt/tests, inifile: pytest.ini
plugins: mock-1.10.1, metadata-1.8.0
collected 12 items / 1 errors / 11 selected

======================================================== ERRORS ========================================================
________________________________________ ERROR collecting test_ecg_analysis.py _________________________________________
ImportError while importing test module '/home/circleci/dspt/tests/test_data.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/home/guillaume/src/dspt/tests/test_data.py:3: in <module>
    ???
dspt/dspt/sp/signal_processing.py:9: in <module>
    from dspt.sp.filters import bilateral_filter
E   ModuleNotFoundError: No module named 'dspt.sp.filters'


text:
Q: How to allow write rights only to specific users building a new module in OpenErp? I'm new to OpenErp and I'm trying to undestand access rights writing a new module.
Let's say I have  this module called Project, with title, description and a many2many relation with res.users called admin_ids, this relation represents project admins.
How can I give write rights on projects only to their admins?
Thanks in advance.

A: http://doc.openerp.com/trunk/developers/server/04_security/#access-rights
OpenERP 7 Access Rights for User Roles
Here are the some links which helpful to you
you have to make a group and assing this group access right to write and give this group to uses


text:
Q: Shopify GraphQL Storefront API Query Error Hello I am a beginner with GrapQL/Shopify and have been following the documentation here. After trying to run a basic Storefront API call below to get information about a Collection
query getProductById($id: "gid://shopify/Product/xxxxxxxxx") {
  product(id: $id) {
    title
  }
}

I get the error below
{
  "errors": [
    {
      "message": "Parse error on \"gid://shopify/Product/xxxxxxxxx\" (STRING) at [1, 27]",
      "locations": [
        {
          "line": 1,
          "column": 27
        }
      ]
    }
  ]
}

I'm sure it's a syntax issue but the documentation isn't very clear on what the correct way of entering the query argument information is.
Thanks in advance

A: You should be passing the data type of the product ID where you're currently passing the product ID. In this case, the data type of the product ID is ID!
It should look like this:
query getProductById($id: ID!) {
  product(id: $id) {
    title
  }
}

The product ID is sent in the variables object which is separate to the query
Shopify have a really useful GraphQL tool to help get a better understanding of how to query data from your store
https://shopify-graphiql-app.shopifycloud.com/login


text:
Q: PHP, remove string using "pattern" I have the following url which will always have a color variable attached:
http://www.example.com/?new=yes&color=red&shape=square

How would I, using PHP, remove everything at the end; starting at &color, so I am left with the following:
http://www.example.com/?new=yes

A: The literal answer to your question is:
$url = substr($url, 0, strpos($url, '&color='));

However, this is good only for the specific case -- it would probably be a good idea to do something a little more robust. For example, splitting the URL, getting the key/value pairs into an array, removing those you don't want (or removing everything except those you want) and recreating the URL.

A: I would recommend the combination of parse_url & parse_str. You can also use http_build_url & http_build_str, though these require pecl_http.

A: $url = "http://www.example.com/?new=yes&color=red&shape=square";

$url_parts = explode("&", $url);

$thePartYouWant = $url_parts[0];


text:
Q: Bash-Shell Script aborts without error On Debian is the following code working, but on CentOS it just aborts without any errors. What is the error? I can't understand it.
    echo "Test 1"
    ANSWER=""
    read -p "Enter y or n " ANSWER;
    echo "Test 2"

The output looks allways like that:
    Test 1

I also tried the read command without the parameter -p, but that's also not working:
    echo "Test 1"
    ANSWER=""
    echo "Enter y or n "
    read ANSWER;
    echo "Test 2"

Output:
    Test 1
    Enter y or n

If I execute the command at the command line is it working, how it should. The script has following "headline": #!/bin/bash
Can somebody help?

A: try this
#!/bin/bash

echo "Test 1"
read -p "Enter y/n: " ANSWER
echo " Test 2: ${ANSWER}"

You didn't need a close on the end of answer.

A: @user2966991 - The script which reads from stdin is inside a bigger while loop which reads a file through stdin. This will not work. Try redirecting your stdin to a different file handler.
Consider this sample code. This will not work becuase both the while loop and read are reading from stdin.
#!/bin/bash
cat samplefile | while read line; do
    read -p "$line (y/n)?" ANSWER
done

Now consider this other code.
#!/bin/bash
# save stdin to file descriptor 5
exec 5<&0

cat samplefile | while read line; do
    read -p "$line (y/n)?" ANSWER <&5
done

# restore stdin and close file descriptor 5
exec 0<&5 5>&-

Personally I prefer input redirection than pipe.
cat file | while read var; do
...
done

can be written as
while read var; do
...
done < file

Next time please post your script here or you will not get any answer.


text:
Q: How to code CssRect borderEdge I found just what I needed to determine the dimensions of a div in Dart here
In short, it says:
Experimental
CssRect get borderEdge

Access the dimensions and position of this element's content + padding + border box.

How do code this?
I'm trying to use it with this variable:
import 'dart:html' as dom;
dom.DivElement textSpan = new dom.DivElement()

I found this example:
CssRect get borderEdge => textSpan.borderEdge;

My IDE (PHPStorm) throws up on it. I'm a Dart noob so I may be missing something obvious. Here's a screen shot:

I also get a build error:
Compiling citation|web/main.dart...
[Error from Dart2JS on citation|web/main.dart]:
packages/citation/tooltip/tooltip.dart:68:5:
Expected ';' after this.
CssRect get borderEdge => textSpan.borderEdge;
^^^^^^^
[Info from Dart2JS]:
Took 0:00:04.330468 to compile citation|web/main.dart.
Build failed.

I installed the Dart Editor and open the program in it. It didn't like it either:

tooltip.dart
This started out as the tooltip component from the Angular Dart Chapter 4 Tutorial
library tooltip;

import 'dart:html' as dom;
import 'package:angular/angular.dart';

@Decorator(selector: '[tooltip]')

class Tooltip
{
final dom.Element element;

@NgOneWay('tooltip')
TooltipModel displayModel;

dom.Element tooltipElem;
dom.Element entry;          // Bibliographic entry: div in the index.html

Tooltip(this.element)
{
element..onMouseEnter.listen((_) => _createTemplate())
       ..onMouseLeave.listen((_) => _destroyTemplate());
}

void _createTemplate()
{
assert(displayModel != null);

tooltipElem = new dom.DivElement();

// All entries have the id 'bex' where x is an integer

entry = dom.querySelector('#be${displayModel.entryRef.toString()}');
String htmlText = entry.innerHtml;

if (displayModel.entryRef != null)
{
  dom.DivElement textSpan = new dom.DivElement()
      ..appendHtml('<hr>')
      ..appendHtml(htmlText)
      ..style.color = "black"
      ..style.fontSize = "smaller"
      ..style.paddingBottom = "5px";

  tooltipElem.append(textSpan);
}
int entryWidth = 200;
tooltipElem.style
    ..padding = "5px"
    ..paddingBottom = "0px"
    ..backgroundColor = "#FFF5E0"
    ..borderRadius = "5px"
    ..width = "${entryWidth}px";

// position the tooltip.

int windowHeight = dom.window.innerHeight;
int windowWidth = dom.window.innerWidth;
var elTopRight = element.offset.topRight;
var elBottomLeft = element.offset.bottomLeft;
int height = 100;
int top = elTopRight.y;
int bottom = elBottomLeft.y;
int left = elBottomLeft.x;
int right = elTopRight.x;
CssRect get borderEdge => textSpan.borderEdge;
print('borderEdge:$borderEdge');
// See if it will fit above
int y = top - height - 10;
if (y < 0) y = bottom + 10;   // If it doesn't fit, put it below
// Start with the left
int x = left;
tooltipElem.style
    ..position = "absolute"
    ..top = "${y}px"
    ..left = "${x}px";

 // Add the tooltip to the document body. We add it here because we need to position it
 // absolutely, without reference to its parent element.
dom.document.body.append(tooltipElem);
}

void _destroyTemplate()
{
  tooltipElem.remove();
}
}

class TooltipModel
{
  final int entryRef;

  TooltipModel(this.entryRef);
}

Answer
This summarizes Günter Zöchbauer's answer in the comments and an answer of my own.
The first problem was that I was using the wrong syntax given the location of the code. The correct code for this location is:
 CssRect borderEdge = tooltipElem.borderEdge;

The second problem unique to my situation was that my import statement was declared as:
import 'dart:html' as dom;

The 'as dom' requires me to prefix all html api references with dom. So in my case, I needed to code:
 dom.CssRect borderEdge = tooltipElem.borderEdge;

I got this code from the Angular dart tutorial. My next step is to remove that prefix so it doesn't screw me up again. Also note the answer code uses tooltipElem instead of textSpan. That change has nothing to do with the fix to the problem.

A: I tried and it works just fine (I'm using Dart bleeding edge/nightly build)


text:
Q: why is there only a referenced before assignment error for int values but not lists inside a nested function? I'm doing a leetcode problem - rightSideView. When I create an inner helper function, I thought I'd have access to the outer function variables. However, that only holds true for result (a list) but not maxHeight (an int). Code referenced below:
class Solution(object):
    def rightSideView(self, root):
       result = []
       maxHeight = 0
       def dfs(node, height):
           if node is not None:
               height += 1
               if height > maxHeight:
                   maxHeight = height
                   result.append(node.val)
               dfs(node.right, height)
               dfs(node.left, height)
       dfs(root, 0)
       return result

This can be fixed if I reference self.maxHeight; however I don't have to do the same for result. Why is this? Could it be that lists are created as global variables inside classes in python? Not sure how else to explain this.
The following code works without errors:
class Solution(object):
    def rightSideView(self, root):
       result = []
       self.maxHeight = 0
       def dfs(node, height):
           if node is not None:
               height += 1
               if height > self.maxHeight:
                   self.maxHeight = height
                   result.append(node.val)
               dfs(node.right, height)
               dfs(node.left, height)
       dfs(root, 0)
       return result


text:
Q: Drive Realtime API no longer returns realtime document on localhost I have been calling the following gapi javascript function with great success for a few months:
gapi.drive.realtime.load(fileId,
                         successHandler,
                         initializer,
                         errorHandler);

Suddenly, at 1:30 PM CDT today, that call stopped working when run in javascript on localhost.  I can deploy the exact same code to my server and it works perfectly!
Frustratingly, none of the callbacks are called - not successHandler OR errorHandler.
I have localhost:3000 set as an allowed javascript origin in my Google API Console project, and anyway I haven't changed any settings there since this was working.  I am correctly authorized and can make REST calls to the Drive API without an issue.
Has anyone else seen this behavior suddenly?  Can anyone from the Google team make a suggestion?
Update: the request inspector shows a GET to
https://drive.google.com/otservice/gs?access_token=[ommitted-for-stackoverflow]&id=[also-omitted]

with the response
)]}'
["17AKDsTY8kHESKfQavrHeh3YybD5k4b6ty8CQ78MHtyc","724b79b808d48070",false,1,[1,""],[0,[28,"724b79b808d48070","110581799581534438628",false,true,"REL DEV","#58B442","https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/s128/photo.jpg"]]]

The headers are
HTTP/1.1 200 OK
status: 200 OK
version: HTTP/1.1
access-control-allow-origin: *
access-control-expose-headers: Content-Length,Content-Type,X-Restart
alternate-protocol: 443:quic
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-disposition: attachment; filename="json.txt"; filename*=UTF-8''json.txt
content-encoding: gzip
content-type: application/json; charset=utf-8
date: Fri, 04 Apr 2014 22:15:40 GMT
expires: Fri, 01 Jan 1990 00:00:00 GMT
pragma: no-cache
server: GSE
vary: Origin
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-restart:
x-xss-protection: 1; mode=block

There are no other requests after that.


text:
Q: Jquery mouseover function not firing I have this Jquery code:
$(document).ready(function() {

    // Do menu mouseovers
    $('.bar a').each(function() {

        var Link = $(this);
        var LinkID = Link.attr("ID");

        $('.menu-pop').each(function() {
            var PopID = $(this).attr("data-for");

            // We have found a match, assign events
            if (PopID == LinkID) {

                Link.mouseover = (function() {
                    alert("trucks lol");
                });

                return;
            }
        });

    });

});

It's for a popup menu I'm writing.  The simplified structure of the menu is:

    Home
    Another Link

    Links and stuff

I'm expecting it to do the alert when my mouse goes over the "Another" link, but at present it throws no errors/no alert.
Any help appreciated.

A: Did you try
Link.mouseover(function() {
  alert("trucks lol");
});

(using jQuery's mouseover function which is a shortcut for binding the mouseover event)

A: See: http://jsfiddle.net/rQ72v/
Change this:
Link.mouseover = (function() {
    alert("trucks lol");
});

to this:
Link.mouseover(function() {
    alert("trucks lol");
});

Link.mouseover = doesn't really make any sense.
Perhaps Link.onmouseover = would work (or would you need Link[0].onmouseover =?) in terms of raw JavaScript.
But, it's much better to use jQuery's .mouseover().

A: I would replace the
// ...
$('.bar a').each(function() {
    var Link = $(this);
// ...

by something line
// ...
$('.bar a').each(function(item) {
    var Link = $(item);
// ...


text:
Q: Java Regex Syntax Error How do I search this regex: "\s*Lol(.*?)\s*" in Java? This won't work.
Pattern posts = Pattern.compile(""\s*Lol(.*?)\s*"");

A: You need to escape backslashes (and quotation marks too)
Pattern posts = Pattern.compile("\"\\s*Lol(.*?)\\s*\"");

Official java tutorial on regular expressions


text:
Q: Migrating only specific database items in Wordpress from staging to live I want to find a way to push only certain pieces of my database from the staging environment to production. For instance, if I make a change in Widgets, but there's changes in Pages I don't want pushed yet, I can just push only Widgets without pushing the entire site.
Is there a plugin I can do this with? Or even any manual options.
Thanks


text:
Q: I would like to find if the new found links from Beautiful soup is already in the queue.txt file and crawled.txt file I have a beautiful soup program where I find all the links on a webpage and put it in a queue.txt file. The program then gets each link from the file and find all the links on those links. They then get put into a crawled.txt file for all the crawled links.
I want to make sure I get no duplicates so I want the program to go through the queue.txt and crawled.txt and if the links that have just been found are in those files, then the new found links shouldn't be put in the file
I have tried doing it so that it prints the newly found links into a list and removes duplicates from there and prints the list to a .txt file but it wouldn't be able to tell what is in the queue file it only removes duplicates from the newly found links from the one page.
This is the code:

from bs4 import BeautifulSoup
import requests
import re
from urllib.parse import urlparse

def get_links(base_url, file_name):
    page = requests.get(base_url)
    soup = BeautifulSoup(page.content, 'html.parser')
    single_slash = re.compile(r'^/\w')
    double_slash = re.compile(r'^//\w')

    parsed_uri = urlparse(base_url)
    domain_name = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)

    with open(file_name, "a") as f:
        for tag in soup.find_all('a'):
            link = str(tag.get('href'))

            if str(link).startswith("http"):
                link = link
                print(link)

            if double_slash.match(link):
                link = 'https:' + link
                print(link)

            if single_slash.match(link):
                link = domain_name + link
                print(link)

            if str(link).startswith("#"):
                continue

            if str(link).startswith("j"):
                continue

            if str(link).startswith('q'):
                continue

            if str(link).startswith('u'):
                continue

            if str(link).startswith('N'):
                continue

            if str(link).startswith('m'):
                continue

            try:
                f.write(link + '\n')
            except:
                pass

get_links('https://stackabuse.com/reading-and-writing-lists-to-a-file-in-python/', "queue.txt")

with open('queue.txt') as f:
    lines = f.read().splitlines()
print(lines)

for link in lines:

    if lines[0] == "/":
        del lines[0]

    print(lines[0])
    with open('crawled.txt', 'a') as h:
        h.write('%s\n' % lines[0])
        h.close()

    del lines[0]

    if lines[0] == "/":
        del lines[0]

    with open('queue.txt', 'w') as filehandle:
        for listitem in lines:
            filehandle.write('%s\n' % listitem)

        page_url = lines[0]
        get_links(page_url, "queue.txt")
    print(lines)

    with open('queue.txt') as f:
        lines = f.read().splitlines()

A: In general for Python, when trying to remove duplicates, sets are usually a good bet. For example:
lines = open('queue.txt', 'r').readlines()
queue_set = set(lines)
result = open('queue.txt', 'w')
for line in queue_set:
    result.write(line)

Note: This will not preserve the order of the links, but I don't see a reason for that in this case.
Also, this was adapted from this answer.


text:
Q: Reverse a singly linked list Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Here's what I saw online:
class Solution:
def reverseList(self, head):
    def reverse(prev, cur):
        if cur:
            reverse(cur, cur.next)
            cur.next = prev
        else:
            nonlocal head
            head = prev

    reverse(None, head)
    return head

But I didn't get the process how it works after the if cur.
For example the test case is [1,2,3,4,5].

*

*input None, 1 into the reverse function

*cur exist, run reverse function with 1, 2
...

*cur exist, run reverse function with 4, 5

*cur does not exist, (then what???)

BTW why does listNode even exist? It is not as easy as others like list array or dictionary. When should i use it?

A: There's no efficient way to do this. The only way without interacting with the list beforehand, is an algorithm of a complexity of O(n * n), where you repeatedly go through the linked list, find last element and remove it, while adding it to a new linked list, until the first list is completely empty. If you wanted to preserve that list, you'd have to recreate that list during the reversing or simply copy it beforehand, not fun at all. This is what example you posted does.
def reverse(prev, cur):
    if cur: # this should actually be if cur is not None:
        reverse(cur, cur.next) # call same method on next node
        cur.next = prev # when we are back from recursion hell, set previous one as next one, because we are reversing
    else: # we finally reached the end
        nonlocal head # excuse me, this is in a class but you wrap in multiple functions and use nonlocal??? Where did you even dig out this thing from?
        head = prev # head now becomes the previous node, because this node is None, or, end of the list

If you just want to learn about them, then this algorithm is perfectly fine, in any other case, you should at least upgrade to doubly linked list, you'll use insignificant amount of memory to speed up reversal a lot.
If you create your own doubly linked list, reversing could be as fast as swapping end and start "pointers", if you write it in a way where every node has two references, left and right in a list, such as neighbours = [left, right], your linked list could store a value called advance direction, which would be either 0 or 1, meaning that you could reverse entire list from start to end while going to left to right to end to start while going right to left by merely swapping start with end and changing "advance value" from 1 to 0. The advance value would be wrapped in a method like next(), which would look something like this:
def next(self):
    if self.current is None:
        return None # could be return self.current or even just "return", this is Python
    self.current = self.current.neighbours[self.advance_value]
    return self.current

When advance_value is 0, it goes left, when advance_value is 1, it goes right through the list, all elements stay in their place, but to whoever is accessing it, it looks like it's reversed.


text:
Q: Error: value unionByName is not a member of null I have the below code to cache various partitions and save them in a map then to union them all
and i am getting the below error
unionByName is not a member of null
Var cache_map = Map[String,Dataframe]()
for (partition <- partitionlist){
  var df_test = spark.read.format("delta").load("abfs://container@storagename.dfs.core.windows.net/dirname")
.where((col("dt").like(partition+"%"))
  cache_map(partition) = df_test.cache()
}

val cache_keys = cache_map.keys
var df_union=null
for (key <- cache_keys){
  if(df_union==null){
    df_union=cache_map.get(key)
  }
  else{
 df_union=df_union.unionByName(cache_map.get(key)
}
}

When I do below
cache_map.get("20221120").unionByName(cache_map.get("20221119"))
I get the below error
Error: value unionByName is not a member of Option[org.apache.spark.sql.DataFrame]
Can anyone help me wity what's going wrong? I don't have as much experience with spark using scala as I have with pyspark. Any help is greatly appreciated.

A: As stated in Exception you are trying to call function unionByName on Option[DataFrame] and its failing because there is no such funtion on Option type. You need to either map or get you underlying dataframe from the Option to be able use df functions
You can try for example something like this:
cache_map.get("20221120").map{_.unionByName(cache_map.get("20221119").getOrElse(spark.emptyDataFrame))}

A: The error you are seeing is masking the real issue that you are going about the problem in the wrong way.
You are, as far as I can tell, reading in a (partitioned?) directory and then wanting only a subset of the data in a DataFrame in the variable df_union.
You are doing this by making multiple passes across the data, and each time you find a set of records you like you save them into a map, before finally combining all of your result sets.
This can be achieved with something like the following, where df stands in for your data:
val df = Seq(
  ("a1", 1),
  ("b1", 2),
  ("c1", 3),
  ("d1", 4),
  ("e1", 5),
).toDF("dt", "x")

// List of partition names you want to include in your final data
val partitionList: List[String] = List("a", "c", "e")
val filterCol: Column = col("dt")
// build a single filter expression
val filterExpr: Column = partitionList.map(pt => filterCol.like(s"$pt%")).reduce(_ or _)
// execute filtering
val filteredDf = df.filter(filterExpr)


text:
Q: Visual Studio won't run my app on windows if the project is stored in an external server I am developping an angular/ionic application that must be compatible with android, windows (phone and desktop) and Ios. I am currently trying to build and deploy the windows version on debug mode. My project is stored on an external server (disk f:). But everytime I start the app from visual studio (Windows-x64 and local machine in the configuration), I get this error (translated from french) :
    "DEP0700: Registration of the app failed. [0x80073CF0] erreur 0x80070003 :
  can't open AppxManifest.xml : The system cannot find the path specified."

I tried to copy my project on my desktop (disk c:) and when i run the app with this project, the deployment works fine and my app is running well.
I try to give all rights to system, user and administrator on the f: project, but nothing changes. There is no special char on the file path (except underscores). What am I doing wrong ?
(i set up everything in this tutorial https://cordova.apache.org/docs/en/7.x/guide/platforms/win8/index.html)

A: I encountered the same limitation, and it appears to be a limitation that Microsoft has decided they will not fix, but are considering for a future version.
Microsoft:  Closed -- Won't Fix: Add network share support
If you open the project properties, select the Build section, and under Output, specifiy a location on your C: drive for the Output path, you won't have to copy the binary files to your desktop manually.


text:
Q: Each User has a Personal Blog Is there a way for a website running Wordpress to have users register, and then each user have their own, personalized blog or page which others can see, or should I use another engine for this, and if so, which?

A: Yes, this is standard multisite behaviour, enable open registration in the network admin panel and visit a multisite blog that doesn't exist yet.


text:
Q: how do I access an object within a Dictionary? I can loop through the values of the Dictionary using a foreach.  However, I do not know how to access the Dictionary out-side of a foreach.
code:
Dictionary<string, dynamic> frmControlProp =
    new Dictionary<string, dynamic>();

public void setFrmControlTagProperties(string n, string tagVal)
{
    var dict = tagVal.Split('|')
        .Select(x => x.Split(':'))
        .Where(x => x.Length > 1 && !String.IsNullOrEmpty(x[0].Trim())
         && !String.IsNullOrEmpty(x[1].Trim()))
        .ToDictionary(x => x[0].Trim(), x => x[1].Trim());

    string en = dict["encrypt"];
    string sn = dict["settingName"];

    var conTag = new { Encrypt = en, SettingName = sn };

    frmControlProp.Add(n, new object());
    frmControlProp[n] = conTag;
}

foreach works as expected:
    foreach (var area in frmControlProp.Keys.ToArray())
    {
        var areaname = frmControlProp[area].Encrypt;
        //MessageBox.Show(areaname.ToString());
    }

Not sure how to access the Dictionary outside of a foreach:
public void textBox_LostFocus(object sender, EventArgs e)
{
    var c = (Control)sender;
    string cn = c.Name;

    //var cd = frmControlProp[cn];

    //MessageBox.Show(frmControlProp.Keys.ToArray()..ToString());
}

EDIT
This code worked as expected:
public void textBox_LostFocus(object sender, EventArgs e)
{
    var c = (Control)sender;
    string cn = c.Name.ToString();

    MessageBox.Show(frmControlProp[cn].Encrypt);
}

A:
I do not know how to access the Dictionary out-side of a foreach.

you are doing it yourself here
string en = dict["encrypt"];

But, i think your problem is that you are unable to access it elsewhere. if you are unable to access it somewhere, then you need to assign it to some variable that is accessible through out your form. As i see that you are trying to access it from your form frmControlProp. So, in your function setFrmControlTagProperties you need to assign dictionary to your form.
First of all create a public property that gets Dictionary. and then assign it like this
frmControlProp.Dict = dict;

then you can get it like this
public void textBox_LostFocus(object sender, EventArgs e)
{
    var c = (Control)sender;
    string cn = c.Name;

    //read the values here
    var cd = frmControlProp.Dict.Keys.ToArray();

}


text:
Q: Convert object instead of upcasting Is it possible to upcast an object in an irreversible way which would cause a loss of data.
For instance I have two classes :
public class A
{
    public string Name { get; set; }
}

public class B : A
{
    public int Length { get; set; }
}

And this simple code:
var b = new B {Length = 10, Name = "B Object"};

var a = b as A;

I would like to know if there is a way that if I cast a back to a B type object, the property Length would not exist and be default(int)

A: You cannot lose information this way. The object referenced by both 'b' and 'a' is the same object. The type-cast simply affects member access from the code's point of view.

A: When you cast, you don't change the object itself. It's only the type of the reference to the object that is changed.
So, even when the type of the reference is A, the actual type of the object is still B. If you cast the reference back to B the object is still intact, because its type never changed.
It's like looking at a unicorn (B) through a cut-out of a horse (A). Even when you don't see the horn and it looks like just a horse, the horn is still there, and when you remove the cut-out, you see that it's still a unicorn. :)


text:
Q: Breadth-First Traversal with a Tree that is implemented with vectors     class Employee {
    public:
        const std::string const getName();
        const std::vector<Employee>& const getSubordinates();
    private:
        std::string name;
        std::vector<Employee> subordinates;
    };

    void printEmployeeLevels(Employee e)
    {
    }

My program is supposed to be able to use breadth-first traversal to print out the names of employees in an hierarchy. For example, a given Employee e could have subordinates a and b. Employee a may have subordinates c and d, and employee b might have subordinate f. Then subordinate c may have subordinate g.
My problem is that I'm not sure how to apply this to a binary tree that doesn't really have a node structure with the attributes of left and right child. My main question that I have is that: If I use a queue to do this traversal, should I make it a queue of Employee objects, or a queue of vector of Employee objects?
    void printEmployeeLevels(Employee e)
    {
        Queue<Employee> q;

        q.enqueue(e);

        while (1){
        while(!q.isEmpty())
        {
            Employee k = q.front();
            std::vector<Employee> v = k.getSubordinates();
            for (int i = 0; i < k.getSubordinates().size(); ++i)
            {
                q.enqueue(v[i]);
                std::cout << v[i].getName() << " ";
            }
            q.dequeue();
            std::cout << '\n';
        }
        }
    }

The expected output is:  (given the scenario above where the order of the children nodes don't matter)
e
a b
c d f
g


text:
Q: How to delete row in for loop function? I want to delete the second row in every sheet in an excel file. Actually, i have done this.
for (i in 1:5)
    {bulan=read_excel(file, sheet=sheet[i],skip = 2)}

but it deletes the first 2 rows. How to only delete the second one? Thanx

A: It depends whether you would really like to delete a row in your excel sheet or read an excel sheet without a certain row.
Because what your are doing here is actually not deleting rows, but skipping the first two rows when reading the sheets. The function read_excel returns a dataframe.
If you want the dataframe without the second row, what you could do is:
for(i in 1:5){bulan <- read_excel(file, sheet=sheet[i])
     bulan <- bulan[-2,]
}

However, this would not make much sense as is, since bulan gets overwritten in every step of the for loop.
If you would like to delete rows in your excel file using R, you could read the file, delete the corresponding row of the dataframe in R, and read the dataframe to an excel file again. Apparently there is am R package called "xlsx" for writing excel files.


text:
Q: States of "positronium" with chiral fermions? When I combine positron and electron to form positronium, or generically two spin 1/2 particles, I have four possible spin combinations that arrange into a singlet and a triplet state, which in turn are the trivial and standard representations of SO(3).
Now, what does happen if one of the particles, or both, are chiral particles without their corresponding chiral partners? Imagine for the sake of discussion that you want to combine a neutrino and an electron, or two neutrinos, or a pair neutrino antineutrino. Are the combinations part of the SO(3) triplet, the singlet, or none of it?
Or instead neutrinos, think for instance mesons with one or two exotic chiral quarks.


text:
Q: Why does this EA (in early development) not produce an alert, or an error? #property strict

string subfolder = "ipc\\";
int last_read = 0;
int t = 0;
struct trade_message
  {
   int   time;       // time
   string   asset;      // asset
   string   direction;  // direction
   double   open_price; // open
   double   stop_price; // open
   double   close_price;// open
   float    fraction;   // fraction
   string   comment;    // comment
   string   status;     // status
  };
trade_message messages[];

int OnInit()
  {
  int FH = FileOpen(subfolder+"processedtime.log",FILE_BIN);
  if(FH >=0)
   {
   last_read = FileReadInteger(FH,4);
   FileClose(FH);
   }
   return(INIT_SUCCEEDED);
  }

void OnTick()
  {
  int FH=FileOpen(subfolder+"data.csv",FILE_READ|FILE_CSV, ","); //open file
  int p=0;
  while(!FileIsEnding(FH))
  {
  t = StringToInteger(FileReadString(FH));
  if(t<=last_read)
   {
   break;
   }
  do
   {
   messages[p].time = t;                                          // time
   messages[p].direction = FileReadString(FH);                    // direction
   messages[p].open_price = StringToDouble(FileReadString(FH));   // open
   messages[p].stop_price = StringToDouble(FileReadString(FH));   // stop
   messages[p].close_price = StringToDouble(FileReadString(FH));  // close
   messages[p].fraction = StringToDouble(FileReadString(FH));     // fraction (?float)
   messages[p].comment = FileReadString(FH);                      // comment
   messages[p].status = FileReadString(FH);                       // status
   Alert(messages[p].comment);
   }
   while(!FileIsLineEnding(FH));
   p++;
   Alert("P = ",p,"; Array length = ", ArraySize(messages));

   }

  FileClose(FH);
  last_read = t;
  FileDelete(subfolder+"processedtime.log");
  FH = FileOpen(subfolder+"processedtime.log",FILE_BIN);
  FileWriteInteger(FH,t,4);
  FileClose(FH);
  ArrayFree(messages);
  }

The code is in tick function in order to test it before taking it out to a function.
The data.csv file is:

Timestamp
Asset
Direction
Price
Stop
Profit
Fraction
Comment
Status

xxx
yyy
SHORT
13240
13240
13220
0.5
yyy SHORT 13240 - taken half at 13220 and stop to breakeven
U

xxx
yyy
SHORT
13240
13262
13040
1.0
55%
DP

The processedtime.log is not being created.

A: So 2 problems, both of my own making.

*

*Not skipping the header row, simply remedied by inserting

do f = FileReadString(FH);
while(!FileIsLineEnding(FH));

after FileOpen() (easier than altering my source for data.csv), and

*forgetting about the asset part of my structure, thus ensuring my structures got out of sync with my lines!! Remedied by adding messages[p].asset = FileReadString(FH); between messages[p].time = t and messages[p].direction = FileReadString(FH);


text:
Q: Why did Star Trek: Voyager season 1 only have 16 episodes?
*

*Star Trek: The Next Generation had 26 episodes in all seasons except for the second, which had 22 (not a huge difference)

*Star Trek: Deep Space Nine had 26 episodes in every season, except for the first, which had 20 (also not as much of a difference)

*Star Trek: Voyager had 26 episodes in every season, except for the first

The first season, however, had only 16.  After (almost) consistently having 26 for so long, why did the first season have such a huge difference?

A: UPN was a new network, and the entire network had a short first season.
Star Trek: Voyager was one of the founding series of Paramount's UPN Network.  The network (and thus ST:V) first went on the air on January 16, 1995.
The usual cycle for American prime-time TV series is from the late summer/early fall through mid-spring.
If you look at the summary table for the list of ST:V episodes, you'll see that all of the show's other seasons fit this pattern.
But UPN (and its competitor WB) likely started airing in January as a tactic to maximize the fledgling network's novelty value, and not compete with new seasons of popular TV shows (compare with Fox, which started prime time programming in April 1987).


text:
Q: VOIP notification with CallKit is not invoking reportIncomingCall when app is inactive killed state It's a video calling app. I have implemented VoIP notifications to receive a video call. On receiving VoIP notification, I am using CallKit to call reportNewIncomingCall().
When I minimise the app, I receive the incoming call and the flow works fine.
But when I kill the app, I am not getting the incoming call. Any idea why?
I also noticed that when I tap and open the app next time, it gets crashed :
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Killing app because it never posted an incoming call to the system after receiving a PushKit VoIP push callback.'

This says that I am not posting reportNewIncomingCall. But I am already doing it and getting call when app is minimized.
func pushRegistry(_ registry: PKPushRegistry,
                  didReceiveIncomingPushWith payload: PKPushPayload,
                  for type: PKPushType,
                  completion: @escaping () -> Void) {

    provider.reportNewIncomingCall(with: uuid, update: update) { error in

    }
    completion()
}

Only on killed state, I don't get the calls. What else to be done to receive calls in killed state? Please help.

A: Have you tried to call the pushRegistry completion handler inside the reportNewIncomingCall completion handler?
func pushRegistry(_ registry: PKPushRegistry,
                  didReceiveIncomingPushWith payload: PKPushPayload,
                  for type: PKPushType,
                  completion: @escaping () -> Void) {

    provider.reportNewIncomingCall(with: uuid, update: update) { error in
        completion() // <----
    }
}

Even if it's not clear in the documentation, I think it's the correct way to handle a new incoming call.


text:
Q: Where are my files created by IsolatedStorageFileStream? I would like to debug an IsolatedStorageFileStream generated xml file. Where do I find the file?

A: Physical location is:
Windows 7 / 2008:
<SYSTEMDRIVE>\Users\<user>\Local Settings\Application Data\IsolatedStorage

Windows XP, Windows Server 2003:
<SYSTEMDRIVE>\Documents and Settings\<user>\Application Data\IsolatedStorage

Programmatic access is (only check the existance of the file, other examples are available from the link provided at the end):
const string ISOLATED_FILE_NAME = "MyIsolatedFile.txt";

IsolatedStorageFile isoStore =
  IsolatedStorageFile.GetStore( IsolatedStorageScope.User
  | IsolatedStorageScope.Assembly, null, null );

string[] fileNames = isoStore.GetFileNames( ISOLATED_FILE_NAME );

foreach ( string file in fileNames )
{
    if ( file == ISOLATED_FILE_NAME )
    {
       Debug.WriteLine("The file already exists!");
    }
}

Extracted from:
http://www.codeproject.com/KB/dotnet/IsolatedStorage.aspx

A: I'm assuming since you've tagged the question WP7 you're looking for the file on a Windows Phone.
The only way to inspect the file at present is to read it via the SDK. You could do something like this for example.
var stream = isoStore.OpenFile("whateverpathyou.gaveit",FileMode.Open);
var reader = new StreamReader(stream);
var output = reader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(output);


text:
Q: Which versions of the Google Calendar API work with OAuth 2.0? Since AuthSub is no longer working reliably, and along with OAuth 1.0 has been deprecated by Google for API Access, it seems that we'll have to upgrade our applications to support OAuth 2.0.  My question is, do we have to upgrade to v3 of the Calendar API to use OAuth 2.0?  Or can we use the older calendar APIs, V1 and/or V2 with OAuth 2.0?  We're using the google Java client libraries.

A: I'd suggest going ahead and upgrading to Calendar v3 at the same time as OAuth 2.0 since you'll probably need to move to the newer Google API libraries rather than the old GData library anyways. However, from a protocol standpoint (not necessarily from a library standpoint), all versions of the Google Calendar API should work with OAuth 2.0 tokens.


text:
Q: How to access todos in another controller rails 4.2? I'm trying to learn RoR by creating an application, however, I have come across a problem and I'm not sure if my method is flawed or if it's the correct way to do it but I'm going about it slightly wrong. I think it has something to do with the variable being an instance variable and it's not called in my other controller but I'm not sure how to get it there?
Anyway the problem is -
I have a todos controller, models, views etc. set up via the scaffolding in Rails but I want to be able to display the todos to each user in their 'dashboard' so to speak when they log in. Therefore I assume I need the todos to be in the dashboard controller too, right?
Here's my dashboard controller
class DashboardController < ApplicationController
  def home
    @todos = current_user.todos
  end
end

Here I'm calling my todos but they aren't showing when I call them in the view.
and my todos scaffold
class TodosController < ApplicationController
  before_action :set_todo, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!

  # GET /todos
  # GET /todos.json
  def index
    @todos = current_user.todos
  end

  # GET /todos/1
  # GET /todos/1.json
  def show
  end

  # GET /todos/new
  def new
    @todo = Todo.new
  end

  # GET /todos/1/edit
  def edit
  end

  # POST /todos
  # POST /todos.json
  def create
    @todo = current_user.todos.new(todo_params)

    respond_to do |format|
      if @todo.save
        format.html { redirect_to @todo, notice: 'Todo was successfully created.' }
        format.json { render :show, status: :created, location: @todo }
      else
        format.html { render :new }
        format.json { render json: @todo.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /todos/1
  # PATCH/PUT /todos/1.json
  def update
    respond_to do |format|
      if @todo.update(todo_params)
        format.html { redirect_to @todo, notice: 'Todo was successfully updated.' }
        format.json { render :show, status: :ok, location: @todo }
      else
        format.html { render :edit }
        format.json { render json: @todo.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /todos/1
  # DELETE /todos/1.json
  def destroy
    @todo.destroy
    respond_to do |format|
      format.html { redirect_to todos_url, notice: 'Todo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_todo
      @todo = Todo.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def todo_params
      params.require(:todo).permit(:title, :item)
    end
end

How would I go about displaying my todo items in the dashboard?
Thanks for any help

A: You just need to add
before_action :authenticate_user!

to DashboardController like the way you have it in TodosController .

A: Do you have a current user in the dashboard controller? You will need to decide how to handle that - either require sign in, or use an if else statement e.g.
def home
  if current_user
    @todos = current_user.todos
  end
end


text:
Q: Includes is not a Function When Using it on Function Parameter I'm trying to convert times to minute. Whenever "X hours" is input it'd be converted to X hours in minutes. The function I'm using throws an error saying includes isn't a function. I've used includes in the same project so I'm not sure why I'm getting this error.

function calcTotalCook(prep, rest, cook) {
  //console.log(rest);

  if (prep.includes('hours')) {
    prep = prep.replace('hours', '');
    prep = Number(prep) * 60;
  }

  if (rest.includes('hours')) {
    rest = rest.replace('hours', '');
    rest = Number(rest) * 60;
  }

  if (cook.includes('hours')) {
    cook = cook.replace('hours', '');
    cook = Number(cook) * 60;
    console.log(cook);
  }

  document.getElementById('totalTime').innerText = Number(prep) + Number(rest) + Number(cook);
}

Prep Time:

  <input type="text" id="prepTime" name="prepTime" class="inputField" value="">

Rest Time:

  <input type="text" id="restTime" name="restTime" class="inputField" value="">

Cook Time:

  <input type="text" id="cookTime" name="cookTime" class="inputField" value="">

Total Time:

<input type="button" class="addButton" value="Calc" onclick="calcTotalCook(document.getElementById('prepTime').value, document.getElementById('restTime').value, document.getElementById('cookTime').value);">

A: I tested your code in Firefox and Chrome... all fine. IE11 is of course throwing the error. See compatibility for includes. If compatibility with IE is a concern, you should use indexOf() instead of includes.
So instead of if (prep.includes('hours')) you would be using if (prep.indexOf('hours') > -1).

A: You code snippet should work fine with modern day browsers except Internet Explorer. Check below image for supported browser.

Instead you can use indexOf method.


text:
Q: R: Draw arrows in ggplot2 based on loop I have a dataset as follows:
i <- data.scores
i
               NMDS1         NMDS2
Plot_1_O  -0.1716069847  -1.177471624
Plot_2_O  -0.2452065424  -0.978276228
Plot_3_O   0.3885298355  -0.578810975
   ...         ...            ...
Plot_64_O  0.7976712787  -0.187241724
Plot_1_N  -0.4044221768  -0.239157686
Plot_2_N   0.2539782304   0.197509348
Plot_3_N   0.3163483600  -0.130876763
   ...         ...            ...
Plot_64_N  0.6346501475   0.265873211

As you (may or may not) see, it's vegetational plot-data on 64 different plots, taken at several points in time (hence the "O"/"N" for "Old" and "New"). I've ran an NMDS via vegan's metaMDS() and got a plot showing my results. I've also calculated a fit via env_fit() and relevant environmental data. The finished plot is fine, but I wanted to add arrows between the pairs of old and new survey data. I used a loop to do so:
for (j in 1:64){
  k <- j+64
 arrows(data.scores$NMDS1[j], data.scores$NMDS2[j],
 data.scores$NMDS1[k], data.scores$NMDS2[k], length = 0.1, lwd=2)
}

The resulting plot looks like this: NMDS-Plot
The black symbols show the old plots, the red symbols the new ones respectively.
For better aesthetics I re-drew the plot in ggplot2, and everything worked perfectly fine, until I had to draw those arrows again. I cannot use a loop within the ggplot2-command, and I do not know how draw all of those arrows at once. I tried something like this:
 geom_segment(data=i, aes(x=i$NMDS1[1:64], xend=i$NMDS1[65:128],
 y=i$NMDS2[1:64], yend=i$NMDS2[65:128]),
 arrow = arrow(length = unit(0.5, "cm")), colour="red",
 inherit.aes=FALSE, lwd=2)

but it does not draw any arrows at all, not even a single one. Removing the column-specification does not help either, and I doubt I would get all the respective arrows at once. Can anybody help?

A: I found a solution: Based on my last line of code where I tried to draw the arrows geom_segment(data=i, aes(x=i$NMDS1[1:64], xend=i$NMDS1[65:128], y=i$NMDS2[1:64], yend=i$NMDS2[65:128]), arrow = arrow(length = unit(0.5, "cm")), colour="red", inherit.aes=FALSE, lwd=2) I saved the plot as an object called "Plot_Final" and tried this:
for (j in 1:64){ #j=1
  k <- j+64
  Plot_Final <- Plot_Final + geom_segment(data=i, x=i$NMDS1[j], xend=i$NMDS1[k], y=i$NMDS2[j], yend=i$NMDS2[k], arrow = arrow(length = unit(0.3, "cm")), colour="black", inherit.aes=FALSE, lwd=0.1)
}

By removing the aes()-argument I finally got my arrows pointing out the plot-pairs within my ggplot2-plot. Thank you anyway!


text:
Q: Use the result of the return of one function in another function I know there are several questions about this, I read but I could not understand. I'm trying to use the result of the return of one function in another:
def multiplication(a):
    c = a*a
    return c

def subtraction(c):
    d = c - 2
    return d

print(subtraction(c))

Output:

NameError: name 'c' is not defined

I know that there is a possibility of using global variables, but I have seen that this is not a good idea since the variables can change their value.
EDIT:
These two functions are just idiotic examples. I have two functions with words and I need to use the return of the first function in the second function. In case of this my idiotic example, I need the result of the first function (c) in the second function.

A: You are not calling your functions properly.
def multiplication(a):
    c = a*a
    return c

def subtraction(c):
    d = c - 2
    return d

# first store some value in a variable
a = 2

# then pass this variable to your multiplication function
# and store the return value
c = multiplication(a)

# then pass the returned value to your second function and print it
print(subtraction(c))

A: Does this makes things clearer?
def multiplication(a):
    c = a*a
    return c

def subtraction(c):
    d = c - 2
    return d

print(multiplication(5))               # 25
print(subtraction(5))                  #  3
print(multiplication(subtraction(5)))  #  9
print(subtraction(multiplication(5)))  # 23

I think you're trying to do what's happing in the last print statement: first call the multiplication function, and then call the subtraction function on the result.

Note that the variable c in your multiplication function is an entirely different variable from the c in your subtraction function. So much so, that it may make things more clear to rename your variables, perhaps something like this:
def multiplication(a):
    product = a * a
    return product

def subtraction(a):
    difference = a - 2
    return difference

A: So why not use return value?
print(subtraction(multiplication(24)))

?

A: 'c' is not declared outside the 'subtraction' function.
You need to give need to declare 'c' before printing.
Let's say you want 'c' to be 5, then:
c = 5
print(subtraction(c))

A: You have defined two functions which both return a number.
If you call subtraction(c) you will get the error you see, because there is no c.
If you define a c in scope of the print statmenet
c = 42
print(subtraction(c))

it will be ok.
Try thinking of it like this: each function takes a variable does things to it and returns a number.
e.g.
>>> multiplication(101)
10201

That this happened to be called c isnide the function isn't known outside the function (i.e scope).
You can save the number to a variable
>>> x = multiplication(101)

Then x remembers that value.
Or
>>> c = multiplication(101)

This is not the same c as you have inside the functions.

(And after the question edit):
Decide what value you want to call the first function with, for example 101:
>>> c = multiplication(101)

then use that return to call the next function:
>>>> subtraction(c)

Or just chain them togther:
subtraction( multiplication(101) )

To start the chain you will need to use a string, int or defined variable.
Otherwise you get name not defined errors.
Once a variable is used in a function it goes out of scope when the function ends.


text:
Q: Error in C++ with header file I am extremely new to C++ so please bear with me. I am following a tutorial to learn C++ and I am also using Eclipse as advised. I did exactly what was asked in creating the header file and putting my prototype in it. But I am getting this weird error when I build my project. I've inserted my code, header file and the error in my console below.
#include <iostream>

#include "utils.h"

using namespace std;

int main() {

    doSomething();
    doSomething();

    return 0;
}

void doSomething() {
    cout << "Hello" << endl;
}

Next is my header file which I named utils.h
#ifndef UTILS_H_
#define UTILS_H_

void doSomething();

#endif /* UTILS_H_ */

And this is what I am getting from my console. I am not sure what it means or how to fix this ...

**** Build of configuration Debug for project Headers_and_Prototypes ****
make all
make: *** No rule to make target 'main.o', needed by 'Headers_and_Prototypes'.  Stop.

A: As far as I know you have to make a .cpp file for your header, which in your case should only have #include "utils.h" and I think it should also have the void doSomething().

A: If my guess is right file name of the program including utils.h is main.cpp. When you are building, the compiler is trying to look for definition of doSomething in utils.h or utils.cpp and it not able to locate the it as the definition is in main.cpp instead.
The definition for the doSomething() should go into utils.cpp.

A: I am of same opinion with other two guys. Along with that, I would suggest not to create a make file project. This will hopefully help you to resolve the issue.
In summery
1)Create a blanck project
2) A header which contains.
a) The pre-processor definition and includes required.
b) The prototypes of the function with extern keyword.
c) Define any user defined data type in the header if required.
d) use #pragma once to include the header only once.
3)In cpp file provide the definition of all the function along with main.
Then first build the project and then run.


text:
Q: How can a #define from another headder file be used if the headderfile is not included? I'm currently working with FreeRTOS, and have noticed something, which i have not encountered before.
The file "projdefs.h" uses a define from the file "FreeRTOSConfig.h" without including "FreeRTOSConfig.h" without including it. "projdefs.h" does not include any other files for that matter.
How is this possible?
The case is shown below:
//projdefs.h

#ifndef pdMS_TO_TICKS
    #define pdMS_TO_TICKS( xTimeInMs )    ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000U ) )
#endif

//FreeRTOSConfig.h
#ifndef configTICK_RATE_HZ
#define configTICK_RATE_HZ (1000)
#endif

I've tried to google my way to the answer but nothing has been forthcoming.

A:
How can a #define from another header file be used if the header file is not included?

Candidate answers.

*

*Even though projdefs.h did not direclty include FreeRTOSConfig.h, projdefs.h did include some .h file that included FreeRTOSConfig.h.  Or maybe projdefs.h did include some .h file that included some .h file that include FreeRTOSConfig.h, etc.  (OP did assert: "projdefs.h" does not include any other files for that matter.")

*projdefs.h itself or included directly (or indirectly) something that defined configTICK_RATE_HZ and the assertion that FreeRTOSConfig.h was included is incorrect.

*configTICK_RATE_HZ was defined by the compiler.

Design tip:
It is often a chore to find where a define, object, function or constant was declared/defined.
I have found using a common prefix_ for them all inside "same_prefix.h" to ease this issue.

A:
How can a #define from another headder file be used if the headderfile is not included?

Macro definitions come from one of these sources:

*

*source files, including headers, read by the compiler

*compiler / standard library built-ins

*compiler command-line arguments

C compilers do not process source files unasked, so a macro definition will be processed from header.h only if the compiler has a reason to read header.h.  Usually, that reason is that the compiler processes an #include directive that directs it to the header.  A header can also be named directly as a file to compile, but this will put its contents into their own translation unit, so it's probably not what you're observing. Some compilers also provide a means to specify headers via the command line, such as GCC's -include option, which perhaps fits your definition of "not included".  Or not.
It can be the case that you get inclusion of the header in question via an obscure route, such as behind multiple levels of #include directives, or a reliance on prior #include directives to have been processed, or from an #include with a macro-generated header name, or via a symbolic-link-supported different name.
It's also possible to see a macro with the same name and replacement text that would be provided by inclusion of one header resulting from any of

*

*inclusion of a different header;

*direct definition via command-line argument; or

*as a compiler built-in,

and none of those are well characterized as being from a header that is not included, but they might give that impression.

As for ...

The file "projdefs.h" uses a define from the file "FreeRTOSConfig.h"
without including "FreeRTOSConfig.h" without including it.
"projdefs.h" does not include any other files for that matter.

... the fact that projdefs.h uses symbols that it does not define, neither directrly nor via including any other files, leads me to suppose that it simply is not a standalone header.  It depends on being #included only at a point where either

*

*the macro pdMS_TO_TICKS is already defined, or

*the macro configTICK_RATE_HZ is already defined, and the symbol TickType_t is defined either as a type designator or as a macro expanding to a type designator

A: In the beginning of FreeRTOS.h, you will notice:
/* Application specific configuration options. */
#include "FreeRTOSConfig.h"

/* Basic FreeRTOS definitions. */
#include "projdefs.h"

Also, pdMS_TO_TICKS() macro is not used by the kernel itself. FreeRTOS kernel always uses ticks. The macro is provided for users (we, application developers) only.

A: There are some good answers already posted, but just to add some details about the pre-processor and header files:
Everything in a header file gets expanded into each .c file that includes it. Formally a .c file and all .h files it includes form a translation unit. So .h files don't really have a life of their own, their contents are always "glued" into the .c file by the pre-processor.
This can lead to various strange or unintended side effects. For example your FreeRTOSConfig.h will be able to access everything from projdefs.h if both were included from the same .c file and FreeRTOSConfig.h was included first. Relying on this is very bad practice though, since it forces the user of the header files to include them in a certain order. Instead each .h file should include every other .h file that it needs.
And that's where the so-called "header guards" #ifndef MYHEADER_H #define MYHEADER_H ... #endif come in. Because if you don't have these in every .h file, your .c file may end up with multiple declarations/definitions of the same thing after expanding the headers. This is also why it is problematic to define variables or functions inside a header file - the user may end up with multiple definitions.
A little list of some good/idiomatic practices:

*

*Never force the caller to include header files in a certain order.

*A header file should include all other header files it uses.

*A header file should always contain header guards.

*Never declare variables in header files. The last resort is to declare them as extern but global variables are also bad practice.

*Avoid defining functions in header files. Some special cases like manual optimizations with static inline may be acceptable, but also as a last resort.

A:
The file "projdefs.h" uses a define from the file "FreeRTOSConfig.h" without including "FreeRTOSConfig.h" without including it. "projdefs.h" does not include any other files for that matter.

This is possible as well as you finally end in a compilation unit including both files.  If you don't include one of them, the undefined macros will expand as themselves.
This was historically used in the file <stdio.h> for some functions that were redefined as macros, to avoid a call to a function.  For example, if you
do #include <stdio.h> the macro putchar() was defined as:
#define putchar(c) fputc(c, stdout)

so in case you include the header, the call to putchar() is translated directly into a call to fputc() while if you didn't include it, a function that did the mapping was linked into the executable.
#include <stdio.h>
int putchar(int c)
{
    return fputc(c, stdout);
}

and you didn't note the difference.
This is still used in several ncurses library functions that use default screens in case you use the abbreviated form.  This results in a less overhead of function calls.


text:
Q: Is there a place you can download the install files for AutoCAD LT 2008 (or other old versions of software) I recently lost my installation CD for AutoCAD LT 2008
I think i may be able to recover my license info, so now i'm wondering if there is somewhere you can download the installer from?

A: You can download the latest LT version (2012 as of today), but not earlier versions.
You've got two options:

*

*Contact Autodesk support and ask for some way to get the AutoCAD LT 2008 installer files.

*Use a P2P or other file sharing method to download a copy of the installer, and use your license credentials.


text:
Q: Using Jquery to Select a class in Joomla 2.5 I am ripping my hair out as to why this isn't working.  I have a client on Joomla 2.5 and the template calls jQuery 1.8.  I'm simply trying to add a target="_blank" attribute to some links with a common class of .social-button  Here is my code:
$(document).ready(function() {
$(".social-button").attr('target','_blank');
});
}

Does anyone have any ideas?

A: Try this:
<script>
        window.onload = function()
        {
            $(".social-button").attr('target','_blank');
        };
</script>

A: I'm not sure where you're adding your code by try the following:
<?php
   $doc = JFactory::getDocument();
   $doc->addScriptDeclaration('
      jQuery(document).ready(function($) {
          $(".social-button").attr("target","_blank");
      });
   ');
?>

The above code uses Jooma API methods to inject your code in the <head> of your template.
I'm not sure how you're importing jQuery or if this is already being done. If you are importing jQuery yourself, then please read my answer on How to import jQuery in Joomla as it might be possible that you have multiple libraries being loaded and thus causing conflicts.
And finally on a side note, Joomla does, like any CMS out there have it's down side, but for an out-the-box CMS it's actually very good and extremely flexible. If you were to upgrade to 3.3.1, you will find even more features at the palm of your hand.


text:
Q: Prove true or false: for all rational numbers $x$, there exist unique integers $a$ and $b$ such that $x = a/b$. I must prove whether this is true or false. I think that it is false because when $b=0$, it does not hold true.
Suppose $x=a/b$. Let $x\in A$ and let $x\in B$. suppose $B=0$. Then for $x=a/0$, the answer is undefined. therefore, $x=a/b$ is not true.
I'm not sure if this is at all correct

A: You're thinking about it the wrong way.  It starts with "for all rational numbers $x$" so if you want to contradict it, pick a rational number $x$.  Say $x = \frac{1}{2}$.  There are integers $a = 1$, $b = 2$, such that $x = \frac{a}{b}$.  But are they unique?  In other words, is that the only pair of integers that satisfies the same equality?

A: Firstly, the definition of rational number from wiki is that, a rational number is any number that can be expressed as the quotient or fraction $p/q$ of two integers, a numerator p and a non-zero denominator $q$. So the key point is that if $p-q$ pair is unique.

*

*if $a=0$: for $a=1/2$, and $a = 2/4 = 3/6 = ... = (1*k)/(2*k)$

*if $a \neq0$: for $a=0/k$, $k$ can be any integer except 0.


text:
Q: mule mapping-exception-strategy only falls through to first 401 branch asking this for some mulesoft expertise.
the following exception mapping strategy is supposed to branch on hhtp.status 401, 403, 429 but keeps on falling into the 401 branch for status codes 401 and 403 (at least, and determined by both debugging and log written to console):
   <apikit:mapping-exception-strategy doc:name="waysact-adaptor-main-exception-strategy">
       <apikit:mapping statusCode="401">
           <apikit:exception value="org.mule.module.http.internal.request.ResponseValidatorException"/>
           <logger message="psc>>> logging 401 = #[payload]" level="INFO" doc:name="log-http-401"/>
       </apikit:mapping>
       <apikit:mapping statusCode="403">
           <apikit:exception value="org.mule.module.http.internal.request.ResponseValidatorException"/>
           <logger message="psc>>> logging 403 = #[payload]" level="INFO" doc:name="log-http-403"/>
       </apikit:mapping>
       <apikit:mapping statusCode="429">
           <apikit:exception value="org.mule.module.http.internal.request.ResponseValidatorException"/>
           <logger message="psc>>> logging 429 =  #[payload]" level="INFO" doc:name="log-http-429"/>
       </apikit:mapping>
       <apikit:mapping statusCode="400">
           <apikit:exception value="org.mule.module.http.internal.request.ResponseValidatorException"/>
           <logger message="psc>>> logging anything =  #[payload]" level="INFO" doc:name="logging-anything"/>
       </apikit:mapping>
   </apikit:mapping-exception-strategy>

is this because it is branching only on exception type org.mule.module.http.internal.request.ResponseValidatorException? i thought it was meant to branch on the status code?
there is another strategy, choice-exception-strategy, that should branch on different exception object types.

A: APIkit matches the exception based on the exception value defined and not by the statusCode defined. Use choice exception strategy and define multiple catch exception strategy in it. Make sure each catch exception strategy matches a unique exception to make the way for proper http.status code and desired exception payload.
For example, if you want to have 400 to be thrown, make sure a catch exception strategy matches BadrequestException. If the status codes are coming out of the HTTP requester, match the ResponseValidatorException and set the incoming http.status and exception payload

A: Branching of exception based on http.status can be defined with choice exception strategy as below example,
<choice-exception-strategy doc:name="Choice Exception Strategy">
    <catch-exception-strategy  when="#[message.inboundProperties.'http.status'=='404']" doc:name="Catch Exception Strategy" >
    <logger message="Exceptions message is ... #[exception.message]" level="ERROR"  doc:name="exceptionLogger"/>
    <set-variable variableName="exceptionMessage" value="#[exception.message]" doc:name="Set exceptionMessage"/>
    <set-payload value="{  errors: {     errorCode: #[message.inboundProperties.'http.status'],     errorMessage: #[flowVars.exceptionMessage]  }  }" doc:name="Set Exception Payload"/>
</catch-exception-strategy>
<catch-exception-strategy  doc:name="Catch Exception Strategy" >
    <logger message="Exception message is ... #[exception.message]" level="ERROR" category="com.project.stacktrace" doc:name="exceptionLogger"/>
    <set-variable variableName="exceptionMessage" value="#[exception.message]" doc:name="Set exceptionMessage"/>
    <set-payload value="{  errors: {     errorCode: #[message.inboundProperties.'http.status'],     errorMessage: #[flowVars.exceptionMessage]  }  }" doc:name="Set Exception Payload"/>
</catch-exception-strategy>
    </choice-exception-strategy>


text:
Q: Clear input's value once it's a jquery object Need to clear the value of a jQuery object. Standard method isn't working for me, figure I'm missing something.
HTML
<input class="file" type="file" />
JavaScript
var file = $input.find('input.file');

    /*blahblahblah stuff*/

    file.value = '';

A: With jQuery you have a method to set the value val(string) you also use this to get the value of the input ie don't pass a string...
file.val('');

See api docs http://api.jquery.com/val/#val2


text:
Q: Three.js - Camera collision with scene This is my first question in StackOverflow, but I've been browsing it for some years now, so I kindly ask you to bear with me. :)
I've been experimenting with Three.js to create a 3D world, and everything looked fine until I needed to control the camera. Since I'm using this lib to avoid having to do matricial calculations myself I found and added TrackballControls to my code aswell. It worked fine but then my camera could pass through the 3D shapes, and also below terrain. Unfortunately, although the movement is exactly what I needed, it didn't serve the purpose of allowing camera to respect collision.
My scene is simply the ground (thin BoxGeometry) and a cube (normal-sized BoxGeometry), and a rotating sphere that shares directionalLight position for a "sun light" effect. Some people here suggested adding Physijs to the code and simulate() physics within the scene, and adding a BoxMesh to the camera to make the physics apply to it aswell, but it simply didn't work (scene turned blank).
My working code so far (without Physijs) is:
window.onload = function() {
        var renderer, scene, camera, ground, box, sphere, ambient_light, sun_light, controls;
        var angle = 0;
        var clock = new THREE.Clock();

        init();
        render();

        function init(){
            // Create renderer and add it to the page
            renderer = new THREE.WebGLRenderer({ antialias: true });
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.setClearColor( 0xffffff );
            renderer.shadowMapEnabled = true;
            document.body.appendChild( renderer.domElement );

            // Create a scene to hold our awesome 3D world
            scene = new THREE.Scene();

            /*** 3D WORLD ***/
            // Objects

            ground = new THREE.Mesh(
                new THREE.BoxGeometry(50, 1, 50),
                new THREE.MeshLambertMaterial({ color: 0x33CC33 }),
                0 // mass
            );

            ground.receiveShadow = true;
            scene.add( ground );

            box = new THREE.Mesh(
                new THREE.BoxGeometry( 10, 10, 10 ),
                new THREE.MeshLambertMaterial({ color: 0xDD3344 })
            );

            box.position.y = 5;
            box.castShadow = true;

            scene.add( box );

            sphere = new THREE.Mesh(
                new THREE.SphereGeometry( 3, 32, 32 ),
                new THREE.MeshBasicMaterial({ color: 0xFFBB00 })
            );
            sphere.position.set( 1, 15.5, 5 );
            scene.add( sphere );

            // Light
            ambient_light = new THREE.AmbientLight( 0x333333 );
            ambient_light.mass = 0;
            scene.add( ambient_light );

            sun_light = new THREE.DirectionalLight( 0xBBBBBB );
            sun_light.position.set( 1, 15.5, 5 );
            sun_light.castShadow = true;

            sun_light.shadowCameraNear = 1;
            sun_light.shadowCameraFar = 100;

            sun_light.shadowCameraLeft = -50;
            sun_light.shadowCameraRight = 50;
            sun_light.shadowCameraTop = -50;
            sun_light.shadowCameraBottom = 50;

            sun_light.shadowBias = -.01;

            scene.add( sun_light );

            // Create a camera
            camera = new THREE.PerspectiveCamera(
                45,                                     // FOV
                window.innerWidth / window.innerHeight, // Aspect Ratio
                1,                                      // Near plane
                1000                                    // Far plane
            );
            camera.position.set( 30, 30, 30 ); // Position camera
            camera.lookAt( box.position ); // Look at the scene origin

            scene.add(camera);

            // After swapping THREE.Mesh to Physijs.BoxMesh, this is where I'd attach a BoxMesh to the camera

            window.addEventListener( 'resize', onWindowResize, false );

            controls = new THREE.TrackballControls( camera );
            controls.rotateSpeed = 4.0;
            controls.panSpeed = 0.3;
            controls.staticMoving = true; // No sliding after-effects

        }

        function render() {
            // use requestAnimationFrame to create a render loop
            angle += .007;
            var oscillateZ = Math.sin(angle * (Math.PI*4));
            var oscillateX = -Math.cos(angle * (Math.PI*4));
            //console.log(oscillateZ);
            sphere.position.setZ( sphere.position.z + oscillateZ );
            sphere.position.setX( sphere.position.x + oscillateX );
            sun_light.position.setZ( sun_light.position.z + oscillateZ );
            sun_light.position.setX( sun_light.position.x + oscillateX );

            requestAnimationFrame( render );
            controls.update();

            renderer.render( scene, camera );
        }

        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();

            renderer.setSize( window.innerWidth, window.innerHeight );
        }
    };

Can you guys enlighten me? Thank you for your time!
@Edit
Physijs attempt


text:
Q: Taking 2 separated Data and insert in SQL database This is a bit complicated but i managed to get this far until now.
http://medieproduktion.mediacollege.dk:10279/Game1/
If you go this site, the first your will be asked is so fill out Navn:(name), Email(email) and select your college.
you can do it since it is all working so please try it.
When you hit the "Start spillet" ( start the game) button then the data you just entered is inserted into my sql database. That works also.
Then you are redirected to the game as you can see. (use crome or firefox) IE dont work with the game. as soon as you click "start spillet" you will noticed at the top the counter is start to go down. and here comes the tricky part.
I want it to add the time used ( 120 sec - "remaining time" ) to the current datainput the user just typed in.
Here is teh Code for the counter :
var timeLeft = 120;
function decrementCounter() {
if (timeLeft > 0) {
    document.all('counter').innerHTML = "Tid tilbage " + timeLeft + "...";
    timeLeft--;
    setTimeout("decrementCounter()", 1000);
    document.getElementById("start_button").style.display = 'none';
    document.getElementById("blackout").style.display = 'none';
}
else {
    window.location = "Failed.aspx";
     }
}

I will provide you with the entire solution if you want.
as i said, everything is working except i dont know how to add the time into the database at the current users.

A: Pm for the correct answer I think you would apricate it alot ; )!


text:
Q: Stopping position:fixed div at certain point (before footer starts) The problem has been discussed on the forum a few times however I cannot make it work so I ask for help.
I have a side contact menu (as a widget) in my WP website and made it position: fixed so it doesn't change position during scrolling. However, I want it to stop being fixed before it hits footer div because it just looks weird.
As far as I read I need jquery and a script that changes my fixed position to a relative at some point so I feel like I understand the basic mechanic of it and even found several scripts but all of them doesn't work at all.
I want something exactly like in here:
Stop fixed position at certain div or certain position
I created 3 files: html, css, js and put all the codes from the answer and it just does not work at all..
My js file - java.js
jQuery(document).ready(function() {

var navTop = $('#nav').offset().top;
var navStop = $('#stop').offset().top;
var lastMode = "absolute";

$(window).scroll(function() {
  var mode;
  if ($(this).scrollTop() >= navTop) {
    if ($(this).scrollTop() - navStop + $('#nav').height() > 0)
      mode = 'absolute';
    else
      mode = 'fixed';
  } else {
    mode = 'absolute';
  }

  if (lastMode !== mode) {
    if (mode == 'fixed') {
      $('#nav').css('position', 'fixed');
      $('#nav').css('top', '0');
    } else {
      $('#nav').css('position', 'absolute');
      $('#nav').css('top', navTop);
    }
    lastMode = mode;
  }
});

}

My css file- style.css:
#nav {
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 200px;
  width: 100px;
  height: 50px;
}

#stop {
  width: 100%;
  background: blue;
  height: 300px;
  position: absolute;
  top: 900px;
  margin-top: 20px;
}

My html doc - index.html
<link rel="stylesheet" type="text/css" href="style.css">

Since the code above is just an answer from another topic - I wanted to change it for my needs but it seems I do something wrong because it does not work.
To detail: I want side contact menu
 to start normally like it is right now (position fixed) and stop it from being fixed when it hits

I am fine using html/css however I do not understand js and I feel my problem is quite easy to solve.
Could you help?

A: https://jsfiddle.net/42muhgj3/1/
$(window).scroll(function() {
  const pos = Math.max(5, 200 - $(this).scrollTop());
  // maximum 200, minimum 5, according to scrollTop
  $('#nav').css('top', pos + 'px');
  console.log(pos);
});

css
#nav {
  background: rgba(0, 0, 0, 0.5);
  position: sticky;
  top: 200px;
  width: 100px;
  height: 50px;
}

A: Your code works. You just missed out a ")" at the end of your javascript file. So completing your JS file it should be:
jQuery(document).ready(function() {

var navTop = $('#nav').offset().top;
var navStop = $('#stop').offset().top;
var lastMode = "absolute";

$(window).scroll(function() {
  var mode;
  if ($(this).scrollTop() >= navTop) {
    if ($(this).scrollTop() - navStop + $('#nav').height() > 0)
      mode = 'absolute';
    else
      mode = 'fixed';
  } else {
    mode = 'absolute';
  }

  if (lastMode !== mode) {
    if (mode == 'fixed') {
      $('#nav').css('position', 'fixed');
      $('#nav').css('top', '0');
    } else {
      $('#nav').css('position', 'absolute');
      $('#nav').css('top', navTop);
    }
    lastMode = mode;
  }
});

})

Here I say this is "Solved"


text:
Q: How to $.extend objects with sub-objects in jquery? I know i can use $.extend({}, x); to merge the contents of two or more objects together into the first object, but my answer is, and the sub-objects? They will only be overwritten? I can't merge then?
I have this:
var settings = $.extend({
    modal: {
        title: "Atention",
        type: "text",
        width: "small"
    },
    ajax: {
        type: "normal",
        trigger: "",
        url: ""
    }
}, {
    modal: {
        title: "Registrar",
        type: "register"
    },
    ajax: {
        trigger: ".bumbum",
        url: "modal/lets/go"
    }
});

This jQuery function will return this:
var setting = {
    modal: {
        title: "Registrar",
        type: "register"
    },
    ajax: {
        trigger: ".bumbum",
        url: "modal/lets/go"
    }
};

And unfortunately I need it:
var setting = {
    ajax: {
        type: "normal",
        trigger: ".bumbum",
        url: "modal/lets/go"
    },
    modal: {
        title: "Registrar",
        type: "register",
        width: "small"
    }
};

Any idea? Thank you.

A: For deep nesting try, $.extend(true, {}, x);. For deep nesting the format is:
jQuery.extend( [ deep ], target, object1 [, objectN ] );


text:
Q: SharePoint Online JSON Column Formatting, if colum text is empty I'm a big beginner with Json. Literally less than an hours experience.
I have a microsoft form that poulates a list within a SharePoint site, via a flow. I want to format a few of the colums so that if they have been left empty within the form, the text displayed will be 'N/A'.
Before anyone suggests it, I have tried setting the colums default value, but as the flow populates each row with whatever is in the microsoft form, it overwrites the default value with empty string.
Could there be another way to do this? An if statement within the flow maybe? Any help appreciated.

A: You could try the below code in JSON formatting:
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "=if(@currentField=='','N/A',@currentField)"
}

Test result:


text:
Q: How play lottie animation in MVVM using Command? This is my content page and i need to play the lottie animation using command in my MVVM
how do i achieve this? Please help me
MainPage.xaml
<lottie:AnimationView
AnimationSource="AssetOrBundle"
Animation="Animation.json"
AutoPlay="False"
Command="{Binding Command}"
x:Name="MyAnimation"/>

This is my ViewModel Example how can i play the lottie animation using command, I cant use the click because the lottie animation is inside of my CollectionView.
MyViewModel.cs
public class MyViewModel : BindableObject
{
    public MyViewModel()
    {
         Command = new Command(ExecuteCommand);
    }

    public ICommand Command { get; set; }

    private void ExecuteCommand()
    {
        // How do i play the animation?
        // MyAnimation.PlayAnimation();
    }
}

Im creating animation button that will fire when you like the post in collection view for example