问:
Using awk to extract lines between patterns
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

```<code>Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$
</code>```

desired output

```<code>Name2
ii
ooo
ppp
$$$$
</code>```

I tried something like this:

```<code>awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile
</code>```

I also tried something like

```<code>awk '/^Name2/,/\\$\\$\\$\\$\\/' input
</code>```

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

答:
Instead of using $$$$ as the record separator, you may use the double empty lines, meaning splitting into paragraphs:

```<code>awk 'BEGIN{RS=""}/Name2/' file
</code>```

RS="" is a special value. From the awk man page:

If RS is set to the null string, then records are separated by blank lines.  When RS is set to the null string, the newline character always acts as
         a field separator, in addition to whatever value FS may have.

While the above code is fine for your example, you get into troubles when there are keys like Name20. Meaning a regex match might not be the right approach. An string comparison would probably be a better suite:

```<code>awk 'BEGIN{RS="";FS="\n"} $1 == "Name2"' file
</code>```

I'm explicitly setting FS="\n" to avoid splitting within single lines.

Body:
I am trying to use awk to extract lines between two patterns, but as the second pattern involves multiple $$$$ sign I do not manage to protect properly the $

input is:

Name1
iii
iii
$$$$

Name2
ii
ooo
ppp
$$$$

Name3
pp
oo
ii
uu
$$$$

desired output

Name2
ii
ooo
ppp
$$$$

I tried something like this:

awk 'BEGIN {RS="\\$\\$\\$\\$\n"; FS="\n"} $1==Name2 {print $0; print "$$$$"}' inputfile

I also tried something like

awk '/^Name2/,/\\$\\$\\$\\$\\/' input

I tried many different protection of $ but i do it wrong, either nothing is printed or it prints the entire file

Many thanks for suggestions

Body:
Instead of using $$$$ as the record separator, you may use the double empty lines, meaning splitting into paragraphs:

awk 'BEGIN{RS=""}/Name2/' file

RS="" is a special value. From the awk man page:

If RS is set to the null string, then records are separated by blank lines.  When RS is set to the null string, the newline character always acts as
         a field separator, in addition to whatever value FS may have.

While the above code is fine for your example, you get into troubles when there are keys like Name20. Meaning a regex match might not be the right approach. An string comparison would probably be a better suite:

awk 'BEGIN{RS="";FS="\n"} $1 == "Name2"' file

I'm explicitly setting FS="\n" to avoid splitting within single lines.


来源: stackexchange

问:
.NET datetime Millisecond precision issue when converting from string to datetime

Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

```<code>string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }
</code>```

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?

答:
Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001.

https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

see also: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

ContentLicense: CC BY-SA 3.0

Body:
Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?


问:
Determine tangent (boundary) lines for a polygon from a point

Is there a quick way of determining the two red boundary lines from the point in the figure by using postgis?

答:
You could for example apply the algorithm detailed here in terms of a custom function. Below is an example how it could be translated into PostgreSQL/PostGIS (the implementation assumes that the polygon being tested consists of only one "component").

```<code>CREATE OR REPLACE FUNCTION ST_IsLeft(P0 geometry(POINT), P1 geometry(POINT), P2 geometry(POINT)) RETURNS float AS $$
BEGIN
    RETURN (ST_X(P1) - ST_X(P0))*(ST_Y(P2) - ST_Y(P0)) - (ST_X(P2) - ST_X(P0))*(ST_Y(P1) - ST_Y(P0));
END
$$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION ST_IsAbove(P0 geometry(POINT), Vi geometry(POINT), Vj geometry(POINT)) RETURNS bool AS $$
BEGIN
    RETURN (ST_IsLeft(P0, Vi, Vj) > 0);
END
$$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION ST_IsBelow(P0 geometry(POINT), Vi geometry(POINT), Vj geometry(POINT)) RETURNS bool AS $$
BEGIN
    RETURN (ST_IsLeft(P0, Vi, Vj) < 0);
END
$$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION ST_TangentLine(P geometry(POINT), polygon geometry(POLYGON)) RETURNS SETOF geometry AS $$
DECLARE
    boundary geometry;
    Vi geometry;
    Vr geometry;
    Vl geometry;
    N int;
    i int;
    ePrev float;
    eNext float;
BEGIN
    N := ST_NPoints(polygon);
    i := 0;

    boundary := ST_Boundary(polygon);

    Vr := ST_PointN(boundary, 1);
    Vl := Vr;

    ePrev := ST_IsLeft(ST_PointN(boundary, 1), ST_PointN(boundary, 2), P);
    FOR i IN 2 .. (N-1)
    LOOP
        Vi := ST_PointN(boundary, i);
        eNext := ST_IsLeft(Vi, ST_PointN(boundary, i+1), P);

        IF ((ePrev <= 0) AND (eNext > 0)) THEN
            IF ( NOT ST_IsBelow(P, Vi, Vr) ) THEN
                Vr := Vi;
            END IF;
        ELSIF ((ePrev > 0) AND (eNext <= 0)) THEN
            IF ( NOT ST_IsAbove(P, Vi, Vl) ) THEN
                Vl := Vi;
            END IF;
        END IF;
        ePrev := eNext;
    END LOOP;

    RETURN NEXT ST_MakeLine(P, Vl);
    RETURN NEXT ST_MakeLine(P, Vr);
END
$$ LANGUAGE PLPGSQL;

DROP TABLE IF EXISTS polygons;
CREATE TABLE polygons(iid INTEGER, outline GEOMETRY);
INSERT INTO polygons VALUES (1, ST_GeomFromText('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'));

SELECT iid, ST_AsText(ST_TangentLine(ST_MakePoint(-1, 0.5), outline)) FROM polygons;
</code>```

This then returns

```<code> iid |       st_astext
-----+------------------------
   1 | LINESTRING(-1 0.5,0 1)
   1 | LINESTRING(-1 0.5,0 0)
</code>```

Body:
You could for example apply the algorithm detailed here in terms of a custom function. Below is an example how it could be translated into PostgreSQL/PostGIS (the implementation assumes that the polygon being tested consists of only one "component").

CREATE OR REPLACE FUNCTION ST_IsLeft(P0 geometry(POINT), P1 geometry(POINT), P2 geometry(POINT)) RETURNS float AS $$
BEGIN
    RETURN (ST_X(P1) - ST_X(P0))*(ST_Y(P2) - ST_Y(P0)) - (ST_X(P2) - ST_X(P0))*(ST_Y(P1) - ST_Y(P0));
END
$$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION ST_IsAbove(P0 geometry(POINT), Vi geometry(POINT), Vj geometry(POINT)) RETURNS bool AS $$
BEGIN
    RETURN (ST_IsLeft(P0, Vi, Vj) > 0);
END
$$ LANGUAGE PLPGSQL;
CREATE OR REPLACE FUNCTION ST_IsBelow(P0 geometry(POINT), Vi geometry(POINT), Vj geometry(POINT)) RETURNS bool AS $$
BEGIN
    RETURN (ST_IsLeft(P0, Vi, Vj) < 0);
END
$$ LANGUAGE PLPGSQL;

CREATE OR REPLACE FUNCTION ST_TangentLine(P geometry(POINT), polygon geometry(POLYGON)) RETURNS SETOF geometry AS $$
DECLARE
    boundary geometry;
    Vi geometry;
    Vr geometry;
    Vl geometry;
    N int;
    i int;
    ePrev float;
    eNext float;
BEGIN
    N := ST_NPoints(polygon);
    i := 0;

    boundary := ST_Boundary(polygon);

    Vr := ST_PointN(boundary, 1);
    Vl := Vr;

    ePrev := ST_IsLeft(ST_PointN(boundary, 1), ST_PointN(boundary, 2), P);
    FOR i IN 2 .. (N-1)
    LOOP
        Vi := ST_PointN(boundary, i);
        eNext := ST_IsLeft(Vi, ST_PointN(boundary, i+1), P);

        IF ((ePrev <= 0) AND (eNext > 0)) THEN
            IF ( NOT ST_IsBelow(P, Vi, Vr) ) THEN
                Vr := Vi;
            END IF;
        ELSIF ((ePrev > 0) AND (eNext <= 0)) THEN
            IF ( NOT ST_IsAbove(P, Vi, Vl) ) THEN
                Vl := Vi;
            END IF;
        END IF;
        ePrev := eNext;
    END LOOP;

    RETURN NEXT ST_MakeLine(P, Vl);
    RETURN NEXT ST_MakeLine(P, Vr);
END
$$ LANGUAGE PLPGSQL;

DROP TABLE IF EXISTS polygons;
CREATE TABLE polygons(iid INTEGER, outline GEOMETRY);
INSERT INTO polygons VALUES (1, ST_GeomFromText('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))'));

SELECT iid, ST_AsText(ST_TangentLine(ST_MakePoint(-1, 0.5), outline)) FROM polygons;

This then returns

 iid |       st_astext
-----+------------------------
   1 | LINESTRING(-1 0.5,0 1)
   1 | LINESTRING(-1 0.5,0 0)


