问:
Exception about SoftwareBitmapSource in UWP Code
What's wrong with this code?

private async void FrameMonitor_PartEvent(object sender, MonitorParam monitorParam)
    {
        SoftwareBitmap bmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)monitorParam.WP_FrameInfo.ImageWidth, (int)monitorParam.WP_FrameInfo.ImageHeight, BitmapAlphaMode.Ignore);
        IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(monitorParam.WP_FrameBytes);
        bmp.CopyFromBuffer(buffer);
        SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();
        await bmpsource.SetBitmapAsync(bmp);
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
        {

            Img_WPImg.Source = bmpsource;
        });
        bmp.Dispose();
    }
```

<p>On this code:</p>

<pre class="lang-cs prettyprint-override"><code>SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();
</code>```

Visual Studio shows this exception:

System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

I hope there is a master hand can help me.

答:
That exception tells me that you need to do that from the UI thread, so just move that code inside the Dispatcher, like this:

private async void FrameMonitor_PartEvent(object sender, MonitorParam monitorParam)
{
    SoftwareBitmap bmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)monitorParam.WP_FrameInfo.ImageWidth, (int)monitorParam.WP_FrameInfo.ImageHeight, BitmapAlphaMode.Ignore);
    IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(monitorParam.WP_FrameBytes);
    bmp.CopyFromBuffer(buffer);
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
    {
        SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();

        await bmpsource.SetBitmapAsync(bmp);

        Img_WPImg.Source = bmpsource;
    });
    bmp.Dispose();
}
```

Body:
What's wrong with this code?

private async void FrameMonitor_PartEvent(object sender, MonitorParam monitorParam)
    {
        SoftwareBitmap bmp = new SoftwareBitmap(BitmapPixelFormat.Bgra8, (int)monitorParam.WP_FrameInfo.ImageWidth, (int)monitorParam.WP_FrameInfo.ImageHeight, BitmapAlphaMode.Ignore);
        IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(monitorParam.WP_FrameBytes);
        bmp.CopyFromBuffer(buffer);
        SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();
        await bmpsource.SetBitmapAsync(bmp);
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async () =>
        {

            Img_WPImg.Source = bmpsource;
        });
        bmp.Dispose();
    }

On this code:

SoftwareBitmapSource bmpsource = new SoftwareBitmapSource();

Visual Studio shows this exception:

System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

I hope there is a master hand can help me.


来源: stackexchange

问:
How to change Orchard record repository
I work on a project where we're considering using Orchard CMS.

However, we want to use web services as data sources for some of the content items. I guess we have to change the repository implementation in order to make this possible, but I'm not sure about that.

So my question is: Is my guess correct, or is it more complex? And how can it be done then?

Thanks!

Update:
I see that Orchard's IRepository interface requires LINQ provider to be implemented. That's impossible in this scenario since the web services are offered via SOAP.

I'll better further describe the scenario:

The website we wish to build has to use web services to get information about an organization members and units. We would like to display members of some organizational unit, for example, on the website. We also want to create our own content type "Event" that should have an M:N relationship (Attendees) with "Member" (from WS).

答: Actually you don't need to use a repository or even a record. Depending on what you are trying to do, triggering the fetching logic from a handler might work.

ContentLicense: CC BY-SA 2.5

Title: How to change Orchard record repository


问:
MYSQL to MS SQL Query Conversion
I have MySQL query. I want to execute this query in MS SQL Server.
How can I convert MySQL to MS SQL.

```<code>SELECT  DST.name AS name,
        BWT.name AS name,
        FOD.name AS name,
        GROUP_CONCAT(ODH.name SEPARATOR ';') as name,
FROM DST
LEFT join BWT
    on DST.name = BWT.name
LEFT join firstorderdata as FOD
    on DST.name = FOD.name
LEFT join ODH
    on DST.name = ODH.name
WHERE DST.dist_status != 'T'
group by DST.name
</code>```

And also I want to generate csv for this query result if possible.

if anybody know please help me ...

答:
From SQL Server 2017 you could use STRING_AGG:

```<code>SELECT  DST.name AS name,
        BWT.name AS name,
        FOD.name AS name,
        STRING_AGG(ODH.name, ';') as name    --changed
FROM DST
LEFT join BWT
    on DST.name = BWT.name
LEFT join firstorderdata as FOD
    on DST.name = FOD.name
LEFT join ODH
    on DST.name = ODH.name
WHERE DST.dist_status != 'T'
group by DST.name AS name,
        BWT.name AS name,    -- added
        FOD.name AS name;    -- added
</code>```

Columns should have distinctive aliases:

```<code>SELECT  DST.name AS d_name,
        BWT.name AS b_name,
        FOD.name AS f_name,
</code>```

ContentLicense: CC BY-SA 3.0

Title: MYSQL to MS SQL Query Conversion

Body:
I have MySQL query. I want to execute this query in MS SQL Server.
How can I convert MySQL to MS SQL.

SELECT  DST.name AS name,
        BWT.name AS name,
        FOD.name AS name,
        GROUP_CONCAT(ODH.name SEPARATOR ';') as name,
FROM DST
LEFT join BWT
    on DST.name = BWT.name
LEFT join firstorderdata as FOD
    on DST.name = FOD.name
LEFT join ODH
    on DST.name = ODH.name
WHERE DST.dist_status != 'T'
group by DST.name

And also I want to generate csv for this query result if possible.

if anybody know please help me ...

Body:
From SQL Server 2017 you could use STRING_AGG:

SELECT  DST.name AS name,
        BWT.name AS name,
        FOD.name AS name,
        STRING_AGG(ODH.name, ';') as name    --changed
FROM DST
LEFT join BWT
    on DST.name = BWT.name
LEFT join firstorderdata as FOD
    on DST.name = FOD.name
LEFT join ODH
    on DST.name = ODH.name
WHERE DST.dist_status != 'T'
group by DST.name AS name,
        BWT.name AS name,    -- added
        FOD.name AS name;    -- added

Columns should have distinctive aliases:

SELECT  DST.name AS d_name,
        BWT.name AS b_name,
        FOD.name AS f_name,


问:
Render multilpe times - Double render in rails
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

```<code>def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end
</code>```

Also should i try something this way Double render error rails ?

答:
Call performed? to check if render or redirect has already happened.

You might want to change your to code to something like this:

```<code>def check_count
  assign_values_from_params

  return if performed?

  if count >= failed_count
    render(partial: params[:view_name], layout: false)
  else
    render(text: 'works')
  end
end

def assign_values_from_params
  # code

  if @date.blank?
    redirect_to(main_index_path) and return
  end

  # code
