text:
Q: Vuetify data table - export to excel I want to export data from vuetify data table to excel. If user change sorting or filter data I want to export the data as I can see. Every operation is client-side, server only generates whole data source.
<v-data-table
  :headers="headers"
  :items="items"
  :items-per-page="5"
></v-data-table>
...
created() {
  this.items = await this.$axios.$get('/api/get-items')
}

My idea is take json data and use e.g. exceljs to generate excel file. But, there is only one prop (items), which is array before client-side operations (like sorting or filtering). Of cource, that I can take html code and parse data to json or edit api to accept sorting, filterig etc., but this is ugly way. Is there any other solution?

A: You can do it client-side with one major restriction: you will not be able to use pagination on this table.
If it's OK for you, a special @current-items event should to the trick:
<v-data-table
  :headers="headers"
  :items="desserts"
  :items-per-page="-1"
  @current-items="onCurrentItemsChanged"
></v-data-table>
...
data () {
  return {
    currentItems: [],
    ...
  }
},
methods: {
  onCurrentItemsChanged(val) {
    this.currentItems = val;
  }
}

This emits the items every time the internalCurrentItems is changed.
But when you apply pagination, this event will return only current page data. Not all table elements are displayed at once (to improve performance, I guess).
You won't be able to implement this via HTML code parse either, because v-data-table produce <tr>s only for the elements of the current page.
So if you are not satisfied with this restriction, it'd be better to do it server-side.
You can test this at CodePen.


text:
Q: asp.net mvc ajax.BeginForm Redirecting I dont think i quite get the Ajax functions in mvc, because i get this wierd problem.
I got the following code which makes my ajax call, it is placed in a partial view with a productList:
                <% using(Ajax.BeginForm("AddToBasket", "Basket",
                            new { productID = item.Id },
                            new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "Basket", OnSuccess = "productAdded(" + item.Id + ")" })) { %>
                    <input type="image" src="/Content/addToCart.png" />
                <% } %>

I have a

 on my masterpage
And this method in BasketController, which returns a partial view that is found in Basket/BasketList.ascx:
        [HttpPost]
    public ActionResult AddToBasket(int productID)
    {
        // DO STUFF

        return PartialView("BasketList");
    }

When i am logged in using the default asp.net membership it all works fine, it updates the basket and it is all async, but when i am logged out and is clicking the addToCart, it redirects me to Basket/AddToBasket?productID=1, which is a partial view.
Does anyone know why this happens?
I have a similar problem with an ajax.actionlink
<%= Ajax.ActionLink("Gem", "SaveBasket", "Basket", new AjaxOptions { HttpMethod = "Post" })%>

where it says "The resource cannot be found." when it should fire, which is placed in the BasketController
[HttpPost]
public void SaveBasket()
{
    // DO STUFF
}

A: It sounds like you have a javascript error somewhere that is blocking the AJAX stuff that should be happening.  Can't say why that would only happen when logged out though.
Do you have any errors in the error console/firebug?

A: Are you sure all your pages are including the Microsoft Ajax libraries?  And in the correct order?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alexa Presentation Language (APLT) with Python I'm writing an Alexa Skill via the online Alexa Developer Console with the alexa-hosted provisioning. I am using python to code the skill.
I've gotten everything working speech-wise, but I'm trying to use the APLT interface to display text on an Echo Dot with Clock. There seems to be very little online about how to get this working with the alexa-hosted skill and I cannot seem to get it working.
I've been trying all day and starting to get annoyed at how hard it is to simply show some text!
I'm sorry if this is an easy question, I'm very new to alexa skills! Any help would be greatly appreciated.

A: This is the type of JSON you need to return:
Design your APL document here - APL design. Everything is drag and drop in this. Keep trying and you will get it.
When you are done you can download the JSON file from the top right corner on the page. The JSON file has document and datasources. Pass them in the directives below.
{
    "directives": [
        {
          "type": "Alexa.Presentation.APL.RenderDocument",
          "datasources": aplDataSource,
          "document": aplDocument,
          "token": "randomToken"
        },
        {
                "type": "AudioPlayer.Stop"
        }
    ],
    'outputSpeech': {
        'type': 'SSML',
        'ssml': '<speak>' + speechOutput + '</speak>'
    },
    'card': {
        'type': 'Simple',
        'title':  cardTitle,
        'content':  cardContent
    },
    'reprompt': {
        'outputSpeech': {
            'type': 'SSML',
            'ssml': '<speak>' + repromptText + '</speak>'
        }
    },
    'shouldEndSession': shouldEndSession
}


text:
Q: PHP shell_exec wait for script to done? I have a PHP script that queries a database for a list of jobs to be done and fires off other PHP scripts based on what it finds in the database (basically a process queue).
Some of the scripts that the queue runner script executes may take 30 seconds or so to finish running (convert video, resizing images, etc).
The problem is that shell_exec() in the queue runner script calls the processing scripts, but then doesn't wait for them to finish, resulting in the queue not being completed.
Queue runner script:
#!/usr/bin/php
<?php
    // Loop through database and find jobs to be done
    shell_exec("nohup $command > /dev/null 2> /dev/null & echo $! &");
?>

Running the job script directly from the command line works and the PDF is created.
Any ideas on how to fix this? Or a better way to run a process queue?

A: shell_exec is not the cause of your problems. It'll wait and return the output of your command. However, you mustn't start your command in the background and using nohup.
nohup is the command you are calling but as soon as it has started its child process it will exit immediatelly, thus, shell_exec will not wait for that process to be completed. You should also refrain from running the command in the background with &.

A: I'd first suggest not executing code from PHP but use PHP wrappers and libraries whenever possible.
One problem I see is that your processing is synchronous, this means the user will have to wait that the server responds without any clue about what is going on.
He may even refresh the page which would increase the load of your server without control, and this is a very serious issue. This would enable a DOS attack.
I suggest AJAX for these long-running task. You can display something to show progress on the webpage and update it (AJAX) when it's done or switch to another page.
You can even handle the case of the user quitting the page by catching that event in javascript and killing the process.


text:
Q: Registration validation - if statement inside db.query doesn't work Everything works fine in my web application, just one thing.
When I try to POST form is a problem.
This is the RELEVANT code:
app.post('/register' , (req,res)=>{
    const {body} = req,
    {email, passwrod , fullname} = body;

    db.query(`SELECT email FROM users` , (err,dbRes)=>{
        let arrEmail = dbRes.rows; //array of objects , every object contain row end result of query
        for(let i = 0; i<arrEmail.length; i++)
        {
            /*
            console.log(arrEmail[i].email); //email adress (output)
            console.log(email); //email from FORM (output)
            console.log(typeof(arrEmail[i].email)); //string (output)
            console.log(typeof(arrEmail[i].email)); //string (output)
             */
            if(email == arrEmail[i].email)
            {
                console.log("Same");
                break;
            }
        }

        res.send("dsds");
    });
});

No matter how much I tried to "play" and manipulate the if statement, with a break , without break, with === instead of ==, with anything ---> if statement always false even the values are the same.
When I tried, for example, req.body() with the annual string it actually matches, for example:
//this is actually work
    if(email == "adad@asdasd.com")
    {
        console.log("Same");
        break;
    }

*

*I know it's not the correct way, but I just want to do this, for now, in this way

*I know also I need hash passwords, doesn't matter, for the moment, please ignore.
Thanks!


text:
Q: Accessing/Changing Parents State from Child Class using props (React) I am trying to set state of the parent class with the child. But having trouble figuring out how to do this. I've abstracted away anything I deemed irrelevant to the question at hand. The issue is that I am
Class Parent extends Component {
     constructor(props){
      super(props)
       this.state = {
         foo: "bar"
       }
     }
     coolMethod(n){
        this.setState({foo: n})
     }
     render{
        return(
          <Child coolmethod={this.coolMethod} />
         )
      }
}

Class Child extends Component {
     constructor(props){
      super(props)
     }
     componentDidMount(){
      let that = this;
       videojs('my-player', options, function onPlayerReady() {
         this.on('end',()=>{
           that.props.coolMethod(<whatever string returns as a result of
           this method>)
         })
       })
     }
     render{
        return(
          // irrelevant stuff to this question
         )
      }
}

Currently this code gives me "type error: this.setState is not a function"
If you want more info on videojs: http://videojs.com/ (though this is irrelevant to the question by itself, other than the fact that I reference it in my videojs call in componentDidMount of the child)

A: I assume the 2nd class is Class Child extends Component .... You need to bind this.coolMethod in your Parent constructor first.

Class Parent extends Component {
     constructor(props){
      super(props)
       this.state = {
         foo: "bar"
       }

       this.coolMethod = this.coolMethod.bind(this);
     }

     coolMethod(n){
        this.setState({foo: n})
     }
     render{
        return(
          <Child coolmethod={this.coolMethod} />
         )
      }
}

A: Try this, tested working on my side, found two issues in the code

*

*Javascript is case sensitive coolmethod is passed in to the Child, but you are trying to access coolMethod.

*You need this > this.coolMethod = this.props.coolMethod.bind(this); in the constructor to inherit the setState function from the Parent, otherwise, this inside the coolMethod will be undefined.
import React, { Component } from 'react';

export default class Parent extends Component {
  constructor(props){
    super(props)
    this.state = {
      foo: "bar"
    }
  }

  coolMethod(n){
      this.setState({foo: n})
  }

  render(){
      return(
        <Child coolMethod={this.coolMethod} />
      )
    }
}

class Child extends Component {
  constructor(props){
    super(props)
    this.coolMethod = this.props.coolMethod.bind(this);
  }

  render(){
      return(
        <button onClick={() => this.coolMethod("aabbcc")}>1</button>
      )
    }
}


text:
Q: Ionic 2 destroy previous pages while navigating I'm creating an Ionic 2 application to run on the IOS environment. My application has resource heavy pages and when navigating between pages using the ionic NavController, the application get stuck towards the latter part of the navigation. After analyzing I realized that it is because the NavController stacking the previous pages in it's memory. Is there a mechanism to destroy the previous pages when navigating forward in Ionic.

A: this.navCtrl.push(newPage).then(() => {
  let index = this.navCtrl.length;
  this.navCtrl.remove(index - 2);
  // index is your stack size
  // index - 1 is your newly pushed page
  // index - 2 is the page previous to it
});


text:
Q: How to show categories of pie chart when hovered over? How to identify each slice of the pie via hoverlabel type thing? This pie is divided equally, but i want it so when i hover my mouse over a portion it'll show me what that portion represents. I.e, hover over knowledge slice, and it displays "Knowledge Category".
    knowledge_slice1 =     (k_weighting1/100) * 360
    thinking_slice1 =      (t_weighting1/100) * 360
    communication_slice1 = (c_weighting1/100) * 360
    application_slice1 =   (a_weighting1/100) * 360

    course1_pie = Canvas(assessmentsframe1, width=255, height=255, bg = 'white')

    course1_pie.create_arc((5, 5, 250, 250), fill = "#FFFFAA",
                           start= 0,
                           extent = knowledge_slice1)

    course1_pie.create_arc((5, 5, 250, 250), fill = "#C0FEA4",
                           start= knowledge_slice1,
                           extent = thinking_slice1)

    course1_pie.create_arc((5, 5, 250, 250), fill = "#AFAFFF",
                           start= knowledge_slice1 + thinking_slice1,
                           extent = communication_slice1)

    course1_pie.create_arc((5, 5, 250, 250), fill = "#FFD490",
                           start= knowledge_slice1 + thinking_slice1 + communication_slice1,
                           extent =application_slice1)

