问:
Centering mat-tab-group
I have 2 labels and I want them to be in the middle. Angular Material provides simple class mat-align-tabs="center" which doesn't work at all. I searched an internet an found solutions for md, which is old version of Material. Surprised that nobody didn't face same problem.

HTML:

```<code><mat-tab-group [(selectedIndex)]="selectedTabIndex"  mat-align-tabs="center">
    <mat-tab id="Wyszuk" label="Wyszukiwanie" *ngIf="!leadOffer.isSent">
      <app-offer-search-candidates [offerId]="leadOffer.id" [leadId]="leadId" [offer]="leadOffer"
        [candidatesToVerification]="candidatesToVerificationDataSource.data" [awaitingCandidates]="awaitingCandidatesDataSource.data"
        (addCandidatesToVerification)="onAddCandidatesToVerification($event)" (addAwaitingCandidates)="onAddAwaitingCandidates($event)"
        (addCandidatesToCart)="onAddCandidatesToCart($event)" (searchSave)="onSearchSave($event)">
      </app-offer-search-candidates>
    </mat-tab>

    <mat-tab label="Koszyk ofertowy">
      <app-offer-cart [dataSource]="candidatesDataSource" [searchModel]="searchModel" [readOnly]="leadOffer.isSent"
        [attachmentsDataSource]="attachmentsDataSource" (refresh)="onRefreshCandidates()" (removeCandidates)="onRemoveCandidatesFromCart($event)"
        (sendOffer)="onSendOffer($event)" (removeAllCandidates)="onRemoveAllCandidates()" (removeCart)="onRemoveCart()"
        (generateOffer)="onGenerateOffer()" (attachmentsLoaded)="onAttachmentsLoaded($event)" (removeAttachments)="onRemoveAttachments($event)"
        (generateCvs)="onGenerateCvs($event)" (updateProjectRole)="onUpdateProjectRole($event)" (updateSuggestedPrice)="onUpdateSuggestedPrice($event)"
        (candidateCvLoaded)="onCandidateOfferCvLoaded($event)">
      </app-offer-cart>
    </mat-tab>
</mat-tab-group>
</code>```

答:
It must be a versioning problem. Tried it in Angular 6, not working. But with Angular 7, it is:

https://stackblitz.com/edit/angular-mat-7-install-mat-tab-center

Angular 6:
Add this to your global stylesheet style.scss.

```<code>.mat-tab-labels {
    justify-content: center;
}
</code>```

For more, read here. If you add it to the component.scss it will be overwritten, in the global not. Additional you can specify the component you want this style applied to.
https://stackblitz.com/edit/angular6-material-components-mat-tab-centered

Title: Centering mat-tab-group

Body:
I have 2 labels and I want them to be in the middle. Angular Material provides simple class mat-align-tabs="center" which doesn't work at all. I searched an internet an found solutions for md, which is old version of Material. Surprised that nobody didn't face same problem.

HTML:

<mat-tab-group [(selectedIndex)]="selectedTabIndex"  mat-align-tabs="center">
    <mat-tab id="Wyszuk" label="Wyszukiwanie" *ngIf="!leadOffer.isSent">
      <app-offer-search-candidates [offerId]="leadOffer.id" [leadId]="leadId" [offer]="leadOffer"
        [candidatesToVerification]="candidatesToVerificationDataSource.data" [awaitingCandidates]="awaitingCandidatesDataSource.data"
        (addCandidatesToVerification)="onAddCandidatesToVerification($event)" (addAwaitingCandidates)="onAddAwaitingCandidates($event)"
        (addCandidatesToCart)="onAddCandidatesToCart($event)" (searchSave)="onSearchSave($event)">
      </app-offer-search-candidates>
    </mat-tab>

    <mat-tab label="Koszyk ofertowy">
      <app-offer-cart [dataSource]="candidatesDataSource" [searchModel]="searchModel" [readOnly]="leadOffer.isSent"
        [attachmentsDataSource]="attachmentsDataSource" (refresh)="onRefreshCandidates()" (removeCandidates)="onRemoveCandidatesFromCart($event)"
        (sendOffer)="onSendOffer($event)" (removeAllCandidates)="onRemoveAllCandidates()" (removeCart)="onRemoveCart()"
        (generateOffer)="onGenerateOffer()" (attachmentsLoaded)="onAttachmentsLoaded($event)" (removeAttachments)="onRemoveAttachments($event)"
        (generateCvs)="onGenerateCvs($event)" (updateProjectRole)="onUpdateProjectRole($event)" (updateSuggestedPrice)="onUpdateSuggestedPrice($event)"
        (candidateCvLoaded)="onCandidateOfferCvLoaded($event)">
      </app-offer-cart>
    </mat-tab>
</mat-tab-group>

Body:
It must be a versioning problem. Tried it in Angular 6, not working. But with Angular 7, it is:

https://stackblitz.com/edit/angular-mat-7-install-mat-tab-center

Angular 6:
Add this to your global stylesheet style.scss.

.mat-tab-labels {
    justify-content: center;
}

For more, read here. If you add it to the component.scss it will be overwritten, in the global not. Additional you can specify the component you want this style applied to.
https://stackblitz.com/edit/angular6-material-components-mat-tab-centered


来源: stackexchange

问:
Unobtrusive javascript drivers for Rails3
I have spent some hours looking for a Rails3 dojo-toolkit UJS-driver but I had no luck.
Google, github, the dojo official site and different blogs didn't help me.

It seems like rails3 has only three drivers actually written.
These are the drivers I found:

Two officials:

Prototype-UJS (default in rails 3.0).

jQuery-UJS (optional, it will be the default option in rails 3.1).

Two unofficials:

Mootools-UJS

Dojo-UJS

We could complete this list with the existing ujs-drivers.

答: There's dojox.rails, though I'm only looking at it right now.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Can a Jekyll site be a sub site within an existing website?
I'm managing a site that is generated by Jekyll and hosted on github. The product manager does not like the home page and wants to redesign it and has asked if it could be created separately from the rest of the site (which is Jekyll).

Personally I'd love to pull the whole site out of Jekyll as what we are doing and what Jekyll is made for are two different things. But budget and time are factors and doing a major overhaul is not in the foreseeable future.

Has anyone tried this and if so what are the pain points/best practices?

Thanks

答:
You are in luck. That is not a complex task AT ALL. Just create a folder called _layouts in the root and create a 'customhome.html' file in it.

Then create an 'index.md' file in the root and set this:

```<code>---
title: Home
layout: customhome
---
</code>```

Write your whole (custom) webpage in the 'customhome.html' file, like this:

```<code><!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>
</code>```

As a bonus you can test your customhome.html file directly in your browser without intalling Jekyll (as long as you keep everyting inline).

PS. You can even forget the above and put a simple 'index.html' file in the root... that works too! Make sure you delete the existing 'index.md' file if available.

Body:
You are in luck. That is not a complex task AT ALL. Just create a folder called _layouts in the root and create a 'customhome.html' file in it.

Then create an 'index.md' file in the root and set this:

---
title: Home
layout: customhome
---

Write your whole (custom) webpage in the 'customhome.html' file, like this:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>

As a bonus you can test your customhome.html file directly in your browser without intalling Jekyll (as long as you keep everyting inline).

PS. You can even forget the above and put a simple 'index.html' file in the root... that works too! Make sure you delete the existing 'index.md' file if available.


问:
How to fix the hoverinfo error in my shiny app?
I have developed a shiny app using ggplot2 and plotly, however, the hover text was not correctly showed for two horizontal lines which I added as the upper and lower limits. I want to hide the hover text for these two lines. Does anyone know how to achieve it？

I found one solution but it didn't work for shiny

Disable hover information for a specific layer (geom) of plotly

```<code>  library(shiny)
    shinyServer(

     function(input,output,session){
       reactivelab <- reactive({
           gg <-labn %>% filter(PARCAT2  == input$Group & LBTEST ==
                 input$Par & SUBJID == input$ID) })

 output$labpot <- renderPlotly({
     req(nrow(reactivelab()) > 0)
     q <- ggplot(data=reactivelab(),aes(x=ADY, y=AVAL))+
        geom_point()+geom_line()+
        geom_hline(aes(yintercept=ANRLO),linetype="longdash")+
        geom_hline(aes(yintercept=ANRHI),linetype="longdash")+
        ylab("Lab Standard Value") + xlab("Lab Test Day")
        mm <- style(q,  text =  paste("Lab Parameter:", reactivelab()$PARAM,
                                "<br>Lab Test Day:", reactivelab()$ADY,
                                "<br>Lab Standard Value:", reactivelab()$AVAL,
                                "<br>Normal Range Upper Limit:", reactivelab()$ANRHI,
                                "<br>Normal Range Lower Limit:", reactivelab()$ANRLO

  ), hoverinfo = "text")})

 })
</code>```

答:
Instead of using style, you can pass the text aesthetic to the aes of the ggplot function:

```<code>ggplot(data=reactivelab(),
       aes(x=ADY, y=AVAL,
           text = paste("Lab Parameter:", PARAM,
                        "<br>Lab Test Day:", ADY,
                        "<br>Lab Standard Value:", AVAL,
                        "<br>Normal Range Upper Limit:", ANRHI,
                        "<br>Normal Range Lower Limit:", ANRLO)))
</code>```

Body:
I have developed a shiny app using ggplot2 and plotly, however, the hover text was not correctly showed for two horizontal lines which I added as the upper and lower limits. I want to hide the hover text for these two lines. Does anyone know how to achieve it？

I found one solution but it didn't work for shiny

Disable hover information for a specific layer (geom) of plotly

  library(shiny)
    shinyServer(

     function(input,output,session){
       reactivelab <- reactive({
           gg <-labn %>% filter(PARCAT2  == input$Group & LBTEST ==
                 input$Par & SUBJID == input$ID) })

 output$labpot <- renderPlotly({
     req(nrow(reactivelab()) > 0)
     q <- ggplot(data=reactivelab(),aes(x=ADY, y=AVAL))+
        geom_point()+geom_line()+
        geom_hline(aes(yintercept=ANRLO),linetype="longdash")+
        geom_hline(aes(yintercept=ANRHI),linetype="longdash")+
        ylab("Lab Standard Value") + xlab("Lab Test Day")
        mm <- style(q,  text =  paste("Lab Parameter:", reactivelab()$PARAM,
                                "
Lab Test Day:", reactivelab()$ADY,
                                "
Lab Standard Value:", reactivelab()$AVAL,
                                "
Normal Range Upper Limit:", reactivelab()$ANRHI,
                                "
Normal Range Lower Limit:", reactivelab()$ANRLO

  ), hoverinfo = "text")})

 })

Body:
Instead of using style, you can pass the text aesthetic to the aes of the ggplot function:

ggplot(data=reactivelab(),
       aes(x=ADY, y=AVAL,
           text = paste("Lab Parameter:", PARAM,
                        "<br>Lab Test Day:", ADY,
                        "<br>Lab Standard Value:", AVAL,
                        "<br>Normal Range Upper Limit:", ANRHI,
                        "<br>Normal Range Lower Limit:", ANRLO)))


问:
How to check if a variable is an integer in Jinja2?
The aim is to check whether a variable is an integer and if that is true insert hello.

Attempt

```<code>{% if int(variable) %} hello {% endif %}
</code>```

Result

```<code>'int' is undefined"
</code>```

答:
None of these solutions worked for me, however this did :

{% if variable is even or variable is odd %}

Body:
The aim is to check whether a variable is an integer and if that is true insert hello.

Attempt

{% if int(variable) %} hello {% endif %}

Result

'int' is undefined"


问:
Does HTML Encoding a mailto tag stop spammers
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

```<code><a href="mailto:newbi...">email me</a>
</code>```

Also, are there any other techniques that I've left out?  Which is the best method?

答:
Another technique is to use some Javascript to dynamically generate the mailto tag at page load time. In order for spammers to scrape such addresses, they would need to have a full Javascript processor in their web spider.

Some spammers may already do this.

OwnerDisplayName: bendewey

Body:
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

email me

Also, are there any other techniques that I've left out?  Which is the best method?

LastEditorDisplayName: bendewey

OwnerDisplayName: Greg Hewgill

ContentLicense: CC BY-SA 2.5


问:
Finding missing numbers in a preset range
I am having a problem finding missing values within a preset range.  For example I have:

Column A: 3, 5, 7, 9, 10, 11
I want either VBA or a formula in excel to return
Column B: 1, 2, 4, 6, 8, 12, 13 --> 30

The final number in Column B will vary.  I want it to change based on user discretion.  For my problem I am working with days of the month.  So January, February, and March have different total days.  I've seen a lot of examples, but all are based on a array in the spreedsheet.  What if I want to change the array to 1-30, 1-31, or 1-28 (depending on which month I am looking at)?

答:
a possible formula solution would be ARRAY FORMULA:   CTRL + SHIFT + ENTER

```<code>{=SMALL(IF(COUNTIF(A:A,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1)=0,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1),ROW())}
</code>```

Copy downwards to get all values.

Body:
a possible formula solution would be ARRAY FORMULA:   CTRL + SHIFT + ENTER

{=SMALL(IF(COUNTIF(A:A,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1)=0,ROW(INDIRECT("1:"&MAX(A:A)-MIN(A:A)+1))+MIN(A:A)-1),ROW())}

Copy downwards to get all values.


问:
How to change the aggregation calculation in react-table.js
I'm trying to get a proper average aggregation from react-table. For the moment, when you do an average on aggregation, it does the average of the sub-rows. If you only have 1 level of aggregation, no problem. If you have several levels, it brings a problem. It does the average of the averages of the sub-rows. This is not correct.

I've tried to aggregate it differently, but I don't know where to get the values for all the sub-rows in all the aggregation.

```<code>const data = [
  {
    region: "South",
    country: "Spain",
    item: "item1",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "Spain",
    item: "item2",
    item_type: "type2",
    value: 240
  },
  {
    region: "South",
    country: "Spain",
    item: "item3",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "Spain",
    item: "item4",
    item_type: "type2",
    value: 240
  },
  {
    region: "South",
    country: "France",
    item: "item5",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "France",
    item: "item6",
    item_type: "type2",
    value: 240
  },
  {
    region: "North",
    country: "UK",
    item: "item7",
    item_type: "type1",
    value: 140
  },
  {
    region: "North",
    country: "UK",
    item: "item8",
    item_type: "type1",
    value: 240
  },
  {
    region: "North",
    country: "UK",
    item: "item9",
    item_type: "type1",
    value: 10
  },
  {
    region: "North",
    country: "UK",
    item: "item10",
    item_type: "type2",
    value: 30
  },
  {
    region: "North",
    country: "UK",
    item: "item11",
    item_type: "type2",
    value: 450
  }
];
</code>```

Those are my columns:

```<code>const columns = [
        {
          Header: "region",
          accessor: "region"
        },
        {
          Header: "country",
          accessor: "country"
        },
        {
          Header: "item",
          accessor: "item"
        },

        {
          Header: "item_type",
          accessor: "item_type"
        },
        {
          Header: "value",
          accessor: "value"
        }
      ];
</code>```

And this is my component:

```<code><ReactTable data={data} columns={columns} pivotBy={["region", "country", "item_type"]} />
</code>```

In that example, Average for Spain is 145, the average for France is 505. If you do the average for all the rows, you get 265. And yet, in the table, it does the average of France and Spain, so 145 + 505 / 2. This is not correct. It should be 1590/6.

答: I ran in this problem too and haven't found a solution that included the builtin aggregation flows in react-table. Ended up doing the aggregation separatly and displaying then the aggregated data in react-table.</p>

Body:
I'm trying to get a proper average aggregation from react-table. For the moment, when you do an average on aggregation, it does the average of the sub-rows. If you only have 1 level of aggregation, no problem. If you have several levels, it brings a problem. It does the average of the averages of the sub-rows. This is not correct.

I've tried to aggregate it differently, but I don't know where to get the values for all the sub-rows in all the aggregation.

const data = [
  {
    region: "South",
    country: "Spain",
    item: "item1",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "Spain",
    item: "item2",
    item_type: "type2",
    value: 240
  },
  {
    region: "South",
    country: "Spain",
    item: "item3",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "Spain",
    item: "item4",
    item_type: "type2",
    value: 240
  },
  {
    region: "South",
    country: "France",
    item: "item5",
    item_type: "type1",
    value: 140
  },
  {
    region: "South",
    country: "France",
    item: "item6",
    item_type: "type2",
    value: 240
  },
  {
    region: "North",
    country: "UK",
    item: "item7",
    item_type: "type1",
    value: 140
  },
  {
    region: "North",
    country: "UK",
    item: "item8",
    item_type: "type1",
    value: 240
  },
  {
    region: "North",
    country: "UK",
    item: "item9",
    item_type: "type1",
    value: 10
  },
  {
    region: "North",
    country: "UK",
    item: "item10",
    item_type: "type2",
    value: 30
  },
  {
    region: "North",
    country: "UK",
    item: "item11",
    item_type: "type2",
    value: 450
  }
];

Those are my columns:

const columns = [
        {
          Header: "region",
          accessor: "region"
        },
        {
          Header: "country",
          accessor: "country"
        },
        {
          Header: "item",
          accessor: "item"
        },

        {
          Header: "item_type",
          accessor: "item_type"
        },
        {
          Header: "value",
          accessor: "value"
        }
      ];

And this is my component:

<ReactTable data={data} columns={columns} pivotBy={["region", "country", "item_type"]} />

In that example, Average for Spain is 145, the average for France is 505. If you do the average for all the rows, you get 265. And yet, in the table, it does the average of France and Spain, so 145 + 505 / 2. This is not correct. It should be 1590/6.


