text:
Q: Is the Haar measure on the orthogonal group uniform on preimages of balls in orbits? Let $G$ be the orthogonal group on $\mathbb{R}^n$. The norm on $G$ is the operator norm. $G$ is a compact (Lie) group, so it has a unique Haar measure $\mu$ of total measure 1 which is both left and right invariant.
Fix a unit vector $x_0 \in \mathbb{R}^n$. The orbit of $x_0$ is $Gx_0 = S^{n-1} \subseteq \mathbb{R}^n$. The map $\alpha: g \mapsto g x_0$ is a surjection from $G$ to $S^{n-1} \subseteq \mathbb{R}^n$.
Cover $S^{n-1}$ by balls $B_i$ in $\mathbb{R}^n$ of radius $r$ whose centers lie on $S^{n-1}$.
I think the preimages $\alpha^{-1}(B_i)$ of the balls should all have the same measure (say up to a constant factor).
How can I prove (or disprove) this?
EDIT:
https://en.wikipedia.org/wiki/Spherical_measure#Relationship_with_other_measures
According to that wikipedia article, the image measure of the Haar measure $\mu$ on $G$ through $\alpha$ is exactly the uniform measure $\sigma$ on the sphere:
$$
\sigma(A)=\mu(\{ g: \alpha(g)=gx_0 \in A\}) = \mu(\alpha^{-1}(A))
$$
In particular,
$$
\sigma(B_i \cap S^{n-1}) = \sigma(B_i) = \mu(\alpha^{-1}(B_i \cap S^{n-1}))
$$
Since $\sigma$ is uniform and since the balls have the same radius with centers on the sphere, $\sigma(B_i \cap S^{n-1})=\sigma(B_j \cap S^{n-1})$ for all $i,j$.
Thus my question can be reduced to:
Why is the image measure $\mu(\alpha^{-1}( \; \cdot \; ))$ exactly the uniform measure $\sigma$ on the sphere?

A: Consider two $B_1$ and $B_2$ balls of radius $r$ with centers on $S^{n-1}$. So the centers are $g_1 x_0$ and $g_2 x_0$ for some $g_1,g_2 \in G$.
Note
\begin{align}
B_1 \cap S^{n-1} &= \{ gx_0 : g \in G, \; |gx_0 - g_1x_0| < r \} \\
B_2 \cap S^{n-1} &= \{ gx_0 : g \in G, \; |gx_0 - g_2x_0| < r \}
\end{align}
and so
\begin{align}
\alpha^{-1}(B_1 \cap S^{n-1}) &= \{ g \in G : |gx_0 - g_1x_0| < r \} \\
\alpha^{-1}(B_2 \cap S^{n-1}) &= \{ g \in G : |gx_0 - g_2x_0| < r \}
\end{align}
Claim: $\alpha^{-1}(B_1 \cap S^{n-1})$ and $\alpha^{-1}(B_2 \cap S^{n-1})$ are translates.
Since $\mu$ is translation invariant, the claim implies
$$
\mu(\alpha^{-1}(B_1 \cap S^{n-1})) = \mu(\alpha^{-1}(B_2 \cap S^{n-1})).
$$
This proves $\mu(\alpha^{-1}(\; \cdot \;))$ must be the uniform measure on the sphere, since it assigns the same measure to ''caps'' of equal radius.
Proof of Claim: Since $g_2 = (g_2 g_1^{-1})g_1$, we have
\begin{align*}
g_2 g_1^{-1} \alpha^{-1}(B_1 \cap S^{n-1})
&= \{ (g_2 g_1^{-1}) g \in G : |gx_0 - g_1x_0| < r \} \\
&= \{ (g_2 g_1^{-1}) g \in G : |(g_2 g_1^{-1})gx_0 - (g_2 g_1^{-1})g_1x_0| < r \} \\
&= \{ h \in G : |hx_0 - (g_2 g_1^{-1})g_1x_0| < r \} \\
&= \{ h \in G : |hx_0 - g_2x_0| < r \} \\
&= \alpha^{-1}(B_2 \cap S^{n-1})
\end{align*}


text:
Q: List tables of sqlite database in chrome extension? I'm using sqlite manager extension in chrome to use sqlite database.I have a sqlite database.This extension works properly with select delete alter commands.but the problem is i can't list tables of database.is there any way to do this?.

A: You have not said what extension you are running for SO members to be able to offer definitive help.
Having said that, if you say can run SELECT queries, try:
SELECT * FROM sqlite_master WHERE type='table'

If you want only the table name, without schema details, try:
SELECT name  FROM sqlite_master WHERE type='table';

Examples, including table creation
/* Create 3  table */
CREATE TABLE Your_First_Table (Id integer PRIMARY KEY, Address text);
CREATE TABLE Your_Second_Table (Id integer PRIMARY KEY, Price text);
CREATE TABLE Your_third_Table (Id integer PRIMARY KEY, Stats text);

/*Get table names and schema details */
SELECT * FROM sqlite_master WHERE type='table';

/*Get table names */
SELECT name  FROM sqlite_master WHERE type='table';

Output from 1st Select:
table|Your_First_Table|Your_First_Table|2|CREATE TABLE Your_First_Table (Id integer PRIMARY KEY, Address text)
table|Your_Second_Table|Your_Second_Table|3|CREATE TABLE Your_Second_Table (Id integer PRIMARY KEY, Price text)
table|Your_third_Table|Your_third_Table|4|CREATE TABLE Your_third_Table (Id integer PRIMARY KEY, Stats text)

Output from 2nd Select:
Your_First_Table
Your_Second_Table
Your_third_Table

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fulfillment error occurred when trying to test google action in voice assistant I'm trying to create a webhook that will get the Intent and current state, change the state, and send back a reply using actions-on-google library for node.js.
index.js is as follows:
'use strict';

const {dialogflow} = require('actions-on-google');
const functions = require('firebase-functions');
const app = dialogflow({debug: true});

app.intent('welcome', conv => {
  let replyState = setReplyState( conv, 'prompt' );
  let intent = getIntentName( conv );
  sendReply( conv, intent, replyState );
});

function getReplyState( conv ){
  return conv.data['replyState'];
}

function setReplyState( conv, state ){
  conv.data['replyState'] = state;
  return state;
}

function getIntentName( conv ){
  return conv.intent;
}

const welcomeReplies = [
  "Welcome!"
];

const allReplies = {
  welcome: welcomeReplies,
};

function sendReply( conv, intent, replyState ){

  let repliesNamed = replyState;
  let replies = allReplies[repliesNamed];
  conv.add( reply );
}

exports.fulfillment = functions.https.onRequest(action);

package.json is as follows:
{
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
        "node": "8"
      },
  "dependencies": {
    "firebase-admin": "~6.0.0",
    "firebase-functions": "^2.0.3",
    "actions-on-google": "~2.5.0"
  },
  "private": true
}

Error occurred:

MalformedResponse
      Failed to parse Dialogflow response into AppResponse because of invalid platform response: Could not find a RichResponse or SystemIntent in the platform response for agentId: ab93fe46-9eb1-4a6c-aea7-1699d67d7369 and intentId: 1ec758db-d03a-40b7-85fe-189d9245e6e2.

I referred https://github.com/afirstenberg/examples/tree/master/conversation-to-code-2-aog

A: You don't show the function execution log, but it looks like action isn't defined anywhere, so the call functions.https.onRequest(action); returns an error.
In the source you're working from, action is defined as
const action = dialogflow();

and all the Intent Handlers are registered with
action.intent(...)

While you have a similar definition
const app = dialogflow({debug: true});

so you can probably change the line that defines the function to
exports.fulfillment = functions.https.onRequest(app);

to resolve your immediate problem.


text:
Q: C getchar vs scanf I am confused by a piece of code found in a function I am studying:
char GetCommand( void )
{
    char command;

    do {
        printf( "Enter command (q=quit, n=new, l=list):  " );
        scanf( "%c", &command );
        Flush();
    }
    while ( (command != 'q') && (command != 'n')
           && (command != 'l') );

    printf( "\n----------\n" );
    return( command );
}

void Flush( void ) {
    while ( getchar() != '\n' )
        ;
}

What I don't quite understand here is the usage of the Flush() function.  I mean, the book I am reading explains it by saying that it prevents the user from inputting more than a single character and then having that character read when they are prompted for input the 2nd time.
What I don't understand is how Flush() is preventing this from happening. It doesn't DO anything.  All it is is a while command. (While this is true......what?????)  Doesn't make sense.

