text:
Q: MediaStream Desktop Capture with Web Camera Overlay I am currently trying to build a WebRTC-based application using MediaStream to capture the computer screen and save it to a video file. I have it working, BUT, now I am trying to add an additional layer to the recorded video so that the Web Camera appears.
As far as I understand, with the Media Streams API, I cant use two Video sources at the same time. So I decided to draw the captured video to a Canvas element and layer the Web Camera on that, and get the stream from the Canvas. But I am having issues and can't get it working
What I am trying to build is something like what Loom has, with the desktop capture and the web camera layered on-top in a circle.
I would like to know if I am heading in the right direction If you were to build something like this, how would you approach it?

A: If you can, the best is probably to stream two MediaStreams: one for the camera, and an other for the screencast.
Then it's just css overlaying of two <video> elements.
Of course you could also do the compositing on the emitter side, by drawing both videos to an HTMLCanvasElement and then streaming a MediaStream generated from this canvas using its captureStream method, but I guess it would end up being more inefficient than the two streams option, and canvas streams quality is generally quite bad...


text:
Q: Write-read errors, Raid1 recovery? This might sound stupid, but I'm supposed to ask any question here, as long as it is related.
So here. I have RAID 1 on the server that is officially soon to be dead. After a chkdsk, the files are corrupting on a more regular basis, and things are looking pretty apocalyptic from my terrified pessimistic oh-my-god-we're-all-gonna-die standpoint.
I'm unable to read files on the server, notably everything that was done this morning by a coworker was lost.
Okay, context apart, I want to see if the alternate drive is working any better than the master one, so here are my questions:
How do I know which one is the master, and which one is the slave, how do I determine which one is faulty?
When that is determined, what do I do? Can I just pull the other drive away? I tried doing so (taking appropriate precautions as to not kill any other hardware), but I got a "broken raid detected, enter setup?" message at boot.
Do I need to insert another drive before I can get the data?
Is trying to boot using a live ubuntu disk a good way to try to save some data?
I'm trying my best not to panic, here, but when my boss finally understood what I meant by "We're going to be in deep shit real soon", it was already close to the expected depht, and "soon" was less than a week's time apart from that moment. Oy vey...
UPDATED:
I tried the SeaTools, as suggested below, and both drives failed the long generic test. On a scale from one to infinity, how much poop am I exactly into now?
Say I really, REALLY need to have the data back, how much money will my boss have to give away to do so? Is it even possible? I mean, I stopped believing in Santa a while back...

A: You need to remove each hard drive, and test them with a tool like Seatools seperately.
http://www.seagate.com/www/en-us/support/downloads/seatools
One of the disks is likely going bad, but with RAID1, there is no way for the computer to know for certain which disk has good data on it, and which disk has bad data on it.  If you're very unlucky, both disks will be going bad, but more than likely, it's just one of them.
In a RAID 1 configuration, there is no Master/Slave, the two disks become one, and everything is controlled via the Raid Controller.  Because of this, you'll likely want to test the drives in a different machine.  Also, if the tests come back with one disk bad, all you need to do is remove the old drive, and get a replacement soon.  If you have RAID1, then the computer will run with only 1 drive.

A: In theory you should be able to just pop out a drive on a mirrored array while the system is running, and it should keep running fine.  I actually did this once (by accident I hasten to add) and there were no ill effects (aside from missing one of the mirrored pair, of course).
Very very risky on a live system though, so my recommendation here is to get a replacement in place NOW, and get as much data as possible transferred over to it, with the old server then being taken offline.  The worst you can do is wait until it fails before taking action.
Having done that you will have established a position where most of your stuff is up and running and available to users.  So then - and only then - you can start experimenting with the old box and seeing how much of the rest you can get back.
My suggestion of popping the drive is one way - pop a drive while running and check the data.  If you get corruptions you know that the other one is good, if you don't you know that this one is good.
I would definitely not do anything that involved reboots of that system as the whole thing could fail to come back up at any point.  If you've ever been in that position you know how unpleasant it is.

A: Is it a hardware RAID controller? Most have a utility that you can use to check the health of your disks and which one may be degraded. The manufacturer will also provide a recommended procedure to replace the degraded drive and to rebuild the mirror.
Cheers

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the use case of IOptions versus IConfiguration (other than IOptions allows mapping to object)? I can inject the IConfiguration config into constructor and then access the app settings from json file via config["settignName"];
Example code inside service class:
public MyService(IConfiguration config)
        {
            _key = config["MyKey"];
        }

I came across IOptions which allows to map app settings from json file to a .net object.
Example:
public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<MySettings>(Configuration.GetSection("MySettings"));
...
}

And then inject the IOption into the constructor.
What is the use case of IOptions versus IConfiguration (other than IOptions allows mapping to object)? I don't see IConfiguration being used in online examples so is that OK to be used or should I switch to IOption?

A: As explained in documentation sometimes you prefer to split your settings by groups or scenarios, this is really easy with IOptions.
services.Configure<AppSettings1>(configuration.GetSection("AppSettings1"));
services.Configure<AppSettings2>(configuration.GetSection("AppSettings2"));

And then you can specify in your class constructor which one you need. You can have something similar with IConfiguration but you need write more code.
Other reason, I prefer access to the configs values using properties rather than using indexes. If I need to update a config key it will more painful  using indexes.

A: Don't inject the whole IConfiguration interface into your service.
Injecting a class, say SmtpOptions, instead of injecting IConfiguration is a better design approach. When you inject IConfiguration, it implies that the client class (your service) will need to understand how the configuration file is structured and it will access some configuration using a key like this "Smtp:Host". So, it creates tight coupling between the client code and the configuration structure. Consequently, if the configuration file changes, you will have to change every client class.
Using IOptions (or other approaches) decouples the client class from the configuration. For example, if you decide to read the configuration from the database instead of a file, you will have only to change one piece of code which is responsible for reading and understanding the configuration file.  This is much better than changing all classes that depend on IConfiguration. It is a maintenance nightmare.
Decoupling reduces applications' complexity and makes them much more maintainable.
Check this toturial https://www.youtube.com/watch?v=SizJCLcjbOA


text:
Q: PHP Warning: print_r and debug_backtrace when passing a mysqli connection I have a very complicated system which was opening and closing MySQLi connections every time it wanted to perform a query - of which it was doing about 40,000 of per given operation (inefficient, I know).  I decided to pass the mysqli connection between functions, to prevent this open-and-close-repeatedly inefficiency.
My problem is: when a query fails I wanted to email myself the debug_backtrace(), formatted in an easy-to-read format (so I wrap it in print_r()).  For some reason, I'm now getting a PHP warning that says print_r(): Property access is not allowed yet in... on line XXX where line XXX simply reads addNotification("Backtrace: ".print_r(debug_backtrace(), true), "debug");
Is there some reason that print_r() doesn't like debug_backtrace() when one of the passed parameters in the backtrace is an mysqli_connect object?  Does the mysqli_connect lack a toString function?
EDIT After a little more research I've found that you CAN call print_r or var_dump on a mysqli_connect object, but if that object is mysqli_closed it causes this warning.  If it is closed and unset it is okay.

A: See the example here.
http://php.net/manual/en/function.debug-backtrace.php
it's using var_dump instead of print_r
my personal favorite is var_export, because it creates php readable format.


text:
Q: Workbook_NewSheet Excel VBA Error MEssage I have added code to my Excel ThisWorkbook in an attempt to add a worksheet_change code to each sheet that is created in my Excel workbook. I run the code and get the following error message: Compile error: Method or data member not found.
Does anyone knwo what this could be?
  Private Sub Workbook_NewSheet(ByVal Sh As Object)
    Dim ws As Worksheet
    Set ws = Sh

    ' Add Worksheet_Change event to new sheet
    Dim code As String
    code = "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf & _
           "    If Not (Application.Intersect(Range(""A1:E19""), Target) Is Nothing) Then" & vbCrLf & _
           "        MsgBox ""Cell "" & Target.Address & "" has changed."", vbInformation, ""Test""" & vbCrLf & _
           "    End If" & vbCrLf & _
           "End Sub"

    With ws.CodeModule
        .InsertLines 2, code
    End With
End Sub

A: Your code works with a small fix:
Private Sub Workbook_NewSheet(ByVal Sh As Object)
    Dim ws As Worksheet
    Set ws = Sh

    ' Add Worksheet_Change event to new sheet
    Dim code As String
    code = "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf & _
           "    If Not (Application.Intersect(Range(""A1:E19""), Target) Is Nothing) Then" & vbCrLf & _
           "        MsgBox ""Cell "" & Target.Address & "" has changed."", vbInformation, ""Test""" & vbCrLf & _
           "    End If" & vbCrLf & _
           "End Sub"

    With ThisWorkbook.VBProject.VBComponents(Sh.CodeName).CodeModule
        .InsertLines 2, code
    End With
End Sub


text:
Q: Support Website for My iOS App, any suggestions? I'm getting ready to set up a website for my support URL for the app before I submit to the App Store. I was thinking I'll probably just do a WordPress site. Any thoughts or suggestions? I'd love to get some links to some good themes, on the cheap.

A: You could set up a simple static page on github, if you're using that to host your source (or even if not): http://pages.github.com/

A: There's a lot of WordPress themes out there for app websites. Here's one I ran across a while back: http://www.appdesignvault.com/darstell-iphone-wordpress-theme/.
It's free if you tweet about them! Am considering using this for my app, or using it as a starting point for my own wordpress theme.
This is a brief review of some paid themes. Most are inexpensive. (note: website seems to load slow)

*

*http://www.devlounge.net/design/6-wordpress-themes-for-iphone-apps/
Here's some others. I haven't looked into them much though.

*

*http://www.apptamin.com/app-websites/

*http://www.elegantthemes.com/gallery/myapp/

*http://templatic.com/cms-themes/iphone-app/
Good luck!

A: I'm hosting a static site on Heroku for Railscasts for iOS. It's free and barely requires any maintenance.


text:
Q: php mysqli inserting duplicate value I created a website where you insert radio button data to the database after you click submit button.
However, the problem is that whenever I click the submit button it inserts two duplicate values instead of one.
My code is the following:
<form action="test.php" method ="post" >
<b> what is you fav sport ؟ </b>
</br>
<input type="radio" name="sport1" value="football"> football
<input type="radio" name="sport1" value="basketball"> football
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
    die("Connection failed: " . $conn->connect_error);
}
mysqli_query($conn, "set names 'utf8'");
?>
<input type="submit" name="submit" value="submit"/>