问:
Flask function in link onClick doesn't work after going back with browser
I am using python flask framework to create a web project. In one of its pages, there is a link to another page which is like this:

```<code><a onclick="{{ recipe.increment_clickcount() }}" href="/recipe/{{ recipe.id }}">{{ recipe.name }}</a>
</code>```

Here I send recipe object to that page and it has a method called increment_clickcount which increments the clickcount variable in that recipe object by one. I do this to store how many times that recipe is clicked.

When I click that link it does what I want, Then I go back to the page where the link is in using the back button of the browser (Google Chrome). Then I click that link again but this time, it doesn't increment it. I refreshed the page then clicked that link and increment works fine again.

I assume it stored in the cache or something but I do not have enough iinformation about it.

How can I make this function work even when the above situation happened?

答:
Try adding an empty function to the top of the JS (or HTML, for that matter) file of that page:

```<code>window.onunload = function(){};
</code>```

But I'm now entirely sure that's what you need. If it was clicked already, isn't it more logical the click count will not increment ?

Body:
I am using python flask framework to create a web project. In one of its pages, there is a link to another page which is like this:

{{ recipe.name }}

Here I send recipe object to that page and it has a method called increment_clickcount which increments the clickcount variable in that recipe object by one. I do this to store how many times that recipe is clicked.

When I click that link it does what I want, Then I go back to the page where the link is in using the back button of the browser (Google Chrome). Then I click that link again but this time, it doesn't increment it. I refreshed the page then clicked that link and increment works fine again.

I assume it stored in the cache or something but I do not have enough iinformation about it.

How can I make this function work even when the above situation happened?

Body:
Try adding an empty function to the top of the JS (or HTML, for that matter) file of that page:

window.onunload = function(){};

But I'm now entirely sure that's what you need. If it was clicked already, isn't it more logical the click count will not increment ?


问:
Adding columns with two data types in SQL Server
I need to achieve the output like this can anyone please help me. Thanks in advance

答:
try the following:

```<code>declare @tab table (names varchar(1000))
insert into @tab
select 'a10' union select 'abc20' union select 'xyz5' union select 'b6'

select * from @tab

select names, substring(names, 1, patindex('%[0-9]%',names)-1) [name], substring(names, patindex('%[0-9]%',names), len(names)) [sum]
from @tab
</code>```

Thanks.

Body:
try the following:

declare @tab table (names varchar(1000))
insert into @tab
select 'a10' union select 'abc20' union select 'xyz5' union select 'b6'

select * from @tab

select names, substring(names, 1, patindex('%[0-9]%',names)-1) [name], substring(names, patindex('%[0-9]%',names), len(names)) [sum]
from @tab

Thanks.


问:
NUXT - SSR - components are not being rendered server side
I'm new to Nuxt - converted my vue app to it, and got it working on production: gameslate.io

The app is using the asyncData method to get the list of games - however the full layout isn't being rendered the server...

If you view the page source you'll see that Nuxt is putting all of the data in window.__NUXT__, but there's no grid html.

How do I render the full layout on the server after getting data with asyncData?

Otherwise, google can't crawl the game lists - this becomes pretty useless for SEO... (checkout twitter's page source - it loads the entire page including dynamic content)

This is the "home" page component that makes the asyncData call (simplified):

```<code><template>
  <div>things</div>                       <!-- rendered on server -->
  <game-grid :games="games"></game-grid>  <!-- rendered in browser -->
</template>

<script>
  export default {
    data() {
      return {
        games: []
      }
    }
    async asyncData() {
      let games = await getGames(filters);
      return { games };
    }
  }
</script>
</code>```

答:
You have to remove the data () (returning an empty array) because it's overriding the asyncData.

And google can crawl perfectly because the DOM tree is generated if you use asyncData, you can check on view-source:http://localhost:3000

Body:
I'm new to Nuxt - converted my vue app to it, and got it working on production: gameslate.io

The app is using the asyncData method to get the list of games - however the full layout isn't being rendered the server...

If you view the page source you'll see that Nuxt is putting all of the data in window.__NUXT__, but there's no grid html.

How do I render the full layout on the server after getting data with asyncData?

Otherwise, google can't crawl the game lists - this becomes pretty useless for SEO... (checkout twitter's page source - it loads the entire page including dynamic content)

This is the "home" page component that makes the asyncData call (simplified):

<template>

things

  <game-grid :games="games"></game-grid>
</template>


问:
Node/Express API, Email verification using JWT token, unexpected behavior

Kind of a strange issue. I am building a NodeJS/Express api using json web tokens for email verification for users. Code for both the user registration and email confirmation routes are below. When testing these routes in Postman using the following procedure, everything goes fine (status 200, user object returns):
  1. Send POST request to create user.
  2. Use mongodb shell to get the token from the new user.
  3. Use copy/pasted token in get request to confirmation route.

However, when actually clicking the link that gets sent by email everything updates in the DB as it's meant to, but I get a 401 error. Even copying and pasting the token from the link in the email and sending it in postman has the same result.

Routes:

```<code>app.post('/api/users', (req, res) => {
  let body = _.pick(req.body, [
    'email', 'password', 'firstName', 'lastName', 'adminRequested'
  ]);
  let user = new User(body);

  user.save().then(() => {
    return user.generateAuthToken('confirmation', '1h');
  }).then((token) => {
    let currentUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    let confirmationUrl = currentUrl + `/confirm/${token}`;
    mailTransport.sendMail({
      from: `Break Board API <${process.env.MAIL_USER}>`,
      to: user.email,
      subject: 'Your Email Confirmation Link',
      text: `Click this link to verify your email: ${confirmationUrl}`
    });
    res.send(JSON.stringify(user, undefined, 2));
  }).catch((e) => {
    res.status(400).send(e);
  });
});

app.get('/api/users/confirm/:token', confirmToken, (req, res) => {
  let token = req.token;
  let user = req.user;
  req.user.update({
    $set: {
      emailConfirmed: true
    },
    $pull: {
      tokens: {token}
    }
  }).then(() => {
    res.send(user);
  });
});
</code>```

confirmToken middleware:

```<code>let {User} = require('./../models/user');

let confirmToken = (req, res, next) => {
  let token = req.params.token;

  User.findByToken(token).then((user) => {
    if(!user) {
      return Promise.reject();
    }
    req.user = user;
    req.token = token;
    next();
  }).catch((e) => {
    res.status(401).send();
  });
};
</code>```

The middle ware is the only place in the entire code that has a res.status(401), so I know that is where it's coming from, but can't understand why it only happens when using the token from the email, or all the DB operations are still succeeding if it is indeed a 401. When forcing 401 errors in Postman with modified or non-existant JWT tokens, the DB operations are never performed.

Any ideas?

答: Okay, after getting fed up I decided to just move on with implementation and inadvertently found the solution. When I switched to rendering the email in html instead of text, the email client no longer caused the token link to be followed.</p>

Body:
Kind of a strange issue. I am building a NodeJS/Express api using json web tokens for email verification for users. Code for both the user registration and email confirmation routes are below. When testing these routes in Postman using the following procedure, everything goes fine (status 200, user object returns):
  1. Send POST request to create user.
  2. Use mongodb shell to get the token from the new user.
  3. Use copy/pasted token in get request to confirmation route.

However, when actually clicking the link that gets sent by email everything updates in the DB as it's meant to, but I get a 401 error. Even copying and pasting the token from the link in the email and sending it in postman has the same result.

Routes:

app.post('/api/users', (req, res) => {
  let body = _.pick(req.body, [
    'email', 'password', 'firstName', 'lastName', 'adminRequested'
  ]);
  let user = new User(body);

  user.save().then(() => {
    return user.generateAuthToken('confirmation', '1h');
  }).then((token) => {
    let currentUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    let confirmationUrl = currentUrl + `/confirm/${token}`;
    mailTransport.sendMail({
      from: `Break Board API <${process.env.MAIL_USER}>`,
      to: user.email,
      subject: 'Your Email Confirmation Link',
      text: `Click this link to verify your email: ${confirmationUrl}`
    });
    res.send(JSON.stringify(user, undefined, 2));
  }).catch((e) => {
    res.status(400).send(e);
  });
});

app.get('/api/users/confirm/:token', confirmToken, (req, res) => {
  let token = req.token;
  let user = req.user;
  req.user.update({
    $set: {
      emailConfirmed: true
    },
    $pull: {
      tokens: {token}
    }
  }).then(() => {
    res.send(user);
  });
});

confirmToken middleware:

let {User} = require('./../models/user');

let confirmToken = (req, res, next) => {
  let token = req.params.token;

  User.findByToken(token).then((user) => {
    if(!user) {
      return Promise.reject();
    }
    req.user = user;
    req.token = token;
    next();
  }).catch((e) => {
    res.status(401).send();
  });
};

The middle ware is the only place in the entire code that has a res.status(401), so I know that is where it's coming from, but can't understand why it only happens when using the token from the email, or all the DB operations are still succeeding if it is indeed a 401. When forcing 401 errors in Postman with modified or non-existant JWT tokens, the DB operations are never performed.