问:
How do I increase a secondary ID (not the primary key) using linq?
I am trying to log measurement from a sensor to sql table named MeasResult.

This table has its ID as primary key and one other ID named MeasID. I need to increase this MeasID by 1 every measurement logging. Every measurement logging will add 50 rows to database and these last added rows should have same MeasID.

I tried following:

```<code>private void BtnSaveMeas_Click(object sender, EventArgs e)
{
    using (LinqDataClassesDataContext dataContext = new LinqDataClassesDataContext())
    {
        var measid = dataContext.MeasResults.Max(x => x.MeasId) + 1;

        string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

        id = comboBMouldID.SelectedText;
        plane = comboBSurface.SelectedText;
        pos = Convert.ToInt32(txtTravelPos.Text);

        for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
        {
            dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
            apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

            var st = new MeasResult()
            {
                st.MID = id,
                st.Plane = plane,
                st.Postn = pos,
                st.Distnc = dist,
                st.Apert = apert,
                st.MeasId = measid
            };

            dataContext.MeasResults.InsertOnSubmit(st);
            dataContext.SubmitChanges();
        }
    }
}
</code>```

I took three measurements and logged them, but in the the database MeasID column is null for all of them. The default value for the MeasID column is 1.

What am I doing wrong?

答:
Try like this:

var measid = dataContext.MeasResults.Select(a=>a.MeasId).DefaultIfEmpty().Max(p => p ?? 0) + 1;

Body:
I am trying to log measurement from a sensor to sql table named MeasResult.

This table has its ID as primary key and one other ID named MeasID. I need to increase this MeasID by 1 every measurement logging. Every measurement logging will add 50 rows to database and these last added rows should have same MeasID.

I tried following:

private void BtnSaveMeas_Click(object sender, EventArgs e)
{
    using (LinqDataClassesDataContext dataContext = new LinqDataClassesDataContext())
    {
        var measid = dataContext.MeasResults.Max(x => x.MeasId) + 1;

        string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

        id = comboBMouldID.SelectedText;
        plane = comboBSurface.SelectedText;
        pos = Convert.ToInt32(txtTravelPos.Text);

        for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
        {
            dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
            apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

            var st = new MeasResult()
            {
                st.MID = id,
                st.Plane = plane,
                st.Postn = pos,
                st.Distnc = dist,
                st.Apert = apert,
                st.MeasId = measid
            };

            dataContext.MeasResults.InsertOnSubmit(st);
            dataContext.SubmitChanges();
        }
    }
}

I took three measurements and logged them, but in the the database MeasID column is null for all of them. The default value for the MeasID column is 1.

What am I doing wrong?


问:
How can I update react state using axios(to get json data) and redux(to update state)?
I am trying to update the value of state of react using redux. To get the data I am using axios, but the data us not being returned and updated. When I check the state using redux tool the state is still empty list of initialState.

Here is the from src/action/feedbacks.js. Here axios is used to return the data in json format

```<code>import axios from "axios";

import { GET_FEEDBACKS } from "./types";

export const getFeedbacks = () => dispatch => {
  console.log(axios.get("/api/feedbacks/").res.data);
  axios
    .get("/api/feedbacks/")
    .then(res => {
      dispatch({
        type: GET_FEEDBACKS,
        payload: res.data
      });
    })
    .catch(err => console.log(err));
};
</code>```

This code is from src/reducers/feedbacks.js.

```<code>import { GET_FEEDBACKS } from "../actions/types.js";

const initialState = {
  feedbacks: []
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_FEEDBACKS:
      return {
        ...state,
        feedbacks: action.payload
      };
    default:
      return state;
  }
}
</code>```

This code is from src/components/feedbacks/Feedbacks.js

```<code>import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";

import { getFeedbacks } from "../../actions/feedbacks";

export class Feedbacks extends Component {
  static propTypes = {
    feedbacks: PropTypes.array.isRequired
  };

  ComponentDidMount() {
    this.props.getFeedbacks();
  }
  render() {
    return (
      //some return code
    );
  }
}
const mapStateToProps = state => ({
  feedbacks: state.feedbacks.feedbacks
});
export default connect(
  mapStateToProps,
  { getFeedbacks }
)(Feedbacks);
</code>```

答:
Maybe you can get this update on componentDidUpdate or do this with hooks.

Try something like this:

import React, {useEffect} from "react";
import {connect} from "react-redux";
import PropTypes from "prop-types";

import {getFeedbacks} from "../../actions/feedbacks";

export const Feedbacks = props => {
    const {feedbacks, getFeedbacks} = props

    useEffect(() => {
        getFeedbacks();
    }, [])

    return (
       //some return code
    )
}

Feedbacks.propTypes = {
    feedbacks: PropTypes.array.isRequired
};

const mapStateToProps = state => ({
    feedbacks: state.feedbacks.feedbacks
});

export default connect(
    mapStateToProps,
    {getFeedbacks}
)(Feedbacks);```

When redux update, this component receive the json of feedbacks, so when mounting this, maybe you should check if feedbacks has data or is empty before manipulate it.

Body:
I am trying to update the value of state of react using redux. To get the data I am using axios, but the data us not being returned and updated. When I check the state using redux tool the state is still empty list of initialState.

Here is the from src/action/feedbacks.js. Here axios is used to return the data in json format

import axios from "axios";

import { GET_FEEDBACKS } from "./types";

export const getFeedbacks = () => dispatch => {
  console.log(axios.get("/api/feedbacks/").res.data);
  axios
    .get("/api/feedbacks/")
    .then(res => {
      dispatch({
        type: GET_FEEDBACKS,
        payload: res.data
      });
    })
    .catch(err => console.log(err));
};

This code is from src/reducers/feedbacks.js.

import { GET_FEEDBACKS } from "../actions/types.js";

const initialState = {
  feedbacks: []
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_FEEDBACKS:
      return {
        ...state,
        feedbacks: action.payload
      };
    default:
      return state;
  }
}

This code is from src/components/feedbacks/Feedbacks.js

import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";

import { getFeedbacks } from "../../actions/feedbacks";

export class Feedbacks extends Component {
  static propTypes = {
    feedbacks: PropTypes.array.isRequired
  };

  ComponentDidMount() {
    this.props.getFeedbacks();
  }
  render() {
    return (
      //some return code
    );
  }
}
const mapStateToProps = state => ({
  feedbacks: state.feedbacks.feedbacks
});
export default connect(
  mapStateToProps,
  { getFeedbacks }
)(Feedbacks);

Body:
Maybe you can get this update on componentDidUpdate or do this with hooks.

Try something like this:

import React, {useEffect} from "react";
import {connect} from "react-redux";
import PropTypes from "prop-types";

import {getFeedbacks} from "../../actions/feedbacks";

export const Feedbacks = props => {
    const {feedbacks, getFeedbacks} = props

    useEffect(() => {
        getFeedbacks();
    }, [])

    return (
       //some return code
    )
}

Feedbacks.propTypes = {
    feedbacks: PropTypes.array.isRequired
};

const mapStateToProps = state => ({
    feedbacks: state.feedbacks.feedbacks
});

export default connect(
    mapStateToProps,
    {getFeedbacks}
)(Feedbacks);

When redux update, this component receive the json of feedbacks, so when mounting this, maybe you should check if feedbacks has data or is empty before manipulate it.


问:
How to read boost variable with type std::vector<std::vector<boost:any>>?
In Qt creator, I can read a variable (variable in front of "held" in the screenshot) that I want to use in my code.
However I can't store it in a variable.

I've already tried to use this syntax, but it doesn't work :

```<code>int maVar = boost::any_cast<int>(_myCUBParam->m_ValueVect[0])
</code>```

答:
Thanks @mch. I'm feeling a bit stupid because it was just the missing second [0]...
When I spy maVar with maVar = boost::any_cast<int>(_myCUBParam->m_ValueVect[0][0]) value is not displayed (<optimized out> is displayed instead).
But when I print maVar in a csv file in my case, value is correctly printed.

Thanks a lot for your help

Body:
In Qt creator, I can read a variable (variable in front of "held" in the screenshot) that I want to use in my code.
However I can't store it in a variable.

I've already tried to use this syntax, but it doesn't work :

int maVar = boost::any_cast<int>(_myCUBParam->m_ValueVect[0])


问:
How to resolve conflicting types problem In C
I am trying to re-use BlueZ code in my own C program to manage Bluetooth connection and running into compilation issues.

When I analyzed the problem further here is what I think is happening:

It all comes down to my program structure:

```<code>1.myadv.c includes myadv.h includes gio.h
2. myadv.c includes "gdbus.h" (Helper lib)

</code>```

Now the problem is gdbus.h has certain symbol definitions (typedef, methods etc...) that conflict with internal defs in gio.h

Because of that I get compiler errors like this:

```<code>/usr/include/glib-2.0/gio/gioenums.h:1383:3: error: conflicting types for ‘GDBusSignalFlags’
 } GDBusSignalFlags;
   ^~~~~~~~~~~~~~~~