A: getchar reads one character from standard input.  If you put it in a while loop, it will continue to read one character at a time until the condition is false.
What the Flush function is doing is reading until it encounters a newline (\n).  This is the character produced when the user hits the enter key.
So, the code you gave will read one character (I'm unclear on why it uses scanf for this instead of simply getchar, which would be faster), and then discards the rest of the input until the user hits enter.
If you were to feed this program foobar, it would take the f and discard the oobar in the Flush function.  Without calling flush, the f could go to one scanf, and the second scanf would get the first o.

A: getchar() has the side effect of removing the next character from the input buffer. The loop in Flush reads and discards characters until - and including - the newline \n ending the line.
Since the scanf is told to read one and only one character (%c) this has the effect of ignoring everything else on that input line.
It would probably be more clear if the scanf was replace with
command = getchar();

but it's actually a generally bad example as it does not handle End Of File well.
In general scanf is best forgotten; fgets and sscanf work much better as one is responsible for getting the input and the other for parsing it. scanf (and fscanf) try to do too many jobs at once.

A: When you enter your character and press Enter, a newline character is generated by you pressing the Enter key and it remains in the buffer. This is problematic because it will wait around until the next time you require user input and it will be used for that input. Flush is used to flush the newline character from the input buffer so you don't have that problem. Flush actually uses the newline in the input buffer when it reads it and it is discarded, so it is no longer in the buffer.


text:
Q: Selecting object property with variable? I'm using an API which returns this JSON:
"Deadlines": {
        "Monday": "10:00:00",
        "Tuesday": "10:00:00",
        "Wednesday": "10:00:00",
        "Thursday": "10:00:00",
        "Friday": "10:00:00",
        "Saturday": null,
        "Sunday": null
    },

right now I can get a deadline time by using dot notation.
var deadline = _api.Select(x => x.Deadlines.Friday);

However, what I want, is to check which day it is today
var todaysDayOfWeek = DateTime.Now.DayOfWeek.ToString();

and then use that variable as the property name.
However, I have absolutely no idea how to do this. I though that maybe I can use bracket notation, but I just get a "Cannot apply indexing with [] to an expression of type Deadlines. (Deadlines is just a model which has mon-sun timespan properties)
var todaysDayOfWeek = DateTime.Now.DayOfWeek.ToString();
var deadline = _api.Select(x => x.Deadlines[todaysDayOfWeek]); // <-- produces aforementioned error

    public class Deadlines
    {
        public TimeSpan? Monday { get; set; }
        public TimeSpan? Tuesday { get; set; }
        public TimeSpan? Wednesday { get; set; }
        public TimeSpan? Thursday { get; set; }
        public TimeSpan? Friday { get; set; }
        public TimeSpan? Saturday { get; set; }
        public TimeSpan? Sunday { get; set; }
    }

How would one go about achieving this?

A: Well, maybe you should use a Dictionary<DayOfWeek, TimeSpan?> instead of multiple properties.
If that's not possible:
The efficient way, a switch:
public class Deadlines
{
    public TimeSpan? Monday { get; set; }
    public TimeSpan? Tuesday { get; set; }
    public TimeSpan? Wednesday { get; set; }
    public TimeSpan? Thursday { get; set; }
    public TimeSpan? Friday { get; set; }
    public TimeSpan? Saturday { get; set; }
    public TimeSpan? Sunday { get; set; }

    public TimeSpan? GetDeadLine(DayOfWeek dow)
    {
        switch(dow)
        {
            case DayOfWeek.Monday:
                return Monday;
            case DayOfWeek.Tuesday:
                return Tuesday;
            case DayOfWeek.Wednesday:
                return Wednesday;
            case DayOfWeek.Thursday:
                return Thursday;
            case DayOfWeek.Friday:
                return Friday;
            case DayOfWeek.Saturday:
                return Saturday;
            case DayOfWeek.Sunday:
                return Sunday;
            default: throw new ArgumentException(nameof(dow));
        }
    }
}

Or you could have a dictionary that returns the deadline:
public class Deadlines
{
    public TimeSpan? Monday { get; set; }
    public TimeSpan? Tuesday { get; set; }
    public TimeSpan? Wednesday { get; set; }
    public TimeSpan? Thursday { get; set; }
    public TimeSpan? Friday { get; set; }
    public TimeSpan? Saturday { get; set; }
    public TimeSpan? Sunday { get; set; }

    private static readonly Dictionary<DayOfWeek, Func<Deadlines, System.TimeSpan?>> DayOfWeekMapper;
    static Deadlines()
    {
        DayOfWeekMapper = new Dictionary<System.DayOfWeek, Func<Deadlines, System.TimeSpan?>>
        {
            { DayOfWeek.Monday, dl => dl.Monday },{ DayOfWeek.Tuesday, dl => dl.Tuesday },{ DayOfWeek.Wednesday, dl => dl.Wednesday },
            { DayOfWeek.Thursday, dl => dl.Thursday },{ DayOfWeek.Friday, dl => dl.Friday },{ DayOfWeek.Saturday, dl => dl.Saturday },{ DayOfWeek.Sunday, dl => dl.Sunday }
        };
    }

    public TimeSpan? GetDeadline(DayOfWeek dow) => DayOfWeekMapper[dow].Invoke(this);
}

There's also reflection but i would not use it here since it's not efficient and not readable.
Well, here it is:
public class Deadlines
{
    public TimeSpan? Monday { get; set; }
    public TimeSpan? Tuesday { get; set; }
    public TimeSpan? Wednesday { get; set; }
    public TimeSpan? Thursday { get; set; }
    public TimeSpan? Friday { get; set; }
    public TimeSpan? Saturday { get; set; }
    public TimeSpan? Sunday { get; set; }

    private static readonly Dictionary<string,PropertyInfo> DayOfWeekPropertyMapper;
    static Deadlines()
    {
        DayOfWeekPropertyMapper = typeof(Deadlines).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => Enum.GetNames(typeof(DayOfWeek)).Contains(p.Name))
            .ToDictionary(p => p.Name, p => p);
    }

    public TimeSpan? GetDeadline(string dayOfWeek) => (TimeSpan?)DayOfWeekPropertyMapper[dayOfWeek].GetValue(this);
}

With your sample:
string dow = DateTime.Now.DayOfWeek.ToString();
IEnumerable<TimeSpan?> deadlines = _api.Select(x => x.Deadlines.GetDeadline(dow));

A: You have two options:

*

*The switch statement
switch( dayOfWeek )
{
    case Monday: return deadlines.Monday;
    case Tuesday: return deadlines.Tuesday;
    ...
}

*Reflection.
This is quite advanced, and mighty hacky, so I do not recommend it. It consists of getting the list of fields from typeof(DayOfWeek), and for each one of them, checking whether the name of the field is the name you are looking for, and if so, obtaining the value of that field.  I am only mentioning it for completeness, I do not recommend using it, therefore I am skipping the exact details on how to do it.


text:
Q: Rollback single table How to rollback the single table in laravel 4.
I ran php artisan migrate:rollback to roll back all the migrations but how to rollback the single table
Advice much appreciated

A: for example, you want to create the user table again, just go to mysql and delete from migration's table the field that correspond to TIMESTAMP_create_users_table:
DELETE FROM MIGRATIONS WHERE MIGRATION ="2014_10_12_000000_create_users_table";

and drop the users table too:
DROP TABLE users;

after that, just run
php artisan migrate

and that's it!

A: If you wish to rollback only a specific table, you should make a migration that only includes that table. It's really that simple. Making large migrations covering several updates doesn't make any sense.
Create migrations based upon their purpose. That means; on a live project every little code change should have its own related migration.

A: Just run The command (Laravel 5):-
php artisan migrate:rollback --step=5

It will undo last 5 migrations (in fact it will execute the function "down" in each one)
php artisan migrate

It will add all migration table into database


text:
Q: the return is not working i have function including while loop in my function first process is completed but not gone again in click event

$('body').on('click', 'button.expandcollapse', function() {
      // var currenttrid = $("tr.selected").attr("data-id");
      var parentid = $(".selected").data("id");
      var parrentid = (parentid) - 1;
      var rowclick = parseInt($(this).closest('tr').attr('data-id'));
      var currentid = rowclick + 1;

      if ($("tr[data-id='" + parrentid + "'] > td:first-child button").hasClass("expandcollapse")) {
        var parentleft = $("tr[data-id='" + rowclick + "']> td:first-child").css("padding-left");
        while (true) {
          var chiledtrleft = $("tr[data-id='" + currentid + "']> td:first-child").css("padding-left");

          if (chiledtrleft <= parentleft) {
            break;
          }

          $("tr[data-id='" + currentid + "']").hide();
          currentid = currentid + 1;
        }
        $("span", this).text
      } else {
        var parentleft = $("tr[data-id='" + rowclick + "']> td:first-child").css("padding-left");
        while (true) {
          var chiledtrleft = $("tr[data-id='" + currentid + "']> td:first-child").css("padding-left");

          if (chiledtrleft <= parentleft) {
            break;
          }

          $("tr[data-id='" + currentid + "']").show();
          currentid = currentid + 1;

        }
        $("button").removeClass("expandcollapse");
        $("span", this).text("-");
      }

i want again it comes to click event
now the else condition is continuously working but i want go to the click event after one step completd

A: In the end of the function You are doing
 $("button").removeClass("expandcollapse");

So since there is no button with class expandcollapse  . It does not get triggered for second time
Checkout this Demo .  Your code goes something like this , and dont work on second click.
So better plan a logic first before implementing.
You can use this selector to make it work (only and only if you are not adding the button dynamically)
$("button.expandcollapse").click(function(){

Working Demo
if dynamic then use your selector with this change for your second last line of code
$(this).removeClass("expandcollapse");

Suggestion : Better Use different class for .removeClass() at last .  Why do you want to remove the same class with which you are triggering the event. Please use some other class for other functionalities in click function.


text:
Q: Client is unauthorized to retrieve access tokens on google service I am trying to upload the file from local system to my gmail Google Drive. I have created the Google Service with my gmail account. Service account address generate by google is ucxxx@ucxxxx.iam.gserviceaccount.com. When i try to upload the file it show it is successfully uploaded but i can't see any file on Google drive.
Also when i pass my email address then it is giving error Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested
public static Google.Apis.Drive.v3.DriveService GetService2()
    {
        string[] scopes = new string[] { Google.Apis.Drive.v3.DriveService.Scope.Drive };

        //"SERVICE_ACCOUNT_EMAIL_HERE";

        String serviceAccountEmail = "ucxxx@ucxxxx.iam.gserviceaccount.com";

        // Scope and user email id which you want to impersonate
        var initializer = new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = scopes,
            User = "ucxxxxx@gmail.com" //// this is giving me error when i pass  actual gmail id but
                                      ////when i pass ucxxx@ucxxxx.iam.gserviceaccount.com file
                                     ///uploaded successfully but don't know where the file is uploading
        };

        //get private key, from .JSON file
        //var credential = new ServiceAccountCredential(initializer.FromPrivateKey("-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0B\ndQtio==\n-----END PRIVATE KEY-----\n"));

        // Create the service.
        var service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "DriveAPI",
        });

        service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
        return service;
    }

I have read many articles from stackoverflow and other but not get a proper solution or may be i did not understand. Thanks for your comments and

A: There's an actual page detailing all the JWT Errors and possible solution, for your case you have:

A service account was authorized using the client email address rather than the client ID (numeric) in the Admin console.

In the Domain-wide delegation page in the Admin console, remove the client, and re-add it with the numeric ID.

Also from your post I deduced that you are using a plain @gmail.com account that doesn't involve a domain. From all the documentation I could find you need an organization and a Google Workspace Account to set up a Domain-wide delegation

A:
Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested

Normally means that you are trying to use ServiceAccountCredential.Initializer with invalid service account email address in your case i suspect it may have to do with the fact that your not loading the FromCertificate
I recommend using the following code and passing it the full creetinals.json file you downloaded from Google developer console.  Make sure that you have actually created service account credentials and not another type of credentials and this is the file you are using.  Also be sure to enable the Google drive api.
const string serviceAccount = "XXX@XXX.com";

var certificate = new X509Certificate2("cred.p12", "notasecret", X509KeyStorageFlags.Exportable);

        var gsuiteUser = "user@yourdomain.com";

        var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
        {
            User = gsuiteUser,
            Scopes = new string[] { Google.Apis.Drive.v3.DriveService.Scope.Drive };
 }

        }.FromCertificate(certificate);

  // Create the  Analytics service.
  return new DriveService(new BaseClientService.Initializer()
          {
          HttpClientInitializer = credential,
          ApplicationName = "Drive Service account Authentication Sample",
           });