Any ideas?


问:
Creating one output table for multiple results from different functions in R
I was trying search accordingly to find the solution for my issue but I failed, so I'm writing here. At the moment I've created quite large set of functions in R, around 500 lines of the code for each scripts (7 scripts) producing the output of the calculation in the standardized form:

```<code>    >getFunction1(Key_ID)
#output
              calc1    calc2
category1       0.00     0.3
category2       0.06     0.2
category3       0.00     0.3

>getFunction2(Key_ID)
#output
              calc1    calc2
category1       0.10     0.1
category2       0.02     0.3
category3       0.01     0.3
(...)
>getFunction7(Key_ID)
#output
              calc1    calc2
category1       0.20     0.15
category2       0.04     0.4
category3       0.02     0.35
</code>```

Designed functions whithin 7 scripts are same from the structure point of view but contating different calculations depend on category of the function (specific use case) and (inside the script) category of the calculations. Everything work perfectly but I'm not able to create one coherent table storing calculation coming from all getFunction1-7(Key_ID) in one tablelaric form looking like this:

```<code>Key_ID|Name_Function(refering to use case)|Category(whithin the function)|Cal1|Cal2|
</code>```

Key_ID is crucial part, because this is ID allowing join new calculation with the previous one in data base. I cannot simply create tabelaric structure like:

```<code>tableFunction1 <- as.data.frame(getFunction1(Key_ID))
</code>```

cause depending on Key_ID I can receive different scores depending on the subject of the calculation, thus Key_ID referring on different objects with different attributes included into calculations.

Have you ever faced with kind of issue ? Any advise so far for me ?
Thanks a lot for any.
Aleksandra

答:
If the output from each function is a data frame containing categories and calculations, you need a way to add KEY_ID and the name of the function that produced the calculations. Since the OP didn't include logic of any of the functions being discussed, we'll assume that the current output is a data frame containing the columns category, calc1, and calc2.

First, since KEY_ID is passed as an argument into each of the seven functions, you can create a column in the output data frame containing this value.

```<code># assuming output frame has already been created, add id column
# by using rep() to repeat the value of the KEY_ID argument
output$id <- rep(KEY_ID,nrow(output))
</code>```

Second, you'll want to similarly add the name of the current function as a column in your output data frame. This can be accomplished with match.call().

```<code># add name of current function to output data frame
output$name_function <- rep(match.call()[[1]],nrow(output))
</code>```

Body:
I was trying search accordingly to find the solution for my issue but I failed, so I'm writing here. At the moment I've created quite large set of functions in R, around 500 lines of the code for each scripts (7 scripts) producing the output of the calculation in the standardized form:

    >getFunction1(Key_ID)
#output
              calc1    calc2
category1       0.00     0.3
category2       0.06     0.2
category3       0.00     0.3

>getFunction2(Key_ID)
#output
              calc1    calc2
category1       0.10     0.1
category2       0.02     0.3
category3       0.01     0.3
(...)
>getFunction7(Key_ID)
#output
              calc1    calc2
category1       0.20     0.15
category2       0.04     0.4
category3       0.02     0.35

Designed functions whithin 7 scripts are same from the structure point of view but contating different calculations depend on category of the function (specific use case) and (inside the script) category of the calculations. Everything work perfectly but I'm not able to create one coherent table storing calculation coming from all getFunction1-7(Key_ID) in one tablelaric form looking like this:

Key_ID|Name_Function(refering to use case)|Category(whithin the function)|Cal1|Cal2|

Key_ID is crucial part, because this is ID allowing join new calculation with the previous one in data base. I cannot simply create tabelaric structure like:

tableFunction1 <- as.data.frame(getFunction1(Key_ID))

cause depending on Key_ID I can receive different scores depending on the subject of the calculation, thus Key_ID referring on different objects with different attributes included into calculations.

Have you ever faced with kind of issue ? Any advise so far for me ?
Thanks a lot for any.
Aleksandra

Body:
If the output from each function is a data frame containing categories and calculations, you need a way to add KEY_ID and the name of the function that produced the calculations. Since the OP didn't include logic of any of the functions being discussed, we'll assume that the current output is a data frame containing the columns category, calc1, and calc2.

First, since KEY_ID is passed as an argument into each of the seven functions, you can create a column in the output data frame containing this value.

# assuming output frame has already been created, add id column
# by using rep() to repeat the value of the KEY_ID argument
output$id <- rep(KEY_ID,nrow(output))

Second, you'll want to similarly add the name of the current function as a column in your output data frame. This can be accomplished with match.call().

# add name of current function to output data frame
output$name_function <- rep(match.call()[[1]],nrow(output))


问:
React-native: Google maps only loads statically
I've been fighting this code for quite some time now.
I've gotten it to the point where the google map loads, only after using the Android 'multi-tasker'.

The page starts up with a white background: as seen here

Then after pressing the button in the bottom right corner, to switch apps, it loads:
Google Maps loaded

But, if I drag to go to a different place, I need to do the app switching again before it does that. Some kind of static updating. Not sure why..

This is the second page, and if I go back to the first page of the app, google maps goes back to the white background. I've tried making the google maps page  into the first page, but that doesn't resolve anything either.

The code I'm using right now:

```<code>  import React, { Component } from 'react';
  import MapView from 'react-native-maps';
  import { AppRegistry, View, StyleSheet, Dimensions } from 'react-native';

  const { width, height } = Dimensions.get('window');
  const ASPECT_RATIO    = width / height;
  const LATITUDE        = 37.78825;
  const LONGITUDE       = -122.4324;
  const LATITUDE_DELTA  = 0.0122;
  const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
  const SPACE           = 0.01;

  class Additional extends React.Component {
  constructor() {
  super();
  this.state = {
  region: {
    latitude: LATITUDE,
    longitude: LONGITUDE,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
    }
   }
  }

  componentDidMount() {
  navigator.geolocation.getCurrentPosition(
  (position) => {
    this.setState({
      region: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
        accuracy: position.coords.accuracy
      }
    });
  },
  (error) => alert(error.message),
  {timeout: 10000}
);

    this.watchID = navigator.geolocation.watchPosition((position) => {
    const newRegion = {
    latitude: position.coords.latitude,
    longitude: position.coords.longitude,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
    accuracy: position.coords.accuracy
  }
  this.setState({newRegion});
});
}

componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}

render() {
return (
  <View style={styles.container}>
    <MapView
      style={styles.map}
      region={this.state.region}
      showsUserLocation={true}
      followUserLocation={true}>
    </MapView>
  </View>
 );
 }
 }

 const styles = StyleSheet.create({
  container: {
  ...StyleSheet.absoluteFillObject,
  justifyContent: 'flex-end',
  alignItems: 'center',
  },
  map: {
  ...StyleSheet.absoluteFillObject,
  },
  });
  AppRegistry.registerComponent('Additional', () => Additional);

  export default Additional;
</code>```

Does anyone know the answer to making this work like the normal google-maps component as it should?

Thanks in advance!

EDIT:
I've tried this code with a fresh React-Native project, but the exact same thing happens. Anyone got some input? Thanks!

答:
The issue lies within react-native-maps.

In // lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java

```<code>if (!contextHasBug(appContext.getCurrentActivity())) {
   superContext = appContext.getCurrentActivity();
} else if (contextHasBug(superContext)) {
</code>```

Into:

```<code>if (contextHasBug(superContext)) {
</code>```

And you'll be good to go.

Body:
I've been fighting this code for quite some time now.
I've gotten it to the point where the google map loads, only after using the Android 'multi-tasker'.

The page starts up with a white background: as seen here

Then after pressing the button in the bottom right corner, to switch apps, it loads:
Google Maps loaded

But, if I drag to go to a different place, I need to do the app switching again before it does that. Some kind of static updating. Not sure why..

This is the second page, and if I go back to the first page of the app, google maps goes back to the white background. I've tried making the google maps page  into the first page, but that doesn't resolve anything either.

The code I'm using right now:

  import React, { Component } from 'react';
  import MapView from 'react-native-maps';
  import { AppRegistry, View, StyleSheet, Dimensions } from 'react-native';

  const { width, height } = Dimensions.get('window');
  const ASPECT_RATIO    = width / height;
  const LATITUDE        = 37.78825;
  const LONGITUDE       = -122.4324;
  const LATITUDE_DELTA  = 0.0122;
  const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
  const SPACE           = 0.01;

  class Additional extends React.Component {
  constructor() {
  super();
  this.state = {
  region: {
    latitude: LATITUDE,
    longitude: LONGITUDE,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
    }
   }
  }

  componentDidMount() {
  navigator.geolocation.getCurrentPosition(
  (position) => {
    this.setState({
      region: {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
        accuracy: position.coords.accuracy
      }
    });
  },
  (error) => alert(error.message),
  {timeout: 10000}
);

    this.watchID = navigator.geolocation.watchPosition((position) => {
    const newRegion = {
    latitude: position.coords.latitude,
    longitude: position.coords.longitude,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
    accuracy: position.coords.accuracy
  }
  this.setState({newRegion});
});
}

componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchID);
}