conflicting types for ‘g_dbus_proxy_new’
 void             g_dbus_proxy_new

</code>```

What is the best practice to avoid such symbol conflict errors during inclusion? Please note, I need to use both header files:

gio.h (The gnome lib)

gdbus.h (The dbus helper directly borrowed from BlueZ)

答:
Don’t use the gdbus.h from BlueZ. It’s not compatible with GLib, yet erroneously uses the GLib symbol namespace (the g_ or G prefix).

Use the GDBus API from GLib itself, seeing as you’re already using GLib/GIO in your project.

Body:
I am trying to re-use BlueZ code in my own C program to manage Bluetooth connection and running into compilation issues.

When I analyzed the problem further here is what I think is happening:

It all comes down to my program structure:

1.myadv.c includes myadv.h includes gio.h
2. myadv.c includes "gdbus.h" (Helper lib)

Now the problem is gdbus.h has certain symbol definitions (typedef, methods etc...) that conflict with internal defs in gio.h

Because of that I get compiler errors like this:

/usr/include/glib-2.0/gio/gioenums.h:1383:3: error: conflicting types for ‘GDBusSignalFlags’
 } GDBusSignalFlags;
   ^~~~~~~~~~~~~~~~

conflicting types for ‘g_dbus_proxy_new’
 void             g_dbus_proxy_new

What is the best practice to avoid such symbol conflict errors during inclusion? Please note, I need to use both header files:

gio.h (The gnome lib)

gdbus.h (The dbus helper directly borrowed from BlueZ)


问:
How to add a legend in ggplot to my graph
Hi have some code to simulate a Gaussian process. Please can someone help me add a legend to my plots on the top right corner. I want to state the different parameter values for each of the line styles/colours, e.g. l=1, l=5, l=10. Thanks.</p>

```<code># simulate a gaussian process
simGP = function(K){
  n = nrow(K)
  U = chol(K) # cholesky decomposition
  z = rnorm(n)
  c(t(U) %*% z)
}

# choose points to simulate the covariance.
x = seq(-1, 1, length.out = 500)

# Exponential kernel ------------------------------------------------------

kernel_exp = function(x, l = 1) {
  d = as.matrix(dist(x))/l
  K = exp(-d)
  diag(K) = diag(K) + 1e-8
  K
}

{y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- as.data.frame(x,y1)
data2 <- as.data.frame(x,y2)
data3 <- as.data.frame(x,y3)
df=data.frame(data1,data2,data3)

ggplot() +
  geom_line(data=data1, aes(x=x, y=y1), color="green4", linetype = "twodash", size=0.5) +
  geom_line(data=data2, aes(x=x, y=y2), color='red', linetype="longdash", size=0.5) +
  geom_line(data=data3, aes(x=x, y=y3), color='blue') +
  scale_color_manual(values = colors) +
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))}
</code>```

答:
You can do it using a dataframe variable to group the linetype and colour.
If you want to specify color and linetype, use scale_color_discrete and scale_linetype_discrete

```<code>y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- data.frame(x, y = y1, value = "10")
data2 <- data.frame(x, y = y2, value = "1")
data3 <- data.frame(x, y = y3, value = "0.1")
df=rbind(data1,data2,data3)

ggplot(data = df, aes(x=x, y=y, color = value, linetype = value, group = value)) +
  geom_line(size=0.5) +
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))
</code>```

Body:
Hi have some code to simulate a Gaussian process. Please can someone help me add a legend to my plots on the top right corner. I want to state the different parameter values for each of the line styles/colours, e.g. l=1, l=5, l=10. Thanks.

# simulate a gaussian process
simGP = function(K){
  n = nrow(K)
  U = chol(K) # cholesky decomposition
  z = rnorm(n)
  c(t(U) %*% z)
}

# choose points to simulate the covariance.
x = seq(-1, 1, length.out = 500)

# Exponential kernel ------------------------------------------------------

kernel_exp = function(x, l = 1) {
  d = as.matrix(dist(x))/l
  K = exp(-d)
  diag(K) = diag(K) + 1e-8
  K
}

{y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- as.data.frame(x,y1)
data2 <- as.data.frame(x,y2)
data3 <- as.data.frame(x,y3)
df=data.frame(data1,data2,data3)

ggplot() +
  geom_line(data=data1, aes(x=x, y=y1), color="green4", linetype = "twodash", size=0.5) +
  geom_line(data=data2, aes(x=x, y=y2), color='red', linetype="longdash", size=0.5) +
  geom_line(data=data3, aes(x=x, y=y3), color='blue') +
  scale_color_manual(values = colors) +
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))}

Body:
You can do it using a dataframe variable to group the linetype and colour.
If you want to specify color and linetype, use scale_color_discrete and scale_linetype_discrete

y1 = simGP(kernel_exp(x,l=10))
y2 = simGP(kernel_exp(x,l=1))
y3 = simGP(kernel_exp(x,l=0.1))
data1 <- data.frame(x, y = y1, value = "10")
data2 <- data.frame(x, y = y2, value = "1")
data3 <- data.frame(x, y = y3, value = "0.1")
df=rbind(data1,data2,data3)

ggplot(data = df, aes(x=x, y=y, color = value, linetype = value, group = value)) +
  geom_line(size=0.5) +
  theme_classic() +
  labs(x='input, x',
       y='output, f(x)')+
  theme(axis.text=element_text(size=16),
        axis.title=element_text(size=14))


问:
How to format the given date "31.12.9999" in the format "yyyy/MM/dd HH:mm:ss"
i have a common doubt for a long while. During date formation if the input date in the format like "2019/05/22 02:00:23" then with the help following line we can format the date,

```<code>String inputDate = "2019/05/22 02:00:23";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);
</code>```

I can see both input format and the required format is same. Suppose if i change the input date like below, it is showing the java.text.ParseException: Unparseable date: exception.

```<code>String inputDate = "31.12.9999";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);
</code>```

Please suggest how to achieve this.

答:
Please try below i mentioned date format code,I hope it will help you,

From this,

```<code>String inputDate = "31.12.9999";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);
</code>```

To Change:

```<code>Date date = new SimpleDateFormat("dd.MM.yyyy").parse("31.12.9999");
String formattedDate = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date);
System.out.println("formattedDate  :: " + formattedDate);
</code>```

Thanks,.

Body:
i have a common doubt for a long while. During date formation if the input date in the format like "2019/05/22 02:00:23" then with the help following line we can format the date,

String inputDate = "2019/05/22 02:00:23";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);

I can see both input format and the required format is same. Suppose if i change the input date like below, it is showing the java.text.ParseException: Unparseable date: exception.

String inputDate = "31.12.9999";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);

Please suggest how to achieve this.

Body:
Please try below i mentioned date format code,I hope it will help you,

From this,

String inputDate = "31.12.9999";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date toDate = dateFormatter.parse(inputDate);

To Change:

Date date = new SimpleDateFormat("dd.MM.yyyy").parse("31.12.9999");
String formattedDate = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date);
System.out.println("formattedDate  :: " + formattedDate);

Thanks,.


问:
Can I ensure the order of dialog conversations in sql service broker?
So, I've got an 'A' server and a 'B' server.  We are using SQL Service Broker to perform replication.  An application we have will need to write data to either the 'A' server, or the 'B' server.  (one may be down, and the other one should take over)

Data is written to the database only within stored procedures, which are wrapped in a transaction to keep the data in the tables consistent.

One of these transactions will include all of the messages to be sent to the peer server.  So, in my application code, when I attempt to commit a transaction, it should write all of the data to the tables, and send the messages to the peer server.

However, if the peer server is down, then the messages will wait in sys.transmission_queue.

Message order within a dialog conversation is guaranteed, but can I ensure that dialog conversations will be processed in the order that I created them?

For example, I could have a problem if the 'B' server is down, A user writes data to the 'A' server.  Once the 'B' server is back up again, if those dialog conversations are processed out of order, they may not work correctly.  (They could try to insert data with a bad foreign key, or something like that).

I am working under the following assumptions:

I should have a single dialog
conversation for each transaction.

The form of the solution must be as
replication by way of sql service
broker.  (This is done in other
parts of the database, so any reason
to use an alternate strategy must be
compelling).

答: You should user Broker Priority.http://msdn.microsoft.com/en-us/library/bb934170.asp</p>


问:
Automatically suffix every style with !important
I'm making a widget in Angular 7 which will be put on different websites. I want this widget to get rid of all the styles which are being applied by that website and then use my own. For that, I'm using cleanslate (http://cleanslatecss.com/) but this means that all my styles will need to be prefixed by !important which I'm okay with because for now, this is the route I want to go (ShadowDOM doesn't work for me for various reasons).

What I wanted to know was, is there any webpack plugin or something else which I could use to suffix all my styles with the !important tag at the time of building?

答:
!important is a bad practice, you should instead use CSS selector specificity.

You also have a all: unset property, which removes every CSS property from the element it is applied to.

Be careful about the support though.


问:
Move app service from one app service plan to another (same resource group and region)
I have two app service plans running in the same region, same resource group and in the same subscription. I have a web app in app service plan a, that I want to move to app service plan b. When clicking Change App Service Plan, the Portal tells me that "No App Service Plans Found".

App service plan a is running on Standard: 1 Small. App service plan b is running on Standard: 2 Large. Changing app service plan a to Standard: 1 Large, doesn't make app service plan b show up when trying to move the app service.

What could be the problem here?

答:
You have to check the webspace between the 2 App Service Plans. Are there identical?
You might move (multiple times) your App Service Plan to different Ressource Group but the webspace is based on your original Resource Group (when you created this App Service Plan the first time)

You might have also deleted your original Resource Group, so you might have to recreate it? (I have never tried this case, but it should create in the same webspace then)

To check I use PowerShell command:

```<code>Login-AzureRMAccount
Get-AzureRmSubscription
Select-AzureRmSubscription -SubscriptionId <Your Subscription Guid>