<?php
if(isset($_POST['submit'])  && !empty($_POST)){
    $sport1 = $_POST['sport1'];
    $SQL = "INSERT INTO userTable (user_q1) VALUES ('$sport1')";
    $result = mysqli_query($conn, $SQL);
    if ($conn->query($SQL) === TRUE) {
        echo "New record created successfully";
    }else{
        echo "Error: " . $SQL . "<br>" . $conn->error;
    }
    $conn->close();
}
?>
</form>

Any help would be be appreciated.

A: you are doing the same thing twice
Just use either
$result = mysqli_query($conn, $SQL)
//or
$conn->query($SQL)

mysqli_query and $conn->query() are used fro same purpose.
just remove any one of the statement, you will get what you need


text:
Q: The document element is not available Sometimes I get error:
java.lang.IllegalStateException: The document element is not available.
when doing a findElements call on the Document. Is there a way to test if the document element is available rather than catching the exception.

A: You can check whether document element exists or not using the following code:
DOMDocument document = browser.getDocument();
DOMElement documentElement = document.getDocumentElement();
if (documentElement != null) {
    DOMElement element = documentElement.findElement(By.className("name"));
}

In general, the following code is doing the same thing, but throws exception if documentElement is null:
DOMDocument document = browser.getDocument();
DOMElement element = document.findElement(By.className("name"));


text:
Q: Renaming a variable in a loop in R I'm trying to rename several variables by attaching a string from a loop:
df <- data.frame(net_low_mptc=1:3,   net_medium_mptc=4:6, net_high_mptc=7:9)
x<-c("low","medium","high")

for(lvl in x) {
rename(df, c(sprintf("net_%s_mptc", lvl) = sprintf("bill_%s_F", lvl))) }