render() {
return (
  <View style={styles.container}>
    <MapView
      style={styles.map}
      region={this.state.region}
      showsUserLocation={true}
      followUserLocation={true}>
    </MapView>
  </View>
 );
 }
 }

 const styles = StyleSheet.create({
  container: {
  ...StyleSheet.absoluteFillObject,
  justifyContent: 'flex-end',
  alignItems: 'center',
  },
  map: {
  ...StyleSheet.absoluteFillObject,
  },
  });
  AppRegistry.registerComponent('Additional', () => Additional);

  export default Additional;

Does anyone know the answer to making this work like the normal google-maps component as it should?

Thanks in advance!

EDIT:
I've tried this code with a fresh React-Native project, but the exact same thing happens. Anyone got some input? Thanks!

Body:
The issue lies within react-native-maps.

In // lib/android/src/main/java/com/airbnb/android/react/maps/AirMapView.java

if (!contextHasBug(appContext.getCurrentActivity())) {
   superContext = appContext.getCurrentActivity();
} else if (contextHasBug(superContext)) {

Into:

if (contextHasBug(superContext)) {

And you'll be good to go.


问:
Razor syntax within html attributes
Check out the following:

```<code><a href="/test?x=@if (Model.IsTest) { @(1) } else { @(4) }"></a>
</code>```

Is there a better way to write this instead of the @(1) and @(4)?

答:
You can use the conditional operator:</p>

```<code><a href="/test?x=@(Model.IsTest ? 1 : 4)"></a>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Razor syntax within html attributes

Body:
Check out the following:

Is there a better way to write this instead of the @(1) and @(4)?

Body:
You can use the conditional operator:

<a href="/test?x=@(Model.IsTest ? 1 : 4)"></a>


问:
MySQL Markup Records with Duplicates on Select
I have seen MySQL Mark Records with Duplicates question and answers. But I have a different situation.

How to select all records, but have a flag for those records who have duplicates in a given field.

```<code>id     name
--------------
1      John
2      Peter
3      John
4      David
</code>```

And I want something like that:

```<code>SELECT
    id,
    name,
  -- IF(~duplicate in name~, 1, 0) AS is_duplicate
FROM tab
</code>```

答:
I assume id is set to auto increment then you can use following query for your desired output

```<code>select distinct a.*,
case when b.id is null then 0 else 1 end `duplicate`
from tab a
left join tab b
on a.name = b.name
and a.id > b.id
order by a.id
</code>```

Demo

Body:
I have seen MySQL Mark Records with Duplicates question and answers. But I have a different situation.

How to select all records, but have a flag for those records who have duplicates in a given field.

id     name
--------------
1      John
2      Peter
3      John
4      David

And I want something like that:

SELECT
    id,
    name,
  -- IF(~duplicate in name~, 1, 0) AS is_duplicate
FROM tab

Body:
I assume id is set to auto increment then you can use following query for your desired output

select distinct a.*,
case when b.id is null then 0 else 1 end `duplicate`
from tab a
left join tab b
on a.name = b.name
and a.id > b.id
order by a.id

Demo


问:
How to get values from JObject
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

```<code> [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}
</code>```

Json which I am getting :

```<code>{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}
</code>```

答:
You can try like this;</p>

```<code>[HttpPost]
[Route("")]
public void Post(JObject message)
{
    var dynamicMessage = (dynamic)message;
    var status = dynamicMessage.status;
    var title = dynamicMessage.title;
}
</code>```

Title: How to get values from JObject

Body:
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

 [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}

Json which I am getting :

{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}

Body:
You can try like this;

[HttpPost]
[Route("")]
public void Post(JObject message)
{
    var dynamicMessage = (dynamic)message;
    var status = dynamicMessage.status;
    var title = dynamicMessage.title;
}


问:
pthread segmentation fault (core dumped) error
Can somebody point out why my code is throwing segmentation fault? Most likely I am making a mistake when calling pthread_create() but I am failing to understand the mistake. Can somebody point out where am I going wrong?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int x = 0;
int counter =
    0;  // This is the global variable that all the threads will increment.
pthread_mutex_t lock;

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;
  int* y = (int*)x;
  int total = (*id) * (*y);
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

int main(int argc, char* argv[]) {
  int thread_count = 0;
  int loop_count = 0;
  int expected_value = -1;

  if (argc != 3) {
    printf("Usage: threads <no_of_threads> <no_of_loops>\n");
    exit(1);
  }

  thread_count = atoi(argv[1]);
  loop_count = atoi(argv[2]);
  x = loop_count;

  // Start your implementation after this comment.
  pthread_t* threads;
  threads = malloc(sizeof(pthread_t) * thread_count);
  int t;
  int flag = 0;
  for (t = 0; t < thread_count; t++) {
    int* z = malloc(sizeof(int));
    *z = t;
    flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
  }
  if (flag != 0) {
    printf("error in creating threads");
    exit(0);
  }

  for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
  // Do not change the code below this comment
  return 0;
}
</code>```

The output of this code is:

Segmentation fault (core dumped)

How should I resolve this error?

答:
first thing, you should initialize mutex variable with PTHREAD_MUTEX_INITIALIZER.

```<code>pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
</code>```

or you can call pthread_mutex_init(&lock,0) from main thread to initialize lock.

second thing, replace below statement

```<code> int* y = (int*) x;
</code>```

with

```<code> int* y = (int*) &x;
</code>```

because y should have valid address else you can't perform *y later(as you are doing)

I hope it helps.

Body:
Can somebody point out why my code is throwing segmentation fault? Most likely I am making a mistake when calling pthread_create() but I am failing to understand the mistake. Can somebody point out where am I going wrong?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int x = 0;
int counter =
    0;  // This is the global variable that all the threads will increment.
pthread_mutex_t lock;

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;
  int* y = (int*)x;
  int total = (*id) * (*y);
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

int main(int argc, char* argv[]) {
  int thread_count = 0;
  int loop_count = 0;
  int expected_value = -1;

  if (argc != 3) {
    printf("Usage: threads <no_of_threads> <no_of_loops>\n");
    exit(1);
  }

  thread_count = atoi(argv[1]);
  loop_count = atoi(argv[2]);
  x = loop_count;

  // Start your implementation after this comment.
  pthread_t* threads;
  threads = malloc(sizeof(pthread_t) * thread_count);
  int t;
  int flag = 0;
  for (t = 0; t < thread_count; t++) {
    int* z = malloc(sizeof(int));
    *z = t;
    flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
  }
  if (flag != 0) {
    printf("error in creating threads");
    exit(0);
  }

  for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
  // Do not change the code below this comment
  return 0;
}

The output of this code is:

Segmentation fault (core dumped)

How should I resolve this error?

Body:
first thing, you should initialize mutex variable with PTHREAD_MUTEX_INITIALIZER.

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

or you can call pthread_mutex_init(&lock,0) from main thread to initialize lock.

second thing, replace below statement

 int* y = (int*) x;

with

 int* y = (int*) &x;

because y should have valid address else you can't perform *y later(as you are doing)

I hope it helps.


问:
CONVERT ASP TO ASP.NET
Which is the best way to convert a .asp page to .aspx? Classic asp to asp.net.
I'm trying to avoid rewriting all the pages from scratch.

Thanks

答: I think it's a completely different language and you really can't avoid doing everything from scracth. I think that any solution other than starting all over would take just as much time and headache than starting from scratch.</p>

Title: CONVERT ASP TO ASP.NET


问:
use vector of vectors to draw a ground in opengl
I initialized the vector as this:

```<code>   vector<vector<GLfloat> > ground_vertices {
   {-10, -0.1, 50},
   {10, -0.1, 50},
   {-10, -0.1, -300},
   {10, -0.1, -300} };
</code>```

and my drawing function is like this

```<code>  void Ground() {
  glBegin(GL_QUADS);
     for (int i=0; i < 4; i++)
     {
         glColor3f(0.0f, 1.0f, 0.0f);
         glVertex3f(ground_vertices[i]);
     }
  glEnd();
</code>```

}

But I kept getting

ground.cpp|37 col 40 error| cannot convert ‘__gnu_cxx::__alloc_traits > ::value_type   {aka std::vector}’ to ‘GLfloat {aka float}’ for argument ‘1’ to ‘void glVertex3f(GLfloat, GLfloat, GLfloat)’

I wonder how can I fix it. Thank you!

答:
Use the function glVertex3fv(const GLfloat * v) and pass a pointer to the vertex data to it.

You can get a pointer to the data contained in a std::vector by std::vector::data:

```<code>glVertex3fv(ground_vertices[i].data());
</code>```

Note, the correct coding with the use of glVertex3f(GLfloat x, GLfloat y, GLfloat z) would be:

```<code>glVertex3f(
    ground_vertices[i][0],
    ground_vertices[i][1],
    ground_vertices[i][2]);
</code>```

Body:
I initialized the vector as this:

   vector<vector<GLfloat> > ground_vertices {
   {-10, -0.1, 50},
   {10, -0.1, 50},
   {-10, -0.1, -300},
   {10, -0.1, -300} };

and my drawing function is like this

  void Ground() {
  glBegin(GL_QUADS);
     for (int i=0; i < 4; i++)
     {
         glColor3f(0.0f, 1.0f, 0.0f);
         glVertex3f(ground_vertices[i]);
     }
  glEnd();

}

But I kept getting

ground.cpp|37 col 40 error| cannot convert ‘__gnu_cxx::__alloc_traits > ::value_type   {aka std::vector}’ to ‘GLfloat {aka float}’ for argument ‘1’ to ‘void glVertex3f(GLfloat, GLfloat, GLfloat)’

I wonder how can I fix it. Thank you!

Body:
Use the function glVertex3fv(const GLfloat * v) and pass a pointer to the vertex data to it.

You can get a pointer to the data contained in a std::vector by std::vector::data:

glVertex3fv(ground_vertices[i].data());

Note, the correct coding with the use of glVertex3f(GLfloat x, GLfloat y, GLfloat z) would be:

glVertex3f(
    ground_vertices[i][0],
    ground_vertices[i][1],
    ground_vertices[i][2]);


问:
How to push struct type variable in standard stack in c++
Code Should i use &g on calling or *s in stack declaration?:</p>

```<code>#include<iostream>
#include<stack>
using namespace std;

struct node{
    int data;
    struct node *link;
};

main(){
    stack<node> s;
    struct node *g;
    g = new node;
    s.push(g);
}
</code>```

答: I think you have an error at s.push(g) because type of gis node*, so you cannot put it into stack<node>. I think you should declare stack < node*> because it's easy to use with new operation.

Body:
Code Should i use &g on calling or *s in stack declaration?:

#include<iostream>
#include<stack>
using namespace std;

struct node{
    int data;
    struct node *link;
};

main(){
    stack<node> s;
    struct node *g;
    g = new node;
    s.push(g);
}


问:
Kivy: How to change window size?
I'm starting to write a program using kivy, but I have some problems understand how it deals with sizes.

For example:

```<code>import kivy
kivy.require('1.5.1')

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self): return Button(text='Some text')

MyApp().run()
</code>```

The above program works, but it creates a huge window. Trying to set size=(100, 100) does not change anything. Setting size_hint=(None, None) will show a button with the correct size, but it is placed randomly inside a still huge window.
Trying to set the size of MyApp does not change anything too.

How do I create a window with the same size of the button?
It should be a simple enough task, but looking at the documentation and example I can't find anything about this.

答:
I would comment on martin's answer, but I don't have the reputation. When setting the config file, be sure to "write" your changes:

```<code>from kivy.config import Config
Config.set('graphics', 'width', '200')
Config.set('graphics', 'height', '200')
Config.write()
</code>```

It's exactly like committing info to a database, if you know anything about that.

Title: Kivy: How to change window size?

Body:
I'm starting to write a program using kivy, but I have some problems understand how it deals with sizes.

For example:

import kivy
kivy.require('1.5.1')

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self): return Button(text='Some text')