A: I'm new to python and Tkinter myself but it seems like you might want to use the <Enter> and <Leave> Event bindings. For example, this worked for me:
master=Tk()
knowledge_slice1 =     (40.0/100) * 360
thinking_slice1 =      (30.0/100) * 360
communication_slice1 = (20.0/100) * 360
application_slice1 =   (10.0/100) * 360

course1_pie = Canvas(master, width=265, height=265, bg = 'white')
course1_pie.pack()
knowarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#FFFFAA",
   start= 0,
   extent = knowledge_slice1)
thinkarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#C0FEA4",
   start= knowledge_slice1,
   extent = thinking_slice1)
commarc=course1_pie.create_arc((5, 5, 250, 250), fill = "#AFAFFF",
   start= knowledge_slice1 + thinking_slice1,
   extent = communication_slice1)
apparc=course1_pie.create_arc((5, 5, 250, 250), fill = "#FFD490",
   start= knowledge_slice1 + thinking_slice1 + communication_slice1,
   extent =application_slice1)

hover_text=course1_pie.create_text((125,260),text="")

def know_enter(event):
   course1_pie.itemconfig(hover_text,text="Knowledge Category")
def think_enter(event):
   course1_pie.itemconfig(hover_text,text="Thinking Category")
def comm_enter(event):
   course1_pie.itemconfig(hover_text,text="Communication Category")
def app_enter(event):
   course1_pie.itemconfig(hover_text,text="Application Category")
def any_leave(event):
   course1_pie.itemconfig(hover_text,text="")

course1_pie.tag_bind(knowarc,'<Enter>',know_enter)
course1_pie.tag_bind(knowarc,'<Leave>',any_leave)
course1_pie.tag_bind(thinkarc,'<Enter>',think_enter)
course1_pie.tag_bind(thinkarc,'<Leave>',any_leave)
course1_pie.tag_bind(commarc,'<Enter>',comm_enter)
course1_pie.tag_bind(commarc,'<Leave>',any_leave)
course1_pie.tag_bind(apparc,'<Enter>',app_enter)
course1_pie.tag_bind(apparc,'<Leave>',any_leave)


text:
Q: How do I efficiently redistribute massive amounts of data spread across multiple drives with almost no space on them? My problem is simple but severe. I have a huge amount of data (many files in many folders) on multiple drives (4 external HDD). Each drive is at least 1TB in size and the overall size of this "pool" is > 7TB. No drive has more than a few GB free. The largest file is 20Gb and most files are around 500MB to 2GB.
I want to reorganize the files on all of the drives. The problem is that I can't simple move one folder from one drive to another drive because the space left on each of these drives is so low that this would never work. Doing everything by hand is not imaginable and would take forever.
I am looking for a tool (free or paid) that allows me to do the following things:

*

*change / reorganize the file structure of multiple drives BEFORE actually moving / copying any data; so I want to virtually rearrange the drives before actually doing it

*reorganizing shall include redistribution across all drives; i.e. file A may go from drive X to drive Y and file B may go from drive Y to drive X and so on...

*the tool that I am looking for shall be able to calculate the resulting actual free space for any included drive before actually moving anything so that I can see how to rearrange stuff so that it really fits on the drives

*when everything has been virtually reorganized I want this tool to calculate the "shortest" most efficient way to actually reorganize everything

*finally when the perfect reorganizing procedure has been calculated the tool shall actually perform the file movements - taking into account the space left on each drive at every moment during this process!
Such a tool takes away the burden of not being able to restructure my drives - and also everything would go the most efficient way.
So one could say that what I am looking for is some sort of defragmentation for files cluttered across several disks!
Is there any such tool available to do the job? Preferably it shall be an open source tool.
Thanks.


text:
Q: What is the best partition setup for a linux installation? As a general rule, what is the best partition setup for a linux installation?
I currently use three different ones, one as a swap space, one dedicated to the /home folder, and another one containing everything else.
Are there better setups, with partitions for other specific linux system folders?

A: For general setups, your partitioning scheme is fine. Just ensure that each partition is of adequate size. I tend to allocate twice the amount of RAM for /swap and then split the remaining hard disk space 33%/66% for / and /home.
Having a seperate (small, ~200mb) partition for /boot may be advantageous though if you are using an ext2 partitioning scheme and required if you have encrypted / partition. Generally though, putting /boot on a seperate drive is from the old days.

A: Amount of RAM in the system Recommended swap space

2GB       - 2 times the amount of RAM
2GB – 8GB - Equal to the amount of RAM
8GB – 64GB    - 0.5 times the amount of RAM
64GB      - 4GB of swap space

Minimum partition sizes are
/       2 GB
/usr    /usr on a seperate partition is not supported.
/tmp    tmpfs by default, 50 MB otherwise.
/var    500 MB
/home   100 MB
/boot   250 MB

You can read more about partitioning at Fedora Docs.
Reference: https://docs.fedoraproject.org/en-US/Fedora/20/html/Installation_Guide/s2-diskpartrecommend-x86.html


text:
Q: Wildfly Management CLI Configuration I've been finding ways to load configuration to wildfly in bulk (say I have a json data).
Something that kind of look like this.
./jboss-cli.sh -c subsystem=messagingactivemq/server=default:add(<data.json>)
Where <data.json>
{
    "outcome" => "success",
    "result" => {
        "address-full-policy" => "BLOCK",
        "dead-letter-address" => "jms.queue.DLQ",
        "expiry-address" => "jms.queue.ExpiryQueue",
        "last-value-queue" => false,
        "max-delivery-attempts" => 10,
        "max-size-bytes" => 12333,
        "message-counter-history-day-limit" => 10,
        "page-max-cache-size" => 5,
        "page-size-bytes" => 12333,
        "redelivery-delay" => 0,
        "redistribution-delay" => 222L,
        "send-to-dla-on-no-route" => false
    }
}

I want to load the above json directly to wildlfy via jboss-cli. Is this even possible? i have been looking for references about this for the past weeks. Any inputs are welcome.
EDITED
Just to be clear with my goals, I am trying ti migrate manually configured items on jBoss AS7.1 into Wildfly 10.1. Currently migration scripts only supports EAP versions of jBoss. So I have to manually select configurations fron jBoss to be migrated to wildfly. Yes, there are configuration that are deprecated and/or deleted in wildfly, so between jBoss AS7.1 and Wildfly10.1 I have to make some changes to the configuration before I load it to wildfly hence I mentioned the json data.
Since when I try to outputresource in jBoss AS7.1 via jboss-cli.sh using command /subsystem=messaging/hornetq-server=default:read-resource it will output something like
{
    "outcome" => "success",
    "result" => {
        "acceptor" => undefined,
        "allow-failback" => true,
        "async-connection-execution-enabled" => true,
        "backup" => false,
        "bridge" => undefined,
        "broadcast-group" => undefined,
        "cluster-connection" => undefined,
    ... some resource ....

So I will make some modification on the above data (since wildfly uses activemq) and load it to wildfly as activemq. But it just want to use the json data and load it directly to wildfly's jboss-cli.sh. I want to automate this and just execute a script (shell) to do the migration.

A: Not entirely sure, what exactly are you trying to achieve here, but if you want to execute bulk operations from file, you can use jboss-cli.sh --file=commands.cli where commands.cli is a text file containing jboss cli commands.
This way you can perform multiple operations at once, plus you can utilize the batch functionality provided by JBoss CLI to make sure all changes are applied or reverted.
Example file with multiple commands:
#Add xa datasource
xa-data-source add  \
    --name=my.app.ds \
    --jndi-name=java:jboss/datasources/my.app.ds \
    --driver-name=h2 \
    --user-name=username \
    --password=password \
    --use-java-context=true \
    --enabled=true \
    --xa-datasource-properties={"URL"=>"jdbc:h2:tcp://${env.DB_HOST:localhost}:${env.DB_PORT:1521}/~/my.app.ds;MVCC=TRUE"}

#Add JMS queue
jms-queue add --queue-address=foo.bar.myapp.queue --entries=java:/jms/queue/foo.bar.myapp.queue

#Add system property
/system-property=ENABLE_MY_COOL_MESSAGING_FEATURE:add(value="true")

If you want to define modules or execute operations based on JSON file or any other format apart from the CLI command format, I am afraid you are out of luck. You can make you own java library that wraps the JBoss CLI to execute it though - as JBoss/Wildfly provides CLI bindings for Java and Python I believe.


text:
Q: Change column value if value is in another dataframe I have 2 dataframe as follow:
df1:
       Materials      Col2       Col3 ...
1      Wood metal      X          Y
2        Rock          X          Y
3      Rock Metal      X          Y

df2:
       Mat
1     Metal
2      ...

I would like to loop over the first dataframe, if value of Materials contains a word that I can find in df2 then I will change it to 1 so I would get:
df1:
        Materials    Col2       Col3 ...
1         1            X          Y
2         0            X          Y
3         1            X          Y

Any suggestions ?
Many thanks !

A: #check if Materials column contains any words from df2. This will also handle both lower case and upper case matching

df1.Materials = df1.apply(lambda x: 1 if np.in1d(np.array(x.Materials.lower().split()),df2.Mat.str.lower()).any() else 0, axis=1)

df1
Out[2619]:
   Materials   Col2  Col3
1          1      X      Y
2          0      X      Y
3          1      X      Y

A: To do this without using apply, you could use pd.Series.str.contains and np.where
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'Materials': ['Wood metal', 'Rock', 'Rock Metal'],
                    'Col2': ['X', 'X', 'X'], 'Col3': ['Y', 'Y', 'Y']})

df2 = pd.DataFrame({'Mat': ['Metal']})

df1['Materials'] = np.where(df1['Materials'].str.lower().str.contains('|'.join(df2['Mat']).lower()), 1, 0)


text:
Q: Spring security repeated redirects I am using spring security in my application. I want the user to be logged in first before accessing any pages on the server, hence i am taking the redirect approach. But the redirect seems to be in an infinite loop cause it redirects me to the login page no matter how many times i submit the page. I tried debugging and the request always hits the GET instead of the POST method as i expected. I am using LDAP authentication using the details entered by the user on the form. Here is the code in the security context xml . Can someone point me in the right direction.
<http pattern="/resources/**" security="none" />