The error is caused by the sprintf expression:
Error: unexpected '=' in:
"for(lvl in x) {
rename(df, c(sprintf("net_%s_mptc", lvl) ="

A: Edit:
colnames(df) <- sub("net_", "bill_", colnames(df))
colnames(df) <- sub("_mptc", "_F", colnames(df))

colnames(df)
# [1] "bill_low_F"    "bill_medium_F" "bill_high_F"

I am guessing here, maybe try this:
x <- c("low", "medium", "high")
colnames(df_1)[colnames(df_1) %in% paste0("bill_no_net_tdcv_", x)] <-
  paste0("bill_tdcv_", x, "_F")

You might be better off with regex solution, please provide your data.

A: I'm guessing this is what he/she is trying to do:
library(plyr)

x <- c("low","medium","high")

for(lvl in x) {
  df_1 <- rename(df_1, setNames(sprintf("bill_tdcv_%s_F", lvl), sprintf("bill_no_net_tdcv_%s", lvl)))
}


text:
Q: Factorization of a matrix into two linear terms On page 150 of Richter-Gebert's Perspectives on Projective Geometry, the author mentions that if a conic in $\mathbb{R}\text{P}^2$ of matrix $A$ contains a line of homogeneous coordinates $l$, then the matrix $A$ must necessarily factor into two linear terms $A=l \cdot g^T$ for a suitable vector $g$. Why is that so?
My thought process goes as follows: if the conic contains a whole line, that means that the matrix of that conic is at most of rank 3-1=2. Does that imply directly the result, and if so, how?
The converse is obvious.

A: It looks like you're conflating the matrix $A$ with its associated quadratic form $\mathcal Q_A(p)$. What Richter-Gebert writes is that when the quadratic form $\mathcal Q_A(p)$ factors into linear terms, it can be written as $\mathcal Q_{lg^T}(p)$ for suitable vectors $l$ and $g$, i.e., that $p^Tlg^Tp = p^TAp$ for all $p$. This, however, does not imply that $A=lg^T$: the matrix on the right-hand side has rank one, but $A$ could have rank two. Moreover, when dealing with conics $A$ is usually symmetric, but $lg^T$ generally isn't.
For example, $$A = \begin{bmatrix}1&0&1\\0&-1&0\\1&0&1\end{bmatrix}$$ is a symmetric rank-two matrix that generates the quadratic form $$\begin{align} \mathcal Q_A(p) &= p_1^2-p_2^2+p_3^2+2p_1p_3 \\ &= (p_1+p_2+p_3)(p_1-p_2+p_3) \\ &= p^T\begin{bmatrix}1\\1\\1\end{bmatrix} \begin{bmatrix}1&-1&1\end{bmatrix}p.\end{align}$$ All of the columns of $lg^T$ are scalar multiples of $l$. With $l=(1,1,1)^T$, as shown, no scalar multiple of it can equal any column of $A$. Using the other linear term instead so that $l=(1,-1,1)^T$ doesn't improve the situation. Note, however, that the symmetric part of $lg^T$, namely, $\frac12(lg^T+gl^T)$ does equal $A$ here. This is to be expected, since only the symmetric part of a matrix contributes to its associated quadratic form.
This factorization is the key to the method described later in the book for splitting a degenerate conic. The author develops an algorithm for finding a skew-symmetric matrix $M$ such that $A+M=lg^T$.


text:
Q: How to enable debug mode for firebase analytics events in Unity android project? In firebase documentation, only this paragraph describes how to turn on debug mode for events,

"To enable Analytics Debug mode on an Android device, execute the following commands:
  adb shell setprop debug.firebase.analytics.app package_name"

however, I think that you can do it only in android studio.
How to turn on debug mode for firebase events in my Unity project?

A: To wrap this all up in an answer. Using the Firebase SDK, you can execute adb shell setprop debug.firebase.analytics.app package_name to enable debug mode. Adb is a the "Android Debug Bridge", which exists on your machine if you're able to load games onto a phone (either via Android Studio or via Unity).
For finding your SDK location and setting your path, it depends on the host OS and shell you're running as well as how you've installed the Android SDK. Therefore, I'll try to give OS agnostic instructions for if you selected to install the Android SDK that ships in Unity 2019 (specifically 2019.2.3f1 as installed by Unity Hub).
In this case, the path to ADB is {Unity_Installation_Directory}/PlaybackEngines/AndroidPlayer/SDK/platform-tools/adb. So the command without messing with my path or cd'ing to a weird directory would be: /Applications/Unity/Hub/Editor/2019.2.3f1/PlaybackEngines/AndroidPlayer/SDK/platform-tools/adb shell setprop debug.firebase.analytics.app package_name
Now, I have Android Studio installed and I use my .profile file to set my path on OSX (I use the fish shell, so this is a little tricky). To make that version of ADB accessible as a command as indicated by the instructions page, I have this towards the end of the file:
# Add environment variable NDK_ROOT
export NDK_ROOT="/Users/username/Library/Android/sdk/ndk-bundle"
export ANDROID_SDK_ROOT="/Users/username/Library/Android/sdk"
export PATH=$NDK_ROOT:$PATH

But this is specific enough that I posted the general solution first.
Hope this helps!
--Patrick


text:
Q: Performance Issue with SQL Server 2008 R2 64 Bit I have a SQL Server 2008 R2 which is 64 bit. Recently I have been observing that there is a huge performance issue in the server. The physical capacity of the server is 28GB. This server is the data warehouse and contains tables having records more than 4 Million.
Whenever a job runs , the memory consumption goes to 98% and the execution rate is extremely slow reaching one record per minute.The job is run through SSIS package.
I want to know what is causing the issue and any help on this


text:
Q: Exponential decay estimate for $(x,t) \in U_T$
Suppose $u$ is a smooth solution of
  $$\begin{cases}u_t - \Delta u + cu = 0 & \text{in }U \times (0,\infty) \\ \qquad \qquad \quad  \, \,u=0 & \text{on } \partial U \times [0,\infty) \\\qquad \qquad \quad  \, \, u=g & \text{on }U \times \{t=0\} \end{cases}$$ and the function $c$ satisfies $c \ge \gamma > 0$. Prove the exponential decay estimate $$|u(x,t)| \le Ce^{-\gamma t} \quad ((x,t) \in U_T).$$

This is from PDE Evans, 2nd edition: Chapter 7, Exercise 7.
Here is what I have worked on so far:
Let $v=e^{ct}u$. Then $v_t=e^{ct}u_t+ce^{ct}u$ and $\Delta v = e^{ct} \Delta u$. So our IBVP becomes $$\begin{cases}v_t - \Delta v = 0 & \text{in }U \times(0,\infty) \\ \qquad \quad v = 0 & \text{on } \partial U \times [0,\infty) \\ \qquad \quad v = e^{ct} g  &\text{on } U \times \{t=0\}. \end{cases}$$
The following convolution is a solution (see page 41 of textbook) to this auxiliary PDE: Edit: This convolution does not work; it does not satisfy the boundary conditions prescribed by the auxiliary IBVP. So the remainder of this solution does not follow.
$$v(x,t)=\frac 1{(4\pi t)^{\frac n2}} \int_U e^{-\frac{|x-y|^2}{4t}} [e^{ct} g(y)] \, dy,$$ which means in turn $$u(x,t)=e^{-ct} v(x,t)= \frac 1{(4\pi t)^{\frac n2}} \int_U e^{-\frac{|x-y|^2}{4t}} g(y) \, dy. \tag{$*$}$$
This is where I got stuck, because the $e^{-ct}$ factor is now gone. In an earlier attempt of this problem, I overlooked the $e^{ct}$ in the $e^{ct}g(y)$ part of the convolution, so I originally had this: $$u(x,t)=e^{-ct} \frac 1{(4\pi t)^{\frac n2}} \int_U e^{-\frac{|x-y|^2}{4t}} g(y) \, dy. \tag{$**$}$$
I was able to continue on from that point (while using that $g$ has compact support, so $|g(y)| \le M$):
\begin{align}
|u(x,t)|&\le e^{-ct} \frac 1{(4\pi t)^{\frac n2}} \int_U e^{-\frac{|x-y|^2}{4t}} |g(y)| \, dy \\
&\le Me^{-ct} \frac 1{(4\pi t)^{\frac n2}} \int_U e^{-\frac{|x-y|^2}{4t}} \, dy \\
&\le Me^{-ct} \cdot N \\
&= Ce^{-ct} \\
&\le Ce^{-\gamma t}.
\end{align}
My question is: Why am I getting stuck at $(*)$? I should arrive at $(**)$ instead, which would enable me to finish the proof.

A: I don't know if your approach could be made to work, but in my opinion you're going the wrong way. First of all, since $c=c(x,t)$, you can't just ignore the factor $e^{ct}$ when taking the laplacian of $v$. Moreover, the convolution integral will, in general, not be a solution of your problem: If $g>0$ then the convolution integral defines a strictly positive function on $\mathbb{R}^n$; in particular it can't satisfy the boundary conditions.
What you want to try is the maximum principle: Set $v=e^{\gamma t}u$, then $v_t-\Delta u =(\gamma-c)v$. Since $\gamma-c<0$ we can apply the maximum principle to get, for $(x,t)\in U_T$,
$$
-\max_{U}g^-=-\max_{\Gamma_T}v^-\leq \min_{U_T} v \leq \sup_{U_T} v =\sup_{\Gamma_T} v^+ = \sup_U g^+.
$$
This implies the desired inequality with $C\leq \sup_U |g|$.


text:
Q: Cannot access Jenkins parameters from a templatized pipeline argument I cannot access to any Jenkins parameter (ex: A as below) from the scope of myPipelineTemplate.
From the Jenkinsfile file:
library 'myPipelineTemplate'

properties([
    parameters([
        booleanParam(name: 'A', defaultValue: false, description: '')
    ])
])

myPipelineTemplate {
    arg1 = A
    arg2 = true
}

From the pipeline template:
def call(body) {
    def args = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = args
    body()

    echo "$args.arg1" // return (null)
    echo "$args.arg2" // return (true)

    pipeline {
        ...
    }

Any lead ?
EDIT: Jenkins ver. 2.107.1

A: You are using Closure.DELEGATE_FIRST strategy and the delegate is a Map. Your arg2 = true assigns the property, but the A property lookup is a key lookup on that map which is why the assignment is null. The A property lookup is never done on the owner context which would eventually delegate to params.A.
With your delegation strategy, the invocation sort of looks like this:
delegate.arg1 = delegate.A
delegate.arg2 = true

where delegate is the def args = [:]. The delegate in this case handles the property lookup. The value is null and then it is assigned to delegate.arg1. Your map after the call is [arg1:null, arg2:true]. If you change it to params.A, it would be like delegate.params.A which will fail with a NullPointerException because delegate.params is null.
To make sure the call is resolved to the owner, you could instead use this.params (see this question/answer for meaning of this in a Closure):
myPipelineTemplate {
    arg1 = this.params.A
    arg2 = true
}

You could also change the resolution strategy:
body.resolveStrategy = Closure.OWNER_FIRST

delegate.arg1 = A
delegate.arg2 = true

I would recommend just changing your call method from a Closure parameter to. any of:

*

*Map

*Domain specific object for your pipeline

*Multiple arguments

For example, for Map:
def call(Map args) {
  // ...
}

myPipelineTemplate([
    arg1: params.A
    arg2: true
])

A: Workaround:
properties([
    parameters([
        booleanParam(name: 'A', defaultValue: false, description: '')
    ])
])

def params = params

myPipelineTemplate {
    arg1 = A
    arg2 = true
}


text:
Q: What is the total number of distinct $m\times n$ matrices in row canonical form using only $0$s and $1$s? Suppose that $A$ is an $m \times n$ matrix over a field $F$. What is the total number $N$ of the distinct matrices in row-reduced echelon form that are row equivalent to $A$ and that only have entires either $0$s or $1$s?
I know that this number $N$ is $5$ if $A$ is $2 \times 2$, and that $N$ is 16 if $A$ is $3\times 3$. Am I right?
Can a general formula be obtained?
We can assume without any loss of generality that $F$ is the field $\mathbb{R}$ of real numbers. Am I right?

A: An $m \times n$ matrix of rank $k$ in RREF will have $k$ leading ones, which can be in any $k$ of the $n$ columns.  There are ${n \choose k}$ ways to choose these if $0 \le k \le \min(m,n)$.  Suppose those are columns $j_1 < j_2 < \ldots <  j_k$.  In row $i$ (for $i \le k$) we have $n - j_i - (k-i)$ "free" positions where there can be either $0$ or $1$.
Thus for a given choice of $j_1, \ldots, j_k$ there are a total of $M = nk + \frac{k-k^2}{2} - \sum_{i=1}^k j_i$ free positions, and this corresponds to $2^M$ of those matrices.
Hmm: it looks to me like in the case $m\ge n$ this is OEIS sequence A006116.


text:
Q: WriteDec stops working after 5 calls, in a loop storing to an array? for a class project we're asked to create a Fibonacci sequence program. I am using Visual Studio 2017 to run my program (32 bit). All goes well when I run the below program until I try to print to console the 6th number in the sequence, 5, (0,1,1,2,3,5). Nothing past the 5th number is being outputted to the console. I am using the WriteDec procedure from Irvine32 Library to accomplish to write decimals to the console.
I am bamboozled because eax register holds the right values when I step through in debugger mode, but WriteDec won't print it out. The address of the array I use to store Fibonacci numbers has these values when computing the 8th term of the sequence :
 0x00406000  00 00 00 00 01 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 05 00 00 00 08 00 00 00 0d 00 00 00
The output looks like:

0
1
123
  ;Fibionacci Sequence

; This program outputs a fibonacci sequence and sum

Include Irvine32.inc

.data
array DWORD 0,1

.code

main proc
    mov ecx, 6 ; would be the 8th term in the sequence
    mov esi, 4
    mov eax, 0
    call WriteDec
    call crlf
    mov eax, 1
    call WriteDec
    call crlf
    L1:
        mov edx, array[esi]
        mov edi, array[esi-4]
        add edx,edi
        mov array[esi+4],edx
        mov eax, edx
        call WriteDec ; Writes an unsigned 32-bit decimal number to standard output in decimal format with no leading zeros.
        add esi,4
    loop L1
    invoke ExitProcess,0
main endp
end main

A: When you write past the end of the two dwords you reserved for your array DWORD 0,1, you're probably overwriting some data that WriteDec uses.

how could i test if writedec overwrites data?

You have it backwards.  Your code is writing outside your array.  The linker probably puts it right before some data that WriteDec needs to read, e.g. maybe a file handle for the console or something.  So after you step on WriteDec's constants, future calls to it stop printing anything.
Your debugger output confirms that WriteDec didn't overwrite the Fibonacci sequence values you stored, so we can conclude that WriteDec isn't writing to that memory, just reading it.
And also that it's not a pointer, or it would crashed when overwrote it with small integers.

Try something like
array DWORD 0,1
  DWORD 10 DUP(?)       ;  or DUP(0)  because that's what you'll really get

to make a larger array with explicit initializers for the first 2 values, then more space in the same section.


text:
Q: Trouble finding correct basis of subspace defined with a linear equation. I have the following subspace in R^3 : H = {(X,Y,Z) in R^3 | x + 2y − z = 0 }
When I try to solve,
I express z = x + 2y which implies that (X,Y,X+2Y).
I then find my basis as follows
T(e1) = T(1 0 0) = (1 0 1)
T(e2) = T(0 1 0) = (0 1 2)
So my basis is v1 = (1 0 1) and v2 = (0 1 2) but the correct answer for v2 is (2 -1 0)
I do not understand why. If basis is not unique I want to know how to find (2 -1 0).

A: The space consists of all vectors orthogonal to $\mathbf n = (1,2,-1)^T$, (why?) so any two linearly-independent vectors orthogonal to $\mathbf n$ form a basis for it. Without further constraints there's no good reason to call one choice more "correct" than another.
Now, as to how to come up with $(2,-1,0)^T$ specifically, I would first suggest following whatever method your text demonstrated for solving similar problems. However, for any nonzero vector $\mathbf v = (a,b,c)^T$, we also have that the vectors $(0,c,-b)^T$, $(-c,0,a)^T$ and $(b,-a,0)^T$ are all orthogonal to $\mathbf v$ and at least two of them are non-zero. (These are just the cross products of $\mathbf v$ with the standard basis vectors.) For $\mathbf v=(1,2,-1)^T$, the last one just happens to be $(2,-1,0)^T$.


text:
Q: 'RNFirebaseBackgroundMessage' Event not triggered while receiving data notification in React Native Application I am using react-native-firebase@5.2.3. I had created a headless task to receive the data notification, and my server is sending me a data notification but it is not reflecting in my application although i had created the event for this.
It is working finely in android < v7. But not working in android version > v7.
I'm not getting anything in console, while server has sent me the data-only notification. Once this callback on headless task execute i will code here to show notification but there is no event triggering.
Environment :
    OS: Ubuntu
        "react": "16.6.3",
        "react-native": "^0.58.6",
        "react-native-firebase": "^5.2.3",

My code is given below.
import {AppRegistry} from 'react-native';
import 'babel-polyfill';
import App from './App';
import {name as appName} from './app.json';
console.disableYellowBox = true;

const bgMessaging = async(messages) => {
    console.log("BgMessaging",messages);
    return Promise.resolve();
};

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging);
AppRegistry.registerComponent(appName, () => App);

A: I got the solution.
When your application is set to use battery in optimised way, then it does not allow to execute the headless task, So, simply i had changed my app's battery setting to normal mode and it started working finely.
My android device was set to use all application in battery optimisation. That's why i had faced this issue.


text:
Q: dependent dropdown for update loads all the states by default in Laravel In my Laravel-5.8, I am using dependent dropdown for country and corresponding states. For the create view blade, I have this:
Controller
public function getStateList(Request $request)
{
    $states = DB::table("config_states")
                ->where("country_id",$request->country_id)
                ->pluck("state_name","id")
                ->sortByDesc('state_name');
    return response()->json($states);
}

public function edit($id)
{
    $userCompany = Auth::user()->company_id;

    $employee = HrEmployee::where('id', $id)->first();
    $countries          =       ConfigCountries::all();
    $states             =       ConfigState::all();

    return view('hr.employees.edit')
            ->with('employee', $employee)
            ->with('countries', $countries)
            ->with('states', $states);
}

create.blade

               Country:
              <select id="country" class="form-control select2bs4" data-placeholder="Choose Country" tabindex="1" name="country_id" style="width: 100%;">
                <option value="" selected disabled>Select Country</option>
                   @if($countries->count() > 0 )
                     @foreach($countries as $country)
                       <option value="{{$country->id}}">{{$country->country_name}}</option>
                     @endforeach
                   @endif
              </select>

               State:
              <select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
              </select>

Javascript

This works.
However, for the edit view blade:

               Country:
              <select id="country" class="form-control select2bs4" data-placeholder="Choose Country" tabindex="1" name="country_id" style="width: 100%;">
                <option value="" selected disabled>Select Country</option>
                   @if($countries->count() > 0 )
                     @foreach($countries as $country)
                       <option value="{{$country->id}}" @if($country->id == $employee->country_id) selected @endif>{{$country->country_name}}</option>
                     @endforeach
                   @endif
              </select>

               State:
              <select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
              </select>

Javascript

I expect it by default to load the current state of origin from the database into the select id="state" dropdown but it was empty.
Then when I changed it to:

               State:
              <select id="state" class="form-control select2bs4" data-placeholder="Choose State" tabindex="1" name="state_id" style="width: 100%;">
                <option value="" selected disabled>Select state</option>
                   @if($states->count() > 0 )
                     @foreach($states as $state)
                       <option value="{{$state->id}}" @if($state->id == $employee->state_id) selected @endif>{{$cstate->state_name}}</option>
                     @endforeach
                   @endif
              </select>

It loads all the states of origin in the database instead of the corresponding state.
How do I resolve this?
Thanks

A: As i said in the comment, you're missing the condition of the country in your states selection.
public function edit($id)
{
    $userCompany = Auth::user()->company_id;

    $employee = HrEmployee::where('id', $id)->first();
    $countries = ConfigCountries::all();
    $states = ConfigState::where("country_id", $employee->country_id)->get();

    return view('hr.employees.edit')
            ->with('employee', $employee)
            ->with('countries', $countries)
            ->with('states', $states);
}


text:
Q: Is having different iOS bundle ID from android package name bad? What are the downsides of different android package name and iOS bundle ID in React Native?

A: See at the end package name is what uniquely identifies your app in the respective app store and playstore.
There maybe a case where you have the desired bundleId taken by some other app etc, in that case you have to use a differnt bundle/app id.
There are no down side of different package name and bundle id . Just make sure you have a proper bundleId / package name which suits your app well. I mean thats one of the criteria what depends on which app it shows first when user searches suppose programming, then a programming related app shows which has suppose app.programming.learn in its package name. So just be wise. You can have different names.
Hope its clear. Feel free for doubts


text:
Q: Trouble getting custom function syntax right: Contains() I'm desperately trying to implement this solution to my own code: https://stackoverflow.com/a/43196497/11632049
The goal is to search for various strings ("ABC", "123", ...) and if a data row contains the string, copy the row to a different workbook.  I am getting a sub or function not defined error
Public Function ContainsAny(ByVal needle As String, ByVal caseSensitive As _
    Boolean, ParamArray haystack() As Variant) As Boolean

    Dim k As Integer
    Dim found As Boolean

    For k = LBound(haystack) To UBound(haystack)
        found = Contains(needle, CStr(haystack(k)), caseSensitive)
        If found Then Exit For
    Next
    ContainsAny = found

End Function

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

    Dim CoderBook As Workbook
    Dim Review As Workbook
    Dim Alpha As Worksheet
    Dim Coder As Worksheet
    Dim LastRow As Long
    Dim NextRow As Long
    Dim i As Long

    Set CoderBook = Workbooks.Open(FilePath)
    Set Coder = CoderBook.Sheets("Sheet1")

    Set Review = ThisWorkbook
    Set Alpha = Review.Sheets("Sheet5")

    'Search code
    LastRow = Alpha.Cells.Find(What:="*", After:=[A1], _
    SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    Application.ScreenUpdating = False

    'Loop search code
    For i = 2 To LastRow

        If Alpha.Range("G" & i) <> Alpha.Range("H" & i) Or _
        Alpha.Range("J" & i) <> Alpha.Range("K" & i) Then

        Select Case True
        Case ContainsAny(Ophth.Range("H" & i), False, "ABC", "123")

            DuplicateCheck = Application.Match(Alpha.Range("A" & i).Value, _
            Coder.Columns(1), 0)
            If IsError(DuplicateCheck) Then
                Coder.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0). _
                EntireRow.Value = Alpha.Rows(i).Value
            End If
        End Select
       End If

    Next i

CoderBook.Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub

A: You are getting a "function not defined" compile error because ContainsAny is invoking the Contains function, which you removed. Add it back.
found = Contains(needle, CStr(haystack(k)), caseSensitive)

But, the logic of the Contains method needs to be flipped for it to work the way you want to use it:
Public Function Contains(ByVal needle As String, ByVal haystack As String, Optional ByVal caseSensitive As Boolean = False) As Boolean

    Dim compareMethod As VbCompareMethod

    If caseSensitive Then
        compareMethod = vbBinaryCompare
    Else
        compareMethod = vbTextCompare
    End If

    Contains = (InStr(1, haystack, needle, compareMethod) <> 0)
    If Not Contains Then Contains = (InStr(1, needle, haystak, compareMethod) <> 0)

End Function

That way Contains will return True when either string contains the other - and with that you can do:
 If ContainsAny(Ophth.Range("H" & i).Value, False, "ABC", "123", "XYZ") Then

And the conditional block will execute when the cell value contains any one of the specified strings.

A: This seems to be working - I adjusted @MathieuGuindon 's custom function to try clarify for myself the desired relationship between my search terms:  I have a set of search terms and I need to know when any of them appear in my data.
Public Function ContainsAny(ByVal data As String, ByVal caseSensitive _
    As Boolean, ParamArray searchterms() As Variant) As Boolean

    Dim k As Integer
    Dim found As Boolean

    For k = LBound(searchterms) To UBound(searchterms)
        found = Contains(data, CStr(searchterms(k)), caseSensitive)
        If found Then Exit For
    Next

    ContainsAny = found

End Function

Public Function Contains(ByVal data As String, ByVal searchterms _
    As String, Optional ByVal caseSensitive As Boolean = False) As Boolean

    Dim compareMethod As VbCompareMethod

    If caseSensitive Then
        compareMethod = vbBinaryCompare
    Else
        compareMethod = vbTextCompare
    End If

    Contains = (InStr(1, data, searchterms, compareMethod) <> 0)

End Function

'implemented as
Case ContainsAny(Alpha.Range("H" & i), False, "ABC", "123", "XYZ)


text:
Q: Memory mapped ADC on DE1-SoC using HPS (hard-core processor) I am unable to read from or write to the AD7928 analog to digital converter (ADC) on the DE1-SoC (Rev. F) development board.
I have the datasheets for the board and the ADC. I am using a mix of custom IP and pre-made hardware components. I have implemented the LEDs, push buttons, and 7-segment displays in Qsys along with the ADC. Base addresses and ranges are set for the memory space of each component. I am controlling the hardware with a C program running in Linux on the dev board. Using a virtual address and offset, I can control all the aforementioned components except the ADC.
The datasheet for the ADC shows 8 registers for reading and 2 for writing. The ADC is set up in Qsys to use one channel (channel 0) out the 8 channels available, running at 12.5MHz. The memory range in Qsys shows correctly that there are 32bytes of addressing assigned to the ADC (8 registers at 4 bytes each). Two of the registers share a read and write command.
Here are the pointers I use for writing the Auto Enable command and reading the 12-bit temperature from channel 0 of the ADC:
// Set ADC to automatically update (write to register offset 4)
*(uint32_t *)(h2p_lw_adc_addr + 4) = 1;

// Read channel 0 from the ADC (read from register offset 0)
temp_in = *(uint32_t *)h2p_lw_adc_addr;

I use the same pointer set-up with the other components, which all work.
I looked at the soft-core processor set-up for the ADC and it has a .h file that contains a command to turn the ADC on, but it seems the hard-core processor systems does not have that command.
Is there some other set-up required for the ADC to be able to use it with the HPS (hard-core processor sys)? The ADC datasheet only shows the 8 registers for control and I have tried both the Auto Enable and Begin Conversion modes. The command registers are shown below.
Command registers for ADC


text:
Q: Does $f\otimes_A 1_{A/m}:M\otimes A/m\to N\otimes A/m$ injective for all maximal $m$ imply $f$ is an isomorphism?
Let $A$ be a commutative ring. Suppose $f\colon M\to N$ is a morphism of free $A$-modules of equal, finite rank. If $f\otimes_A 1_{A/m}$ is injective for all maximal ideals of $A$, does this imply $f$ is an isomorphism?

I suspect it is true, since it seems similar to statements about localizing at maximal ideals in commutative algebra.
Fixing bases of $M$ and $N$, let $D$ be the determinant of $f$ with respect to these bases. Towards a contradiction, suppose $D$ is not a unit, so that $f$ is not invertible. Then $D$ is contained in some maximal ideal $m$. By hypothesis,
$$
f\otimes_A 1_{A/m}\colon M\otimes_A A/m\to N\otimes_A A/m
$$
is injective, and these are now $A/m$-vector spaces of equal, finite dimension, so $f\otimes 1_{A/m}$ is an isomorphism.
As a scalar, $D$ is now $0$ since it's in $m$, is there a contradiction to be found using $f\otimes 1_{A/m}$?

A: Suppose first that $A$ is local with maximal ideal $\mathfrak m$. Then you want to show that if $\hat f:M/\mathfrak mM\to N/\mathfrak mN$ is injective $f$ is an isomorphism. Since this is an injective map of $k=A/\mathfrak m$ vector spaces of equal dimension it is also onto, and this means that $f$ itself is onto (use Nakayama). It suffices you show that an onto map $f:M\to N$ with $M,N$ free of equal rank must be an isomorphism. There is a lovely argument by Vasconcelos: $M=A^n$ is an $A[X]$ module by $Xm=f(m)$ and the hypothesis is that $\mathfrak aM=M$ for the ideal $(X)$ of $A[X]$. By Nakayama there is an element $u=X p(X)\in \mathfrak a$ such that $(1-Xp(X))M=0$. It follows that if $f(m)=Xm=0$ then $m=0$, so $f$ is a monomorphism. Note this works when $f:M\to M$ is an endomorphism with $M$ finitely generated.
This proves the claim for local rings. Can you try to prove the general case now?

A: A homomorphism $f$ of free modules of the same rank, say $n$, corresponds to an $n\times n$ matrix, say $M$.
Notice that $f$ is an isomorphism iff $M$ is invertible.
Since $f$ modulo every maximal ideal is injective, hence bijective, we have that $M$ is invertible modulo every maximal ideal, that is, $\det M\ne0$ for every maximal ideal. This shows that $\det M$ is an invertible element of $A$, hence $M$ is invertible.


text:
Q: Multi-line text output in R Shiny I have a shiny app that allows the user to specify a bunch of options for building a statistical model, and the end result is supposed to be the output of a series of regression coefficients, as shown in this screenshot of a simple print() to the console:

However, when I try to render that exact message to my Shiny UI, newlines are ignored, resulting in a jumbled mess of characters, like this:

unmarkedFrame Object 16 sites Maximum number of observations per site:
  23 Mean number of observations per site: 4.38 Number of primary survey
  periods: 23 Number of secondary survey periods: 1 Sites with at least
  one detection: 16 Tabulation of y observations: 0 1 22 48 298
  Site-level covariates: site Elevation Min. : 1.00 Min. : 148.2 1st
  Qu.: 4.75 1st Qu.:1085.0 Median : 8.50 Median :1318.2 Mean : 8.50 Mean
  :1604.8 3rd Qu.:12.25 3rd Qu.:2264.2 Max. :16.00 Max. :2958.9 NA's :4
  Yearly-site-level covariates: Year 2016 :80 2013 :64 2014 :48 2015 :48
  2017 :48 2012 :32 (Other):48 Year 2016 :80 2013 :64 2014 :48 2015 :48
  2017 :48 2012 :32 (Other):48

So the question is:
How can I get the text to output to my shiny webpage while maintaining the readable formatting of the console output?
I found the following related question, but neither answer seemed to solve my problem...
how to insert new line in R shiny string

A: I figured it out: I needed to use the collapse argument in paste such that
 was inserted between every item in the character vector capture.output(print(summary(m0))).
The next problem was that whitespace would be ignored (because HTML), which I fixed by sandwiching the output between
 tags in order to preserve whitespace verbatim. The solution in server.R looks like this:
output$modelParameters <- renderUI(
        HTML(
          paste(
            c("
", capture.output(print(summary(m0))), "
"),
            collapse = "
"
          )
        )
      )

When called in ui.R by htmlOutput("modelParameters"), it outputs the text, formatted appropriately in a grey box, as intended.


text:
Q: How to decode MySql blob from backup file? I got a MySql backup file containing a column like:
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`profilepicture` blob,
)

The content of this row profilepicture is encoded in the backup file to some kind of dump, starting (in a text editor) like this:
INSERT INTO `tbox_account_transaction` VALUES (8,'?\?\?0JFIF\0\0\0\0\0\0[...]');

How can I decode this from the .sql backup file in c#? It is not Base64, but I do not recognize what else it might be. I don't want to restore the backup.sql file to MySql but instead decode the blob from the backup file.

A: The bytes you are seeing are almost certainly the initial bytes of a JPEG image. The readable string "JFIF" starting at the fifth byte is the clue (see https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format).
Many of the other binary bytes are null or else non-printable characters. All the weird \? or \0 sequences are the client's best effort at representing these bytes on your text display.
The easiest way to access this data is to restore the dump file to a MySQL instance (even a local one running on a laptop), and then use SQL in your C# code to access the binary contents of the profilepicture blob.
Either save the data from one blob to a .jpg file as @Tommaso Belluzzo suggests, or else just display it directly, if you can. I'm not a C# programmer, but it seems there's a Bitmap class for this (see https://msdn.microsoft.com/en-us/library/8tda2c3c(v=vs.85).aspx).
It's outside the scope of a Stack Overflow answer to give a tutorial on how to write SQL in a C# application. There are plenty of resources available for that.

A: That looks like a jpg file header. Try the following (blob is a String typed variable containing the profilepicture):
using (MemoryStream stream = new MemoryStream(buffer))
{
    Image image = Image.FromStream(stream, true, true);
    image.Save("C:\\Test.jpg", ImageFormat.Jpeg);
}


text:
Q: Converting other C++ classes to MTensor in LibraryLink Hopefully this will be a quick question + a quick answer:
Say I have a C++ (or C) code using LibraryLink. I am using a library that defines a specific matrix class, as many numerical libraries commonly do. So during the computations I am using this class and, at the very end, I want to convert it to an MTensor to be used as output.
What is the simplest way to do that? Hopefully, one that does not require reallocating the entire matrix?
[Not sure it helps, but the matrix elements are assumed to be stored sequentially.]
Thank you in advance for the support.
Gabriel
Edit:
Two examples are the NVector class in SUNDIALS and the Matrix class in numerical recipes (3rd Edition in C++). Here is a quote from Numerical Recipes ($n$,$m$ are integers): let
MatDoub a(n,m);
Doub *b &a[0][0];

Then $a[i][j]$ and $b[m*i+j]$ are equivalent.

A: Preface:
Since you want to

convert other C++ classes to MTensor

I have to tell you, that I don't see a possibility for that, because I haven't found how to tell the Wolfram Library to take a chunk of already allocated data and use it for an MTensor.
What I do is the other way around. I use the internal data of an MTensor as underlying array for my own tensor class. Therefore, at best I don't have to allocate any data since I reuse an input MTensor and store the result directly in it. Therefore, I allocate the tensor inside Mathematica and change it.
The following does explain a bit more:
Implementation:
I don't want to leave this question unanswered, when I can give at least some hints. In my C++ code, I had the same problem as you have. The advantage in the following is, that I have my own tensor class which stores even multidimensional tensor data as a flat sequencial array.
If you use a third-party library, you can, as Leonid pointed out, not rely on internal implementation details and in general you are stuck with copying the data. What I show now, works quite nice and is tested on Linux64, Windows32/64 and OSX64, but nevertheless, there are always bugs you haven't found already.
Here is a simple LibraryLink function which loads 2 tensors and an integer, calls a function and returns the output.
EXTERN_C DLLEXPORT int dilation3d(
        WolframLibraryData lib,
        int argc,
        MArgument *args,
        MArgument res) {

    try {
        if (argc != 2)
            throw std::invalid_argument("Two arguments are expected");
        Tensor<mint,3> *input = fromMTensor<mint,3>(lib, MArgument_getMTensor(args[0]));
        Tensor<mint,3> output(*input);
        mint iterations = MArgument_getInteger(args[1]);
        MorphologicalOperations3d::dilate(*input,&output,iterations);
        MTensor m_result = toMTensor(lib, output);
        MArgument_setMTensor(res, m_result);

    } catch(std::exception &e) {
        reportExceptionToMathematica(e, lib);
        return LIBRARY_FUNCTION_ERROR;
    }

    return LIBRARY_NO_ERROR;
}

fromTensor is a template function which tries to create a tensor of appropriate rank from an MTensor. This call does not copy the MTensor, but it uses only a pointer to it's data. The implementation is
template <class Type, int Rank>
Tensor<Type,Rank>* fromMTensor(WolframLibraryData lib, MTensor mtensor) {
    int rank = lib->MTensor_getRank(mtensor);
    if( rank != Rank) throw std::invalid_argument("Rank does not match");

    Tensor<Type,Rank>* res = new Tensor<Type,Rank>();
    const int *mdims = lib->MTensor_getDimensions(mtensor);
    res->data = (MTensorType<Type>::getData(lib))(mtensor);

    res->dims = new int[Rank];
    for (int i=0; i<Rank; ++i) res->dims[i] = mdims[Rank-i-1];
    res->flattened_length = lib->MTensor_getFlattenedLength(mtensor);
    return res;
}

Most of the stuff lines are easy to understand, but this here needs maybe explanation
res->data = (MTensorType<Type>::getData(lib))(mtensor);

You know, that you can call MTensor_getRealData, MTensor_getIntegerData, ... on every MTensor but it is in your duty to call the right one. The question is, when I have a template parameter Type, how can call the right getData automatically?
Here I solved it by giving an instance of the class MTensorType for every possible library type. The instance for mint looks like
template <class Type> struct MTensorType;

template <> struct MTensorType<mint> {
    static const int val = MType_Integer;
    static mint* (*getData(WolframLibraryData lib))(MTensor) {
        return (lib->MTensor_getIntegerData);
    }
    static int mlPutType(MLINK mlp, mint m) {
        return MLPutInteger(mlp,m);
    }
    static int mlPutList(MLINK mlp, mint *list, long length) {
        return MLPutIntegerList(mlp,list,length);
    }
};

Therefore, the static class function getData returns a pointer to the correct WolframLibrary function lib->MTensor_getIntegerData.
The next line in the first code block with output(*input) is the copy constructor of my tensor class. There, I really make a copy of the underlying data. The dilate function writes into this output and at the end my Tensor<mint,3> type is converted back to an MTensor with the toMTensor call. Let me give you code for this too:
template <class DataType, int Rank>
MTensor toMTensor(WolframLibraryData lib, const Tensor<DataType,Rank> &t) {
    MTensor res;
    int *mdims = new int[Rank]();
    for (int i = 0; i < Rank; ++i) mdims[i] = t.dims[Rank-i-1];
    lib->MTensor_new(MTensorType<DataType>::val, Rank, mdims, &res);
    memcpy((void*) (MTensorType<DataType>::getData(lib))(res), (void*) t.data, t.flattened_length*sizeof(DataType));
    delete [] mdims;
    return res;
}

Again, for the parts of the code which have to decide which type of MTensor is constructed. I make use of MTensorType<DataType>::val to get the value for the appropriate type back (this is defined in WolframLibrary.h and I store it in MTensorType). And again, I use getData to get the pointer to the array of the MTensor.
For your purpose, you probably only need the first part of my answer which shows how to use the pointer to MTensor data in your own tensor library. When you transfered the tensors from Mathematica with the "Shared" specifier you can change the array contents without doing a single copy.

A: As @halirutan said, it is not possible to take already allocated memory and return it to Mathematica.  The LibraryLink API does not provide any access to Mathematica's memory management (like malloc, free).  You will need to copy the data.
However, with many libraries, you can do the reverse. You can allocate an MTensor, and use another library's matrix/vector class to wrap that existing storage. For example, Armadillo has this feature.
The LTemplate package that I wrote to make it easier to create LibraryLink libraries comes with some examples that show how to interface with Armadillo while doing a minimal amount of data copying.

Here's how to create a new MTensor and immediately copy some data into it using LTemplate.
Create a new vector of type Real (double in C++) of length n:
auto vec = mma::makeVector<double>(n, data);

data is a pointer to the data to be copied. It does not need to be of type double *. If it is of a different type (e.g. float), it will be automatically converted.
To create an n by m matrix of type Integer (mint in C++), use
auto mat = mma::makeMatrix<mint>(m, n, data);

To make a four-dimensional Real tensor of dimensions $k\times l\times m\times n$, use
auto ten = mma::makeTensor<double>({k,l,m,n});
std::copy(data, data + k*l*m*n, ten.begin());


text:
Q: Three finger tap lookup no longer show Wikipedia pages since upgrading to Sierra First, it showed nothing but I had to go to the dictionary and download it but now I can't lookup things that aren't in the dictionary, that would previously result in it showing me a Wikipedia page.
Any way to fix this?

A: Apple uses Spotlight Suggestions for this functionality since El Capitan: https://support.apple.com/kb/PH21573

If you're using OS X v10.10.3 or later and Spotlight Suggestions are enabled in Spotlight preferences, you may also see information about related music, movies, or map locations.

But Spotlight Suggestions are disabled for some reason in most countries: http://www.apple.com/macos/feature-availability/#spotlight-suggestions
Check if your country is in the Supported list. If not, you're out of luck at the moment, just as me. I couldn't find any normal workaround, that doesn't involve constant VPN connection. If you're OK with VPN inconvenience, cost and additional latency, you may check this solution: https://www.reddit.com/r/apple/comments/3cln0j/how_can_you_enable_spotlight_suggestions_in_mac/
Supported countries at the time of writing:

*

*Australia

*Austria

*Belgium

*Canada

*France

*Germany

*Ireland

*Italy

*Japan

*Mexico

*Netherlands

*New Zealand

*Spain

*Switzerland

*UK

*USA

A: This question is more than four years old, yet I did not experience the same issue until I upgraded to MacOS 11 Big Sur NOV 2020. This thread however helped me to work out an easy fix by clicking Spotlight in System Preferences and choosing both "Siri Suggestions" + "Other." Options now include an array of responses to three tap lookup such as News; Siri Suggested Web Sites; Movies; iTunes; Maps; et al. Often it displays Siri Knowledge instead of Wikipedia, but appears to scrape, or be interchangeable from Wikipedia. In any case I'm provided with deeper breadth and context then merely Dictionary and works quite well.


text:
Q: Can't get photo to render In this directory that I made accessible
http://www.comehike.com/img/member_photo/543/
I have two photos.  The jpg can render in a browser, and the jpeg can not.  Any idea why? I am stuck :)
Thanks!

A: I get:
The image "http://www.comehike.com/img/member_photo/543/full_photo.jpeg" cannot be displayed because it contains errors.

So it would seem the image is corrupted in some way or other.
Search around for JPEG recovery software - it is out there. Depending on what happened to your file to get it into that state, it may or may not be recoverable.
Update: I looked at the file in a hex editor, and the tail of it seems to be all zeroes.
Starting at offset 0x5581:
.Win_BestPos.204.192.205.200.206
.205.203.205.Win:7.Error:0 0 0 0
0 0 0 0.2M:222 1M:256 FT:2 .P:2
05 0 +0.........................
................................
................................
................................
................................
................................
................................
................................

I don't know what it means, or if if Win:7.Error:... indicates anything in particular, but everything after that point is zeroed.


text:
Q: JavaScript Slider inside modal window I want to make a slider inside the modal window. I made the first part of my code: the modal window opens after clicking on the each picture. Now I make two buttons previous and next in the modal window, after clicking on that I want to go to the next image. And I can't understand how should I write js function for previous and next buttons. My code is below:
<!DOCTYPE html>

    <title></title>
    <meta charset="uff-8">

    X

    ❮
    ❯

A: Basically, I have added a data  attribute to the slideshow images which contains their index and whenever next or previous is clicked I load the next or previous index image..
Check out the code below :

var modal = document.getElementById("myModal");
var img = document.getElementsByTagName('img');
var modalImg = document.getElementById('img01');
var currentImage;
for (var i = 0; i  0) currentImage = img[count - 1];
  modalImg.src = currentImage.src;
}

document.getElementById('next').onclick = function() {
  var count = parseInt(currentImage.getAttribute("data"));
  if (count < img.length - 2) currentImage = img[count + 1];
  modalImg.src = currentImage.src;
}

document.getElementsByClassName("close")[0].onclick = function() {
  modal.style.display = "none";
}
.myImg {
  cursor: pointer;
  transition: 0.3s;
}
.myImg:hover {
  opacity: 0.7;
}
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
}
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}
.modal-content {
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duraion: 0.6s;
}
/* Next & previous buttons */

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 0;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}
/* Position the "next button" to the right */

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}
@-webkit-keyframes zoom {
  from {
    -webkit-transform: scale(0)
  }
  to {
    -webkit-transform: scale(1)
  }
}
@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}
.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}
@media only screen and (max-width: 700px) {
  .modal-content {
    width: 100%;
  }
}

  X

  ❮
  ❯