MyApp().run()

The above program works, but it creates a huge window. Trying to set size=(100, 100) does not change anything. Setting size_hint=(None, None) will show a button with the correct size, but it is placed randomly inside a still huge window.
Trying to set the size of MyApp does not change anything too.

How do I create a window with the same size of the button?
It should be a simple enough task, but looking at the documentation and example I can't find anything about this.

Body:
I would comment on martin's answer, but I don't have the reputation. When setting the config file, be sure to "write" your changes:

from kivy.config import Config
Config.set('graphics', 'width', '200')
Config.set('graphics', 'height', '200')
Config.write()

It's exactly like committing info to a database, if you know anything about that.


问:
how to open facebook app from website link
I have this code to open my facebook page from my website link.
But when browsing my page on mobile browser it open facebook link in browser too but I'd like to open the facebook page in app if installed.
Here is my code

答:
replace //facebook.com with fb://

```<code><a href="fb://myfacepage/" target="_blank" rel="alternate"><img src="images/facebook-logo.png" alt="" /></a></p>
</code>```

Body:
replace //facebook.com with fb://

<a href="fb://myfacepage/" target="_blank" rel="alternate"><img src="images/facebook-logo.png" alt="" /></a></p>


问:
Display IF output somewhere else PhP
So i have got this code:

```<code><?php
$host = "http://$_SERVER[HTTP_HOST]";
    $rd = "/beta/";
    $beta = "<font color='#6034b1'>BETA</font>";
    if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
    header('Refresh:10;' . $host.$rd);
    echo "<center>You are member of the $beta Project<br>You will be redirected in:<div id='countdown'>10</div><br><progress value='0' max='9' id='progressBar'></progress></center>";}
        else {
    echo "<center>You are not a Member of our $beta Project!<br><a style='border-bottom:1px solid black;' href='switch-to-beta.php'>JOIN NOW</a>";
    }
    ?>
</code>```

Since I have to Place the PhP Script before my  tag so the header refresh works, the echo messages get displayed on the very top of the page ( Basically behind my Navbar).

So now my question, is there a way to display the output of this if statement via something like a variable somwhere else on the site?

答:
Yes, you could set the message as a variable,

```<code>if (YOUR STATEMENT HERE) {
    header();
    $message = "your message";
else {
    $message = "another message";
}
</code>```

Then later in your HTML you could open another PHP tag and echo the variable.

```<code><p><?php echo $message; ?></p>
</code>```

Title: Display IF output somewhere else PhP

Body:
So i have got this code:

<?php
$host = "http://$_SERVER[HTTP_HOST]";
    $rd = "/beta/";
    $beta = "BETA";
    if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
    header('Refresh:10;' . $host.$rd);
    echo "You are member of the $beta Project
You will be redirected in:
10

<progress value='0' max='9' id='progressBar'></progress>";}
        else {
    echo "You are not a Member of our $beta Project!
JOIN NOW";
    }
    ?>

Since I have to Place the PhP Script before my  tag so the header refresh works, the echo messages get displayed on the very top of the page ( Basically behind my Navbar).

So now my question, is there a way to display the output of this if statement via something like a variable somwhere else on the site?

Body:
Yes, you could set the message as a variable,