<http auto-config="true">
    <intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/**" access="ROLE_USER" />
    <form-login login-page="/login" default-target-url="/dashboard"
        authentication-failure-url="/loginfailed" />
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="bob" password="bobspassword" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

When i remove the
<form-login login-page="/login" default-target-url="/dashboard"
            authentication-failure-url="/loginfailed" />
it defaults to spring login page and it works but i have to use the user credentials from the configuration xml as opposed to LDAP credentials.
Edit**
   <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
 <link rel="stylesheet" href="${contextPath}/resources/css/styles.css" type="text/css">

Login to continue to Application

    <form:form method="POST" modelAttribute="login" action="authenticate">

                <form:label path="username" class="label">Username:</form:label>
                <form:input path="username" class="input"/>
                <form:errors path="username" class="error" />

                <form:label path="password" class="label">Password:</form:label>
                <form:password path="password" class="input"/>
                <form:errors path="password" class="error"/>

                <input type="submit"
                    value="Login" class="button"/>

    </form:form>

thanks
Sree

A: @sri
as mentioned in your code i can see that you have intercepted the URL "/login*"
now any url with login at the end will be intercepted by spring security and after that you have to put the correct credentials....
now After giving credentials your are redirected to page /login
now its clear that again our url is ending with login hence it is intercepted again by spring security ...
thats why the loop continues....
Possible Solution
this may work for you,
just put the following code below <http pattern="/resources/**" security="none" /> tag as shown:
code:
<http pattern="/resources/**" security="none" />
<http pattern="/Login.html" security="none" />

A: Ok. Finally i got to a working state. Here are the changes i made to the security context xml
        <intercept-url pattern="/login/**" access="IS_AUTHENTICATED_ANONYMOUSLY"/>

the url regex change. And also the action in my login.jsp is now
action="/login/authenticate"

and finally the controller request mapping path is updated.
Hope this helps anyone who has a similar issue. I am yet to discover if this is the right approach to achieve it but works for now.
-Sree


text:
Q: Max salary of employee with name using MapReduce Suppose I have a file in HDFS with the below data:
EmpId,EmpName,Dept,Salary

121,Raj,Dept1,8000
122,Kiran,Dept2,6000
123,John,Dept3,9000

Using MapReduce I want to get only the Salary and EmpName of the employee with the max Salary
I was able to get the max Salary but not able to get the corresponding EmpName. I am able to get only the max Salary by keeping the empty key in my map class and Math.max() in my reduce class. When I keep the key as EmpName then it is displaying all the salaries of unique employees.
My Mapreduce code
File : test.csv
121,Raj,Dept1,8000
122,Kiran,Dept2,6000
123,John,Dept3,9000

public static class MyMap extends Mapper<LongWritable,Text,Text,IntWritable>
 {
  public void map(LongWritable k,Text v, Context con)throws IOException, InterruptedException
  {
   String line = v.toString();
   String[] w=line.split(",");
   int sal=Integer.parseInt(w[3]);
   con.write(new Text("Raj"), new IntWritable(sal));
   }
 }

 public static class MyRed extends Reducer<Text,IntWritable,IntWritable,Text>
 {
  public void reduce(Text k, Iterable<IntWritable> vlist, Context con)
  throws IOException , InterruptedException
     {
      int max=0;
      for(IntWritable v:vlist)
   {
      max=Math.max(max, v.get());
   }

   con.write(new IntWritable(max), new Text());
  }

Output :
9000

Here I need the output to be:
9000 John

Please let me know how to get this output.

A: In your map phase save the entry with the highest salary and write it to the context during cleanup. This results in only one output per mapper which is the entry with the highest salary those mappers have seen. When you output the entry you could just output the whole text line. In your single reduce phase you then split the text line again and determine the max. salary of the sent text lines - which are not that many as each mapper just sent a single item.
Here is an example in Java for determining the top 10 users based on their reputation. You should be able to get the idea from it.
BTW: You requested code but didn't mention in which language and also didn't show any previous attempts by yourself, therefore I just point you to the example mentioned above.

A: pls try the following code. you will get the results.
public static class MyMap extends Mapper<LongWritable,Text,Text,Text>
 {
  public void map(LongWritable k,Text v, Context con)throws IOException, InterruptedException
  {
   String line = v.toString();
   String[] w=line.split(",");
   int sal=Integer.parseInt(w[3]);
   string name=Integer.parseInt(w[1]);
   con.write(new Text(name), new Text(name+","+sal));
   }
 }

 public static class MyRed extends Reducer<Text,Text,IntWritable,Text>
 {
  public void reduce(Text k, Iterable<Text> vlist, Context con)
  throws IOException , InterruptedException
     {
      int max=0;
      for(Text v:vlist)
   {
        String line = v.toString();
        String[] w=line.split(",");
        int sal=Integer.parseInt(w[1]);
        max=Math.max(max, sal);
   }
   con.write(new IntWritable(max), k);
  }

 }

A: You have to pass values from mapper like {raj,8000 kiran,6000 john,9000} , so key will be constant , in following code you can check how it can be done ,
 public class MyMap extends Mapper<LongWritable,Text,Text,Text>
   {
     public void map(LongWritable k,Text v, Mapper<LongWritable,Text,Text,Text>.Context
     con)throws IOException, InterruptedException
   {
     String line = v.toString();
     String[] w=line.split(",");
     String name = w[1] ;
    int sal=Integer.parseInt(w[3]);
    String map_op = name+","+sal ;
    con.write(new Text("ds"), new Text(map_op));
    //ds {raj,8000 kiran,6000 john,9000}

    }
   }

after shuffling and sorting "//ds {raj,8000 kiran,6000 john,9000}"
This will be the result,here we are passing ds as key ,
Now let's have a look at reducer method
    public class MyRed extends Reducer<Text,Text,IntWritable,Text>
{

      //ds {raj,8000 kiran,6000 john,9000}

 public void reduce(Text k, Iterable<Text> vlist, Reducer<Text,Text,IntWritable,Text>.Context con)
 throws IOException , InterruptedException
    {
     int max=0;
     String name = k.toString() ;

     for(Text v: vlist)
  {

         int salary = Integer.parseInt(v.toString().split(",")[1]) ;
         max=Math.max(max, salary);

         if(salary == max)
        {
            name = v.toString().split(",")[0] ;
        }
  }

  con.write(new IntWritable(max), new Text(name));
 }
}

//9000 john :- This o/p will be produced by reducer


text:
Q: getting error from update column from same table using mysql I am updating a table column from same table  field. But i am getting one error.
  UPDATE t
     SET t.date = t2.date
    FROM date_table t
    JOIN date_table t2
      ON t.id = t2.id
   WHERE t2.status = 'completed'
     AND t2.id = 969

i am getting one error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM cdp_lti_topic_details t JOIN cdp_lti_topic_details t2 ON t.id = t2.' at line 3

A: Here's an example of a syntactically correct query...
 UPDATE date_table t
   JOIN date_table t2
     ON t.id = t2.id
    SET t.date = t2.date
  WHERE t2.status = 'completed'
    AND t2.id = 969


text:
Q: Vagrant up doesn't load chef configs and doesn't keep an error log I'm trying to set up a vagrant box and I'm running with all sort of troubles. Right now I'm getting a strange error message where it states there's a stack trace file with more info, but that file is no where to be found.
This is the error:
stdin: is not a tty
[Sun, 16 Sep 2012 18:31:47 +0000] INFO: *** Chef 0.10.0 ***
[Sun, 16 Sep 2012 18:31:48 +0000] INFO: Setting the run_list to ["recipe[apt]", "recipe[openssl]", "recipe[apache2]", "recipe[mysql]", "recipe[mysql::server]", "recipe[php]", "recipe[php::module_apc]", "recipe[php::module_curl]", "recipe[php::module_mysql]", "recipe[apache2::mod_php5]", "recipe[apache2::mod_rewrite]"] from JSON
[Sun, 16 Sep 2012 18:31:48 +0000] INFO: Run List is [recipe[apt], recipe[openssl], recipe[apache2], recipe[mysql], recipe[mysql::server], recipe[php], recipe[php::module_apc], recipe[php::module_curl], recipe[php::module_mysql], recipe[apache2::mod_php5], recipe[apache2::mod_rewrite]]
[Sun, 16 Sep 2012 18:31:48 +0000] INFO: Run List expands to [apt, openssl, apache2, mysql, mysql::server, php, php::module_apc, php::module_curl, php::module_mysql, apache2::mod_php5, apache2::mod_rewrite]
[Sun, 16 Sep 2012 18:31:48 +0000] INFO: Starting Chef Run for natty.talifun.com
[Sun, 16 Sep 2012 18:31:48 +0000] ERROR: Running exception handlers
[Sun, 16 Sep 2012 18:31:48 +0000] ERROR: Exception handlers complete
[Sun, 16 Sep 2012 18:31:48 +0000] FATAL: Stacktrace dumped to /tmp/vagrant-chef-1/chef-stacktrace.out
[Sun, 16 Sep 2012 18:31:48 +0000] FATAL: NameError: wrong constant name Chef-symfony2Console
Chef never successfully completed! Any errors should be visible in the
output above. Please fix your recipes so that they properly complete.

And this is what my vagrantfile looks like:
Vagrant::Config.run do |config|
  config.vm.box = "ubuntu-1104-server-i386"

  config.vm.network :hostonly, "33.33.33.33"

  config.vm.forward_port 80, 8000

  config.vm.share_folder "symfony.tests", "/var/www/symfony.tests", "data", :nfs => true

  config.vm.provision :chef_solo do |chef|
    chef.cookbooks_path = ["../my-recipes/cookbooks", "site-cookbooks"]
    chef.add_recipe "apt"
    chef.add_recipe "openssl"
    chef.add_recipe "apache2"
    chef.add_recipe "mysql"
    chef.add_recipe "mysql::server"
    chef.add_recipe "php"
    chef.add_recipe "php::module_apc"
    chef.add_recipe "php::module_curl"
    chef.add_recipe "php::module_mysql"
    chef.add_recipe "apache2::mod_php5"
    chef.add_recipe "apache2::mod_rewrite"
    chef.add_recipe "Symfony"
    chef.json = {
        :mysql => {
            :server_root_password => 'root',
            :bind_address => '127.0.0.1'
        }
    }
  end
end

A: It appears to be a problem with the 'Symfony' recipe
You can't find the stacktrace because that file is on the vm rather than your host machine, to see the stacktrace you can do:
$ vagrant ssh
vagrant@yourvm:~$ tail -n 50 /tmp/vagrant-chef-1/chef-stacktrace.out

then
vagrant@yourvm:~$ exit

to get back to your host shell


text:
Q: RuntimeError: Given groups=1, weight of size [32, 3, 3, 3], expected input[1, 1, 3, 416] to have 3 channels, but got 1 channels instead

! python /content/gdrive/MyDrive/Yolov6/YOLOv6/infer.py --yaml /content/gdrive/MyDrive/Yolov6/YOLOv6/data/data.yaml --img-size 640 --weights /content/gdrive/MyDrive/Yolov6/runs/train/exp6/weights/last_ckpt.pt --source /content/gdrive/MyDrive/Yolov6/YOLOv6/data/images/test --device 0

Namespace(agnostic_nms=False, classes=None, conf_thres=0.4, device='0', half=False, hide_conf=False, hide_labels=False, img_size=[640], iou_thres=0.45, max_det=1000, name='exp', not_save_img=False, project='runs/inference', save_dir=None, save_txt=False, source='/content/gdrive/MyDrive/Yolov6/YOLOv6/data/images/test', view_img=False, weights='/content/gdrive/MyDrive/Yolov6/runs/train/exp6/weights/last_ckpt.pt', yaml='/content/gdrive/MyDrive/Yolov6/YOLOv6/data/data.yaml')
Save directory already existed
Loading checkpoint from /content/gdrive/MyDrive/Yolov6/runs/train/exp6/weights/last_ckpt.pt

Fusing model...
Switch model to deploy modality.
Traceback (most recent call last):
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/infer.py", line 116, in <module>
    main(args)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/infer.py", line 111, in main
    run(**vars(args))
  File "/usr/local/lib/python3.7/dist-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/infer.py", line 103, in run
    inferer = Inferer(source, weights, device, yaml, img_size, half)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/yolov6/core/inferer.py", line 50, in __init__
    self.model(torch.zeros(1, 3, *self.img_size).to(self.device).type_as(next(self.model.model.parameters())))  # warmup
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/yolov6/layers/common.py", line 360, in forward
    y, _ = self.model(im)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/yolov6/models/yolo.py", line 39, in forward
    x = self.backbone(x)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/yolov6/models/efficientrep.py", line 98, in forward
    x = self.stem(x)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/content/gdrive/MyDrive/Yolov6/YOLOv6/yolov6/layers/common.py", line 209, in forward
    return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py", line 457, in forward
    return self._conv_forward(input, self.weight, self.bias)
  File "/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py", line 454, in _conv_forward
    self.padding, self.dilation, self.groups)
RuntimeError: Given groups=1, weight of size [32, 3, 3, 3], expected input[1, 1, 3, 640] to have 3 channels, but got 1 channels instead

I am trying to train a object detection model using YOLOv6. Training is done but when I try to excecute the inference I get this error. My trainig image size is 640x640x1 and test image provided is in rgb only i.e in 3 channels.
p.s. This is my first question on the platform, sorry if any mistakes made....


text:
Q: Error code: DelimitedTextMoreColumnsThanDefined Azure Data Factory I am trying to copy data from a csv file to a sql table in Azure Data Factory
This is my type property for the CSV file
        "typeProperties": {
            "location": {
                "type": "AzureBlobStorageLocation",
                "fileName": "2020-09-16-stations.csv",
                "container": "container"
            },
            "columnDelimiter": ",",
            "escapeChar": "\\",
            "firstRowAsHeader": true,
            "quoteChar": "\""

I recieve following error:
ErrorCode=DelimitedTextMoreColumnsThanDefined,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=Error found when processing 'Csv/Tsv Format Text' source '2020-09-16-stations.csv' with row number 2: found more columns than expected column count 11.,Source=Microsoft.DataTransfer.Common,'
This is row #2
0e18d0d3-ed38-4e7f,Station2,Mainstreet33,,12207,Berlin,48.1807,11.4609,1970-01-01 01:00:00+01,"{""openingTimes"":[{""applicable_days"":96,""periods"":[{""startp"":""08:00"",""endp"":""20:00""}]},{""applicable_days"":31,""periods"":[{""startp"":""06:00"",""endp"":""20:00""}]}]}"
I think the last column, the JSON query is making trouble in this case. When I view the data it looks fine:

I thought exactly the "quoteChar": "\""would prevent that the last column makes problems. I have no idea why I am getting this error while i run debug

A: Try setting the escape character = " (a double quote). This should treat each pair of double quotes as an actual single quote and wont consider them as a "Quote Char" within the string, so you will end up with a string that looks like this (and which the system knows is a single string and not something it has to split):
{"openingTimes":[{"applicable_days":96,"periods":[{"startp":"08:00","endp":"20:00"}]},
{"applicable_days":31,"periods":[{"startp":"06:00","endp":"20:00"}]}]}

A: This is because this value "{""openingTimes"":[{""applicable_days"":96,""periods"":[{""startp"":""08:00"",""endp"":""20:00""}]},{""applicable_days"":31,""periods"":[{""startp"":""06:00"",""endp"":""20:00""}]}]}" contains several comma and your columnDelimiter is "," which leads to that value is split to several column. So you need to change your columnDelimiter.


text:
Q: Работа phpmyadmin и unicron - одновременно? server {
 listen 80 default_server;
server_name test_domain  www.test_domain;
root /var/www/test_domain;

index index.html index.htm index.php;

location / {
    try_files $uri $uri/ =404;
   # include proxy_params;
   # proxy_pass http://unix:/home/test/flask_api/myproject.sock;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
 }

location ~ /\.ht {
    deny all;
}

location /app {
    include proxy_params;
    proxy_pass http://unix:/home/test/flask_api/myproject.sock;
}

}

Я хочу, что бы по адресу http://192.168.120.137/phpmyadmin - отрывалась админ панель, а по адресу http://192.168.120.137/app - срабатывал unicorn - вызывая мой python-скрипт (flask). Проблема в том, что перенаправление на unicron - срабатывает, если я по корневому пути - / - прописываю proxy_pass, но  тогда это ломает мне доступ к phpmyadmin. Попытался прописать еще один путь - location /app , ео получаю 404 ? Как правильно настроить nginx в данном случае ?
UPD
Все же расскоментировал
include proxy_params;
proxy_pass http://unix:/home/test/flask_api/myproject.sock;

- в корневом пути и добавил / - в конце - т.е. вот так: proxy_pass http://unix:/home/test/flask_api/myproject.sock/; - что бы перенаправляло по остаточному пути, после myproject.sock, если там 404 - но теперь получаю 502 от ohomyadmin
UPD 2
Изменил маршрут во Flask:
@app.route("/app")
def hello():
    return "
Hello There!
"

конфиг nginx:
server {
 listen 80 default_server;
server_name test_domain  www.test_domain;
root /var/www/test_domain;

index index.html index.htm index.php;

location / {
    try_files $uri $uri/ =404;
   # include proxy_params;
   # proxy_pass http://unix:/home/test/flask_api/myproject.sock;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
 }

location ~ /\.ht {
    deny all;
}

location /app {
    include proxy_params;
    proxy_pass http://unix:/home/test/flask_api/myproject.sock;
}

}

После каждого изменения файла конфигурации ил python-скрипта - перезапускаю службы:
sudo systemctl restart flask_api.service && sudo systemctl restart nginx.service

, но все равно, по маршруту http://192.168.120.137/app/ - получаю 404 (проблемы с phpmyadmin - исчезли)
Вызов - sudo systemctl status flask_api.service - показывает, что сервис работает
/var/log/nginx/error.log - пустой (до этого удалял файл, что бы посмотреть, какие ошибки сыпятся)
/var/log/nginx/access.log - просто показывает 404 со второй машины - откуда обращаюсь


text:
Q: Why read.csv breaks lines longer than the first line into multiple rows? I have tried to read the following file in R using read.csv and it seems to me that whenever the first line of the file doesn't contain the largest number of columns, read.csv reads it incorrectly. Specifically, when I put the record "CCW12 ERV14 PER1 PTK2 RPN4 SEC66 SKY1 SUR4 VPS51 VPS52 VPS53 VPS54 VTC4" in the first line of my file then read.csv reads the file correctly into a 7-row table.
My file:
CCW12 ERV14 PER1 PTK2 RPN4 SEC66 SKY1 SUR4 VPS51 VPS52 VPS53 VPS54 VTC4
ERV14 HLJ1 ILM1 KRE1 PER1
BST1 ERV14 ERV25 HLJ1 KIN3 KRE1 LAS21 PER1 VPS38
ANP1 CWH43 ERV14 HLJ1 LAS21 PER1 SUR4 VPS51
CCW12 ERD1 ERV14 OST3 PER1 PMT2 SUM1 SUR4 TED1
ERV14 PER1 SEC66 SSH1 SUR4 VPS51
CCW12 PER1 PMT2 RPN4 SKY1 SUR4 TED1

y=read.csv("./file.txt", sep=" ", header=FALSE)
y
     V1    V2    V3   V4    V5    V6    V7    V8    V9   V10   V11   V12  V13
1 CCW12 ERV14  PER1 PTK2  RPN4 SEC66  SKY1  SUR4 VPS51 VPS52 VPS53 VPS54 VTC4
2 ERV14  HLJ1  ILM1 KRE1  PER1
3  BST1 ERV14 ERV25 HLJ1  KIN3  KRE1 LAS21  PER1 VPS38
4  ANP1 CWH43 ERV14 HLJ1 LAS21  PER1  SUR4 VPS51
5 CCW12  ERD1 ERV14 OST3  PER1  PMT2  SUM1  SUR4  TED1
6 ERV14  PER1 SEC66 SSH1  SUR4 VPS51
7 CCW12  PER1  PMT2 RPN4  SKY1  SUR4  TED1

But when I put that record in some other place, then read.csv puts breaks that record into two rows one of which contains the items {CCW12 ERV14  PER1 PTK2  RPN4 SEC66  SKY1  SUR4 VPS51} and the other contains {VPS52 VPS53 VPS54 VTC4}.
My file after I moved the first line to another place:
ERV14 HLJ1 ILM1 KRE1 PER1
BST1 ERV14 ERV25 HLJ1 KIN3 KRE1 LAS21 PER1 VPS38
ANP1 CWH43 ERV14 HLJ1 LAS21 PER1 SUR4 VPS51
CCW12 ERD1 ERV14 OST3 PER1 PMT2 SUM1 SUR4 TED1
ERV14 PER1 SEC66 SSH1 SUR4 VPS51
CCW12 ERV14 PER1 PTK2 RPN4 SEC66 SKY1 SUR4 VPS51 VPS52 VPS53 VPS54 VTC4
CCW12 PER1 PMT2 RPN4 SKY1 SUR4 TED1

y=read.csv("./file.txt", sep=" ", header=FALSE)
y
     V1    V2    V3   V4    V5    V6    V7    V8    V9
1 ERV14  HLJ1  ILM1 KRE1  PER1
2  BST1 ERV14 ERV25 HLJ1  KIN3  KRE1 LAS21  PER1 VPS38
3  ANP1 CWH43 ERV14 HLJ1 LAS21  PER1  SUR4 VPS51
4 CCW12  ERD1 ERV14 OST3  PER1  PMT2  SUM1  SUR4  TED1
5 ERV14  PER1 SEC66 SSH1  SUR4 VPS51
6 CCW12 ERV14  PER1 PTK2  RPN4 SEC66  SKY1  SUR4 VPS51
7 VPS52 VPS53 VPS54 VTC4
8 CCW12  PER1  PMT2 RPN4  SKY1  SUR4  TED1

I have checked with vim that there is no invisible/wired character in my file other than the spaces between two items in a record/line and end-of-line characters at the end of lines. So am I doing something wrong or is it an R problem?
I have seen one post that raises the same issue but couldn't find much help from there.

A: First of all, it's a bit odd to use read.csv when you don't actually have a comma separated value. read.table is a more natural choice.
But the main problem is that you don't have rectangular data. read.table and read.csv both output a data.frame where they assume each row has the same number of columns. R reads the first few lines of a file to figure out how many columns that is and what data type each column is. So if your longest line is after this "peeking" zone, then R won't expect that many columns. If you do know the maximum number of columns that your data has, you can specify a vector of that length to colClasses. So if the longest line has 30 values and they are all character, you can specify colClasses=rep("character",30).
It sounds like you might want consider alternate ways to read in your data and store it. Perhaps readLines or scan might be better choices. And you can keep your data in a list rather than a data.frame.


text:
Q: Inserting literal values along with razor into javascript I'm trying to insert quotes AND a value inside a javascript function.
I'm doing this through a foreach method call.
@foreach (DateEarningsViewClass d in Model.dateEarnings) {
                 @d.date.ToShortDateString()
             }

The issue is that I want to insert around each date, but I get all sorts of errors when I attempt doing so. How can I do this?
What I essentially wanna display is:
@foreach (DateEarningsViewClass d in Model.dateEarnings) {
                     "@d.date.ToShortDateString()",
                 }

A: Just try this:
@foreach (DateEarningsViewClass d in Model.dateEarnings) {
   @Html.Raw("\"" + d.date.ToShortDateString() + "\"")
}

A: You can use the  tag.
@foreach (DateEarningsViewClass d in Model.dateEarnings) {
    <text>"</text>
    @d.date.ToShortDateString()
    <text>"</text>
}


text:
Q: How to get access for ApplicationpoolIdentity on particular folder My deployed application is creating file on a shared location.
To get it work and allow applicaiton to write file on shared location, I have set applicaiton pool as domain\user account.
Please guide me how should i get it working using applicationpoolidentity account too ?

A: Versions of IIS 7.5 and later create a virtual app pool user account running under the umbrella of ApplicationPoolIdentity. This will be unique to that app pool and therefore won't be the same account as on another server.
You'll need to have the same specific local user account or domain user account set as having permissions against both the shared folder and the app pool.


text:
Q: Is basis change ever useful in practical linear algebra? In layman's terms, why would anyone ever want to change basis? Do eigenvalues have to do with changing basis?

A: Linear algebra is all about basis-change. Matrices are change of basis machines !
When you form a linear combination $a\vec u+b\vec v+\cdots c\vec w$, you can see it as the vector $(a,b,\cdots c)$ expressed in the basis $(\vec u,\vec v,\cdots \vec w)$.
For the same reason, a matrix product $AB$ expresses what the matrix $A$ becomes when applied to the vectors of the matrix $B$. And think that most matrix operations can be described as products of elementary transforms (which are changes of basis involving one axis or two).
Looking at the resolution of a system of linear equations, you can see it as a change of basis such that the hyperplanes corresponding to the equations become parallel to the axis, so that computing their intersections becomes trivial.

And so on, and so on.
The Eigendecomposition is indeed a convenient way to characterize a change of basis, as it finds the directions that are left unchanged by the transforms (the axis that are mapped onto themselves). These special directions are indeed quite interesting as the behavior of the transform is very simple there (just a scalar product).
Rotations are a particularly important class of transformations, as they preserve distances and cause no deformation (they are so-called "rigid-body" transforms). The Eigendecomposition expresses that any (diagonizable) transform can be seen as a rotation that aligns the Eigendirections with the axis, followed by a (possibly anisotropic) stretching of the axis, followed by the inverse rotation.
The Eigendecomposition generalizes as the Singular Value decomposition. It allows the two spaces to have differing dimensions, but still decomposes a transform as a sequence of rotation/scaling/rotation.

The Singular Values fully characterize the resizing/deformation (and possible loss of dimensions), giving a very synthetic view on the transform.

A: It's used to prove the Master Theorem. Diagonal matrices are very easy to take powers of ($diag(a_1,\ldots,a_n)^k = diag(a_1^k, \ldots, a_n^k)$) and we have $(PAP^{-1})^k = PA^kP^{-1}$. The Master Theorem relies on changing to a diagonal basis, taking a large power, and changing back.
At the least, try working out the explicit formula for the Fibonacci numbers this way.

A: \begin{equation}
\sum_{k=0}^{n-1}k^3 = \sum_{k=0}^{n-1}6\binom k3+6\binom k2 + \binom k1
 = 6\binom n4+6\binom n3 + \binom n2=\frac{n^4-2n^3+n^2}4.
\end{equation}
Hey, that change of basis in the space of polynomials was useful.

A: Note that the Fourier transform is simply a change of basis. It is entirely possible you're actually reading this very answer thanks to change of basis. Check out https://en.wikipedia.org/wiki/Orthogonal_frequency-division_multiplexing for instance. Edit: it might be weird to see the connection if you're just starting out with linear algebra. In signal processing among other fields, we generalize the notion of vectors in such a way that functions can also be seen as vectors. Starting from this idea, it might not be so weird to talk about basis changes for functions - which is exactly what the Fourier transform does. Indeed, this is what Taylor expansions does as well in a sense.
Another thing, in wireless communications with multiple transmitter/receiver antenna systemes (MIMO) it's very common to model the multiplicative noise in the channel as a linear transformation, i.e. the received signal is given by $\textbf{y} = H\textbf{x}$ (plus additive noise). I.e. there is one noisy channel for every pair of transmitter/receiver antennas. But by the singular value decomposition, we can find the appropriate change of basis for the transmitted signal that makes it "orthogonal to the channel" in the sense that $H$ is diagonal. This helps throughput lot.

A: Structural dynamics with the Finite Element Method
Computing the dynamic response of a structure is done with modal analysis.
The original vector space is displacements and rotations in each node. These are unsuited to dynamic response. The system of equations is therefore transformed into a new vector space where each element in the vector space represents a vibration mode.
Wikipedia has some nice animations of vibration modes, ordered from lowest to highest frequency:

Each mode (eigenvector) is the vibration to a specific frequency (eigenvalue). When these have been found, we can compute interesting stuff like the structural response to an earthquake of a certain frequency spectrum. Afterwards, the basis is changed back to the original to obtain forces and displacements in each node.

A: Changing basis allows you to convert a matrix from a complicated form to a simple form. It is often possible to represent a matrix in a basis where the only nonzero elements are on the diagonal, which is exceptionally simple. These diagonal elements will be the eigenvalues of the matrix. This is especially helpful in solving linear systems of differential equations. Often in physics, engineering, logistics, and probably lots of other places, you have a system of differential equations which all depend on each other. In order to solve the system directly, you would have to solve all equations at once, which is hard. We can use matrices to describe this system. By changing basis, you may be able to make that matrix diagonal, which effectively separates the differential equations from each other, so you can solve just one at a time. This is comparatively easy. Situations where I know this comes up are:

*

*Quantum mechanics, solving the Schrodinger equation to describe the state of matter on the quantum level.

*Electrical engineering, understanding the time-evolution of an electrical circuit.

*Mechanical engineering, understanding the motion of a linear mechanical system, such as multiple spring-mass system.

Edit:
Here is another very important reason for change of basis I just remembered: suppose you have a matrix $A$, and you want to calculate $A^n$ for some large $n$. This takes a while, even for computers. But, if you can find a change of basis matrix $P$ so that $A=P^{-1}DP$ for a diagonal matrix $D$, then $$A^n=P^{-1}DPP^{-1}DPP^{-1}DP...P^{-1}DP.$$ All of the terms $PP^{-1}$ are the identity, so we get $$A^n=P^{-1}D^nP.$$ Powers of diagonal matrices are really easy: just raise each diagonal element to the $n$th power. So this method allows us to find powers of matrices very easily. When would we ever want to take large powers of matrices? Whenever finding numerical solutions to differential equations, partial or ordinary. This comes up all the time, so we are glad that we can change bases!

A: Practical speed related aspects Matrix multiplication and division and equation system solving can become much faster to perform in some bases than others. Often one can cut the algorithmic complexity so much that it becomes a difference between something being practically useful or far too slow for usefulness. The reason for this is that the underlying field of elements provides $1$ and $0$ elements which by definition make multiplication and addition simpler. $$\text{field properties for the elements 1 and 0 utilizable for saving calculations}\begin{cases}a \cdot 0 &= 0\\ a + 0 &= a\\a\cdot 1 &= a\end{cases}$$
The first two together lets us ignore whole parts of scalar products with zero elements which is the main gain. Then the third one allows us to avoid multiplications which can be nice as in computers adding is less computationally complex than multiplying, saving hardware on the chip or clock cycles.
$${\bf D} = \left(\begin{array}{ccccc} d_1&0&0&\cdots&0\\0& d_2 & 0 &\cdots & 0\\0&0&\ddots& \ddots &0\\0&0&\ddots&d_{n-1}&0\\0&0&\cdots&0&d_n\end{array}\right) \hspace{1cm}  {\bf C} = \left(\begin{array}{ccccc} {\bf C_1}&\bf 0&\bf 0&\cdots& \bf 0\\\bf 0& \bf C_2 & \bf 0 &\cdots & \bf 0\\ \bf \bf 0&\bf 0&\ddots& \ddots &\bf 0\\\bf 0&\bf 0&\ddots& \bf C_{n-1}&\bf 0\\\bf 0&\bf 0&\cdots&\bf 0&\bf C_n\end{array}\right) \hspace{1cm}$$
Diagonal matrix to the left, only n non-zero values - the ones on the diagonal. Block-diagonal matrix to the right. The $\bf C_k$ matrices on the diagonal are square and by properties of matrix multiplication will multiply onto their own position only. The larger we can make these $\bf 0$ matrices the more time we can save when doing computations.
Theory understanding aspects Basis change is the basis of understanding more advanced algebra. Eigenvalues, eigenvectors and matrix diagonalization are the first "steps" to that. Then canonical bases of various kinds and matrix representation of groups and fields with simultaneous block-diagonalizations ( that a set of matrices which multiply onto each other can be put on the same block-diagonal form ). Can be used to create an understanding and a framework for systematic work on these more advanced algebras.

A: Changing basis can make it easier to understand a given linear transformation.
Suppose $T:V \to V$ is a linear transformation.  It may seem difficult to understand or to visualize what effect $T$ has when it is applied to a vector $x$.
However, suppose we are lucky enough to find a vector $v$ with the special property that $T(v) = \lambda v$ for some scalar $\lambda$.  Then, it's easy enough to understand what $T$ does to $v$, at least.
Suppose we are lucky enough to find an entire basis $\{v_1,\ldots,v_n\}$ of these special vectors.  So
$T(v_i) = \lambda_i v_i$, for some scalars $\lambda_i, i =1,\ldots,n$.
Given any vector $x$, we can write $x$ as a linear combination of the vectors $v_i$:
\begin{equation}
x = c_1 v_1 + \cdots + c_n v_n.
\end{equation}
And now it seems easier to think about $T(x)$:
\begin{align}
T(x) &= c_1 T(v_1) + \cdots + c_n T(v_n) \\
&= c_1 \lambda_1 v_1 + \cdots + c_n \lambda_n v_n.
\end{align}
That is fairly simple.  Each component of $x$ (with respect to our special basis)
simply got scaled by a factor $\lambda_i$.
So if we can find a basis of eigenvectors for $T$ (and often we can), then it helps us to understand $T$.

By the way, one great practical example of a change of basis is computing a convolution efficiently using the fast Fourier transform (FFT) algorithm.  Any discrete convolution operator is diagonalized by a special basis, the discrete Fourier basis.  So, to perform a convolution on an image (in image processing), you take the FFT of the image (you change basis to the Fourier basis), then you multiply pointwise by the eigenvalues of the convolution operator, then you take the inverse FFT (change back to the standard basis).  This approach is much, much faster than performing convolution in the space domain.

A: You may have noticed multiplying matrices can be hard. By changing bases, we can make it easier.

A: Singular Value Decomposition, which is one of the most widely-used techniques in numerical computing, is a basis-change. It takes a linear transformation, and does a basis change on both the input space and the output space so that the transformation becomes just multiplication with no addition (ie a diagonal matrix).
This uncovers a lot of useful information about the transformation such as which input variables play the biggest role, how correlated they are to each other, whether there are any irrelevant variables, etc. It is pretty much the sledge-hammer for doing numerical computing with matrices.

A: Solid mechanics. Computing the principal stresses/strains in a material involves a change of basis. With the principal stresses, we can compute the maximum normal stress and maximum shear stress the material experiences. And these maxima tell us whether the material will become damaged or not.


text:
Q: Streamming a h.264 coded video over UDP I don't know too much about h.264, but the thing is that I've got this video in h.264 in a mp4 container which I would like to stream over UDP.
My question is simple, is there any tweaks I can maybe do while coding the video so that it comes out fairly tolerant to some "light" packet loss?
I know that compressed video usually has a keyframe every N frames and then in between those it just sends the deltas. I can imagine h.264 should is a lot more complex than that, and so the it might not be just so simple.
To be more precise, I've been making some experiments and realized that just by removing 1024 bytes out of a stream of video, I render it completely "unplayable" from the point of the loss and on.
What I would like is for it to tolerate light losses like that, is it possible?
Thanks
Nelson

A: It depends on what data you're losing.  Some data in the H264 stream is not data that can be lost.  For example, if your experiment where you dropped 1024 bytes happened to be the first 1024 bytes you sent, then you probably dropped your Sequence Parameter Set and Picture Parameter Set (SPS/PPS), which is basically the information that tells the decoder how to interpret the incoming information.  You also probably can't just drop a random 1024 bytes out of the stream; typically H264 is packetized so that sort of thing wouldn't happen anyway.
So H264 does contain some small pieces of data that really aren't "discardable"; many of the streaming protocols like RTSP make this clear by specifically stating you SHOULD NOT send this sort of information through the lossy transport channel, but instead during the SDP exchange (which happens over TCP).
As far as loss-tolerance goes, H264 does have features that are supposed to aid loss tolerance (ASO, FMO, etc.), but in practice most encoders don't support them.  If you can, I'd use x264; their low-latency streaming configuration purportedly works well even with packet loss as high as 20% or more.  If your H264 is already encoded, then there's not much to be done.  Your video is already encoded and you'll have to stream it as-is.


text:
Q: transferring a property into an event function within an objects method I am trying to take an objects property and transfer it into a keypress event - trouble is you can only add the event itself and using this.x_point will not work in a child function. here is my code. i could also tranfer this.x_point to var.x_point and then use it but that ruins the point of it being an object at all.
function ninja(name, speed){
this.name = name;
this.speed = speed;
this.x_point = 0;
this.y_point = 0;
loadImages("n_main", 0, 0);
loadImages("n_armL", -5, 8);
loadImages("n_armR", 25, 8);

}
ninja.prototype.move = function(){
window.addEventListener("keydown", keyPress, false);
function keyPress(e){
    if(e.keyCode == 68){ //d
        alert(this.x_point);
    }
}

}

A: You can use bind for this:
ninja.prototype.move = function(){
window.addEventListener("keydown", keyPress.bind(this), false);
function keyPress(e){
    if(e.keyCode == 68){ //d
        alert(this.x_point);
    }
}

Or if you use jQuery try jQuery.proxy(keyPress, this).

A: If you use that for example:
ninja.prototype.move = function(){
 var that = this;
 window.addEventListener("keydown", keyPress, false);
 function keyPress(e){
  if(e.keyCode == 68){ //d
    alert(that.x_point);
 }
}


text:
Q: version control for binary files I'm in the process of writing a program that will use its own binary format for storing data.
I would like to make possible to have some form of version control, at the very least two different people should be able to make changes on a file and after that merge this changes.
As git seems to be a very common and very powerful version control system, I am wondering if it is possible to use it.  I have only basic knowledge of git (pull add commit push), but I understand it has more advanced features. I want to understand if I can implement some basic functionality and get all the advanced features for free.
So the use case is that each project would consist of a sole binary file, and git would have to be able to work with it.
I've been searching and got to understand that I would have to write a custom mergetool ? Is my understanding correct?
I also understand that a three-way merge is done by a diff3 program or at least that git has some of it functionality embedded. Would I have to write a custom version of it? Would it be even possible to use it with git? Would it be necessary to recompile git?
git also stores commits as changes in order to save space. Does it use diff for it? Would be possible to replace it? Would git need to be recompiled?
Is there any other kind of functionality that I would have to implement?
My initial plan was to use a single file for the project, but each project is made of independent sub-projects, that would be merged independently. Would I gain anything by storing the project as different files for each subproject?
Is there anywhere some good documentation on to what interface a diff , diff3 and mergetool must conform? In which languages could these be written?
I'm quite confused because everyone seems to be interested in eliminating binary files from version control and apparently nobody wants to use git on them. Is it a bad idea? I feel like any kind of data for which merging makes sense in some way should be version controlled.

A:
So the use case is that each project would consist of a sole binary file, and git would have to be able to work with it.

There are 3rd party tools for handling binary files.

but each project is made of independent sub-projects

In git you have submodules && subtree for this purpose
git submodule add only pick latest Commit

Is there anywhere some good documentation on to what interface a diff , diff3 and mergetool must conform?
In which languages could these be written?

Read this out, there is a references to diff2 & diff3 algorithm
What is the diff version git use? diff2 or diff3?


text:
Q: Identification of a space with a subset of the topological cone
Let $X$ be a topological space and define the cone $c(X)= (X \times I)/(X \times \{1\})$. Identify $X$ with $\{\{(x,0)\} \mid x \in X\} \subset c(X)$. Show that a continuous map $f:X \to Y$ is null-homotopic if and only if it has a continuous extension $g:c(X)\to Y$.

I might have missed a part in lectures on quotient spaces, but what do they mean by "identifying" $X$ with the set $\{\{(x,0)\} \mid x \in X\}$? Do they want me to treat the points of $X$ as the elements $\{(x,0)\}$? If so what is the purpose of this identification?

A: You don't need to do much. As you said, treat points in $X$ as points in $c(X)$, specifically by regarding each $x \in X$ as $\{(x, 0)\} \in c(X)$.
Why the set brackets? Remember, $c(X)$ is a quotient of $X \times I = X \times [0, 1]$, identifying all the points of the form $(x, 1)$ together. This means $c(X)$ will consist of equivalence classes of points, where $X \times \{1\}$ is one equivalence class, making all points of the form $(x, 1)$ equivalent, and every other point $(x, t)$, where $0 \le t < 1$, forms its own equivalence class $\{(x, t)\}$.
Why do we do this identification? It makes things nicer. It also is necessary for the question to make sense. It talks about $f : X \to Y$ having a continuous extension $g : c(X) \to Y$. This only makes sense if $X$ is a subset of $c(X)$, which it is not, strictly speaking. By pretending that $\{(x, 0)\} \in c(X)$ and $x \in X$ are the same point, then $X$ becomes, in our eyes, a subset of $X$, so the idea of extending it to the rest of $c(X)$ makes sense.


text:
Q: Javascript window.scrollTo Behavior On Different Browsers I'm facing an issue with the scrollTo function when the body has an dir=rtl attribute. here is a jsfiddle for my case.
HTML:

    window.scrollTo(-200, 0);

So if I pass a positive value for the xpos parameter, it works on IE (sort of) naturally, it scrolls from the right side of the screen for an amount of 200px. but on chrome and firefox it doesn't work, I have to pass a negative value for the scrolling to work as expected.
My question, is how I can handle this case in my code, should I do browser sniffing? or is there a better way? some feature I can test if its supported?

A: This snippet worked for me on IE and Chrome
http://jsfiddle.net/05w4tr0g/4/
var m = -1;
var pos = window.pageXOffset;
window.scrollTo(0,0);
window.scrollTo(1, 0);
if (-1 == window.pageXOffset) m = 1;
window.scrollTo(pos, 0);
window.scrollTo(m*200, 0);

Hope that helps. The idea is that that the pageXOffset is with IE and Chrome always negative if there was scrolling. The snippet will cause a little flicker because of the test scroll to x=0 and x=-1.
You could store the m value on a page load and reuse it in a wrapper function for scrollTo (or scrollBy for that matter). You could also overload the two methods and keep it all in the window context.

A: as othree explains in his jQuery rtl scroll type plugin there are 3 main implementations for horizontal scrolling when dir is set to rtl: WebKit, Firefox/Opera and IE
the difference between these implementations is as follows:

because you can't use jQuery I've modified othree code in this plunker and it works fine in chrome, firefox and IE11


text:
Q: Reflecting ionic2 project changes in XCode Reflecting new changes of ionic2 project in xcode is a painful process for me.
I tried these commands:

*

*sudo ionic state restore

*sudo ionic prepare ios

from command line
and tried Product => Clean & rebuild from xcode, but still having the old project
Am using XCode Version 8.2.1 (8C1002) on macOS Sierra version 10.12.3
Any idea?


text:
Q: Hidding an element as alternative to animation I have the following CSS Plunker Example:
@-webkit-keyframes ngdialog-fadeout {
  0% {opacity: 1;}
  100% {opacity: 0; }
}

@keyframes ngdialog-fadeout {
  0% {opacity: 1;}
  100% {opacity: 0; }
}

.ngdialog.ngdialog-closing .ngdialog-overlay {
  -webkit-backface-visibility: hidden;
  -webkit-animation: ngdialog-fadeout 0.5s;
  animation: ngdialog-fadeout 0.5s;
}

.ngdialog.ngdialog-closing .ngdialog-content {
  -webkit-backface-visibility: hidden;
  -webkit-animation: ngdialog-fadeout 0.5s;
  animation: ngdialog-fadeout 0.5s;
}

I do not want to use animation. So I tried the following:
.ngdialog.ngdialog-closing .ngdialog-overlay {
  visibility: hidden;
}

.ngdialog.ngdialog-closing .ngdialog-content {
  visibility: hidden;
}

I am able to hide it but after doing it every link on the page is non reactive like something is over it ...
What am I missing?
UPDATE
I tried the following:
.ngdialog {
  bottom: 0;
  left: 0;
  overflow: auto;
  position: fixed;
  right: 0;
  top: 0;
  z-index: 10000;
  -webkit-overflow-scrolling: touch;
}

.ngdialog-overlay {
  background-color: black;
  bottom: 0;
  left: 0;
  position: fixed;
  right: 0;
  top: 0;
  opacity: 0.6;
  z-index: 100000;
}

.ngdialog.ngdialog-closing .ngdialog-overlay {
  opacity: 0;
  visibility: hidden;
}

.ngdialog-content {
  background: white;
}

.ngdialog.ngdialog-closing .ngdialog-content {
  opacity: 0;
  visibility: hidden;
}

The same problem happens ...

A: Best way that I could find to "disable" animations from ngDialog is actually to speed them up so that they won't be visible anymore.
.ngdialog * {
  -webkit-animation-duration: 0.01s !important;
  -moz-animation-duration: 0.01s !important;
  -o-animation-duration: 0.01s !important;
  -ms-animation-duration: 0.01s !important;
  animation-duration: 0.01s !important;
}


text:
Q: Test for, and compare means of folded normal distribution I have two datasets of absolute distances to a single point in a 2D space. I have reasons to expect that if I had the sign and magnitude of these distances, my datasets would be normally distributed with a mean of zero.
Think of the datasets to be the absolute distances from the Bull's eye in a game of darts. I have a set of these distances for two different players, and I would like to compare the performance of the two players (both players had to aim for the Bull's eye).
I think the 'folded normal distribution' applies to my dataset. Since I would like to compare the two datasets, I need to answer the following questions.

*

*How can I verify that I indeed have a 'folded normal distribution'?

*How can I compare the (means of) these two datasets in this distribution? For example, am I allowed to use ANOVA?

Thank you!

A: Multiply each data point by $+1$ or $-1$, taken independently with equal probabilities.  If your datasets are indeed samples from folded normal distributions, you will now have normal distributions with mean $0$, and you can use any of the tools appropriate thereto.

A: I like @Robert Israel's answer above for verifying your distribution as half-normal (half-normal since you believe it came from normal with mean zero, thus simpler than general folded-normal distribution).  Another approach may be to compare a normalized histogram of your data to the probability density function for a half-normal distribution, which is
$$
p(x) = \frac{2}{\sqrt{\pi}\sigma}\exp\left(-\frac{x^2}{2\sigma^2}\right)
$$
You'd need to use a $\sigma$ parameter, that you could perhaps empirically find using a normal fit from the ±1 approach above, or play around with the parameter if you just want to get a feel for the distribution.


text:
Q: Odoo 12 : How to prevent default field method to be executed
I scheduled an cron that execute every 1st of the month, the purpose is to allocate leave for all employee according to their tags. here is sample of my code :
for leave in leave_type_ids:
    for employee_tag in employee_tag_ids:
        values = {
            'name': 'Allocation mensuelle %s %s' % (now.strftime('%B'), now.strftime('%Y')),
            'holiday_status_id': leave.id,
            'number_of_days': employee_tag.allocation,
            'holiday_type': 'category',
            'category_id': employee_tag.id,
        }
        try:
            self.create(values).action_approve()
        except Exception as e:
            _logger.critical(e)

I want to point out that self is instance of 'hr.leave.allocation'.
The problem is when I create the record, the field employee_id is automatically fill with the user/employee OdooBot (the one who executed the program in the cron) and that is not all, the employee OdooBot was allocated a leaves.
This behavior is due to those codes in odoo native modules :
    def _default_employee(self):
        return self.env.context.get('default_employee_id') or self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
    employee_id = fields.Many2one(
    'hr.employee', string='Employee', index=True, readonly=True,
    states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, default=_default_employee, track_visibility='onchange')

So my question is how to prevent this when it's the cron and set it to normal when it's in Form view?
The field "employé" should be empty here (in image below), because it is an allocation by tag.

A: You must loop over hr.employee because then you can do either of the following:
self.with_context({'default_employee_id': employee.id}).create(...)

OR
self.sudo(employee.id).create(...)


text:
Q: Template string as object or array of object I'm currently trying to fix the annotations of a function of my project that looks like this :
https://psalm.dev/r/7b974e8822
However, it always refuse something like A::class . '[]' as a class-string and would like only a string. But doing so I lose my type hint. How should I do it ?
I actually don't know if I missed something in Psalm documentation or if I should open an issue to support it. I'm have to use this because of symfony serializer. I know I can still force it, but I would like to find the way to make it work in a proper way. Psalm support in phpdoc B[] so I see no reason to not support it as a param value.


text:
Q: How can I prettify Join Result on Rest API response object? I started learning about building REST API using PHP as core language and I came into issue with creating response object. I have table users and user_social inside my MySQL database. What I am trying to achieve is to get response object to be like this:
{
    id,
    name,
    age,
    social: [
        twitter,
        facebook,
        github
    ]
}

My sql query looks like this currently:
select users.id, users.name, users.age, user_social.* from users inner join user_social on users.id = user_social.user_id limit 10;

And my JSON response looks like this currently:
{
    id,
    name,
    age,
    twitter,
    facebook,
    github
}

So the question is, how can I group results from join to be in structure like I want to be? Is there MySQL way or I should map it by looping through each record inside PHP and then send response.

A: MySQL just returns rows and fields. You should reformat it with PHP.


text:
Q: carto sidebar not showing just started learning how to use carto using the tutorial HERE. My sidebar isnt shown anywhere on my dashboard. How do i find this so that i can continue with the tutorial.

A: That tutorial is outdated. You need to go to the new CARTO Learn website for updated guides and documentation.


text:
Q: Calling controller method from Javascript function i want to call a controller method from a javascript method. I have the following code:
function test() {
        $.ajax({
        url: @Url.Action("abc"),
        method: 'GET',
        success: function(data) { alert(data); }
   });
     }

[HttpGet]
        public string abc(string id)
        {
            return "Info";
        }

How is it possible to get the "info" string back, in my alert() in the Javascript controller?

A: You need to add dataType attribute in ajax call.
Try this one:
function test() {
    $.ajax({
      url: @Url.Action("abc"),
      method: 'GET',
      dataType: "text",
      success: function(data) { alert(data); }
   });
 }


text:
Q: ggforest - sizing and change landscape to portrait in R I have a huge ggforest (20 variables) that I cannot show due to embargo of the data. (example below)

Right now the font is 0.7, and I have to make the plots window really big in order to see it all. The plot perfectly fits the PLOT WINDOW as landscape (making it bigger and bigger) the problem is when I narrow the window for a "landscape" view (aka to have a "vertical" plot, the font is illegible. Also the plot window doens't appear to have a scroll down option, and I can only see what the window can fit.
I need help. (also I would like to make the font bigger)


text:
Q: Image flickering In Chrome This Piece of code I am using to refresh a div without complete page refresh. Its working fine in all browsers , except chrome the functionality of auto refresh is working but after given time interval Images of that section is blinking. How to stop The blink in chrome.
 <script>
 $(document).ready(function() {
     $("#multicomment").load("refresh.php?id=<?php echo $conversation['id'];?>");
   var refreshId = setInterval(function() {
      $("#multicomment").load('refresh.php?id=<?php echo $conversation['id'];?>');
   }, 1000);
   $.ajaxSetup({ cache: false });
});
</script>

Desired Output Which I need: I want to create a comment section with user profile Image.If anybody comments on a particular topic That comment will reflect without pressing Ctrl+F5 with commenter's profile pic Like many social networking sites.


text:
Q: What does it mean for an almost complex structure to be compatible with a Riemannian metric? This is on p. 37 of The Ricci Flow and the Sphere Theorem by Simon Brendle. The author is going to show that a gradient Ricci soliton on $S^2$ has constant scalar curvature.
Here is the setting: Let $(S^2,g)$ be a gradient Ricci soliton, i.e., there exists $\rho\in\mathbb{R}$ and $f:S^2\to\mathbb{R}$ such that $D^2f=(\rho-\operatorname{scal}_g/2)g$. Let $\xi$ be the gradient vector field of $f$. The author then says:

We assume that $J$ is an almost complex structure on $S^2$ which is compatible
  with the metric $g$.

I have several questions around this sentence.
Firstly, what does it mean to be compatible? Does it mean that $g(-,J-)$ should be a symplectic form on $g$? In particular, it should be closed as a $2$-form?
Secondly, if my understanding is correct, then why does such an almost complex structure exist?
Thirdly, I am confused because this is used in the next proposition, which says that $J\xi$ is a Killing vector field. The proof the author gave goes thus: $$\begin{aligned}\mathcal{L}_{J\xi}g(X,Y)&=-g(D_X\xi,JY)-g(D_Y\xi,JX)\\&=-D^2f(X,JY)-D^2f(Y,JX)\\&=0.\end{aligned}$$ Here $\mathcal{L}$ denotes the Lie derivative, and $D$ denotes the Levi-Civita connection. However, what I get is $$\mathcal{L}_{J\xi}g(X,Y)=g(D_XJ\xi,Y)+g(D_YJ\xi,X).$$ So how do I get the above formula? Should something similar to $D_XJ=0$ hold?

A: $1)$ An almost complex structure $J$ is compatible with a Riemannian metric $g$ if $g(Jv, Jw) = g(v, w)$ for all $v$ and $w$. If that is the case, then $\omega(v, w) = g(Jv, w)$ is a two-form. If this form is closed, then $\omega$ is a symplectic form and $g$ is called a Kähler metric. In real dimension two, $\omega$ is automatically closed.
$2)$ A two-dimensional surface admits an almost complex structure if and only if it is orientable. If $X$ is an oriented surface, then choosing a Riemannian metric on $X$, we obtain the corresponding Hodge dual $\ast : T^*X \to T^*X$ which satisfies $\ast^2 = -\operatorname{id}_{TX}$. The Riemannian metric also gives rise to an isomorphism $\Phi_g : TX \to T^*X$ which allows us to construct the map $J : TX \to TX$ given by $J = \Phi_g^{-1}\circ\ast\circ\Phi_g$. As $J$ satisfies $J^2 = -\operatorname{id}_{TX}$, it is an almost complex structure on $X$. Moreover, it is compatible with $g$, see this question.
$3)$ For any almost complex structure $J$, we have $DJ = 0$ if and only if $\omega$ is closed and $N_J = 0$ where $N_J$ denotes the Nijenhuis tensor, see this question. That is, $DJ = 0$ if and only if $J$ is integrable and $g$ is Kähler. Every almost complex structure on a surface is integrable, see this question, and every compatible metric is Kähler, so $DJ = 0$ in this case. Therefore,
$$D_X(J\xi) = (D_XJ)(\xi) + J(D_X\xi) = J(D_X\xi)$$
so
\begin{align*}
\mathcal{L}_{J\xi}g(X,Y) &= g(D_XJ\xi,Y) + g(D_YJ\xi,X)\\
&= g(JD_X\xi, Y) + g(JD_Y\xi, X)\\
&=g(J^2D_X\xi, JY) + g(J^2D_Y\xi, JX)\\
&= -g(D_X\xi, JY) - g(D_Y\xi, JX)
\end{align*}
where we have used compatability of the almost complex structure $J$ with the Riemannian metric $g$ in the third equality.


text:
Q: Node.js Callbacks: Call a grand_callback when all callbacks are returned I have task to search meaning of certain words via lookup on a database for which i am making asynchronous calls to the database, every request would look for sat n number of terms.
The issue i have is I want to call another call back, say, grand_callback, the goal of this callback is to aggregate data from all other callbacks and process the next set of codes after aggregating all the data.
Is there a way I can implement the same..
Some details:
terms = [........] // 1000 terms
grand_callback = () ->
  #called with aggreagted data.
getbucket_data = (bucket ,callback) ->
  #some treatment over terms
  callback null , data
some_func = (term) ->
  bucket.push term
  if bucket.length is 15{
     getbucket_data bucket , (err, data)->
        #i need to aggregate this data
}
_.map terms , some_func

A: You can, of course, just keep track of which callbacks are done manually, but this can be a pain and pretty error prone if you have to do it a lot. Perhaps you could benefit from one of these solutions:
1. Use an async library
I personally like using async by caolan. It has a bunch of functions that can be useful for managing asynchronous operations; the one you're looking for is probably parallel (docs):

parallel(tasks, [callback])
Run the tasks array of functions in parallel, without waiting until the previous
  function has completed. If any of the functions pass an error to its
  callback, the main callback is immediately called with the value of the error.
  Once the tasks have completed, the results are passed to the final callback as an
  array.

So you would do something like:
async.parallel([
  asyncFunctionOne,
  asyncFunctionTwo,
  asyncFunctionThree
], function(error, results) {
  // ...
});

2. Use promises
Promises are a nice abstraction on top of asynchronous operations. A promise represents a value that either exists now or will exist in the future; you don't have to care which. You can wait for multiple promises to complete by creating a new promise that contains them all. One of the most popular promise libraries for Node is Q by kriskowal.
// creating a promise manually
var deferred1 = Q.defer();
var promise1 = deferred1.promise;

asyncFunction1(function(err, value) {
  if (err) deferred1.reject(err);
  else deferred1.resolve(value);
});

// wrapping a Node-style function to create promises
var promise2 = Q.nfcall(asyncFunction2, arg1, arg2);

// Create a promise that waits for all other promises
var grandPromise = Q.all([promise1, promise2]);
grandPromise.then(Q.spread(function(promise1result, promise2result) {
  // ...
}));


text:
Q: lxml will return empty lisy but requests_html will return wanted result I wrote two codes one with requests and lxml other with request_html. The code with requests and lxml will return an empty list while the code with request_thml will return the wanted result.
code 1:
from lxml import html

url = 'https://www.amazon.com/OnePlus-Glacial-Unlocked-Android-Smartphone/dp/B08723759H/ref=sr_1_1?dchild=1&keywords=oneplus&qid=1624692877&sr=8-1'

page = requests.get(url)

content = html.fromstring(page.text)

price = content.xpath('//*[@id="productTitle"]')

print(price)

#output is always
#[]

code 2 :
from requests_html import HTMLSession

url = 'https://www.amazon.com/OnePlus-Glacial-Unlocked-Android-Smartphone/dp/B08723759H/ref=sr_1_1?dchild=1&keywords=oneplus&qid=1624692877&sr=8-1'

session = HTMLSession()

r = session.get(url)

r.html.render(sleep=1)

title = r.html.xpath('//*[@id="productTitle"]', first=True)

print(title)

#output

#OnePlus 8 Glacial Green, 5G Unlocked Android Smartphone U.S Version, 8GB RAM+128GB Storage, 90Hz Fluid Display,Triple Camera, with Alexa Built-in,


text:
Q: j2me form (on android) Im running an j2me app on android.
Im aware that form runs in fullscreen, but since on android all actions are in menu i would like to get rid of the action buttons on form.
How can i do that?

A: You should write a native Android app. Running J2ME apps on Android is never a good idea:

*

*they are not native, so they won't "feel right"

*you will not be able to use a lot of the goodies the platform offers you (such as the menu button)

*the interface will most probably look a bit bodged

*J2ME apps are harder to debug

*you might even run into performance issues

Try porting your J2ME app to the Android SDK. Keep only the non-interface stuff (any calculations, api libs, etc.) and rewrite the interface stuff using the Android SDK. It's a bit more work, but it will be completely worth it.

A: You can use an automatic conversion tool from J2ME to Android. UpOnTek provides an automatic conversion tool, which includes optimization tips for the app. Take a look at www.UpOnTek.com or contact michal.geva@UpOnTek.com for more details.


text:
Q: Git command output is in editor (vim) and not directly to terminal output I don't know why but the output from some git command are in editor (vim) and not directly to the terminal output.
By example, the command git branch open vim and list the branches but I would like that the output are directly in the terminal.
I didn't set vim as default editor on the git config.
My config is Ubuntu 18.04 and zsh with oh-my-zsh plugin.
Thanks in advance for your replies

A: Reply to myself.
It is a default behavior change introduced in git 2.16.
With git --no-pager branch or git config --global pager.branch false it's ok


text:
Q: Accessing controls through threads I use WebBrowser Control in c# to check a couple search engine results but sometime for no reason it gets stuck. My first thought was to make each searching function as a thread and use thread.abort() from a timer but I just couldn't handle with the UI Controls (including the WebBrowser) no matter what I've tried.
Anyone has a solution for me? an example would be great cause I already tried so many things and I keep getting all these exceptions.

A: I believe you can use WebRequest in a Background worker & avoid the difficulties of dealing with the COM threading model.  You can use WebRequest.Timeout to handle anything you think is taking too long.
Try something like this:
   static void Main(string[] args)
   {
       BackgroundWorker bg = new BackgroundWorker();
       bg.DoWork += backgroundWorker_DoWork;

       bg.RunWorkerAsync(new List<object> { "http://download.thinkbroadband.com/512MB.zip" });
       while (true) {}
   }

   private static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
   {
       Console.WriteLine("Starting operation.");
       BackgroundWorker bw = sender as BackgroundWorker;

       List<object> args = (List<object>)e.Argument;

       var url = (string)args[0];
       WebRequest request = WebRequest.Create(url);
       request.Timeout = 300;

       try
       {
           WebResponse response = request.GetResponse();
           Console.WriteLine("Request successful.");
       }
       catch (Exception ex)
       {
           Console.WriteLine("Request timed out.");
       }
   }

WebBrowser is a component you should use when you want to embed an instance of IE into your presentation layer.  Unless you need this, you can use something more lightwweight.

A: Use the control's .Invoke() method: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx
There are other methods you can use too: .BeginInvoke and .EndInvoke for asynchronous invokes.
if(control.InvokeRequired)
{
    control.Invoke(control.delegate);
}


text:
Q: Run a Spring Boot application with elastic-apm Java agent on OpenShift I want to deploy a Spring Boot application on an OpenShift cluster that I want to monitor with elastic-apm, therefore, with the JAVA elastic agent.
I managed to deploy in a project an Elasticsearch instance, a Kibana instance and an apm-server.
Next to that, I also managed to deploy my Spring Boot application. For this I used the web console. I imported my project from GitLab, and chose the Java 8 image builder. However, using this method, I didn't find a way to launch my application by associating the java-agent elastic-apm-agent.
Locally, I run this command to start my application:
mvn package && java -javaagent:elastic-apm-agent/elastic-apm-agent-1.26.0.jar \
-Delastic.apm.service_name=ms-salarie \
-Delastic.apm.server_urls=http://localhost:8200 \
-Delastic.apm.secret_token= \
-Delastic.apm.environment=development \
-Delastic.apm.application_packages=com.leanerp.salarie \
-Delastic.apm.config_file=elastic-apm-agent/elasticapm.properties \
-jar target/salarie-1.1.3-SNAPSHOT.jar

Is there a way to override the command launched by the container of my application? Or another solution allowing me to use the elastic-apm-agent?
I am a newbie on OpenShift, so I don't fully understand all the concepts.

A: Ok, so the answer was adding this environment variable :
JAVA_OPTS_APPEND=-javaagent:{{path_to_elastic_apm_agent}}

this command allows you to launch your java application with options.

A: The Java agent allows multiple ways to configure it, one of which are command line system properties. Others include packaging an elasticapm.properties resource file or setting environment variables.
Check out the docs. Small excerpt:

*

*Properties file: The elasticapm.properties file is located in the same folder as the agent jar, or provided through the config_file option. dynamic config.

*Environment variables: All configuration keys are in uppercase and prefixed with ELASTIC_APM_.

Different option sources have different priority and precedence.
To attach the agent to a running JVM process (from within your application), you can use the API to self-attach.


text:
Q: Match and mark the positions of elements of a vector along a given axis of a numpy array I want to mark all maxima along a given axis of an array (which shape may be n-dimensional), this works fine along the first one, but for the rest I can't figure it out. I don't want to iterate over axis, because there can be arbritarily many of them.
>>> A = range(5)*3
>>> A = array(a).reshape([3,5], order='F')
>>> A
array([[0, 3, 1, 4, 2],
       [1, 4, 2, 0, 3],
       [2, 0, 3, 1, 4]])
>>> B = amax(A, axis= 0)
>>> C = amax(A, axis= 1)
>>> B == A
array([[False, False, False,  True, False],
       [False,  True, False, False, False],
       [ True, False,  True, False,  True]], dtype=bool)

This is what I want it to do for:
>>> C == A
False

but (of course) it does not.
How to get this working?

A: In response to your direct example, when you do :
>>>A == C
False

it "doesn't work" because numpy doesn't understand how to broadcast the operation to give you the output your want.
using transpose twice you can get a simpler solution than what you proposed :
>>>C = amax(A, axis=1)
>>>transpose(C == transpose(A))
array([[False, False, False,  True, False],
       [False,  True, False, False, False],
       [False, False, False, False,  True]], dtype=bool)

A: I finally came up with:
def tiletuple(t,axis):
  m = [1]*t.ndim
  m[axis] = t.shape[axis]
  return m

ax = 1
tile(expand_dims(amax(A, axis=ax), axis=ax), tiletuple(A, ax)) == A

A: Late to the party, but how about this one:
rollaxis(amax(A, ax)[...,newaxis], -1, ax) == A

It is basically inserting the axis again, which fell out of the array due to the amax. Then, the broadcasting works again.
Or, equivalently:
a = list(A.shape)
a[ax] = 1
amax(A, ax).reshape(a) == A


text:
Q: adding html tag inside typescript file in angular i am using angular2 so i want to implement html tag  inside the return function in ts file
  tooltip: (param: any) => {
        return `<span> ${param.value} </span>`;
      }

i have tried to use template literal but that make my span visible.

is there any idea how can i use the span proper way

A: try this code
stackblitz example

import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

import { DomSanitizer } from '@angular/platform-browser'

@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform  {
  constructor(private sanitized: DomSanitizer) {}
  transform(value) {
    console.log(this.sanitized.bypassSecurityTrustHtml(value))
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

@Component({
  selector: 'my-app',
  template: `<div [innerHtml]="tooltip('Hello World') | safeHtml">
    </div>`,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  tooltip(param: any) {
        return `<span> ${param} </span>`;
      }
}