text:
Q: Suppose $a_n$ are positive reals and $\sum a_n$ converges . Suppose $a_n$ are positive reals and $\sum a_n$ converges .
Does $\sum \frac{\sqrt{a_n}}{\sqrt{n}}$ converge?
Since $a_n$ is convergent , there exists $N_0$ such that $a_n$< $\epsilon$ for n>$N_0$ also
$a_n+a_{n+1}...a_m$ < $\epsilon$ for all n,m > $N_0$
Also, we know $a_n$ < $\sqrt a_n$ for n>$N_0$.
Any counterexample?
How to continue?


text:
Q: When one clause has "have", what should the other clause in the same sentence have? Consider this sentence: "Why does "singer" have /ŋ/ and "longer" have /ŋg/?"
In this sentence, "Why does "singer" have /ŋ/" is a separate clause having "does" refer to "have" (does + have).
""longer" have /ŋg/" is a separate clause. But I am not certain about the "have" in the second clause. I rephrased the sentence as:
"Why does "singer" have /ŋ/ and "longer" has /ŋg/?" but it doesn't sound right to me.
Can the first does also refer to the second clause? If so, how?
What else could I write to avoid two haves or have and has? Is my sentence correct?

A: Your original sentence is correct.
This is an example of parallelism.  If you wrote it out in full you would need to repeat "why does".  English grammar often allows for repeated phrases to be deleted in the second phrase, but other words should be written as if they were there.
So in full