if (YOUR STATEMENT HERE) {
    header();
    $message = "your message";
else {
    $message = "another message";
}

Then later in your HTML you could open another PHP tag and echo the variable.

<p><?php echo $message; ?></p>


问:
Dont count respectively vhdl
```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity A is
  Port (
        clk : in STD_LOGIC;
        reset: in std_logic; -- reset input
        counter: out std_logic_vector(3 downto 0) := "0000"-- output 4-bit counter
);
end A;

architecture Behavioral of A is
 signal counter_up: std_logic_vector(3 downto 0) := "0000";
 signal countOf : integer := -1;
 signal count : integer := 0;
 signal temp : std_logic := '0';
begin
-- up counter

      process(clk)
     begin
if(clk'event and clk='1') then
count <=count+1;
if(count = 50000000) then
temp <= not temp;
count <=1;
end if;
end if;
end process;

process(temp,reset)
begin
if(reset = '1') then
    countOf <= 0;
 else
        if(temp = '1') then

             if( countOf < 4) then countOf <= countOf + 1;
             else countOf <= 0; end if;

            if(countOf = 0) then counter_up <= "0000"; end if;
            if(countOf = 1) then counter_up <= "0001"; end if;
            if(countOf = 2) then counter_up <= "0010"; end if;
            if(countOf = 3) then counter_up <= "0100"; end if;
            if(countOf = 4) then counter_up <= "1000"; end if;

        end if;

 end if;
end process;

counter <= counter_up;

end Behavioral;
</code>```

Hi I want to make a counter from 0 up to 4. As you see I divide my clock to 1 HZ and in the process of temp and reset, I assigned all conditions however it doesnt count how ı want. It is very weird . How can I fix it? Thanks in advance.

答:
Your process(temp, reset) cannot work, because you made it combinatoric, which is not what you need in this instance. Works fine in simulation, doesn't work at all in hardware.

What you wrote generates a loop in hardware: The state of countOf is dependent on the state of temp and the state of countOf itself. Since your process contains no clock, the state of countOf changes as fast as gate delay allows it(if this code will be synthesized correctly at all).

If your software is any good, it'll give you a warning like this:

```<code>[Synth 8-614] signal 'countOf' is read in the process but is not in the sensitivity list
</code>```

which you should never ignore, because in 99% of the cases, that means you'll get undesired behaviour and/or simulation mismatches.

What you need to do is make temp your clock. It is generated by a clock divider, so logically you almost certainly want it to be a clock as well. If you replace if (temp = '1') then with if rising_edge(temp) then, your code will work as desired.

Side note: Please remove use IEEE.STD_LOGIC_ARITH.ALL; and use IEEE.STD_LOGIC_UNSIGNED.ALL;. Not only do you not need any unsigned library for your code at all, but IEEE.STD_LOGIC_ARITH is deprecated and should no longer be used. It has been for years. Use IEEE.NUMERIC_STD instead.

Title: Dont count respectively vhdl

Body:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity A is
  Port (
        clk : in STD_LOGIC;
        reset: in std_logic; -- reset input
        counter: out std_logic_vector(3 downto 0) := "0000"-- output 4-bit counter
);
end A;

architecture Behavioral of A is
 signal counter_up: std_logic_vector(3 downto 0) := "0000";
 signal countOf : integer := -1;
 signal count : integer := 0;
 signal temp : std_logic := '0';
begin
-- up counter

      process(clk)
     begin
if(clk'event and clk='1') then
count <=count+1;
if(count = 50000000) then
temp <= not temp;
count <=1;
end if;
end if;
end process;

process(temp,reset)
begin
if(reset = '1') then
    countOf <= 0;
 else
        if(temp = '1') then

             if( countOf < 4) then countOf <= countOf + 1;
             else countOf <= 0; end if;

            if(countOf = 0) then counter_up <= "0000"; end if;
            if(countOf = 1) then counter_up <= "0001"; end if;
            if(countOf = 2) then counter_up <= "0010"; end if;
            if(countOf = 3) then counter_up <= "0100"; end if;
            if(countOf = 4) then counter_up <= "1000"; end if;

        end if;

 end if;
end process;

counter <= counter_up;

end Behavioral;

Hi I want to make a counter from 0 up to 4. As you see I divide my clock to 1 HZ and in the process of temp and reset, I assigned all conditions however it doesnt count how ı want. It is very weird . How can I fix it? Thanks in advance.

Body:
Your process(temp, reset) cannot work, because you made it combinatoric, which is not what you need in this instance. Works fine in simulation, doesn't work at all in hardware.

What you wrote generates a loop in hardware: The state of countOf is dependent on the state of temp and the state of countOf itself. Since your process contains no clock, the state of countOf changes as fast as gate delay allows it(if this code will be synthesized correctly at all).

If your software is any good, it'll give you a warning like this:

[Synth 8-614] signal 'countOf' is read in the process but is not in the sensitivity list

which you should never ignore, because in 99% of the cases, that means you'll get undesired behaviour and/or simulation mismatches.

What you need to do is make temp your clock. It is generated by a clock divider, so logically you almost certainly want it to be a clock as well. If you replace if (temp = '1') then with if rising_edge(temp) then, your code will work as desired.

Side note: Please remove use IEEE.STD_LOGIC_ARITH.ALL; and use IEEE.STD_LOGIC_UNSIGNED.ALL;. Not only do you not need any unsigned library for your code at all, but IEEE.STD_LOGIC_ARITH is deprecated and should no longer be used. It has been for years. Use IEEE.NUMERIC_STD instead.


问:
Using PHP Object values in AJAX
I am working on a pet-project. I have a php class. in the HTML, I make instances of that object. So the same page can contain many instances. now, I have to make ajax calls. the ajax call is based on the instances of the object. the data sent in ajax calls is can contain names of database tables and such. I was wondering how safe that is. any thoughts?</p>

答:
Well, consider this case:

a) You have a Javascript function that does an AJAX call to perform a query on your server, and it's something like:

```<code>function doQuery(tablename, fieldname, whereclause) { ... }
</code>```

b) On the server, you dynamically build a query using the passed over parameters of that AJAX call:

```<code>$query = "SELECT $fieldname FROM $tablename WHERE $whereclause";
</code>```

What's to stop a malicious user from injection a call to your AJAX function with

```<code>fieldname = '*'
tablename = 'mysql.user'
whereclause = '1=1'
</code>```

You end up with

```<code>SELECT * from mysql.user WHERE 1=1
</code>```

and your entire MySQL username/password collection goes happily out the door.

Never ever EVER allow user-supplied data control what your code does, especially when it comes to interfacing with "outside" systems such as a database.

Title: Using PHP Object values in AJAX

Body:
Well, consider this case:

a) You have a Javascript function that does an AJAX call to perform a query on your server, and it's something like:

function doQuery(tablename, fieldname, whereclause) { ... }

b) On the server, you dynamically build a query using the passed over parameters of that AJAX call:

$query = "SELECT $fieldname FROM $tablename WHERE $whereclause";

What's to stop a malicious user from injection a call to your AJAX function with

fieldname = '*'
tablename = 'mysql.user'
whereclause = '1=1'

You end up with

SELECT * from mysql.user WHERE 1=1

and your entire MySQL username/password collection goes happily out the door.

Never ever EVER allow user-supplied data control what your code does, especially when it comes to interfacing with "outside" systems such as a database.


问:
Make an object from a string in node js
I am sending the string from AngularJS to NodeJS in following form.

```<code>"{↵obj:{↵one:string,↵two:integer↵}↵}"//request object from browser console
</code>```

I want to convert this string in object and use its properties.for this the server side code is following:

```<code>var data=req.body.data.replace(/"/g,"");
var str=data.replace(/\n/g," ");
//res.json(str) // returning "{ obj:{ one:string, two:integer } }"
try {
var obj=JSON.parse(JSON.stringify(str)).replace(/"/g,"");
res.json(obj);//returning same "{ obj:{ one:string, two:integer } }"
} catch (error) {
console.log(error);
}
</code>```

I want to get ['users'] by  Object.keys[obj] or by any other method want to access the properties of this object.but failed to achieve this.

Many solutions like This couldn't be helpful.any suggestion here??

答:
For example my raw data is like this :

```<code>var raw_data =
    {
        "ok": true,
        "user": {
            "id": "U89MZ4PV2",
            "team_id": "T895HCY8H",
            "name": "hyosoka187",
        }
    }
</code>```

then just use JSON.parse(raw_data, true);. So

```<code>var real_data = JSON.parse(raw_data, true);
console.log(real_data.user.name);
</code>```

Result :

```<code>hyosoka187
</code>```

NOTE :
Output of JSON.parse(raw_data, true) :

```<code>{
    ok: true,
    user: {
        id: 'U89MZ4PV2',
        team_id: 'T895HCY8H',
        name: 'hyosoka187',
    }
}
</code>```

Title: Make an object from a string in node js

Body:
I am sending the string from AngularJS to NodeJS in following form.

"{↵obj:{↵one:string,↵two:integer↵}↵}"//request object from browser console

I want to convert this string in object and use its properties.for this the server side code is following:

var data=req.body.data.replace(/"/g,"");
var str=data.replace(/\n/g," ");
//res.json(str) // returning "{ obj:{ one:string, two:integer } }"
try {
var obj=JSON.parse(JSON.stringify(str)).replace(/"/g,"");
res.json(obj);//returning same "{ obj:{ one:string, two:integer } }"
} catch (error) {
console.log(error);
}

I want to get ['users'] by  Object.keys[obj] or by any other method want to access the properties of this object.but failed to achieve this.

Many solutions like This couldn't be helpful.any suggestion here??

Body:
For example my raw data is like this :

var raw_data =
    {
        "ok": true,
        "user": {
            "id": "U89MZ4PV2",
            "team_id": "T895HCY8H",
            "name": "hyosoka187",
        }
    }

then just use JSON.parse(raw_data, true);. So

var real_data = JSON.parse(raw_data, true);
console.log(real_data.user.name);

Result :

hyosoka187

NOTE :
Output of JSON.parse(raw_data, true) :

{
    ok: true,
    user: {
        id: 'U89MZ4PV2',
        team_id: 'T895HCY8H',
        name: 'hyosoka187',
    }
}


问:
How to access the data in a Dropdown list which is inside a repeater when button is clicked
I have a dropdown list inside a repeater which has data in its list item I need to access the selected data when the button inside the repeater is clicked. my html code is as follows</p>

```<code><asp:Repeater runat="server" ID="rptrData"  OnItemCommand="rptrData_ItemCommand">
    <ItemTemplate>
        <tr role="row" class="odd">
            <td>
                <asp:DropDownList ID="ddlProgress" runat="server">
                    <asp:ListItem Value="0">No Basement</asp:ListItem>
                    <asp:ListItem Value="1">Basement</asp:ListItem>
                    <asp:ListItem Value="2">Lintel</asp:ListItem>
                    <asp:ListItem Value="3">Roof</asp:ListItem>
                </asp:DropDownList></td>
            <td>
                <div class="btn-group btn-group-xs">
                    <asp:Button ID="Update" runat="server" Text="Update" UseSubmitBehavior="False" CommandName="Update" />
                </div>
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>
</code>```

答:
You can use FindControl on the RepeaterCommandEventArgs Item since the Repeater is the sender.

```<code>protected void rptrData_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    //use findcontrol to locate the DDL and cast it
    DropDownList drp = e.Item.FindControl("ddlProgress") as DropDownList;

    //show result
    Label1.Text = drp.SelectedValue;
}
</code>```

Note that all your values in ddlProgress are 0, that can cause problems. Make those unique.

Body:
I have a dropdown list inside a repeater which has data in its list item I need to access the selected data when the button inside the repeater is clicked. my html code is as follows

<asp:Repeater runat="server" ID="rptrData"  OnItemCommand="rptrData_ItemCommand">
    <ItemTemplate>

                <asp:DropDownList ID="ddlProgress" runat="server">
                    <asp:ListItem Value="0">No Basement</asp:ListItem>
                    <asp:ListItem Value="1">Basement</asp:ListItem>
                    <asp:ListItem Value="2">Lintel</asp:ListItem>
                    <asp:ListItem Value="3">Roof</asp:ListItem>
                </asp:DropDownList>

                    <asp:Button ID="Update" runat="server" Text="Update" UseSubmitBehavior="False" CommandName="Update" />

    </ItemTemplate>
</asp:Repeater>

Body:
You can use FindControl on the RepeaterCommandEventArgs Item since the Repeater is the sender.

protected void rptrData_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    //use findcontrol to locate the DDL and cast it
    DropDownList drp = e.Item.FindControl("ddlProgress") as DropDownList;

    //show result
    Label1.Text = drp.SelectedValue;
}

Note that all your values in ddlProgress are 0, that can cause problems. Make those unique.


问:
Firestore update is crashing app
```<code>let dataRef = database.collection("stores").document(store.id).collection("data").document("storeData")

var storeData: [String:Any] = [:]
storeData["seq"] = store.seq + 1
storeData["shiftSeq"] = store.shiftSeq + 1
dataRef.updateData(storeData)
</code>```

I am receiving the following error when executing the above code. It was working fine until I upgraded to the latest version of Firebase/Firestore

* Assertion failure in -[FSTWriteStream startWithDelegate:], third_party/firebase/ios/Source/Firestore/Source/Remote/FSTStream.m:244
2017-12-08 10:48:47.819586-0500 centroOne[1833:473631] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Delegate must be nil'

答: I've faced this problem in swift recently and solved my problem by checking if documentId exists. In above case, please check store.id exits in your Firestore db and then run update method.</p>

Title: Firestore update is crashing app

Body:
let dataRef = database.collection("stores").document(store.id).collection("data").document("storeData")

var storeData: [String:Any] = [:]
storeData["seq"] = store.seq + 1
storeData["shiftSeq"] = store.shiftSeq + 1
dataRef.updateData(storeData)

I am receiving the following error when executing the above code. It was working fine until I upgraded to the latest version of Firebase/Firestore

* Assertion failure in -[FSTWriteStream startWithDelegate:], third_party/firebase/ios/Source/Firestore/Source/Remote/FSTStream.m:244
2017-12-08 10:48:47.819586-0500 centroOne[1833:473631] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Delegate must be nil'


问:
I can edit the content before printing?
The first chrome plugin to work. I do not have detailed information.

Before I print the contents of This link I want to get the specific part.

```<code><table class="receiptSectionTable2Col" >
</code>```

just how can I print the contents of this table. Is this possible?

答:
I think this answer from this question will help you:

```<code>HTMLElement.prototype.printMe = printMe;
function printMe(query){
  var myframe = document.createElement('IFRAME');
  myframe.domain = document.domain;
  myframe.style.position = "absolute";
  myframe.style.top = "-10000px";
  document.body.appendChild(myframe);
  myframe.contentDocument.write(this.innerHTML) ;
  setTimeout(function(){
  myframe.focus();
  myframe.contentWindow.print();
  myframe.parentNode.removeChild(myframe) ;// remove frame
  },3000); // wait for images to load inside iframe
  window.focus();
 }
</code>```

Usage in your case:

```<code>document.getElementsByClassName("receiptSectionTable2Col")[0].printMe();
</code>```

Title: I can edit the content before printing?

Body:
The first chrome plugin to work. I do not have detailed information.

Before I print the contents of This link I want to get the specific part.

just how can I print the contents of this table. Is this possible?

Body:
I think this answer from this question will help you:

HTMLElement.prototype.printMe = printMe;
function printMe(query){
  var myframe = document.createElement('IFRAME');
  myframe.domain = document.domain;
  myframe.style.position = "absolute";
  myframe.style.top = "-10000px";
  document.body.appendChild(myframe);
  myframe.contentDocument.write(this.innerHTML) ;
  setTimeout(function(){
  myframe.focus();
  myframe.contentWindow.print();
  myframe.parentNode.removeChild(myframe) ;// remove frame
  },3000); // wait for images to load inside iframe
  window.focus();
 }

Usage in your case:

document.getElementsByClassName("receiptSectionTable2Col")[0].printMe();


问:
Column name or number of supplied values does not match table definition - .NET MVC
I am currently working on a final year project in .net MVC.
When i open Location_new (Action in LocationController) and click on submit then it shows error

"

Column name or number of supplied values does not match table
  definition.

"

Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Column name or
  number of supplied values does not match table definition.

Source Error:

Line 22:  Line 23:             conn.Open(); Line 24:             int
  count = command.ExecuteNonQuery(); Line 25:             conn.Close();
  Line 26:

Source File: C:\Users\Dev D\Documents\Visual Studio
  2015\Projects\MySafar\MySafar\Models\DBUtility.cs    Line: 24

Location.cs (Model class for query)

```<code>public class Location
    {
        public int LocationID;
        public string LocationName;
        public string PhotoPath;
        public string Details;
        public string CityID;

        public int Insert()
        {
            string query = "Insert Location VALUES(@LocationName, @PhotoPath, @Details, @CityID)";
            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("@LocationName", this.LocationName));
            parameters.Add(new SqlParameter("@PhotoPath", this.PhotoPath));
            parameters.Add(new SqlParameter("@Details", this.Details));
            parameters.Add(new SqlParameter("@CityID", this.CityID));

            return DBUtility.ModifyData(query, parameters);
        }
</code>```

DBUtility.cs (Model class for database)

```<code>public class DBUtility
    {
        public static int ModifyData(String query, List<SqlParameter> parameter)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Dev D\\Documents\\Visual Studio 2015\\Projects\\MySafar\\MySafar\\App_Data\\MySafarDB.mdf\";Integrated Security=True";

            SqlCommand command = new SqlCommand();
            command.Connection = conn;

            command.CommandText = query;
            command.Parameters.AddRange(parameter.ToArray());

            conn.Open();
            int count = command.ExecuteNonQuery();
            conn.Close();

            return count;
        }
</code>```

AdminController

```<code>public ActionResult Location_New()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Location_New_Submit()
        {
            Location l = new Location();
            l.LocationName = Request.Form["LocationName"];
            l.PhotoPath = Request.Form["PhotoPath"];
            l.Details = Request.Form["PhotoPath"];
            //l.CityID = Convert.ToInt32(Request.Form["CityID"]);
            l.CityID = Request.Form["CityID"];

            l.Insert();

            return RedirectToAction("Location_List");
        }

[HttpPost]
        public ActionResult Location_List()
        {
          return View();
        }
</code>```

答:
Specify your columns in your statements, this error occurs when you have an identity field that you wouldn't specify a value for.

Instead of

```<code>string query = "Insert Location VALUES(@LocationName, @PhotoPath, @Details, @CityID)";
</code>```

Use

```<code>string query = "Insert INTO Location(LocationName, PhotoPath, Details, CityID) VALUES(@LocationName, @PhotoPath, @Details, @CityID)";
</code>```

Just make sure to change them to your actual column names, I assumed the names off of the parameters names for my example.

Body:
I am currently working on a final year project in .net MVC.
When i open Location_new (Action in LocationController) and click on submit then it shows error

"

Column name or number of supplied values does not match table
  definition.

"

Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Column name or
  number of supplied values does not match table definition.

Source Error:

Line 22:  Line 23:             conn.Open(); Line 24:             int
  count = command.ExecuteNonQuery(); Line 25:             conn.Close();
  Line 26:

Source File: C:\Users\Dev D\Documents\Visual Studio
  2015\Projects\MySafar\MySafar\Models\DBUtility.cs    Line: 24

Location.cs (Model class for query)

public class Location
    {
        public int LocationID;
        public string LocationName;
        public string PhotoPath;
        public string Details;
        public string CityID;

        public int Insert()
        {
            string query = "Insert Location VALUES(@LocationName, @PhotoPath, @Details, @CityID)";
            List<SqlParameter> parameters = new List<SqlParameter>();
            parameters.Add(new SqlParameter("@LocationName", this.LocationName));
            parameters.Add(new SqlParameter("@PhotoPath", this.PhotoPath));
            parameters.Add(new SqlParameter("@Details", this.Details));
            parameters.Add(new SqlParameter("@CityID", this.CityID));

            return DBUtility.ModifyData(query, parameters);
        }

DBUtility.cs (Model class for database)

public class DBUtility
    {
        public static int ModifyData(String query, List<SqlParameter> parameter)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Dev D\\Documents\\Visual Studio 2015\\Projects\\MySafar\\MySafar\\App_Data\\MySafarDB.mdf\";Integrated Security=True";

            SqlCommand command = new SqlCommand();
            command.Connection = conn;

            command.CommandText = query;
            command.Parameters.AddRange(parameter.ToArray());

            conn.Open();
            int count = command.ExecuteNonQuery();
            conn.Close();

            return count;
        }

AdminController

public ActionResult Location_New()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Location_New_Submit()
        {
            Location l = new Location();
            l.LocationName = Request.Form["LocationName"];
            l.PhotoPath = Request.Form["PhotoPath"];
            l.Details = Request.Form["PhotoPath"];
            //l.CityID = Convert.ToInt32(Request.Form["CityID"]);
            l.CityID = Request.Form["CityID"];

            l.Insert();

            return RedirectToAction("Location_List");
        }

[HttpPost]
        public ActionResult Location_List()
        {
          return View();
        }

Body:
Specify your columns in your statements, this error occurs when you have an identity field that you wouldn't specify a value for.

Instead of

string query = "Insert Location VALUES(@LocationName, @PhotoPath, @Details, @CityID)";

Use

string query = "Insert INTO Location(LocationName, PhotoPath, Details, CityID) VALUES(@LocationName, @PhotoPath, @Details, @CityID)";

Just make sure to change them to your actual column names, I assumed the names off of the parameters names for my example.


问:
Android: Can an Android app have multiple FirebaseMessagingServices
I am building a library project in which I have a FirebaseMessagingService.
I also have a FirebaseMesagingService in my app. What I see is, whenever an FCM is sent from the server, only one FirebaseMessagingService processes it. This was not the case when I was using GCM Receivers. Both the GCM Receivers used to receive the message and based on message content, they would/would not do anything about it.

How can I achieve the same in FCM.

答:
Your library's manifest should not have a FirebaseMessagingService subclass. Adding the messa service to the app's manifest should be a part of the integration step, integrating the SDK. Also you should provide a hook in the SDK from where the app can pass the FCM message payload to the SDK.

Essentially if the app does not have its own FirebaseMessagingService subclass it would add your SDK's listener service in the manifest else it will add the hook in its own listener service which passes the payload to your SDK and SDK takes the required action


问:
How to print just the top 10 words and their frequency from a HashMap?
I have a problem with my code.
I am reading in a file with some text, and then counting the words and their frequency. I am then trying to print out the top 10 most frequently used words in the text.

However, with the approaches that I have tried (putting for loops set to stop after 10 iterations for example), I get the words printed back in the same fashion just 10 times. Otherwise, I am able to print ALL the words in the file with their frequency.I would just require the top-10 most frequently used ones only.

```<code>ArrayList<Integer> values = new ArrayList<>();
    values.addAll(wordcount.values());
    Collections.sort(values, Collections.reverseOrder());
    int last_i = -1;
    for(Integer i: values) {
        if (last_i == i)
            continue;
        last_i = i;
        System.out.println("The top 10 words are: ");
       // for (int count = 0; count < 10; count++) {
            for (String s : wordcount.keySet())
                if (wordcount.get(s) == i)
                    System.out.println(s + " : " + i);
           }
       }
}
</code>```

Please find above the "problematic" code. I am using a

```<code>BufferedReader
</code>```

to read in the text File and then removing all punctuation and stuff that may cause the same word to appear as two different entries in my HashMap.

Any help in greatly appreciated. Thanks!

答:
Here is a Java 8 example with lambdas:

```<code>        Map<String, Integer> wordcount = new HashMap<>();
        wordcount.put("two", 20);
        wordcount.put("five", 50);
        wordcount.put("three", 30);
        wordcount.put("four", 40);
        wordcount.put("one", 10);
        wordcount.put("six", 60);
        wordcount.put("eight", 80);
        wordcount.put("twelve", 1);
        wordcount.put("nine", 90);
        wordcount.put("ten", 100);
        wordcount.put("seven", 70);
        wordcount.put("eleven", 1);
        wordcount.put("15", 1);
        wordcount.put("13", 2);
        wordcount.put("16", 4);
        wordcount.put("14", 3);
        wordcount.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
                .limit(10)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                )).forEach((s, integer) -> System.out.println(String.format("%s : %s", s, integer)));
</code>```

Should print something like:

```<code>ten : 100
nine : 90
eight : 80
seven : 70
six : 60
five : 50
four : 40
three : 30
two : 20
one : 10
</code>```

Body:
I have a problem with my code.
I am reading in a file with some text, and then counting the words and their frequency. I am then trying to print out the top 10 most frequently used words in the text.

However, with the approaches that I have tried (putting for loops set to stop after 10 iterations for example), I get the words printed back in the same fashion just 10 times. Otherwise, I am able to print ALL the words in the file with their frequency.I would just require the top-10 most frequently used ones only.

ArrayList<Integer> values = new ArrayList<>();
    values.addAll(wordcount.values());
    Collections.sort(values, Collections.reverseOrder());
    int last_i = -1;
    for(Integer i: values) {
        if (last_i == i)
            continue;
        last_i = i;
        System.out.println("The top 10 words are: ");
       // for (int count = 0; count < 10; count++) {
            for (String s : wordcount.keySet())
                if (wordcount.get(s) == i)
                    System.out.println(s + " : " + i);
           }
       }
}