text:
Q: Dynamically update Linear Gradient CSS How to dynamically change the argument value of linear-gradient using javascript / Jquery? I have to change both color and its percentage as per user choice and the range slider value respectively.
I have written the below code, but it is not working. As we have to put linear-gradient in " " and due to double quotation mark all arguments turn into simple string.
var gradColor1 = `${this.color1} ${percentage}%`;
var gradColor1 = `${this.color1} ${percentage}%`;
slider.style.background =linear-gradient(to left, gradColor1, gradColor1);

A: The issue is because you need to concatenate the values in to a string which you set as the value of style.backgroud. As you're already using template literals, try this:
slider.style.background = `linear-gradient(to left, ${gradColor1}, ${gradColor1})`

Note that if you want to specify a gradient you'll need two colours, like this:

var percentage1 = 50;
var color1 = "#C00";
var percentage2 = 100;
var color2 = "#000";

slider.style.background = `linear-gradient(to left, ${color1} ${percentage1}%, ${color2} ${percentage2}%)`;
#slider {
  width: 200px;
  height: 200px;
}

Finally, note that unless you're calculating colours dynamically in JS, it would be a much better idea to set the background using CSS only, like this:

#slider {
  width: 200px;
  height: 200px;
  background: linear-gradient(to left, #C00 50%, #000 100%);
}

A: Here is my snippet using javascript where you can select OriginalColor and does darkening or lightening shadow of the same color (in case original color comes from json for example). By modifying codepen below you can add logic to change percentage where fading starts, lightening or darkening, original color and auto calculated second color (in case you would like to make it totally dynamic and programmatic). Its little bit more than you asked for but I hope someone finds it useful as it came to me as request during my project.
codepen: Dynamic linear color depending on original color
<!DOCTYPE html>

      <title>Dynamic linear color depending on original color</title>

Linear Gradient - Left to Right

This linear gradient starts ModifiedColor  at the left, transitioning to OriginalColor at the Right in 55% proportion:

JS:
function ModColor(color, adjustBy) {
        return '#' + color.replace(/^#/, '').replace(/../g, color => ('0'+Math.min(255, Math.max(0, parseInt(color, 16) + adjustBy)).toString(16)).substr(-2));
    }

var OriginalColor="#ad112b";
//this is fade itno color and ModifiedColor is starting color but it can be reverted in calculation below
var ModifiedColor=ModColor(OriginalColor,-40);
//replace -40 to 40 to switch darken to lighten or change value -80 to get more shadow etc...

document.body.style.backgroundImage = 'linear-gradient(to right,'+ModifiedColor+' 55%,'+OriginalColor+')';
//55% is where is going to start fading into OriginalColor so left side is ModifiedColor but can be reverted if needed differently


text:
Q: Send binary message using Net::Stomp::Client I need to send a binary message to Message Broker using the perl library Net::Stomp::Client. But whenever I send a message using the send or send_with_receipt methods, the message is received as a Text message.
I'm using ActiveMQ in my server, and when I call consume, the received message is of type TextMessage. I need it to be of type BytesMessage.
Update:
I see in this link that setting the content-length header will set the type to Bytes message... But I didn't find any example using Net::Stomp::Perl... If anyone can provide an example it would be great...

A: I solved this by adding bytes_message => 1 to the send() method
In newer versions you need to use stomp 1.1 or greater (default is 1.0) (pass version or accept_version to the stomp client constructor) and higher and set the content-type


text:
Q: Liferay RSSUtil + rome.jar I would like use RSSUtil to read an RSS feed but i'm facing a problem with the class loader...
The exception thrown is :
com.sun.syndication.feed.synd.SyndFeedImpl cannot be cast to com.sun.syndication.feed.synd.SyndFeedImpl

My Code is :
        SyndFeedImpl feed = null;
        final String _CLASS_NAME = "com.liferay.portlet.rss.util.RSSUtil";
        MethodKey _CONSTRUCTOR = new MethodKey(_CLASS_NAME, "getFeed", String.class);

        ObjectValuePair ovp = (ObjectValuePair) PortalClassInvoker.invoke(true, _CONSTRUCTOR, url);
        Class<SyndFeed> clazz = (Class<SyndFeed>) PortalClassLoaderUtil.getClassLoader().loadClass(
                "com.sun.syndication.feed.synd.SyndFeedImpl");

         feed = (SyndFeedImpl) ovp.getValue();

The problem is also explained in https://www.liferay.com/fr/community/forums/-/message_boards/message/15812507. I tried to do the same things but it doesn't work...
Thanks in advance for your help...
UPDATE : if i use the code below (other solution without RSSUtil) :
        URL feedUrl = new URL(url);
        HttpURLConnection httpcon = (HttpURLConnection) feedUrl.openConnection();

        SyndFeedInput input = new SyndFeedInput();
        XmlReader reader = new XmlReader(httpcon);
        SyndFeed feed = input.build(reader);

The exception thrown is :
java.lang.ClassCastException: com.sun.syndication.feed.synd.impl.ConverterForAtom10 cannot be cast to com.sun.syndication.feed.synd.Converter

A: i've faced the same problem.
I've ended up copying two jars (dom4j.jar and rome.jar) from liferayroot/tomcatxxx/webapps/ROOT/WEB-INF/lib to liferayroot/tomcatxxx/lib/ext
The first error you get is because the class are loaded by differents class loaders (the portal class loader and your portlet class loader).
Try copy the jars, should work


text:
Q: Error conexión mysql local Al intentar conectarme a la base local de mysql me arroja el siguiente mensaje:

Your connection attempt failed for user 'root' from your host to
  server at 127.0.0.1:3306:   Access denied for user 'root'@'localhost'
  (using password: YES)

*

*Info
Estoy intentando conectarme desde el workbench.
El servidor mysql local está corriendo.

Alguna solución?.

A: tuve el mismo problema con MySQL versión 8.0.23.
Lo solucione de la siguiente manera:
1- Abriendo nuevamente el instalador msi para Windows.
2- En MySQL Server hice click en "Reconfigurar".
3- Luego hice click en los pasos siguientes hasta llegar a "Cuentas y Roles" y ahí configure la contraseña de "root"
4- Por ultimo en SQL Workbench, entre a Manage Server Conections y hice click en "store in Vault.." donde introduje la misma contraseña que en el paso 3
PD: Este procedimiento también crea el Servicio de MySQL en Windows lo que también ayuda a solucionar este problema.
Espero que sea de utilidad


text:
Q: No. of items increase itself in recyclerview after clicking on a item When i am clicking on an item from recyclerview i am going to DetailsActivity but when i am coming back from DetailsActivity to MainActivity I see no. of elements increased in my recyclerview but there is no increase in no. of elements on firebase and when i restart the app no. of elements are back to normal in recyclerview.

MainActivity.java
    public class MainActivity extends AppCompatActivity {
    private  Button button;
    private  Button button2;
    EditText editText;
    EditText editText2;
    String TAG ="MyTag";
    //private FirebaseDatabase mRootRef;
    //private DatabaseReference mRefMain;
    private ChildEventListener mchildeventlistener;
    private RecyclerView mRecyclerView;
    private mModelAdapter modelAdapter;
    private List<User> mDataList;

    DatabaseReference mRootRef= FirebaseDatabase.getInstance().getReference();
    DatabaseReference mRefMain =mRootRef.child("Users");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.Senddata);
        button2 = (Button) findViewById((R.id.GetData));
        editText = (EditText) findViewById(R.id.Firstname);
        editText2 = (EditText) findViewById(R.id.Agee);
        mRecyclerView = findViewById(R.id.recyclerView);

        //mRootRef = FirebaseDatabase.getInstance();
        //mRefMain = mRootRef.getReference("Users");

        mDataList = new ArrayList<>();

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        modelAdapter = new mModelAdapter(MainActivity.this, mDataList);
        mRecyclerView.setAdapter(modelAdapter);

    }

    @Override
    protected void onStart() {
        super.onStart();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name = editText.getText().toString();
                 int age = Integer.parseInt(editText2.getText().toString());

                User user = new User(name,age);

                String key = mRefMain.push().getKey();
                mRefMain.child(key).setValue(user);

                Toast.makeText(MainActivity.this, "Done", Toast.LENGTH_SHORT).show();
            }
        });

        mchildeventlistener = new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                User user = dataSnapshot.getValue(User.class);
                assert user != null;
                user.setUid(dataSnapshot.getKey());
                mDataList.add(user);
                modelAdapter.notifyDataSetChanged();
                //modelAdapter = new mModelAdapter(MainActivity.this,mDataList); //this will recreate the adapter with new data
                //RecyclerView.setAdapter(modelAdapter); //Again set adapter to recyclerview

                //Log.d(TAG, "OnChildAdded : Name    " + user.getName());
                //Log.d(TAG, "OnChildAdded : age    " + user.getAge());

            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
                //User user=dataSnapshot.getValue(User.class);
                //user.setUid(dataSnapshot.getKey());

                //mDataList.remove(user);
                //modelAdapter.notifyDataSetChanged();

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };

        mRefMain.addChildEventListener(mchildeventlistener);

       /* button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });

        */

    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        mRefMain.removeEventListener(mchildeventlistener);
    }

}

