问:
Is it possible to access the applied filters at List Component rendering time
I'm using admin-on-rest and i'm in a case where i have to change the column set in a list view according to the applied filters.

Is there any way i can get the currently applied filters so i can do some kind of conditional rendering?

Example:

```<code>export const AssetList = (props) => (
(!props.filters.includes('group_by') ?
  <List title="Assets" filters={<AssetFilter/>} {...props}>
      <Datagrid>
          <TextField source="asset_uid" />
          <TextField source="amounts.price" label="Price" />
          <ChipListField source="flags" />
          <EditButton />
      </Datagrid>
  </List>
:
  <List title="Assets" filters={<AssetFilter/>} {...props}>
      <Datagrid>
          <TextField source="group_id" />
          <ChipField source="flag_counts.flag1" label="virtual" />
          <ChipField source="flag_counts.flag2" label="operational" />
          <TextField source="total_amounts.price" label="Price" />
          <EditButton />
      </Datagrid>
  </List>)
);
</code>```

Currently there is no such thing as props.filters is there any way i can access them ?

答:
You can get filters based on admin-on-rest resources from another resource. You need to connect the component and access the filter like this in mapStateToProps.
Then you can access it as this.props.eventFilters in your component.

```<code>function mapStateToProps(state) {
  return {
    eventFilters:  state.admin.resources.myEventsResource.list.params.filter
  };
}

export default connect(mapStateToProps)(MyComponent)
</code>```

Body:
I'm using admin-on-rest and i'm in a case where i have to change the column set in a list view according to the applied filters.

Is there any way i can get the currently applied filters so i can do some kind of conditional rendering?

Example:

export const AssetList = (props) => (
(!props.filters.includes('group_by') ?
  <List title="Assets" filters={<AssetFilter/>} {...props}>
      <Datagrid>
          <TextField source="asset_uid" />
          <TextField source="amounts.price" label="Price" />
          <ChipListField source="flags" />
          <EditButton />
      </Datagrid>
  </List>
:
  <List title="Assets" filters={<AssetFilter/>} {...props}>
      <Datagrid>
          <TextField source="group_id" />
          <ChipField source="flag_counts.flag1" label="virtual" />
          <ChipField source="flag_counts.flag2" label="operational" />
          <TextField source="total_amounts.price" label="Price" />
          <EditButton />
      </Datagrid>
  </List>)
);

Currently there is no such thing as props.filters is there any way i can access them ?

Body:
You can get filters based on admin-on-rest resources from another resource. You need to connect the component and access the filter like this in mapStateToProps.
Then you can access it as this.props.eventFilters in your component.

function mapStateToProps(state) {
  return {
    eventFilters:  state.admin.resources.myEventsResource.list.params.filter
  };
}

export default connect(mapStateToProps)(MyComponent)


来源: stackexchange

问:
What is the best practices of making a repository class with EF4 code first?
There seem to be many ways to apply the repository patterns that is why i need your opinion and a good clear answer on what seem the best way of applying the repository pattern. It is the generic repository ? But there is a problem where some domain object dont have the same behaviour as others. It is specify repository ? What about code repeatition between repositories? it is both combinaison ? how about using a di container for both kind of implementation ?

Thanks

Edit: the orm i am using is entity framework 4. Would be nice to have an example with EF4.

答:
This post by Gabriel Schenker is a good explanation of the repository pattern. He implements it with NHibernate (you don't say which ORM you are using) and provides a generic base repository. For me the repository pattern is very connected to testing and being able to fake it or mock it and this blog post also shows how to make your own fake.

In my experience most repositories share some common functionality e.g. GetById, Add, Remove. So it is useful to have a base class that can be inherited. Where it can get a little trickier is when you start thinking about dynamic Linq queries and how those can be tested.

Examples of repository patterns with Linq can be found here and here but I would start simple as these could be overkill for some projects.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How can I move existing tab to Firefox container?
I'm testing new Firefox container feature but can't seem to find how to move existing tabs to a specific container.

Is open blank tab in said container then pasting URL the only solution?

答:
Tabs can be assigned to containers via:

Mouse

Switch Container adds a toolbar icon which gives a list of the containers from which to select.

Keyboard

Search and Switch Containers allows you to switch the current tab's container by going to to the location bar and typing:

```<code>co <container name>
</code>```

Body:
Tabs can be assigned to containers via:

Mouse

Switch Container adds a toolbar icon which gives a list of the containers from which to select.

Keyboard

Search and Switch Containers allows you to switch the current tab's container by going to to the location bar and typing:

co <container name>


问:
ASP.NET MVC - How to use code first and database first method in same project and with same context
I have a requirement that I have to use code first pattern (which I have to implement) along with database first (which exists in the current system).

Now the condition is I must not create a different context for new tables or any other changes which I make in the database but have to maintain current context from DB first pattern. Is it possible to create code first and DB first in the same project sharing the same context? Do I must manage .edmx file or is it possible to handle the database from code first pattern only? And that too with managing TransactionScope.

I need some suggestions on this.

答:
There are some things that I learned from my above problem.

One cannot use the same context for Code first and Database first.

To use code first and database first in the same project, context must be different and irrespective of ConnectionString. (one can use either existing ConnectionString or make a new one)

It is not good practice to use two patterns at same, but if situation demands it, than one must have no choice. Therfore at last one can create POCO classes for code first, from database first so it can be useful.

TransactionScope be used with irrespective number of database connections and it will work properly.

If anything I am missing, than please add it so other can have better idea, or they could at least save their time.


问:
Check if span contains value but value is after another nestled span
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
  </span>
</span></code>```

答:
You can replace the currency symbol first and cast the remaining content as float with parseFloat()

jQuery(document).ready(function($) {
  $(".woocommerce-Price-amount").each(function() {
    var inner = parseFloat($(this).text().replace("$", ""));
    if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
      console.log("Exists!");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
    </span>
  <span class="my-price"></span>
</span></code>```

Body:
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});

2 ×

      $ 21.95

    $19.76

Body:
You can replace the currency symbol first and cast the remaining content as float with parseFloat()

jQuery(document).ready(function($) {
  $(".woocommerce-Price-amount").each(function() {
    var inner = parseFloat($(this).text().replace("$", ""));
    if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
      console.log("Exists!");
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
    </span>
  <span class="my-price"></span>
</span>


问:
ASP.NET Multiple Select ListBox with CheckBoxes in a MultiView Control using jQuery and Bootstrap
I have been trying to implement a multiple select dropdown list available at here.

However, my situation is slightly different than the example as the listbox is in an ASP.NET VIEW control, where this view is not loaded initially.

I noticed that the dropdown list works fine when I directly set SampleView2 as active view in the page load. However if I load SampleView2 later on click on button event, List box is not populated properly. Check boxes are missing.

I believe that’s because the JavaScript is not fired when SampleView2 is loaded during the post back?  Can anyone please advise how to achieve this?

Here’s my code.

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Bootstrap_MultiSelect_DropDown.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
    <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $('[id*=lstFruits]').multiselect({
                    includeSelectAllOption: true
                });
            });
        </script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="MultiViewMain" runat="server">
<asp:View ID="ViewSampleView1" runat="server">
<p>SampleView1</p>
<asp:Button ID="ButtonLoadSampleView2" runat="server" Text="LoadSampleView2"
        onclick="ButtonLoadSampleView2_Click" />
</asp:View>
<asp:View ID="ViewSampleView2" runat="server">
<div>
<p>SampleView2</p>
<asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="Mango" Value="1" />
    <asp:ListItem Text="Apple" Value="2" />
    <asp:ListItem Text="Banana" Value="3" />
    <asp:ListItem Text="Guava" Value="4" />
    <asp:ListItem Text="Orange" Value="5" />
</asp:ListBox>
</div>
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace Bootstrap_MultiSelect_DropDown
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MultiViewMain.SetActiveView(ViewSampleView1);
            }
        }

        protected void ButtonLoadSampleView2_Click(object sender, EventArgs e)
        {
            MultiViewMain.SetActiveView(ViewSampleView2);
        }
    }
}
</code>```

答:
You need to run client side code after server side. So you can use

*.cs

```<code>protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       MultiViewMain.SetActiveView(ViewSampleView1);
   }
}

protected void ButtonLoadSampleView2_Click(object sender, EventArgs e)
{
      MultiViewMain.SetActiveView(ViewSampleView2);
      //Line to add so that you can access client script from server side
      //where getView is a function on client side
      ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "alertScript", "getView();", true);
}
</code>```

*.js

```<code><link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