Please find above the "problematic" code. I am using a

BufferedReader

to read in the text File and then removing all punctuation and stuff that may cause the same word to appear as two different entries in my HashMap.

Any help in greatly appreciated. Thanks!

Body:
Here is a Java 8 example with lambdas:

        Map<String, Integer> wordcount = new HashMap<>();
        wordcount.put("two", 20);
        wordcount.put("five", 50);
        wordcount.put("three", 30);
        wordcount.put("four", 40);
        wordcount.put("one", 10);
        wordcount.put("six", 60);
        wordcount.put("eight", 80);
        wordcount.put("twelve", 1);
        wordcount.put("nine", 90);
        wordcount.put("ten", 100);
        wordcount.put("seven", 70);
        wordcount.put("eleven", 1);
        wordcount.put("15", 1);
        wordcount.put("13", 2);
        wordcount.put("16", 4);
        wordcount.put("14", 3);
        wordcount.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
                .limit(10)
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                )).forEach((s, integer) -> System.out.println(String.format("%s : %s", s, integer)));

Should print something like:

ten : 100
nine : 90
eight : 80
seven : 70
six : 60
five : 50
four : 40
three : 30
two : 20
one : 10


问:
Jquery Jtable load Json from ajax call
I am using jtable.org-s library for showing rows in a table. For populating rows I used listAction like this:

```<code>actions: {
  listAction: '/Passengers/Search'
},
</code>```

This URL returned valid json and everything worked fine. But I want to call the URL manually from ajax, because this URL returns more info than rows. It also returns info I need for other form elements, such as search result items count, woman/man ratio and etc.

So, I want to ajax call, and load the response to my jtable:

```<code>$.ajax({
  url: '/Passengers/Search',
  type: 'POST',
  data: {},
  success: function(data) {
    // here I would like to inject the Json(data) to my table
  }
});
</code>```

答:
You can use FunctionsAsActions feature of jquery-jtable.
 In ajax success filter you can filter your response data and by using $dfd.resolve(data); you can load filtered data to jquery-jtable.

For example:

```<code>listAction: function (postData, jtParams) {
                    console.log("Loading from custom function...");
                    return $.Deferred(function ($dfd) {
                        $.ajax({
                            url: '/Demo/StudentList?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
                            type: 'POST',
                            dataType: 'json',
                            data: postData,
                            success: function (data) {
                                //filter your data here and then pass filtered data to $dfd.resolve function

                                $dfd.resolve(data);
                            },
                            error: function () {
                                $dfd.reject();
                            }
                        });
                    });
                },
</code>```

Title: Jquery Jtable load Json from ajax call

Body:
I am using jtable.org-s library for showing rows in a table. For populating rows I used listAction like this:

actions: {
  listAction: '/Passengers/Search'
},

This URL returned valid json and everything worked fine. But I want to call the URL manually from ajax, because this URL returns more info than rows. It also returns info I need for other form elements, such as search result items count, woman/man ratio and etc.

So, I want to ajax call, and load the response to my jtable:

$.ajax({
  url: '/Passengers/Search',
  type: 'POST',
  data: {},
  success: function(data) {
    // here I would like to inject the Json(data) to my table
  }
});

Body:
You can use FunctionsAsActions feature of jquery-jtable.
 In ajax success filter you can filter your response data and by using $dfd.resolve(data); you can load filtered data to jquery-jtable.

For example:

listAction: function (postData, jtParams) {
                    console.log("Loading from custom function...");
                    return $.Deferred(function ($dfd) {
                        $.ajax({
                            url: '/Demo/StudentList?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
                            type: 'POST',
                            dataType: 'json',
                            data: postData,
                            success: function (data) {
                                //filter your data here and then pass filtered data to $dfd.resolve function

                                $dfd.resolve(data);
                            },
                            error: function () {
                                $dfd.reject();
                            }
                        });
                    });
                },