mModelAdapter.java
    public class mModelAdapter extends RecyclerView.Adapter<mModelAdapter.MyViewHolder> {
    private Context context;
    private List<User> mDataList;
     public static final String USER_KEY = "user_key";
    public mModelAdapter(Context context, List<User> mDataList) {
        this.context = context;
        this.mDataList = mDataList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View rootView= LayoutInflater.from(context).inflate(R.layout.recycler_view_item,parent,false);

        return new MyViewHolder(rootView);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        final User user = mDataList.get(position);

       holder.textView.setText(user.getName()+"   |    "+user.getAge());

       holder.textView.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
              String uid=user.getUid("");
               Intent intent = new Intent(context,DetailsActivity.class);
               intent.putExtra(USER_KEY,uid);
               context.startActivity(intent);
           }
       });

      /* holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
           @Override
           public boolean onLongClick(View v) {

               String userId= user.getUid("");
               Task<Void> voidTask = Utils.removeUser(userId);
               voidTask.addOnSuccessListener(new OnSuccessListener<Void>() {
                   @Override
                   public void onSuccess(Void aVoid) {
                       Toast.makeText(context,"Deleted Successfully",Toast.LENGTH_SHORT).show();

                   }
               });
               return true;
           }
       });

       */

    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        TextView textView;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textView);
        }
    }
}

DetailsActivity.java
    public class DetailsActivity extends AppCompatActivity {
    private TextView mOutPuText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        mOutPuText=findViewById(R.id.Show_Text);

        String uid= getIntent().getStringExtra(mModelAdapter.USER_KEY);

       // DatabaseReference mRootRef= FirebaseDatabase.getInstance().getReference();
        //DatabaseReference mRefMain =mRootRef.child("Users").child(uid);

        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(uid);

         databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user =dataSnapshot.getValue(User.class);
                mOutPuText.setText(user.getName());

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

}

A: Create the "mchildeventlistener" in the onCreate() method instead of "onStart". This will solve your issue.
reason: onStart() method gets called every time you go to DetailActivity and come back. Hence new ChildEventListener is created every time resulting in duplication of data.


text:
Q: How to connect other library to binary in IDA test.c
#include <stdio.h>
void libtest1();  //from libtest1.so

int main()
{
    libtest1();  //calls puts() from libtest1.so twice
    libtest1();
    puts("-----------------------------");
    return 0;
}

libtest1.c
#include <stdio.h>

void libtest1()
{
    puts("libtest1: 1st call to the original puts()");
    puts("libtest1: 2nd call to the original puts()");
}

libfaketest1.c
#include <stdio.h>
void func1()
{
    puts("func 1 fakelib");

}
void libtest1()
{
    puts("libfaketest1:1st call to the fake puts()");
    puts("libfaketest1:2nd call to the fake puts()");
}

I compiled libtest1.c and libfaketest1.c to shared library: libtest1.so, libfaketest1.so.
And test.c to linux binary with dependents libtest1.so, NOT WITH libfaketest1.so!
And open test binary in IDA
import table:
Address                  Name
-------                  ----
0000000000600AD8         puts@@GLIBC_2.2.5
0000000000600ADC         libtest1
0000000000600AE0         __libc_start_main@@GLIBC_2.2.5
0000000000600AE4         puts
0000000000600AE8         __libc_start_main
0000000000600AEC         _ITM_deregisterTMCloneTable
0000000000600AF0         __gmon_start__
0000000000600AF4         _Jv_RegisterClasses
0000000000600AF8         _ITM_registerTMCloneTable

main:
.plt:0000000000400570 _libtest1       proc near               ; CODE XREF: main+9p
.plt:0000000000400570                                         ; main+13p
.plt:0000000000400570                 jmp     cs:off_600AB0
.plt:0000000000400570 _libtest1       endp
......
.text:0000000000400696 ; int __cdecl main(int argc, const char **argv, const char **envp)
.text:0000000000400696                 public main
.text:0000000000400696 main            proc near               ; DATA XREF: _start+1Do
.text:0000000000400696                 push    rbp
.text:0000000000400697                 mov     rbp, rsp
.text:000000000040069A                 mov     eax, 0
.text:000000000040069F                 call    _libtest1
.text:00000000004006A4                 mov     eax, 0
.text:00000000004006A9                 call    _libtest1
.text:00000000004006AE                 mov     edi, offset s   ; "-----------------------------"
.text:00000000004006B3                 call    _puts
.text:00000000004006B8                 mov     eax, 0
.text:00000000004006BD                 pop     rbp
.text:00000000004006BE                 retn
.text:00000000004006BE main            endp
......
.got.plt:0000000000600AB0 off_600AB0      dq offset libtest1      ; DATA XREF: _libtest1r
......
extern:0000000000600ADC                 extrn libtest1:near     ; DATA XREF: .got.plt:off_600AB0o

How to connect to the binary libfaketest1.so without replacing original lib libtest1.so in IDA?
I want to here .text:00000000004006A9                 call    _libtest1 call function from libfaketest1.so.


text:
Q: Random Elements from two Lists - Python So I have two lists in Python:
import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)

This doesn't seem to work. How can I get a random number from either list 1 or list 2?

A: You can concatenate the lists:
num = random.choice(list_1 + list_2)

or alternatively choose a list and then choose a character:
num = random.choice(random.choice([list_1],[list_2]))

A: Not short but could be a reference...
import random

name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','man','shopping','pen','mouse']

population = list(zip(name, second))
ox_list = []

for a in range(20):
    samples = random.sample(population, 1)
    samples = str(samples).strip('[]')
    ox_list.append(samples.replace("', '", ''))

for o in set(ox_list):
    print (o.replace("')",'').replace("('",''))

I have lemon
I want cat
I love banana
I like man
I buy soap
I hate water
I see shopping

A: use random.sample to select from the two lists.  If you want to select exclusively from one list or another you can use a mod % and flip even and odd where one list is even and one list is odd then randomly sample.
name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','woman','shopping','pen','mouse']

result=[]
for i in range(10):
    a=random.sample(name,1)
    b=random.sample(second,1)
    result.append(a[0]+ b[0])
print(result)
#[result.append(random.sample(name,1)[0]+random.sample(second,1)[0]) for i in
range(10)]
print(result)

output:
 ['I buy pen', 'I buy cat', 'I like woman', 'I have water', 'I hate water', 'I want water', 'I buy water', 'I see banana', 'I love woman', 'I buy woman']

randomly flipping between two lists
result=[]
for i in range(10):
    a_num=random.sample(range(10000),1)
    if a_num[0]%2:
        result.append(random.sample(name,1))
    else:
        result.append(random.sample(second,1))
print(result)

output:
[['mouse'], ['I see '], ['banana'], ['cat'], ['I buy '], ['soap'], ['woman'], ['I like '], ['soap'], ['cat']]


text:
Q: applying custom rolling function to dataframe I am getting an exception when attempting to apply a custom rolling function to a pandas data frame. For example:
import statsmodels.api as sm
import pandas as pd
import numpy as np

def univar_regr_beta(y, x):
    Y, X = y.as_matrix(), x.as_matrix()

    X = sm.add_constant(X)

    model = sm.OLS(Y, X)
    return model.fit().params[1]

df = pd.DataFrame(np.random.randn(20,3))
srs = pd.Series(np.random.randn(20))

# this returns a value e.g.: 0.06608957
univar_regr_beta(df[0], srs)

# and this returns a rolling sum dataframe
df.rolling(5, 5).apply(np.sum)

# but this breaks when attemp to get rolling beta
df.rolling(5, 5).apply(lambda x: univar_regr_beta(x, srs))

Specifically the exception I get is the following:
AttributeError: 'numpy.ndarray' object has no attribute 'as_matrix'

It looks as though when each column is passed into  univar_regr_beta via lambda, that it is being passed as a bumpy array as opposed to a Series. I am not sure if there is a better way to achieve a rolling beta, or if I am just missing something.
Any help is appreciated. Thanks


text:
Q: Unable to create a GCP account. The option for the country China is not available I am trying to help a friend who would like to sign up for a GCP account,he is located in China. And he said that the option for the country upon the creation of the account shows all other country exempt for China. Why and how can we proceed?

A: GCP does not yet offer the services directly in China due to international laws and regulations. For additional details about the how some restrictions came in, you can visit these pages 1 , 2 (May 2011).
To help your friend, I suggest that he contact one of GCP's technological partners on this pages 3 or 4. Under partnership program, they can be assisted to register an account through them.
Links:
- http://www.google.com/transparencyreport/traffic/
- https://support.google.com/transparencyreport/answer/7381384?hl=en
- https://cloud.google.com/partners/technology-partners
- https://cloud.withgoogle.com/partners/?search=china&sort-type=RELEVANCE


text:
Q: GIDSignIn current user is nil after restorePreviousSignIn() My issue here is that: This shared instance is called
GIDSignIn.sharedInstance.restorePreviousSignIn()

But when I try to check the current user it remains nil after the call.
GIDSignIn.sharedInstance.currentUser != nil