<script>
    function getView() {
        $('#<%= lstFruits.ClientID %>').multiselect({ includeSelectAllOption: true });
    }
</script>
</code>```

*.html

```<code><ContentTemplate>
            <asp:MultiView ID="MultiViewMain" runat="server">
                <asp:View ID="ViewSampleView1" runat="server">
                    <p>SampleView1</p>
                    <asp:Button ID="ButtonLoadSampleView2" runat="server" Text="LoadSampleView2" OnClick="ButtonLoadSampleView2_Click" />

                </asp:View>
                <asp:View ID="ViewSampleView2" runat="server">
                    <div>
                        <p>SampleView2</p>
                        <asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
                            <asp:ListItem Text="Mango" Value="1" />
                            <asp:ListItem Text="Apple" Value="2" />
                            <asp:ListItem Text="Banana" Value="3" />
                            <asp:ListItem Text="Guava" Value="4" />
                            <asp:ListItem Text="Orange" Value="5" />
                        </asp:ListBox>
                    </div>
                </asp:View>
            </asp:MultiView>
        </ContentTemplate>
</code>```

Body:
I have been trying to implement a multiple select dropdown list available at here.

However, my situation is slightly different than the example as the listbox is in an ASP.NET VIEW control, where this view is not loaded initially.

I noticed that the dropdown list works fine when I directly set SampleView2 as active view in the page load. However if I load SampleView2 later on click on button event, List box is not populated properly. Check boxes are missing.

I believe that’s because the JavaScript is not fired when SampleView2 is loaded during the post back?  Can anyone please advise how to achieve this?

Here’s my code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Bootstrap_MultiSelect_DropDown.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="MultiViewMain" runat="server">
<asp:View ID="ViewSampleView1" runat="server">

SampleView1

<asp:Button ID="ButtonLoadSampleView2" runat="server" Text="LoadSampleView2"
        onclick="ButtonLoadSampleView2_Click" />
</asp:View>
<asp:View ID="ViewSampleView2" runat="server">

SampleView2

<asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="Mango" Value="1" />
    <asp:ListItem Text="Apple" Value="2" />
    <asp:ListItem Text="Banana" Value="3" />
    <asp:ListItem Text="Guava" Value="4" />
    <asp:ListItem Text="Orange" Value="5" />
</asp:ListBox>

</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
</form>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace Bootstrap_MultiSelect_DropDown
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MultiViewMain.SetActiveView(ViewSampleView1);
            }
        }

        protected void ButtonLoadSampleView2_Click(object sender, EventArgs e)
        {
            MultiViewMain.SetActiveView(ViewSampleView2);
        }
    }
}

Body:
You need to run client side code after server side. So you can use

*.cs

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       MultiViewMain.SetActiveView(ViewSampleView1);
   }
}

protected void ButtonLoadSampleView2_Click(object sender, EventArgs e)
{
      MultiViewMain.SetActiveView(ViewSampleView2);
      //Line to add so that you can access client script from server side
      //where getView is a function on client side
      ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "alertScript", "getView();", true);
}

*.js

<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

<script>
    function getView() {
        $('#<%= lstFruits.ClientID %>').multiselect({ includeSelectAllOption: true });
    }
</script>

*.html

<ContentTemplate>
            <asp:MultiView ID="MultiViewMain" runat="server">
                <asp:View ID="ViewSampleView1" runat="server">
                    <p>SampleView1</p>
                    <asp:Button ID="ButtonLoadSampleView2" runat="server" Text="LoadSampleView2" OnClick="ButtonLoadSampleView2_Click" />

                </asp:View>
                <asp:View ID="ViewSampleView2" runat="server">
                    <div>
                        <p>SampleView2</p>
                        <asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
                            <asp:ListItem Text="Mango" Value="1" />
                            <asp:ListItem Text="Apple" Value="2" />
                            <asp:ListItem Text="Banana" Value="3" />
                            <asp:ListItem Text="Guava" Value="4" />
                            <asp:ListItem Text="Orange" Value="5" />
                        </asp:ListBox>
                    </div>
                </asp:View>
            </asp:MultiView>
        </ContentTemplate>


问:
how i can compare changing API response body with expected API using restAssured

Hi, I am trying to create a API Automation Framework using Rest assured library what issue i am facing is the API response body is changing very frequently. Plz Help how i can compare changing API response body with expected API
</p>

答:
If you are open to evaluating other tools take a look at Karate because one of the key features is being able to handle variable parts of the response.

For example, look at fuzzy matching and the contains keyword.


问:
Web app doesn't deploy: Sorry, unable to open the file at present
I have a AppsScript in my Google Sheet that I want to deploy as a WebApp (something I've done many times before).
I have deployed it as public (Anyone, even anonymous), and the link comes up with:
"Sorry, unable to open the file at present.
Please check the address and try again."

This also happens when I click "Test web app for your latest code"

The script works perfectly from within the spreadsheet, and my deployment code is:

```<code>    function doGet() {
  return HtmlService.createTemplateFromFile('Weekly.html')
      .evaluate();
}

function onOpen() {
  var Menu = SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Survey');
      Menu.addItem('Run Survey', 'doSurvey')
        .addToUi();
}

function doSurvey() {
  var html = HtmlService.createTemplateFromFile('Weekly.html')
      .evaluate();
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, ' ');
}
</code>```

Any hints?
Thank you!

答:
This problem has been resolved in this github forum: Can't submit the form, Receiving "Sorry, unable to open the file at present."

And the suggested solution is to :

```<code>just remove the user part of the URL should work too, e.g. for the OP:

https://script.google.com/macros/s/AKfycbyO4vXIPrq4smOSFpUzyQSuOxvJE9YWqlND6GfyZ3Y2lR-pPMk/exec

we should add this to the tutorial, I suppose. also relevant for some gsuite users:
https://stackoverflow.com/questions/26153872/cant-make-a-google-apps-script-publish-for-anonymous-users
</code>```

Body:
I have a AppsScript in my Google Sheet that I want to deploy as a WebApp (something I've done many times before).
I have deployed it as public (Anyone, even anonymous), and the link comes up with:
"Sorry, unable to open the file at present.
Please check the address and try again."

This also happens when I click "Test web app for your latest code"

The script works perfectly from within the spreadsheet, and my deployment code is:

    function doGet() {
  return HtmlService.createTemplateFromFile('Weekly.html')
      .evaluate();
}

function onOpen() {
  var Menu = SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .createMenu('Survey');
      Menu.addItem('Run Survey', 'doSurvey')
        .addToUi();
}

function doSurvey() {
  var html = HtmlService.createTemplateFromFile('Weekly.html')
      .evaluate();
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, ' ');
}

Any hints?
Thank you!

Body:
This problem has been resolved in this github forum: Can't submit the form, Receiving "Sorry, unable to open the file at present."

And the suggested solution is to :

just remove the user part of the URL should work too, e.g. for the OP:

https://script.google.com/macros/s/AKfycbyO4vXIPrq4smOSFpUzyQSuOxvJE9YWqlND6GfyZ3Y2lR-pPMk/exec

we should add this to the tutorial, I suppose. also relevant for some gsuite users:
https://stackoverflow.com/questions/26153872/cant-make-a-google-apps-script-publish-for-anonymous-users


问:
How to give response based on user response in Amazon Lex?
How do I give response to a user in Amazon Lex based on the choice that the user have made?

For example: If user is married then system should ask how many children do you have, if user is not married the system should ask when are you getting married.

Is there any way to do this?

答:
If it's purpose is simply responding to the user without any elicit slot or chaining intents then it can be done simply in Lambda function with an if condition.

```<code>def close(message):
    return {
        "dialogAction":{
            "type":"Close",
            "fulfillmentState":"Fulfilled",
            "message":{
                "contentType":"PlainText",
                "content":message
            }
        }
    }

if user['married'] == True:
    return close('how many children do you have')
else:
    return close('when are you getting married')