Get-AzureRmResource -ResourceId "/subscriptions/<SUB-ID>/resourceGroups/<RG-NAME>/resources" | Select Name, ResourceName, @{Name='webSpace'; Expression={$_.Properties.webSpace}} | Format-List
</code>```

For the name space, you will get something like:

```<code>Name           : Consoto_AppServicePlan
ResourceName   : Consoto_ResourceGroup
webSpace       : Consoto-SouthCentralUSwebspace
</code>```

(Supposed that the location is South Central US)

So if you want to move your App Service to another App Service Plan name, you will have to create a new App Service Plan in the Resource Group named "Consoto" (refer to my example above) in the Location South Central US in the same subscription of course.
Then you will be able to use the Change App Service Plan functionality in the Azure Portal

Body:
You have to check the webspace between the 2 App Service Plans. Are there identical?
You might move (multiple times) your App Service Plan to different Ressource Group but the webspace is based on your original Resource Group (when you created this App Service Plan the first time)

You might have also deleted your original Resource Group, so you might have to recreate it? (I have never tried this case, but it should create in the same webspace then)

To check I use PowerShell command:

Login-AzureRMAccount
Get-AzureRmSubscription
Select-AzureRmSubscription -SubscriptionId <Your Subscription Guid>

Get-AzureRmResource -ResourceId "/subscriptions/<SUB-ID>/resourceGroups/<RG-NAME>/resources" | Select Name, ResourceName, @{Name='webSpace'; Expression={$_.Properties.webSpace}} | Format-List

For the name space, you will get something like:

Name           : Consoto_AppServicePlan
ResourceName   : Consoto_ResourceGroup
webSpace       : Consoto-SouthCentralUSwebspace

(Supposed that the location is South Central US)

So if you want to move your App Service to another App Service Plan name, you will have to create a new App Service Plan in the Resource Group named "Consoto" (refer to my example above) in the Location South Central US in the same subscription of course.
Then you will be able to use the Change App Service Plan functionality in the Azure Portal


问:
Create record via client script in a relation model in App Maker
Could someone point me to documentation that shows how to create a record in a model with one to many relation via client side script.

Thanks in advance!

答:
There are two ways of creating a new record.

1. Via a client-side script

You can do this by calling a createItem function from a widget. This link might help with that.

2. Via a server-side script

You can do this by directly creating a new record, assigning it to the relation of a model and then saving that model. This link might help with this method. By the way, it's easier to do this in a server-side script, as the guide itself says.

Since you just requested the link to official documentation, I've limited my answer to links only. Please feel free to ask if you need clarifications!


问:
Extract Pattern Matches / Remove Everything From Line Except Pattern
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

```<code>grep -o -P '(?<="city":").*?(?=")' input.txt
</code>```

Example input:

```<code>email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,
</code>```

Desired output:

```<code>north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD
</code>```

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

Body:
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

grep -o -P '(?<="city":").*?(?=")' input.txt

Example input:

email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,

Desired output:

north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

Body:
Sed:

sed 's/.*city":"\([^"]*\).*/|\1/; /^[^|]/s/.*//; s/^|//'


问:
Why isn't my css applied unless i clean browser cache?
I'm making a simple website for a school project. It was going well until i added php to the code. Now it doesn't want to apply my css changes every time for some reason. I validated html, css and php on some sites and everything seems to be clean. Then i came across a article that said i have to clear the cache for the css to get applied. It worked (using chrome) though now i have to clean it after every css change or it wont get applied. Only thing that is coming to my mind is that I'm working in PhpStorm but checking the code using xampp and not the PhpStorm built-in browsers, though it worked perfectly until the php. Is there a better way out then clearing cache after every single css change?</p>

答:
Add a random query string in the link where you are importing the css. That way Chrome will not recognize it as a static asset and will always fetch the newest version from the server.

Be sure to remove it before going live if you need to enhance caching.

Using php it would look like this:

```<code><link href="style.css?v=<?=rand(1,1000)?>" />
</code>```

This way one time it will be like style.css?v=28, next time style.css?v=674, then style.css?v=18 and so on, thus no browser will cache this style.

Body:
Add a random query string in the link where you are importing the css. That way Chrome will not recognize it as a static asset and will always fetch the newest version from the server.

Be sure to remove it before going live if you need to enhance caching.

Using php it would look like this:

<link href="style.css?v=<?=rand(1,1000)?>" />

This way one time it will be like style.css?v=28, next time style.css?v=674, then style.css?v=18 and so on, thus no browser will cache this style.


问:
How are static data variables addresses determined at compile time in MIPS1?
So in MIPS static variables are declared in the .data section, and these will be placed in memory in the static segment. However, does the assembler determine these addresses at compile time, or are these addresses determined when the program is loaded int memory by the OS?</p>

答:
However, does the assembler determine these addresses at compile time, or are these addresses determined when the program is loaded int memory by the OS?

This depends from OS to OS and is even dependent of the type of the variable:

10 years ago, most WLAN routers used a MIPS CPU running Linux on it.

On Linux, there exists a code type which is called "position-dependent" code. This means that the code will always be loaded to the same address in memory. In this case, one tool of the compiler tool chain (compiler, assembler, linker, ...) (*) calculates the address of the variable and writes the code "correctly". Example: If the variable is located at address 0x100024, the code will look like this:

```<code>lui t2, 0x10
lw  t3, 0x24(t2)
</code>```

Then there is "position-independent" code. This type of code can be loaded into any address. Let's assume that the variable is stored at address X and the label "nextAddress" is located at address Y. Addresses X and Y may change, however the difference (X-Y) is fixed. Let's say X-Y = 0x100024:

```<code>  bgezal zero, nextAddress
  nop
nextAddress:
  ; Now the address "nextAddress" is in register "ra"
  lui    t2, 0x10
  addu   t2, t2, ra
  ; The next instruction will access address X+0x100024
  lw     t3, 0x24(t2)