Why does "singer" have /ŋ/, and why does "longer" have /ŋg/?

becomes

Why does "singer" have /ŋ/ and "longer" have /ŋg/?

When the parallel phrase "why does" is removed.
You could go further and also remove have.

Why does "singer" have /ŋ/ and "longer" /ŋg/?

But now there are two different deletions at two places and it is that much harder to understand (your brain needs to work harder to put "why does" in before "longer" and "have" after it.) So your original sentence is the best compromise between being short and being easy to understand.


text:
Q: Address fields by country The iPhone Contacts app has a nice interface for saving addresses. When you change the country, the fields change to be specific to that country's address fields. For example, the US has a "Zip" field, where other countries have a "Postal Code".

Is there any method to get these fields, possibly by passing a country code?

A: I think what you are looking for is ABCreateStringWithAddressDictionary method of ABAddressFormatting class. Here is the link to the ABAddressFormatting Class reference


text:
Q: Jquery after validating data, submiting a form fails with message: Uncaught TypeError: Cannot call method 'submit' of undefined I am doing a lot of validations on my form, and when it's getting to it's finish step, I can use this.form.submit(); to submit the form. It gets to that step, I tried using console.log, and it worked. But it just doesn't submit the form and getting this error:
Uncaught TypeError: Cannot call method 'submit' of undefined

Why is it becoming undefined?
        $("#center").on('click', function(e) {

            var valid = true;
            var fields;
            var canSubmit;
            var readyForValidate;
            var emailValidation;

            var close        = $("#close");
            var errors       = $(".errors");
            var username     = $("#username");
            var pass         = $("#password");
            var repass       = $("#repassword");
            var pass_f       = $("#password_f");
            var repass_f     = $("#repassword_f");
            var email        = $("#email");
            var display      = $("#display");
            var incomplete   = $(':input', this.form).filter(function() {
                                   return $(this).val() == '';
                               });

            $(':input', this.form).each(function(i, ele) {
                e.preventDefault();
                if (ele.value.trim() == "") {
                    ele.style.border = '2px solid red';
                    valid = false;
                    errors.html("One of the fields are empty, please fill them up. X");
                    errors.fadeIn("slow");
                    close.click(function() {
                        errors.fadeOut("slow");
                        errors.html("");
                    });
                }
                else
                {
                    $(this).removeAttr('style');
                }
            });

            if(!incomplete.length) {
                fields = true;
            } else {
                fields = false;
            }

            if (fields) {
                if (!isValidEmailAddress(email.val())) {
                    errors.html("The entered email address is not valid. X");
                    errors.fadeIn("slow");
                    email.css("border", "solid 2px red");
                    close.click(function() {
                        errors.fadeOut("slow");
                        errors.html("");
                    });
                } else if (pass.val() != repass.val()) {
                    errors.html("Your passwords for in-game are not equal! X");
                    errors.fadeIn("slow");
                    pass.css("border", "solid 2px red");
                    repass.css("border", "solid 2px red");
                } else if (pass_f.val() != repass_f.val()) {
                    errors.html("Your passwords for forums are not equal! X");
                    errors.fadeIn("slow");
                    pass_f.css("border", "solid 2px red");
                    repass_f.css("border", "solid 2px red");
                } else if (pass.val().length < 5) {
                    errors.html("Your in-game password is too short! X");
                    errors.fadeIn("slow");
                    pass.css("border", "solid 2px red");
                } else if (pass_f.val().length < 5) {
                    errors.html("Your forums password is too short! X");
                    errors.fadeIn("slow");
                    pass_f.css("border", "solid 2px red");
                } else if (
                pass_f.val() == repass_f.val()      &&
                pass.val() == repass.val()          &&
                isValidEmailAddress(email.val())    &&
                pass.val().length > 4               &&
                pass_f.val().length > 4) {

                    readyForValidate = true;

                } else {
                    readyForValidate = false;
                }

                if (readyForValidate) {
                    validateUsername(username.val()).done(function(data) {
                        if ($.trim(data) == 1) {
                            errors.html("That username already exists! Please use another.X");
                            errors.fadeIn("slow");
                            username.css("border", "solid 2px red");
                        } else {
                            validateEmail(email.val(), 'email').done(function(data) {
                                if ($.trim(data) == 1) {
                                    errors.html("That email is already registered. Please use another.X");
                                    errors.fadeIn("slow");
                                    email.css("border", "solid 2px red");
                                }
                                else
                                {
                                        this.form.submit();
                                }
                            });
                        }
                    });
                }
            }
        });

    });

    /**
    * Function check email
    * Checks if email is valid
    *
    * @param emailAddress Entered email address
    * @return email is valid
    **/

    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
        return pattern.test(emailAddress);
    }

    function validateUsername(username, type) {
        return $.post("js/ajax/ajax.php", { validateUsername : 1 });
    }

    function validateEmail(username, type) {
        return $.post("js/ajax/ajax.php", { validateEmail : 1 });
    }

A: That is because of the this context
this does not point to the same object inside the done handler.
Save a reference of this  and then try using it
You can either save the reference and use it inside done.
or use $.proxy and bind the this context to it.

A: You're inside the scope of an ajax done() function, so this would be $.ajax, and this.form doesn't exist, so this.form.submit() does nothing ?
$("#center").on('click', function(e) {
   var self = this;

   .......

   validateEmail(email.val(), 'email').done(function(data) {
       self.form.submit();
   });
});


text:
Q: Load a resource into a frame work from an app I have a framework I wrote for an app and now I am writing some unit tests for it. To complete the test suite, I need to load a configuration file from the main app into my framework's unit tests. When I try to use Bundle(for: self.classForCoder) and load that config file, it returns nil all the time. Any thoughts?

A: Neither your framework, nor the tests for it, can access your main app bundle that way.
Since your app provides the config file to the framework, your tests can do the same. If you can use a test config file, just add it to your test bundle. If you need a copy of the actual config file, then make a copy.
(You may want a Run Script build phase to do the copying. Don't forget that just making a copy isn't enough — you still need to add it to the test target.)


text:
Q: Preloading a lot of images, stop a preloading screen I'm trying to preload 20 pictures. I have written this code, but I'm not sure it works. Even though they don't pixelate, they appear strange, by flashing and lagging. Any ideas what I'm doing wrong?
$(window).on("load", (function () {
   PrepareImgs();
   console.debug('loaded');
}));
var sectionArray = ["whoAreWe", "video", "web", "community", "charity"];
var imgArray = [];
function PrepareImgs() {
 // console.debug("PrepareImgs started");
 for (var i = 0; i < 5; i++) {
     for (var j = 1; j <= 4; j++) {
         var zdj = "Assets/Images/CroppedAndCleaned/" + sectionArray[i] + "/pp" + j + ".jpg";
         imgArray.push(zdj);
     }
 }
 LoadImages();
}

function LoadImages() {
// console.debug("LoadImages started");
var i = 0;
$(imgArray).each(function () {
    // console.debug("loop started");
     var img = new Image();
     $(img).attr('src', imgArray[i]);
     img.src=imgArray[i];
     console.debug(i);
    // function preloadImage(url)
    // {
    //     var img=new Image();
    //     img.src=url;
    // }
     img.onload = function () {
         console.debug("Internal loop started");
         i+=1;

         if (i == $(imgArray).length)
             HideLoader();
     }
 });
}
function HideLoader() {
 // console.debug("HideLoader Started");
 setTimeout(function () {
     $('body').addClass('loaded');
 }, 1);
}

A: Try to follow this example,
it loads image and appends them to the DOM once all of them are loaded.
It uses Promises.

function preloadImages(...images) {

  return Promise
    .all(
      images.map((src, i) => new Promise((resolve, reject) => {
        src = `https://lorempixel.com/400/200/${src}/Image-Number-${i}`;
        const img = $('<img />');

        return img
          .attr('src', src)
          .on('load', () => resolve(img))
          .on('error', reject)
      }))
    )
  ;
};

preloadImages('sports', 'food', 'business', 'animals', 'nightlife', 'fashion')
  .then(res => {
    console.log('images loaded');

    return res.forEach($img => $img.appendTo('body'))
  })