</code>```

If you are planning to trigger some different intent then inside if-else write code for intent switching. You will need to pass the confirmIntent dialog action from the lambda with the intent you want to switch to.

Check this link for details about intent switching.

Body:
If it's purpose is simply responding to the user without any elicit slot or chaining intents then it can be done simply in Lambda function with an if condition.

def close(message):
    return {
        "dialogAction":{
            "type":"Close",
            "fulfillmentState":"Fulfilled",
            "message":{
                "contentType":"PlainText",
                "content":message
            }
        }
    }

if user['married'] == True:
    return close('how many children do you have')
else:
    return close('when are you getting married')

If you are planning to trigger some different intent then inside if-else write code for intent switching. You will need to pass the confirmIntent dialog action from the lambda with the intent you want to switch to.

Check this link for details about intent switching.


问:
How to do Tag/Label/Text View?
I want to do something like this view (I don't know even name it) but I don't know where to start to do it the most efficient (the most less amount of code) way.

I want to do this tag/label/text with same functionality like Apple Mail has. Facebook Messenger has almost the same. Is there some official high level public API for that? Where is the best place to start? TextKit? UITextInput? Can you provide me at least abstract algorithm or point me to some inspirational place?

答:
Instead of using addition framework, I recommend UICollectionView to implement Tags. It's less code, less overhead and easy to implement.

Follow this link for implementing:

https://codentrick.com/create-a-tag-flow-layout-with-uicollectionview/

This is how it looks like. Please note it is flexible too, you could integrate according to your logic.

Hope this will help you

Title: How to do Tag/Label/Text View?


问:
Retrieve and print data from dynamic sql query with linq
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

```<code>private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}
</code>```

...

```<code>string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}
</code>```

答: I don't see the value in moving to LINQ here.  The beauty of LINQ is that you can write your query in the language of your domain objects, rather than in T-SQL.  In your case you only want to accept actual SQL commands.  It seems like it would be more work to deconstruct the command, turn it into LINQ -- using reflection to identify the appropriate tables in the data context -- and then execute the query only to print out the properties of the resulting objects.</p>

OwnerDisplayName: Noit

Body:
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}

...

string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}

OwnerDisplayName: tvanfosson


问:
shader sun position - glsl
I am trying to make a shader that simulates the sun position and the light that it reflects in a object.

To simulate the sun trajectory I have a timer, and the light position is defined by:

```<code>fvLightPosition.x=-cos(Time)*speed;
fvLightPosition.y=sin(Time)*speed;
fvLightPosition.z=100.0;
</code>```

The timer is a variable float Time0_X

I almost get the right trajectory, except that is upside down, and somehow look a bit weird. Can anyone give me a tip how to simulate the sun trajectory in the right way?

I am using RenderMonkey to make the shader.

答:
Make sure that you scale your Time value so that it lies between 0 and 2*PI radians (which corresponds to 0 and 180 degrees respectively). If your original Time value ranges from 0 to some number MAX, you can do the scaling like this: (Time / MAX) * 2PI.

I'm not sure what speed refers to, but you should most likely not be multiplying by that. The cos and sin values represent the X and Y components of the vector between the sun and the origin, so you should multiply by the distance of the sun from the centre of your scene, which is usually constant.

Title: shader sun position - glsl

Body:
I am trying to make a shader that simulates the sun position and the light that it reflects in a object.

To simulate the sun trajectory I have a timer, and the light position is defined by:

fvLightPosition.x=-cos(Time)*speed;
fvLightPosition.y=sin(Time)*speed;
fvLightPosition.z=100.0;

The timer is a variable float Time0_X

I almost get the right trajectory, except that is upside down, and somehow look a bit weird. Can anyone give me a tip how to simulate the sun trajectory in the right way?

I am using RenderMonkey to make the shader.


问:
On scroll recyclerview item Background color changed when recylcerview scroll
I want to change Recyclerview item background color on my condition but when I scroll  background color automatically changed   I know    holder.setIsRecyclable(false);  but I don't want to set holder.setIsRecyclable(false);

and I know

```<code> if(item.value == 1){
    // do something
    } else{
      // do something
   }
</code>```

but i want to do using nested if else

```<code>           if (feetInt > 0 && feetInt < 4) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_green));
            } else if (feetInt >= 4 && feetInt < 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_yellow));
            } else if (feetInt == 0 || feetInt >= 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_red));
            }else{
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_grey));
            }
</code>```

答:
It looks like you are not updating the value of feetInt for every single object in list. That's why you are facing this issue.

Update feet int value in list for different different position, you will get the desire result.

Also, remove getItemViewCount() and setIsRecyclable(). These are not required at all. Also, share your code for more specific answers.

Body:
I want to change Recyclerview item background color on my condition but when I scroll  background color automatically changed   I know    holder.setIsRecyclable(false);  but I don't want to set holder.setIsRecyclable(false);

and I know

 if(item.value == 1){
    // do something
    } else{
      // do something
   }

but i want to do using nested if else

           if (feetInt > 0 && feetInt < 4) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_green));
            } else if (feetInt >= 4 && feetInt < 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_yellow));
            } else if (feetInt == 0 || feetInt >= 6) {
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_red));
            }else{
                ((PatientViewHolder) holder).rlClientItemMain.setBackgroundColor(ContextCompat.getColor(mContext, R.color.player_list_grey));
            }


问:
Update one value in parent activity from a child activity while retaining all remaining original values on the parent
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

```<code>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});
</code>```

Here is my AndroidManifest.xml entry:

```<code><activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
</code>```

答:
You can achieve what you want using EventBus, create a model class to pass data from third to first activity

Add below dependency in gradle

```<code>compile 'org.greenrobot:eventbus:3.0.0'
</code>```

CopyModel.java

```<code>public class CopyModel{
  private int copies;
  public CopyModel(int copies){
    this.copies = copies;
  }

  public int getSelectedCopies(){
     return copies;
  }
}
</code>```

ThirdActivity

```<code>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        EventBus.getDefault().post(new CopyModel(5)); //<-- pass data before navigating to first activity
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});
</code>```

FirstActivity

```<code>private int selectedCopies; //global declaration

@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CopyModel copyModel) {
       //get your selected copies and assign it to global variable
       this.selectedCopies = copyModel.getSelectedCopies();
    }

 @Override
 public void onResume(){
    //you can use new selectedCopies value here and write code to update UI based on new value
 }
</code>```

Body:
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});

Here is my AndroidManifest.xml entry:

<activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>

Body:
You can achieve what you want using EventBus, create a model class to pass data from third to first activity

Add below dependency in gradle

compile 'org.greenrobot:eventbus:3.0.0'

CopyModel.java

public class CopyModel{
  private int copies;
  public CopyModel(int copies){
    this.copies = copies;
  }

  public int getSelectedCopies(){
     return copies;
  }
}

ThirdActivity

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        EventBus.getDefault().post(new CopyModel(5)); //<-- pass data before navigating to first activity
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});

FirstActivity

private int selectedCopies; //global declaration

@Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CopyModel copyModel) {
       //get your selected copies and assign it to global variable
       this.selectedCopies = copyModel.getSelectedCopies();
    }

 @Override
 public void onResume(){
    //you can use new selectedCopies value here and write code to update UI based on new value
 }


问:
Saving multiple images in laravel
I'm trying to save multiple images in an array to the database, but I'm struggling with that. I've managed to be able to upload the multiple images to the folder just not the database.

My controller

```<code>public function store(Request $request)
{

    $content = new Content();

    $request->validate($this->getRules());

    $content->fill($this->getSafeInput($request));

    if($request->hasFile('image'))
    {
        foreach($request->file('image') as $image)
        {
            $destinationPath = 'content_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            $content->image = $filename;

        }

    }

    $content->save();

    return redirect()->route('content.index');
}
</code>```

My form

```<code><div class="content-form">
    {{ Form::open(array('route' => 'content.store', 'method' => 'post','files'=>'true' )) }}
        {{ csrf_field() }}

        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" id="title" class="form-control" name="title">
        </div>

        <div class="form-group">
            <input type="file" name="image[]" multiple="multiple">
        </div>

        <input type="submit" class="btn btn-primary" value="Submit"></input>
    {{ Form::close() }}