</code>```

Of course, the difference (X-Y) is calculated by a tool of the compiler tool chain during compile time.

There were also handheld devices (similar to a smartphone today) running Windows CE on MIPS CPUs.

This operating system uses a so-called "base relocation table": The .EXE or .DLL file contains a "desired" address. The code in the file looks like "position-dependent" code described above. When the file is loaded to the "desired" address, no action needs to be taken.

The "base relocation table" contains information about addresses in the file. For example a list of all lui instructions in the file. Let's say the "desired" address for loading the file is 0x80000 but Windows has to load the file to address 0xA0000. This means that the address of all variables in the file changes by 0x20000. Windows will process the information in the "base relocation table" and add 0x20 to the last 16 bits of each lui instruction in the file, so lui t2, 0x10 becomes lui t2, 0x30 in the example for "position dependent code" above.

So the address of the variable is first calculated by the compiler tool chain, but later it is modified by the operating system.

The next possibility are "global offset tables" (Linux) and "import tables" (Windows). These are typically used for accessing variables in DLL files.

The global offset table contains the addresses of the actual variables. In C programming language, this can be explained the following way:

Actual C code:

```<code>static int staticVariable;
...
staticVariable = 1234;
</code>```

What the resulting assembler code actually does:

```<code>static int staticVariable;
static int * staticVariable_got = &staticVariable;
...
(*staticVariable_got) = 1234;
</code>```

Assembly code:

```<code>lui t2, 0x10
lw  t3, 0x24(t2)
; Now t3 contains the address of the variable
sw  t4, (t3)
</code>```

In this case the compiler tool chain will calculate the address of the auxiliary "variable" (staticVariable_got). However, the address of the actual variable (staticVariable) is only known to the OS. The OS writes that address to the "variable" staticVariable_got.

(*) Note that this needs not necessarily be the linker; there are also compilers that directly write executable files (without the need of an assembler or linker) and there are linkers whose output is post-processed by another tool.

Body:
However, does the assembler determine these addresses at compile time, or are these addresses determined when the program is loaded int memory by the OS?

This depends from OS to OS and is even dependent of the type of the variable:

10 years ago, most WLAN routers used a MIPS CPU running Linux on it.

On Linux, there exists a code type which is called "position-dependent" code. This means that the code will always be loaded to the same address in memory. In this case, one tool of the compiler tool chain (compiler, assembler, linker, ...) (*) calculates the address of the variable and writes the code "correctly". Example: If the variable is located at address 0x100024, the code will look like this:

lui t2, 0x10
lw  t3, 0x24(t2)

Then there is "position-independent" code. This type of code can be loaded into any address. Let's assume that the variable is stored at address X and the label "nextAddress" is located at address Y. Addresses X and Y may change, however the difference (X-Y) is fixed. Let's say X-Y = 0x100024:

  bgezal zero, nextAddress
  nop
nextAddress:
  ; Now the address "nextAddress" is in register "ra"
  lui    t2, 0x10
  addu   t2, t2, ra
  ; The next instruction will access address X+0x100024
  lw     t3, 0x24(t2)

Of course, the difference (X-Y) is calculated by a tool of the compiler tool chain during compile time.

There were also handheld devices (similar to a smartphone today) running Windows CE on MIPS CPUs.

This operating system uses a so-called "base relocation table": The .EXE or .DLL file contains a "desired" address. The code in the file looks like "position-dependent" code described above. When the file is loaded to the "desired" address, no action needs to be taken.

The "base relocation table" contains information about addresses in the file. For example a list of all lui instructions in the file. Let's say the "desired" address for loading the file is 0x80000 but Windows has to load the file to address 0xA0000. This means that the address of all variables in the file changes by 0x20000. Windows will process the information in the "base relocation table" and add 0x20 to the last 16 bits of each lui instruction in the file, so lui t2, 0x10 becomes lui t2, 0x30 in the example for "position dependent code" above.

So the address of the variable is first calculated by the compiler tool chain, but later it is modified by the operating system.

The next possibility are "global offset tables" (Linux) and "import tables" (Windows). These are typically used for accessing variables in DLL files.

The global offset table contains the addresses of the actual variables. In C programming language, this can be explained the following way:

Actual C code:

static int staticVariable;
...
staticVariable = 1234;

What the resulting assembler code actually does:

static int staticVariable;
static int * staticVariable_got = &staticVariable;
...
(*staticVariable_got) = 1234;

Assembly code:

lui t2, 0x10
lw  t3, 0x24(t2)
; Now t3 contains the address of the variable
sw  t4, (t3)

In this case the compiler tool chain will calculate the address of the auxiliary "variable" (staticVariable_got). However, the address of the actual variable (staticVariable) is only known to the OS. The OS writes that address to the "variable" staticVariable_got.

(*) Note that this needs not necessarily be the linker; there are also compilers that directly write executable files (without the need of an assembler or linker) and there are linkers whose output is post-processed by another tool.


问:
Error Using Phusion Passenger - Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)
I have finally got RoR set up on my server using Phusion Passenger and the default RoR applicatioon page shows, however when I click 'About your application’s environment' I get an error saying 'Ruby (Rack) application could not be started' and under the Error Message bit 'Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)'.

If I do 'bundle install' at the command line I get a list of 'Using x (y)' style messages including this:

Using sqlite3-ruby (1.2.5)

(I had to downgrade to 1.2.5 due to an issue with the latest one)

I really dont understand why I am getting the error above as sqlite3-ruby is obviously there.

Stack Trace On Error Page:

```<code>0   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    87  in `materialize'
1   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `map!'
2   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `materialize'
3   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  90  in `specs'
4   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  135     in `specs_for'
5   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  124     in `requested_specs'
6   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/environment.rb     23  in `requested_specs'
7   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb     11  in `setup'
8   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler.rb     107     in `setup'
9   /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  326     in `prepare_app_process'
10  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   155     in `initialize_server'
11  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  572     in `report_app_init_status'
12  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   153     in `initialize_server'
13  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    204     in `start_synchronously'
14  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    180     in `start'
15  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   128     in `start'
16  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  253     in `spawn_rack_application'
17  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     132     in `lookup_or_add'
18  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  246     in `spawn_rack_application'
19  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     82  in `synchronize'
20  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     79  in `synchronize'
21  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  244     in `spawn_rack_application'
22  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  137     in `spawn_application'
23  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  275     in `handle_spawn_application'
24  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `__send__'
25  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `server_main_loop'
26  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    206     in `start_synchronously'
27  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/helper-scripts/passenger-spawn-server   99
</code>```

Edit:

This is my passenger.conf file.

```<code>LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6
PassengerRuby /opt/ruby-enterprise-1.8.7-2011.03/bin/ruby
PassengerMaxPoolSize 2
</code>```

答:
Your Passenger configuration seems wrong.. you supply the PassengerRoot of a passenger gem in your 1.9.1 universe, but point to PassengerRuby in the 1.8.7 universe.

I would advise recompiling the passenger apache module from Ruby 1.9 using passenger-install-apache2-module and change your configuration according to the instructions given by the installer.

Also, if you're using Rails I suggest you upgrade to 1.9.2 or stick with 1.8.7. Rails does not play nice with Ruby 1.9.1.

Body:
I have finally got RoR set up on my server using Phusion Passenger and the default RoR applicatioon page shows, however when I click 'About your application’s environment' I get an error saying 'Ruby (Rack) application could not be started' and under the Error Message bit 'Could not find sqlite3-ruby-1.2.5 in any of the sources (Bundler::GemNotFound)'.

If I do 'bundle install' at the command line I get a list of 'Using x (y)' style messages including this:

Using sqlite3-ruby (1.2.5)

(I had to downgrade to 1.2.5 due to an issue with the latest one)

I really dont understand why I am getting the error above as sqlite3-ruby is obviously there.

Stack Trace On Error Page:

0   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    87  in `materialize'
1   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `map!'
2   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/spec_set.rb    81  in `materialize'
3   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  90  in `specs'
4   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  135     in `specs_for'
5   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/definition.rb  124     in `requested_specs'
6   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/environment.rb     23  in `requested_specs'
7   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler/runtime.rb     11  in `setup'
8   /opt/ruby-enterprise-1.8.7-2011.03/lib/ruby/gems/1.8/gems/bundler-1.0.12/lib/bundler.rb     107     in `setup'
9   /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  326     in `prepare_app_process'
10  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   155     in `initialize_server'
11  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/utils.rb  572     in `report_app_init_status'
12  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   153     in `initialize_server'
13  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    204     in `start_synchronously'
14  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    180     in `start'
15  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/rack/application_spawner.rb   128     in `start'
16  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  253     in `spawn_rack_application'
17  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     132     in `lookup_or_add'
18  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  246     in `spawn_rack_application'
19  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     82  in `synchronize'
20  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server_collection.rb     79  in `synchronize'
21  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  244     in `spawn_rack_application'
22  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  137     in `spawn_application'
23  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/spawn_manager.rb  275     in `handle_spawn_application'
24  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `__send__'
25  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    357     in `server_main_loop'
26  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/lib/phusion_passenger/abstract_server.rb    206     in `start_synchronously'
27  /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/helper-scripts/passenger-spawn-server   99

Edit:

This is my passenger.conf file.

LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6/ext/apache2/mod_passenger.so
PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.6
PassengerRuby /opt/ruby-enterprise-1.8.7-2011.03/bin/ruby
PassengerMaxPoolSize 2


问:
Json Data is not displayed on table using php json
i am tring to displayed the json data in to the table but it didn't show what tried so far i attached below of code.what the error when the page is loaded i attached the image below.if i check at the console.log all data is displayed. not passing at the table
enter image description here

Table

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <table class="table table-striped" id="mytable">
    <thead>
      <tr>
        <th>ProductID</th>
        <th>Productname</th>
        <th>Price</th>
        <th>Qty</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
</div>
<script>
  function getProducts() {
    $.ajax({
      type: 'GET',
      url: 'cart.php',
      dataType: 'JSON',
      success: function(data) {
        //   console.log(data);
        for (var i = 0; i < data.length; i++) {
          console.log(data);
          var id = data[i].id;
          var product_name = data[i].product_name;
          var price = data[i].price;

          $('#mytable tbody tr').after(
            '<tr> ' +
            '<td>' + product_name + '</td>' +
            '<td>' + price + '</td>' +
            '<td>' + "<input type = 'text' id='pname'/>" + '</td>' +
            '</tr>');
        }
      },
      error: function(xhr, status, error) {
        alert(xhr.responseText);
      }
    });
  }
</script>
</code>```

cart.php

```<code><?php
include("db.php");
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare("select id,product_name,price from cart order by id DESC ");
$stmt->bind_result($id,$product_name,$price);

if ($stmt->execute()) {
    while ( $stmt->fetch() ) {
        $output[] = array ("id"=>$id, "product_name"=>$product_name,"price"=>$price);
    }

    echo json_encode( $output );
}
$stmt->close();

//}
</code>```