I would assume I may need a proper delay before checking if the user is nil or not. How can I properly add a delay or populate the user before checking if the user is nil.
ex: confirming that GIDSignIn.sharedInstance.restorePreviousSignIn()   has finished before checking GIDSignIn.sharedInstance.currentUser
 if(GIDSignIn.sharedInstance.hasPreviousSignIn() && GIDSignIn.sharedInstance.currentUser == nil) {
                GIDSignIn.sharedInstance.restorePreviousSignIn()
        }else{
                print("user has no shared instance. User has not been prev signed in")
        }

        if (GIDSignIn.sharedInstance.currentUser != nil) {
         }else{
               print("user is nil")
        }

Using GoogleSignIn SDK
GoogleSignIn Framework Reference

A: If you studied at the documentation you linked you'd be able to see the restorePreviousSiginin is asynchronous and also know how to use it.

func restorePreviousSignIn(callback: GIDSignInCallback? = nil)
callback
The GIDSignInCallback block that is called on completion. This block will be called asynchronously on the main queue.

where the completion handler is defined as:

typealias GIDSignInCallback = (GIDGoogleUser?, Error?) -> Void

You should use the completion handler to process the result of trying to restore the previous sign in, not try to do it synchronously in the method.  Something like
if(GIDSignIn.sharedInstance.hasPreviousSignIn() && GIDSignIn.sharedInstance.currentUser == nil) {
  GIDSignIn.sharedInstance.restorePreviousSignIn() {
    user, error in
    if let user = user {
      print(user)  // handle the user info
    } else {
       print(error ?? "unknown error")
    }
  }
}


text:
Q: Word order, e.g. in "Hotel California", "Brothers Quay" This is a question about the order of words when a common name is associated to a proper name. Does it matter to say "California Hotel" rather than "Hotel California"? Similarly, there are two filmmaker brothers usually referred to as "the brothers Quay", which seems less common than "the Coen brothers". As a non-native English speaker, I'm interested to know is there's any difference, and which form is more natural or correct.

A: All examples you mention are correct in their uses, especially since they're proper nouns (names of things/persons), and don't exactly follow "the rules."
In general, "the brothers Quay" and other similar "backward" constructions are considered archaic or out of fashion, more popular about 100 years ago or more.  However, some may still choose to use these now unconventional constructions on purpose to achieve certain effects (i.e., make the name sound cooler).
In the case of "Hotel California", you should never say "California Hotel", since the former is the name of the song.  That is to say, rather than looking for a concrete rule, you should determine the "correct" construction depending on the context.  It really depends on who named the object/person.  For example, "Ramada Inn" (a popular hotel chain) is never called the "Inn Ramada".  Its name is Ramada Inn, and that's how it's always written.

A: The only real difference is that the first word is generally considered the noun, and the second the adjective modifying that noun. So in Coen brothers, you are talking about some people named "Coen" who are further distinguished by being brothers (rather than married, or cousins or something). In brothers Quay, you are talking about some brothers, who also happen to have the name "Quay".
Effectively in the first you are emphasising the name, whereas in the second sentence you are emphasising the relationship.

A: English normally puts the adjective before the noun, though there are a number of "set phrases", such as the body beautiful that don't follow the rule. Per @ShreevatsaR's comment, the standard word order is sometimes inverted for stylistic reasons (not recommended for non-native speakers).
In constructions such as the Coen brothers, arguably both words are nouns, but I for one would say that they're primarily brothers, and that Coen is effectively an adjective telling us which particular brothers we're talking about. This reflects the normal usage.
In this context, The Brothers Grimm is an idiomatic usage probably affected by the fact that the Grimms weren't actually English. Many other languages (particularly European ones - and, surprisingly enough, American Sign Language) normally place adjectives after nouns.
Specifically addressing OP's question as to which order is "correct" where there's an ordinary noun and a proper name, the answer is that by default the proper name should come first. Unless you're already aware that the more common sequence for that particular pair inverts the normal order.


text:
Q: iOS scrolling tableView reusable cells reload I am working with tableviews in iOS. Reusable cells are reloaded when scrolling.
So, when updating -for example- textfields inside a cell, it disappears once scrolling over. I solved it by using an Array that saves all texts in all cells, but I wonder if there's a better way to solve this issue.
Thanks.

A: Using String array you have to store data of all textfields in tableview.
Use delegate methods of UITableView to implement more efficiently.
-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
   MyCell * mc = (MyCell *) cell;
   names[indexPath.row] = mc.myTf.text;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
   MyCell * mc = (MyCell *) cell;
   mc.myTf.text = names[indexPath.row];
}

Here, MyCell is the custom cell which has UITextField. name[] is the NSString array declared at class scope like NSString * names[20].

A: for memory management (to releasing memory) tableview remove cell memory which are not displaying in current screen its only keep those cell in memory which are currently displaying on screen so you have to store that text separate from tableview.

A: What you are describing is how tableviews are meant to work!  The tableView is a display, not a store, and the reusable cells are only those currently displayed
You are right to use an array (or collection) to hold the data and just use the tableView to display it

A: You issue can be because of multithreading. If you are reloading data from a GCD operation or any NSOperation(different thread), then you have to use the below code to get the handle to main thread
dispatch_sync(dispatch_get_main_queue(), ^{
//perform the reload activity
});

A: Yes you are doing right, as cells are reused you need to save your data, something like this -
1 . Have an array to hold your data.
2 . Update your array whenever you make any change in your textFields, so that your UI and data are in sync.

*Use this array to populate your tableView.

A: You need to define the cellIdentifier as unique. Then each cell created with unique identifier.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%dR%d",indexPath.section,indexPath.row];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];

           //your logic here
        }

       return cell;
    }


text:
Q: MGF of a sum of r.variables Suppouse $X_1,X_2,...X_N$ are independent having exponential distribution with parameter $\lambda$ and $N$ has a poisson($\lambda$) distribution and is independant pf the $X_i$.
1) determining the mgf of $S_N=X_1+...+X_N$:
my sol. since $X_i$'s are independent, the mgf of their sum is the product of their respective mgfs so $M_{S_N}(t)=(\frac{\lambda}{\lambda-t})^N$.
2)Find the mean.
my sol. since $M_{S_N}(t)=M_Z(t)$ where $Z$~$gamma(N,\lambda)$, they have the same distribution so the mean is N.
3) Find the distribution of $Y=\sum_{i=1}^N2(\lambda)X_i$ and identify it.
my sol. by theorem, since the $X_i$ are independant, $M_Y(t)=(\frac{\lambda}{\lambda-2\lambda t})^N$ But im not sure what distribution this corresponds to
Any help would be appreciated.

A: For (3), $M_Y(t) = \left ( \frac{1}{1-2t} \right )^N = \left(1 - 2t \right ) ^{-N}$ is the moment generating function for a Gamma Distribution, $\Gamma(k,\theta)$, with parameters $k = N$ and $\theta = 2$ per the Wikipedia article on moment generating functions.


text:
Q: JEdit fails to log in with com.jcraft.jsch.JSchException: Auth cancel I am using Jedit to remotely edit files on a Linux server, via the ftp plugin. I am using sftp with password authentication.
Up until today it was working fine, but all of a sudden it is now displaying the following error every time I try to log in:
com.jcraft.jsch.JSchException: Auth cancel

This error is also visible in the sshd log file on the server.
I can log in via ssh using eg. putty with no problems.

A: The problem turned out to be that I had added a line to one of my bash profile scripts on the server which was echoing text every time I logged in, like this:
export PGVERSION=9.6
echo "PGVERSION=$PGVERSION"

The additional text was confusing the JEdit sftp plugin.
The solution was to ensure that the text was not echoed unless talking to a terminal, so I changed the second line above to:
[ -t 0 ] && echo "PGVERSION=$PGVERSION"


text:
Q: How to load jQuery inside a Blazor web app? The example provider here does not work
How to use jQuery UI from Blazor component
https://blazorfiddle.com/s/kg13ms5x

A: This is how you initialize the resizable widget from Blazor. You can place this code where you want, preferably in the App or layout components...
@inject IJSRuntime JSRuntime

@code {

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeAsync<object>("jQueryWidgets.initialize");
        }
    }

Add the following script... jQueryWidgets is the namespace, initialize is the 'name' of the function...
JavaScript (_Host.cshtml, if you use Blazor Server )
<script src="_framework/blazor.server.js"></script>
    <script>
      window.jQueryWidgets = {

         initialize: function () {
              $("#resizable").resizable();
         }
      };
    </script>

Note that you should also add the necessary jQuery files. Place them within the head html element in _Host.cshtml, if you use Blazor Server

A: @Isaac's code is correct.It seems that you do not have proper references to jquery-ui:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ServerSideBlazor</title>
<base href="~/" />
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
<link href="css/site.css" rel="stylesheet" />

@*Add below references*@
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<style>
    #resizable {
        width: 100px;
        height: 100px;
        background: #ccc;
    }
</style>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

I suggest that you could create a new blazor project with visual studio 2019 and asp.net core 3.0 sdk.


text:
Q: Delphi - SysUtils.Trim not deleting last space(?) char Delphi RIO.  I have built an Excel PlugIn with Delphi (also using AddIn Express).  I iterate through a column to read cell values.  After I read the cell value, I do a TRIM function.  The TRIM is not deleting the last space.  Code Snippet...
acctName := Trim(UpperCase(Acctname));

Before the code, AcctName is 'ABC Holdings '.  It is the same AFTER the TRIM function.  It appears that Excel has added some type of other char there. (new line?? Carriage return??)  What is the best way to get rid of this?  Is there a way I can ask the debugger to show me the HEX value for this variable.  I have tried the INSPECT and EVALUATE windows.  They both just show text.  Note that I have to be careful of just deleting NonText characters, and some companies names have dashes, commas, apostrophes, etc.
**Additional Info - Based on Andreas suggestion, I added the following...
ShowMessage(IntToHex(Ord(Acctname[Acctname.Length])));

