问:
How to filter nonaggregated query results by an aggregated column?
I'm creating a price comparison service. Products from one Site are compared to products from one or more Sites. Products are matched from one Site to another using a ProductMatch table:

Given the following query to extract products, together with their matches:

SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id

WHERE p1.site_id = 1;
```

<p><strong>How can I filter products whose price (<code>p1.price</code>) is lower than the minimum competitor price (<code>MIN(p2.price)</code>)?</strong></p>

<p>Using subqueries, here's how I would do it:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id

WHERE p1.id IN (
    SELECT x.id FROM (
        SELECT _p1.id, _p1.price
        FROM Product _p1
        JOIN ProductMatch _m ON _m.fromProduct_id = _p1.id
        JOIN Product _p2 ON _m.toProduct_id = _p2.id
        WHERE _p1.site_id = 1
        GROUP BY _p1.id
        HAVING _p1.price < MIN(_p2.price)
    ) x
);
</code>```

Is it possible to simplify this query to not use subqueries?

My concerns:

it feels weird to repeat the exact same joins in the subquery

I have concerns about the performance of subqueries on larger data sets

subqueries don't play very well with my ORM

答:
With MIN() window function inside a CTE which will be filtered:

```<code>WITH cte AS (
  SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time,
    MIN(p2.price) OVER (PARTITION BY p1.id) AS min_price
  FROM Product p1
  LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
  LEFT JOIN Product p2 ON m.toProduct_id = p2.id
  WHERE p1.site_id = 1
)
SELECT
  p1_id, p1_name, p1_price,
  p2_id, p2_name, p2_price,
  time
FROM cte
WHERE p1_price < min_price
</code>```

Body:
I'm creating a price comparison service. Products from one Site are compared to products from one or more Sites. Products are matched from one Site to another using a ProductMatch table:

Given the following query to extract products, together with their matches:

SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id

WHERE p1.site_id = 1;

How can I filter products whose price (p1.price) is lower than the minimum competitor price (MIN(p2.price))?

Using subqueries, here's how I would do it:

SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time
FROM Product p1
LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
LEFT JOIN Product p2 ON m.toProduct_id = p2.id

WHERE p1.id IN (
    SELECT x.id FROM (
        SELECT _p1.id, _p1.price
        FROM Product _p1
        JOIN ProductMatch _m ON _m.fromProduct_id = _p1.id
        JOIN Product _p2 ON _m.toProduct_id = _p2.id
        WHERE _p1.site_id = 1
        GROUP BY _p1.id
        HAVING _p1.price < MIN(_p2.price)
    ) x
);

Is it possible to simplify this query to not use subqueries?

My concerns:

it feels weird to repeat the exact same joins in the subquery

I have concerns about the performance of subqueries on larger data sets

subqueries don't play very well with my ORM

Body:
With MIN() window function inside a CTE which will be filtered:

WITH cte AS (
  SELECT
    p1.id AS p1_id, p1.name AS p1_name, p1.price AS p1_price,
    p2.id AS p2_id, p2.name AS p2_name, p2.price AS p2_price,
    m.time,
    MIN(p2.price) OVER (PARTITION BY p1.id) AS min_price
  FROM Product p1
  LEFT JOIN ProductMatch m ON m.fromProduct_id = p1.id
  LEFT JOIN Product p2 ON m.toProduct_id = p2.id
  WHERE p1.site_id = 1
)
SELECT
  p1_id, p1_name, p1_price,
  p2_id, p2_name, p2_price,
  time
FROM cte
WHERE p1_price < min_price


来源: stackexchange

问:
Pyspark + Redis Remote Server
I have a server with redis and maven configured
I then do the following sparkSession

```<code>spark = pyspark
.sql
.SparkSession
.builder
.master('local[4]')
.appName('try_one_core')
.config("spark.redis.host", "XX.XXX.XXX.XXX")
.config("spark.redis.port", "6379")
.config("spark.redis.auth", "XXXX")
.getOrCreate()
</code>```

I am trying to connect to a remote redis server and write/load data from it, however when I try to .save() with the following command

```<code>df
.write
.format("org.apache.spark.sql.redis")
.option("table", "df")
.option("key.column", "case_id")
.save()
</code>```

I get the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling
  o327.save. : java.lang.ClassNotFoundException: Failed to find data
  source: org.apache.spark.sql.redis. Please find packages at
  http://spark.apache.org/third-party-projects.html

Is there any fix to this?

答:
As addition to @fe2s answer , instead of loading it from disk or network storage it can be also loaded directly from maven

```<code>bin/pyspark --packages com.redislabs:spark-redis:2.4.0
</code>```

the --packages and --jars  arguments can also be used with normal spark-submit command

ContentLicense: CC BY-SA 4.0

Title: Pyspark + Redis Remote Server

Body:
I have a server with redis and maven configured
I then do the following sparkSession

spark = pyspark
.sql
.SparkSession
.builder
.master('local[4]')
.appName('try_one_core')
.config("spark.redis.host", "XX.XXX.XXX.XXX")
.config("spark.redis.port", "6379")
.config("spark.redis.auth", "XXXX")
.getOrCreate()

I am trying to connect to a remote redis server and write/load data from it, however when I try to .save() with the following command

df
.write
.format("org.apache.spark.sql.redis")
.option("table", "df")
.option("key.column", "case_id")
.save()

I get the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling
  o327.save. : java.lang.ClassNotFoundException: Failed to find data
  source: org.apache.spark.sql.redis. Please find packages at
  http://spark.apache.org/third-party-projects.html

Is there any fix to this?

Body:
As addition to @fe2s answer , instead of loading it from disk or network storage it can be also loaded directly from maven

bin/pyspark --packages com.redislabs:spark-redis:2.4.0

the --packages and --jars  arguments can also be used with normal spark-submit command


问:
Convert date/time format from Etc/GMT to ISO
I need to convert date/time values.

For example I want to convert this "2019-11-21 09:53:10 Etc/GMT" to a value with the same format as this "2020-02-13T15:24:47.977Z".

If you can provide the resulting equivalent value of the given example, I can make that as reference so I can already find the correct code for the conversion.

Or else if you can provide the exact javascript code for the conversion, that is better. I am using 'moment' and 'moment-timezone'.

答:
Try this out

```<code> var d = new Date();
 var n = d.toUTCString();
</code>```

You can have a refernce here https://www.geeksforgeeks.org/how-to-convert-a-javascript-date-to-utc/

Body:
Try this out

 var d = new Date();
 var n = d.toUTCString();

You can have a refernce here https://www.geeksforgeeks.org/how-to-convert-a-javascript-date-to-utc/


问:
XDocument: How to find an attribute value in nested xml
Given the working code snippet below, I'm trying to get the target element inside RootChild2.

https://dotnetfiddle.net/eN4xV9

```<code>string str =
    @"<?xml version=""1.0""?>
    <!-- comment at the root level -->
    <Root>
        <RootChild1>
            <Child>Content</Child>
            <Child>Content</Child>
            <Child>Content</Child>
        </RootChild1>
        <RootChild2>
            <Child>Content</Child>
            <Child key='target'>Content</Child>
            <Child>Content</Child>
        </RootChild2>
    </Root>";
XDocument doc = XDocument.Parse(str);

foreach (XElement element in doc.Descendants("RootChild2"))
{
    if (element.HasAttributes && element.Element("Child").Attribute("key").Value == "target")
        Console.WriteLine("found it");
    else
        Console.WriteLine("not found");
}
</code>```

答:
There are three problems here:

You're checking if the RootChild2 element has any attributes - and it doesn't

You're only checking the first Child element under each RootChild2 element

You're assuming the attribute is present (by dereferencing the XAttribute)

Here's code which will find all the target elements within a RootChild2:

foreach (XElement element in doc.Descendants("RootChild2"))
{
    var targets = element
        .Elements("Child")
        .Where(child => (string) child.Attribute("key") == "target")
        .ToList();
    Console.WriteLine($"Found {targets.Count} targets");
    foreach (var target in targets)
    {
        Console.WriteLine($"Target content: {target.Value}");
    }
}
```

Note that the cast of XAttribute to string is a simple way of avoiding null reference issues - because the result of the explicit conversion is null when the source is null. (That's a general pattern in LINQ to XML.)

Body:
Given the working code snippet below, I'm trying to get the target element inside RootChild2.

https://dotnetfiddle.net/eN4xV9

string str =
    @"<?xml version=""1.0""?>

    <Root>
        <RootChild1>
            <Child>Content</Child>
            <Child>Content</Child>
            <Child>Content</Child>
        </RootChild1>
        <RootChild2>
            <Child>Content</Child>
            <Child key='target'>Content</Child>
            <Child>Content</Child>
        </RootChild2>
    </Root>";
XDocument doc = XDocument.Parse(str);

foreach (XElement element in doc.Descendants("RootChild2"))
{
    if (element.HasAttributes && element.Element("Child").Attribute("key").Value == "target")
        Console.WriteLine("found it");
    else
        Console.WriteLine("not found");
}

Body:
There are three problems here:

You're checking if the RootChild2 element has any attributes - and it doesn't

You're only checking the first Child element under each RootChild2 element

You're assuming the attribute is present (by dereferencing the XAttribute)

Here's code which will find all the target elements within a RootChild2:

foreach (XElement element in doc.Descendants("RootChild2"))
{
    var targets = element
        .Elements("Child")
        .Where(child => (string) child.Attribute("key") == "target")
        .ToList();
    Console.WriteLine($"Found {targets.Count} targets");
    foreach (var target in targets)
    {
        Console.WriteLine($"Target content: {target.Value}");
    }
}

Note that the cast of XAttribute to string is a simple way of avoiding null reference issues - because the result of the explicit conversion is null when the source is null. (That's a general pattern in LINQ to XML.)


问:
Material ui update select style globally with theme
I am trying to use the following to update the border color of all of my outlined select, but it doesn't work (apparently the style of the border comes from fieldset element). I have tried MuiOutlinedInput but that applies tom all of the inputs. Is there a way to target just the select outlined variant?

```<code>  overrides: {
    MuiButton: {
      outlined: {
        '&:hover': {
          boxShadow: 'none'
        },
      },
      contained: {
        '&:hover': {
          boxShadow: 'none'
        },
      }
    },
    MuiSelect: {
      root: {
        '& $notchedOutline': {
          borderColor: 'red',
        },
      }
    }
  }
</code>```

答:
The problem with what you tried is that the $notchedOutline element is not a descendant of the .MuiSelect-root element, but rather a sibling. The overall structure of the outlined select is roughly as follows (with less relevant details left out):

```<code><div class="MuiFormControl-root">
   <div class="MuiOutlinedInput-root">
      <div class="MuiSelect-root MuiSelect-outlined MuiOutlinedInput-input">Displayed Text</div>
      <input type="hidden" value="Displayed Text">
      <fieldset class="MuiOutlinedInput-notchedOutline"><legend>less relevant details</legend></fieldset>
   </div>
</div>
</code>```

Below is an example that customizes both outlined input and outlined select using different colors.

```<code>import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import MenuItem from "@material-ui/core/MenuItem";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
const theme = createMuiTheme({
  overrides: {
    MuiOutlinedInput: {
      root: {
        "& $notchedOutline": {
          borderColor: "pink"
        },
        "&$focused $notchedOutline": {
          borderColor: "red"
        },
        color: "blue",

        "& .MuiSelect-root ~ $notchedOutline": {
          borderColor: "green"
        },
        "&$focused .MuiSelect-root ~ $notchedOutline": {
          borderColor: "orange"
        },
        "& .MuiSelect-root": {
          color: "purple"
        }
      }
    }
  }
});
function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <TextField
        variant="outlined"
        label="Outlined Input"
        defaultValue="My Text"
      />
      <br />
      <br />
      <TextField
        variant="outlined"
        label="Outlined Select"
        select
        value="My Text 1"
      >
        <MenuItem value="My Text 1">My Text 1</MenuItem>
        <MenuItem value="My Text 2">My Text 2</MenuItem>
      </TextField>
    </MuiThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Related answers and documentation:

https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

Global outlined override

Change outline for OutlinedInput with React material-ui

Can't change border color of Material-UI OutlinedInput

Body:
I am trying to use the following to update the border color of all of my outlined select, but it doesn't work (apparently the style of the border comes from fieldset element). I have tried MuiOutlinedInput but that applies tom all of the inputs. Is there a way to target just the select outlined variant?

  overrides: {
    MuiButton: {
      outlined: {
        '&:hover': {
          boxShadow: 'none'
        },
      },
      contained: {
        '&:hover': {
          boxShadow: 'none'
        },
      }
    },
    MuiSelect: {
      root: {
        '& $notchedOutline': {
          borderColor: 'red',
        },
      }
    }
  }

Body:
The problem with what you tried is that the $notchedOutline element is not a descendant of the .MuiSelect-root element, but rather a sibling. The overall structure of the outlined select is roughly as follows (with less relevant details left out):

<div class="MuiFormControl-root">
   <div class="MuiOutlinedInput-root">
      <div class="MuiSelect-root MuiSelect-outlined MuiOutlinedInput-input">Displayed Text</div>
      <input type="hidden" value="Displayed Text">
      <fieldset class="MuiOutlinedInput-notchedOutline"><legend>less relevant details</legend></fieldset>
   </div>
</div>

Below is an example that customizes both outlined input and outlined select using different colors.

import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import MenuItem from "@material-ui/core/MenuItem";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
const theme = createMuiTheme({
  overrides: {
    MuiOutlinedInput: {
      root: {
        "& $notchedOutline": {
          borderColor: "pink"
        },
        "&$focused $notchedOutline": {
          borderColor: "red"
        },
        color: "blue",

        "& .MuiSelect-root ~ $notchedOutline": {
          borderColor: "green"
        },
        "&$focused .MuiSelect-root ~ $notchedOutline": {
          borderColor: "orange"
        },
        "& .MuiSelect-root": {
          color: "purple"
        }
      }
    }
  }
});
function App() {
  return (
    <MuiThemeProvider theme={theme}>
      <TextField
        variant="outlined"
        label="Outlined Input"
        defaultValue="My Text"
      />
      <br />
      <br />
      <TextField
        variant="outlined"
        label="Outlined Select"
        select
        value="My Text 1"
      >
        <MenuItem value="My Text 1">My Text 1</MenuItem>
        <MenuItem value="My Text 2">My Text 2</MenuItem>
      </TextField>
    </MuiThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Related answers and documentation:

https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator

Global outlined override

Change outline for OutlinedInput with React material-ui

Can't change border color of Material-UI OutlinedInput


答:
You are accessing the RootChild2-Element itself through element inside your loop.
Take a look at the following version:

```<code>        foreach (XElement element in doc.Descendants("RootChild2").Nodes())
        {
            if (element.HasAttributes && element.Attribute("key").Value == "target")
                Console.WriteLine("found it");
            else
                Console.WriteLine("not found");
        }
</code>```

Now it loops through all nodes of RootChild2.

Title: XDocument: How to find an attribute value in nested xml

Body:
You are accessing the RootChild2-Element itself through element inside your loop.
Take a look at the following version:

        foreach (XElement element in doc.Descendants("RootChild2").Nodes())
        {
            if (element.HasAttributes && element.Attribute("key").Value == "target")
                Console.WriteLine("found it");
            else
                Console.WriteLine("not found");
        }

Now it loops through all nodes of RootChild2.


答:
You should rewrite your foreach loop at little bit, add accessing of child Elements() collection in RootChild2 and check every element in enumeration. You also can check that key attribute is present in element to prevent a potential null reference exception

foreach (XElement element in doc.Descendants("RootChild2").Elements())
{
    if (element.HasAttributes && element.Attribute("key")?.Value == "target")
        Console.WriteLine("found it");
    else
        Console.WriteLine("not found");
}
```

Descendants(XName) returns only elements with matching names, therefore you are getting only one RootChild2 element as the result in your code

Body:
You should rewrite your foreach loop at little bit, add accessing of child Elements() collection in RootChild2 and check every element in enumeration. You also can check that key attribute is present in element to prevent a potential null reference exception

foreach (XElement element in doc.Descendants("RootChild2").Elements())
{
    if (element.HasAttributes && element.Attribute("key")?.Value == "target")
        Console.WriteLine("found it");
    else
        Console.WriteLine("not found");
}

Descendants(XName) returns only elements with matching names, therefore you are getting only one RootChild2 element as the result in your code


问:
Need some sort of idea to Implementing async storage in React Native app to stay user sign in the app
respective StackOverflow developer community. I am new to react native development about a month ago i start learning and implementing app in react native now i am stuck in async storage thing. Actually i use php web service to login user in my app mysql is database i m using. Now i want to stay user signed in into my app like if user signed in successfully then if user close app the app store his username and password and next time when user open app he's no need to sign in again. app directly show him home screen i read async storage is responsible for this kind of work need help to implement this kind of functionality
I follow this tutorial for login :
https://reactnativecode.com/react-native-user-login-using-php-mysql/

import React, { Component } from 'react';

import { StyleSheet, TextInput, View, Alert, Button, Text , AsyncStorage} from 'react-native';

// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator , createAppContainer } from 'react-navigation';

// Creating Login Activity.
class LoginActivity extends Component {

  // Setting up Login Activity title.
  static navigationOptions =
   {
      title: 'LoginActivity',
   };

constructor(props) {

    super(props)

    this.state = {

      UserEmail: '',
      UserPassword: ''

    }

  }

UserLoginFunction = () =>{
 const { UserEmail }  = this.state ;
 const { UserPassword }  = this.state ;

fetch('http://192.168.0.107/loginrn/User_Login.php', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({

    email: UserEmail,

    password: UserPassword
    //console.log('UserEmail')
  })

}).then((response) => response.json())
      .then((responseJson) => {

        // If server response message same as Data Matched
       if(responseJson === 'Data Matched')
        {

            //Then open Profile activity and send user email to profile activity.
            this.props.navigation.navigate('Second', { Email: UserEmail });

        }
        else{

          Alert.alert(responseJson);
        }

      }).catch((error) => {
        console.error(error);
      });

  }

  render() {
    return (

<View style={styles.MainContainer}>

        <Text style= {styles.TextComponentStyle}>User Login Form</Text>

        <TextInput

          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Email"

          onChangeText={UserEmail => this.setState({UserEmail})}

          // Making the Under line Transparent.
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}
        />

        <TextInput

          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Password"

          onChangeText={UserPassword => this.setState({UserPassword})}

          // Making the Under line Transparent.
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}

          secureTextEntry={true}
        />

        <Button title="Click Here To Login" onPress={this.UserLoginFunction} color="#2196F3" />

</View>

    );
  }
}
// Creating Profile activity.
class ProfileActivity extends Component
{

  // Setting up profile activity title.
   static navigationOptions =
   {
      title: 'ProfileActivity',

   };

   render()
   {

     const {goBack} = this.props.navigation;

      return(
         <View style = { styles.MainContainer }>

            <Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text>

            <Button title="Click here to Logout" onPress={ () => goBack(null) } />

         </View>
      );
   }
}

const AppNavigator= createStackNavigator(
{
   First: { screen: LoginActivity },

   Second: { screen: ProfileActivity }

});
export default createAppContainer(AppNavigator);```

答:
Welcome to Stackoverflow :)...

First of all, if you are new to React Native follow all the needed documentation parts here

Anyway as a beginner your code is ok.. but the thing is in React Native as you know we are implementing classes for each component/screen/function. In your code where you are trying to do all the application features in one single code base in one single file. That's not best practice. Learn React Native with best practices as much as you can. :)

Let's move on to your question now

In your scenario simply you need to add React Native Local Storage - AsyncStorage to maintain user sessions easily. Once the user has been successfully logged in you need to make some constant variable in user's device that we can check once we start the application - That is the simple scenario.

Let's do the coding now

First of all you need to install AsyncStorage which given by @react-native-community

If you are using yarn run this yarn add @react-native-community/async-storage
or if you are using npm run this npm i -s @react-native-community/async-storage

If you are using React Native Version 0.60 or above you don't need to link npm packages manually :)

If you are running on android you can run normal way, but you are run on iOS you need to do pod installation

cd ios && pod install

Now import AsyncStorage using

import AsyncStorage from '@react-native-community/async-storage';

After that, you need to save user email once user has successfully logged in

AsyncStorage.setItem('userEmail', JSON.stringify(UserEmail));

Now you can check the logic - If Local Storage has user email then the user is logged

But here you need to clear Local Storage once the user has tap on log out button using AsyncStorage.clear()

FINAL CODE

```<code>import React, { Component } from "react";

import {
  StyleSheet,
  TextInput,
  View,
  Alert,
  Button,
  Text,
  AsyncStorage
} from "react-native";

// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator, createAppContainer } from "react-navigation";

//Import Async Storage - Local Storage
import AsyncStorage from "@react-native-community/async-storage";

// Creating Login Activity.
class LoginActivity extends Component {
  // Setting up Login Activity title.
  static navigationOptions = {
    title: "LoginActivity"
  };

  constructor(props) {
    super(props);

    this.state = {
      UserEmail: "",
      UserPassword: ""
    };
  }

  //Check If the user is already logged or not
  componentDidMount() {
    //Get User Email From Local Storage
    AsyncStorage.getItem("userEmail").then(data => {
      if (data) {
        //If userEmail has data -> email
        this.props.navigation.navigate("Second", { Email: JSON.parse(data) }); //Navigate to Second Screen
      }
    });
  }

  UserLoginFunction = () => {
    const { UserEmail } = this.state;
    const { UserPassword } = this.state;

    fetch("http://192.168.0.107/loginrn/User_Login.php", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email: UserEmail,

        password: UserPassword
        //console.log('UserEmail')
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        // If server response message same as Data Matched
        if (responseJson === "Data Matched") {
          //Save User Details to Local Storage
          AsyncStorage.setItem("userEmail", JSON.stringify(UserEmail));
          //Then open Profile activity and send user email to profile activity.
          this.props.navigation.navigate("Second", { Email: UserEmail });
        } else {
          Alert.alert(responseJson);
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={styles.TextComponentStyle}>User Login Form</Text>

        <TextInput
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Email"
          onChangeText={UserEmail => this.setState({ UserEmail })}
          // Making the Under line Transparent.
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />

        <TextInput
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Password"
          onChangeText={UserPassword => this.setState({ UserPassword })}
          // Making the Under line Transparent.
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
          secureTextEntry={true}
        />

        <Button
          title="Click Here To Login"
          onPress={this.UserLoginFunction}
          color="#2196F3"
        />
      </View>
    );
  }
}
// Creating Profile activity.
class ProfileActivity extends Component {
  // Setting up profile activity title.
  static navigationOptions = {
    title: "ProfileActivity"
  };

  //logout button click
  logOutAction = () => {
    const { goBack } = this.props.navigation;
    AsyncStorage.clear(); // Clear the Async Storage Before Log out
    goBack(null);
  };

  render() {
    const { goBack } = this.props.navigation;

    return (
      <View style={styles.MainContainer}>
        <Text style={styles.TextComponentStyle}>
          {" "}
          {this.props.navigation.state.params.Email}{" "}
        </Text>

        <Button
          title="Click here to Logout"
          onPress={() => this.logOutAction()}
        />
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  First: { screen: LoginActivity },

  Second: { screen: ProfileActivity }
});
export default createAppContainer(AppNavigator);
</code>```

If you have any doubts feel free to ask :) Happy Coding :)

Body:
Welcome to Stackoverflow :)...

First of all, if you are new to React Native follow all the needed documentation parts here

Anyway as a beginner your code is ok.. but the thing is in React Native as you know we are implementing classes for each component/screen/function. In your code where you are trying to do all the application features in one single code base in one single file. That's not best practice. Learn React Native with best practices as much as you can. :)

Let's move on to your question now

In your scenario simply you need to add React Native Local Storage - AsyncStorage to maintain user sessions easily. Once the user has been successfully logged in you need to make some constant variable in user's device that we can check once we start the application - That is the simple scenario.

Let's do the coding now

First of all you need to install AsyncStorage which given by @react-native-community

If you are using yarn run this yarn add @react-native-community/async-storage
or if you are using npm run this npm i -s @react-native-community/async-storage

If you are using React Native Version 0.60 or above you don't need to link npm packages manually :)

If you are running on android you can run normal way, but you are run on iOS you need to do pod installation

cd ios && pod install

Now import AsyncStorage using

import AsyncStorage from '@react-native-community/async-storage';

After that, you need to save user email once user has successfully logged in

AsyncStorage.setItem('userEmail', JSON.stringify(UserEmail));

Now you can check the logic - If Local Storage has user email then the user is logged

But here you need to clear Local Storage once the user has tap on log out button using AsyncStorage.clear()

FINAL CODE

import React, { Component } from "react";

import {
  StyleSheet,
  TextInput,
  View,
  Alert,
  Button,
  Text,
  AsyncStorage
} from "react-native";

// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator, createAppContainer } from "react-navigation";

//Import Async Storage - Local Storage
import AsyncStorage from "@react-native-community/async-storage";

// Creating Login Activity.
class LoginActivity extends Component {
  // Setting up Login Activity title.
  static navigationOptions = {
    title: "LoginActivity"
  };

  constructor(props) {
    super(props);

    this.state = {
      UserEmail: "",
      UserPassword: ""
    };
  }

  //Check If the user is already logged or not
  componentDidMount() {
    //Get User Email From Local Storage
    AsyncStorage.getItem("userEmail").then(data => {
      if (data) {
        //If userEmail has data -> email
        this.props.navigation.navigate("Second", { Email: JSON.parse(data) }); //Navigate to Second Screen
      }
    });
  }

  UserLoginFunction = () => {
    const { UserEmail } = this.state;
    const { UserPassword } = this.state;

    fetch("http://192.168.0.107/loginrn/User_Login.php", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        email: UserEmail,

        password: UserPassword
        //console.log('UserEmail')
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        // If server response message same as Data Matched
        if (responseJson === "Data Matched") {
          //Save User Details to Local Storage
          AsyncStorage.setItem("userEmail", JSON.stringify(UserEmail));
          //Then open Profile activity and send user email to profile activity.
          this.props.navigation.navigate("Second", { Email: UserEmail });
        } else {
          Alert.alert(responseJson);
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={styles.TextComponentStyle}>User Login Form</Text>

        <TextInput
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Email"
          onChangeText={UserEmail => this.setState({ UserEmail })}
          // Making the Under line Transparent.
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />

        <TextInput
          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Password"
          onChangeText={UserPassword => this.setState({ UserPassword })}
          // Making the Under line Transparent.
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
          secureTextEntry={true}
        />

        <Button
          title="Click Here To Login"
          onPress={this.UserLoginFunction}
          color="#2196F3"
        />
      </View>
    );
  }
}
// Creating Profile activity.
class ProfileActivity extends Component {
  // Setting up profile activity title.
  static navigationOptions = {
    title: "ProfileActivity"
  };

  //logout button click
  logOutAction = () => {
    const { goBack } = this.props.navigation;
    AsyncStorage.clear(); // Clear the Async Storage Before Log out
    goBack(null);
  };

  render() {
    const { goBack } = this.props.navigation;

    return (
      <View style={styles.MainContainer}>
        <Text style={styles.TextComponentStyle}>
          {" "}
          {this.props.navigation.state.params.Email}{" "}
        </Text>

        <Button
          title="Click here to Logout"
          onPress={() => this.logOutAction()}
        />
      </View>
    );
  }
}

const AppNavigator = createStackNavigator({
  First: { screen: LoginActivity },

  Second: { screen: ProfileActivity }
});
export default createAppContainer(AppNavigator);

If you have any doubts feel free to ask :) Happy Coding :)


答:
This finds all 3 RootChild2/Child elements, then tests each in turn:

        foreach (XElement child in doc.Descendants("RootChild2").Elements("Child"))
        {
            if ((string)child.Attribute("key") == "target")
                Console.WriteLine("found it");
            else
                Console.WriteLine("not found");
        }
```


答:
It's not really secure to store credentials locally. You should consider implementing a token based authentication like this: https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

Each time the user does something that requires authentication, you should to pass your token as an Authorization header and validate it on the server side. The documentation shows it how to implement it. It's easy and realiable.

Title: Need some sort of idea to Implementing async storage in React Native app to stay user sign in the app

Body:
respective StackOverflow developer community. I am new to react native development about a month ago i start learning and implementing app in react native now i am stuck in async storage thing. Actually i use php web service to login user in my app mysql is database i m using. Now i want to stay user signed in into my app like if user signed in successfully then if user close app the app store his username and password and next time when user open app he's no need to sign in again. app directly show him home screen i read async storage is responsible for this kind of work need help to implement this kind of functionality
I follow this tutorial for login :
https://reactnativecode.com/react-native-user-login-using-php-mysql/

import React, { Component } from 'react';

import { StyleSheet, TextInput, View, Alert, Button, Text , AsyncStorage} from 'react-native';

// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator , createAppContainer } from 'react-navigation';

// Creating Login Activity.
class LoginActivity extends Component {

  // Setting up Login Activity title.
  static navigationOptions =
   {
      title: 'LoginActivity',
   };

constructor(props) {

    super(props)

    this.state = {

      UserEmail: '',
      UserPassword: ''

    }

  }

UserLoginFunction = () =>{
 const { UserEmail }  = this.state ;
 const { UserPassword }  = this.state ;

fetch('http://192.168.0.107/loginrn/User_Login.php', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({

    email: UserEmail,

    password: UserPassword
    //console.log('UserEmail')
  })

}).then((response) => response.json())
      .then((responseJson) => {

        // If server response message same as Data Matched
       if(responseJson === 'Data Matched')
        {

            //Then open Profile activity and send user email to profile activity.
            this.props.navigation.navigate('Second', { Email: UserEmail });

        }
        else{

          Alert.alert(responseJson);
        }

      }).catch((error) => {
        console.error(error);
      });

  }

  render() {
    return (

<View style={styles.MainContainer}>

        <Text style= {styles.TextComponentStyle}>User Login Form</Text>

        <TextInput

          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Email"

          onChangeText={UserEmail => this.setState({UserEmail})}

          // Making the Under line Transparent.
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}
        />

        <TextInput

          // Adding hint in Text Input using Place holder.
          placeholder="Enter User Password"

          onChangeText={UserPassword => this.setState({UserPassword})}

          // Making the Under line Transparent.
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}

          secureTextEntry={true}
        />

        <Button title="Click Here To Login" onPress={this.UserLoginFunction} color="#2196F3" />

</View>

    );
  }
}
// Creating Profile activity.
class ProfileActivity extends Component
{

  // Setting up profile activity title.
   static navigationOptions =
   {
      title: 'ProfileActivity',

   };

   render()
   {

     const {goBack} = this.props.navigation;

      return(
         <View style = { styles.MainContainer }>

            <Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text>

            <Button title="Click here to Logout" onPress={ () => goBack(null) } />

         </View>
      );
   }
}

const AppNavigator= createStackNavigator(
{
   First: { screen: LoginActivity },

   Second: { screen: ProfileActivity }

});
export default createAppContainer(AppNavigator);


问:
Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type
I read how TypeScript module resolution works.

I have the following repository: @ts-stack/di.
After compiling the directory structure is as follows:

```<code>├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json
</code>```

In my package.json I wrote "main": "dist/index.js".

In Node.js everything works fine, but TypeScript:

```<code>import {Injector} from '@ts-stack/di';
</code>```

Could not find a declaration file for module '@ts-stack/di'. '/path/to/node_modules/@ts-stack/di/dist/index.js' implicitly has an 'any' type.

And yet, if I import as follows, then everything works:

```<code>import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';
</code>```

What am I doing wrong?

答:
Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts that'll contain all the missing declaration files from various packages:

Index.d.ts:

```<code>declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';
</code>```

and reference it to in your tsconfig.js:

```<code>"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "index.d.ts" // this
  ]
</code>```

Body:
I read how TypeScript module resolution works.

I have the following repository: @ts-stack/di.
After compiling the directory structure is as follows:

├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json

In my package.json I wrote "main": "dist/index.js".

In Node.js everything works fine, but TypeScript:

import {Injector} from '@ts-stack/di';

Could not find a declaration file for module '@ts-stack/di'. '/path/to/node_modules/@ts-stack/di/dist/index.js' implicitly has an 'any' type.

And yet, if I import as follows, then everything works:

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

What am I doing wrong?

Body:
Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts that'll contain all the missing declaration files from various packages:

Index.d.ts:

declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';

and reference it to in your tsconfig.js:

"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx",
    "index.d.ts" // this
  ]


问:
curl POST format for CURLOPT_POSTFIELDS
When I use curl via POST and set CURLOPT_POSTFIELD do I have to urlencode or any special format?

for example: If I want to post 2 fields, first and last:

```<code>first=John&last=Smith
</code>```

what is the exact code/format that should be used with curl?

```<code>$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);
</code>```

答:
It depends on the content-type

url-encoded or multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

In such cases, content must be explicitely encoded as JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),
```