答:
You can use .each() function to loop through the results and also on $('#mytable tbody tr').after() you need to remove the tr as there's no tr element in your body it should be $('#mytable tbody').after(....) then when you done run the function by calling getProducts()

Your code should look like :

```<code> <script>
      function getProducts() {
        $.ajax({
          type: 'GET',
          url: 'cart.php',
          dataType: 'JSON',
          success: function(data) {
             data.forEach(function(element) {

               var id = element.id;
               var product_name = element.product_name;
                var price = element.price;

               $('#mytable tbody').after(
                '<tr> ' +
                '<td>' + id + '</td>' +
                '<td>' + product_name + '</td>' +
                '<td>' + price + '</td>' +
                '<td>' + "<input type = 'text' id='pname'/>" + '</td>' +
                '</tr>');

             });
          },
          error: function(xhr, status, error) {
            alert(xhr.responseText);
          }
        });
      }
      getProducts();
    </script>
</code>```

Body:
i am tring to displayed the json data in to the table but it didn't show what tried so far i attached below of code.what the error when the page is loaded i attached the image below.if i check at the console.log all data is displayed. not passing at the table
enter image description here

Table

        ProductID
        Productname
        Price
        Qty

cart.php

<?php
include("db.php");
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare("select id,product_name,price from cart order by id DESC ");
$stmt->bind_result($id,$product_name,$price);

if ($stmt->execute()) {
    while ( $stmt->fetch() ) {
        $output[] = array ("id"=>$id, "product_name"=>$product_name,"price"=>$price);
    }

    echo json_encode( $output );
}
$stmt->close();

//}

Body:
You can use .each() function to loop through the results and also on $('#mytable tbody tr').after() you need to remove the tr as there's no tr element in your body it should be $('#mytable tbody').after(....) then when you done run the function by calling getProducts()

Your code should look like :

 <script>
      function getProducts() {
        $.ajax({
          type: 'GET',
          url: 'cart.php',
          dataType: 'JSON',
          success: function(data) {
             data.forEach(function(element) {

               var id = element.id;
               var product_name = element.product_name;
                var price = element.price;

               $('#mytable tbody').after(
                '<tr> ' +
                '<td>' + id + '</td>' +
                '<td>' + product_name + '</td>' +
                '<td>' + price + '</td>' +
                '<td>' + "<input type = 'text' id='pname'/>" + '</td>' +
                '</tr>');

             });
          },
          error: function(xhr, status, error) {
            alert(xhr.responseText);
          }
        });
      }
      getProducts();
    </script>


问:
Dividing by decimal values - rounding issue
I'm trying to divide two decimal values, in hope they will return the following; 1.132930.

However, SQL appears to be rounding the value to 1.132931.

The value returned before conversion is 1.1329305135951.

The SQL code i'm using is as follows:

```<code>DECLARE @p1 DECIMAL(10,2)
DECLARE @p2 DECIMAL(10,2)

SET @p1 = 225.00
SET @p2 = 198.60

SELECT Cast(@p1/@p2 AS DECIMAL(9,6))
</code>```

答:
You can round the value before the cast as following:</p>

```<code>DECLARE @p1 DECIMAL(10,2)
DECLARE @p2 DECIMAL(10,2)

SET @p1 = 225.00
SET @p2 = 198.60

SELECT Cast(ROUND(@p1/@p2,6,1) AS DECIMAL(9,6))
</code>```

Body:
I'm trying to divide two decimal values, in hope they will return the following; 1.132930.

However, SQL appears to be rounding the value to 1.132931.

The value returned before conversion is 1.1329305135951.

The SQL code i'm using is as follows:

DECLARE @p1 DECIMAL(10,2)
DECLARE @p2 DECIMAL(10,2)

SET @p1 = 225.00
SET @p2 = 198.60

SELECT Cast(@p1/@p2 AS DECIMAL(9,6))

Body:
You can round the value before the cast as following:

DECLARE @p1 DECIMAL(10,2)
DECLARE @p2 DECIMAL(10,2)

SET @p1 = 225.00
SET @p2 = 198.60

SELECT Cast(ROUND(@p1/@p2,6,1) AS DECIMAL(9,6))


问:
How to save an image on a machine without graphic devices?
On a virtual machine on Azure, the following code produces a file with 4 KB that cannot be opened by a viewer:

```<code>pdf(pdf_filepath)
ggplot2::ggplot(...)
dev.off()
</code>```

The code with png("...png") fails to even produce an image.

How to save a plot on a virtual machine without graphic devices?

答:
Since you use ggplot2, you can use ggsave:

gplot2 <- ggplot2::ggplot(...)
ggsave(filepath, plot = gplot2, width = 14, height = 5, units = 'cm')
```

Also mentioned in this thread.

Body:
On a virtual machine on Azure, the following code produces a file with 4 KB that cannot be opened by a viewer:

pdf(pdf_filepath)
ggplot2::ggplot(...)
dev.off()

The code with png("...png") fails to even produce an image.

How to save a plot on a virtual machine without graphic devices?

Body:
Since you use ggplot2, you can use ggsave:

gplot2 <- ggplot2::ggplot(...)
ggsave(filepath, plot = gplot2, width = 14, height = 5, units = 'cm')

Also mentioned in this thread.


问:
My ArrayList is not getting sorted by Collections.sort()
I'm trying to sort an Array by Collections.sort because SDK<24 but it's doing nothing, the array is in the same order, this is the code of my Comparator:

```<code>public class ComparatorFecha implements Comparator<Dinero> {

@Override
public int compare(Dinero o1, Dinero o2) {
    return o1.getFecha().compareTo(o2.getFecha());
}
}
</code>```

Here is the class Dinero:

```<code>public class Dinero implements Serializable {

private String nombre;
private String descripcion;
private int total;
private String date;
private String id;
private Date fecha;

public Dinero(String nombre, String descripcion, int total, String date) {
    this.nombre = nombre;
    this.descripcion = descripcion;
    this.total = total;
    this.date = date;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public void setFecha(Date fecha) {
    this.fecha = fecha;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public int getTotal() {
    return total;
}

public void setTotal(int total) {
    this.total = total;
}

public String getFecha() {
    return date;
}

public void setFecha(String fecha) {
    this.date = fecha;
}

public Date stringToDate(String d1){
    try {
        Log.d(TAG, "FECHA CAMBIADA");
        Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(d1);
        return date1;
    } catch (ParseException e) {
        Log.w(TAG, "FECHA NO CAMBIADA");
        e.printStackTrace();
        return null;
    }
}
}
</code>```

And finally here is which is supposed to sort:

```<code>     public void getIngresos(String user, IngresosIsLoaded iLoaded){
    final  ArrayList<Dinero> beneficio = new ArrayList<>();
    final IngresosIsLoaded ingresosIsLoaded = iLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Ingresos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            beneficio.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
 dinero.setFecha(dinero.stringToDate(fecha));
                dinero.setId(ds.getKey());
                gastos.add(dinero);
            }
            Collections.sort(gastos, new ComparatorFecha());
            gastosLoaded.gastosIsLoaded(gastos);
</code>```

My array is not getting sorting, dont know why, also, there is no log of the class stringToDate, like is not making the function, maybe this could be the problem if "fecha" doesnt exists, nothing will be sorted.

Thanks!

答:
Since your fecha field is not initialized in constructor, it will be null until you call setFecha().  To deal with null values in the sort, change your sort line as follows:</p>

```<code>Collections.sort(gastos, Comparator.nullsFirst(new ComparatorFecha()));
</code>```

Body:
I'm trying to sort an Array by Collections.sort because SDK<24 but it's doing nothing, the array is in the same order, this is the code of my Comparator:

public class ComparatorFecha implements Comparator<Dinero> {

@Override
public int compare(Dinero o1, Dinero o2) {
    return o1.getFecha().compareTo(o2.getFecha());
}
}

Here is the class Dinero:

public class Dinero implements Serializable {

private String nombre;
private String descripcion;
private int total;
private String date;
private String id;
private Date fecha;

public Dinero(String nombre, String descripcion, int total, String date) {
    this.nombre = nombre;
    this.descripcion = descripcion;
    this.total = total;
    this.date = date;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public void setFecha(Date fecha) {
    this.fecha = fecha;
}

public String getNombre() {
    return nombre;
}

public void setNombre(String nombre) {
    this.nombre = nombre;
}

public String getDescripcion() {
    return descripcion;
}

public void setDescripcion(String descripcion) {
    this.descripcion = descripcion;
}

public int getTotal() {
    return total;
}

public void setTotal(int total) {
    this.total = total;
}

public String getFecha() {
    return date;
}

public void setFecha(String fecha) {
    this.date = fecha;
}

public Date stringToDate(String d1){
    try {
        Log.d(TAG, "FECHA CAMBIADA");
        Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(d1);
        return date1;
    } catch (ParseException e) {
        Log.w(TAG, "FECHA NO CAMBIADA");
        e.printStackTrace();
        return null;
    }
}
}

And finally here is which is supposed to sort:

     public void getIngresos(String user, IngresosIsLoaded iLoaded){
    final  ArrayList<Dinero> beneficio = new ArrayList<>();
    final IngresosIsLoaded ingresosIsLoaded = iLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Ingresos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            beneficio.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
 dinero.setFecha(dinero.stringToDate(fecha));
                dinero.setId(ds.getKey());
                gastos.add(dinero);
            }
            Collections.sort(gastos, new ComparatorFecha());
            gastosLoaded.gastosIsLoaded(gastos);

My array is not getting sorting, dont know why, also, there is no log of the class stringToDate, like is not making the function, maybe this could be the problem if "fecha" doesnt exists, nothing will be sorted.

Thanks!

Body:
Since your fecha field is not initialized in constructor, it will be null until you call setFecha().  To deal with null values in the sort, change your sort line as follows:

Collections.sort(gastos, Comparator.nullsFirst(new ComparatorFecha()));


问:
Get data from Observable in Angular 7
I am fairly new to  Angular. Trying to consume  data as follows from a GET REST Endpoint-

```<code>{"employees":[{"empId":"1","name":"emp1","designation":"manager","salary":3000.0},{"empId":"2","name":"emp2","designation":"developer","salary":3000.0}],"addresses":[{"city":"London"},{"city":"Belgium"}]}
</code>```

It has two lists employees and addresses.
In angular i have created the classes as follows-

```<code>export class Employee {

  constructor(

  ) { }
}

export class Address {

  constructor(

  ) { }
}

export class EmployeeDetail {
  public employees: Employee[];
  public addresses: Address[];

  constructor( ) { }
  public get employee(): Employee[] {
    return this.employees;
  }

  public get address(): Address[] {
    return this.addresses;
  }

  public set address(addresses: Address[]){
    this.addresses = addresses;
}

}
</code>```

Trying to construct the EmployeeDetail class as follows-

```<code>getData() {
    return this.httpClient.get<EmployeeDetail>('http://localhost:8080/employees')
    .pipe(
      map(data => {
        const employeeList: Employee[] = [];
        const addressList: Address[] = [];
        var employeeDetail = new EmployeeDetail();
        const newList1 : Employee[] = data.employee;
        const newList2 : Address[] = data.address;
        console.log(newList1);
        newList1.forEach(item =>
          employeeList.push(Object.assign(new Employee(), item)));
        newList2.forEach(item =>
          newList.push(Object.assign(new Address(), item)));
          employeeDetail.employee = employeeList;
          employeeDetail.address = addressList;

        return employeeDetail;
      })
   );
</code>```

Getting following exception

```<code>TypeError: Cannot read property 'forEach' of undefined
    at MapSubscriber.project (http-client.service.ts:119)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
</code>```

Could some one please help me create the EmployeeDetail object. Thanks

答:
You don't really need to put in all that redundant logic in the getData() method.

How about simplifying your implementation like this:

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export class Employee {
  empId: string;
  name: string;
  designation: string;
  salary: number;
}

export class Address {
  city: string;
}

export class EmployeeDetail {
  employees: Employee[];
  addresses: Address[];
}

@Injectable()
export class EmployeeService {

  constructor(private http: HttpClient) {}

  getEmployeeData(): Observable < EmployeeDetail > {
    return this.http.get < EmployeeDetail > ('/assets/employees.json');
  }

}
</code>```

We just specify the T of the get method on the HttpClient to EmployeeDetail and return whatever this method returns. This would return an Observable wrapping a value of type EmployeeDetail.

Here's a Working Sample StackBlitz for your ref.

Title: Get data from Observable in Angular 7

Body:
I am fairly new to  Angular. Trying to consume  data as follows from a GET REST Endpoint-

{"employees":[{"empId":"1","name":"emp1","designation":"manager","salary":3000.0},{"empId":"2","name":"emp2","designation":"developer","salary":3000.0}],"addresses":[{"city":"London"},{"city":"Belgium"}]}

It has two lists employees and addresses.
In angular i have created the classes as follows-

export class Employee {

  constructor(

  ) { }
}

export class Address {

  constructor(

  ) { }
}

export class EmployeeDetail {
  public employees: Employee[];
  public addresses: Address[];

  constructor( ) { }
  public get employee(): Employee[] {
    return this.employees;
  }

  public get address(): Address[] {
    return this.addresses;
  }

  public set address(addresses: Address[]){
    this.addresses = addresses;
}

}

Trying to construct the EmployeeDetail class as follows-

getData() {
    return this.httpClient.get<EmployeeDetail>('http://localhost:8080/employees')
    .pipe(
      map(data => {
        const employeeList: Employee[] = [];
        const addressList: Address[] = [];
        var employeeDetail = new EmployeeDetail();
        const newList1 : Employee[] = data.employee;
        const newList2 : Address[] = data.address;
        console.log(newList1);
        newList1.forEach(item =>
          employeeList.push(Object.assign(new Employee(), item)));
        newList2.forEach(item =>
          newList.push(Object.assign(new Address(), item)));
          employeeDetail.employee = employeeList;
          employeeDetail.address = addressList;

        return employeeDetail;
      })
   );

Getting following exception

TypeError: Cannot read property 'forEach' of undefined
    at MapSubscriber.project (http-client.service.ts:119)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38)
    at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)

Could some one please help me create the EmployeeDetail object. Thanks

Body:
You don't really need to put in all that redundant logic in the getData() method.

How about simplifying your implementation like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

export class Employee {
  empId: string;
  name: string;
  designation: string;
  salary: number;
}

export class Address {
  city: string;
}

export class EmployeeDetail {
  employees: Employee[];
  addresses: Address[];
}

@Injectable()
export class EmployeeService {

  constructor(private http: HttpClient) {}

  getEmployeeData(): Observable < EmployeeDetail > {
    return this.http.get < EmployeeDetail > ('/assets/employees.json');
  }

}

We just specify the T of the get method on the HttpClient to EmployeeDetail and return whatever this method returns. This would return an Observable wrapping a value of type EmployeeDetail.

Here's a Working Sample StackBlitz for your ref.


问:
Truncate span inside td
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P</span>
          <span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

JSFiddle

Expected result:

答: Make sure you have a width or max-width style rule set to the element as well. Otherwise, as long as there is room to grow, it will take up that space. Adding the style rule max-width: 50px; did the trick for me in your example.

Title: Truncate span inside td

Body:
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />

        Col 1
        Col 2
        Col 3

          P
          Pedro Luis Arend Gonçalves

        Info 2
        Info 3

JSFiddle

Expected result:


问:
Matplotlib heatmap for multiple timeseries to show distribution over time
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

```<code>import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()
</code>```

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

答:
Try set_xticklabels:

```<code>series_len = 1000
n_series = 10

fig, ax = plt.subplots(figsize=(10,6))
np.random.seed(1)
y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xs, ys = np.histogram2d(x, y, bins=20)

fig, ax = plt.subplots(figsize=(10,6))
ax.contourf(heatmap.T)

# the actual x-axis and y-axis are from 0 to 19
# we want to put 11 ticks on the axis
ax.set_xticks(np.linspace(0,19,11))
ax.set_xticklabels(range(0,1001,100))

ax.set_yticks(np.linspace(0,19,11))
ax.set_yticklabels(['{:.3f}'.format(y) for y in ys[::2]])

plt.show()
</code>```

Output:

Body:
I have n_series recordings with the same frames 0, 1, 2, 3,... and would like to make a 2D contour out of it.

I've found that I can very easily do the following:

import matplotlib.pyplot as plt
import numpy as np

series_len = 1000
n_series = 10

y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xbins, ybins = np.histogram2d(x, y, bins=20)

plt.contourf(heatmap.T)
plt.show()

But since this just gives a 20x20 histogram, I have no idea how my intensities are distributed in the outputted plot (e.g. roughly zero-centered), nor how to fix the ticks.

What I'd like is this ('shopped):

Body:
Try set_xticklabels:

series_len = 1000
n_series = 10

fig, ax = plt.subplots(figsize=(10,6))
np.random.seed(1)
y = np.random.normal(0, 0.15, series_len * n_series)
x = np.tile(np.arange(0, series_len, 1), n_series)

heatmap, xs, ys = np.histogram2d(x, y, bins=20)

fig, ax = plt.subplots(figsize=(10,6))
ax.contourf(heatmap.T)

# the actual x-axis and y-axis are from 0 to 19
# we want to put 11 ticks on the axis
ax.set_xticks(np.linspace(0,19,11))
ax.set_xticklabels(range(0,1001,100))

ax.set_yticks(np.linspace(0,19,11))
ax.set_yticklabels(['{:.3f}'.format(y) for y in ys[::2]])

plt.show()

Output: