Como baixar um arquivo de um repositório privado do Github?

Question: Oi! Tudo bem?
Estou desenvolvendo um projeto em JavaScript e queria criar um pequeno banco de imagens para ele no Github.
Mas queria deixar privado, só que não sei como posso pegar a URL de uma imagem quando o repo está privado.
Já tentei com o username:password mas nd... Talvez seja pelo Token, mas também não aprendi a mexer com ele.
Se alguém souber, me ajudaria muito!
Ou se alguém tiver uma sugestão de outro sistema que possa fazer usando JS, também aceito.
Obs: Seria muitas imagens, então colocar-las na pasta do projeto e hospedar tudo, seria meio inviável.
Comment: Deve ser mais fácil jogar num volume S3 da Amazon AWS configurado para acesso público.
Comment: Seria para usar em produção? O problema aí é que a chave ficaria aberta no seu js... por isso a ideia acima de usar um volume ou colocar em um CDN é mais viável
Answer: Tente esse exemplo: baixar o arquivo baz da versão 0.1.3 de um repositorio privado do Github para o pasta /tmp, você faria o seguinte:
GITHUB_OAUTH_TOKEN="seu token"
fetch --repo="https://github.com/usuario/teste" --tag="0.1.3" --source-path="/baz" /tmp

Espero que ajude.


Execute lambda function on local device using greengrass

Question: I am trying to learn AWS greengrass and so I was following this tutorial https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-gs.html which explains step by step on setting up with greengrass on raspberry pi and publishing some messages using a lambda function.
A simple lambda function is as following :
import greengrasssdk
import platform
from threading import Timer
import time

# Creating a greengrass core sdk client
client = greengrasssdk.client('iot-data')

# Retrieving platform information to send from Greengrass Core
my_platform = platform.platform()

def greengrass_hello_world_run():
    if not my_platform:
        client.publish(topic='hello/world', payload='hello Sent from Greengrass Core.')
    else:
        client.publish(topic='hello/world', payload='hello Sent from Greengrass Core running on platform: {}'.format(my_platform))

    # Asynchronously schedule this function to be run again in 5 seconds
    Timer(5, greengrass_hello_world_run).start()

# Execute the function above
greengrass_hello_world_run()

# This is a dummy handler and will not be invoked
# Instead the code above will be executed in an infinite loop for our example
def function_handler(event, context):
    return

Here this works but I am trying to understand it better by having a lambda function to do some extra work for example opening a file and writing to it.
I modified the greengrass_hello_world_run() function as following
def greengrass_hello_world_run():
    if not my_platform:
        client.publish(topic='hello/world', payload='hello Sent from Greengrass Core.')
    else:
        stdout = "hello from greengrass\n"
        with open('/home/pi/log', 'w') as file:
            for line in stdout:
                file.write(line)
        client.publish(topic='hello/world', payload='hello Sent from Greengrass Core running on platform: {}'.format(my_platform))

I expect upon deploying, the daemon running on my local pi should create that file in the given directory coz I believe greengrass core tries to run this lambda function on local device. However it doesnt create any file nor it publish anything coz I believe this code might be breaking. Not sure how though, I tried looking into cloudwatch but I dont see any events or errors being reported.
Any help on this would be really appreciated,
cheers !
Answer: A few thoughts on this...
If you turn on the local logging in your GG group set up it will start to write logs locally on your PI. The settings are:

The logs are located in: /greengrass/ggc/var/log/system
If you tail the python_runtime.log you can see any errors from the lambda execution.
If you want to access local resources you will need to create a resource in your GG group definition. You can then give this access to a volume which is where you can write your file.
You do need to deploy your group once this has been done for the changes to take effect.
Answer: I think I found the answer, we have to create the resource in lambda environment and also make sure to give read and write access to lambda for accessing that resource. By default lambda can only access /tmp folder.
Here is the link to the documentation
https://docs.aws.amazon.com/greengrass/latest/developerguide/access-local-resources.html


PrimeNG Dropdown LazyLoad event not firing

Question: I have upgraded my Angular PrimeNG app from v9 to 11. Dropdown lazy loading has stopped working and event onBranchLazyLoadEvent isn't called now.  Below is the sample code

What could be wrong here?
Answer: Even though the primeng 14 documentation says it's supported, it doesn't truly work. Not even on the example page and there is very little saying about this.
Answer: Latest versions doesn't support dropdown lazyloading
Reference to latest dropdown source dropdown source
Some open issues about it with working lazy dropdown repo fork by @yelhouti 7284
5955
Comment: Still an issue in 2022, thanks for the link.
Answer: Since primeng 14 this is again supported (below is their official example with lazy loading and virtual scroll).

Virtual Scroll (100000 Items) and Lazy

    <ng-template pTemplate="loader" let-options="options">

    </ng-template>

Answer: In PrimeNG 13, where the option lazy doesn't exist, I managed to hack it like this (and I assume it will work for earlier versions like your 11):

    <ng-template let-tag pTemplate="item">

{{ tag.name }}

    </ng-template>

The code above should be self-explanatory, you need to load your options in the loadTags() or loadWhatever() method and make sure you don't load them again, depending on your needs, by using an extra boolean like areTagsLoaded.
Comment: what about scrolling ? , your fix is not complete
Comment: @IbraHimM.Nada this fixes the lazy loading part, in the sense that the options are loaded dynamically. It doesn't fix the virtual scrolling issue, which is far more complicated. If you need this, you can look for answers elsewhere


Barycentric interpolation polynomial

Question: I am trying to prove that if $$l_i(x) = \frac{w_{n+1}(x)}{(x - x_i)w_{n+1}'(x_i)} \ \ \ \text{where} \ \ w_{n+1}(x) = \left[ \sum_{i=0}^{n}\frac{\lambda_i}{(x-x_i)}\right] ^{-1} $$ then $$\sum_{i=0}^{n}l_i(x) = w_{n+1}(x) = \sum_{i=0}^{n}\frac{\lambda_i}{(x-x_i)} = 1$$
I think we need to expand the sum and somehow terms will cancel leading you to 1 but I am not sure how to show this, any suggestions or hints is greatly appreciated.
Answer: You have:
$$\sum_{i=0}^{n}l_i(x) = 1$$
This follows from the fact that $w_{n+1}(x)$ is zero at all the $x_i$, therefore $l_i(x)$ is zero at all the $x_j$ for $j\neq i$ while at $x = x_i$ it is equal to 1 (after you remove the removable singularity). This means that $\sum_{i=0}^{n}l_i(x)$ is equal to 1 at all the $x_i$. Because the $l_i(x)$ are nth degree polynomials, it follows that the summation is a constant equal to 1.
Comment: Ok, I think I understand, is there a way of proving it formally?

Barycentric interpolation polynomial


Covariance of continuous functions, uniform and normal distribution

Question: For X~Uniform(1, 9.9) and Y|X = x~Normal(1.4, x^2)
What is Cov(X, Y) equal to?
What I tried was:
E[XY] - E[X]E[Y]
Where E[X] = 5.45 and E[Y] = 1.4
But for E[XY] I'm a bit clueless. I've considered:
$$ \int_1^{9.9}\int_{-\infty}^{\infty} xx \frac{1}{9.9-1} \frac{e^-\frac{x^2}{2}}{\sqrt{2\pi}} dxdx = 1$$
or is E[XY] more like:
$$ \int_1^{9.9}\int_{-\infty}^{\infty} xy \frac{1}{9.9-1} \frac{e^-\frac{(y-1.4)^2}{2x^2}}{\sqrt{2\pi x^2}} dydx = 7.63 $$
and now I realized that 7.63 is already equal to 5.45*1.4 so that would result in 0...
Answer: Your calculation is right. $\mathbb E(X\cdot Y)=\mathbb E_X(X\cdot \mathbb E_{Y|X}[Y])=7.63$
You´re right as well that $\mathbb E(X)\cdot \mathbb E(Y)=7.63$. That means that $Cov(X,Y)=0$.
This is a nice example that a covariance of $0$ does $\texttt{not}$ necessarily imply independence.
Answer: By the law of total expectation,
$$E[XY]=E\left[E\,[XY\mid X]\right]=E\left[XE\,[Y\mid X]\right]$$
, where you are given that $E\,[Y\mid X]=1.4$ (which also implies $E\,[Y]=1.4 $ by the same result).
And note that by this theorem,
$$E\,[XY]=\iint xy f_{X,Y}(x,y)\,\mathrm{d}x\,\mathrm{d}y$$
, where $f_{X,Y}(x,y)=f_{Y\mid X=x}(y)f_{X}(x)$ is the joint density of $(X,Y)$.


Change node author with Rules

Question: I have field in content type called field_new_author which is User reference field.
I need to make a Rule to change Node author field to match value in field_new_author.
I tryed this solution: Change node author on node save with rules
But I'm getting database error:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4141-0-all' for key 'PRIMARY': INSERT INTO {node_access} (nid, realm, gid, grant_view, grant_update, grant_delete) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 4141 [:db_insert_placeholder_1] => all [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => 1 [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => 0 ) in node_access_write_grants() (line 3440 of /home2/test/modules/node/node.module).
I also tryed different setups in Rules but could not find anything that would work.
Answer: I assume you are using D7 with Entity Reference.  You should be able to do this with stock Rules, without any PHP code:

Create a new rule
Event, select "After updating existing content"
Condition, select "Content is of type" to match whatever content type it is.  This will qualify the fields so that you can use them later
Condition, select some other limiting condition so that you don't target every single node with updated content.  You could, for example, do a data comparison to check if the content has a given taxonomy term
Action, select "Set data value".  Your target should be node(updated content):author.  Your new value should be node(updated content):field-new-author
Comment: It only change the node uid in the `node` table not in the `node revision` table.
Answer: I'm not that experienced with the Rules module so I can't help you in that regard. However you could create your own module and implement this hook:
hook_node_presave
This hook allows you to modify the node object before it is saved or updated within the database. You'll then be able change the Node author value to the value of your User reference field within your own module. Remember to check the content type of the node first to ensure values are only changed on your intended nodes.

Change node author with Rules


Firestore disconnect

Question: After disconnecting the Internet, the listener "no internet" is triggered. After the connection is resumed, the "no internet" function also works. Success does not work, only after restarting the application. How to fix?
Answer: As per official documentation regarding the use of transactions in Cloud Firestore:

Transactions will fail when the client is offline.

With other words, you cannot use transactions when you are offline.
Also keep in mind that, when there is a loss of network connectivity (there is no network connection on user device), neither onSuccess() nor onFailure() methods are triggered. This behavior makes sense, since the task is only considered completed when the data has been committed (or rejected) by Firebase servers.
If you want to check whether you're receiving data from the server or the cache, use the fromCache property on the SnapshotMetadata in your snapshot event. If fromCache is true, the data came from the cache and might be incomplete. If fromCache is false, the data is complete and current with the latest updates on the server.
Comment: You currently don't have any control over how the Firestore SDK manages its connections.

Most code that performs retries do so with an [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) algorithm.  This prevents the retries from happening so quickly that it impairs the performance of the host app, and also possibly consuming too much of the user's data plan.  However, this means that it may take some time to regain the connection.
Comment: It is clear. But why does not the connection resume after the connection is lost?
Comment: Recovery takes place within 30-45 seconds. This is normal?
Comment: Yes. I experienced 10 seconds, even up to a minute.
Comment: You're welcome @ИльяЛитвинцев ! Cheers!

Firestore disconnect


I can't display extended values of my user model

Question: On this case my problem arise displaying extended values of my user model in my index.html
here my models.py
from django.db import models
from django.contrib.auth.models import User

def url(self,filename):
    ruta = "MultimediaData/Users/%s/%s"%(self.user.username,filename)
    return ruta

class userProfile(models.Model):

    user = models.OneToOneField(User)
    photo = models.ImageField(upload_to=url)
    telefono = models.CharField(max_length=30)
    email = models.EmailField(max_length=75)

    def __unicode__(self):
        return self.user.username

my index.html:
{% extends 'base.html' %}
{% block title %} Inicio - Bienvenidos {% endblock %}
{% block content %}

Dracoin, el portal que facilitará tu vida

{% if user.is_authenticated %}

Bienvenido {{ user.username }}

    {% if user.get_profile.photo %}

    {% endif %}
    {% if user.get_profile.telefono %}

Numero Tel: {{user.get_profile.telefono}}

    {% endif %}
{% endif %}
{% endblock %}

I don't have problem managing that information in my admin panel but i cant view that information in my index. I believe the mistake is in {% if user.get_profile.xxxx %} calling but I cant solve it.
apologizeme in advance if I overlook something.
Thanks!!
Comment: What version of django are you using?
Answer: get_profile() was deprecated in django 1.5, and removed in django 1.7.
Try {{ user.userprofile.xxxx }} instead.


Adding text to GMSMapView without resizing

Question: I need add some text strings to my GMSMapView, can do it like in solution of previous asked question here (get UIImage from UILabel then add GMSGroundOverlay with that image as icon to GMSMapView), but I need add text, which will not resize when user change zoom of the map.

You can see when user changes zoom of the map, my label changes font size too, but i need add label which will be looks same way as street names - without resizing when zoom. How to make it?
Comment: Hello, did you find the solution ?
Comment: Nope, solution was not found :(
Comment: How did you set "Job" text to GMSGroundOverlay center ? I have convert my lable to image and set as GMSGroundOverlay icon. But it will not set in center of GMSGroundOverlay.
Answer: With your requirement, Why don't use GMSMarker instead of GMSGroundOverlay ?
This code works for me
- (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Adding label marker
UILabel *label = [UILabel new];
label.text = @"Job";

label.opaque = NO;

label.font = [UIFont fontWithName: @"Arial" size: 14];
label.textColor = [UIColor blackColor];
label.backgroundColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentCenter;

label.layer.borderWidth = 2.0;
label.layer.borderColor = [UIColor blackColor].CGColor;
label.layer.masksToBounds = true;

label.layer.cornerRadius = 50;
label.frame = CGRectMake(0, 0, 100, 100);

GMSMarker *title = [GMSMarker markerWithPosition:centerPosition];
title.icon = [self imageWithView:label];
title.map = mapView;

Comment: Hello. The question is tagged "Swift", not Objective-C. Please post the Swift version so that OP can use your solution. Thank you.
Answer: Based on @Bùi Đức Khánh's answer above, Swift4
import UIKit
import CoreLocation
import GoogleMaps

extension GMSMarker {
    convenience init(position: CLLocationCoordinate2D, text: String, backgroundColor: UIColor? = .white) {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        label.isOpaque = false
        label.font = UIFont(name: "Arial", size: 14)
        label.textColor = .white
        label.backgroundColor = backgroundColor ?? .white
        label.textAlignment = .center
        //label.layer.borderWidth = 2.0
        //label.layer.borderColor = UIColor.black.cgColor
        //label.layer.masksToBounds = true
        //label.layer.cornerRadius = 50
        label.text = text
        self.init(position: position)
        icon = UIImage.imageFromView(label)
    }
}

 extension UIImage {
    class func imageFromView(_ view: UIView) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        view.layer.render(in: context)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

Usage:
let marker = GMSMarker(position: CLLocationCoordinate2DMake(40.1, 25.5),
                            text: "Lorem ipsum",
                            backgroundColor: .green)
marker.map = self.mapView


HTML Content DIV Frame over image not working

Question: I've been trying to make a simple DIV website based off of ONE Image, and it's just not working. I've aligned the buttons, in which the buttons do work, however the Content does not show over the content box area, what am I doing wrong?
The Content box's positioning is under #frame1 in the code. The javascript for the changeframe is located in the  tag.

HERE CONTENT FOR home

HERE CONTENT FOR about

HERE CONTENT FOR shop

HERE CONTENT FOR shout

HERE CONTENT FOR honor

        <map name="map">
          <area shape="rect" coords="273,740,356,768" onclick="changeframe('home','frame1')">
          <area shape="rect" coords="360,740,445,768" onclick="changeframe('about','frame1')">
          <area shape="rect" coords="450,740,535,768" onclick="changeframe('shop','frame1')">
          <area shape="rect" coords="539,740,624,768" onclick="changeframe('shout','frame1')">
          <area shape="rect" coords="630,740,715,768" onclick="changeframe('honor','frame1')">
       </map>

Answer: I see two issues with your code
this condition is falsy which why your tag is not replaced with the new html
$("#layoutimg").attr("src") ==
btree.decode(
"aHR0cHM6Ly91c2VyaW1hZ2VzLWFrbS5pbXZ1LmNvbS91c2VyZGF0YS8wMi84OS83MC83OC91c2VycGljcy9TbmFwX2Jia3hTUVBucHk4OTcxMTY5OTgucG5n"
)

if you comment the above condition it will work but your css push it way down and text is white that's why you don't see it so something roughly like this should work.
https://codesandbox.io/s/zen-volhard-7nt5d?file=/index.html
I made the text red so it is more visible for you to debug
Comment: Seemed to fix that issue, however now I have a new issue. I put the style, and the first script into their own seperate css/JS files and linked them, upon doing so it broke the script/style ???? But as soon as I put those back in the index.html instead of shortlinking them it works again.
Comment: Here is the modified version with css and JS as external files https://codesandbox.io/s/zen-volhard-7nt5d?file=/index.html
Comment: I figured out my issue. I was missing some of my #'s for the style.css Oops. Thank you so much!


Questions about :first-of-type:before:hover

Question: So I am playing around with someone's codepen and wanted to add some arrows from fontawesome to the code.
I was able to add the arrow with the following code:
<code>.button:first-of-type:before {
 content: "\f100";
 font-family: fontAwesome;
 color: #000;
 font-size: 1em;
 z-index: 10;
 margin: 20px 0 0 -75px;
 position: absolute;
}
</code>
This works, but when someone hovers the button, I want the before css to be display none.
I have tried the following but it doesn't work:
<code>.button:before:hover:first-of-type {
 display: none;
}
</code>
and
<code>.button:first-of-type:before:hover {
display: none;
}
</code>
and
<code>.button:first-of-type:hover:before {
display: none;
}
</code>
I have also tried to add !important but nothing works.
Here is a link to the codepen: http://codepen.io/bskousen/pen/tgJdH
Comment: `.button:first-of-type:hover:before` [seems to work](http://jsbin.com/vapeqa/1/watch?html,css,output).
Comment: `.button:first-of-type:hover:before` works for me http://jsfiddle.net/19uuwp27/
Comment: Also are you sure `first-of type` is the selector you want?  http://jsfiddle.net/19uuwp27/2/
Comment: Not sure why it wasn't working, but you guys are correct, it does work. Thanks!
Answer: Your solution might be
<code>.button:hover::before{
    content: "";
}
</code>
So instead of hiding the :before, simply remove it.

One more thing, it looks like when you hover the left arrow, the upper button activates, you might want to check your code.
Comment: I went with this solution, so thanks for your help. And yes you were correct, the code was screwed up, I was position it as the left button, when I was targeting the top button.
Comment: Please keep in touch, I really like that design! ;)
Answer: This is the right one
<code>.button:first-of-type:hover:before {
  display: none;
}
</code>


How to construct orthogonal tangents to an ellipse

Question: Given an ellipse, we want to draw a set of tangents to it, which are orthogonal to each other.
We are looking for a synthetic way; not through algebra or trigonometry.
I know how to construct one tangent:
Given any point $P$ on the ellipse, we connect it with the two foci, say $F_1$ and $F_2$ and then we bisect angle $F_1PF_2$. The bisector is the "normal". Then we draw an orthogonal line to the bisector, from point $P$f and this is our tangent.
I am trying to think of a way to construct another tangent, orthogonal to it.
Clearly the normal of the second tangent will be orthogonal to the 1st normal.
We are looking for the single point $Q$ (or maybe 2 points), for which, the 2nd normal will bisect angle $F_1QF_2$ but I can't think of any way to construct it.
Any ideas? Thank you!
Comment: Sorry but "which are vertical to each other" doesn't mean anything... Please correct it. Maybe you wanted to say "orthogonal" ?
Comment: https://en.wikipedia.org/wiki/Director_circle
Comment: @JeanMarie sorry but English is not my mother tongue. I corrected it.
Comment: I have changed in your question all remaining adjectives "parallel" into "orthogonal" which is the most appropriate term for 2 lines making a 90° angle.
Answer: There is a simple way to construct a second tangent, perpendicular to the first one you constructed at $P$. Let the normal at $P$ intersect again the ellipse at $N$ and let $M$ be the midpoint of $PN$. The line passing through $M$ and the center $O$ of the ellipse will then intersect the ellipse at two points $Q$ and $Q'$, with the property that the tangents at both points are parallel to $PN$, and hence perpendicular to the first tangent.
As I wrote in a comment, the intersections between the tangents at $Q$ and $Q'$ and the tangent at $P$ lie on the director circle of the ellipse.
Comment: Brilliant solution! Is there a proof?
Comment: If the Wikipedia proof I linked is not enough, I could try to provide another proof.
Answer: This being my first contribution to the forum, let me hope that I got the formatting and importing procedures correct.
I have constructed a tangent through point P just as you said, bisecting ∠F₁PF₂, and constructing the tangent perpendicular to that bisector.
Through center O I have constructed a diameter perpendicular to the tangent line at P. It meets the ellipse at Q, and there I have constructed another tangent line using the same angle bisection method.
Through O I have constructed a second diameter, parallel to the tangent at Q. This diameter meets the ellipse at points A and B.
Lines OQ and AOB, are conjugate diameters. I have constructed lines through A and B, both parallel to OQ, which makes them tangent to the ellipse. It also makes them perpendicular to the tangent through P.
ellipse construction


Is there a SQL Server Management Studio option controlling parameters assignment?

Question: I am not able to execute a lot of T-SQL statements due to various errors. The statements are basically some CREATE OR ALTER statements of routines. I guess I have turned on/off option of SQL Server Management Studio to force these errors because everything was working OK earlier.
For example the following code:
DECLARE @TEST1 DATETIME2 = SYSDATETIME();
DECLARE @TEST2 BIT;

gives this:

If I execute only one of the lines or the following:
DECLARE @TEST1 DATETIME2
SET @TEST1 = SYSDATETIME();
DECLARE @TET2 BIT;

everything is OK.
This cannot be due to SQL Server version/setting or hardware, because the query is working fine on other laptop.
I was using SSMS 18.0, then updated to SSMS 18.1 and nothing change.
Has anyone idea what is causing this?
Comment: Are you sure you don't have some other hidden characters on the machine where this fails. I don't see how you would get that error from the code posted.
Comment: The only time I know of that SSMS will mess with the command you input is if you've configured it to use (and respect) Always Encrypted, where it will attempt to transparently translate statements using literals into parameterized ones with encryption, but that should still not have any effect on the code shown here. As an "out of the box" thing, try saving your commands to a new file, verifying that it looks like what you expect, then re-opening that to make sure the editor isn't lying to you.
Comment: can't reproduce this (not that I thought I could), but I've tested on 3 different environments, just to be sure.
Comment: Is there more SQL below that, Perhaps you have some dynamic SQL that is generating the error. SQL run in a dynamic statement has its own lines numbers. [DB<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=fbd090b429bc2c07cf741aa7610ccf47) for example says the error is on line "3", but that's line 3 of the dynamic statement, the actual error is on line 6 of the whole statement (which tries to assign the value of `@TEST1` to the variable `@t`; which I declared as a `bit`). The error being on line 3 of the whole statement makes no sense, as (like your statement) it is blank.
Comment: @gotqn so if you highlight those *2* lines and execute the highlighted SQL it says the error is on line 3? That seems very unlikely, as Line 3 wasn't reached.
Comment: @SeanLange If you mean hidden like ASCII unit separator for example - I am sure there are no such. I have copy the `.sql` files to other machine and execute it without changing anything. Anyway, I guess I will try to find this in the hard way.
Comment: Have to agree, I can't replicate this on SSMS 18.1 either, and I made sure I copy and pasted the SQL you had, rather than transcribing it, just *incase* there was something off. I note as well that the error specifically states the error is on line 3, which according to your image, is blank.
Comment: What happens if you highlight only the two lines in your screenshot and execute?
Comment: Larnu - strange, yes. Tab Alleman - same error. OK, guys give me some time to examine the options.
Comment: Yeah this is a weird one. Please comment back if you figure out what was causing this. I am curious.
Comment: Works fine on my machine as well. As per @Larnu, try highlighting only the script you shared in your question and execute?
Comment: @JeroenMostert Yes, man. That was the issue indeed.
Answer: It was caused by this option:

We are not using always encrypted, so I guess I have turned it on with some short-key or other way (damn me). If you enable this, open new query window and paste the code above, you will be able to reproduce the issue.
There might be something with how Parameterization is working with SSMS when this is ON because some of the statements are not support.


Closed-form value for $\min_{x^T\Sigma x \le 1}\|x\|_1 - x^Ta$

Question: Let $a \in \mathbb R^n$ and $\Sigma$ be a positive definite matrix of size $n$.
Question
What is the closed-form value of
$$\min_{\|x\|_\Sigma \le 1}\|x\|_1 - x^Ta,
$$
where $\|x\|_\Sigma := \sqrt{x^T\Sigma x}$ is the norm induced by by the inner product $(x, y) \mapsto x^T\Sigma y$ ?
Comment: Is there a compelling reason to believe such a closed form should exist?
Comment: Changed argmin ==> min.  About a compelling reason, the limiting case $\Sigma \rightarrow 0$ corresponds to the convex conjugate of $x \mapsto \|x\|_1$ evaluated at $a$. This evaluates to the indicator function of the $\ell_\infty$ unit ball. My question is just a "slight twist" to this problem.
Comment: This should be possible if $\Sigma$ is diagonal. Non-diagonal 'twists' tend to make this impossible.
Comment: A solution to a non-trivial special case, e.g the diagonal case $\Sigma = \text{diag}(\sigma_1^2,\ldots,\sigma_n^2)$, of the problem should already be very interesting. Please don't hesitate to write something down :)
Comment: Please try using Lagrange multiplier:  $L=\sum x_j - \mathbf{x}^T \mathbf{a} - \lambda \mathbf{x}^T \Sigma \mathbf{x},$ and take the partial derivatives and set equal to zero:  $0=\frac{\partial L}{\partial x_j}, \quad 0=\frac{\partial L}{\partial \lambda}.$
Comment: Thanks to the helpful comments. Below, I've put together a solution which looks like the "best thing possible".
Answer: It has been suggested in the comments that the solution value might not be analytically expressible in general, but that there is some hope, when the matrix $\Sigma$ is diagonal. I'm going to provide a solution hereunder. Also, I'm bad at using Lagrange multiplies (e.g I always screw up the signs, etc.). I'm going to attempt a more "synthetic" solution.
Now, using the dual representation of the $\ell_1$-norm, one has

$$
\begin{split}\alpha:=\min_{\|z\|_\Sigma \le 1} \|z\|_1 - z^Ta &= \min_{\|z\|_\Sigma \le 1}\max_{\|w\|_\infty \le 1}z^Tw-z^T a =\max_{\|w\|_\infty \le 1}\min_{\|z\|_\Sigma \le 1}z^T(w-a)\\
&=\max_{\|w\|_\infty \le 1}-\left(\max_{\|z\|_\Sigma \le 1}-z^T(w-a)\right)=\max_{\|w\|_\infty \le 1}-\|w-a\|_{\Sigma^{-1}}\\
&=-\min_{\|w\|_\infty \le 1}\|w-a\|_{\Sigma^{-1}},
\end{split}
$$

where I've used Sion's minimax theorem to interchange min and max.
The above expression for the optimal objective value $\alpha$ is unlikely to be computable analytically in general, due to the non-separability of the objective (even though the constraint is perfectly separable as a product of 1D constraints).

In any case, it follows from the above display that $\alpha \le 0$, with equality iff $\|a\|_\infty \le 1$.

Exact formula for diagonal $\Sigma$
In the special case where $\Sigma=\text{diag}(\sigma_1,\ldots,\sigma_2)$, the square of the optimal objective value $\alpha^2$ can be separated as

$$
\alpha \le 0,\;\alpha^2 = \sum_{i=1}^n\min_{|w_i| \le 1}\sigma_i^{-2}(w_i-a_i)^2 = \sum_{i=1}^n\sigma_i^{-2}\begin{cases}(a_i+1)^2,&\mbox{ if }a_i \le -1,\\ 0,&\mbox{ if }-1 < a_i \le 1,\\ (a_i-1)^2,&\mbox{ if }a_i > 1,\end{cases}
$$

which is indeed an analytical formula, albeit a very "hairy" one.
Upper and lower bounds for general $\Sigma$
Let $\sigma_n \ge \ldots \ge \sigma_2 \ge \sigma_1 > 0$ be the eigenvalues of $\Sigma$. Then, one has
$$
\sigma_n^{-1}\|w-a\|_2 \le \|w-a\|_{\Sigma^{-1}} \le \sigma_1^{-1}\|w-a\|_2.
$$
Thus one has the bounds

$-\sqrt{\gamma/\sigma_1} \le \alpha \le -\sqrt{\gamma/\sigma_n}$,
where $\gamma := \sum_{i=1}^n\begin{cases}(a_i+1)^2,&\mbox{ if }a_i \le -1,\\ 0,&\mbox{ if }-1 < a_i \le 1,\\ (a_i-1)^2,&\mbox{ if }a_i > 1.\end{cases}$

Moreover, if $\|a\|_\infty > 1$, then it isn't hard to see that $\gamma \le n(\|a\|_\infty-1)$ (see details below), from where $\alpha \ge -\sqrt{\gamma/\sigma_1} \ge -\sqrt{n/\sigma_1}(\|a\|_\infty-1)$, which corresponds to a bound which has been observed by someone in the comments. However, by construction, this bound is potentially very loose.

Note that $a_i \le -1 \implies (a_i + 1)^2 \le (\|a\|_\infty - 1)^2$
and similarly $a_1 > 1 \implies 0 \le (a_i - 1)^2 \le (\|a\|_\infty-1)^2$. Thus $\gamma \le n(\|a\|_\infty-1)$.
Comment: Writing KKT conditions with the subdifferential variant, one sees that if $\|a\|_{\infty}\leq 1$, the min is $0$, and if $\|a\|_{\infty}> 1$, the min is $\geq -(\|a\|_{\infty}- 1)\sqrt{\frac{n}{\lambda_1}}$ where $\lambda_1$ is the smallest eigenvalue of $\Sigma$. I don't know how tight the last bound is.
Comment: what's the formal justification for switching $\min$ and $\max$ ?
Comment: Sion's minimax theorem https://en.wikipedia.org/wiki/Sion%27s_minimax_theorem.
Comment: Yes, your bound holds, but is very loose. It is a simplification of a tighter but slighter more complicated bound. See edit to my answer above.


The Observer seems not to be executed whenever the observable is changing its value

Question: The observer seems to initialize the subscription just fine. However, when the value of the layer changes the observer doesn't execute the function it supposes to. Am I missing something?
You can check my repository on github:
https://github.com/stefiHB/ol-angular-ionic
layer-msg.service.ts
import { Injectable } from '@angular/core';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {customMapLayers} from './customMapLayers';

@Injectable({
  providedIn: 'root'
})
export class LayerMsgService {

  private layer = new BehaviorSubject<customMapLayers>(customMapLayers.pwd);

  constructor() { }

  getLayer() {
    return this.layer.asObservable();
  }

  setLayer(mapLayer: customMapLayers) {
    this.layer.next(mapLayer);
    console.log('Setting new value...', this.layer.value);
  }
}

MyButtons.ts
import {LayerMsgService} from './layer-msg.service';
import {customMapLayers} from './customMapLayers';

export class MyButton {

  private layerService: LayerMsgService;
  buttonPWD: HTMLButtonElement;
  buttonOSM: HTMLButtonElement;
  myElement: Element;

  constructor(el: Element) {
    this.layerService = new LayerMsgService();

    this.buttonPWD = document.createElement('button');
    this.buttonPWD.innerHTML = 'pwd';
    this.buttonOSM = document.createElement('button');
    this.buttonOSM.innerHTML = 'osm';

    this.buttonOSM.addEventListener('click', () => this.changeLayer(customMapLayers.osm));
    this.buttonPWD.addEventListener('click', () => this.changeLayer(customMapLayers.pwd));

    el.appendChild(this.buttonPWD);
    el.appendChild(this.buttonOSM);
  }

  changeLayer(l: customMapLayers) {
    console.log('Request for Changing layer...');
    this.layerService.setLayer(l);
  }

}

app.component.ts
import {Component, OnDestroy, OnInit, Renderer2} from '@angular/core';
import {LayerMsgService} from './layer-msg.service';
import {Subscription} from 'rxjs';
import {MyButton} from './MyButton';
import {customMapLayers} from './customMapLayers';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'ObservablesMashup';
  layer: customMapLayers;

  layerSub: Subscription;
  private myBtn: MyButton;

  myText: Element;

  constructor(private layerService: LayerMsgService) {

    this.layerSub = this.layerService.getLayer().subscribe(
      l => {
        if (l) {
          console.log('Getting layer... ', l);
          this.layer = l;
        }
      });
  }

  ngOnInit(): void {
    const el = document.getElementById('map');
    console.log(el);
    this.myBtn = new MyButton(el);
    this.myText = document.getElementById('p1');
  }

  ngOnDestroy(): void {
    this.layerSub.unsubscribe();
  }
}

I tried to use btn.onclick = (event) => {...} but it doesn't seem to fix the problem.
I expect the console to log:
Request for Changing layer...
Setting new value... PWD
Changing Layer... PWD

but the function of the observer is not being executing so this is the actual log when i click on the buttons:
Request for Changing layer...
Setting new value... PWD

Answer: The solution was simple. I was misdirected in the beggining because of the documentation. According to this url:
https://angular.io/tutorial/toh-pt4#provide-the-heroservice
"When you provide the service at the root level, Angular creates a single, shared instance of HeroService and injects into any class that asks for it. "
I thought that the LayerMsgService  was shared among all the classes. However, I had to give it as an argument in the MyButtons class.
layer-msg.service.ts
constructor(el: Element, layerMsgService : LayerMsgService  ) {
// code...
}

Answer: The function setLayer from the service is in charge of emitting new values.
It's called in the controller.changeLayer function, which itself is called on button clicks, defined a bit earlier.
if the stream doesn't make a new event, it probably means that the buttons aren't doing their job.
Seeing that you use addEventListener, i would first tell you to change to btn.onclick = (event) => {...} to try it.
if it still doesn't work, try seeing if button clicks work, and if they don't, it means you either don't click on the right ones, or you are outisde of Angular's context (see NgZone)
Comment: ```btn.onclick = (event) => {...}``` doesn't seem to fix the problem. But either way the buttons I think they work(?). The ```controller.changeLayer``` is been executing.

Also the setLayer() in map.service.ts is been executed, because it logs in the console the message: "Setting new value...' and prints the correct value.
Comment: @skassi could you provide a [mcve] of your issue ? It's hard to help you without any evidence that it doesn't work ... Other than that, I don't see what's wrong !
Comment: I tried that before posting a question here but I couldn't make a minimal reproducible example. However I will give it one more try. I also posted my GitHub repository with that particular project, so you can download it if you have the time. Anyway, I will try again the minimal reproducible example. Thanks.
Comment: @skassi I'm on a corporate computer, I am limited by a firewall (and we use bitbucket ... Yay). For a [mcve], you can mock most of your code, as long as the issue is reproduced. If you can't manage to make it, then it probably means you have a typo/error somewhere ! So go from your [mcve], and rebuild your components/services so that they work.
Comment: I've tried to provide a more minimal reproducible example. Same problem with the observer in the ```app.component.ts```


GTM + Gravity Forms Goal tracking in Google Analytics

Question: I have a Gravity Form with a text confirmation page, not a redirect confirmation. I would like to track this form through Google Tag Manager to display a goal conversion in Google Analytics (Universal Analytics).
I've followed the steps here: http://www.notesonclick.com/blog/gravity-form-event-tracking-via-tag-manager/
No conversions are being recorded. However when using GTM-debug mode, all the triggers are firing, even the gform.submit.success tag is being fired after clicking the submit button.
Could someone please help?
Answer: We've had the same issue. The only way we've been able to get GTM to record conversions is to remove validation. We'd rather it validate, but we haven't found any other workarounds.
Answer: I have implement that code in multiple site and it is working fine, Since you are not getting conversion then there might be issue with form Goal Creation in google analytics. or some time i have noticed this things happening when google analytics have been implement directly on the site and event tracking setup through tag manager..
if you still need some more help leave comment in comment box of same blog
Answer: I saw the excellent and elegant solution by Dinesh but was not able to implement it on the site I was working with. I put a hack together that work correctly. For detailed instructions, please see here.
http://www.albanyanalytics.com/2018/03/gravity-form-tracking-with-google-tag.html
Comment: Please see here: https://meta.stackexchange.com/a/8259/266197 why link only answers are not great.
Comment: copy the information here kills all my pictures so the link works best here


Cálculos no SELECT do mySQL vs. cálculo no script

Question: Digamos que eu queira calcular as porcentagens de registros numa tabela mySQL para determinadas informações, como, por exemplo, usuários até 20 anos, de 21 a 30, e acima de 30 anos, e essa tabela possui uns 100 mil registros.
Em termos de performance, é melhor fazer os cálculos direto no SELECT ou receber as informações do banco de calcular no script PHP ou ASP, por exemplo?
Comment: com certeza no mysql porque ao contrario do php ele nao vai precisar interpretar o codigo antes de fazer o calculo.
Comment: também acho. Mas não tenho conteúdo para formular uma resposta =]
Comment: Usar as funções do MySQL é mais rápido do que usar o código do PHP para fazer as mesmas coisas, isso dito nesse link. PHP vs MySQL Performance - em ingles  https://onextrapixel.com/mysql-has-functions-part-5-php-vs-mysql-performance
Comment: Fazer o cálculo diretamente no SELECT será mais rápido porque os dados só serão percorridos uma vez. Se você quiser fazer o cálculo no script você terá que copiar todos os dados para a memória do programa e então percorrê-los, ou seja, os dados serão lidos duas vezes. Além disso, você vai consumir muito mais memória para ter o mesmo resultado.
Answer: Usar as funções do MySQL é mais rápido do que usar o código do PHP para fazer as mesmas coisas, isso dito nesse link abaixo.
PHP vs MySQL Performance - em ingles
PHP vs MySQL Performance - em portugues (Google tradutor)
============== caso a pagina do link acima seja removida temos ==============
Sintam-se a vontade para corrigir a tradução feita pelo Google tradutor
Metodologia de Testes
Não há sentido em executar testes de desempenho sem algum tipo de método que tente dar resultados tão precisos quanto possível, e que tente levar em consideração quaisquer leituras anômalas. Então aqui está o exemplo:
Cada teste foi executado dentro de seu próprio script PHP para ser chamado pelo navegador. Como o código do computador é executado tão rápido, não é possível executar o código apenas uma vez para obter medições decentes. Então eu  decidi executar o código de cada teste 10.000 vezes dentro de um loop FOR .
Antes e depois de cada teste, registrei variáveis chamadas $start e $end e atribui a elas valores da função microtime() do PHP, que retorna um timestamp do Unix incluindo microssegundos. Sem a parte de microssegundos, o tempo não seria preciso o suficiente. O tempo gasto para as 10.000 execuções do código seria, portanto, igual a $end - $start .
A estrutura de cada teste:
    $conn = mysqli_connect(...); //connect to the DB

    ob_start(); //buffer the output, we don't actually care about seeing it

    $start = microtime(true);

    for($i = 0; $i < 10000; $i++) //loop 10K times
    {
        //test code here
    }

    $end = microtime(true);

    ob_end_clean(); //get rid of the buffered output

    $time = $end - $start;

Para realmente executar os testes, carreguei os scripts em um dos meus servidores da Web e os executei por meio do meu navegador. Eu corri cada teste 10 vezes, em três momentos diferentes do dia, para conter quaisquer leituras anômalas causadas por coisas como processos em segundo plano que compartilhavam o tempo de CPU ou disco. Uma média de todos os tempos de execução foi então tomada.

Teste 1 - Calculando uma pontuação média

Em uma parte anterior, olhei para usar algumas das funções do MySQL para recuperar dados de uma tabela de alunos. Eu usei uma tabela de teste semelhante dessa vez e calculei a pontuação média do exame.

Quando o MySQL calcula a média

    $sql = "SELECT AVG(score) as average_score FROM school";

    $result = mysqli_query($conn, $sql);

    $row = mysqli_fetch_assoc($result);

    echo $row['average_score'];

Simples sim? O MySQL faz todo o trabalho na consulta, então tudo que o PHP precisa fazer é ecoar o resultado.
Isso levou em média 2,14 segundos para 10.000 iterações.
No PHP, no entanto, as coisas não eram tão simples.

Quando o PHP calcula a média

O código de teste do PHP para calcular a pontuação média ficou assim:
    $sql = "SELECT score FROM school";

    $result = mysqli_query($conn, $sql);

    $total = 0;

    $num = mysqli_num_rows($result);

    while($row = mysqli_fetch_assoc($result)) {
           $total += $row['score'];
    }

    echo ($total / $num);

Uma consulta um pouco mais simples, mas o código tinha que percorrer todas as linhas retornadas e totalizar todas as pontuações, depois dividir esse número pelo número de linhas via mysqli_num_rows para obter a média.
Isso levou 5,65 segundos para executar 10.000 iterações.

Resultado final teste 1

Portanto, para essa instância, o MySQL era 4,76 vezes mais rápido que o equivalente ao PHP.
A utilização da função AVG() do MySQL foi 2,64 vezes mais rápida que o código PHP equivalente, por isso é mais clara e mais rápida.
Sobre o cache de consulta?
O teste do AVG() foi executado com o cache de consulta do MySQL desabilitado, e fiquei curioso para ver se teria algum impacto nos resultados se ele estivesse ativado.
Eu assumi que os testes do MySQL terminariam ainda mais rápido, porque o cache de sua consulta significaria que nenhum cálculo do AVG() seria necessário e eu não estava errado.
Com o cache de consulta ativado e configurado para 32MB (provavelmente o overkill), o teste do MySQL demorou 0,91 segundos e o teste do PHP levou 4,27 segundos . Então desta vez o MySQL foi 4.7 vezes mais rápido que o PHP.

Teste 2 - formatar uma data

Na Parte 1 - Funções de Data e Hora , eu olhei as funções que o MySQL fornece para brincar com datas e horas, em particular a função DATE_FORMAT() , que surpreendentemente produz strings de data formatadas de maneira similar à date() do PHP date() função.
O objetivo do código nesse teste era pegar o campo de data formatada pelo MySQL (AAAA-MM-DD) de cada linha e enviá-la como uma string no formato DD / MM / AAAA .

Quando o MySQL formata as datas

O código de teste do MySQL ficou assim:
$sql = "SELECT DATE_FORMAT(rating_date, '%D/%M/%Y') AS rating_date FROM ratings";

$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_assoc($result)) {
        echo $row['rating_date'] . ' ';
}

Esse código levou em média 8,30 segundos para executar 10.000 iterações .
Para este teste, usei a tabela de classificações de vídeo da Parte 4, preenchida com muitos dados de amostra encantadores usando o procedimento armazenado personalizado que criei.

Quando o PHP formata as datas

O código PHP foi mais complicado desta vez, por causa da necessidade de primeiro transformar a data do MySQL em um timestamp que poderia ser usado pela função date() do PHP.
$result = mysqli_query($conn, "SELECT rating_date FROM ratings");

while($row = mysqli_fetch_assoc($result)) {
    $timestamp = strtotime($row['rating_date']);

    $theDate = date('d/m/Y', $ timestamp);

    echo $theDate . ' ';
}

Achei o resultado desse teste bastante surpreendente: o código PHP levou 39,48 segundos para ser executado 10.000 vezes.

Resultado final - Teste 2

Portanto, para essa instância, o MySQL era 4,76 vezes mais rápido que o equivalente ao PHP.
Com o cache de consulta do MySQL habilitado
Mais uma vez eu decidi executar os testes novamente com o cache de consulta habilitado e definido para 32MB.
O teste do MySQL levou 6.25 segundos e o teste do PHP levou 35.85 segundos , o que significa que o MySQL foi 5.74 vezes mais rápido.

----------  Conclusão

Usar as funções do MySQL foi mais rápido do que usar o código do PHP para fazer as mesmas coisas. Eu tinha certeza que chamar uma função MySQL seria mais rápido do que fazer um loop em um conjunto de resultados no PHP e potencialmente usar múltiplas funções do PHP para atingir o mesmo fim.
Uma coisa a ter em mente, no entanto, é que, embora o MySQL tenha sido até 5,7 vezes mais rápido do que o PHP, isso foi feito por dez mil vezes o mesmo código.
Comment: Show de bola! Era isso que eu precisava.


How can I get my array to work when assigning non-sequential numeric indexes in jQuery?

Question: I have an XML file dynamically created from a database where each item has both an id and name. In the following syntax:
<item>
   <id>1</id>
   <name>FirstName</name>
</item>

... and so on ...
I am trying to use these values for a jQuery autocomplete, where the ID will be submitted via form when the name is selected from the autocomplete.
I've tried the following block of code (executed from a button within a form):
function listItems(){
    var dataString = "";
    dataString += $("form#getItemsForm").serialize();

    $.ajax({ type: 'GET', url: 'myXML.xml', dataType: 'xml', success: function(xml){
        var myList = new Array();
        $('restaurant', xml).each(function() {
            var myId = Number($(this).find('id').text());
            var myName = $(this).find('name').text();
            myList[myId] = myName;
        });
        alert(myList);
        $('.listItems').autocomplete({source:myList});
    }});
}

However, this is not working as the IDs begin at 1 and the array is searching for an index of zero so when I alert myList it popups with ,FirstName,SecondName (instead of FirstName,SecondName -- no leading comma).
I've tried making an array of objects but that's a little more cryptic to me as my alert returns [object Object] for each item.
Any pointers would be helpful. Thanks!
Answer: If you want the name attribute to appear as the 'label' of the item and the id to be the 'value', you could do this:
var myList = [];
$('restaurant', xml).each(function() {
    var myId = Number($(this).find('id').text());
    var myName = $(this).find('name').text();
    myList.push({label: myName, value: myId});
});

Relevant excerpt from the documentation:

The local data can be a simple Array
  of Strings, or it contains Objects for
  each item in the array, with either a
  label or value property or both. The
  label property is displayed in the
  suggestion menu. The value will be
  inserted into the input element after
  the user selected something from the
  menu. If just one property is
  specified, it will be used for both,
  eg. if you provide only
  value-properties, the value will also
  be used as the label.
Comment: Hmmm, quoting seems to be broken in Chrome. Can anyone else confirm this?
Comment: Excellent. This is certainly a starting point to where I need to go. Thank you!


Access denied for user anonymous while accessing custom table data

Question: I am trying to fetch custom table result anonymously with services but I am getting
<?xml version="1.0" encoding="utf-8"?>

Access denied for user anonymous
My Code are as follow :
    function custom_data_services_resources() {
  return array(
    'getdata' => array(
      'retrieve' => array(
        'help' => 'Retrieves a data',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
            'name' => 'parameters',
            'type' => 'array',
            'description' => '',
            'source' => 'param',
            'optional' => TRUE,
            'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

I tried with "X-CSRF-Token" also But no luck :(
Any help appreciated
Comment: I'd recommend using the `actions` variable in your array as described here: http://docs.drupalgap.org/7/Services/Create_a_Custom_Service - The CRUDI approach you are using is typically reserved for custom Entity Types.
Answer: Following up with an answer from our comments...
Here's an example custom service resource:
custom_data.module
function custom_data_services_resources() {
  $resources = array(
    'custom_data_resources' => array(
      'actions' => array(
        'getdata' => array(
          'help' => t('Gets custom data.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'callback' => 'custom_data_getdata',
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'The data dude.',
              'source' => 'data',
              'optional' => FALSE,
            )
          ),
          'access callback' => 'custom_data_access',
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'access arguments' => array('access user profiles'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );
  return $resources;
}

custom_data.resource.inc
function custom_data_getdata($data) {
  return array('foo' => $data['bar']);
}

function custom_data_access($permission) {
  return user_access($permission);
}

After that, just enable the custom resource under your endpoint's configuration and clear all of Drupal's caches. Then you can make a POST to:
?q=[my-endpoint]/custom_data_resources/getdata.json
If you need to send along custom arguments, I usually recommend a single array parameter, that way you can easily expand upon it and send as many variables/properties you need along with the payload:
{ "bar": 123 }
Which will then return to you:
{ "foo": 123 }
Don't forget to attach a header to your request with a name of X-CSRF-Token and value retrieved from: ?q=services/session/token


How do I parse through a command to receive a specific line with a child process in Node JS

Question: I am trying to get the diskspace of a vm using a child process on node js. This is my code:
const { exec } = require('child_process');

function diskSpace(err, result) {
   exec('df -h',(error, stdout, stderr) => {
     if (error) {
       console.error(`exec error: ${error}`);
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.log(`stderr: ${stderr}`);
})};

diskSpace();

When I receive  run this using node stats.js, which is the name of my file I get the out of the df -h command on my terminal. I want to parse through this info and only get the info for /dev/disk/1:
[node stats.js][1]
[1]: https://i.stack.imgur.com/2vzb1.png but I dont know how. help ?
Answer: Well, you are doing that all correct. The callback function is executed on the child process termination, so stdout is actually a string:
const { exec } = require('child_process');
function diskSpace(err, result) {
   exec('df -h',(error, stdout, stderr) => {
     if (error) {
       console.error(`exec error: ${error}`);
       return;
     }
     console.log(`stdout: ${stdout}`);
     console.log(`stderr: ${stderr}`);
     console.log('>>', /(\/dev\/disk1.*)\/\n/.exec(stdout)[1]);
})};

diskSpace();


Private storage in 2.1?

Question: I need to store files on SD card or other storage. I'd like this storage

to be private (not very critical)
to go away on app uninstall
not to be erased by OS if resources limited

User will take pictures and they will be uploaded to server. I want to be more or less sure that I have those files until they uploaded and then I will delete them on completion.
I thought getExternalFilesDir is what I need but it's only from API 8 and I develop for API 7 (2.1)
What should i use? What is my best option? Also, is there any way to check available space? I need maybe 2-5Mb total..
Answer: Just store it within your apps data folder and you are good.
Comment: How to get reference to that folder? Is it getFilesDir?

Private storage in 2.1?


Perturbation Theory: Approximation of an inverse of a matrix

Question: Does someone know theorems about approximating the inverse of a matrix through perturbation theory? I would be very grateful, if you could recommend me some literature on that.
Because I am reading a paper which says that given a matrix A which is quadratic, real-valued and consists of eigenvectors from another matrix B, then the following approximation holds for A because of perturbation theory techniques (and unfortunately they don't say in detail which techniques):
$A^{-1}=(I+H)^{(−1)} \approx (I-H) $, where I is the identity matrix.
The equality is okay (I calculated it) but I don't understand why the approximation holds.
Comment: What do you mean by "$A$ is quadratic"?
Comment: @GiuseppeNegro I meant that A is a square matrix
Comment: Yes, I had got it. Please see my answer.
Answer: It is just Taylor expansion:
$$\tag{1}(I+\epsilon K)^{-1} = 1-\epsilon K + O(\epsilon^2), $$
so if $H:=\epsilon K$ is small with respect to the identity matrix then you can neglect the quadratic term in the expansion. The proof of (1) is based on Neumann's sums:
$$
(I+\epsilon K)^{-1}= \sum_{n=0}^\infty (-1)^n\epsilon^n K^n, $$
for all $0\le |\epsilon|<|\lambda|^{-1}$, where $\lambda $ is the dominant eigenvalue of $K$, that is, the eigenvalue that is biggest in modulus. The expansion (1) is just the Neumann sum truncated to the first two summands.
Comment: thank you, I was also told that this is a taylor expansion but applying the taylor expansion onto a matrix is very new to me. I calculated the Neuman's sums and got (1) but what is it's relation to the taylor expansion? @Giuseppe Negro
Comment: Please see edit.
Comment: Would you please help me further? I got it that (1) is to be proven with the Neumann sum but I can't see the Taylor expansion (with all the derivatives etc.) in (1) or do you mean that in such cases with matrices Taylor expansion equals the Neumann sum?
Comment: That's just a function of a single variable, $\epsilon$. The Neumann sums contain its complete Taylor expansion.
Comment: I just came across the book "Differential equations: a dynamical systems approach" by Hubbard and West. It contains a short and nice appendix on asymptotic development. Might be a good read for you.
Comment: Thank you very much, for your help and the book recommendation:)
Comment: You are welcome. If this answer was useful, please upvote it. If you think that this answer completely solves the question, please accept it.


What does it mean to "Capture the mouse" in WPF?

Question: On System.Windows.UIElement there is a CaptureMouse() and a paired ReleaseMouseCapture() method.  In this WPF DragDrop sample they call CaptureMouse on MouseDown and release it on MouseUp.  The documentation in MSDN is about as useless as it comes - "CaptureMouse -> Captures the mouse."
In my head before trying it I assumed that it somehow locked the mouse inside the UIElement bounds, but that's clearly not the case when I try it.  From experimenting, it seems to have something to do with responding to events when the mouse is outside of the UIElement, but not wanting to be a cargo cult programmer I don't want to just use it because the example does, I'd like an authoritative description of what it means.
Comment: Think about how you can [resize](https://i.stack.imgur.com/Z7su9.png) (more generally manipulate) an element drawn in a graphic editor. If you want to resize it using the corners of the bounding box, and be allowed to drag a corner outside the canvas, then you need to capture the mouse to continue receiving mouse events when the mouse pointer has left the canvas element.
Answer: From Capture and Uncapture the Mouse on MSDN:

When an object captures the mouse, all mouse related events are treated as if the object with mouse capture perform the event, even if the mouse pointer is over another object.

Only the capturing control receives the mouse events until released.
Capturing the mouse is useful for dragging because all the dragging code can exist in the one control, rather than being spread over multiple controls.
Comment: The most important on capture mouse is **only capturing control** receives mouse events.
Comment: Such a very important information not being mentioned in MSDN
Answer: When it has captured the mouse, a control will receive mouse events even if the mouse pointer is no longer within its bounding area.
Typically, it's used for:

Drag and drop
Buttons (to handle Mouse Up when you put the mouse down on the button and move the mouse before you release the button)
Answer: The Silverlight 2 documentation for it has a more verbose description, I don't know why it isn't a part of the 3.5 documentation page too:

When an object has captured the mouse, that object receives mouse input whether or not the mouse pointer is within its bounding area. The mouse is typically only captured during simulated drag operations.
  ...

It works the same with WPF, and so the reason it is used with DragDrop, is that is how the
it knows to report back to the control being dragged from when the mouse may be outside of that control.  If you comment out the MyCanvas.Capture() and the Capture(Null) (which clears it) then you can no longer drop.
Comment: From the SL documentation you have cited: "The mouse is typically only captured during simulated drag operations." - what is a "simulated drag operation" and how does it differ from a real one? Thanks.


i am creating a kernel module to find the resident pages for all the process

Question: I am creating a kernel module to find the resident pages for all the process. I am using get_mm_rss() and for_each_process but it works
only for init process / first time after first iteration it doesn't    work.
int __init schedp(void){
    struct task_struct *p;

    for_each_process(p) {
        int pid = task_pid_nr(p);
        printk("Process: %s (pid = %d) , (rpages : %lu)\n",
                p->comm, pid, get_mm_rss(p->mm));
    }
    return 0;
}

Results:
BUG: unable to handle kernel NULL pointer dereference at 00000160,

Answer: You're probably getting NULL in p->mm, because some tasks may have invalid mm pointer because they are exiting or don't have mm (because they are kernel-threads, not sure).
When you confused on how to use kernel API, always look for examples inside kernel itself. Quick search with cross-reference tool gave me kernel/cpu.c:
for_each_process(p) {
    struct task_struct *t;

    /*
     * Main thread might exit, but other threads may still have
     * a valid mm. Find one.
     */
    t = find_lock_task_mm(p);
    if (!t)
        continue;
    cpumask_clear_cpu(cpu, mm_cpumask(t->mm));
    task_unlock(t);
}

Note that you need to call find_lock_task_mm() and task_unlock() and explicitly check for NULL.
Comment: thanks,i used all the above code, but the problem is still remains the same ... plz can u solve this for me
Answer: finally it works after creating a function which checks a mm_struct  is valid or not for_each_process
struct task_struct *task_mm(struct task_struct *p){
struct task_struct *t;
rcu_read_lock();
for_each_thread(p, t) {
task_lock(t);
if (likely(t->mm))
goto found;
task_unlock(t);
}
t = NULL;
found:
rcu_read_unlock();
return t;
}


Ubercart Authorize.Net checkout loops back to cart page

Question: I am trying to process an Ubercart order using Authorize.Net. I go through the Checkout and Review pages. When I submit the cart for credit card processing, I get returned to the Checkout page.
The only error I can find is:
    page not found  09/23/2014 - 17:39  cart/sites/all/themes/metroblocks/images/int.png
I think maybe the cart solution has an incorrect relative path somewhere to go to cart/../sites/all....
At one time I tried getting Commerce to work, but couldn't install Kickstart. I deactivated Commerce, but didn't uninstall it. Don't know if there is a conflict between Commerce and Ubercart.
Could someone please explain how I might troubleshoot/resolve this issue?
Using Drupal 7.32, Ubercart 3.7 on a shared hosting server, Apache2.
Comment: This question appears to be off-topic because it is a bugreport for Ubercart's Authorize.Net gateway, and should be reported in appropriate issue queue, not here.
Comment: I have done more troubleshooting in the code and have found that empty($_SESSION['uc_checkout'][$_SESSION['cart_order']]['do_review']) evaluates to true.

It might not be validating the form in uc_cart_checkout_form_validate, but I don't know. How can I find out where it validates the fields?
Comment: Are you using Drupal 3.1?
Answer: I reinstalled Drupal, and it was able to identify the missing image files. It was an issue with Drupal after all. Good thing I don't get dismissed so easily.


Integrating both sides of an equation

Question: Suppose i have
$g(x)=f(x)$
Now, i integrate both sides of the equation
$\int g(x)dx=\int f(x)dx$
I get:
$G(x)+C=F(x)+C$ , where G(x) and F(x) are anti-derivatives.
because G(x) is the area from 0 to x, as F(x), and because g(x)=f(x), then the 2 constants of integration, to me, must be the same. Is it correct ?
Comment: No. There is no reason why the two constants are the same. The interpretation in terms of areas applies only to definite integrals.
Comment: The area under a curve only applies to the definite integral. You've got indefinite integrals.
Comment: No. You just can't state that in general. However, you can assume w.l.o.g that one of the constants is $0$, i.e. $G(x)=F(x)+C$.
Comment: So the antiderivative F(x) is not the area from 0 to x ?
Comment: No, the antiderivative is a completely different thing.
Comment: @MikeR.: completely different ?
Comment: "Completely" is there for emphasis.
Comment: The antiderivative can be seen as the area… from some $x_0$, not necessarily $0$. For this reason, the two constants can differ.
Comment: @MikeR.: I'd rather emphasize with *slightly* different.
Comment: Well, through the fundamental theorem of calculus, right?
Comment: So, can i say that the antiderivative F(x) is the area of f(x) from a certain point $x_{ a}$  to x, and the antiderivative G(x) is the area of g(x) from a certain point $x_{ b}$ , and $x_{ a}$ not need to be equal to $x_{ b}$  ?
Answer: Well, if you say that one function is equal to another function, it means that the result of integration, which is a family of functions that differ only by a constant, of one of the functions will be equal to the result of integration, which is again a family of functions that differ only by a constant, of the other one. That's obviously true because the functions are the same.
Let's say we have two functions $f(x)=x^2+x$ and $g(x)=x(x+1)$. I hope you can see that they are exactly the same function. So, we can write down the following: $f(x)=g(x)$. And we also know that $\int f(x)\,dx=\frac{x^3}{3}+\frac{x^2}{2}+C$. Then, what will $\int g(x)\,dx$ be equal to if we defined $g(x)$ to be equal to $f(x)$? Well, obviously it's going to be the same family of functions: $\frac{x^3}{3}+\frac{x^2}{2}+C$!
$$
\int g(x)\,dx=\int[x(x+1)]\,dx=\int (x^2+x)\,dx=\int f(x)\,dx=\frac{x^3}{3}+\frac{x^2}{2}+C.
$$
The notation $F(x)+C$ just means "a family of functions that differ only by a constant". It's really just a shorthand for this: $\{F(x)+C,C\in\mathbb{R}\}$.
P.S. Don't confuse two different concepts: the definite integral (antiderivative) and the indefinite integral (geometrically, the area under a curve). They're different! There is something that unites them, however, and that something is called the fundamental theorem of calculus.
Comment: So, can i say that the antiderivative F(x) is the area of f(x) from a certain point $x_{ a}$  to x, and the antiderivative G(x) is the area of g(x) from a certain point $x_{ b}$ , and $x_{ a}$ not need to be equal to $x_{ b}$  ?
Comment: You could try and do something like this: $\int_{x_a}^{x}f(t)\,dt=F(t)\bigg|_{x_a}^{x}=F(x)-F(x_a)=F(x)-C_1$ and $\int_{x_b}^{x}g(t)\,dt=G(t)\bigg|_{x_b}^{x}=G(x)-G(x_b)=G(x)-C_2$. But I don't know how you could you use this as a definition of the antiderivative? Those are actually definite integrals. The concept of antiderivative is more closely associated with the indefinite integral. What would you say an antiderivative is in your own words?
Answer: Nearly, but as the antiderivatives $F$ and $G$ can themselves differ by a constant, the reasoning can fail.
What you can write is
$$F(x)+C_F=G(x)+C_G$$ and verify the condition at a single point, say
$$F(x_0)+C_F=G(x_0)+C_G,$$ which can be enforced with $$C_G=C_F+F(x_0)-G(x_0).$$
Now it holds for all $x$.
In other words, subtracting both,
$$F(x)-F(x_0)=G(x)-G(x_0)$$
which is equivalent to
$$\int_{x_0}^x f(t)\,dt=\int_{x_0}^x g(t)\,dt.$$
Answer: What you're computing is the indefinite integral and there's no reason for the constants of integration to be the same on both the sides. Let $\int f(x) \mathrm dx=F(x)+C_1$ and $\int g(x)\mathrm dx=G(x)+C_2$ In fact you may simply write the following:$$f(x)=g(x) \implies \int f(x)\mathrm dx=\int g(x) \mathrm dx\implies F(x)=G(x)+C \ \text{where} \ C=C_2-C_1$$Note that this is the case even during computation of definite integral, however the effect of the constants of integration gets nullified in the process:$$\int_{a}^{b}f(x)\mathrm dx=\bigl[F(x)+C_1\bigr]_{a}^{b}=F(b)-F(a)$$
Answer: Observe that if $f$ is differentiable on $\Bbb R$ then the derivative of both $f$ and $f+c$ are same which is $f'$ but $f \neq f+c$ unless $c = 0.$

Integrating both sides of an equation


How to change the size of the Intellij Idea menu lines?

Question: I would like to know how to change the space between lines of the menu (width). My menus having lines too big. There is image to show it.

Comment: Looks like you're using the Material Theme plugin, which is not maintained or supported by JetBrains. Please direct your question to the author of the plugin.
Comment: What is inside your Help | About window? What's the version of OS, JDK, IDE?
Comment: Windows 10. JDK 8. Intellij IDEA 2018.3.5 Ultimate.
Answer: Like yole said, the Material Theme Plugin change the space between each line in menu.
To fix it:

Open IntelliJ settings (Ctrl + Alt +S)
Appearance & Behavior > Material Theme > Tabs Compact
Enable Compact Menus & Compact Dropdown Lists
Comment: You can also use Tools -> Material Theme -> Panel Options -> Compact menus, etc.
Comment: Thank you! It solved. Now the menus are back to normal.
Answer: In my case, the following worked:
Settings >> Material Theme UI >> Settings >> Compact >> tick Compact Menus :)


R: split concatenated dataframe by row

Question: I have a big text file that is the result of another program appending multiple tables together (including headers). I'd like to read that file into R and split it apart.
This is sort of similar to this problem, except I don't know the row number, and I need to split it on the header row, not a particular row number. I do know that each table starts with a header, though, and that the Wvlgth values always start with 337.0 and end with 823.0.
Here is the text file. It looks identical to this, except with 550 rows.
Wvlgth Global
337.0  .4345
337.5  .1256
338.0  .8754
<...>
821.0  .9923
822.0  .7124
823.0  .2999
Wvlgth Global
337.0  .5632
337.5  .1245
338.0  .0012
<...>
821.0  .1987
822.0  .6743
823.0  .2045

Here is the code to generate something similar in R:
    df = data.frame("Wvlgth" = c('337.0','337.5','338.0','821.0','822.0','823.0'),
                   "Global" = c(.4345, .1256, .8754, .9923, .7124, .2999))

I want this to turn into multiple dataframes, like so:
Dataframe 1
     Wvlgth Global
1    337.0 .4345
2    337.5 .1256
3    338.0 .8754
<...>
548  821.0 .9923
549  822.0 .7124
550  823.0 .2999

Dataframe 2
     Wvlgth Global
1    337.0 .5632
2    337.5 .1245
3    338.0 .0012
<...>
548  821.0 .1987
549  822.0 .6743
550  823.0 .2045

Not sure if there is a way to do this through read.csv or if i need to read the whole thing in and split it after the fact.
Comment: There's not a way to do it on import that I've seen. You can either fix the file (in R with `readLines` or with system tools) or fix the data.frame manually afterwards by subsetting with `df[!grepl('\\D', df$Wvlgnth), ]` and applying `type.convert` manually.
Comment: I would import it `as.numeric` and then split it using `NA`, `NA` as flag for the rows
Comment: @agerom I don't think I understand what you're saying, sorry...How would using the NA rows as a flag for splitting the dataframe be any different than using a row of strings?
Comment: @ale19 would you mind sharing a portion of the csv?
Comment: @agerom Is the portion from my original post not enough?
Comment: @ale19 I imagine that <...> contains only numeric data, right?
Answer: Here's how to do that using split from data.table. Basically, you need to create a group column using cumsum on "Wvlgth" in column 1. Then you can split the result into a list. You can then access the elements of that list like so: df_list[[1]]
df <- read.table(text="Wvlgth Global
337.0  .4345
                337.5  .1256
                338.0  .8754
                821.0  .9923
                822.0  .7124
                823.0  .2999
                Wvlgth Global
                337.0  .5632
                337.5  .1245
                338.0  .0012
                821.0  .1987
                822.0  .6743
                823.0  .2045",header=FALSE,stringsAsFactors=FALSE)
df$group <- cumsum(df[,1]=="Wvlgth")
df_list <- split(df, list(df$group))

$`1`
      V1     V2 group
1 Wvlgth Global     1
2  337.0  .4345     1
3  337.5  .1256     1
4  338.0  .8754     1
5  821.0  .9923     1
6  822.0  .7124     1
7  823.0  .2999     1

$`2`
       V1     V2 group
8  Wvlgth Global     2
9   337.0  .5632     2
10  337.5  .1245     2
11  338.0  .0012     2
12  821.0  .1987     2
13  822.0  .6743     2
14  823.0  .2045     2

To access a single data.frame:
df_list[[1]]
      V1     V2 group
1 Wvlgth Global     1
2  337.0  .4345     1
3  337.5  .1256     1
4  338.0  .8754     1
5  821.0  .9923     1
6  822.0  .7124     1
7  823.0  .2999     1

Additionally, if you want to set up the column names of the data.frames, you can use lapply:
new_col_name <- c("Wvlgth", "Global","group")
df_list <- lapply(df_list, setNames, nm = new_col_name) #set names
df_list <- lapply(df_list, function(x) x[-1,]) #remove first row

> df_list
$`1`
  Wvlgth Global group
2  337.0  .4345     1
3  337.5  .1256     1
4  338.0  .8754     1
5  821.0  .9923     1
6  822.0  .7124     1
7  823.0  .2999     1

$`2`
   Wvlgth Global group
9   337.0  .5632     2
10  337.5  .1245     2
11  338.0  .0012     2
12  821.0  .1987     2
13  822.0  .6743     2
14  823.0  .2045     2

Comment: @ale19 If you are referring to `list` in `split(df, list(df$group))`, it's just the way `data.table` uses inputs. On a broader note, it is good practice in this case to store the data.frames into a list. As you can see, it's easy to do operations on all data.frames using lapply. If you need to get back the results into a single data.frame, you can use rbindlist from data.table.
Comment: That works! Thank you. If it's not too much to ask, why need to split the result into a list? I get an error when I run that line of code without `list()`, but I don't understand what that error means, even after some Googling.
Comment: Ah, that makes sense! It's the same thing in pandas when you are concatenating a dataframe, but I didn't realize that. Still learning all the syntax in R. Thank you!
Answer: I created some monte carlo data myself
#loading libraries
library(stringi)
library(data.table)
library(plyr)

input <- readLines("path/to/your/csv",warn = F)#reading input csv file
input <- trimws(input)#removing spaces left and right

Looking like:
 >input
 [1] "Wvlgth Global" "337.0 0.4345"  "337.5 0.1256"  "338.0 0.8754"  "821.0 0.9923"  "822.0 0.7124"  "823.0 0.2999"  "Wvlgth Global" "327.0 0.5345"  "317.5 0.5256"
[11] "358.0 0.4754"  "871.0 0.93235" "882.0 0.2124"  "893.0 0.1999"  "811.0 0.93235" "972.0 0.33235" "Wvlgth Global" "893.0 0.2399"  "193.0 0.5120"  "892.0 0.3199"

In order to transform it to a more useful format (data.table):
dt<-data.table(ldply(stri_split(str = input,fixed=" "),"["))#creating data.table
dt[,Wvlgth:=as.numeric(V1)][,Global:=as.numeric(V2)][,V1:=NULL][,V2:=NULL]#performing some column manipulation (by importing as.numeric, the characters are transformed into NA's
dt[,containsNA:=is.na(Wvlgth)]#adding boolean tag if Wvlgth is NA

The resulting data table looks like:
>dt
     Wvlgth  Global containsNA
1:     NA      NA       TRUE
2:  337.0 0.43450      FALSE
3:  337.5 0.12560      FALSE
4:  338.0 0.87540      FALSE
5:  821.0 0.99230      FALSE
6:  822.0 0.71240      FALSE
7:  823.0 0.29990      FALSE
8:     NA      NA       TRUE
9:  327.0 0.53450      FALSE
10:  317.5 0.52560      FALSE
11:  358.0 0.47540      FALSE
12:  871.0 0.93235      FALSE
13:  882.0 0.21240      FALSE
14:  893.0 0.19990      FALSE
15:  811.0 0.93235      FALSE
16:  972.0 0.33235      FALSE
17:     NA      NA       TRUE
18:  893.0 0.23990      FALSE
19:  193.0 0.51200      FALSE
20:  892.0 0.31990      FALSE

We then apply
 l1<-split(dt,cumsum(dt$containsNA))

yielding in:
>l1
$`1`
  Wvlgth Global containsNA
1     NA     NA       TRUE
2  337.0 0.4345      FALSE
3  337.5 0.1256      FALSE
4  338.0 0.8754      FALSE
5  821.0 0.9923      FALSE
6  822.0 0.7124      FALSE
7  823.0 0.2999      FALSE

$`2`
   Wvlgth  Global containsNA
8      NA      NA       TRUE
9   327.0 0.53450      FALSE
10  317.5 0.52560      FALSE
11  358.0 0.47540      FALSE
12  871.0 0.93235      FALSE
13  882.0 0.21240      FALSE
14  893.0 0.19990      FALSE
15  811.0 0.93235      FALSE
16  972.0 0.33235      FALSE

$`3`
  Wvlgth Global containsNA
17     NA     NA       TRUE
18    893 0.2399      FALSE
19    193 0.5120      FALSE
20    892 0.3199      FALSE

Finally in order to acquire the format we desire (removing NA rows and containsNA column that is) we perform on every element of the list the following operation:
lapply(l1,function(x) x[,.SD[(!is.na(Wvlgth))]][,containsNA:=NULL])

resulting in:
$`1`
   Wvlgth Global
1:  337.0 0.4345
2:  337.5 0.1256
3:  338.0 0.8754
4:  821.0 0.9923
5:  822.0 0.7124
6:  823.0 0.2999

$`2`
    Wvlgth  Global
1:  327.0 0.53450
2:  317.5 0.52560
3:  358.0 0.47540
4:  871.0 0.93235
5:  882.0 0.21240
6:  893.0 0.19990
7:  811.0 0.93235
8:  972.0 0.33235

$`3`
   Wvlgth Global
1:    893 0.2399
2:    193 0.5120
3:    892 0.3199

ADDENDUM:
In case the link to the MC data gets deprecated, here is the data that was used for the particular question.
 Wvlgth Global
 337.0 0.4345
 337.5 0.1256
 338.0 0.8754
 821.0 0.9923
 822.0 0.7124
 823.0 0.2999
 Wvlgth Global
 327.0 0.5345
 317.5 0.5256
 358.0 0.4754
 871.0 0.93235
 882.0 0.2124
 893.0 0.1999
 811.0 0.93235
 972.0 0.33235
 Wvlgth Global
 893.0 0.2399
 193.0 0.5120
 892.0 0.3199

R: split concatenated dataframe by row


OnTimeSet in onTimeSetListener not working

Question: I have implemented a TimePickerFragment in a fragment. The time picker opens and I can select the time. But, the TextView value isn't updating even after selecting a time through TimePickerDialog. There are other function calls as well inside onTimeSet method which are also not working.
I've followed this tutorial.
Here' the code for TimePickerFragment:
public class TimerPickerFragment extends DialogFragment {
    @NonNull
    @NotNull
    @Override
    public Dialog onCreateDialog(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getTargetFragment(), hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
}

And the Fragment inside which I'm calling the TimePickerFragment is as follows:
public class Fragment_alarm extends Fragment implements TimePickerDialog.OnTimeSetListener {

    private NotificationHelper mNotificationHelper;
    private TextView mTextView;

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Set Alarm");

        View view = inflater.inflate(R.layout.fragment_alarm, container, false);

        Button buttonTimePicker = view.findViewById(R.id.timeButton);
        mTextView = view.findViewById(R.id.time_tv);

        buttonTimePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment timePicker = new TimerPickerFragment();
                timePicker.show(getActivity().getSupportFragmentManager(), "time picker");
            }
        });

        Button buttonCancelAlarm = view.findViewById(R.id.button_cancel);

        buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelAlarm();
            }
        });
        return view;
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hourOfDay);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
        updateTimeText(c);
        startAlarm(c);
    }

    private void updateTimeText(Calendar c) {
        String timeText = "Alarm set for: ";
        timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

        mTextView.setText(timeText);
    }

    private void startAlarm(Calendar c) {
        ...
    }

    private void cancelAlarm() {
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getActivity(), AlertReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);

        alarmManager.cancel(pendingIntent);
        mTextView.setText("Alarm cancelled");
    }
}

The cancelAlarm method works fine as expected. But the other two functions which are being called from onTimeSet aren't working.
Please help me resolve this issue.
Thank you in advance.
Answer: This is the code of one of my alarm project.
just trigger this method at onClickEvent of the button, Hope this work for you
    private void addAlarm(){
    final Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.add_alarm);
    final EditText editN = dialog.findViewById(R.id.edittextALARM);
    final TextView picktime = dialog.findViewById(R.id.addAlarm_timepick);
    picktime.setOnClickListener(v -> {
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                getActivity(),
                (view, hourOfDay, minute) -> {
                    h = hourOfDay;
                    m = minute;
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(0,0,0, h, m);a
                    //this right here maybe the answer u need
                    picktime.setText(DateFormat.format("hh:mm aa", calendar));
                    getActiveAlarm();
                },12,0,false
        );
        timePickerDialog.updateTime(h, m);
        timePickerDialog.show();
    });


Is it possible to use Spearman Rank Correlation to analyze two time series that exhibit cyclic behavior

Question: I am extremely new to statistics so pardon me if this question is really easy to answer. I am trying to analyze two time series that should be physically related (wind speed and temperature). Since both time series are cyclic, I figured that a linear correlation technique like Pearson would not work and instead something that studies the monotonic relationship of the data would be better. However, from my understanding Spearman would require the sorting of data to assign ranks which would remove the cyclic behavior of both time series.
Is it possible to study the monotonic correlation between both time series without having to sort the data?
Comment: *Possible* in that you can physically carry it out, sure. Sensible? not in general, no. For example, you should be aware of the possibility of spurious correlation. https://en.wikipedia.org/wiki/Spurious_relationship#Examples . Note also that even in the absence of that sort of issue, the usual forms of inference for Spearman correlation (tests, CIs etc) relies on independence.  To be honest this sounds like an XY problem -- what would you be using this correlation to achieve, exactly? I think good answers would rely on knowing that.
Comment: @Glen_b I was trying to study the correlation between wind speed and the temperature of a component in a wind turbine, in the hope to set get a basis of normal temperature jumps at wind speeds, so that eventually I can use it to check if the component is overheating abnormally compared to historical data.
Comment: " set get a basis of normal temperature jumps at wind speeds, so that eventually I can use it to check if the component is overheating abnormally compared to historical data" ... this doesn't sound like a good use case for Spearman correlation at all.
Answer: Short answer: No, that won't work.
Longer answer: If I were new to statistics, I would not try to analyze time series on my own.  In fact, even though I did data analysis for 25 years, I would not try to do time series on my own. It is very tricky and very easy to go wrong. If a client came to me with a time series problem, I would not take it on.
For one thing, cyclic data are not monotonic. "Monotonic" means constantly increasing or decreasing. For another, when you have two variables that are closely related to time, it is extremely easy to find spurious correlations.
For instance, if you plot sales of ice cream and shark attacks over time, you will find a strong correlation.  Or the Dow Jones with the number of cell phones. Or all sorts of things.
I suggest you either hire a consultant or, if you are at a university, find a colleague in the statistics department who can help you for co-authorship on a paper.
Comment: +1, although I think that by "monotonic", OP is referring to the relationship between the two series, not the behavior of a single series over time.
Comment: Cyclic data aren't monotonic, but the relationship between two cyclic variables may be. I don't see much issue in how the OP is using the term.
Comment: Thank you for your help. When I used monotonic, I was trying to figure out if the data points from one time series changes by the same magnitude as the other time series, which I assumed would be considered monotonic. I could be wrong in the terminology I used so I apologize for the confusion caused.
Comment: Maybe you are both right about what OP meant, but I'm not so sure. The reason they give for not wanting Pearson's is that the data are cyclic.


Where are mathematical discoveries posted when being undergraduate?

Question: I am interested about where a mathematical discovery can be posted to be credited for it, if its "father" is an undergraduate or someone who never took mathematics courses but studies mathematics on his own and is pretty good at it? Is it some scientific company or some university?
Comment: Not to discourage, but the chances of a new discovery by someone without some exposure to the mathematical community are fairly small. You might want to mention what field of mathematics you are thinking of.
Comment: You would normally submit the result as a paper or note to a relevant journal.
Comment: @copper.hat Journal like what? Let's say I discovered a new type of function which somehow turns out to be important to multivariable calculus or something. I write a paper 300 pages long about its discovery, properties, and applications. Where do I post it now? (By the way I didn't discover anything, I am just curious.)
Comment: @copper.hat Sorry I didn't make the question clear enough. I meant someone who studies mathematics by their own and is pretty good at it but never really attended some formal teaching. I will correct the question.
Comment: It is a little hard to answer the hypothetical, particularly given the likelihood.
Comment: Sad reality here - this is so rare there is no general rule. Even if an undergraduate really were to do something amazing his/her works generally aren't accepted right away, historically either because of culture or a lack of formalization on the student's part. There are of course famous exceptions, but don't think this is the norm.
Comment: @BrevanEllefsen how about students belonging to an university. How do they share their discoveries? I'm curious too.
Comment: @KKZiomek depends. Comment is too short to describe, but it could be word of mouth, published in journal, communication and publication through professor, Associates/Bachelors degree theses (which are generally never read by anyone, but are published in some manner), or even possibly kept in notebooks because no one will listen to an undergraduate and believe their work is legitimate. All have happened.
Comment: @KKZiomek if you're interested in any of those or any other methods I can go into detail, but as-is your question is a bit broad
Comment: @BrevanEllefsen If you want you can assemble an answer. If you want of course. With some examples in the history or anything.
Answer: A possible venue for unpublished articles by undergraduates or anyone else is the arxiv: https://arxiv.org/
However, you will have to get an endorsement from someone who already has an authorisation to place papers there, such as a mathematician familiar with this work.  This may be nontrivial but certainly easier than getting the article published in a peer-reviewed journal.
Answer: I did original research as an undergraduate and wrote a paper on it. I published the paper I wrote on arXiv, and am currently in the process of working to get it published in a journal. In the meanwhile it's been read at least a few times because it's been cited in further work on the topic. There are also journals that specifically publish the work of undergraduates.


Can a sequence of functions with bounded derivative converge to something unbounded?

Question: Suppose we have a sequence of continuous functions $h_n$ on the interval $[0,1]$ with uniformly bounded Lipschitz norm, $\sup_{x,y } \frac{|h_n(x)-h_n(y)|}{|x-y|}$. Let $h_n$ converge to some function $h$ in a continuous norm.
Is it true that the Lipschitz norm of $h$ is bounded as well ?
I would like it to be true but I have a feeling of counterexample although I am not able to find it. Any sequence of functions that I construct with a bounded derivative gives me a bounded derivative for the limit.
What do you think?
Comment: What do you mean by a continuous norm?
Comment: +1 for "I would like it to be true but I have a feeling of counterexample" because that is such a recognizable state of being when dealing with this sort of problem. A question though: what do you mean by 'converge in a continuous norm'?
Comment: Yes: it is true.
Answer: Let $M$ be the uniform Lipschitz bound. Then $|h_n(x) - h_n(y)| \le M |x-y|$ for all $n$ and for all $x,y \in [0,1]$. All you require for the limit $h$ to be Lipschitz with the same constant is pointwise convergence: $h_n(t) \to h(t)$ for all $t$.
Comment: You are so right and gosh was it so simple :|I am ashamed I didn't see it myself.


Castle Validators how to Validate Is Lesser/Greater Than Or Equal

Question: I see the ValidateIsLesser and ValidateIsGreater attributes. But what if I want to do a ValidateIsLesserOrEqual and/or ValidateIsGreaterOrEqual. Do I just need to write these custom attributes or is there pre-built capabilities for this that I am having a hard time finding?
<code>[ValidateNonEmpty]
[ValidateDate]
[ValidateIsLesser(IsLesserValidationType.Date, "EndDate", "Start Date must be before End Date.")]
public DateTime StartDate { get; set; }

[ValidateNonEmpty]
[ValidateDate]
[ValidateIsGreater(IsGreaterValidationType.Date, "StartDate", "End Date must be after the Start Date.")]
public DateTime EndDate { get; set; }
</code>
Answer: You can use the ValidateSelf attribute and supply your own validation for the OrEqual comparisons:
<code>[ValidateNonEmpty]
[ValidateDate]
public DateTime StartDate { get; set; }

[ValidateNonEmpty]
[ValidateDate]
public DateTime EndDate { get; set; }

[ValidateSelf]
public void ValidateDate(ErrorSummary errors)
{
    if (StartDate >= EndDate)
        errors.RegisterErrorMessage("StartDate", "Start date must be earlier than end date.");
}
</code>
Comment: awesome idea. this looks like a useful technique for many other situations!


Nest.js save User object to Request in middleware best practice

Question: I am working a nest.js application and I have a middleware that authenticates a firebase token and I map a firebase user_id to my database. In the middleware, I call firebase and get the user_id and then I fetch the User object from the database. I want to set the user object into the request object so that I use later on in the controllers. What is the best practice to do that?
<code>      //middleware
      async use(req: Request, res: Response, next: NextFunction) {
        const token = req.headers.authorization;

        if (token != null && token != '') {
          try {
            const decodedToken = await this.defaultApp
              .auth()
              .verifyIdToken(token.replace('Bearer ', ''));

            const authUser = await this.authenticationService.findById(
              decodedToken.user_id,
            );
            ---> req.user = authUser; //SOMETHING LIKE THIS
          }
        }
      }
</code>
I read a lot and there were a lot of conflicting solutions.
Answer: So, what I ended up doing was somewhat of a "hack" an as I haven't found any solutions, nor I've found something that I could understand and didn't go over my head I'm gonna share this "hack"
DISCLAIMER:
I do know that again, this is a H A C K and probably there are many better ways of doing this. But again, I'm gonna leave my answer here as it has helped me, if you know your stuff and could explain why what I'm doing is wrong, please say so in the comments.
Answer:
<code>  type ExtendedRequest = Request & { user: string; };

  //middleware
  export class AuthMiddleware implements NestMiddleware {
     (req: ExtendedRequest, res: Response, next: NextFunction) {
       const token = "I'm a random, verified, totally legit token :)";
       req.user = token;

       next();
     }
  }
</code>
So basically, just modify the type of "Request" , et voilà !, now TypeScript won't complain about "unknown" properties.
Comment: I think the best is to use the passport authentication module, but as you said I didn't find any easy solution taking into consideration I am also using firebase authentication. I will try this but eventually I have to try the passport strategy pattern
Comment: It will complain when you use the user property some where in your code. Something like this: Property user does not exist on type IncomingMessage


Finding subsets of all the 3-dimensional vectors over finite field, such that every triple is independent

Question: If you have a set of points $P = \{(x_i, y_i) : 0 < i < k\}$ in the general position on the plane (no three collinear), then the matrix constructed by having the $i$th row ($R_i$) equal to $(x_i, y_i, 1)$ will have the property that every three rows are linearly independent.
I am a bit rusty on my linear algebra but I expect this is the case because if you have $c_1, c_2 \in \mathbb{R}$, and $c_1 R_1 + c_2 R_2 = R_3$ then by examining the third coordinate you can conclude that the third point is an affine combination of the the first two, violating the assumption of no three collinear.
You can make $P$ as large as you want (perturbing the points in it to achieve general position). I want to understand what can be said about the bounds on the size of $P$ when a finite field $F$ is used instead of $\mathbb{R}$. Is there a concise formula for this?
More generally, I am curious what happens when you ease the restriction on the third coordinate:

$S$ is a subset of vector space $F^3$.
All sets of three distinct vectors from $S$, that is the members of $\binom{S}{3}$, are linearly independent.
How large can $S$ be?
Answer: For your first question (where the 3rd entry is fixed to be $1$ in every vector), the vectors $(1,a,a^2)$ are linearly independent for any 3 distinct choices of $a$ in the field (due to the Vandermonde determinant formula, you can look it up). Thus the maximal size set you can come up with when the 3rd coordinate is $1$ for every vector in the set is at least size $|F|$.
The more general question (not fixing the 3rd coordinate) seems much harder.