end
</code>```

Body:
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end

Also should i try something this way Double render error rails ?

Body:
Call performed? to check if render or redirect has already happened.

You might want to change your to code to something like this:

def check_count
  assign_values_from_params

  return if performed?

  if count >= failed_count
    render(partial: params[:view_name], layout: false)
  else
    render(text: 'works')
  end
end

def assign_values_from_params
  # code

  if @date.blank?
    redirect_to(main_index_path) and return
  end

  # code
end


问:
React Native Relase, Debug apk crashes in physical devices
I followed the facebook documentation on how to generate signed apk exactly. But still I am getting error: undefined is not an object (evaluating 'e.length'
Here is the screenshot

However, the app works fine in Android Emulator with command react-native run-android.
But, I got the issue which was causing the app to crash. It was native-base.
Here is the following code in my App.js:

```<code>import React, { Component } from 'react';
import {Text} from 'react-native';
import { Container, Header, Content, Form,Text, Item, Input, Label, Button }
from 'native-base';
export default class ReactNativeExample extends Component {
constructor(props) {
    super(props);
    this.state = {
        username: '',
        password: ''
    };
    this.doSignIn = this.doSignIn.bind(this);
}

doSignIn() {

let formdata = new FormData();
formdata.append("username", this.state.username)
formdata.append("password", this.state.password)

fetch('http://someweb.com/loginUser',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then((response) => response.json())
    .then((responseData) => {
         console.log("Inside responsejson");
         if(responseData.error != true) {
            console.log('You have logged in...');
         }
     }).done();
 }

render() {

return (
  <Container>
    <Header />
    <Content>
      <Form>
        <Item floatingLabel style={{margin: 8}}>
          <Label>Username</Label>
          <Input ref="username" onChangeText={(username) =>
          this.setState({username})}/>
        </Item>
        <Item floatingLabel last style={{margin: 8}}>
          <Label>Password</Label>
          <Input ref="username" onChangeText={(password) =>
          this.setState({password})}/>
        </Item>
         <Button block info style={{margin: 8}} onPress={this.doSignIn}>
        <Text>Login</Text>
      </Button>
      </Form>
    </Content>
  </Container>
  <Text> Hello </Text>
  );
 }
}
</code>```

I want to know what is wrong with the above native-base code that is making the App crash? Is there any way I can make native-base code work?

Thank You.

ReactNative version: 0.50.1

答:
tried your code. Was able to generate an apk successfully. Didn't find any issue while running the apk. Posting the code.

```<code>import React, { Component } from "react";
import { Container, Header, Content, Form, Text, Item, Input, Label,Button } from "native-base";
export default class ReactNativeExample extends Component {
constructor(props) {
  super(props);
  this.state = {
  username: "",
  password: "",
};
this.doSignIn = this.doSignIn.bind(this);
}
doSignIn() {
  let formdata = new FormData();
  formdata.append("username", this.state.username);
  formdata.append("password", this.state.password);

  fetch("https://httpbin.org/", {
    method: "post",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    body: formdata,
  })
    .then(response => console.log("response", response))
    .done();
}

render() {
  return (
    <Container>
      <Header />
      <Content>
        <Form>
          <Item floatingLabel style={{ margin: 8 }}>
            <Label>Username</Label>
            <Input ref="username" onChangeText={username => this.setState({ username })} />
          </Item>
          <Item floatingLabel last style={{ margin: 8 }}>
            <Label>Password</Label>
            <Input ref="username" onChangeText={password => this.setState({ password })} />
          </Item>
          <Button block info style={{ margin: 8 }} onPress={this.doSignIn}>
            <Text>Login</Text>
          </Button>
        </Form>
      </Content>
    </Container>
   );}
}
</code>```

When using NativeBase components use <Text/> from 'native-base'

Body:
I followed the facebook documentation on how to generate signed apk exactly. But still I am getting error: undefined is not an object (evaluating 'e.length'
Here is the screenshot

However, the app works fine in Android Emulator with command react-native run-android.
But, I got the issue which was causing the app to crash. It was native-base.
Here is the following code in my App.js:

import React, { Component } from 'react';
import {Text} from 'react-native';
import { Container, Header, Content, Form,Text, Item, Input, Label, Button }
from 'native-base';
export default class ReactNativeExample extends Component {
constructor(props) {
    super(props);
    this.state = {
        username: '',
        password: ''
    };
    this.doSignIn = this.doSignIn.bind(this);
}

doSignIn() {

let formdata = new FormData();
formdata.append("username", this.state.username)
formdata.append("password", this.state.password)

fetch('http://someweb.com/loginUser',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then((response) => response.json())
    .then((responseData) => {
         console.log("Inside responsejson");
         if(responseData.error != true) {
            console.log('You have logged in...');
         }
     }).done();
 }

render() {

return (
  <Container>

    <Content>
      <Form>
        <Item floatingLabel style={{margin: 8}}>
          Username
          <Input ref="username" onChangeText={(username) =>
          this.setState({username})}/>
        </Item>
        <Item floatingLabel last style={{margin: 8}}>
          Password
          <Input ref="username" onChangeText={(password) =>
          this.setState({password})}/>
        </Item>
         <Button block info style={{margin: 8}} onPress={this.doSignIn}>
        <Text>Login</Text>
      </Button>
      </Form>
    </Content>
  </Container>
  <Text> Hello </Text>
  );
 }
}

I want to know what is wrong with the above native-base code that is making the App crash? Is there any way I can make native-base code work?

Thank You.

ReactNative version: 0.50.1

Body:
tried your code. Was able to generate an apk successfully. Didn't find any issue while running the apk. Posting the code.

import React, { Component } from "react";
import { Container, Header, Content, Form, Text, Item, Input, Label,Button } from "native-base";
export default class ReactNativeExample extends Component {
constructor(props) {
  super(props);
  this.state = {
  username: "",
  password: "",
};
this.doSignIn = this.doSignIn.bind(this);
}
doSignIn() {
  let formdata = new FormData();
  formdata.append("username", this.state.username);
  formdata.append("password", this.state.password);

  fetch("https://httpbin.org/", {
    method: "post",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    body: formdata,
  })
    .then(response => console.log("response", response))
    .done();
}

render() {
  return (
    <Container>
      <Header />
      <Content>
        <Form>
          <Item floatingLabel style={{ margin: 8 }}>
            <Label>Username</Label>
            <Input ref="username" onChangeText={username => this.setState({ username })} />
          </Item>
          <Item floatingLabel last style={{ margin: 8 }}>
            <Label>Password</Label>
            <Input ref="username" onChangeText={password => this.setState({ password })} />
          </Item>
          <Button block info style={{ margin: 8 }} onPress={this.doSignIn}>
            <Text>Login</Text>
          </Button>
        </Form>
      </Content>
    </Container>
   );}
}

When using NativeBase components use <Text/> from 'native-base'


问:
Change title in App Bar when user navigates to a different component in React
I have a React app with a bunch of components and have it structured in the following way

```<code>class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>
          <div className="App">
              <div>
                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />
              </div>
          </div>
         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;
</code>```

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?

答:
You can use following method.

Read the URL of the current page using window.location.href.Since on each page, ResponsiveDrawer is present.So from the current URL you can map title of a page in ResponsiveDrawer component.

If you are using redux then from each component you can update a global title variable in store.And then connect ResponsiveDrawer to store and show title.

Body:
I have a React app with a bunch of components and have it structured in the following way

class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>

                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />

         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?


问:
Facebook logout programmatically in Xamarin ios in Visual Studio
I have an application in IOS in which there is a Facebook Login Button.
when ever user clicks this Facebook login button My app redirects the user to the Facebook App installed in my device. So I want to logout the user from the application as soon as he leaves the facebook app and comes to my app.
i redirect the user to the facebook app using </p>

```<code>NSUrl url = NSUrl.FromString("fb://profile/<id>");
UIApplication.SharedApplication.OpenUrl(url);
</code>```

答:
I found the Facebook login documentation. As the documentation described, I think you have added the CFBundleURLTypes, like this:

```<code><key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>fb[APP_ID]</string>
  </array>
  </dict>
</array>
</code>```

It means that Facebook will trigger the openURL to return back to your app via the URLScheme you have set here.

So, you can override OpenUrl(UIApplication app, NSUrl url, NSDictionary options) in AppDelegate.cs, and the parameters url or options contain the information related to Facebook. So, you can identify the resource.

```<code>public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        Console.WriteLine(url);
        Console.WriteLine(options);

        return true;
    }
</code>```

According to this, you can do the action you want when return back from Facebook.

Body:
I have an application in IOS in which there is a Facebook Login Button.
when ever user clicks this Facebook login button My app redirects the user to the Facebook App installed in my device. So I want to logout the user from the application as soon as he leaves the facebook app and comes to my app.
i redirect the user to the facebook app using

NSUrl url = NSUrl.FromString("fb://profile/<id>");
UIApplication.SharedApplication.OpenUrl(url);

Body:
I found the Facebook login documentation. As the documentation described, I think you have added the CFBundleURLTypes, like this:

<key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>fb[APP_ID]</string>
  </array>
  </dict>
</array>

It means that Facebook will trigger the openURL to return back to your app via the URLScheme you have set here.

So, you can override OpenUrl(UIApplication app, NSUrl url, NSDictionary options) in AppDelegate.cs, and the parameters url or options contain the information related to Facebook. So, you can identify the resource.

public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        Console.WriteLine(url);
        Console.WriteLine(options);

        return true;
    }

According to this, you can do the action you want when return back from Facebook.


问:
Install Dependencies again for new React Project
I was working on a React Project and I successfully completed it. Now I started working on another project. Do I need to install these dependencies again or how can I inject dependencies and start work on my new React Project? </p>

<p>Let me know if you need more explanation. </p>

答:
if you copy over your package.json you'll have the same node_modules you have used in your previous project, so copy over the package.json and edit the fields that are specific to your new project (dependencies and devdependencies are the ones that will be installed) and do

```<code>npm i or yarn
</code>```

These commands will generate the real node_modules declared by your package.json.

whatever you prefer, thought i'd give you some more explanation so you know how this process works.

Feel free to hit me up if you got questions :) good luck coding.

Body:
I was working on a React Project and I successfully completed it. Now I started working on another project. Do I need to install these dependencies again or how can I inject dependencies and start work on my new React Project?

Let me know if you need more explanation.

Body:
if you copy over your package.json you'll have the same node_modules you have used in your previous project, so copy over the package.json and edit the fields that are specific to your new project (dependencies and devdependencies are the ones that will be installed) and do

npm i or yarn

These commands will generate the real node_modules declared by your package.json.

whatever you prefer, thought i'd give you some more explanation so you know how this process works.

Feel free to hit me up if you got questions :) good luck coding.


问:
Angular 4 return value in undefined
This is my current code. How can I return rowData value in this case?

```<code>private createRowData() {
const rowData: any[] = [];

this.http
  .get(`/assets/json/payment.json`)
  .toPromise()
  .then(response => response.json())
  .then(data => {
    data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
      });
    });
  });
return rowData;}
</code>```

I had tried to console rowData before return and it gave me undefine.

答:
You are making an asynchronous http call. The call is incomplete when the return rowData; line is executed, and hence you get undefined. To resolve this, return a promise from your function and use a .then() call to retrieve rowData from wherever you are calling your function.

```<code>private createRowData() {
  const rowData: any[] = [];

  return this.http  // <- Return promise
   .get(`/assets/json/payment.json`)
   .toPromise()
   .then(response => response.json())
   .then(data => {
     data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent
      });
      return rowData;
    });
  });
 //return rowData; // <- This is undefined because the call isn't complete yet
}

ngOnInit() {
  this.createRowData().then(data => {
    console.log(data) // <- rowData
  });
}
</code>```

Title: Angular 4 return value in undefined

Body:
This is my current code. How can I return rowData value in this case?

private createRowData() {
const rowData: any[] = [];

this.http
  .get(`/assets/json/payment.json`)
  .toPromise()
  .then(response => response.json())
  .then(data => {
    data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
      });
    });
  });
return rowData;}

I had tried to console rowData before return and it gave me undefine.

Body:
You are making an asynchronous http call. The call is incomplete when the return rowData; line is executed, and hence you get undefined. To resolve this, return a promise from your function and use a .then() call to retrieve rowData from wherever you are calling your function.

private createRowData() {
  const rowData: any[] = [];

  return this.http  // <- Return promise
   .get(`/assets/json/payment.json`)
   .toPromise()
   .then(response => response.json())
   .then(data => {
     data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent
      });
      return rowData;
    });
  });
 //return rowData; // <- This is undefined because the call isn't complete yet
}

ngOnInit() {
  this.createRowData().then(data => {
    console.log(data) // <- rowData
  });
}


问:
M-V-C Fool-proof not working and showing Uncaught error?
I installed Fool-Proof from nuGet, but its not working uncaught errors.

```<code>Install-Package foolproof -Version 0.9.4518
</code>```

As I installed it, new folder with name Clients Scripts gets added in to my project with three libraries: FoolProof Unobtrusive, FoolProof jQuery Validation and FoolProof Validation. Then I create new bundle in bundle.config and linked with my shared layout.

```<code>    public bool active { get; set; }

    [RequiredIf("active", true,ErrorMessage = "Code is Required")]
    public int Code { get; set; }
</code>```

It's not displaying validation message. Now, when I checked my console I am getting following errors:

答:
You haven't loaded required js files. Add the following in BundleConfig.js

```<code>bundles.Add(new ScriptBundle("~/bundles/mvcfoolproof").Include(
            "~/Scripts/MicrosoftAjax.js",
            "~/Scripts/MicrosoftMvcAjax.js",
            "~/Scripts/MicrosoftMvcValidation.js",
            "~/Client Scripts/mvcfoolproof.unobtrusive.min.js",
            "~/Client Scripts/MvcFoolproofJQueryValidation.min.js",
            "~/Client Scripts/MvcFoolproofValidation.min.js"));
</code>```

and then include in your View in correct order

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/mvcfoolproof")
</code>```

Body:
I installed Fool-Proof from nuGet, but its not working uncaught errors.

Install-Package foolproof -Version 0.9.4518

As I installed it, new folder with name Clients Scripts gets added in to my project with three libraries: FoolProof Unobtrusive, FoolProof jQuery Validation and FoolProof Validation. Then I create new bundle in bundle.config and linked with my shared layout.

    public bool active { get; set; }

    [RequiredIf("active", true,ErrorMessage = "Code is Required")]
    public int Code { get; set; }

It's not displaying validation message. Now, when I checked my console I am getting following errors:

Body:
You haven't loaded required js files. Add the following in BundleConfig.js

bundles.Add(new ScriptBundle("~/bundles/mvcfoolproof").Include(
            "~/Scripts/MicrosoftAjax.js",
            "~/Scripts/MicrosoftMvcAjax.js",
            "~/Scripts/MicrosoftMvcValidation.js",
            "~/Client Scripts/mvcfoolproof.unobtrusive.min.js",
            "~/Client Scripts/MvcFoolproofJQueryValidation.min.js",
            "~/Client Scripts/MvcFoolproofValidation.min.js"));

and then include in your View in correct order

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/mvcfoolproof")


问:
Select component with ability to write custom value
Hi is there any option that Material UI Select component can accept custom string? To not force user to pick only existing value? </p>

答:
No, Select component dont provide such functionality. For the same purpose I used the combination of two components: TextField for custom string input and IconMenu for select from the predefined values and set it to the input field.

And it looks almost the same:


问:
How to choose best automation Tool combination with selenium
It might be opinion based question but I am really confused about choosing automation tools combination.

Till date I have been using Selenium webdriver,maven and Java to build automation frameworks. This seems totally working fine.

Now a days I feel that many automation engineers moving to use of WebdriverJS , WebdriverIO, NodeJS etc.

Someone told me that if we build automation framework using WebdriverJS/ WebdriverIO/NodeJS, Then execution will be faster than Java.

I know that I should choose tool based on my requirements but at the same time I feel that we can not use WebdriverJS/ WebdriverIO/NodeJS in some kind of website where all elements must be located by xpath as most of elements changing class / id dynamically.

So If anyone can just give me hint about which tools to choose for which kind of website then it would be really helpful. i.e For AngularJS website Node.Js is fine for automation with selenium.

答:
As per the Selenium Official Webpage, Download Section, you can see in the Selenium Client & WebDriver Language Bindings section the following are listed :

Java

C#

Ruby

Python

Javascript (Node)

So from my personal take would be, these 5 variants which are the most widely used Selenium Clients while dealing with Automation Framework with Selenium

Documentation

Leaving aside Selinium's GitHub ducumentation, its pretty clear majority of the documentation available on internet is on Selenium (Java). It's because of Java's world wide popularity as a Language. So learning becomes easier.
Even the frequency of Selenium (Java) Client Releases would support my native view.

But, personally I have found Selinium's GitHub Documentation for all the client bindings are perfect and precise.

WebdriverIO

WebdriverIO is another variant of the Selenium Release. No doubt the WebdriverIO team have played it hard in building up the catch-up game with the Selenium Client Releases. But my take would be WebdriverIO is still evolving.

Functional Perspective:

From a functional perspective my take will be either on NodeJS or WebdriverJS. Reason is simple I still feel the Selenium-RC way is still in practice when we inject javascript into the Web Browser once the browser loads completely and then use its javascript to drive the Application Under Test within the browser.

ContentLicense: CC BY-SA 4.0


问:
Centering an ImageView in FullScreen mode
I am simply trying to center an ImageView in a FullScreen app. I've read several posts on this site on people asking what seems like same question, and I've tried everything I've read, but I can't seem to get it to center.

Here is my code for the layout. I realize there might be some overkill here to get the centering, as a result of trying various other posts. This code puts the image on the top left part of the screen.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:background="#000000"
    android:orientation="vertical" >

    <ImageView
       android:id="@+id/image"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_alignParentTop="false"
       android:layout_centerInParent="true"
       android:layout_gravity="center"
       android:layout_centerHorizontal="true"
       android:layout_centerVertical="true"
       android:adjustViewBounds="true"
       android:background="@android:color/black"
       android:contentDescription="@string/descImage"
       android:cropToPadding="false"
       android:gravity="center"
       android:src="@drawable/placeholder" />
</code>```

Here is my full screen code in AndroidManifest.xml.

```<code>android:screenOrientation="landscape"
android:theme="@style/Theme.FullScreen">
</code>```

Theme.FullScreen is defined as

```<code><style name="Theme.FullScreen" parent="@android:style/Theme.Holo">
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowFullscreen">true</item>
</style>
</code>```

Thanks.

答:
fill_parent has been replaced with match_parent in later Android versions and I've using an SVG drawable resource, so I had to modify the answers above slightly.

This is what worked for me:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.MyActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        app:srcCompat="@drawable/my_drawable" />
</android.widget.RelativeLayout>
</code>```

Body:
I am simply trying to center an ImageView in a FullScreen app. I've read several posts on this site on people asking what seems like same question, and I've tried everything I've read, but I can't seem to get it to center.

Here is my code for the layout. I realize there might be some overkill here to get the centering, as a result of trying various other posts. This code puts the image on the top left part of the screen.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:background="#000000"
    android:orientation="vertical" >

    <ImageView
       android:id="@+id/image"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:layout_alignParentTop="false"
       android:layout_centerInParent="true"
       android:layout_gravity="center"
       android:layout_centerHorizontal="true"
       android:layout_centerVertical="true"
       android:adjustViewBounds="true"
       android:background="@android:color/black"
       android:contentDescription="@string/descImage"
       android:cropToPadding="false"
       android:gravity="center"
       android:src="@drawable/placeholder" />

Here is my full screen code in AndroidManifest.xml.

android:screenOrientation="landscape"
android:theme="@style/Theme.FullScreen">

Theme.FullScreen is defined as

Thanks.

Body:
fill_parent has been replaced with match_parent in later Android versions and I've using an SVG drawable resource, so I had to modify the answers above slightly.

This is what worked for me:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.MyActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        app:srcCompat="@drawable/my_drawable" />
</android.widget.RelativeLayout>


问:
R: graphing upper and lower bounds with ggplot2
I have a dataset with three variables. One continous independent variable, one continous dependent variable, and a binary variable that catagorizes how the measurements were taken. Using ggplot, I know that I can make a scatter plot with the points colored by the catagory:

```<code>g <- ggplot(dataset, aes(independent, dependent))
g + geom_point(aes(color=catagory))
</code>```

However, I want to know if there is a way to make a graph where there is a vertical line comming up from points of catagory 0 and a vertical line going down from points of catagory 1. It would look something like this:

```<code>-   |        |    |
|   |        |    |
|   |        |    |
|   |        |    |
-   |        |  o |
|   |        |  | |
|   |    o   |  | |
|   | o  |   |  | |
-   | |  |   o  | o
|   | |  |      |
|   o |  |      |
|     |  |      |
+----|-----|-----|-----|-----|
</code>```

The reason for wanting a plot like this is that one category represents an upper bound (the points with lines going downwards) and one represents a lower bound (the points with lines going upwards). Having these lines would make it easy to visualize the area which is between these bounds, and whether a function plotted on top could accurately represent the data:

```<code>-   |        |    |
|   |        |    |
|   |        |    |
|   |        |    |
-   |        |  o |   _____
|   |        |  |_|__/
|   |    o   |_/| |
|   | o  |__/|  | |
-   | | /|   o  | o
|  _|_|/ |      |
| / o |  |      |
|/    |  |      |
+----|-----|-----|-----|-----|
</code>```

If there is any way to do this using ggplot or any other graphing library for R, I would love to know how. However, if it isn't possible, I'd be open to hearing other ways to represent this data. Simply distinguishing the catagories based on color doesn't do enough to emphasize the upper/lower bound nature of the catagories for my purposes.

答:
The following could work for you, I hope I understood the problem well.

First, generating some random data for the dataframe, as no sample data was provided. The random numbers will make the plot ugly, I hope it will look better with real data:

```<code>dataset <- data.frame (
    independent = runif(100),
    dependent = runif(100),
    catagory = floor(runif(100)*2))
</code>```

Next, find the upper or lower part of the plot (=min/max of values) based on "catagory" for every case:

```<code>dataset$end[which(dataset$catagory == 0)] <- max(dataset$dependent)
dataset$end[which(dataset$catagory == 1)] <- min(dataset$dependent)
</code>```

Now, we can plot data with geom_segment().

```<code>g <- ggplot(dataset, aes(independent, dependent, min, max))
g + geom_segment(aes(x=independent, y=dependent, xend=independent, yend=end, color=catagory))
</code>```

Note, that I also added + theme_bw() +  opts(legend.position = "none") parameters to the plot as it looked very strange with random datas.

Body:
I have a dataset with three variables. One continous independent variable, one continous dependent variable, and a binary variable that catagorizes how the measurements were taken. Using ggplot, I know that I can make a scatter plot with the points colored by the catagory:

g <- ggplot(dataset, aes(independent, dependent))
g + geom_point(aes(color=catagory))

However, I want to know if there is a way to make a graph where there is a vertical line comming up from points of catagory 0 and a vertical line going down from points of catagory 1. It would look something like this:

-   |        |    |
|   |        |    |
|   |        |    |
|   |        |    |
-   |        |  o |
|   |        |  | |
|   |    o   |  | |
|   | o  |   |  | |
-   | |  |   o  | o
|   | |  |      |
|   o |  |      |
|     |  |      |
+----|-----|-----|-----|-----|

The reason for wanting a plot like this is that one category represents an upper bound (the points with lines going downwards) and one represents a lower bound (the points with lines going upwards). Having these lines would make it easy to visualize the area which is between these bounds, and whether a function plotted on top could accurately represent the data:

-   |        |    |
|   |        |    |
|   |        |    |
|   |        |    |
-   |        |  o |   _____
|   |        |  |_|__/
|   |    o   |_/| |
|   | o  |__/|  | |
-   | | /|   o  | o
|  _|_|/ |      |
| / o |  |      |
|/    |  |      |
+----|-----|-----|-----|-----|

If there is any way to do this using ggplot or any other graphing library for R, I would love to know how. However, if it isn't possible, I'd be open to hearing other ways to represent this data. Simply distinguishing the catagories based on color doesn't do enough to emphasize the upper/lower bound nature of the catagories for my purposes.

Body:
The following could work for you, I hope I understood the problem well.

First, generating some random data for the dataframe, as no sample data was provided. The random numbers will make the plot ugly, I hope it will look better with real data:

dataset <- data.frame (
    independent = runif(100),
    dependent = runif(100),
    catagory = floor(runif(100)*2))

Next, find the upper or lower part of the plot (=min/max of values) based on "catagory" for every case:

dataset$end[which(dataset$catagory == 0)] <- max(dataset$dependent)
dataset$end[which(dataset$catagory == 1)] <- min(dataset$dependent)

Now, we can plot data with geom_segment().

g <- ggplot(dataset, aes(independent, dependent, min, max))
g + geom_segment(aes(x=independent, y=dependent, xend=independent, yend=end, color=catagory))

Note, that I also added + theme_bw() +  opts(legend.position = "none") parameters to the plot as it looked very strange with random datas.


问:
Simulate a mouse click during test. JUnit, JavaFX
In my test method, I'm trying to simulate a mouse click using Robot class:

```<code>@Test
public void testMouseEvents(){
    clickMouse();
}

private void clickMouse() {
    final boolean[] flag = {true};
    Platform.runLater(() -> {
        try {
            Robot robot = new Robot();
            robot.mouseMove(900, 500);
            robot.delay(2000);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
        } catch (Exception ignored) {

        }
        flag[0] = false;
    });

    try {
        while (flag[0]) {
            Thread.sleep(3);
        }
        Thread.sleep(20);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

But the last method throws different exeptions: sometimes it's NullPointerm but more often it's:

```<code>java.util.concurrent.RejectedExecutionException: Task     com.sun.javafx.tk.quantum.PaintRenderJob@24f7eafc rejected from  com.sun.javafx.tk.quantum.QuantumRenderer@14a5ef25[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
</code>```

Curiously, but when I simulate KeyEvent, it works perfectly. Moreover, if I delete the line where the mouse key is supposed to be pressed, the robot moves the cursor and no exception is thrown.
I suspect that the issue might concern the thread in which JavaFX application works. But still I can't figure out why it doesn't work.

答:
mimicking an actual mouse click on a Button is (I think) considerd to be a no-no (yes I have seen "developers" solving issues this way in non-JUnit issues)

The best thing to do is to de-couple the button push evenet and its action: rewrite the button click so that it will invoke a certain class which allow you to invoke that exact same code from JUnit itself. There will be a different way of plumbing the same code in the real application and in the test harnass: the command invoked will be the same which is the aim of your exercise. It will also get rid of that strange nasty exception you get which is something you can expect

Body:
In my test method, I'm trying to simulate a mouse click using Robot class:

@Test
public void testMouseEvents(){
    clickMouse();
}

private void clickMouse() {
    final boolean[] flag = {true};
    Platform.runLater(() -> {
        try {
            Robot robot = new Robot();
            robot.mouseMove(900, 500);
            robot.delay(2000);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(2000);
        } catch (Exception ignored) {

        }
        flag[0] = false;
    });

    try {
        while (flag[0]) {
            Thread.sleep(3);
        }
        Thread.sleep(20);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

But the last method throws different exeptions: sometimes it's NullPointerm but more often it's:

java.util.concurrent.RejectedExecutionException: Task     com.sun.javafx.tk.quantum.PaintRenderJob@24f7eafc rejected from  com.sun.javafx.tk.quantum.QuantumRenderer@14a5ef25[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)

Curiously, but when I simulate KeyEvent, it works perfectly. Moreover, if I delete the line where the mouse key is supposed to be pressed, the robot moves the cursor and no exception is thrown.
I suspect that the issue might concern the thread in which JavaFX application works. But still I can't figure out why it doesn't work.


问:
video player studio mp4
I would like to play a video in a dialog window, but it doesn't work. The video is instead of the "raw" directory. I don't know where I'm wrong. Can you help me Please?
There is the code

```<code>ImageButton video_player = (ImageButton) findViewById(R.id.img_btt_on_ear_watch);
        video_player.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.layout_video_player);

                String filePlace = "android.resource://" + getPackageName() + "/" + R.raw.grado_video_cuffie_making;
                VideoView videoV = (VideoView) findViewById(R.id.vv_video_player);
                Uri videoURI = Uri.parse((String) filePlace);
                videoV.setVideoURI(videoURI); //this is the 128 raw
                videoV.setMediaController(new MediaController(context));
                videoV.start();

                ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.img_btt_vv_close);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.show();

            }
        });
</code>```

There is the Logcat

```<code>11-15 10:40:50.666 3893-3893/com.huawei.headphones.huaweimusic E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.huawei.headphones.huaweimusic, PID: 3893
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setVideoURI(android.net.Uri)' on a null object reference
                                                                                at com.huawei.headphones.huaweimusic.Activity_Cuffia1$1.onClick(Activity_Cuffia1.java:128)
                                                                                at android.view.View.performClick(View.java:5610)
                                                                                at android.view.View$PerformClick.run(View.java:22265)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

答:
Use this

```<code> VideoView videoV = (VideoView) dialog.findViewById(R.id.vv_video_player);
</code>```

insted of this

```<code>VideoView videoV = (VideoView) findViewById(R.id.vv_video_player);
</code>```

Title: video player studio mp4

Body:
I would like to play a video in a dialog window, but it doesn't work. The video is instead of the "raw" directory. I don't know where I'm wrong. Can you help me Please?
There is the code

ImageButton video_player = (ImageButton) findViewById(R.id.img_btt_on_ear_watch);
        video_player.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.layout_video_player);

                String filePlace = "android.resource://" + getPackageName() + "/" + R.raw.grado_video_cuffie_making;
                VideoView videoV = (VideoView) findViewById(R.id.vv_video_player);
                Uri videoURI = Uri.parse((String) filePlace);
                videoV.setVideoURI(videoURI); //this is the 128 raw
                videoV.setMediaController(new MediaController(context));
                videoV.start();

                ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.img_btt_vv_close);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.show();

            }
        });

There is the Logcat

11-15 10:40:50.666 3893-3893/com.huawei.headphones.huaweimusic E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.huawei.headphones.huaweimusic, PID: 3893
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setVideoURI(android.net.Uri)' on a null object reference
                                                                                at com.huawei.headphones.huaweimusic.Activity_Cuffia1$1.onClick(Activity_Cuffia1.java:128)
                                                                                at android.view.View.performClick(View.java:5610)
                                                                                at android.view.View$PerformClick.run(View.java:22265)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Body:
Use this

 VideoView videoV = (VideoView) dialog.findViewById(R.id.vv_video_player);

insted of this

VideoView videoV = (VideoView) findViewById(R.id.vv_video_player);


问:
how to check for localStorage value, before page loads
I have a function named validateLogin in index.html where I set the local-Storage value key userID, and on return true of this function, I load other web-page (home.html) where I used this local-Storage value userID, but now, I need to restrict user and redirect them to signup.html, if local-Storage is empty when home.html is accessed directly without the validateLogin function or localStorage is empty ,
I tried below but its not working, what am I doing wrong?

index.html

```<code><form id="login_form" name="login" action="home.html" method=POST onsubmit="return validateLogin()">
<script>
  var userid;
  function validateLogin() {
    userid = document.getElementById('user_id').value;
    localStorage.setItem("userID",userid);
    var passid = document.getElementById('pass_id').value;
    if ((userid.length < 3) || (passid.length < 6)) {
      document.getElementById('user_error').setAttribute("style", "color:red")
      document.getElementById('user_error').innerHTML = "invalid username/password.";
      return false;
    }
    preventBack();
    return true;
  }
</script>
</code>```

home.html

```<code><body>
  <!--Navigation bar-->
  <div id="nav-placeholder">
  </div>
  <!--end of Navigation bar-->

<script>
  window.onload = checkUser;
  function checkUser(){
    if(localStorage.getItem("userID") === "") {
      window.location ="signup.html";
    }
    else {
      $("#nav-placeholder").load("nav_auth.html");
    }
  };
  </script>
</body>
</code>```

答:
```<code>localStorage.getItem("toto")
</code>```

returns null if the key is not found, so you should check for null instead of empty string

Body:
I have a function named validateLogin in index.html where I set the local-Storage value key userID, and on return true of this function, I load other web-page (home.html) where I used this local-Storage value userID, but now, I need to restrict user and redirect them to signup.html, if local-Storage is empty when home.html is accessed directly without the validateLogin function or localStorage is empty ,
I tried below but its not working, what am I doing wrong?

index.html

<form id="login_form" name="login" action="home.html" method=POST onsubmit="return validateLogin()">

home.html

Body:
localStorage.getItem("toto")

returns null if the key is not found, so you should check for null instead of empty string


问:
Spring Boot - Let Hibernate initialize all datasources of AbstractRoutingDataSource
I've implemented the AbstractRoutingDataSource in order to horizontally partition my data [1]. I rely on Hibernates functionality to create and update the database schema. This works fine for the first datasource, which is resolved by the determineCurrentLookupKey() declared in AbstractRoutingDataSource.

Is there a way to apply the schema generation/update to the other datasources as well?

I've found the classes SchemaExport and SchemaUpdate respectively, that are capable of the required functionality. However, both require an instance of org.hibernate.boot.MetaData, which I don't how to obtain.

(I'm using Spring Boot in version 1.4.2.RELEASE.)

[1] https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

Thanks!

答:
I got the same issue and found a solution using the SchemaExport class of hibernate.
For each DataSourceEnum you can manually initialize the datasource.

here is my detailed answer to my own issue discription


问:
Make input type file required based on condition in AngularJS
I am receiving a JSON data from backend like these

```<code>{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}
</code>```

And in the html i am populating a form by ng-repeat

```<code><tr data-ng-repeat="choice in choices track  by $index">
    <td>{{choice.number}}</td>
    <td><p>{{choice.short_text}}</p></td>
    <td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
    <td><input type="checkbox"  ng-model="choice.include"></td>
    <td><input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">
    </td>
</tr>
</code>```

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

答:
You can use "ng-required"

For documentation you could read this: https://docs.angularjs.org/api/ng/directive/ngRequired

Like this

```<code><input name="myInput" ng-model="myInput" ng-required="myVar == 2">

//If photo is true required will be true else false
<input name="myInput" ng-model="myInput" ng-required="_photo">

<input name="myInput" ng-model="myInput" ng-required="choice.is_photo">

//Or use some function which returns boolean
<input name="myInput" ng-model="myInput" ng-required="isRequired(choice)">

//This is how you would use it with form and stop form from submittion
<form ng-app="myApp" ng-controller="validateCtrl"
      ng-init="isRequired=true"
      name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        Username: <input type="text" name="user" ng-model="user"
                         ng-required="isRequired">
        Email : <input type="email" name="email" ng-model="email" required>
        <input type="submit" ng-click="isRequired=!isRequired;" />
</form>

    <script>
       var app = angular.module('myApp', []);
       app.controller('validateCtrl', function($scope) {
           $scope.user = 'John Doe';
           $scope.email = 'john.doe@gmail.com';
           $scope.submit = () => {console.log("s");}
       });
    </script>
</code>```

Body:
I am receiving a JSON data from backend like these

{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}

And in the html i am populating a form by ng-repeat

    {{choice.number}}

{{choice.short_text}}

    <input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required>
    <input type="checkbox"  ng-model="choice.include">
    <input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

Body:
You can use "ng-required"

For documentation you could read this: https://docs.angularjs.org/api/ng/directive/ngRequired

Like this

<input name="myInput" ng-model="myInput" ng-required="myVar == 2">

//If photo is true required will be true else false
<input name="myInput" ng-model="myInput" ng-required="_photo">

<input name="myInput" ng-model="myInput" ng-required="choice.is_photo">

//Or use some function which returns boolean
<input name="myInput" ng-model="myInput" ng-required="isRequired(choice)">

//This is how you would use it with form and stop form from submittion
<form ng-app="myApp" ng-controller="validateCtrl"
      ng-init="isRequired=true"
      name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        Username: <input type="text" name="user" ng-model="user"
                         ng-required="isRequired">
        Email : <input type="email" name="email" ng-model="email" required>
        <input type="submit" ng-click="isRequired=!isRequired;" />
</form>

    <script>
       var app = angular.module('myApp', []);
       app.controller('validateCtrl', function($scope) {
           $scope.user = 'John Doe';
           $scope.email = 'john.doe@gmail.com';
           $scope.submit = () => {console.log("s");}
       });
    </script>


问:
Compile-time reversal of parameter-pack expansion
In the following class template I want to initalize the member-array b with the values of the parameter-pack vv in reverse-oder!

```<code>template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv) : b{vv...,} // how to initialize member b with pack expansion v... in reverse order
    {
    }
private:
    std::byte b[sizeof(T)];
};
</code>```

I can't imagine how to reverse the parameter-pack expansion in a form, that it is as well usable in an initializer list.

答:
given that b is a non static data member, the following more compact version may turn out equivalent once optimized(*):

```<code>template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv){ auto rb = std::rbegin(b); ((*rb++ = vv),...); }
private:
    char b[sizeof(T)];
};
</code>```

(*) unless, Jarod42's solution ends up with the already reversed B's in data section when constexpr...

EDIT: it looks like both trunk clang and gcc are so smart to place the reversed B's in the data section both in Jarod42's code and mine !

Body:
In the following class template I want to initalize the member-array b with the values of the parameter-pack vv in reverse-oder!

template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv) : b{vv...,} // how to initialize member b with pack expansion v... in reverse order
    {
    }
private:
    std::byte b[sizeof(T)];
};

I can't imagine how to reverse the parameter-pack expansion in a form, that it is as well usable in an initializer list.

Body:
given that b is a non static data member, the following more compact version may turn out equivalent once optimized(*):

template<typename T>
struct Test {
public:
    template<typename... B>
    explicit Test(B... vv){ auto rb = std::rbegin(b); ((*rb++ = vv),...); }
private:
    char b[sizeof(T)];
};

(*) unless, Jarod42's solution ends up with the already reversed B's in data section when constexpr...

EDIT: it looks like both trunk clang and gcc are so smart to place the reversed B's in the data section both in Jarod42's code and mine !


问:
Detect circular dependencies in project
Last time i found in my project problem with circular dependencies. I resolve my problem but, i would like avoid this in future.
I think about plugin which found circular dependencies in my all project and give me feedback.

Example:

File a.js:

```<code>var functionFromA= require("./b.js");
console.log("file a", functionFromA);
module.exports = {functionFromA: functionFromA};
</code>```

File b.js:

```<code>var functionFromB = require("./c.js");
console.log("file b", functionFromB );
module.exports = {functionFromB : functionFromB };
</code>```

File c.js:

```<code>var functionFromC = require("./a.js");
console.log("file c", functionFromC );
module.exports = {functionFromC : functionFromC }
</code>```

When i run file a.js i see in console:

file c {}

file b { functionFromC: {} }

file a { functionFromB: { functionFromC: {} } }

I found "Circular Dependency Plugin" in npm but i don't know how use it?
May be someone has similar problem and found a solution?

答:
You can find this other tool useful: https://www.npmjs.com/package/madge

is very easy to use: madge --circular [directory] give you a list of circular dependencies in your code located inside [directory]. It can also generate a graph image.

Title: Detect circular dependencies in project

Body:
Last time i found in my project problem with circular dependencies. I resolve my problem but, i would like avoid this in future.
I think about plugin which found circular dependencies in my all project and give me feedback.

Example:

File a.js:

var functionFromA= require("./b.js");
console.log("file a", functionFromA);
module.exports = {functionFromA: functionFromA};

File b.js:

var functionFromB = require("./c.js");
console.log("file b", functionFromB );
module.exports = {functionFromB : functionFromB };

File c.js:

var functionFromC = require("./a.js");
console.log("file c", functionFromC );
module.exports = {functionFromC : functionFromC }

When i run file a.js i see in console:

file c {}

file b { functionFromC: {} }

file a { functionFromB: { functionFromC: {} } }

I found "Circular Dependency Plugin" in npm but i don't know how use it?
May be someone has similar problem and found a solution?


问:
eBay API Oauth Refresh Token in PHP
Im currently trying to integrate with the eBay API, i have managed to integrate it manually and put in the oAuth key manually to pull data.

What i cannot for the life of me get working is the oAuth refresh token, i keep getting the most indescript error messages from the API just saying "There was an error, please try again".

My current code is below -

```<code>    function GetTokens($sessionid){
            // Create headers to send with CURL request.
$headers = array
(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic REMOVED'
);

$xml =  '<?xml version="1.0" encoding="utf-8"?>'.
    '<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">'.
         '<SessionID>' . $sessionid . '</SessionID>'.

   '</FetchTokenRequest>';

// Send request to eBay and load response in $response
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $this->api_server .
"/identity/v1/oauth2/token");
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
    print_r($response);
}
</code>```

Any help would be greatly appreciated !

答:
you could at least stop lying to the API. you tell the api i'm sending you some data in application/x-www-urlencoded format, and then sending them data in application/xml format! maybe that's why you're getting the cryptic error.

you should also complain on their bugtracker, if they have one, about this error, the error should be more descriptive (for example, failed to parse the request body as appliation/x-www-urlencoded, malformed syntax along with a http 400 Bad Request response would be good)

Title: eBay API Oauth Refresh Token in PHP

Body:
Im currently trying to integrate with the eBay API, i have managed to integrate it manually and put in the oAuth key manually to pull data.

What i cannot for the life of me get working is the oAuth refresh token, i keep getting the most indescript error messages from the API just saying "There was an error, please try again".

My current code is below -

    function GetTokens($sessionid){
            // Create headers to send with CURL request.
$headers = array
(
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic REMOVED'
);

$xml =  '<?xml version="1.0" encoding="utf-8"?>'.
    '<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">'.
         '<SessionID>' . $sessionid . '</SessionID>'.

   '</FetchTokenRequest>';

// Send request to eBay and load response in $response
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $this->api_server .
"/identity/v1/oauth2/token");
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
    print_r($response);
}

Any help would be greatly appreciated !


问:
IntelliJ IDEA 2017.2.5: Cannot determine embedded database driver
Since some months I'm getting a lot of false positives when starting my Spring application in IntelliJ 2017.2.5. When starting it shows the error Cannot determine embedded database driver class for database type NONE. I just have to give it some additional tries and it will work. Often opening the appliation.properties in the IDE also helps (but might be coincidence). This happens to me (Linux) and also a friend working with the same project (Mac). Anyone else experienced that?