</div>
</code>```

答:
You are overriding the value of  $content->image on each image save so finally your $content->image will have only the name of the last image.

This should work:

```<code>if($request->hasFile('image'))
{
    $names = [];
    foreach($request->file('image') as $image)
    {
        $destinationPath = 'content_images/';
        $filename = $image->getClientOriginalName();
        $image->move($destinationPath, $filename);
        array_push($names, $filename);

    }
    $content->image = json_encode($names)
}
</code>```

Here the image names are initially stored in an array and the array later is saved into db in json format. so that you can later access them by doing json_decode and you will have your array of names back!

Title: Saving multiple images in laravel

Body:
I'm trying to save multiple images in an array to the database, but I'm struggling with that. I've managed to be able to upload the multiple images to the folder just not the database.

My controller

public function store(Request $request)
{

    $content = new Content();

    $request->validate($this->getRules());

    $content->fill($this->getSafeInput($request));

    if($request->hasFile('image'))
    {
        foreach($request->file('image') as $image)
        {
            $destinationPath = 'content_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            $content->image = $filename;

        }

    }

    $content->save();

    return redirect()->route('content.index');
}

My form

    {{ Form::open(array('route' => 'content.store', 'method' => 'post','files'=>'true' )) }}
        {{ csrf_field() }}

            Title
            <input type="text" id="title" class="form-control" name="title">

            <input type="file" name="image[]" multiple="multiple">

        <input type="submit" class="btn btn-primary" value="Submit"></input>
    {{ Form::close() }}

Body:
You are overriding the value of  $content->image on each image save so finally your $content->image will have only the name of the last image.

This should work:

if($request->hasFile('image'))
{
    $names = [];
    foreach($request->file('image') as $image)
    {
        $destinationPath = 'content_images/';
        $filename = $image->getClientOriginalName();
        $image->move($destinationPath, $filename);
        array_push($names, $filename);

    }
    $content->image = json_encode($names)
}

Here the image names are initially stored in an array and the array later is saved into db in json format. so that you can later access them by doing json_decode and you will have your array of names back!

ContentLicense: CC BY-SA 4.0


问:
What are the focal lengths and the principal point in KITTI stereo dataset?
I am using the KITTI stereo dataset 2012 and 2015 in a research.

But I need some values that I didn't find:

focal lengths for x and y direction.

the principal point.

There are some files inside the "calib" folder in dataset. A content example is here (calib/000000.txt):

P0: 7.070912e+02 0.000000e+00 6.018873e+02 0.000000e+00 0.000000e+00 7.070912e+02 1.831104e+02 0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00

P1: 7.070912e+02 0.000000e+00 6.018873e+02 -3.798145e+02 0.000000e+00 7.070912e+02 1.831104e+02 0.000000e+00 0.000000e+00 0.000000e+00 1.000000e+00 0.000000e+00

P2: 7.070912e+02 0.000000e+00 6.018873e+02 4.688783e+01 0.000000e+00 7.070912e+02 1.831104e+02 1.178601e-01 0.000000e+00 0.000000e+00 1.000000e+00 6.203223e-03

P3: 7.070912e+02 0.000000e+00 6.018873e+02 -3.334597e+02 0.000000e+00 7.070912e+02 1.831104e+02 1.930130e+00 0.000000e+00 0.000000e+00 1.000000e+00 3.318498e-03

Following this paper (specifically in section IV, B):
http://www.mrt.kit.edu/z/publ/download/2013/GeigerAl2013IJRR.pdf

I got that P is the projection matrix after retification. And i ∈ {0, 1, 2, 3} is the camera index, where 0 represents the left grayscale, 1 the right grayscale, 2 the left color and 3 the right color camera.

But my problem is that I don't know how to find the focal length and the principal point that I need.

Can someone help me?

Thank you all!

答:
The P0 matrix is the projection matrix.

Value at P0[0, 0] is Fy, the focal length along the x axis,

P0[0, 2] is Cx,

P0[1, 1] is Fy, and

P0[1, 2] is Cy.

The P0 matrix is like any other projection matrix.


问:
Event entries scheduling algorithm PHP
we have an entry portal system in which we accept entries for events.

For example Championship Event 2017 will be held on 30th Nov.

Event got about 150 entries in different classes. Junior Class, Senior Class, Pro Class etc.

Now event venue only has certain numbers of ground on which the competition can be held. For example Ground 1, Ground 2 and Ground 3. Its a solo performance event.

Now our system needs to generate a schedule in such a way that competitors who entered multiple classes or same classes multiple times should get maximum break between their performances.

The input data we have are registration under each class.
Starting time of each Ground. For example Ground A will start at 8:00 AM, Ground 2 at 8:00 and Ground 3 at 9:00.
We also know that which class will be held in which arena. For example Junior and senior Class will be held in Ground 1 and Pro Class will be held in Ground 2.

We know the performance time as well. Senior Class 1 performance is 5 minutes. Junior class performance is 7 minutes and Pro Performance is 9 minutes.

Now I have written following code to get the schedule so that competitors competing multiple times in one class or in multiple class get maximum break between their performance but it still puts same competitor performance one after another.

Let me know what is my mistake.

```<code>foreach ($totalPerformanceTimeSlot as $time => $performance) {
    # $totalPerformanceTimeSlot is array of timeslots starting from 8:00 am

    foreach ($performance as $classId) {
        #there could be 2 performance at the same time in different arena for different class.
        $totalPerformanceLeftThisClass = count($this->lassRegistrationLinks[$classId]); //Get the total performance for this class from array;

        # $accountRidesLeftArray has value of how many times each account is performing in this class
        arsort($accountRidesLeftArray);
        # for each person,  estimate what their start time threshold should be based on how many times they're performing
        $accountPerformanceTimeThreshold = array();

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            $tempPerformanceThreshold = 20 * 60;
            # reduce this person's performance threshold by a performance at a time until the minimum performance threshold has been met
            while ((($totalPerformanceLeftThisClass * $this->classes[$classId]['performanceTime']) / $accountPerformanceLeft < $tempPerformanceThreshold) && ($tempPerformanceThreshold > $this->minRideThreshold))
                $tempPerformanceThreshold -= $this->classes[$classId]['performanceTime'];

            $accountPerformanceTimeThreshold[$accountId] = $tempPerformanceThreshold;
        }

        $performanceLeft = $totalPerformanceLeftThisClass - $count;

        # given the number of performance left in the class,
        # calculate how important it is per account that they get placed in the next slot
        $accountToPerformNextImportanceArray = array();
        $timeLeft = $performanceLeft * $this->classes[$classId]['performanceTime'];

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            # work out the maximum number that can be used as entropy
            $entropyMax = (20 * 60 / ($timeLeft / 1)) * 0.5;
            $entropy = ((mt_rand (0, $entropyMax * 1000)) / 1000);

            # the absolute minimum amount of time required for this user to perform
            $minTimeRequiredForComfortableSpacing = ($accountRidesLeft - 1) * 20* 60;
            # add a bit of time around the absolute minimum amount of time required for this person to perform so that it doesn't instantly snap in when this person suddenly has the minimum amount of time left to perform
            $generalTimeRequiredForComfortableSpacing = $minTimeRequiredForComfortableSpacing * 1.7;

            $nearestPerformancePrior = $this->nearest_performance_prior($classDetails['date'], $currentTime, $accountId);
            $nearestRideAfter = $this->nearest_performance_after($classDetails['date'], $currentTime, $accountId);

           # work out how important it is for this rider to ride next based on how many rides they have left
           $importanceRating = 20 * 60 / ($timeLeft / $accountPerformanceLeft);

           # if there's more than enough time left then don't worry about giving this person any importance rating,  ie. it's not really important that they perform straight away
           if ($timeLeft > $generalTimeRequiredForComfortableSpacing)
                $importanceRating = 0;

           # add a little bit of random entropy to their importance rating
           $importanceRating += $entropy;

           # if this account has performed too recently to place them here in this slot,  then make them very undesirable for this slot
           if ((!is_null($nearestPerformancePrior)) && ($nearestPerformancePrior > $currentTime - $accountPerformanceTimeThreshold[$accountId]))
               $importanceRating = -1;

          # work out if this account will perform too soon afterwards to place them here in this slot,  then make them very undesirable for this slot
          if ((!is_null($nearestRideAfter)) && ($nearestRideAfter < $currentTime + $accountRideTimeThreshold[$accountId]))
               $importanceRating = -1;

           $accountToPerformNextImportanceArray[$accountId] = $importanceRating;

       }

       arsort($accountToPerformNextImportanceArray);
       //Then I take the first one from this array and allocate the time for that user.
       $this->set_performance_time($classDetails['date'], $accountId, $currentTime);
       $currentTime += $this->classes[$classId]['performanceTime'];
    }
}
</code>```

Here is some explanation of the variables

```<code>$accountPerformancessLeft is total number of performance for each user.
For e.g. if user has entered into 2 classes that means $accountPerformancessLeft is 6 for that user.
threshold is something like break.
Rider and account is conceptually the same.
</code>```

I know it is hard to think the output without the actual data but any help would be appreciated.

Thank you

答:
What an interesting problem!

Here is how I'd tackle it:

Set up a random schedule which works (but doesn't fit the criteria).

Write a function that can swap 2 performances

Write a shuffler which uses swap() many times in order to get a new timetable

Write a function to calculate a score(), how good is this particular schedule? does it have a lot of breaks between performances?

A score should sum all the performance gaps together, this is the function we want to maximise.

Write an algorithm that takes a "search" approach and backtracking to the problem, and let it run for a couple hours, the backtracking should:

Swap stuff

See if the swapped stuff has a better score

if so, continue from swapped

otherwise, backtrack

It can take a while, but the program can generate a better timetable.

Let us know if this approach helps.

Title: Event entries scheduling algorithm PHP

Body:
we have an entry portal system in which we accept entries for events.

For example Championship Event 2017 will be held on 30th Nov.

Event got about 150 entries in different classes. Junior Class, Senior Class, Pro Class etc.

Now event venue only has certain numbers of ground on which the competition can be held. For example Ground 1, Ground 2 and Ground 3. Its a solo performance event.

Now our system needs to generate a schedule in such a way that competitors who entered multiple classes or same classes multiple times should get maximum break between their performances.

The input data we have are registration under each class.
Starting time of each Ground. For example Ground A will start at 8:00 AM, Ground 2 at 8:00 and Ground 3 at 9:00.
We also know that which class will be held in which arena. For example Junior and senior Class will be held in Ground 1 and Pro Class will be held in Ground 2.

We know the performance time as well. Senior Class 1 performance is 5 minutes. Junior class performance is 7 minutes and Pro Performance is 9 minutes.

Now I have written following code to get the schedule so that competitors competing multiple times in one class or in multiple class get maximum break between their performance but it still puts same competitor performance one after another.

Let me know what is my mistake.

foreach ($totalPerformanceTimeSlot as $time => $performance) {
    # $totalPerformanceTimeSlot is array of timeslots starting from 8:00 am

    foreach ($performance as $classId) {
        #there could be 2 performance at the same time in different arena for different class.
        $totalPerformanceLeftThisClass = count($this->lassRegistrationLinks[$classId]); //Get the total performance for this class from array;

        # $accountRidesLeftArray has value of how many times each account is performing in this class
        arsort($accountRidesLeftArray);
        # for each person,  estimate what their start time threshold should be based on how many times they're performing
        $accountPerformanceTimeThreshold = array();

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            $tempPerformanceThreshold = 20 * 60;
            # reduce this person's performance threshold by a performance at a time until the minimum performance threshold has been met
            while ((($totalPerformanceLeftThisClass * $this->classes[$classId]['performanceTime']) / $accountPerformanceLeft < $tempPerformanceThreshold) && ($tempPerformanceThreshold > $this->minRideThreshold))
                $tempPerformanceThreshold -= $this->classes[$classId]['performanceTime'];

            $accountPerformanceTimeThreshold[$accountId] = $tempPerformanceThreshold;
        }

        $performanceLeft = $totalPerformanceLeftThisClass - $count;

        # given the number of performance left in the class,
        # calculate how important it is per account that they get placed in the next slot
        $accountToPerformNextImportanceArray = array();
        $timeLeft = $performanceLeft * $this->classes[$classId]['performanceTime'];

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            # work out the maximum number that can be used as entropy
            $entropyMax = (20 * 60 / ($timeLeft / 1)) * 0.5;
            $entropy = ((mt_rand (0, $entropyMax * 1000)) / 1000);

            # the absolute minimum amount of time required for this user to perform
            $minTimeRequiredForComfortableSpacing = ($accountRidesLeft - 1) * 20* 60;
            # add a bit of time around the absolute minimum amount of time required for this person to perform so that it doesn't instantly snap in when this person suddenly has the minimum amount of time left to perform
            $generalTimeRequiredForComfortableSpacing = $minTimeRequiredForComfortableSpacing * 1.7;

            $nearestPerformancePrior = $this->nearest_performance_prior($classDetails['date'], $currentTime, $accountId);
            $nearestRideAfter = $this->nearest_performance_after($classDetails['date'], $currentTime, $accountId);

           # work out how important it is for this rider to ride next based on how many rides they have left
           $importanceRating = 20 * 60 / ($timeLeft / $accountPerformanceLeft);

           # if there's more than enough time left then don't worry about giving this person any importance rating,  ie. it's not really important that they perform straight away
           if ($timeLeft > $generalTimeRequiredForComfortableSpacing)
                $importanceRating = 0;

           # add a little bit of random entropy to their importance rating
           $importanceRating += $entropy;

           # if this account has performed too recently to place them here in this slot,  then make them very undesirable for this slot
           if ((!is_null($nearestPerformancePrior)) && ($nearestPerformancePrior > $currentTime - $accountPerformanceTimeThreshold[$accountId]))
               $importanceRating = -1;

          # work out if this account will perform too soon afterwards to place them here in this slot,  then make them very undesirable for this slot
          if ((!is_null($nearestRideAfter)) && ($nearestRideAfter < $currentTime + $accountRideTimeThreshold[$accountId]))
               $importanceRating = -1;

           $accountToPerformNextImportanceArray[$accountId] = $importanceRating;

       }

       arsort($accountToPerformNextImportanceArray);
       //Then I take the first one from this array and allocate the time for that user.
       $this->set_performance_time($classDetails['date'], $accountId, $currentTime);
       $currentTime += $this->classes[$classId]['performanceTime'];
    }
}

Here is some explanation of the variables

$accountPerformancessLeft is total number of performance for each user.
For e.g. if user has entered into 2 classes that means $accountPerformancessLeft is 6 for that user.
threshold is something like break.
Rider and account is conceptually the same.

I know it is hard to think the output without the actual data but any help would be appreciated.

Thank you


问:
Exception when code first tried to create database
I've created a new ASP.NET MVC 4 application, and would like it to use code first. However it doesn't seem to initially create the database file if it doesn't exist already. If I delete the .mdf file from the App_Data folder, then I get the following exception when the app tries to access the database:

```<code>System.Data.SqlClient.SqlException: Cannot attach the file '<path-to-db-file>.mdf' as database '<my-db-file-name>'.
</code>```

If I run it in the app in the debugger, then I can see that the exception is occurring in the InitializeSimpleMembershipAttribute::OnActionExecuting method when calling LazyInitializer.EnsureInitialized. The caught exception is:

```<code>[System.Reflection.TargetInvocationException]   {"Exception has been thrown by the target of an invocation."}   System.Reflection.TargetInvocationException
</code>```

With an inner exception of:

```<code>[System.InvalidOperationException]  {"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588"} System.InvalidOperationException
</code>```

Which then has the first exception I mentioned above as the inner exception of that.

Any ideas what I'm doing wrong?

Update

I've just tried it with a brand new MVC4 app. I can replicate it by doing the following:

Create the MVC app in the VS wizard.

Run the app for the first time and go to the login page (note the mdf file now gets generated).

Delete the mdf file, and go back to the login page. The exception is now thrown.

答:
what fixed it for me when I was receiving this error is that I changed the connection string in App.config file of my VS Project.

I have added this in the connection string:

```<code>  <connectionStrings>
<add name="Blog" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=C:\Users\kostadin\Database1.mdf" providerName="System.Data.SqlClient" />
</code>```

Hope this helps someone else.

Body:
I've created a new ASP.NET MVC 4 application, and would like it to use code first. However it doesn't seem to initially create the database file if it doesn't exist already. If I delete the .mdf file from the App_Data folder, then I get the following exception when the app tries to access the database:

System.Data.SqlClient.SqlException: Cannot attach the file '<path-to-db-file>.mdf' as database '<my-db-file-name>'.

If I run it in the app in the debugger, then I can see that the exception is occurring in the InitializeSimpleMembershipAttribute::OnActionExecuting method when calling LazyInitializer.EnsureInitialized. The caught exception is:

[System.Reflection.TargetInvocationException]   {"Exception has been thrown by the target of an invocation."}   System.Reflection.TargetInvocationException

With an inner exception of:

[System.InvalidOperationException]  {"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588"} System.InvalidOperationException

Which then has the first exception I mentioned above as the inner exception of that.

Any ideas what I'm doing wrong?

Update

I've just tried it with a brand new MVC4 app. I can replicate it by doing the following:

Create the MVC app in the VS wizard.

Run the app for the first time and go to the login page (note the mdf file now gets generated).

Delete the mdf file, and go back to the login page. The exception is now thrown.

Body:
what fixed it for me when I was receiving this error is that I changed the connection string in App.config file of my VS Project.

I have added this in the connection string:

  <connectionStrings>
<add name="Blog" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=C:\Users\kostadin\Database1.mdf" providerName="System.Data.SqlClient" />

Hope this helps someone else.


问:
How to register ODBC driver?
I have created a inventory system for my school project and I use SqlLite as standalone DB. I am able to run it as long as I install the SqlLite ODBC connection (separate installer).

But what I want is to create an installer and install the SqlLite ODBC Drivers along with my porject in one installer instead of of running two separate installer (my application and sqlLite ODBC driver installer).

Any idea how to do it? Or do you have any recommendation?

What I have done so far. I copy the SQLLite ODBC dll into my application folder and run it but an error shows telling that no ODBC driver installed. I failed to register the SqlLite odbc dll on both 32 and 64 bit windows OS.

答:
You can use the odbcconf command to register the driver dll directly. Note there're both 32 bit and 64 bit ODBC drivers, so you will need to use the respective odbcconf command.

For example to install 64 bit ODBC driver on 64 bit machine:

```<code>odbcconf /A {INSTALLDRIVER "My Driver Name|driver=Path to my driver dll"}
</code>```

To install the 32 bit driver on 64 bit machine:

```<code>%systemroot%/systemwow64/odbcconf /A {INSTALLDRIVER "My Driver Name|driver=Path to my driver dll"}
</code>```

You can find more about the odbcconf command at Microsoft Docs

Title: How to register ODBC driver?

Body:
You can use the odbcconf command to register the driver dll directly. Note there're both 32 bit and 64 bit ODBC drivers, so you will need to use the respective odbcconf command.

For example to install 64 bit ODBC driver on 64 bit machine:

odbcconf /A {INSTALLDRIVER "My Driver Name|driver=Path to my driver dll"}

To install the 32 bit driver on 64 bit machine:

%systemroot%/systemwow64/odbcconf /A {INSTALLDRIVER "My Driver Name|driver=Path to my driver dll"}

You can find more about the odbcconf command at Microsoft Docs


问:
Cobol Mainframe - perform varying Index - display
so I am just starting to learn COBOL on Z/OS. I have done quite a bit using visual cobol; however, this is still quite different.

I need to display a table starting at the Index of 1 and displaying until the index is 50

```<code>     PERFORM VARYING W03-SUBJ-INDX FROM 1 BY 1
 UNTIL W03-SUBJ-INDX = 50
 DISPLAY W03-SUBJ-TABLE
 END-PERFORM
</code>```

That is what I currently have I also tried

```<code>     PERFORM VARYING W03-SUBJ-INDX FROM 1 BY 1
 UNTIL W03-SUBJ-INDX = 50
 DISPLAY W03-SUBJ-TABLE(w03-subj-indx)
 END-PERFORM
</code>```

The top example displays only the first indexed item (To be expected) - The second example gives me an error stating ")" was unexpected.

Any help would be appreciated.. I was told I have to use the index

答:
So regarding your existing code....there was some flakiness in some of the versions of the Enterprise Cobol parsers...

```<code>DISPLAY W03-SUBJ-TABLE(w03-subj-indx)
</code>```

might work as this:

```<code>DISPLAY W03-SUBJ-TABLE ( w03-subj-indx )
</code>```

Some of the versions of the Enterprise Cobol compiler did not parse well without spaces.  This was especially important when doing reference modification, but applied to tables as well.

Give it a try, YMMV.

Body:
so I am just starting to learn COBOL on Z/OS. I have done quite a bit using visual cobol; however, this is still quite different.

I need to display a table starting at the Index of 1 and displaying until the index is 50

     PERFORM VARYING W03-SUBJ-INDX FROM 1 BY 1
 UNTIL W03-SUBJ-INDX = 50
 DISPLAY W03-SUBJ-TABLE
 END-PERFORM

That is what I currently have I also tried

     PERFORM VARYING W03-SUBJ-INDX FROM 1 BY 1
 UNTIL W03-SUBJ-INDX = 50
 DISPLAY W03-SUBJ-TABLE(w03-subj-indx)
 END-PERFORM

The top example displays only the first indexed item (To be expected) - The second example gives me an error stating ")" was unexpected.

Any help would be appreciated.. I was told I have to use the index

Body:
So regarding your existing code....there was some flakiness in some of the versions of the Enterprise Cobol parsers...

DISPLAY W03-SUBJ-TABLE(w03-subj-indx)

might work as this:

DISPLAY W03-SUBJ-TABLE ( w03-subj-indx )

Some of the versions of the Enterprise Cobol compiler did not parse well without spaces.  This was especially important when doing reference modification, but applied to tables as well.

Give it a try, YMMV.


问:
Device Owner setup using code not working
Runtime.getRuntime().exec("dpm set-device-owner com.integral.kiosk.kioskapp/.receivers.MyDeviceAdminReceiver");

not setting the device owner in Android emulator Nexus 6 OS Android 8.
but when using adb shell command it is working fine.

attaching the code below which i used in oncreate function.

```<code> ComponentName deviceAdmin = new ComponentName(this, MyDeviceAdminReceiver.class);
        if (!mDevicePolicyManager.isAdminActive(deviceAdmin)) {
            Toast.makeText(this, "Not Device Admin", Toast.LENGTH_SHORT).show();

            Intent activateDeviceAdmin = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            activateDeviceAdmin.putExtra(
                    DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin
            );
            activateDeviceAdmin
                    .putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "After activating admin, you will be able to block application uninstallation.”");
            startActivityForResult(activateDeviceAdmin,
                    PM_ACTIVATION_REQUEST_CODE);
        }

        if (mDevicePolicyManager.isDeviceOwnerApp(getPackageName())) {
            mDevicePolicyManager.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()});
            Toast.makeText(this, "Device Owner", Toast.LENGTH_SHORT).show();
//            startLockTask();
            mDevicePolicyManager.clearDeviceOwnerApp(getPackageName());
        } else {

            Toast.makeText(this, "Not Device Owner", Toast.LENGTH_SHORT).show();
            try {
                Runtime.getRuntime().exec("dpm set-device-owner com.integral.kiosk.kioskapp/.receivers.MyDeviceAdminReceiver");
            } catch (IOException e) {
                e.printStackTrace();
            }
</code>```

Please help.
Thanks in advance

答: Try removing all the "add device admin" code, everything within the first if statement block. Each Android release since Lollipop deprecates more and more device administrator APIs. Your app only needs to be the device owner. Once it is the device owner, it cannot be uninstalled and you can set locked tasks from it such as itself.</p>

Body:
Runtime.getRuntime().exec("dpm set-device-owner com.integral.kiosk.kioskapp/.receivers.MyDeviceAdminReceiver");

not setting the device owner in Android emulator Nexus 6 OS Android 8.
but when using adb shell command it is working fine.

attaching the code below which i used in oncreate function.

 ComponentName deviceAdmin = new ComponentName(this, MyDeviceAdminReceiver.class);
        if (!mDevicePolicyManager.isAdminActive(deviceAdmin)) {
            Toast.makeText(this, "Not Device Admin", Toast.LENGTH_SHORT).show();

            Intent activateDeviceAdmin = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            activateDeviceAdmin.putExtra(
                    DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin
            );
            activateDeviceAdmin
                    .putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "After activating admin, you will be able to block application uninstallation.”");
            startActivityForResult(activateDeviceAdmin,
                    PM_ACTIVATION_REQUEST_CODE);
        }

        if (mDevicePolicyManager.isDeviceOwnerApp(getPackageName())) {
            mDevicePolicyManager.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()});
            Toast.makeText(this, "Device Owner", Toast.LENGTH_SHORT).show();
//            startLockTask();
            mDevicePolicyManager.clearDeviceOwnerApp(getPackageName());
        } else {

            Toast.makeText(this, "Not Device Owner", Toast.LENGTH_SHORT).show();
            try {
                Runtime.getRuntime().exec("dpm set-device-owner com.integral.kiosk.kioskapp/.receivers.MyDeviceAdminReceiver");
            } catch (IOException e) {
                e.printStackTrace();
            }

Please help.
Thanks in advance


问:
C# Error ORA 00907: Missing Right Parenthesis
My error:

ORA 00907: Missing Right Parenthesis

My code:

```<code>CREATE TABLE TBL_TD_USER
(

  USER_ID                 INTEGER(10) NOT NULL,
  USER_NAME               VARCHAR2(20) NOT NULL,
  PASSWORD                VARCHAR2(20) NOT NULL,
  CREATED_BY              VARCHAR2(20) NOT NULL,
  CREATED_DATE            DATE NOT NULL,
  MODIFIED_BY             VARCHAR2(20) NOT NULL,
  MODIFIED_DATE           DATE NOT NULL,
  IS_ACTIVE               CHARACTER(1) NOT NULL,
  DESCRIPTION             VARCHAR2(200) NOT NULL,

  CONSTRAINT TBL_TD_USER PRIMARY KEY (USER_ID)

);
</code>```

答:
This works:

```<code>CREATE TABLE TBL_TD_USER
(
 USER_ID       INTEGER NOT NULL ,
 USER_NAME     VARCHAR2(20) NOT NULL,
 PASSWORD      VARCHAR2(20) NOT NULL,
 CREATED_BY    VARCHAR2(20) NOT NULL,
 CREATED_DATE  DATE NOT NULL,
 MODIFIED_BY   VARCHAR2(20) NOT NULL,
 MODIFIED_DATE DATE NOT NULL,
 IS_ACTIVE     VARCHAR2(1) NOT NULL,
 DESCRIPTION   VARCHAR2(200) NOT NULL,
 CONSTRAINT TBL_TD_USER PRIMARY KEY (USER_ID)
);
</code>```

There's no variable type named CHARACTER in oracle, as an alternative, you to use VARCHAR2 with length value in parenthesis.

You can use INTEGER type without length.

demo

Body:
My error:

ORA 00907: Missing Right Parenthesis

My code:

CREATE TABLE TBL_TD_USER
(

  USER_ID                 INTEGER(10) NOT NULL,
  USER_NAME               VARCHAR2(20) NOT NULL,
  PASSWORD                VARCHAR2(20) NOT NULL,
  CREATED_BY              VARCHAR2(20) NOT NULL,
  CREATED_DATE            DATE NOT NULL,
  MODIFIED_BY             VARCHAR2(20) NOT NULL,
  MODIFIED_DATE           DATE NOT NULL,
  IS_ACTIVE               CHARACTER(1) NOT NULL,
  DESCRIPTION             VARCHAR2(200) NOT NULL,

  CONSTRAINT TBL_TD_USER PRIMARY KEY (USER_ID)

);

Body:
This works:

CREATE TABLE TBL_TD_USER
(
 USER_ID       INTEGER NOT NULL ,
 USER_NAME     VARCHAR2(20) NOT NULL,
 PASSWORD      VARCHAR2(20) NOT NULL,
 CREATED_BY    VARCHAR2(20) NOT NULL,
 CREATED_DATE  DATE NOT NULL,
 MODIFIED_BY   VARCHAR2(20) NOT NULL,
 MODIFIED_DATE DATE NOT NULL,
 IS_ACTIVE     VARCHAR2(1) NOT NULL,
 DESCRIPTION   VARCHAR2(200) NOT NULL,
 CONSTRAINT TBL_TD_USER PRIMARY KEY (USER_ID)
);

There's no variable type named CHARACTER in oracle, as an alternative, you to use VARCHAR2 with length value in parenthesis.

You can use INTEGER type without length.

demo


问:
How can i solve java.lang.NoClassDefFoundError: Failed resolution of: L(Activity Path)?

CODE in Activity_Splash

Gradle Version - 2.3.3

```<code>  catch (Exception e) {
                    Intent iLogin = new Intent(Activity_Splash.this, Activity_Login.class);
                    startActivity(iLogin);
                    finish();
                }
</code>```

App crashed on 6.0.1 but running perfectly on 4.2.2 by having follwing Runtime Exception:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main

java.lang.NoClassDefFoundError: Failed resolution of: Lelink/mWSS/Activity_Login

at elink.mWSS.Activity_Splash.login(Activity_Splash.java:116)

at elink.mWSS.Activity_Splash$1.run(Activity_Splash.java:55)

at android.os.Handler.handleCallback(Handler.java:739)

at android.os.Handler.dispatchMessage(Handler.java:95)

at android.os.Looper.loop(Looper.java:148)

at android.app.ActivityThread.main(ActivityThread.java:5437)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
</code>```

I searched for it but not getting any idea how to solve it, So can you solve this?

Build.gradle (Version of Gradle: 2.3.3)

```<code>android {
    compileSdkVersion 23
    buildToolsVersion "25.0.1"

    defaultConfig {
        applicationId ""
        minSdkVersion 14
        targetSdkVersion 22
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            lintOptions {
                disable 'MissingTranslation'
                checkReleaseBuilds false
                abortOnError false
            }
        }
    }
}
</code>```

Dependencies in Build.gradle

```<code>{

 compile 'com.android.support:multidex:1.0.0'
            compile 'com.android.support:support-v4:25.0.1'
            compile 'com.android.support:design:25.0.1'
            compile 'com.google.code.gson:gson:2.2.4'
            compile 'com.google.android.gms:play-services-maps:9.0.2'
            compile 'com.github.amlcurran.showcaseview:library:5.4.3'
            compile 'com.google.firebase:firebase-messaging:9.0.2'
            compile 'com.android.support:appcompat-v7:25.0.1'
}
</code>```

Please Help me to solve this issue..I am stucked in this

答: App crashed on 6.0.1 but running perfectly on 4.2.2 by having follwing Runtime Exception because your have set targetSdkVersion 22 and you are running your app in API 23. So, in API 23 permissions are needed during runtime and this may be the cause of crashing. Increase your targetSdkVersion 23 in build.gradle and in your manifest too. May be you have to download package for API 23, if it doesn't present in your sdk.

Body:
CODE in Activity_Splash

Gradle Version - 2.3.3

  catch (Exception e) {
                    Intent iLogin = new Intent(Activity_Splash.this, Activity_Login.class);
                    startActivity(iLogin);
                    finish();
                }

App crashed on 6.0.1 but running perfectly on 4.2.2 by having follwing Runtime Exception:

E/AndroidRuntime: FATAL EXCEPTION: main

java.lang.NoClassDefFoundError: Failed resolution of: Lelink/mWSS/Activity_Login

at elink.mWSS.Activity_Splash.login(Activity_Splash.java:116)

at elink.mWSS.Activity_Splash$1.run(Activity_Splash.java:55)

at android.os.Handler.handleCallback(Handler.java:739)

at android.os.Handler.dispatchMessage(Handler.java:95)

at android.os.Looper.loop(Looper.java:148)

at android.app.ActivityThread.main(ActivityThread.java:5437)

at java.lang.reflect.Method.invoke(Native Method)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

I searched for it but not getting any idea how to solve it, So can you solve this?

Build.gradle (Version of Gradle: 2.3.3)

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.1"

    defaultConfig {
        applicationId ""
        minSdkVersion 14
        targetSdkVersion 22
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_7
            targetCompatibility JavaVersion.VERSION_1_7
        }
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            lintOptions {
                disable 'MissingTranslation'
                checkReleaseBuilds false
                abortOnError false
            }
        }
    }
}

Dependencies in Build.gradle

{

 compile 'com.android.support:multidex:1.0.0'
            compile 'com.android.support:support-v4:25.0.1'
            compile 'com.android.support:design:25.0.1'
            compile 'com.google.code.gson:gson:2.2.4'
            compile 'com.google.android.gms:play-services-maps:9.0.2'
            compile 'com.github.amlcurran.showcaseview:library:5.4.3'
            compile 'com.google.firebase:firebase-messaging:9.0.2'
            compile 'com.android.support:appcompat-v7:25.0.1'
}

Please Help me to solve this issue..I am stucked in this


问:
gradle could not find other gradle script
```<code>/--common
/--common/build.gradle
/--common/deploy.gradle
/--project1
/--project1/build.gradle
</code>```

I have a multi-project structure and have extracted repeating code from my build.gradle file and placed this into another file deploy.gradle.

I have placed the deploy.gradle file into the common project at the same folder level as the build.gradle file. The folder structure is shown above.

In the build.gradle file of the common project I can reference the file using the statement,

```<code>apply from: 'deploy.gradle'
</code>```

This works like a dream and the common project build works perfectly calling in the tasks from the deploy.gradle file.

The problem comes when I try to reference deploy.gradle file from one of the other projects. When I add the apply... statement to the build.gradle of  project1 I get the compilation error,