<p>When communicating in JSON, we also usually set <code>accept</code> and <code>content-type</code> headers accordingly:</p>

<pre class="lang-php prettyprint-override"><code>CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]
</code>```

ContentLicense: CC BY-SA 3.0

Title: curl POST format for CURLOPT_POSTFIELDS

Body:
When I use curl via POST and set CURLOPT_POSTFIELD do I have to urlencode or any special format?

for example: If I want to post 2 fields, first and last:

first=John&last=Smith

what is the exact code/format that should be used with curl?

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);

Body:
It depends on the content-type

url-encoded or multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

JSON encoding

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

In such cases, content must be explicitely encoded as JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set accept and content-type headers accordingly:

CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]


问:
Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven
I have a maven project forked and cloned from a git repo onto my eclipse. It is build on Java 8. The first thing i do is perform a

```<code>mvn clean install
</code>```

But I get following failure message:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---
[INFO] Deleting /Users/vshukla/git/Prism/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.266 s
[INFO] Finished at: 2017-03-01T12:11:27+05:30
[INFO] Final Memory: 13M/309M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1]   http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

However, below is the build path details of the project which clearly has JRE - 8 set up:

and the compilation set up:

No matter how many times I build the project, i get the same error. Even after cleaning the project and refreshing it from eclipse doesn't help. Please guide.

UPDATE:

After adding the properties to set maven compiler plugin

```<code><properties>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>
</code>```

,

am getting the below error:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---
[INFO] Deleting /Users/vshukla/git/Prism/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes
[INFO] -------------------------------------------------------------
[WARNING] COMPILATION WARNING :
[INFO] -------------------------------------------------------------
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java uses or overrides a deprecated API.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:deprecation for details.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Some input files use unchecked or unsafe operations.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:unchecked for details.
[INFO] 4 warnings
[INFO] -------------------------------------------------------------
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol
  symbol: class Application
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol
  symbol: variable Application
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.591 s
[INFO] Finished at: 2017-03-01T13:09:47+05:30
[INFO] Final Memory: 21M/347M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol
[ERROR] symbol: class Application
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol
[ERROR] symbol: variable Application
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

And here is the code snippet giving the compilation error from MainUITabbed class:

```<code>import com.apple.eawt.Application;
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                Application application = Application.getApplication(); // line 93

                ImageIcon imgicon = new ImageIcon(getClass().getResource(
                        "ICON.jpg"));
                Image img = imgicon.getImage();

                application.setDockIconImage(img);

                MainUITabbed frame = new MainUITabbed();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();

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

答: My issues was that I was running mvn compile from a child project directory instead of the parent project.

Body:
I have a maven project forked and cloned from a git repo onto my eclipse. It is build on Java 8. The first thing i do is perform a

mvn clean install

But I get following failure message:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---
[INFO] Deleting /Users/vshukla/git/Prism/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5
  (use -source 7 or higher to enable diamond operator)
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.266 s
[INFO] Finished at: 2017-03-01T12:11:27+05:30
[INFO] Final Memory: 13M/309M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable diamond operator)
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1]   http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

However, below is the build path details of the project which clearly has JRE - 8 set up:

and the compilation set up:

No matter how many times I build the project, i get the same error. Even after cleaning the project and refreshing it from eclipse doesn't help. Please guide.

UPDATE:

After adding the properties to set maven compiler plugin

<properties>
 <maven.compiler.source>1.8</maven.compiler.source>
 <maven.compiler.target>1.8</maven.compiler.target>
</properties>

,

am getting the below error:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---
[INFO] Deleting /Users/vshukla/git/Prism/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes
[INFO] -------------------------------------------------------------
[WARNING] COMPILATION WARNING :
[INFO] -------------------------------------------------------------
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java uses or overrides a deprecated API.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:deprecation for details.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Some input files use unchecked or unsafe operations.
[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:unchecked for details.
[INFO] 4 warnings
[INFO] -------------------------------------------------------------
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol
  symbol: class Application
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol
  symbol: variable Application
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.591 s
[INFO] Finished at: 2017-03-01T13:09:47+05:30
[INFO] Final Memory: 21M/347M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol
[ERROR] symbol: class Application
[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol
[ERROR] symbol: variable Application
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

And here is the code snippet giving the compilation error from MainUITabbed class:

import com.apple.eawt.Application;
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                Application application = Application.getApplication(); // line 93

                ImageIcon imgicon = new ImageIcon(getClass().getResource(
                        "ICON.jpg"));
                Image img = imgicon.getImage();

                application.setDockIconImage(img);

                MainUITabbed frame = new MainUITabbed();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    });
}


问:
How can I properly add headers in my axios post request, post route works in postman but not when using axios
I'm trying to use JWT to protect a post route in my nodejs, express, react application.
I tested it using postman by adding the JWT token to the headers and works perfectly to add the user to the database. But if I do the request from react using axios I get a 401 response (Unauthorized).

This is my axios post request from the front end:

```<code>addClient = async e => {

let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post("/auth/signup", newUser, {
                headers: { Authorization: `JWT ${accessString}` }
            })
                .then(res => {
                    console.log(res);
                    return this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => {
                    return console.log(err);
                });
}
</code>```

Here is my post route:

```<code>router.post("/signup", verifyToken, (req, res) => {
    console.log(req.headers);

    const {
        businessname,
        username,
        firstName,
        lastName,
        phoneNumber,
        email,
        password,
        customerStatus,
        userType,
        Gooduntil
    } = req.body;

    if (password.length < 8) {
        throw "Password must be at least 8 characters";
    } else {
        User.findOne({
            where: {
                email
            }
        }).then(user => {
            if (user) {
                return res.send("Email already exists!");
            } else {
                const encryptedPassword = bcrypt.hashSync(password, salt);

                let newUser = {
                    businessname,
                    username,
                    firstName,
                    lastName,
                    phoneNumber,
                    email,
                    password: encryptedPassword,
                    customerStatus,
                    userType,
                    Gooduntil
                };
                User.create(newUser)
                    .then(() => {
                        // newUser.isAdmin = true
                        delete newUser.password;
                        res.send(newUser);
                    })
                    .catch(function(err) {
                        console.log(err);
                        res.json(err);
                    });
            }
        });
    }
});
</code>```

And this is my middleware:

```<code>const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {
    const token = req.header("JWT");
    if (!token) return res.status(401).send("Access Denied!");

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        return next();
    } catch (err) {
        res.status(400).send("Invalid Token!");
    }
};
</code>```

So, how can I properly make my axios request?
Thanks in advance.

答:
From this line I can see you are checking for a header named JWT.

```<code>const token = req.header("JWT");
</code>```

But in axios you are sending the Authorization header:

```<code>{ headers: { Authorization: `JWT ${accessString}` }
</code>```

You need to send the JWT header. Also alternatively, if you want to check the Authorization header just check for that:

```<code>const token = req.headers['authorization'];
</code>```

Also, Just send the <token>, if you send JWT <token> then you would need to split the header and check only the <token> part.

Body:
I'm trying to use JWT to protect a post route in my nodejs, express, react application.
I tested it using postman by adding the JWT token to the headers and works perfectly to add the user to the database. But if I do the request from react using axios I get a 401 response (Unauthorized).

This is my axios post request from the front end:

addClient = async e => {

let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post("/auth/signup", newUser, {
                headers: { Authorization: `JWT ${accessString}` }
            })
                .then(res => {
                    console.log(res);
                    return this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => {
                    return console.log(err);
                });
}

Here is my post route:

router.post("/signup", verifyToken, (req, res) => {
    console.log(req.headers);

    const {
        businessname,
        username,
        firstName,
        lastName,
        phoneNumber,
        email,
        password,
        customerStatus,
        userType,
        Gooduntil
    } = req.body;

    if (password.length < 8) {
        throw "Password must be at least 8 characters";
    } else {
        User.findOne({
            where: {
                email
            }
        }).then(user => {
            if (user) {
                return res.send("Email already exists!");
            } else {
                const encryptedPassword = bcrypt.hashSync(password, salt);

                let newUser = {
                    businessname,
                    username,
                    firstName,
                    lastName,
                    phoneNumber,
                    email,
                    password: encryptedPassword,
                    customerStatus,
                    userType,
                    Gooduntil
                };
                User.create(newUser)
                    .then(() => {
                        // newUser.isAdmin = true
                        delete newUser.password;
                        res.send(newUser);
                    })
                    .catch(function(err) {
                        console.log(err);
                        res.json(err);
                    });
            }
        });
    }
});

And this is my middleware:

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {
    const token = req.header("JWT");
    if (!token) return res.status(401).send("Access Denied!");

    try {
        const verified = jwt.verify(token, process.env.JWT_SECRET);
        req.user = verified;
        return next();
    } catch (err) {
        res.status(400).send("Invalid Token!");
    }
};

So, how can I properly make my axios request?
Thanks in advance.

Body:
From this line I can see you are checking for a header named JWT.

const token = req.header("JWT");

But in axios you are sending the Authorization header:

{ headers: { Authorization: `JWT ${accessString}` }

You need to send the JWT header. Also alternatively, if you want to check the Authorization header just check for that:

const token = req.headers['authorization'];

Also, Just send the <token>, if you send JWT <token> then you would need to split the header and check only the <token> part.


问:
Python parse and flatten only some fields of a dict in a list
I have a JSON that I have converted to a list of python dicts that looks like so:

```<code>[
{'id': 8675309,
 'slug': 'name',
 'campaigns': [
   {
   'part_id': 'sfgsdfgsd',
   'client_id': '1sdfgsdfg',
   'business_id': None,
   'metadata': {'field':1}},
   {
   'part_id': '354yyr',
   'client_id': 'erty465',
   'business_id': None,
   'metadata': {'field':10}
   }
   ]
},
{'id': 1234567,
 'slug': 'name2',
 'campaigns': [
   {
   'part_id': 'wertyw',
   'client_id': 'sighs',
   'business_id': None,
   'metadata': {'field':1}}
   ]
}
</code>```

and I basically need to flatten the part_id, client_id, and business_id from the campaigns list while maintaining the id and slug fields. Basically I'm looking for a result that looks like this:

```<code>[
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': 'sfgsdfgsd',
     'client_id': '1sdfgsdfg',
     'business_id': None,
    },
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': '354yyr',
     'client_id': 'erty465',
     'business_id': None,
    },
    {
     'id': 1234567,
     'slug': 'name2',
     'part_id': 'wertyw',
     'client_id': 'sighs',
     'business_id': None,
    }
]
</code>```

I know how to flatten the campaign data like this:

```<code>campaigns = [i['campaigns'] for i in data]
campaigns = [item for sublist in campaigns for item in sublist]
</code>```

where data is the list of dicts but how do I do that while maintaining the id and slug fields?

答:
You can use operator.itemgetter() to get certain keys from dictionary in one expression. Then use zip() to create key-value pairs and pass them to a dict().

Code:

```<code>from operator import itemgetter

source = [] # YOUR SOURCE

main_fields = 'id', 'slug'
sub_fields = 'part_id', 'client_id', 'business_id'
main_getter = itemgetter(*main_fields)
sub_getter = itemgetter(*sub_fields)
result = []

for item in source:
    parsed = main_getter(item)
    for campaign in item['campaigns']:
        result.append(dict(zip(main_fields + sub_fields, parsed + sub_getter(campaign))))
</code>```

You can also use nested list comprehension:

```<code>result = [dict(zip(main_fields + sub_fields, itemgetter(*main_fields)(item) + itemgetter(*sub_fields)(campaign))) for item in source for campaign in item['campaigns']]
</code>```

Body:
I have a JSON that I have converted to a list of python dicts that looks like so:

[
{'id': 8675309,
 'slug': 'name',
 'campaigns': [
   {
   'part_id': 'sfgsdfgsd',
   'client_id': '1sdfgsdfg',
   'business_id': None,
   'metadata': {'field':1}},
   {
   'part_id': '354yyr',
   'client_id': 'erty465',
   'business_id': None,
   'metadata': {'field':10}
   }
   ]
},
{'id': 1234567,
 'slug': 'name2',
 'campaigns': [
   {
   'part_id': 'wertyw',
   'client_id': 'sighs',
   'business_id': None,
   'metadata': {'field':1}}
   ]
}

and I basically need to flatten the part_id, client_id, and business_id from the campaigns list while maintaining the id and slug fields. Basically I'm looking for a result that looks like this:

[
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': 'sfgsdfgsd',
     'client_id': '1sdfgsdfg',
     'business_id': None,
    },
    {
     'id': 8675309,
     'slug': 'name',
     'part_id': '354yyr',
     'client_id': 'erty465',
     'business_id': None,
    },
    {
     'id': 1234567,
     'slug': 'name2',
     'part_id': 'wertyw',
     'client_id': 'sighs',
     'business_id': None,
    }
]

I know how to flatten the campaign data like this:

campaigns = [i['campaigns'] for i in data]
campaigns = [item for sublist in campaigns for item in sublist]

where data is the list of dicts but how do I do that while maintaining the id and slug fields?

Body:
You can use operator.itemgetter() to get certain keys from dictionary in one expression. Then use zip() to create key-value pairs and pass them to a dict().

Code:

from operator import itemgetter

source = [] # YOUR SOURCE

main_fields = 'id', 'slug'
sub_fields = 'part_id', 'client_id', 'business_id'
main_getter = itemgetter(*main_fields)
sub_getter = itemgetter(*sub_fields)
result = []

for item in source:
    parsed = main_getter(item)
    for campaign in item['campaigns']:
        result.append(dict(zip(main_fields + sub_fields, parsed + sub_getter(campaign))))

You can also use nested list comprehension:

result = [dict(zip(main_fields + sub_fields, itemgetter(*main_fields)(item) + itemgetter(*sub_fields)(campaign))) for item in source for campaign in item['campaigns']]


问:
Unable to add PDF/A valid meta data
Java: 1.8

pdfbox: 2.0.18

preflight: 2.0.18

I can create a working PDF but our requirements is that it must conform to PDF/A standards.
I've managed to fix all validation issues apart from metadata.

Without adding any meta data I get the error:

```<code>The fileexample.pdf is not valid, error(s) :
7.1 : Error on MetaData, Metadata is not a stream
</code>```

Following some examples (No documentation exists for this under v2+) I've come up with the follow:

```<code>PDMetadata documentMetadata = new PDMetadata(document);
XMPMetadata xmpMetadata = XMPMetadata.createXMPMetadata();
xmpMetadata.createAndAddPFAIdentificationSchema();
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.serialize(xmpMetadata, out, false);
documentMetadata.importXMPMetadata(out.toByteArray());
catalog.setMetadata(documentMetadata);
</code>```

Which gives me the error:

```<code>The fileexample.pdf is not valid, error(s) :
7.1 : Error on MetaData, xmp should start with a processing instruction
</code>```

I've then tried changing the serializer to true for withXpacket and I get the following error:

```<code>org.apache.pdfbox.preflight.exception.ValidationException: Failed while validating
    at org.apache.pdfbox.preflight.process.MetadataValidationProcess.validate(MetadataValidationProcess.java:162)
    at org.apache.pdfbox.preflight.utils.ContextHelper.callValidation(ContextHelper.java:102)
    at org.apache.pdfbox.preflight.utils.ContextHelper.validateElement(ContextHelper.java:141)
    at org.apache.pdfbox.preflight.PreflightDocument.validate(PreflightDocument.java:166)
    at uk.ac.port.pdf.Main.validate(Main.java:53)
    at uk.ac.port.pdf.Main.main(Main.java:21)
Caused by: org.apache.pdfbox.preflight.exception.ValidationException: Schemas not found in the given metadata representation
    at org.apache.pdfbox.preflight.metadata.RDFAboutAttributeConcordanceValidation.validateRDFAboutAttributes(RDFAboutAttributeConcordanceValidation.java:51)
    at org.apache.pdfbox.preflight.process.MetadataValidationProcess.validate(MetadataValidationProcess.java:99)
    ... 5 more
</code>```

At this point I clearly don't understand how this is meant to work. I've found a lot of different examples but they all appear to work for v1.8 and not v2+.

Could someone please provide me with a good working example of adding PDF/A metadata and schema to the PDF file? The website has no documentation, especially for PDF/A.

答:
It turns out I was missing a simple step. There are default values setup but you have to tell it which part and conformance level your PDF/A document will follow. For example 1B.

```<code>XMPMetadata xmp = XMPMetadata.createXMPMetadata();

XMPBasicSchema xmpschema = xmp.createAndAddXMPBasicSchema();
xmpschema.setCreatorTool(creatorTool);
xmpschema.setCreateDate(creationDate);

DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.setTitle(title);

PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
id.setPart(1);
id.setConformance("B");
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, true);
PDMetadata metadata = new PDMetadata(document);
metadata.importXMPMetadata(baos.toByteArray());
catalog.setMetadata(metadata);
</code>```

I now get:

```<code>The file example.pdf is a valid PDF/A-1b file
</code>```

and when check with an online validator..

```<code>Compliance  pdfa-1b
</code>```

Title: Unable to add PDF/A valid meta data

Body:
Java: 1.8

pdfbox: 2.0.18

preflight: 2.0.18

I can create a working PDF but our requirements is that it must conform to PDF/A standards.
I've managed to fix all validation issues apart from metadata.

Without adding any meta data I get the error:

The fileexample.pdf is not valid, error(s) :
7.1 : Error on MetaData, Metadata is not a stream

Following some examples (No documentation exists for this under v2+) I've come up with the follow:

PDMetadata documentMetadata = new PDMetadata(document);
XMPMetadata xmpMetadata = XMPMetadata.createXMPMetadata();
xmpMetadata.createAndAddPFAIdentificationSchema();
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.serialize(xmpMetadata, out, false);
documentMetadata.importXMPMetadata(out.toByteArray());
catalog.setMetadata(documentMetadata);

Which gives me the error:

The fileexample.pdf is not valid, error(s) :
7.1 : Error on MetaData, xmp should start with a processing instruction

I've then tried changing the serializer to true for withXpacket and I get the following error:

org.apache.pdfbox.preflight.exception.ValidationException: Failed while validating
    at org.apache.pdfbox.preflight.process.MetadataValidationProcess.validate(MetadataValidationProcess.java:162)
    at org.apache.pdfbox.preflight.utils.ContextHelper.callValidation(ContextHelper.java:102)
    at org.apache.pdfbox.preflight.utils.ContextHelper.validateElement(ContextHelper.java:141)
    at org.apache.pdfbox.preflight.PreflightDocument.validate(PreflightDocument.java:166)
    at uk.ac.port.pdf.Main.validate(Main.java:53)
    at uk.ac.port.pdf.Main.main(Main.java:21)
Caused by: org.apache.pdfbox.preflight.exception.ValidationException: Schemas not found in the given metadata representation
    at org.apache.pdfbox.preflight.metadata.RDFAboutAttributeConcordanceValidation.validateRDFAboutAttributes(RDFAboutAttributeConcordanceValidation.java:51)
    at org.apache.pdfbox.preflight.process.MetadataValidationProcess.validate(MetadataValidationProcess.java:99)
    ... 5 more

At this point I clearly don't understand how this is meant to work. I've found a lot of different examples but they all appear to work for v1.8 and not v2+.

Could someone please provide me with a good working example of adding PDF/A metadata and schema to the PDF file? The website has no documentation, especially for PDF/A.

Body:
It turns out I was missing a simple step. There are default values setup but you have to tell it which part and conformance level your PDF/A document will follow. For example 1B.

XMPMetadata xmp = XMPMetadata.createXMPMetadata();

XMPBasicSchema xmpschema = xmp.createAndAddXMPBasicSchema();
xmpschema.setCreatorTool(creatorTool);
xmpschema.setCreateDate(creationDate);

DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.setTitle(title);

PDFAIdentificationSchema id = xmp.createAndAddPFAIdentificationSchema();
id.setPart(1);
id.setConformance("B");
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, true);
PDMetadata metadata = new PDMetadata(document);
metadata.importXMPMetadata(baos.toByteArray());
catalog.setMetadata(metadata);

I now get:

The file example.pdf is a valid PDF/A-1b file

and when check with an online validator..

Compliance  pdfa-1b


问:
Converting Postgre to Bigquery
I am having a trouble with a conversion from Postgre to Bigquery query.

Please, how could this query work on bigquery ? I need to subselect a table and bring the last register

```<code>(select g.fase__c
from operacoes.salesforce_gest_o_do_canal_c_full g
where g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
order by g.data_do_credenciamento__c limit 1)  as fase_jornada

from operacoes.salesforce_account_full
</code>```

If I try to execute, Bigquery returns an error I should apply a join, If I apply the join, the order by doesn´t work

Thanks!

答:
A correlated subquery (which is a subquery that references a table of an outer query), if executed "as is", would need to compute the subquery for each row of the results of the outer query, which would not be very efficient.

In order to optimize this, BigQuery first transforms (decorrelates) the query into one that is functionally equivalent to the correlated one but without any correlations between queries and subqueries. Different decorrelation processes are needed for different use cases and they can be quite complex and difficult to implement and properly test.

BigQuery is implementing decorrelation strategies to make a variety of correlated subqueries possible, however decorrelation for the LIMIT clause has not been implemented.

A workaround would be to use ARRAY_AGG instead of a subquery. In your case, I believe the following query would do the work:

```<code>SELECT
  ARRAY_AGG(g.fase__c
    ORDER BY g.data_do_credenciamento__c
    LIMIT 1) AS fase_jornada
FROM
  operacoes.salesforce_account_full a
JOIN
  operacoes.salesforce_gest_o_do_canal_c_full g
ON
  g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
GROUP BY
  g.n_de_indentifica_o_do_parceiro__c
</code>```

Take into account that I have guessed some details since the whole context for the subquery was not provided, so you may need to make some changes to it.

Please let me know if anything was not clear!

Title: Converting Postgre to Bigquery

Body:
I am having a trouble with a conversion from Postgre to Bigquery query.

Please, how could this query work on bigquery ? I need to subselect a table and bring the last register

(select g.fase__c
from operacoes.salesforce_gest_o_do_canal_c_full g
where g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
order by g.data_do_credenciamento__c limit 1)  as fase_jornada

from operacoes.salesforce_account_full

If I try to execute, Bigquery returns an error I should apply a join, If I apply the join, the order by doesn´t work

Thanks!

Body:
A correlated subquery (which is a subquery that references a table of an outer query), if executed "as is", would need to compute the subquery for each row of the results of the outer query, which would not be very efficient.

In order to optimize this, BigQuery first transforms (decorrelates) the query into one that is functionally equivalent to the correlated one but without any correlations between queries and subqueries. Different decorrelation processes are needed for different use cases and they can be quite complex and difficult to implement and properly test.

BigQuery is implementing decorrelation strategies to make a variety of correlated subqueries possible, however decorrelation for the LIMIT clause has not been implemented.

A workaround would be to use ARRAY_AGG instead of a subquery. In your case, I believe the following query would do the work:

SELECT
  ARRAY_AGG(g.fase__c
    ORDER BY g.data_do_credenciamento__c
    LIMIT 1) AS fase_jornada
FROM
  operacoes.salesforce_account_full a
JOIN
  operacoes.salesforce_gest_o_do_canal_c_full g
ON
  g.n_de_indentifica_o_do_parceiro__c = a.n_de_indentifica_o_do_parceiro__c
GROUP BY
  g.n_de_indentifica_o_do_parceiro__c

Take into account that I have guessed some details since the whole context for the subquery was not provided, so you may need to make some changes to it.

Please let me know if anything was not clear!


问:
In Swift, how do I explicitly specify a return value for map with anonymous closure arguments?
Say I call map like this, using the anonymous closure argument $0:

array.map {
  return $0.description
}
```

<p>How would I explicitly define that map returns a <code>string</code>? This doesn’t work:</p>

<pre class="lang-swift prettyprint-override"><code>array.map { -> String
  return $0.description
}
</code>```

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored

Does that mean if I want to specify a return value I have to name my arguments?

[EDIT: I know I do not need an explicit return type here; still would like how to specify one]

答:
You can use as to identify the type of the anonymous enclosure.  In this case you'll need to specify the type of the input as well:

```<code>let result = array.map({ $0.description } as (CustomStringConvertible) -> String)
</code>```

Note:  You could use the type of whatever is in array as the input type.  Here I just used the CustomStringConvertible protocol since that is what is needed to be able to access the .description property.

or as you mentioned, you can specify the output type if you give a name to the input parameter:

```<code>let result = array.map { value -> String in value.description }
</code>```

Another way to look at it is to note that map returns an Array of whatever type the map closure returns.  You could specify that the result of the map is [String] and Swift would then infer that the map closure returns String:

```<code>let result = array.map({ $0.description }) as [String]
</code>```

or

```<code>let result: [String] = array.map { $0.description }
</code>```

Body:
Say I call map like this, using the anonymous closure argument $0:

array.map {
  return $0.description
}

How would I explicitly define that map returns a string? This doesn’t work:

array.map { -> String
  return $0.description
}

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored

Does that mean if I want to specify a return value I have to name my arguments?

[EDIT: I know I do not need an explicit return type here; still would like how to specify one]

Body:
You can use as to identify the type of the anonymous enclosure.  In this case you'll need to specify the type of the input as well:

let result = array.map({ $0.description } as (CustomStringConvertible) -> String)

Note:  You could use the type of whatever is in array as the input type.  Here I just used the CustomStringConvertible protocol since that is what is needed to be able to access the .description property.

or as you mentioned, you can specify the output type if you give a name to the input parameter:

let result = array.map { value -> String in value.description }

Another way to look at it is to note that map returns an Array of whatever type the map closure returns.  You could specify that the result of the map is [String] and Swift would then infer that the map closure returns String:

let result = array.map({ $0.description }) as [String]

or

let result: [String] = array.map { $0.description }


问:
How to decode a JSON string?
On the server side do I have 2 hashes I encode into JSON strings like so

```<code>my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
</code>```

On the client side I have

```<code>$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...
</code>```

users contains

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

```<code>function makeTable(users) {
    var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}
</code>```

which should produce

```<code>Initials    Full Name
ss  Sandra Schlichting
fn  Full name
</code>```

答:
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.

Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/

Title: How to decode a JSON string?

Body:
On the server side do I have 2 hashes I encode into JSON strings like so

my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;

On the client side I have

$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...

users contains

{"ss":"Sandra Schlichting","fn":"Full name"}

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

function makeTable(users) {
    var result = '
\n
Initials	Full Name
\n';
    $.each(users, function(index, value) {
        result += '
' + index + '	' + value + '
\n';
    });
    result += '
';
    return (result);
}

which should produce

Initials    Full Name
ss  Sandra Schlichting
fn  Full name


问:
Self-hosted WCF service maxing cpu load
I am looking into an issue at work with a WindowsService that is taking 100% CPU on a machine with 16 CPU's.

The service is hosting a self-hosted .NET WCF service.

I have received a crash dump which I have loaded up in windbg, in order to look for clues.

So what I have tried:

!threads :

ThreadCount:      646

  UnstartedThread:  0

  BackgroundThread: 643

  PendingThread:    0

  DeadThread:       2

  Hosted Runtime:   no

 642 of the threads were Threadpool workers as following:

    8   29 2a34 000000002068b510  3029220 Preemptive  0000000000000000:0000000000000000 0000000000563f50 0     MTA (Threadpool Worker)

~29s -> !CLRStack

000000003c66eb70 00000000770512fa [GCFrame: 000000003c66eb70]

  000000003c66ec40 00000000770512fa [GCFrame: 000000003c66ec40]

  000000003c66ec78 00000000770512fa [HelperMethodFrame: 000000003c66ec78]
System.Threading.Monitor.Enter(System.Object)

  000000003c66ed70 000007fef7af1c9c System.Threading.TimerQueueTimer.Fire()

  000000003c66ede0 000007fef7a6c2f3 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()

  000000003c66ee30 000007fef7a6c92a System.Threading.ThreadPoolWorkQueue.Dispatch()

  000000003c66f388 000007fef8d57d33 [DebuggerU2MCatchHandlerFrame: 000000003c66f388]

~29s -> K

000000003c66e858 000007fefd7010dc ntdll!NtWaitForSingleObject+0xa

  000000003c66e860 000007fef8d049bf KERNELBASE!WaitForSingleObjectEx+0x79

  000000003c66e900 000007fef8d04977 clr!CLREventBase::WaitEx+0x16c

  000000003c66e940 000007fef8d048f8 clr!CLREventBase::WaitEx+0x103

  000000003c66e9a0 000007fef8e9c5de clr!CLREventBase::WaitEx+0x70

  000000003c66ea30 000007fef8dc5a34 clr!WKS::GCHeap::WaitUntilGCComplete+0x2b

  000000003c66ea60 000007fef8d0c4f4 clr!Thread::RareDisablePreemptiveGC+0x176

  000000003c66eaf0 000007fef8dd1f3d clr!GCCoop::GCCoop+0x3d

  000000003c66eb20 000007fef8e898cf clr!AwareLock::Contention+0x137

  000000003c66ebe0 000007fef7af1c9c clr!JITutil_MonContention+0xaf

  000000003c66ed70 000007fef7a6c2f3 mscorlib_ni+0x521c9c

  000000003c66ede0 000007fef7a6c92a mscorlib_ni+0x49c2f3

  000000003c66ee30 000007fef8d57d33 mscorlib_ni+0x49c92a

  000000003c66eef0 000007fef8d556e6 clr!CallDescrWorkerInternal+0x83

  000000003c66ef30 000007fef8d557af clr!CallDescrWorkerWithHandler+0x4a

  000000003c66ef70 000007fef8eda2c9 clr!MethodDescCallSite::CallTargetWorker+0x2e6

  000000003c66f120 000007fef8ee51b0 clr!QueueUserWorkItemManagedCallback+0x2a

  000000003c66f200 000007fef8ee513e clr!DebuggerU2MCatchHandlerFrame::DebuggerU2MCatchHandlerFrame+0xa0

  000000003c66f240 000007fef8ee50b5 clr!ManagedPerAppDomainTPCount::DispatchWorkItem+0x38e

  000000003c66f340 000007fef8ee51eb clr!ManagedPerAppDomainTPCount::DispatchWorkItem+0x2bd

  000000003c66f3d0 000007fef8eda224 clr!ManagedPerAppDomainTPCount::DispatchWorkItem+0x23b

  000000003c66f430 000007fef8ee6baf clr!ManagedPerAppDomainTPCount::DispatchWorkItem+0xb4

  000000003c66f5c0 000007fef8ee6ab3 clr!ThreadpoolMgr::ExecuteWorkRequest+0x4c

  000000003c66f5f0 000007fef8eda8a6 clr!ThreadpoolMgr::WorkerThreadStart+0xf3

  000000003c66f6b0 0000000076c9652d clr!Thread::intermediateThreadProc+0x7d

  000000003c66f7f0 000000007702c541 kernel32!BaseThreadInitThunk+0xd

  000000003c66f820 0000000000000000 ntdll!RtlUserThreadStart+0x1d

Im having a hard time interpreting the stacktraces since they dont hit any of my applicationcode.
Are they all just idle threadworkers, waiting for work?

答:
Collect ETW with Perfview and follow the big % numbers.

try run in windbg ~*e!clstack => call stacks of all threads look for repeatable code.

Title: Self-hosted WCF service maxing cpu load


问:
Regex for matching decimals only, not integers
I'm looking for a regex to match decimal numbers only, but to fail on integers.

For example, the following numbers should pass

```<code>0.00
1.00
-1.00
3.3
2.22123
</code>```

But the following should fail

```<code>-1
-3
4
559
</code>```

I don't know why this is so hard to find/create, but I'm not having any luck. All available regexes that I found online don't exclude integers.

答:
This pattern works regexr.com/4ulml</p>

```<code>^[-]?\d+\.\d+$
</code>```

Body:
I'm looking for a regex to match decimal numbers only, but to fail on integers.

For example, the following numbers should pass

0.00
1.00
-1.00
3.3
2.22123

But the following should fail

-1
-3
4
559

I don't know why this is so hard to find/create, but I'm not having any luck. All available regexes that I found online don't exclude integers.

Body:
This pattern works regexr.com/4ulml

^[-]?\d+\.\d+$