答: The latest updated of IntelliJ seems to fix the issue: Bug IDEA-178438 application properties not set when starting Spring Boot service in IDEA (https://youtrack.jetbrains.com/issue/IDEA-178438)


问:
Python: Cut off the last word of a sentence?
What's the best way to slice the last word from a block of text?

I can think of

Split it to a list (by spaces) and removing the last item, then reconcatenating the list.

Use a regular expression to replace the last word.

I'm currently taking approach #1, but I don't know how to concatenate the list...

```<code>content = content[position-1:position+249] # Content
words = string.split(content, ' ')
words = words[len[words] -1] # Cut of the last word
</code>```

Any code examples are much appreciated.

答:
Get last index of space and splice the string</p>

```<code>>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'
</code>```

Body:
What's the best way to slice the last word from a block of text?

I can think of

Split it to a list (by spaces) and removing the last item, then reconcatenating the list.

Use a regular expression to replace the last word.

I'm currently taking approach #1, but I don't know how to concatenate the list...

content = content[position-1:position+249] # Content
words = string.split(content, ' ')
words = words[len[words] -1] # Cut of the last word

Any code examples are much appreciated.

Body:
Get last index of space and splice the string

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'


问:
this._form is null error with ScriptManager and Ajax Control Toolkit
I'm using the Ajax Control Toolkit with .NET in VS2008 to put a Rating control on my page. I've got the scriptmanager on the page and the rating control works in Chrome and IE but not Firefox. In Firefox it gives me this error "this._form is null". I've got no other scripts included on the page. There are a couple included in the master page but they are closed with </script>. I've tried using ToolkitScriptManager but it hasn't changed anything.

```<code>   <form id="aspnetForm" runat="server"><ajaxToolkit:ToolkitScriptManager id="ScriptManager1" runat="server" EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePartialRendering="true" SupportsPartialRendering="true" />
<div id="main" align='center'>

<div id="inside">
<div id="nav">
    <div id="photoCount"><label id="lblPhotoCount" runat="server"></label></div>
    <div id="photoNav">
        <a class="nav_a" runat="server" id="previouslink" href="">Previous</a><a class="nav_a" runat="server" id="nextlink" href="">Next</a>
    </div>
    <div class="clear"></div>
</div>
<div id="divBrowseBox" runat="server">
    <div id='divPicHeader' runat='server' style="z-index: 2998">
    </div>
</div>

<div id="likeArea">
  <iframe id="likeIframe" runat="server" src="" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:80px;" allowTransparency="true"></iframe>
</div>

<div id="ratingArea">
    <asp:updatepanel id="UpdatePanel1" runat="server">
        <ContentTemplate>
        <asp:HiddenField ID="hdnCurrentPhotoID" runat="server" />
        <asp:HiddenField ID="hdnCurrentRating" runat="server" />
        <asp:HiddenField ID="hdnAvgRating" runat="server" />
        <asp:HiddenField ID="hdnTotalVotes" runat="server" />
        <asp:HiddenField ID="hdnAddRating" runat="server" />

        <asp:Label ID="lblYourVote" runat="server" Font-Size="12px" Text="Rate This Photo!"></asp:Label>
        <div id="starbox">
        <div id="stars">
        <ajaxToolkit:Rating ID="Rating1" runat="server"
            CurrentRating="3"
            MaxRating="5"
            StarCssClass="ratingStar"
            WaitingStarCssClass="savedRatingStar"
            FilledStarCssClass="filledRatingStar"
            EmptyStarCssClass="emptyRatingStar"
            OnChanged="Rating1_Changed"
            AutoPostBack="true"
            BehaviorID="rbid"
        >
        </ajaxToolkit:Rating>
        </div>
        </div>
        <div style="clear: both;"></div>
        <asp:Label ID="lblTotalVotes" runat="server" Font-Size="10px" Text=""></asp:Label>

        </ContentTemplate>
    </asp:updatepanel>
</div>
<div style="clear: both;"></div>

</div>

</div>
</form>
</code>```

Updated with code. There are only some styles above the form and that is all.

答: I answered my own question. I was trying to create a form within a form and it wasn't working. I didn't get any indication of that from the error messages but eventually figured it out. </p>

Body:
I'm using the Ajax Control Toolkit with .NET in VS2008 to put a Rating control on my page. I've got the scriptmanager on the page and the rating control works in Chrome and IE but not Firefox. In Firefox it gives me this error "this._form is null". I've got no other scripts included on the page. There are a couple included in the master page but they are closed with </script>. I've tried using ToolkitScriptManager but it hasn't changed anything.

   <form id="aspnetForm" runat="server"><ajaxToolkit:ToolkitScriptManager id="ScriptManager1" runat="server" EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePartialRendering="true" SupportsPartialRendering="true" />

        PreviousNext

    <asp:updatepanel id="UpdatePanel1" runat="server">
        <ContentTemplate>
        <asp:HiddenField ID="hdnCurrentPhotoID" runat="server" />
        <asp:HiddenField ID="hdnCurrentRating" runat="server" />
        <asp:HiddenField ID="hdnAvgRating" runat="server" />
        <asp:HiddenField ID="hdnTotalVotes" runat="server" />
        <asp:HiddenField ID="hdnAddRating" runat="server" />

        <asp:Label ID="lblYourVote" runat="server" Font-Size="12px" Text="Rate This Photo!"></asp:Label>

        <ajaxToolkit:Rating ID="Rating1" runat="server"
            CurrentRating="3"
            MaxRating="5"
            StarCssClass="ratingStar"
            WaitingStarCssClass="savedRatingStar"
            FilledStarCssClass="filledRatingStar"
            EmptyStarCssClass="emptyRatingStar"
            OnChanged="Rating1_Changed"
            AutoPostBack="true"
            BehaviorID="rbid"
        >
        </ajaxToolkit:Rating>

        <asp:Label ID="lblTotalVotes" runat="server" Font-Size="10px" Text=""></asp:Label>

        </ContentTemplate>
    </asp:updatepanel>

</form>

Updated with code. There are only some styles above the form and that is all.


问:
Reading Group Conversations from Microsoft Graph using an application permission doesn't seem to be supported
We're building a mashup app that allows you to view data and information from multiple sources in one place.

To do this we need to get all conversations in O365 Groups and have been exploring how to build a daemon job.

According to the documentation this should be supported since we have the permissions Group.Read.All and Group.ReadWrite.All.

However it seems like Groups Conversations is an exception to what you can read with an application permission with Microsoft Graph which is mentioned in a small note on the subscriptions page:

We get permissions errors when calling the API with a application permission using a certificate (fetching groups and other data works fine) so this seems to be a limitation.

This also seems to affect fetching threads which doesn't seem to have any notes regarding application permissions at all since we can't fetch those either.

Does anybody know if there is a workaround or if we're doing something wrong here?

(NOTE: This seems to be a related question: Microsoft Graph API : "403 forbidden" error when getting groups conversations but I'd like to have some input from Microsoft on this)

答:
Microsoft confirmed this as being an issue in the Microsoft Graph through our partner programme.

Until fixed by Microsoft this means that there is no good solution except workarounds as of now.


问:
javascript filesize function glitch with bytes between 1000 and 1024
So I created this function, it adapts the amount of bytes to the right binary unit. The problem I am having is that whenever a file is between 1000 and 1024 bytes it shows up as: 1.02e+3 KB. Am I doing something wrong or did I forgot to catch all exception? Thanks for the help.

```<code>var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];

function grid_filesizeCellClientTemplate(bytes) {
    if (!bytes)
        return "";

    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    var size = (bytes / Math.pow(1024, Math.floor(e)));
    var unit = ce_sizeSuffixes[e];
    //bug with a size >= 1000 and < 1024
    return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';
}
</code>```

Solution:

```<code>var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];
function grid_filesizeCellClientTemplate(bytes) {
if (!bytes)
    return "";

var e = Math.floor(Math.log(bytes) / Math.log(1024));
var size = (bytes / Math.round(size * 1000) / 1000));
var unit = ce_sizeSuffixes[e];
//bug with a size >= 1000 and < 1024
return '<span title="' + bytes + ' bytes">' + (e === 0 ? size : size.toPrecision(3)) + unit + '</span>';
</code>```

答:
toPrecision outputs the number formatted to the given number of significant digits. 1010, or any number between 1000 and 1024 in your case, has 4 significant digits but you tell the code to give 3. Hence, 1.01e+3.

If you want to round the number to 3 decimal places, consider Math.round(size*1000)/1000 instead.

Body:
So I created this function, it adapts the amount of bytes to the right binary unit. The problem I am having is that whenever a file is between 1000 and 1024 bytes it shows up as: 1.02e+3 KB. Am I doing something wrong or did I forgot to catch all exception? Thanks for the help.

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];

function grid_filesizeCellClientTemplate(bytes) {
    if (!bytes)
        return "";

    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    var size = (bytes / Math.pow(1024, Math.floor(e)));
    var unit = ce_sizeSuffixes[e];
    //bug with a size >= 1000 and < 1024
    return '' + (e === 0 ? size : size.toPrecision(3)) + unit + '';
}

Solution:

var ce_sizeSuffixes = [" B", " KB", " MB", " GB", " TB"];
function grid_filesizeCellClientTemplate(bytes) {
if (!bytes)
    return "";

var e = Math.floor(Math.log(bytes) / Math.log(1024));
var size = (bytes / Math.round(size * 1000) / 1000));
var unit = ce_sizeSuffixes[e];
//bug with a size >= 1000 and < 1024
return '' + (e === 0 ? size : size.toPrecision(3)) + unit + '';


问:
How to create a histogram with fixed bin width on percentage scale reflective for each facet?
I would like to create a histogram where the y-axis shows the percentage per facet in ggplot2. I have seen several similar questions but some answers seem outdated or they show the percentage of all observations rather than per facet.

I tried this:

```<code>library(ggplot2)
library(scales)

ggplot(mtcars, aes(mpg))+
    facet_grid(cyl ~ am)+
    stat_count(aes(y=..prop..)) +
    theme_bw()+
    scale_y_continuous(labels = percent_format())
</code>```

Which seems to work, except that the binwidth is not fixed. Facets with few observations have large bars.

How could I fix the binwidth?

EDIT: Solution adapted from ACNB
I overlooked that before and I just saw that Andrey Kolyadin was quicker to provide a more concise solution.

```<code>binwidth <- 1
mtcars.stats <- mtcars %>%
    group_by(cyl, am) %>%
    mutate(bin = cut(mpg, breaks=seq(0,35, binwidth),
                     labels = seq(0 + binwidth, 35, binwidth)-(binwidth/2)),
           n = n()) %>%
    group_by(cyl, am, bin) %>%
    summarise(p = n()/n[1]) %>%
    ungroup() %>%
    mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +
    geom_col() +
    facet_grid(cyl~am)+
    theme_bw()+
    scale_y_continuous(labels = percent_format())
</code>```

答:
have you tried adding the geom_histogram and stat argument, something like ...

```<code>p <- ggplot(mtcars, aes(mpg))
p <- p + geom_histogram(stat = 'bin')
p <- p + facet_grid(cyl ~ am)
p <- p + stat_count(aes(y=..prop..))
p <- p +   theme_bw()
p <- p +   scale_y_continuous(labels = percent_format())
p
</code>```

Body:
I would like to create a histogram where the y-axis shows the percentage per facet in ggplot2. I have seen several similar questions but some answers seem outdated or they show the percentage of all observations rather than per facet.

I tried this:

library(ggplot2)
library(scales)

ggplot(mtcars, aes(mpg))+
    facet_grid(cyl ~ am)+
    stat_count(aes(y=..prop..)) +
    theme_bw()+
    scale_y_continuous(labels = percent_format())

Which seems to work, except that the binwidth is not fixed. Facets with few observations have large bars.

How could I fix the binwidth?

EDIT: Solution adapted from ACNB
I overlooked that before and I just saw that Andrey Kolyadin was quicker to provide a more concise solution.

binwidth <- 1
mtcars.stats <- mtcars %>%
    group_by(cyl, am) %>%
    mutate(bin = cut(mpg, breaks=seq(0,35, binwidth),
                     labels = seq(0 + binwidth, 35, binwidth)-(binwidth/2)),
           n = n()) %>%
    group_by(cyl, am, bin) %>%
    summarise(p = n()/n[1]) %>%
    ungroup() %>%
    mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +
    geom_col() +
    facet_grid(cyl~am)+
    theme_bw()+
    scale_y_continuous(labels = percent_format())

Body:
have you tried adding the geom_histogram and stat argument, something like ...

p <- ggplot(mtcars, aes(mpg))
p <- p + geom_histogram(stat = 'bin')
p <- p + facet_grid(cyl ~ am)
p <- p + stat_count(aes(y=..prop..))
p <- p +   theme_bw()
p <- p +   scale_y_continuous(labels = percent_format())
p


问:
Path sum in a Directed Acyclic Graph
Given a directed acyclic graph, determine if any branch returns a path sum that equals 22. In the example below, such a path can be found at (7 + 8 + 3 + 4). What is the run time complexity of such an algorithm?

```<code>      7
     / \
    8   6
   / \ / \
  2   3   8
 /   /    \
5   4      1
</code>```

This is what I came up with.

```<code>public boolean hasPathToSum(Node root, int sum)
{
    if (root == null) return false;
    if (root.value == sum && (root.left == null && root.right == null))
        return true;

    return hasPathToSum(root.left, sum - root.value) || hasPathToSum(root.right, sum - root.value);
}
</code>```

Any better suggestions on improving the complexity?

答:
If all values in the graph are nonnegative you can solve this problem in O((n + m) * sum) using memoization. In your case sum is fixed and equal to 22, so the solution is effectively linear.

Memoization is a technique not to compute the same value twice. Note that hasPathToSum(root, sum) is a pure function: its result depends only on arguments, it has no side effects. It means that we can save the result of this function into some map (root, sum) -> bool (probably a HashMap or a TreeMap in Java, I cannot say precisely as I'm not familiar with the language).

Now, when calling the function, we check if its arguments are presented in the map. If yes, just return saved value. Otherwise calculate it, save into the map and return. This way the function will be really computed only once for any set of arguments.

The last optimization works only with nonnegative values. Note that the result of hasPathToSum(v, x) is false if x < 0. So you can make a cutoff: just return false immediately if this is the case. This optimization ensures that, for each node, hasPathToSum will be called with at most 23 different sum values, yielding the aforementioned running time.

Title: Path sum in a Directed Acyclic Graph

Body:
Given a directed acyclic graph, determine if any branch returns a path sum that equals 22. In the example below, such a path can be found at (7 + 8 + 3 + 4). What is the run time complexity of such an algorithm?

      7
     / \
    8   6
   / \ / \
  2   3   8
 /   /    \
5   4      1

This is what I came up with.

public boolean hasPathToSum(Node root, int sum)
{
    if (root == null) return false;
    if (root.value == sum && (root.left == null && root.right == null))
        return true;

    return hasPathToSum(root.left, sum - root.value) || hasPathToSum(root.right, sum - root.value);
}

Any better suggestions on improving the complexity?


答:
localStorage.getItem returns null if the key doesn't exist, while you are doing a strict equality check on the empty string.

Replace

```<code>if (localStorage.getItem("userID") === "")
</code>```

with

```<code>if (!localStorage.getItem("userID"))
</code>```

Title: how to check for localStorage value, before page loads

Body:
localStorage.getItem returns null if the key doesn't exist, while you are doing a strict equality check on the empty string.

Replace

if (localStorage.getItem("userID") === "")

with

if (!localStorage.getItem("userID"))


问:
Spotlight Search UserActivity is crashing
I am getting crash logs from Crashlytics for Spotlight Search which is implemented by using CoreSpotlight framework and UserActivity. I am not able find reason behind crash. Please help

答: I resolved this issue by calling activity in Main thread.</p>


问:
How to set Robots.txt or Apache to allow crawlers only at certain hours?
As traffic is distributed unevenly over 24 hours, I would like to disallow crawlers during peek hours and allow them at non-busy hours.

Is there a method to achieve this?

edit:
thanks for all the good advice.

This is another solution we found.

2bits.com has an article on setting IPTables firewall to limit the number of connections from certain IP addresses.

the article

the setting of IPTables:

Using connlimit

In newer Linux kernels, there is a connlimit module for iptables. It can be used like this:

iptables -I INPUT -p tcp -m connlimit --connlimit-above 5 -j REJECT

This limits connections from each IP address to no more than 5 simultaneous connections. This sort of "rations" connections, and prevents crawlers from hitting the site simultaneously.
*

答:
You cannot determine what time the crawlers do their work, however with Crawl-delay you may be able to reduce the frequency in which they request pages.  This can be useful to prevent them from rapidly requesting pages.

For Example:

```<code>User-agent: *
Crawl-delay: 5
</code>```

Body:
You cannot determine what time the crawlers do their work, however with Crawl-delay you may be able to reduce the frequency in which they request pages.  This can be useful to prevent them from rapidly requesting pages.

For Example:

User-agent: *
Crawl-delay: 5


问:
Draggable element scrolling another div with overflow
Hi I have problem with draggable event.
I can't scroll another div with helper.

This is example code, I wrote:

$('.test1').draggable({
  helper: 'clone',
  scroll: false,
  appendTo: '.scrolled-box',
  containment: '.test2',
  start: function(e, ui) {
    $(ui.helper).css({
      'opacity': '0.6'
    });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 250px;
  height: 100px;
  background-color: #ffecc9;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid #333;
}

.test1 {
  width: 200px;
  height: 20px;
  border: 1px solid #333;
  background: #33cccc;
  border-radius: 3px;
  margin: auto;
}

.test1>p {
  font-size: 12px;
  font-weight: bold;
  margin: 0 auto;
  display: block;
  width: 100%;
  text-align: center;
  color: #333;
  padding: 2px 0;
}

.test2 {
  margin-top: 15px;
  width: 250px;
  height: 60px;
  overflow: auto;
  background-color: #333;
  border-radius: 3px;
  color: white;
}

.scrolled-box {
  height: 500px;
  width: 100%;
  text-align: center;
  position: relative;
}

span {
  position: absolute;
  bottom: 10px;
}</code>```

      drag me

      scrolled box

```

Please see this: JsFiddle

I did something wrong, and I don't know what.
Please help me to lvl up my expirience with draggable (jquery ui).
Im looking for solution without extra plugins. Just jQuery Ui.

答:
You need to handle droppable event as well

$('.test1').draggable({
  scroll: true,
  helper: 'clone',
  revert: true,
  appendTo: '.scrolled-box',
  containment: '.test2',
  start: function (e, ui) {
   $(ui.helper).css({'opacity': '0.6'});
  }
});

$('.test2').droppable({
  accept: ".test1",
  drop: function( event, ui ) {
    ui.helper.clone().appendTo('.scrolled-box');
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 250px;
  height: 300px;
  background-color: #ffecc9;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid #333;
}
.test1 {
  width: 200px;
  height: 20px;
  border: 1px solid #333;
  background: #33cccc;
  border-radius: 3px;
  margin: auto;
}
.test1 > p {
  font-size: 12px;
  font-weight: bold;
  margin: 0 auto;
  display: block;
  width: 100%;
  text-align: center;
  color: #333;
  padding: 2px 0;
}
.test2 {
  margin-top: 15px;
  width: 250px;
  height: 160px;
  overflow: auto;
  background-color: #333;
  border-radius: 3px;
  color: white;
  position: relative;
}
.scrolled-box {
  height: 600px;
  width: 100%;
  text-align: center;
  position: relative;
}
span {
  position: absolute;
  bottom: 10px;
}</code>```

      drag me

      scrolled box

```

Body:
Hi I have problem with draggable event.
I can't scroll another div with helper.

This is example code, I wrote:

$('.test1').draggable({
  helper: 'clone',
  scroll: false,
  appendTo: '.scrolled-box',
  containment: '.test2',
  start: function(e, ui) {
    $(ui.helper).css({
      'opacity': '0.6'
    });
  }
});

.container {
  width: 250px;
  height: 100px;
  background-color: #ffecc9;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid #333;
}

.test1 {
  width: 200px;
  height: 20px;
  border: 1px solid #333;
  background: #33cccc;
  border-radius: 3px;
  margin: auto;
}

.test1>p {
  font-size: 12px;
  font-weight: bold;
  margin: 0 auto;
  display: block;
  width: 100%;
  text-align: center;
  color: #333;
  padding: 2px 0;
}

.test2 {
  margin-top: 15px;
  width: 250px;
  height: 60px;
  overflow: auto;
  background-color: #333;
  border-radius: 3px;
  color: white;
}

.scrolled-box {
  height: 500px;
  width: 100%;
  text-align: center;
  position: relative;
}

span {
  position: absolute;
  bottom: 10px;
}

      drag me

      scrolled box

Please see this: JsFiddle

I did something wrong, and I don't know what.
Please help me to lvl up my expirience with draggable (jquery ui).
Im looking for solution without extra plugins. Just jQuery Ui.

Body:
You need to handle droppable event as well

$('.test1').draggable({
  scroll: true,
  helper: 'clone',
  revert: true,
  appendTo: '.scrolled-box',
  containment: '.test2',
  start: function (e, ui) {
   $(ui.helper).css({'opacity': '0.6'});
  }
});

$('.test2').droppable({
  accept: ".test1",
  drop: function( event, ui ) {
    ui.helper.clone().appendTo('.scrolled-box');
    }
});

.container {
  width: 250px;
  height: 300px;
  background-color: #ffecc9;
  padding: 10px;
  border-radius: 3px;
  border: 1px solid #333;
}
.test1 {
  width: 200px;
  height: 20px;
  border: 1px solid #333;
  background: #33cccc;
  border-radius: 3px;
  margin: auto;
}
.test1 > p {
  font-size: 12px;
  font-weight: bold;
  margin: 0 auto;
  display: block;
  width: 100%;
  text-align: center;
  color: #333;
  padding: 2px 0;
}
.test2 {
  margin-top: 15px;
  width: 250px;
  height: 160px;
  overflow: auto;
  background-color: #333;
  border-radius: 3px;
  color: white;
  position: relative;
}
.scrolled-box {
  height: 600px;
  width: 100%;
  text-align: center;
  position: relative;
}
span {
  position: absolute;
  bottom: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
  <div class="test1">
    <p>
      drag me
    </p>
  </div>
  <div class="test2">
    <div class="scrolled-box">
      <span>scrolled box</span>
    </div>
  </div>
</div>


问:
Import error with spacy: "No module named en"
I'm having trouble using the Python spaCy library. It seems to be installed correctly but at

```<code>from spacy.en import English
</code>```

I get the following import error:

```<code>Traceback (most recent call last):
  File "spacy.py", line 1, in <module>
    from spacy.en import English
  File "/home/user/CmdData/spacy.py", line 1, in <module>
    from spacy.en import English
ImportError: No module named en
</code>```

I'm not very familiar with Python but that's the standard import I saw online, and the library is installed:

```<code>$ pip list | grep spacy
spacy (0.99)
</code>```

EDIT
I tested renaming the file, but that's not the problem. I also get the same error when doing:

```<code>$ python -m spacy.en.download --force all
/usr/bin/python: No module named en
</code>```

(The command is supposed to download some models)

答:
For windows, open cmd with admin right. Then,

```<code>python -m spacy download en
</code>```

You should see the shell prompt stating.

You can now load the model via spacy.load('en')

Body:
I'm having trouble using the Python spaCy library. It seems to be installed correctly but at

from spacy.en import English

I get the following import error:

Traceback (most recent call last):
  File "spacy.py", line 1, in <module>
    from spacy.en import English
  File "/home/user/CmdData/spacy.py", line 1, in <module>
    from spacy.en import English
ImportError: No module named en

I'm not very familiar with Python but that's the standard import I saw online, and the library is installed:

$ pip list | grep spacy
spacy (0.99)

EDIT
I tested renaming the file, but that's not the problem. I also get the same error when doing:

$ python -m spacy.en.download --force all
/usr/bin/python: No module named en

(The command is supposed to download some models)

Body:
For windows, open cmd with admin right. Then,

python -m spacy download en

You should see the shell prompt stating.

You can now load the model via spacy.load('en')


问:
Java generics method <T extends Integer> +1
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?

```<code>public <T extends Integer> Integer methodA(T t){
   return t = t + 1;
}
</code>```

It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?

答:
```<code>public class SomeClass {

  public <T extends Integer> Integer methodA(T t) {
    return t.intValue() + 1 ;
  }
}
</code>```

This should work fine

Body:
Im new to generics. Maybe my question is dumb and silly but why the following doesnt work?

public <T extends Integer> Integer methodA(T t){
   return t = t + 1;
}

It says that Operator cannot be applied to 'T', 'int'. What should I do to make this code work?

Body:
public class SomeClass {

  public <T extends Integer> Integer methodA(T t) {
    return t.intValue() + 1 ;
  }
}

This should work fine