This comes back with '00A0'.  So I am thinking I can just do a simple StringReplace... so I add this BEFORE Andreas code...
 acctName := StringReplace(acctName, #13, '', [rfReplaceAll]);
 acctName := StringReplace(acctName, #10, '', [rfReplaceAll]);

Yet, it appears that nothing has changed.  The ShowMessage still shows '00A0' as the last character.  Why isn't the StringReplace removing this?

A: If you want to know the true identity of the last character of your string, you can display its Unicode codepoint:
ShowMessage(IntToHex(Ord(Acctname[Acctname.Length]))).

Or, you can use a utility to investigate the Unicode character on the clipboard, like my own.

Yes, the character in question is U+00A0: NO-BREAK SPACE.
This is like a usual space, but it tells the rendering application not to put a line break at this space. For instance, in Swedish, at least, you want non-breaking spaces in 5 000 kWh.
By default, Trim and TStringHelper.Trim do not remove this kind of whitespace. (They also leave U+2007: FIGURE SPACE and a few other kinds of whitespace.)
The string helper method has an overload which lets you specify the characters to trim. You can use this to include U+00A0:
S.Trim([#$20, #$A0, #$9, #$D, #$A]) // space, nbsp, tab, CR, LF
                                    // (many whitespace characters missing!)

But perhaps an even better solution is to rely on the Unicode characterisation and do
function RealTrimRight(const S: string): string;
var
  i: Integer;
begin
  i := S.Length;
  while (i > 0) and S[i].IsWhiteSpace do
    Dec(i);
  Result := Copy(S, 1, i);
end;

Of course, you can implement similar RealTrimLeft and RealTrim functions.

And of course there are many ways to see the actual string bytes in the debugger. In addition to writing things like Ord(S[S.Length]) in the Evaluate/Modify window (Ctrl+F7), my personal favourite method is to use the Memory window (Ctrl+Alt+E). When this has focus, you can press Ctrl+G and type S[1] to see the actual bytes:

Here you see the string test string. Since strings are Unicode (UTF-16) since Delphi 2009, each character occupies two bytes. For simple ASCII characters, this means that every second byte is null. The ASCII values for our string are 74 65 73 74 20 73 74 72 69 6E 67. You can also see, on the line above (02A0855C) that our string object has reference count 1 and length B (=11).

A: As a demo, to show the unicode string:
program q63847533;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;
type
  array100              = array[0..99] of Byte;
  parray100             = ^array100;
var
  searchResult          : TSearchRec;
  Name                  : string;
  display               : parray100 absolute Name;
  dummy                 : string;

begin
  if findfirst('z*.mp3', faAnyFile, searchResult) = 0 then
  begin
    repeat
      writeln('File name = '+searchResult.Name);
      name := searchResult.Name;
      writeln('File size = '+IntToStr(searchResult.Size));
    until FindNext(searchResult) <> 0;

    // Must free up resources used by these successful finds
    FindClose(searchResult);
  end;
  readln(dummy);
end.

My directory contains two z*.mp3 files, one with an ANSI name and the other with a Unicode name.
WATCHing display^ as Hex or Memorydump will display what you seem to require (the  Is there a way I can ask the debugger to show me the HEX value for this variable. of your question)


text:
Q: Can I get a ui-grid with selection without check column? Can I get a ui-grid with selection plugin enabled but without check column showing?
My html mark

My js config
$scope.gridOptions = {
    data: 'dirs',
    enableSelectAll: false,
    onRegisterApi: function(gridApi) {
        $scope.gridApi = gridApi;

        gridApi.selection.on.rowSelectionChanged($scope, onRowSelection);
    },
    columnDefs: columnDefs
};

Expected Result:
My grid without the first checkbox column.

A: As stated at http://ui-grid.info/docs/#/tutorial/210_selection:

By default the module will provide a row header with checkboxes that allow selection of individual rows. If you set the enableRowHeaderSelection gridOption to false, then the row header is hidden and a click on the row will result in selection of that row.

so, just add enableRowHeaderSelection: false
$scope.gridOptions = {
  enableRowHeaderSelection: false,
  data: 'dirs',
  enableSelectAll: false,
  onRegisterApi: function(gridApi) {
    $scope.gridApi = gridApi;

    gridApi.selection.on.rowSelectionChanged($scope, onRowSelection);
  },
  columnDefs: columnDefs
};


text:
Q: Can WPF ObjectDataProvider invoke generic method? Commonly known, ObjectDataProvider can invoke simple nongeneric methods like that
XAML:
<ObjectDataProvider x:Key="SimpleKey" MethodName="Nongeneric" ObjectType="{x:Type local:SomeClass}">
</ObjectDataProvider>

CodeBehind:
public static SomeClass
{
    public static void NongenericMethod()
    {
        // method body
    }

    public static void GenericMethod<T>()
    {
        // method body
    }
}

Is it possible that ObjectDataProvider invokes generic method? Something like that:
<ObjectDataProvider x:Key="SimpleKey" MethodName="GenericMethod<local:OtherClass>" ObjectType="{x:Type local:SomeClass}">
</ObjectDataProvider>


text:
Q: Linkedin SDK You must specify a valid JavaScript API Domain as part of this key's configuration I created an application in linkedin developers and set OAuth 2.0 redirect urls as http://localhost:8080/ and http://localhost:8080/myProject/. Then I wrote

Also I wrote one more

Then I create an  tag for calling the liLogin function.
Linkedin

Uncaught Error: You must specify a valid JavaScript API Domain as part of > this key's configuration.
     at userspace?v=0.0.2000-RC8.60429-
  1429&apiKey=86g3vbk6gy0y56&onLoad=liLogin()&authorize=yes&secure=1&:22
     at userspace?v=0.0.2000-RC8.60429-
  1429&apiKey=86g3vbk6gy0y56&onLoad=liLogin()&authorize=yes&secure=1&:31

Above error occurs when I run the application.
Also, if I write configuration with "", then linkedin login page appears, but the content is uh oh.

How can I make linkedin configuration?

A: For some reason LinkedIn does not recognize "localhost" as a valid redirect URI.
So I suggest you use the actual domain name when you test your website in dev environment.
Just add the following line to your host file:
127.0.0.1    YOUR SITE DOMAIN


text:
Q: How to prevent cursor from getting stuck in winform control due to validation I'm trying to implement validation on a winform using the error provider and validation events but I'm finding it gives a rather unnatural flow to the form.  Upon opening the form, I set the focus to a text box but if a user was to select another control within the form, they get trapped in the text box until data is entered.  I'm wondering if there is a way to prevent this from happening, I really don't like the behavior where the cursor get stuck in any control until valid data is entered.
What I would like to do is have a flag show up beside the control with invalid data but allow the user the freedom to move to other controls on the form but not permit the form to be saved if it contains invalid data.  Is this possible with the error provider and validation events?  If not, what is the best way to accomplish the type of validation I've outlined?
Thanks


text:
Q: wwwroot directory and sub directory and files not found in docker I have developed asp.net core 6 based application and created docker image and published in google kubernetes cluster.
I am facing issue while trying to access wwwroot files.
As ex, i had some files in below structure
wwwroot/Content/Static/{.vm files}
I need to access this files in source. Process working fine in local.
But docker image running in google kubernetes cluster not found these files.
Do i need to include any additional syntax to copy these wwwroot folder strcuture along with sub directory and sub files?


text:
Q: apply security=none to context root and static resources : spring security version 3.1 my application compiles to ROOT.war which basically means I do not have a context root other than /. There are pages which are to be secured; however there are URLs which do not need it; for example my http://localhost:8080/ gives the home page of this application; and there are similar pages like about us, contact us, etc where security is not need. So I add this to the configuration
  <security:intercept-url pattern="/" access="permitAll" />
  <security:intercept-url pattern="/resources/**" access="permitAll" />
  <security:intercept-url pattern="/register/confirm" access="isAuthenticated()" />
  <security:intercept-url pattern="/register/accept" access="isAuthenticated()" />
  <security:intercept-url pattern="/shopper/**" access="isAuthenticated()" />

but this just says that users are allowed to access these URL "without authentication"if you access these URLs the security filters are all applied, as seen below in the debug logs
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 1 of 12 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 3 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 4 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 5 of 12 in additional filter chain; firing Filter: 'OpenIDAuthenticationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG: org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - / at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/'; against '/'
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /; Attributes: [permitAll]
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2b06c17b, returned: 1
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successful
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication object
DEBUG: org.springframework.security.web.FilterChainProxy - / reached end of additional filter chain; proceeding with original chain
DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing GET request for [/

]
When I try using this configuration (in sequence mentioned below):
 <!-- No Security required for the ROOT Context -->
  <security:http pattern="/**" security="none" />

 <!-- Apply secyrity for shopper URLs -->
 <security:http auto-config="true" use-expressions="true" access-denied-page="/denied">
  <security:intercept-url pattern="/" access="permitAll" />
  <security:intercept-url pattern="/resources/**" access="permitAll" />
  <security:intercept-url pattern="/register/confirm" access="isAuthenticated()" />
  <security:intercept-url pattern="/register/accept" access="isAuthenticated()" />
  <security:intercept-url pattern="/shopper/**" access="isAuthenticated()" /
 ....
  </security:http>

<security:http pattern="/resources/**" security="none" />

It breaks down giving the error
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/auth/login'; against '/'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/auth/login'; against '/resources/**'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/auth/login'; against '/register/confirm'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/auth/login'; against '/register/accept'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/auth/login'; against '/shopper/**'
DEBUG: org.springframework.security.config.http.DefaultFilterChainValidator - No access attributes defined for login page URL
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5bebacc8: defining beans [placeholderConfig,dataSource,entityManagerFactory,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor#0,registrationService,shopperService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.core.session.SessionRegistryImpl#0,org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy#0,org.springframework.security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.openid.OpenIDAuthenticationFilter#0,org.springframework.security.openid.OpenIDAuthenticationProvider#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager,passwordEncoder,registrationAwareUserDetailsService,registrationAwareAuthSuccessHandler,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
INFO : org.hibernate.impl.SessionFactoryImpl - closing
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChainProxy': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: A universal match pattern ('/**') is defined  before other patterns in the filter chain, causing them to be ignored. Please check the ordering in your <security:http> namespace or FilterChainProxy bean configuration

I cannot really understand the reason behind this. Do I have to implement my own request pattern matcher?
Solution
 <beans:bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy" >
 <beans:constructor-arg>
  <beans:list>
   <security:filter-chain pattern="/resources/**"
    filters="none" />
   <security:filter-chain pattern="/aboutus"
    filters="none" />
   <security:filter-chain pattern="/contactus"
    filters="none" />
   <security:filter-chain pattern="/news"
    filters="none" />
  </beans:list>
 </beans:constructor-arg>
</beans:bean>

A: security="none" with pattern /** captures all URLs, so no other rule could be applied. What's why you receive error in second example.
But it's possible to define different filter-chains for different URL-patterns. I don't have example of this with new syntax, but here is example with old syntax (order of filter-chains is important):
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
    <sec:filter-chain-map path-type="ant">
        <sec:filter-chain pattern="/dwr/**" filters="securityContextPersistenceFilter,securityContextHolderAwareRequestFilter,rememberMeAuthenticationFilter,anonymousAuthenticationFilter" />
        <sec:filter-chain pattern="/**" filters="channelProcessingFilter,securityContextPersistenceFilter,logoutFilter,authenticationFilter,securityContextHolderAwareRequestFilter,rememberMeAuthenticationFilter,anonymousAuthenticationFilter,sessionManagementFilter,exceptionTranslationFilter,filterSecurityInterceptor,switchUserProcessingFilter" />
    </sec:filter-chain-map>
</bean>

A: Here's the syntax I have finally chosen to stick with; for it makes the XML a lot easier to read and comprehend
 <!-- Non secure URLs -->
 <security:http pattern="/" security='none' />
 <security:http pattern="/home" security='none' />
 <security:http pattern="/aboutus" security='none' />
 ...
 ...
 <security:http pattern="/resources/**" security='none' />
 <security:http pattern="/favicon.ico" security='none' />

 <!-- URLs under security config -->
  <security:http auto-config="true" use-expressions="true" pattern="/admin/**" access-denied-page="/denied">
         <security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" requires-channel="https" />
  </security:http>


text:
Q: css3 animation issue move div to left and move it back i have following code to move div into left,
But what i want is to move it to left and then again move it back,,This should auto play..any idea??
 div
    {
    width:100px;
    height:100px;
    background:red;
    -webkit-animation: mymove 5s infinite;
    animation: mymove 5s infinite;
    position:absolute;
    }

    @-webkit-keyframes mymove {
        from {left: 0px;}
        to {left: 200px;}
    }

    @keyframes mymove {
        from {left: 0px;}
        to {left: 200px;}
    }

Thank you!

A: You just need to add animation-direction: alternate. It will animate from the last keyframe value.

div {
  width: 100px;
  height: 100px;
  background: red;
  -webkit-animation: mymove 5s infinite alternate;
  animation: mymove 5s infinite alternate;
  position: absolute;
  -webkit-backface-visibility: hidden;
}
@-webkit-keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}
@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 200px;
  }
}

A: the following code should work

div
     {
     width:100px;
     height:100px;
     background:red;
     -webkit-animation: mymove 5s infinite;
     animation: mymove 5s infinite;

     position:absolute;
     }

     @-webkit-keyframes mymove {
         0%   {left: 0px;}
      50%  {left: 200px;}
      100% {left: 0px;}
     }

     @keyframes mymove {

         0%   {left: 0px;}
      50%  {left: 200px;}
      100% {left: 0px;}
     }


text:
Q: How can I pass the mouse positions from JS to shader through a uniform? I want to pass the mouse position to shader through uniform so that the color changes interactively when the mouse is moved.
Please see the comments with "★" where I suppose are the key codes to my issue.
I'm very new to shader and I'm creating this just for an exercising purpose.
What I want to know is how to pass the mouse position from js(I'm using three.js) to shader and how to use it in shader. (I believe it needs to be normalized in order to use the value in r,g and b?)

var container;
var camera, scene, renderer;
var uniforms;

init();
animate();

function init() {
    container = document.getElementById('container');

    camera = new THREE.Camera();
    camera.position.z = 1;

    scene = new THREE.Scene();

    var geometry = new THREE.PlaneBufferGeometry(2, 2);

    uniforms = {

        u_time: { type: "f", value: 1.0 },
        u_resolution: { type: "v2", value: new THREE.Vector2() },
        u_mouse: { type: "v2", value: new THREE.Vector2() }
    };

    var material = new THREE.ShaderMaterial({
        uniforms: uniforms,
        vertexShader: document.getElementById('vertexShader').textContent,
        fragmentShader: document.getElementById('fragmentShader').textContent
    });

    var mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio(window.devicePixelRatio);

    container.appendChild(renderer.domElement);

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

}

function onWindowResize(e) {
    renderer.setSize(window.innerWidth, window.innerHeight);
    uniforms.u_resolution.value.x = renderer.domElement.width;
    uniforms.u_resolution.value.y = renderer.domElement.height;
}

function animate() {
    requestAnimationFrame(animate);
    render();
}

//★set the mouse positions to shader
function render() {
    uniforms.u_time.value += 0.05;
    document.onmousemove = function (e) {
        uniforms.u_mouse.x = e.pageX;
        uniforms.u_mouse.y = e.pageY;
    }
    renderer.render(scene, camera);
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

A: The answer to your question is in your question. Can you see the difference between
uniforms.u_resolution.value.x = renderer.domElement.width;
uniforms.u_resolution.value.y = renderer.domElement.height;

and this?
uniforms.u_mouse.x = e.pageX;
uniforms.u_mouse.y = e.pageY;

Three.js uniforms are in the form uniforms.<name>.value.property. You didn't put the 'value' part.
Other issues though, Colors in three.js go from 0 to 1 so just using e.pageX and e.pageY is not going to give you any colors except black in the top left corner of the page and white everywhere else since the values will be 1 or greater everywhere
You could try
uniforms.u_mouse.x = e.pageX / window.innerWidth;
uniforms.u_mouse.y = e.pageY / window.innerHeight;

To maybe give you a more appropriate value. I say maybe because it's not clear in which context you want to change color. Over the window, over the page, over canvas, over some other element, all of those can be different.
One other thing, you don't generally want to assign an event inside your render loop. You assign it once at init time instead.
Here's the code working in a snippet

var container;
var camera, scene, renderer;
var uniforms;

init();
animate();

function init() {
  container = document.getElementById('container');

  camera = new THREE.Camera();
  camera.position.z = 1;

  scene = new THREE.Scene();

  var geometry = new THREE.PlaneBufferGeometry(2, 2);

  uniforms = {

    u_time: {
      type: "f",
      value: 1.0
    },
    u_resolution: {
      type: "v2",
      value: new THREE.Vector2()
    },
    u_mouse: {
      type: "v2",
      value: new THREE.Vector2()
    }
  };

  var material = new THREE.ShaderMaterial({
    uniforms: uniforms,
    vertexShader: document.getElementById('vertexShader').textContent,
    fragmentShader: document.getElementById('fragmentShader').textContent
  });

  var mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);

  container.appendChild(renderer.domElement);

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

}

function onWindowResize(e) {
  renderer.setSize(window.innerWidth, window.innerHeight);
  uniforms.u_resolution.value.x = renderer.domElement.width;
  uniforms.u_resolution.value.y = renderer.domElement.height;
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

document.onmousemove = function(e) {
  uniforms.u_mouse.value.x = e.pageX / window.innerWidth;
  uniforms.u_mouse.value.y = e.pageY / window.innerHeight;
}

//★set the mouse positions to shader
function render() {
  uniforms.u_time.value += 0.05;
    renderer.render(scene, camera);
  }
body { margin: 0; }
canvas { display: block; }


text:
Q: Build select result based on multiple column values I have a Person table with multiple columns indicating the person's stated ethnicity (e.g. African American, Hispanic, Asian, White, etc).  Multiple selections (e.g. White and Asian) are allowed.  If a particular ethnicity is selected the column value is 1, if it is not selected it is 0, and if the person skipped the ethnicity question entirely it is NULL.
I wish to formulate a SELECT query that will examine the multiple Ethnicity columns and return a single text value that is a string concatenation based on the columns whose values is 1.  That is, if the column White is 1 and the column Asian is 1, and the other columns are 0 or NULL, the output would be 'White / Asian'.
One approach would be to build a series of IF statements that cover all combinations of conditions.  However, there are 8 possible ethnicity responses, so the IF option seems very unwieldy.
Is there an elegant solution to this problem?

A: Assuming SQL Server it would be this.
select case AfricanAmerican when 1 then 'African American/' else '' end
        + case White when 1 then 'White/' else '' end
        + case Hispanic when 1 then 'Hispanic/' else '' end
    from PersonTable

A: This is an efficient way of doing it:
ISNULL(
NULLIF(
    STUFF(
        CASE WHEN AfricanAmerican ='1' THEN 'AfricanAmerican/' ELSE '' END
        + CASE WHEN White='1'  THEN 'White/' ELSE '' END
        + CASE WHEN Asian='1' THEN 'Asian' ELSE '' END
        , 1, 2, '')
        ,'')
    , '')
  As Ethnicity

A: -- Some sample data.
declare @Persons as Table ( PersonId Int Identity,
  AfricanAmerican Bit Null, Asian Bit Null, Hispanic Bit Null, NativeAmerican Bit Null, White Bit Null );
insert into @Persons ( AfricanAmerican, Asian, Hispanic, NativeAmerican, White ) values
  ( NULL, NULL, NULL, NULL, NULL ),
  ( 0, 0, 0, 0, 0 ),
  ( 1, 0, 0, 0, 0 ),
  ( 0, 1, 0, 0, 0 ),
  ( 0, 0, 1, 0, 0 ),
  ( 0, 0, 0, 1, 0 ),
  ( 0, 0, 0, 0, 1 ),
  ( 0, 1, 1, 1, NULL );

-- Display the results.
select PersonId, AfricanAmerican, Asian, Hispanic, NativeAmerican, White,
  Substring( Ethnicity, case when Len( Ethnicity ) > 3 then 3 else 1 end,
    case when Len( Ethnicity ) > 3 then Len( Ethnicity ) - 2 else 1 end ) as Ethnicity
  from (
  select PersonId, AfricanAmerican, Asian, Hispanic, NativeAmerican, White,
    case when AfricanAmerican = 1 then ' / African American' else '' end +
    case when Asian = 1 then ' / Asian' else '' end +
    case when Hispanic = 1 then ' / Hispanic' else '' end +
    case when NativeAmerican = 1 then ' / Native American' else '' end +
    case when White = 1 then ' / White' else '' end as Ethnicity
    from @Persons
  ) as Simone;


text:
Q: Does ArcGIS for Desktop have auto-backup feature? Did Esri decide to dump the backup file when ArcMap crashes and didn't save the file? Did they change anything to that? Did they change that to MXD Doctor?
Whenever I try to exit or save my project in ArcMap, it just crashes and I when I look for the backup file, I see nothing.
I'm using ArcGIS 10.1 for Desktop.

A: As someone who uses ArcMap 10.1 frequently and has it crash frequently, I can say that there is no MXD recovery that I've seen. It's just the "Please tell ESRI what happened!" box and then nothing.
With that said, having ArcMap crash every time you save sounds like a configuration problem. If it's possible, I'd suggest doing a complete uninstall and then a fresh reinstall. I've had issues doing an "upgrade" installation.
Chad Cooper posted a link to the ArcGIS Idea submission in a comment if you'd like to give feedback.

A: While the current session isn't saved, the crash dump files are saved if you want to look at them.
Location of crash dump files
Extract from the Esri technical article:

When using the Windows Vista or Windows 7 operating systems, the crash
  dump files (.dmp) can be found at the following local hard drive
  location within the application data of the user profile:
ArcGIS 10.0:
C:\Users\your_username\AppData\Roaming\ESRI\ErrorReports
ArcGIS 10.1:
C:\Users\your_username\AppData\Local\ESRI\ErrorReports
When using the Windows XP operating system, the crash dump files
  (.dmp) can be found at this location:
C:\Documents and Settings\your_username\Application
  Data\ESRI\ErrorReports


text:
Q: Error login python CSRF When I submit the login form, I get the following error :
403 Forbidden Reason given for failure:CSRF token missing or incorrect.

Here is my code
urls.py
from datetime import datetime
from django.conf.urls import patterns, url
from django.conf.urls import include
from django.contrib import admin
from django.conf import settings
from app.models import *
from app.views import *

admin.autodiscover()
# Uncomment the next lines to enable the admin:

urlpatterns = patterns('',
    url(r'^tinymce/', include('tinymce.urls')),
    url('', include('django.contrib.auth.urls', namespace='auth')),
    url(r'^social/',include('social.apps.django_app.urls', namespace='social')),
    #url(r'^s$', 'app.views.CategoriaProductoss', name='servicios'),
    #url(r'^s/(?P<id>\d+)$', 'app.views.servicioscategoria', name='servicioscategoria'),
    url(r'^media/(?P<path>.*)$','django.views.static.serve', {'document_root':settings.MEDIA_ROOT,}),
    url(r'^$', 'app.views.index', name='Vulpini.co'),
    url(r'^login$', 'django.contrib.auth.views.login', name='Vulpini.co'),
    url(r'^$', 'django.contrib.auth.views.logout', name='logout'),
    url(r'start$', 'app.views.start', name="start"),
    url(r'ajax-upload$', 'app.views.import_uploader', name="my_ajax_upload"),

    # Uncomment the admin/doc line below to enable admin documentation:
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
     url(r'^admin/', include(admin.site.urls)),
)

Here is the template where I have my form:
Layout.html
<form action="/login" class="form-horizontal" formmethod="post">
   {% csrf_token %}

Iniciar Sesion.

      Iniciar sesion con Facebook
      Iniciar sesion con Twitter

     Usuario

           <input name="username" type="text" id="inputEmail" placeholder="Usuario"/>

     Contraseña

           <input name="password" type="password" id="inputPassword" placeholder="Contraseña"/>

        <input type="checkbox" />Recordar
           <button type="submit" class="btn btn-info" formmethod="post" formaction="/login">Ingresar</button>
            Registrar

</form>

Why do I get a CSRF failure even though I have included {% csrf_token %} on my form?

A: The csrf token tag needs access to the request object. In your case, the easiest way to do this is to use the render shortcut instead of render_to_response.
from django.shortcuts import render

def index(request):
    notifi = Notificaciones.objects.all()
    return render(request, 'app/index.html', {'notifi': notifi})


text:
Q: 3 channel depth image 1 channel I have record a depth video using Kinect v2, when I extracted images using MATLAB then each image is 3 channel. Normally the images I saw are just 1 channel. Please any one tell me how can make this 3 channel image to 1 channel?
Here is the code of the depth part:
IplImage depth = new IplImage(512, 424, BitDepth.U16, 1);
CvVideoWriter DepthWriter;
Width = sensor.DepthFrameSource.FrameDescription.Width;
DHeight = sensor.DepthFrameSource.FrameDescription.Height;
WbDepth = new WriteableBitmap(DWidth, DHeight, 96, 96, PixelFormats.Gray16, null);
int depthshft = (int)SliderDepth.Value;
using (DepthFrame depthframe = frame.DepthFrameReference.AcquireFrame())
ushort* depthdata = (ushort*)depth.ImageData;
if (depthframe != null)
   {
    Depthdata = new ushort[DWidth * DHeight];
    ushort[] Depthloc = new ushort[DWidth * DHeight];
    depthframe.CopyFrameDataToArray(Depthdata);
    for (int i = 0; i < DWidth * DHeight; i++)
        {
          Depthloc[i] = 0x1000;
        }
        colorspacePoint = new ColorSpacePoint[DWidth * DHeight];
        depthspacePoint = new DepthSpacePoint[CWidth * CHeight];
        sensor.CoordinateMapper.MapDepthFrameToColorSpace(Depthloc, colorspacePoint);
        for (int y = 0; y < DHeight; y++)
            {
            for (int x = 0; x < DWidth; x++)
                {
                if (depthshft != 0)
                   {
                    Depthdata[y * DWidth + x] = (ushort)((Depthdata[y * DWidth + x]) << depthshft);
                   }

                 }
             }
         depth.CopyPixelData(Depthdata);
 }
WbDepth.WritePixels(new Int32Rect(0, 0, DWidth, DHeight), Depthdata, strideDep, 0);
ImageDepth.Source = WbDepth;
if (depth != null && DepthWriter.FileName != null) Cv.WriteFrame(DepthWriter, depth);
Cv.ReleaseVideoWriter(DepthWriter);
if (CheckBox_saveD.IsChecked == true)
DepthWriter = new CvVideoWriter(string.Format("{1}\\Scene{0}_DepthRecord.avi", scene, TextBlock_saveloca.Text.ToString()), FourCC.Default, 30.0f, new CvSize(512, 424));
CheckBox_saveD.IsEnabled = false;
if (CheckBox_saveD.IsChecked == true) Cv.ReleaseVideoWriter(DepthWriter);

Thank you

A: Everyone so far is advising you to convert the (supposedly) color image to grayscale. I don't think you should do this.
The kinect gives you a "1 channel" image of depth values. If you have a color (3 channel) depth map, then something is wrong. Converting to gray scale will then make you lose depth information.
Instead, try to figure out why your image is loaded as gray scale in the first place. What is the source? Is the conversion maybe done by Matlab when reading the image? Can you then give it some flag to tell it not to?


text:
Q: leaflet js strange map behavior I am having some strange behavior with my leafletjs map. I've tried plotting a few polylines between north america and asia, but get the polyline split into two pieces.
Is there a way to fix this?

A: You did not add any code with your request so it is no easy to respond you correctly
Likely you need to split each polyline in two parts, else they directly jump to the other part of the world passing over the europe. Then try to center the map on the pacific ocean and not in the europe in order to get a better map.


text:
Q: Invoke gdb from python script where should my python files be stored so that I can run that using gdb. I have custom gdb located at /usr/local/myproject/bin. I start my gdb session by calling ./arm-none-eabi-gdb from the above location.
I don't know how this gdb and python are integrated into each other.
Can anyone help.?

A: You'd better use Python subprocess module - you could start GDB from python and drive GDB from python, passing commands on-the-fly
https://docs.python.org/3.6/library/subprocess.html#subprocess.run

A: I was able to figure out. What I understood is
GDB embeds the Python interpreter so it can use Python as an extension language.
You can't just import gdb from /usr/bin/python like it's an ordinary Python library because GDB isn't structured as a library.
What you can do is source MY-SCRIPT.py from within gdb (equivalent to running gdb -x MY-SCRIPT.py).


text:
Q: PDE Initial and Boundary Conditions This question comes from the text book Partial Differential Equations An Introduction, Walter A. Strauss. I was trying to do some of text book questions as I am doing a course in PDE's and had a bit of trouble with one of the questions.
Question
A homogeneous body occupying a solid region D is completely insulated. Its initial temperature is f(x). Find the steady state temperature that it reaches after a long time. (Hint: No heat is gained or lost)
Solution
So u know that the heat equation is given by
$$ u_t = ku_{xx}$$
where $k\neq0$. Since we know the the temperature is in steady state (i.e. there is no heat lost or gained) then
$$ u_t= 0  $$
substituting this back into our PDE we find
$$ 0 = ku_{xx} \implies 0 = u_{xx} .$$
Since the body is completely insulated we know
$$ 0 = u_{x} $$
Finally we can can say
$$ u = constant $$but i am a bit stuck on how the find the steady state temperature now that I have the general solution to u ? Any help would be appreciated!