Error:(23, 0) Could not read script
  'C:\path-to-project1-script-file\deploy.gradle' as it does not exist.

So Gradle is looking for the deploy.gradle file in project1 only even though I have a dependency set to the common project in the project1 build.gradle file.

Question is how can I make deploy.gradle from common project visible to project1.

答:
We successfully use the following project layout

```<code>├── a
│   └── build.gradle
├── b
│   └── build.gradle
├── build.gradle
├── gradle-scripts
│   └── deploy.gradle
└── settings.gradle
</code>```

The rootproject's build.gradle defines

```<code>ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}
</code>```

Subprojects use the scripts within gradle-scripts this way

```<code>apply from: gradleScript('deploy')
</code>```

Whole content of the project:

```<code>$> find . -type f | while read file; do echo "--- $file ---" && cat $file; done
--- ./a/build.gradle ---
apply from: gradleScript('deploy')
--- ./b/build.gradle ---
apply from: gradleScript('deploy')
--- ./build.gradle ---
// Where common build logic is found
ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}
--- ./gradle-scripts/deploy.gradle ---
task myDeployTask {
    doLast { println 'common deploy logic goes here' }
}
--- ./settings.gradle ---
include 'a', 'b'

$> gradle -q b:myDeployTask
common deploy logic goes here
$>
</code>```

Body:
/--common
/--common/build.gradle
/--common/deploy.gradle
/--project1
/--project1/build.gradle

I have a multi-project structure and have extracted repeating code from my build.gradle file and placed this into another file deploy.gradle.

I have placed the deploy.gradle file into the common project at the same folder level as the build.gradle file. The folder structure is shown above.

In the build.gradle file of the common project I can reference the file using the statement,

apply from: 'deploy.gradle'

This works like a dream and the common project build works perfectly calling in the tasks from the deploy.gradle file.

The problem comes when I try to reference deploy.gradle file from one of the other projects. When I add the apply... statement to the build.gradle of  project1 I get the compilation error,

Error:(23, 0) Could not read script
  'C:\path-to-project1-script-file\deploy.gradle' as it does not exist.

So Gradle is looking for the deploy.gradle file in project1 only even though I have a dependency set to the common project in the project1 build.gradle file.

Question is how can I make deploy.gradle from common project visible to project1.

Body:
We successfully use the following project layout

├── a
│   └── build.gradle
├── b
│   └── build.gradle
├── build.gradle
├── gradle-scripts
│   └── deploy.gradle
└── settings.gradle

The rootproject's build.gradle defines

ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}

Subprojects use the scripts within gradle-scripts this way

apply from: gradleScript('deploy')

Whole content of the project:

$> find . -type f | while read file; do echo "--- $file ---" && cat $file; done
--- ./a/build.gradle ---
apply from: gradleScript('deploy')
--- ./b/build.gradle ---
apply from: gradleScript('deploy')
--- ./build.gradle ---
// Where common build logic is found
ext.gradleScript = { scriptName ->
    file("${rootProject.projectDir}/gradle-scripts/${scriptName}.gradle")
}
--- ./gradle-scripts/deploy.gradle ---
task myDeployTask {
    doLast { println 'common deploy logic goes here' }
}
--- ./settings.gradle ---
include 'a', 'b'

$> gradle -q b:myDeployTask
common deploy logic goes here
$>


问:
How to fetch resource id in fragment using kotlin in android?
I tried to this code which is mention below, but getting crash during run time. The error occurred is Android Run time:

FATAL EXCEPTION: main                                                                        Process: com.root.specialbridge, PID: 17706                                                                        kotlin.KotlinNullPointerException at                                             com.root.specialbridge.fragments.profile_fragment.WallFragments.initializeView(WallFragments.kt:49)

```<code>class WallFragments : Fragment(){

private var wallAdapter: WallAdapter? = null
private var wall_recycler: RecyclerView? = null
private val wallArrayList: ArrayList<Wall>? = null
private var mainlayout: LinearLayout? = null
private var no_result_found_layout: RelativeLayout? = null
private var userProfileWallInterface: UserProfileWallInterface? = null
internal var wallActivityBeanse: MutableList<WallActivityBeans> = ArrayList()

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.wall_fragments, container, false)
    userProfileWallInterface = UserProfileWallPresentation(activity, this)
    initializeView()
    wallAdapter = WallAdapter(activity, wallActivityBeanse)
    wall_recycler!!.adapter = wallAdapter

    return view
}
fun initializeView() {
    wall_recycler = view!!.findViewById(R.id.wall_recycler_id) as RecyclerView
    mainlayout = view!!.findViewById(R.id.mainlayout) as LinearLayout
    no_result_found_layout = view!!.findViewById(R.id.no_result_found_layout) as RelativeLayout
    wall_recycler!!.layoutManager = LinearLayoutManager(activity)
    wall_recycler!!.setHasFixedSize(true)
    if (AuthPreference(activity).isGetMemberProfile) {
        userProfileWallInterface!!.getMemberProfileWall(view!!)

    } else {
        userProfileWallInterface!!.getUserProfileWall(AuthPreference(activity).token, AuthPreference(activity).user.id, view!!)

    }
}
companion object {
    val instance: WallFragments
        get() = WallFragments()  }}
</code>```

答:
Add

apply plugin: 'kotlin-android-extensions'

in the app level gradle file and

import

```<code>import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*
</code>```

in the onCreateView of your fragment (e.g. if the id of your textview is textView)

```<code>override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val view = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
    view.textView.text = "hello"   //add your view before id else getting nullpointer exception
    return view
}
</code>```

UPDATE:

declare viewOfLayout in your class instead of view.

```<code>class yourfragment:Fragment(){

    private lateinit var viewOfLayout: View
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        viewOfLayout = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
        viewOfLayout.textView.text = "hello"   //add your view before id else will get nullpointer exception
        return viewOfLayout
    }

}
</code>```

Body:
I tried to this code which is mention below, but getting crash during run time. The error occurred is Android Run time:

FATAL EXCEPTION: main                                                                        Process: com.root.specialbridge, PID: 17706                                                                        kotlin.KotlinNullPointerException at                                             com.root.specialbridge.fragments.profile_fragment.WallFragments.initializeView(WallFragments.kt:49)

class WallFragments : Fragment(){

private var wallAdapter: WallAdapter? = null
private var wall_recycler: RecyclerView? = null
private val wallArrayList: ArrayList<Wall>? = null
private var mainlayout: LinearLayout? = null
private var no_result_found_layout: RelativeLayout? = null
private var userProfileWallInterface: UserProfileWallInterface? = null
internal var wallActivityBeanse: MutableList<WallActivityBeans> = ArrayList()

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.wall_fragments, container, false)
    userProfileWallInterface = UserProfileWallPresentation(activity, this)
    initializeView()
    wallAdapter = WallAdapter(activity, wallActivityBeanse)
    wall_recycler!!.adapter = wallAdapter

    return view
}
fun initializeView() {
    wall_recycler = view!!.findViewById(R.id.wall_recycler_id) as RecyclerView
    mainlayout = view!!.findViewById(R.id.mainlayout) as LinearLayout
    no_result_found_layout = view!!.findViewById(R.id.no_result_found_layout) as RelativeLayout
    wall_recycler!!.layoutManager = LinearLayoutManager(activity)
    wall_recycler!!.setHasFixedSize(true)
    if (AuthPreference(activity).isGetMemberProfile) {
        userProfileWallInterface!!.getMemberProfileWall(view!!)

    } else {
        userProfileWallInterface!!.getUserProfileWall(AuthPreference(activity).token, AuthPreference(activity).user.id, view!!)

    }
}
companion object {
    val instance: WallFragments
        get() = WallFragments()  }}

Body:
Add

apply plugin: 'kotlin-android-extensions'

in the app level gradle file and

import

import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*

in the onCreateView of your fragment (e.g. if the id of your textview is textView)

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val view = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
    view.textView.text = "hello"   //add your view before id else getting nullpointer exception
    return view
}

UPDATE:

declare viewOfLayout in your class instead of view.

class yourfragment:Fragment(){

    private lateinit var viewOfLayout: View
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        viewOfLayout = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
        viewOfLayout.textView.text = "hello"   //add your view before id else will get nullpointer exception
        return viewOfLayout
    }

}