;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: How to migrate from a multipage app to Piral We run a few ASP.NET Core applications that do come with some pages. These are all "classic" multipage applications.
For our new portal we've decided to go with piral. While we add a couple of new modules we also want to use the existing applications.
How can we integrate a multipage application in piral or in a clientside (SPA) micro-frontend?
One example for a multipage app looks like (hosted on some address like https://myexample.com/home)
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Privacy Policy - DotnetApp</title>
    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/css/site.css" />

                DotnetApp
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home

                            Privacy

Privacy Policy

Use this page to detail your site's privacy policy.

            © 2020 - DotnetApp - Privacy

We don't need to have all scripts - most of them are just there due to the boilerplate. Actually we can also run without all of them.

A: Migration of an MPA to Piral can be done in multiple ways.

*

*Create a wrapper pilet that exposes the different SSRed parts via iframes

*Create a wrapper pilet that exposes the different SSRed parts via fragments which are dynamically obtained

*Convert your Razor views into React parts and have a split between FE/BE; put the React parts in a pilet

I don't know how complicated you application is, but maybe (1) would be the easiest to get started (especially if its, e.g., just a single page).
Let's see how (2) may be implemented:
import * as React from 'react';

export function setup(app) {
    const connect = app.createConnector(() => fetch('https://myexample.com/home').then(res => res.text()));
    app.registerPage('/myexample', connect(({ data }) => {
        const __html = data;
        return
;
    }));
}

Here, we lazy load content from https://myexample.com/home and display it in the component (which will be a page).
There are a couple of things you should watch out for:

*

*In the best case detect the fetch (or send a special header) and only return a fragment instead of the full response

*If stylesheets are needed either "fish" them out of the response or integrate them upfront (see next point)

*The code above has no special SPA link handling. Thus all links are relative to the given page URL and they are making a full transition ...

*JavaScript would not be loaded / working in the given solution

Now regarding a stylesheet you could do (among other things):
import './my-style.css';
import * as React from 'react';

export function setup(app) {
  // ...
}

where my-style.css looks like:
@import url(https://myexample.com/css/site.css);

We could have more URLs etc. here, but I leave that out on purpose. Keep in mind that the previously shown way could introduce collisions. So either "download" the sheet upfront and prefix ("scope") it, or use it all in a shadow DOM solution (shadow DOM is always "free" of the parent DOM's style and needs to import its own stylesheets).
For the link handling what you can do: Use a layout effect, get all a elements via a selector, attach an event and cancel the original navigation. Use the history context instead.
In code this looks similar to:
import * as React from 'react';
import { useHistory } from 'react-router';

export function setup(app) {
    const connect = app.createConnector(() => fetch('https://myexample.com/home').then(res => res.text()));
    app.registerPage('/myexample', connect(({ data }) => {
        const __html = data;
        const container = React.useRef();
        const history = useHistory();
        React.useLayoutEffect(() => {
            if (container.current) {
                const anchors = container.current.querySelectorAll('a[href]');
                Array.prototype.forEach.call(anchors, anchor => {
                    anchor.addEventListener('click', ev => {
                        ev.preventDefault();
                        history.push(anchor.getAttribute('href'));
                    });
                });
            }
        }, []);
        return
;
    }));
}


text:
Q: Numerical solution of a second-order non-linear PDE I'm interested in solving the following non-linear terminal value problem
$$
0 = \frac{\partial u}{\partial t} + \frac{1}{2}\sigma^2x
\frac{\partial^2 u}{\partial x^2}
+ \lambda(x_0 - x)\frac{\partial u}{\partial x} - \phi
+ \frac{1}{x}u^2,\qquad u(T, x) = -\alpha.
$$
on $(t, x)\in(0, T)\times(0, \infty)$, where $\sigma>0$, $\lambda>0$, $x_0>0$, $\phi>0$ are constants. For context, this PDE arose from an application of the Hamilton-Jacobi-Bellman equation to a stochastic control problem that I'm studying.
I think it's unlikely that an analytic solution is available, and I expect I'll need to use numerical methods to examine the solution. My first thought is to use a finite difference scheme, such as Crank-Nicolson, but I'm not sure of a suitable boundary condition to use on the solution grid for large $x$.
I'd be very grateful for any suggestions on how to proceed. I'm not very familiar with the literature on the numerical solution of PDEs, so even pointers towards possible references would be really helpful.


text:
Q: Centralize QTableView in window with vertical spacers I am trying to create a main window (fixed size) that contains a QTableView, with QSpacerItems above and below, in order to centralise the table (vertically).
(Sorry, can't post an image, apparently).
I have a QVBoxLayout, into which I have a vertical spacer, the QTableView, and another vertical spacer. I've played with all combinations of QSizePolicy for all three widgets, but I cannot get the table to be displayed without scrollbars. (I cannot use Qt.ScrollBarAlwaysOff because they will be needed if the number of items exceeds the main window's size). So the vertical scrollbars on the QTableView are displayed, even though the vertical spacers are absorbing plenty of space between the view and the main window.
I want the vertical spacers to take up the minimum space required above and below the table widget in order to centralise the rows, and the table widget to display as many rows as possible, without scrollbars.

A: You can subclass QTableView, use QSizePolicy::Fixed in the vertical direction and override sizeHint() to return your preferred vertical height.
Here's a working example (You didn't specify language, so I am going to assume it is Python :-) :
import sys
from PySide import QtCore, QtGui

class MyTableView(QtGui.QTableView):
    def __init__(self, parent=None):
        super().__init__(parent)
        #assume expanding in horizontal direction and fixed in vertica direction
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)

    def sizeHint(self):
        return QtCore.QSize(400, 500) #I allow you to edit that!

class MyApplication(QtGui.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QtGui.QVBoxLayout()
        table_view = MyTableView()
        layout.addWidget(table_view)
        self.model = QtGui.QStringListModel() #use a string list model for simplicity
        table_view.setModel(self.model)
        self.strings = ['1', '2', '3']
        self.model.setStringList(self.strings) #initialize the model
        self.counter = 4
        button = QtGui.QPushButton('Add Cell') #this button updates the model and adds cells
        button.clicked.connect(self.addCell)
        layout.addWidget(button)
        self.setLayout(layout)

    def addCell(self):
        self.strings.append(str(self.counter))
        self.counter += 1
        self.model.setStringList(self.strings)

app = QtGui.QApplication(sys.argv)
main = MyApplication()
main.show()
sys.exit(app.exec_())


text:
Q: Reading mutable references has different lifetime semantics than immutable references Consider the following code, where a reference to a root type R is wrapped. Also stored is some type N(avigate), which knows how to dereference R for T.
use std::ops::Deref;

struct Wrapper<'r, R, N, T>
where
    N: Fn(&'r R) -> &T,
    T: 'static,
{
    r: &'r R,
    n: N,
}

impl<'r, R, N, T> Deref for Wrapper<'r, R, N, T>
where
    N: Fn(&'r R) -> &T,
    T: 'static,
{
    type Target = T;

    fn deref(&self) -> &T {
        let r: &'r R = self.r;
        let t: &'r T = (self.n)(r);
        t
    }
}

Now, if we change our reference type r: &'r R, to be mutable r: &'r mut R, it no longer works:
use std::ops::Deref;

struct Wrapper<'r, R, N, T>
where
    N: Fn(&'r R) -> &T,
    T: 'static,
{
    r: &'r mut R,
    n: N,
}

impl<'r, R, N, T> Deref for Wrapper<'r, R, N, T>
where
    N: Fn(&'r R) -> &T,
    T: 'static,
{
    type Target = T;

    fn deref(&self) -> &T {
        let r: &'r R = self.r;
        let t: &'r T = (self.n)(r);
        t
    }
}

Error:
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
  --> src/lib.rs:21:24
   |
21 |         let r: &'r R = self.r;
   |                        ^^^^^^
   |
note: ...the reference is valid for the lifetime 'r as defined on the impl at 13:6...
  --> src/lib.rs:13:6
   |
13 | impl<'r, R, N, T> Deref for Wrapper<'r, R, N, T>
   |      ^^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the method body at 20:5
  --> src/lib.rs:20:5
   |
20 | /     fn deref(&self) -> &T {
21 | |         let r: &'r R = self.r;
22 | |         let t: &'r T = (self.n)(r);
23 | |         t
24 | |     }
   | |_____^

We get a better error message with nll:
error: lifetime may not live long enough
  --> src/lib.rs:21:16
   |
13 | impl<'r, R, N, T> Deref for Wrapper<'r, R, N, T>
   |      -- lifetime `'r` defined here
...
20 |     fn deref(&self) -> &T {
   |              - let's call the lifetime of this reference `'1`
21 |         let r: &'r R = self.r;
   |                ^^^^^ type annotation requires that `'1` must outlive `'r

I've annotated the lifetimes in deref to make sure i'm on the same track as the compiler about the lifetimes. The nll message is particulary interesting, because it says that it requires &self to outlive 'r.
But that doesn't make sense to me, since if we annotate the lifetimes on deref, it should look like this:
fn deref<'1>(&'1 self) -> &'1 T;

And rather require that 'r: '1, which is implicitly given by Wrapper<'r, ...>
This intuition seems to hold in the first example, but not in the second with the immutable reference.
So two questions unfold for me:

*

*Why does it make a difference if self.r is immutable or not? I can't access r mutably anyway, since &self is immutable.

*Is 1. a fundamental restriction, or can the code be annotated in a way to tell rustc what i want to do?

A: Trait Types are invariant over their generic parameters.
Consider this example:
struct Test<'a, F: Fn(&'a i32)> {
    i: &'a i32,
    f: F,
}

fn main() {
    let i = 1i32;
    let t = Test { i: &i, f: |&_| {} };

    {
        let j = 2i32;
        (t.f)(&j);
    }

    println!("{:?}", t.i);
}

This will give the error:
error[E0597]: `j` does not live long enough
  --> src/main.rs:12:15
   |
12 |         (t.f)(&j);
   |               ^^ borrowed value does not live long enough
13 |     }
   |     - `j` dropped here while still borrowed
14 |
15 |     println!("{:?}", t.i);
   |                      --- borrow later used here

As you can see, the type Test<'a ... is not unified to a shorter lifetime with  that of j because Test contains a trait impl type N (static dispatch). As a result, it will be invariant over 'a, hence 'a cannot be shortened. But j does not live for 'a,  hence the error.
Moving to your question, let's have a look at a minimal version of your code:
struct Wrapper<'r, R, N>
where
    N: Fn(&'r R),
{
    r: &'r mut R,
    n: N,
}

impl<'r, R, N> Wrapper<'r, R, N>
where
    N: Fn(&'r R),
{
    fn myderef(&self) {
        (self.n)(self.r)
    }
}

This would give the same error:
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
  --> src/lib.rs:14:18
   |
14 |         (self.n)(self.r)
   |                  ^^^^^^
   |
note: ...the reference is valid for the lifetime 'r as defined on the impl at 9:6...
  --> src/lib.rs:9:6
   |
9  | impl<'r, R, N> Wrapper<'r, R, N>
   |      ^^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the method body at 13:5
  --> src/lib.rs:13:5
   |
13 | /     fn myderef(&self) {
14 | |         (self.n)(self.r)
15 | |     }
   | |_____^

What's exactly happening here? &self with lifetimes will be of type &'shorter_lifetime Wrapper<'r, R, N> and not &'shorter_lifetime Wrapper<'shorter_lifetime, R, N>. 'r will not be shortened to 'shorter_lifetime as Wrapper will be invariant over it's generic lifetime parameter 'r because of N.
Now that we know what exactly the argument type &self is, let's see what happens inside the body of myderef(). The trait type N (static dispatch) is invoked with self.r. But self.r is a mutable reference, that gets re-borrowed when passed to (self.r)(). So now you have a mutable reference that is behind another reference (self is a reference), that needs to live for 'r (N
needs it's input argument to be with 'r lifetime as per the definition), as a result &self too needs to live for 'r.  But &self's lifetime is 'shorter_lifetime, hence the error.
To put it another way, if you have &'a & 'b mut T (no subtyping relation between 'a and 'b) as an input  argument to a function and the compiler allows you to reborrow the inner reference and return it, then there is a violation of the borrowing rules, since &mut T is already behind a reference. The outer reference "owns" the inner reference, mainly because the inner reference is mutable and the function needs a guarantee that the outer reference remains for at-least as long as the inner (mutable) reference is reborrowed, otherwise after the function call there would be more than one owner of the mutable reference.
As an example, the following code will not compile:
fn test<'a, 'b> (i:&'a &'b mut i32) -> &'b i32 {
    &**i
}

But this one will:
fn test<'a:'b, 'b> (i:&'a &'b mut i32) -> &'b i32 {
    &**i
}

as there's a guarantee that 'a lives for at-least as long as 'b.
If the inner reference is immutable, then the former will also compile as you can have multiple immutable references. There is no notion of outer reference "owning" the inner reference.
To make the minimal version compile, we will have to tell the compiler that &self also lives for 'r. Either that or remove the hard constraint of 'r on the N's input argument (lifetime elision).
In your example, deref() won't allow you to specify a lifetime on &self, as per Deref's definition. If you remove the hard constraint of 'r on N's input argument, it will compile


text:
Q: Azure DevOps commits by developer In Azure DevOps, is there an easy way to find the total number of commits by developer within a specific time period? Possibly with the number of lines added/removed as well? Based on 1 repo or multiple.
Similar to this image from GitHub...

A: You could check out the marketplace. A possible extension would be Contributions Graph, which also allows you to select one or more repositories.

A: I think this is a general git question.
What we did in our peoject is similar to Git number of commits per author on all branches
You would go for something like:
git shortlog -s -n --all --no-merges --since="22 Aug 2019" --before="01 Sept 2019"
This would result in:

you could also add the author by adding --author=name like:

I would suggest to read the docs for options.

A: If you use VisualStudio, a quick way to achieve the number of commits is to copy and paste the changeset history into excel and filter by user. It's not something I'd want to use regularly but it works.
It's worth mentioning though, that lines of code committed can be misleading and therefore unfair to the coders. Good code can be a lot shorter than bad code. And lots of code might just contain external libraries etc.


text:
Q: Kalman filter, car tracking, Matlab I have a small data set of a moving car:
Data_=[time x,y,z];    %# ONLY THIS DATA

I know that in this case velocity and acceleration are not constant.
I want to estimate the car position at various times. I decided to use Kalman filter.
I searched for Kalman filter but I couldn't find code for tracking an object in 3D space with velocity and acceleration. I don't know where to start. Can Kalman filter automatically handle velocity and acceleration?
Can some one help me and give some link or some guidance?

A: My recommendation is to go to the Mathworks file exchange and search for Kalman filters
You'll find several good pieces of code for this very standard algorithm.
As far as Kalman filters themselves, they are what's called a Predictor-Estimator.  That is, they can do prediction of the state at time n given the observations up to time n-1.  Then after you've received the  observations at time n you can do estimation (some call it smoothing) for all times up to and including time n.  The estimation part is done through what's called an innovation and through the current Kalman gain.
Kalman filters work through the concept of a "state space", that is your state stores all the necessary information about the object.  The observation vector, which are different, are what you can observe about your system. In a constant acceleration model, for example, you'll probably assume that the state only contains the 3 position values and the 3 velocity values (x, y, and z for each).  It's the designer of the filter's job to decide the state space and the state transition model (how you expect the state to change in absence of observations.)
You'll have to choose a state transition matrix, you'll have to have some knowledge of the covariance matrix of the error of your observations, of the covariance matrix of the error in your state transition matrix (i.e., how good your state transition model is), and the covariance matrix of your initial state estimate (which you have to also choose).  You'll also have to choose the relationship between the state vector and the observation vector.
Kalman filters are the maximum likelihood optimal linear estimator if you assume Gaussian observation noise, Gaussian process noise and a few other standard things.

A: Kalman Filter is 5-6 lines in a loop. You do not need anybody's implementation.
What you need is a linear system model that describes the trajectory of your car. If you have the system matrices A,B,C (or F,G,H) you are practically done.
Kalman Filter is a general Bayesian filtering algorithm. It will work for any linear gaussian case.

A: Check out the udacity.com course on AI ,CS373. There they have explained kalman filter very nicely.

A: The Computer Vision System Toolbox now has a vision.KalmanFilter object.  Here is an example of how to use it for tracking objects. The example is in 2D, but it can be easily generalized to 3D.

A: The (linear) Kalman filter is probably the best option in your case (one of its first applications was in fact to track the position of the Apollo space ship to properly hit the moon!). So there are plenty of tutorials on exactly this problem, e.g. see the example with this cute little robot. And it is in fact some 5 lines of code (note that you should use persistent variables). The tuning of the covariance matrices (often P, R, Q) is an educated guessing. Initialize P as a diagonal matrix P = eye(length(x))*1e3 and choose the noise matrices R, Q roughly in the same order of the state vector x or the measurements y respectively.
If you don't like the fuzzy with noise matrices, you can use a recursive fit: RLS (recursive-least-squares) is a standard identification method -- but it does not use any statistics as the Kalman filter, i.e. it is prone to noise in the measurements. It consists of even less lines of code but also uses persistent variables.
function [x_est] = RLS(y,x0,mk,fnc)
% (non)linear recursive-least-square
%
% y     measurements
% x0    initial value of the to-be-identified state vector
% mk    measurement matrix, so that y = mk'*x
% fnc   function handle, if the system is non-linear and when mk is the
%       linearized version of this function

persistent  x P
if isempty(x)

    x = x0;
    P = eye(length(x)) * 1e3;
end

% adaption factor (usually [0.9 1))
AdaptFct = .995;

%% nonlinear prediction
if nargin > 4
    y_sim = fnc(x);
else
    y_sim = mk*x;
end
e = y_sim - y;

%% RLS
% Kalman gain
G = P*mk / (AdaptFct + mk'*P*mk);

% Update
% state
x = x + G*e;
% covarianve matrix
I = eye(length(P));
P_new = (I - G*mk')*P;
P = P_new/AdaptFct;

%% output
x_est = x;

end

Note that you have to clear the persistent variables of a function if you want to restart everything: clear RLS


text:
Q: Dash (or minus or subtraction) followed by letter (or function name) causing syntax error in Perl I was surprised when
sub f{1};

my $answer = 1-f(1);

gave me a syntax error in Perl when I was expecting it to perform subtraction.  Adding a space made it work okay again:
sub f{1};

my $answer = 1- f(1);

Why does this cause a syntax error in Perl? Is there an ambiguity? Is the dash interpreted as part of the function name?

A: -f tests whether a file is a plain file, so it does not make sense to perl as it does not see - sign. That is why this works as you expect, as there is no -fo test.
sub fo{1} my $answer = 1-fo(1);

(nor there is +f test)
sub f{1} my $answer = 1+f(1);