问:
Pattern matching HTTPoison.Response
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end
```

<p>The error I return is:</p>

<pre class="lang-rb prettyprint-override"><code>CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}
</code>```

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

答:
The Elixir convention is: banged versions of functions—instead of {:ok, result} and {:error, reason}—return result on success and raise on error. Grep this page for “Elixir doesn’t impose exceptions” for the reference.

HTTPoison follows this convention.

To make your code work, one should either use HTTPoison.post (not banged) in the very top case, or match the result respectively:

```<code>try
  %HTTPoison.Response{status: status, body: body} =
    HTTPoison.post!(...)
  case status do
    201 -> ...
    404 -> ...
  end
rescue
  e in HTTPoison.Error ->
    IO.inspect e
end
</code>```

Title: Pattern matching HTTPoison.Response

Body:
I'm trying handle the response from an API call using HTTPoison

In my app context I have

def add_to_cart(data, user) do
  case HTTPoison.post!(
      "https://api.moltin.com/v2/carts/" <> user <>
      "/items", data,
      [{"Authorization",
        "Bearer #{Agent.get(:token, fn state -> state end)}"},
       {"Content-Type", "application/json"}] do

    {:ok, %HTTPoison.Response{status_code: 201, body: body}} ->
      case Poison.decode(body) do
        {:ok, decoded} -> decoded
        {:error, error} -> {:error, error}
      end

    {:ok, %HTTPoison.Response{status_code: 404}} ->
      IO.puts "Not found :("

    {:error, %HTTPoison.Error{reason: reason}} ->
      IO.inspect reason

  end
end

The error I return is:

CaseClauseError at POST /order
no case clause matching: %HTTPoison.Response{response content}

I have used this pattern elsewhere in my code and it matches fine but when I place it here, it doesn't seem to work.

I'm sure this isn't enough information with which to work but I'm not sure at this point what else to put.  Any guidance would be appreciated.

Body:
The Elixir convention is: banged versions of functions—instead of {:ok, result} and {:error, reason}—return result on success and raise on error. Grep this page for “Elixir doesn’t impose exceptions” for the reference.

HTTPoison follows this convention.

To make your code work, one should either use HTTPoison.post (not banged) in the very top case, or match the result respectively:

try
  %HTTPoison.Response{status: status, body: body} =
    HTTPoison.post!(...)
  case status do
    201 -> ...
    404 -> ...
  end
rescue
  e in HTTPoison.Error ->
    IO.inspect e
end


来源: stackexchange

问:
SubSet sum with N array Solution, Dynamic Solution recquired
Though you can have any number of arrays but let's Suppose you have two arrays {1,2,3,4,5,6} and {1,2,3,4,5,6}
You have to find whether they sum upto 4 with participation of both array elements. i.e.

```<code>1 from array1, 3 from array2
2 from array1, 2 from array2
3 from array1, 1 from array2
</code>```

etc

In Nutshell:Want to implement SubSet Sum Algorithm where there is two arrays and array elements are chosen from both of the arrays to make up the target Sum

here is the subset sum algorithm that I use for one array

```<code>bool subset_sum(int a[],int n, int sum)
{
 bool dp[n+1][sum+1];

   int i,j;

   for(i=0;i<=n;i++)
      dp[i][0]=true;

   for(j=1;j<=sum;j++)
        dp[0][j]=false;

   for(i=1;i<=n;i++)

    {

        for(j=1;j<=sum;j++)

       {

           if(dp[i-1][j]==true)

              dp[i][j]=true;

           else
           {

               if(a[i-1]>j)

                   dp[i][j]=false;

                else

                    dp[i][j]=dp[i-1][j-a[i-1]];

            }

        }

    }
  return dp[n][sum];
}
</code>```

答:
Steps,</p>

```<code>find (Array1, Array2, N)
  sort Array1
  sort Array2

  for (i -> 0 && i < Array1.length) and (j -> Array2.length-1 && j >= 0)
    if(Array1[i] + Array2[j] == N)
      return yes;
    if(Array1[i] + Array2[j] > N)
      j--;
    else
      i++;
  return NO;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Though you can have any number of arrays but let's Suppose you have two arrays {1,2,3,4,5,6} and {1,2,3,4,5,6}
You have to find whether they sum upto 4 with participation of both array elements. i.e.

1 from array1, 3 from array2
2 from array1, 2 from array2
3 from array1, 1 from array2

etc

In Nutshell:Want to implement SubSet Sum Algorithm where there is two arrays and array elements are chosen from both of the arrays to make up the target Sum

here is the subset sum algorithm that I use for one array

bool subset_sum(int a[],int n, int sum)
{
 bool dp[n+1][sum+1];

   int i,j;

   for(i=0;i<=n;i++)
      dp[i][0]=true;

   for(j=1;j<=sum;j++)
        dp[0][j]=false;

   for(i=1;i<=n;i++)

    {

        for(j=1;j<=sum;j++)

       {

           if(dp[i-1][j]==true)

              dp[i][j]=true;

           else
           {

               if(a[i-1]>j)

                   dp[i][j]=false;

                else

                    dp[i][j]=dp[i-1][j-a[i-1]];

            }

        }

    }
  return dp[n][sum];
}

Body:
Steps,

find (Array1, Array2, N)
  sort Array1
  sort Array2

  for (i -> 0 && i < Array1.length) and (j -> Array2.length-1 && j >= 0)
    if(Array1[i] + Array2[j] == N)
      return yes;
    if(Array1[i] + Array2[j] > N)
      j--;
    else
      i++;
  return NO;


问:
Can't center content in a column
I have a box with two parts - an information panel and a pic. I'm trying to get two of these boxes in the same row, centered in their respective column.

I've tried all the solutions I've found on this site. Center-block, align="center", margin: auto, float and plenty others. I cannot figure this out.

Anytime I try to apply some sort of centering class, it moves the pic a little bit and nothing else.

Here's the code. I tried adding a class to the divs that have comments saying first and second box. I've since removed it since it had no effect.

.box-sm {
  background-color: #e0dbc8;
  width: 300px;
  height: 300px;
  margin: 0px;
  padding: 0px;
}

.box-sm-pic {
  margin: 0px;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid">
  <div class="row">
    <div class="col-lg-6">
      <!-- First Box -->
      <div class="row">
        <div class="col-lg-6 box-sm">
          <!-- Header, Description and button -->
          <h2>ROOMS</h2>
          <br>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur maiores eum quod repudiandae, voluptates recusandae?</p>
          <br><button type="button" class="btn btn-primary center-block">BOOK NOW</button>
        </div>
        <div class="col-lg-6 box-sm-pic">
          <!-- Image -->
          <img src="img/box-rooms.jpg" class="img-responsive" width="300" height="300" alt="" />
        </div>
      </div>
    </div>
    <div class="col-lg-6">
      <!-- Second Box -->
      <div class="row">
        <div class="col-lg-6 box-sm">
          <!-- Header, Description and button -->
          <h2>ROOMS</h2>
          <br>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur maiores eum quod repudiandae, voluptates recusandae?</p>
          <br>
          <button type="button" class="btn btn-primary center-block">BOOK NOW</button>
        </div>
        <div class="col-lg-6 box-sm-pic">
          <!-- Image -->
          <img src="img/box-rooms.jpg" class="img-responsive" width="300" height="300" alt="" />
        </div>
      </div>
    </div>
  </div>
</div></code>```

The boxes appear correctly but are left aligned. Someone please help!

答:
if you can center a something with align or anything maybe the style crush with another style
but you can still center your item with this your item

Title: Can't center content in a column

Body:
I have a box with two parts - an information panel and a pic. I'm trying to get two of these boxes in the same row, centered in their respective column.

I've tried all the solutions I've found on this site. Center-block, align="center", margin: auto, float and plenty others. I cannot figure this out.

Anytime I try to apply some sort of centering class, it moves the pic a little bit and nothing else.

Here's the code. I tried adding a class to the divs that have comments saying first and second box. I've since removed it since it had no effect.

.box-sm {
  background-color: #e0dbc8;
  width: 300px;
  height: 300px;
  margin: 0px;
  padding: 0px;
}

.box-sm-pic {
  margin: 0px;
  padding: 0px;
}

ROOMS

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur maiores eum quod repudiandae, voluptates recusandae?

<button type="button" class="btn btn-primary center-block">BOOK NOW</button>

ROOMS

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur maiores eum quod repudiandae, voluptates recusandae?

          <button type="button" class="btn btn-primary center-block">BOOK NOW</button>

The boxes appear correctly but are left aligned. Someone please help!

Body:
if you can center a something with align or anything maybe the style crush with another style
but you can still center your item with this <center>your item</center>


问:
Dynamically change header string in angular 2
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

```<code><h1>{{title}}</h1>
</code>```

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

答:
Based on OP's requirement, it seems OP needs to bind a string property to the page.

In your component have a property. Since its a fix string you can initialize it on each component like:

```<code> public title:string = 'About me';
</code>```

and in your HTML just:

{{title}}

Update:

Since it is to be bound to a constant header component, you will have to emit an event from each component using EventEmitter and listen to it across multiple components in your app and accordingly update the title property.

As suggested by Aamir in comments: You can have a service, wherein you can create an Observable and then update its next value in each component. The observable can then be subscribed in the header component to update the title property.

ContentLicense: CC BY-SA 4.0

Body:
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

{{title}}

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

Body:
Based on OP's requirement, it seems OP needs to bind a string property to the page.

In your component have a property. Since its a fix string you can initialize it on each component like:

 public title:string = 'About me';

and in your HTML just:

<h1>{{title}}</h1>

Update:

Since it is to be bound to a constant header component, you will have to emit an event from each component using EventEmitter and listen to it across multiple components in your app and accordingly update the title property.

As suggested by Aamir in comments: You can have a service, wherein you can create an Observable and then update its next value in each component. The observable can then be subscribed in the header component to update the title property.


问:
Merging QR Code with an image
I'm trying to merge QR Code with an image but no luck. It keeps giving me:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference.

Here is the class to resize and merge:

```<code>    public Bitmap mergeBitmaps(Bitmap myLogo, Bitmap bitmap){
    Bitmap combined = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
    Canvas canvas = new Canvas(combined);
    int canvasWidth = canvas.getWidth();
    int canvasHeight = canvas.getHeight();
    canvas.drawBitmap(bitmap, new Matrix(), null);

    Bitmap resizeLogo = Bitmap.createScaledBitmap(myLogo, canvasWidth / 5, canvasHeight / 5, true);
    int centreX = (canvasWidth - resizeLogo.getWidth()) /2;
    int centreY = (canvasHeight - resizeLogo.getHeight()) / 2;
    canvas.drawBitmap(resizeLogo, centreX, centreY, null);
    return combined;
}
</code>```

And here is how I push it into the ImageView:

```<code>    Bitmap myLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
    Bitmap merge = mergeBitmaps(myLogo, bitmap);

    imageView.setImageBitmap(merge);
</code>```

Please help :(

Edit: The nullpointerexcepion is pointing to Bitmap myLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);

答: So it seems like I tried all the drawable images that I have and some works, some don't, I'm not sure yet what's the requirement of limitation :/</p>

Title: Merging QR Code with an image

Body:
I'm trying to merge QR Code with an image but no luck. It keeps giving me:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference.

Here is the class to resize and merge:

    public Bitmap mergeBitmaps(Bitmap myLogo, Bitmap bitmap){
    Bitmap combined = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig());
    Canvas canvas = new Canvas(combined);
    int canvasWidth = canvas.getWidth();
    int canvasHeight = canvas.getHeight();
    canvas.drawBitmap(bitmap, new Matrix(), null);

    Bitmap resizeLogo = Bitmap.createScaledBitmap(myLogo, canvasWidth / 5, canvasHeight / 5, true);
    int centreX = (canvasWidth - resizeLogo.getWidth()) /2;
    int centreY = (canvasHeight - resizeLogo.getHeight()) / 2;
    canvas.drawBitmap(resizeLogo, centreX, centreY, null);
    return combined;
}

And here is how I push it into the ImageView:

    Bitmap myLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);
    Bitmap merge = mergeBitmaps(myLogo, bitmap);

    imageView.setImageBitmap(merge);

Please help :(

Edit: The nullpointerexcepion is pointing to Bitmap myLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_background);


问:
Separately execute a section of php code on a web page
This is a best practice type question.  I'm dealing with two different frameworks.  When I execute a piece of code from one framework on the page of another framework, I'm getting a code conflict.  What I'm wondering is how to execute a piece of code on a separate web page and bring in the results AFTER the php on that page has executed and produced its HTML.

One Possible Solution

Use Curl - I could house the additional code on a curl page and bring it in that way, but that seems to have a lot of overhead associated with it.

Is there a lower overhead way of doing this than using curl?

More info

Specifically in this case I'm trying to use a magento php script in my page, and the autoloader is trying to load in other scripts in the directory that should not be auto loaded.

答:
Resolve the 'conflict' by wrapping the library code in an class where you define the interface. Then call that class directly.

Adding a server side request to another resource will extend the time each request takes (remember the second request has to fire up a database connection, load the framework, carry out a db query etc).

ContentLicense: CC BY-SA 2.5


问:
How to show a dynamic content in the same page using Angularjs 1.6?
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

```<code>   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}
</code>```

Script.js

```<code>app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);
</code>```

News.html

```<code><div class="container-fluid">

    <div class="row">

        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="NewsRendering">
                <div ng-repeat="NewsData in News.Articles">
                    <h3>{{NewsData.Title}}</h3>
                    <p>{{NewsData.Abstract}}</p>
                    <a data-ng-href="/AngularTask/NewsViewer.html">more</a>
                </div>
            </div>
        </div>

        <div class="col-md-4 questionnaire">
            <h3>Questionnaire of the day</h3>
        </div>

    </div>

</div>
</code>```

NewsViewer.html

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Articles[0].Title}}</h3>
                    <p>{{News.Articles[0].Abstract}}</p>
                    <p>{{News.Articles[0].Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Articles[0].Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

答:
You can do it by passing the index of the news to the /News route.

First, change News.html so it tracks the data by index, and then appends the index of the item to the ng-href.

```<code><div ng-repeat="NewsData in News.Articles track by $index">
  <h3>{{NewsData.Title}}</h3>
  <p>{{NewsData.Abstract}}</p>
  <a data-ng-href="/AngularTask/NewsViewer.html?index={{$index}}">more</a>
</div>
</code>```

Now, for each visit, you will see a new query parameter in the NewsViewer route, which will be index.

Second, change the controller, so it takes the advantage of passed index using $routeParams.

```<code>app.controller("showNews", ["$scope", "$http", "$routeParams",
  function ($scope, $http, $routeParams) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data.Articles[$routeParams.index];
    });
}]);
</code>```

This way, $scope.News will contain the article which resides on the passed index.

Finally, change NewsViewer.html so that it uses $scope.News.

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Title}}</h3>
                    <p>{{News.Abstract}}</p>
                    <p>{{News.Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

For comments, you can again use ng-repeat directive to show all the comments, iterating over them one-by-one.

Hope this answers your question.

Body:
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}

Script.js

app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);

News.html

{{NewsData.Title}}

{{NewsData.Abstract}}

                    more

Questionnaire of the day

NewsViewer.html

{{News.Articles[0].Title}}

{{News.Articles[0].Abstract}}

{{News.Articles[0].Body}}

Comments

{{News.Articles[0].Comments[0]}}

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

Body:
You can do it by passing the index of the news to the /News route.

First, change News.html so it tracks the data by index, and then appends the index of the item to the ng-href.

<div ng-repeat="NewsData in News.Articles track by $index">
  <h3>{{NewsData.Title}}</h3>
  <p>{{NewsData.Abstract}}</p>
  <a data-ng-href="/AngularTask/NewsViewer.html?index={{$index}}">more</a>
</div>

Now, for each visit, you will see a new query parameter in the NewsViewer route, which will be index.

Second, change the controller, so it takes the advantage of passed index using $routeParams.

app.controller("showNews", ["$scope", "$http", "$routeParams",
  function ($scope, $http, $routeParams) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data.Articles[$routeParams.index];
    });
}]);

This way, $scope.News will contain the article which resides on the passed index.

Finally, change NewsViewer.html so that it uses $scope.News.

<div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Title}}</h3>
                    <p>{{News.Abstract}}</p>
                    <p>{{News.Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>

For comments, you can again use ng-repeat directive to show all the comments, iterating over them one-by-one.

Hope this answers your question.


问:
Checking if table exist in database
I have a JDBC code which retrieves data from database and get queries at runtime. At runtime, it will go to database and will try to get data and write it to a file. If table is not present it gives exception that table not found.  How to handle this?

Here I can not use,

```<code>ResultSet rs = md.getTable()
</code>```

I have to check at runtime only.

SQL Example : select * from table; Preparedstatement and ResultSet here,

At runtime this table variable will get names of table when loop above this will iterate.  If table is not there then it gives this exception on console.

How to handle this smoothly?

答:
If you dont want that exception, first you should check what tables are there in the database. If the table doesn't exist you can create and avoid that exception.

```<code>DatabaseMetaData dbm = con.getMetaData();
ResultSet tables = dbm.getTables(null, null, "your_table_name", null);
if (tables.next()) {
  // Table exists
}
else {
  // Table does not exist
}
</code>```

if the table doesnot exist, you may need to create a new table to avoid such exception later.

Title: Checking if table exist in database

Body:
I have a JDBC code which retrieves data from database and get queries at runtime. At runtime, it will go to database and will try to get data and write it to a file. If table is not present it gives exception that table not found.  How to handle this?

Here I can not use,

ResultSet rs = md.getTable()

I have to check at runtime only.

SQL Example : select * from table; Preparedstatement and ResultSet here,

At runtime this table variable will get names of table when loop above this will iterate.  If table is not there then it gives this exception on console.

How to handle this smoothly?

Body:
If you dont want that exception, first you should check what tables are there in the database. If the table doesn't exist you can create and avoid that exception.

DatabaseMetaData dbm = con.getMetaData();
ResultSet tables = dbm.getTables(null, null, "your_table_name", null);
if (tables.next()) {
  // Table exists
}
else {
  // Table does not exist
}

if the table doesnot exist, you may need to create a new table to avoid such exception later.


问:
setNavigationBarHidden animation not working as expected on iPhone X
I have code that enters full screen mode by hiding the UINavigationController's navigation bar. I want a smooth animated zooming effect when entering full screen. I use setNavigationBarHidden(_:animated:). This has all worked fine up to now, even on iOS 11, but on iPhone X the animation is not working well. On hiding, there is no animation and the nav bar just disappears. On unhiding, it does animate but the nav bar appears at a slower rate than the navigation controller's content area reduces, so an ugly black background shows through the navigation bar area during the animation.

I can recreate this in a simple test app. I have a UIViewController embedded in a UINavigationController.

Storyboard

UINavigationController Navigation Bar: Style == Black; Translucent OFF

UIViewController: Extend Edges: all options OFF.

I have tried all the combinations of Adjust Scroll View Insets and Extend Edges that I can think of but they made no difference.

Code

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    setFullScreen(on: fullScreen, animated: animated)
}

override var prefersStatusBarHidden: Bool
{
    return fullScreen
}

override var preferredStatusBarStyle: UIStatusBarStyle
{
    return .lightContent
}

@IBAction func onToggleNavBarVisibility(_ sender: Any) {

    if let navBarHidden = self.navigationController?.isNavigationBarHidden {
        // Toggle the state
        fullScreen = !navBarHidden

        setFullScreen(on: fullScreen, animated: true)
    }
}

private func setFullScreen(on : Bool, animated : Bool) {

    self.navigationController?.setNavigationBarHidden(on, animated: animated)
    self.setNeedsStatusBarAppearanceUpdate()
}
</code>```

答:
In your case you are using both barTintColor & navigationBarStyle with Show Hide animation.
barTintColor overrides the value implied by the Style attribute
You should select either barTintColor or  navigationBarStyle
In below code i have just used  barTintColor & navigationBarStyle is default with Transulent.

```<code>    var fullScreen = false{
      didSet{
        self.setNeedsStatusBarAppearanceUpdate()
     }
   }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Navigation Bar"
        navigationController?.navigationBar.barTintColor = .red
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        setFullScreen(on: fullScreen, animated: animated)
    }
    @IBAction func onToggleNavBarVisibility(_ sender: Any) {
        if let navBarHidden =
          self.navigationController?.isNavigationBarHidden {
            // Toggle the state
            fullScreen = !navBarHidden
            setFullScreen(on: fullScreen, animated: true)
        }
    }
    private func setFullScreen(on : Bool, animated : Bool) {
        self.navigationController?.setNavigationBarHidden(on, animated: animated)
        self.setNeedsStatusBarAppearanceUpdate()
    }
</code>```

EDIT:
If you want to hide status bar-
use prefersStatusBarHidden with the bool value. & use setNeedsStatusBarAppearanceUpdate

```<code>   override var prefersStatusBarHidden: Bool {
        return fullScreen
    }
</code>```

https://developer.apple.com/documentation/uikit/uinavigationbar

Body:
I have code that enters full screen mode by hiding the UINavigationController's navigation bar. I want a smooth animated zooming effect when entering full screen. I use setNavigationBarHidden(_:animated:). This has all worked fine up to now, even on iOS 11, but on iPhone X the animation is not working well. On hiding, there is no animation and the nav bar just disappears. On unhiding, it does animate but the nav bar appears at a slower rate than the navigation controller's content area reduces, so an ugly black background shows through the navigation bar area during the animation.

I can recreate this in a simple test app. I have a UIViewController embedded in a UINavigationController.

Storyboard

UINavigationController Navigation Bar: Style == Black; Translucent OFF

UIViewController: Extend Edges: all options OFF.

I have tried all the combinations of Adjust Scroll View Insets and Extend Edges that I can think of but they made no difference.

Code

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    setFullScreen(on: fullScreen, animated: animated)
}

override var prefersStatusBarHidden: Bool
{
    return fullScreen
}

override var preferredStatusBarStyle: UIStatusBarStyle
{
    return .lightContent
}

@IBAction func onToggleNavBarVisibility(_ sender: Any) {

    if let navBarHidden = self.navigationController?.isNavigationBarHidden {
        // Toggle the state
        fullScreen = !navBarHidden

        setFullScreen(on: fullScreen, animated: true)
    }
}

private func setFullScreen(on : Bool, animated : Bool) {

    self.navigationController?.setNavigationBarHidden(on, animated: animated)
    self.setNeedsStatusBarAppearanceUpdate()
}

Body:
In your case you are using both barTintColor & navigationBarStyle with Show Hide animation.
barTintColor overrides the value implied by the Style attribute
You should select either barTintColor or  navigationBarStyle
In below code i have just used  barTintColor & navigationBarStyle is default with Transulent.

    var fullScreen = false{
      didSet{
        self.setNeedsStatusBarAppearanceUpdate()
     }
   }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Navigation Bar"
        navigationController?.navigationBar.barTintColor = .red
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        setFullScreen(on: fullScreen, animated: animated)
    }
    @IBAction func onToggleNavBarVisibility(_ sender: Any) {
        if let navBarHidden =
          self.navigationController?.isNavigationBarHidden {
            // Toggle the state
            fullScreen = !navBarHidden
            setFullScreen(on: fullScreen, animated: true)
        }
    }
    private func setFullScreen(on : Bool, animated : Bool) {
        self.navigationController?.setNavigationBarHidden(on, animated: animated)
        self.setNeedsStatusBarAppearanceUpdate()
    }

EDIT:
If you want to hide status bar-
use prefersStatusBarHidden with the bool value. & use setNeedsStatusBarAppearanceUpdate

   override var prefersStatusBarHidden: Bool {
        return fullScreen
    }

https://developer.apple.com/documentation/uikit/uinavigationbar


问:
Limit characters by UITextView height
Using the following code I'm attempting to limit the height of my UITextView by disallowing the user to enter characters once the UITextView is beyond a certain content size. But the problem is that with the current code, the last character after the height limit is written anyway such that one character ends up on its own line alone and that line is beyond the height limit.

How I can fix my code so that the text doesn't go past my height limit?

```<code>func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    var frame:CGRect = textView.frame;

    frame.size.height = textView.contentSize.height;

    if(frame.size.height <= 33.0){
        return true
    }
    else {
        return false
    }
}
</code>```

答:
Thanks @lyndsey-scott, Below is the same code updated for latest sdk in xcode 9.1. Made minor edits (replaced max height as a variable)</p>

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // Combine the new text with the old
    let combinedText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    // Create attributed version of the text
    let attributedText = NSMutableAttributedString(string: combinedText)
    let font = textView.font ?? UIFont.systemFont(ofSize: 12.0)
    attributedText.addAttribute(NSAttributedStringKey.font, value: font, range: NSMakeRange(0, attributedText.length))
    // Get the padding of the text container
    let padding = textView.textContainer.lineFragmentPadding
    // Create a bounding rect size by subtracting the padding
    // from both sides and allowing for unlimited length
    let boundingSize = CGSize(width: textView.frame.size.width - padding * 2, height: CGFloat.greatestFiniteMagnitude)
    // Get the bounding rect of the attributed text in the
    // given frame
    let boundingRect = attributedText.boundingRect(with: boundingSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
    // Compare the boundingRect plus the top and bottom padding
    // to the text view height; if the new bounding height would be
    // less than or equal to the height limit, append the text
    if (boundingRect.size.height + padding * 2 <= MyViewController.maximumHeaderHeight){
        return true
    } else {
        return false
    }
}
</code>```

Title: Limit characters by UITextView height

Body:
Using the following code I'm attempting to limit the height of my UITextView by disallowing the user to enter characters once the UITextView is beyond a certain content size. But the problem is that with the current code, the last character after the height limit is written anyway such that one character ends up on its own line alone and that line is beyond the height limit.

How I can fix my code so that the text doesn't go past my height limit?

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    var frame:CGRect = textView.frame;

    frame.size.height = textView.contentSize.height;

    if(frame.size.height <= 33.0){
        return true
    }
    else {
        return false
    }
}

Body:
Thanks @lyndsey-scott, Below is the same code updated for latest sdk in xcode 9.1. Made minor edits (replaced max height as a variable)

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // Combine the new text with the old
    let combinedText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    // Create attributed version of the text
    let attributedText = NSMutableAttributedString(string: combinedText)
    let font = textView.font ?? UIFont.systemFont(ofSize: 12.0)
    attributedText.addAttribute(NSAttributedStringKey.font, value: font, range: NSMakeRange(0, attributedText.length))
    // Get the padding of the text container
    let padding = textView.textContainer.lineFragmentPadding
    // Create a bounding rect size by subtracting the padding
    // from both sides and allowing for unlimited length
    let boundingSize = CGSize(width: textView.frame.size.width - padding * 2, height: CGFloat.greatestFiniteMagnitude)
    // Get the bounding rect of the attributed text in the
    // given frame
    let boundingRect = attributedText.boundingRect(with: boundingSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
    // Compare the boundingRect plus the top and bottom padding
    // to the text view height; if the new bounding height would be
    // less than or equal to the height limit, append the text
    if (boundingRect.size.height + padding * 2 <= MyViewController.maximumHeaderHeight){
        return true
    } else {
        return false
    }
}


问:
generic code for creating an X*Y 2 dimensional list in python
I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g.

```<code>myList = createList(2,3,"-")
</code>```

would create the resulting list:
[["-", "-", "-"]
 ["-", "-", "-"]]

so far I've created the following function for this but it puts all the initial values on one list:

```<code>def createList(x,y,val):
    myList=[]
    for i in range(x):
        for j in range(y):
            myList.append(val)
    return myList

print(createList(2,3,"-"))
</code>```

which creates the output: ['-', '-', '-', '-', '-', '-']

答:
You could simply use the list comprehension in python to create a 2D array in python.</p>

```<code>def create2DArray(x, y, val):
    return [[val for i in range(y)] for j in range(x)]

myList = create2DArray(2, 3, '-')
print(myList)
</code>```

Body:
I'm trying to create a function with three parameters: x,y,val that will return a two dimensional array with x rows and y columns and every single value initialized to val. e.g.

myList = createList(2,3,"-")

would create the resulting list:
[["-", "-", "-"]
 ["-", "-", "-"]]

so far I've created the following function for this but it puts all the initial values on one list:

def createList(x,y,val):
    myList=[]
    for i in range(x):
        for j in range(y):
            myList.append(val)
    return myList

print(createList(2,3,"-"))

which creates the output: ['-', '-', '-', '-', '-', '-']

Body:
You could simply use the list comprehension in python to create a 2D array in python.

def create2DArray(x, y, val):
    return [[val for i in range(y)] for j in range(x)]

myList = create2DArray(2, 3, '-')
print(myList)


问:
Invoke a method every 5 minutes during working hours/days - Quartz.net
In short, I want to invoke a method at each 5 minutes, but only during the working time. At first I was trying to use Thread.Sleep() and at each invocation, I tried to calculate the amount of sleep time. Somehow, it did not work very well.

Here is the code that calculates the time for sleep.

```<code>    void Main()
    {
       while(true)
       {
         Work()
         Thread.Sleep(GetSleepTime());
       }
    }

    int GetSleepTime()
    {
        int time = 0;
        var now = DateTime.Now;
        var isWorkingTime = false;

        switch (now.DayOfWeek)
        {
            case DayOfWeek.Saturday:
            case DayOfWeek.Sunday:
                break;
            default:
                if (now.Hour >= 10 && now.Hour <= 19)
                {
                    time = 5 * 60 * 1000;
                    isWorkingTime = true;
                }
                break;
        }

        if (!isWorkingTime)
        {
            int remainingDays = 1;
            switch (now.DayOfWeek)
            {
                case DayOfWeek.Friday:
                    remainingDays = 3;
                    break;
                case DayOfWeek.Saturday:
                    remainingDays = 2;
                    break;
            }

            DateTime nextWorkingday = now.AddDays(remainingDays).Date;
            DateTime nextWorkingday10 = nextWorkingday.AddHours(10);
            time = (int)(nextWorkingday10 - now).TotalMilliseconds;
        }

        return time;
    }
</code>```

Is this a suitable thing to use Quartz.NET for? If so, how can I do the same thing with it?

答:
You need not use sleep. Quartz.net is intended to take care of the scheduling part.
You need to create a job and its trigger.

```<code>* 0/5 9,17 * * MON-FRI
</code>```

The above trigger will execute the job every 5 minutes from 9AM to 5PM

Below is an alternate Option:

If you are using v2+, you can use the following trigger definition from within the code.

```<code>ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .WithDailyTimeIntervalSchedule(
        x => x.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(9, 0))
                 .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(17, 0))
                 .OnMondayThroughFriday()
                 .WithIntervalInMinutes(5))
    .Build();
</code>```

Body:
In short, I want to invoke a method at each 5 minutes, but only during the working time. At first I was trying to use Thread.Sleep() and at each invocation, I tried to calculate the amount of sleep time. Somehow, it did not work very well.

Here is the code that calculates the time for sleep.

    void Main()
    {
       while(true)
       {
         Work()
         Thread.Sleep(GetSleepTime());
       }
    }

    int GetSleepTime()
    {
        int time = 0;
        var now = DateTime.Now;
        var isWorkingTime = false;

        switch (now.DayOfWeek)
        {
            case DayOfWeek.Saturday:
            case DayOfWeek.Sunday:
                break;
            default:
                if (now.Hour >= 10 && now.Hour <= 19)
                {
                    time = 5 * 60 * 1000;
                    isWorkingTime = true;
                }
                break;
        }

        if (!isWorkingTime)
        {
            int remainingDays = 1;
            switch (now.DayOfWeek)
            {
                case DayOfWeek.Friday:
                    remainingDays = 3;
                    break;
                case DayOfWeek.Saturday:
                    remainingDays = 2;
                    break;
            }

            DateTime nextWorkingday = now.AddDays(remainingDays).Date;
            DateTime nextWorkingday10 = nextWorkingday.AddHours(10);
            time = (int)(nextWorkingday10 - now).TotalMilliseconds;
        }

        return time;
    }

Is this a suitable thing to use Quartz.NET for? If so, how can I do the same thing with it?

Body:
You need not use sleep. Quartz.net is intended to take care of the scheduling part.
You need to create a job and its trigger.

* 0/5 9,17 * * MON-FRI

The above trigger will execute the job every 5 minutes from 9AM to 5PM

Below is an alternate Option:

If you are using v2+, you can use the following trigger definition from within the code.

ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .WithDailyTimeIntervalSchedule(
        x => x.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(9, 0))
                 .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(17, 0))
                 .OnMondayThroughFriday()
                 .WithIntervalInMinutes(5))
    .Build();


问:
Cannot read property 'ref' of undefined
I'm building a simple web app with Vue + Firebase + Vuefire and I get "Uncaught TypeError: Cannot read property 'ref' of undefined" when I try to use my Firebase db variable inside a component.

In main.js

```<code>Vue.use(VueFire)

const firebaseApp = Firebase.initializeApp({ //setting })

// Export the database for components to use.
export const db = firebaseApp.database()
</code>```

And in my component

```<code>// in Recipes.vue
import {db} from '../main.js'

export default {
  recipe: {
    source: db.ref('recipes')
    // Console says: "Uncaught TypeError: Cannot read property 'ref' of undefined"
  }
}
</code>```

I followed the steps in this tutorial https://alligator.io/vuejs/vuefire-firebase/

This code db.ref('recipes') works if used inside main.js, but it never works once I import it inside my component.

答:
.ref is a firebase function, you need to import it. try

```<code>import Firebase from 'firebase'
</code>```

or

```<code>import * from 'firebase'
</code>```

Title: Cannot read property 'ref' of undefined

Body:
I'm building a simple web app with Vue + Firebase + Vuefire and I get "Uncaught TypeError: Cannot read property 'ref' of undefined" when I try to use my Firebase db variable inside a component.

In main.js

Vue.use(VueFire)

const firebaseApp = Firebase.initializeApp({ //setting })

// Export the database for components to use.
export const db = firebaseApp.database()

And in my component

// in Recipes.vue
import {db} from '../main.js'

export default {
  recipe: {
    source: db.ref('recipes')
    // Console says: "Uncaught TypeError: Cannot read property 'ref' of undefined"
  }
}

I followed the steps in this tutorial https://alligator.io/vuejs/vuefire-firebase/

This code db.ref('recipes') works if used inside main.js, but it never works once I import it inside my component.

Body:
.ref is a firebase function, you need to import it. try

import Firebase from 'firebase'

or

import * from 'firebase'


问:
how to simplify scala's function literal like this?
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

```warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1
```

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

答:
The problem is basically that Scala needs to tell the difference between

```<code>val isOdd = ((_:Int) & 1 ) == 1
</code>```

where you want everything to the right of the equals sign to be a lambda, and

```<code>val result = collection.map( _ + 1 )
</code>```

where you want only the stuff inside the parentheses to be a lambda

Scala has decided that when you use the underscore to create a lambda, that it's going to pick the innermost set of parentheses as the boundaries of that lambda. There's one exception: (_:Int) doesn't count as the innermost parentheses because its purpose is only to group they type declaration with the _ placeholder.

Hence:

```<code>val isOdd = ((_:Int) & 1 ) == 1
            ^^^^^^^^^^^^^^
            this is the lambda

val result = collection.map( _ + 1 )
                            ^^^^^^^
                            this is the lambda

val result = collection.map(( _ + 1) / 2)
                            ^^^^^^^^
                            this is the lambda
                            and the compiler can't infer the type of the _

val result = somemap.map(( _ + 1) / 2 * _)
                         ^^^^^^^^
                         this is an inner lambda with one parameter
                         and the compiler can't infer the type of the _
                         ^^^^^^^^^^^^^^^^^
                         this is an outer lambda with one parameter
</code>```

This last case lets you do things like

```<code>_.map(_ + 1)
</code>```

and have that get translated into

```<code>x => x.map( y=> y + 1 )
</code>```

Body:
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

Body:
The problem is basically that Scala needs to tell the difference between

val isOdd = ((_:Int) & 1 ) == 1

where you want everything to the right of the equals sign to be a lambda, and

val result = collection.map( _ + 1 )

where you want only the stuff inside the parentheses to be a lambda

Scala has decided that when you use the underscore to create a lambda, that it's going to pick the innermost set of parentheses as the boundaries of that lambda. There's one exception: (_:Int) doesn't count as the innermost parentheses because its purpose is only to group they type declaration with the _ placeholder.

Hence:

val isOdd = ((_:Int) & 1 ) == 1
            ^^^^^^^^^^^^^^
            this is the lambda

val result = collection.map( _ + 1 )
                            ^^^^^^^
                            this is the lambda

val result = collection.map(( _ + 1) / 2)
                            ^^^^^^^^
                            this is the lambda
                            and the compiler can't infer the type of the _

val result = somemap.map(( _ + 1) / 2 * _)
                         ^^^^^^^^
                         this is an inner lambda with one parameter
                         and the compiler can't infer the type of the _
                         ^^^^^^^^^^^^^^^^^
                         this is an outer lambda with one parameter

This last case lets you do things like

_.map(_ + 1)

and have that get translated into

x => x.map( y=> y + 1 )


问:
Break Array Values Into New Line in Angular
How can i break this array of errors into new line? I tried using "\n" and it doesn't break into lines in Angular?

JSON

```<code>{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}
</code>```

error.ts

```<code>error => {
             alert("ERROR" + "\n" +  error.error.error + "\n");
             console.log(error.error.error);
          });
</code>```

答:
You can use array#join() with
 to insert breakline when displaying error in HTML page. When you want to display error in alert() or console you can array#join('\n').

var error = {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://sample.com","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://sample.com: 404 Not Found","error":{"error":["Error1","Error2","Error3"]}}
alert(error.error.error.join('\n'));
document.write(error.error.error.join('
'));```

Body:
How can i break this array of errors into new line? I tried using "\n" and it doesn't break into lines in Angular?

JSON

{
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}

error.ts

error => {
             alert("ERROR" + "\n" +  error.error.error + "\n");
             console.log(error.error.error);
          });

Body:
You can use array#join() with <br> to insert breakline when displaying error in HTML page. When you want to display error in alert() or console you can array#join('\n').

var error = {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url":"http://sample.com","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://sample.com: 404 Not Found","error":{"error":["Error1","Error2","Error3"]}}
alert(error.error.error.join('\n'));
document.write(error.error.error.join('<br>'));


问:
Generic application controller action
I have a rails app that displays user activity on the RHS on each page.

Presently I pass the collection to the partial directly:

```<code><%= render partial: "activities/activity", collection: current_user.activities.order(created_at: :desc) %>
</code>```

I wish to now paginate this activity list.

```<code>current_user.activities.order(created_at: :desc).page(params[:page]).per_page(10)
</code>```

I am guessing I need to have this set as an instance variable and have it placed in a route that can be accessed from the view.

My question is where should I define this instance variable as the route needs to be generic as the activity is displayed on a views.

If it helps I am doing the pagination with ajax, "remote: true".

答:
I think what you need to do is have a controller action that receives the ajax request which would include the page number. This action would pull up the relevant activities for that page (using the code you put in the question) then it would render some js which would clear the activities panel and repopulate with the new page of actions. It would also have to re-render the pagination controls so that the links are updated with the new page numbers.

If you're using a gem for pagination then it probably has a method to call to generate the pagination controls, and those controls will link to the route to the controller action that I described, passing the relevant page number as a parameter.

Title: Generic application controller action

Body:
I have a rails app that displays user activity on the RHS on each page.

Presently I pass the collection to the partial directly:

<%= render partial: "activities/activity", collection: current_user.activities.order(created_at: :desc) %>

I wish to now paginate this activity list.

current_user.activities.order(created_at: :desc).page(params[:page]).per_page(10)

I am guessing I need to have this set as an instance variable and have it placed in a route that can be accessed from the view.

My question is where should I define this instance variable as the route needs to be generic as the activity is displayed on a views.

If it helps I am doing the pagination with ajax, "remote: true".


问:
How can I loop through a string and print certain items?
```<code>lst = 'AB[CD]EF[GH]'
</code>```

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

```<code>while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi
</code>```

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

答:
Please try the following code snippet.</p>

```<code>my_string = 'AB[CD]EF[GH]'

lst = []
ind = 0
n = len(my_string)

while (ind < n):
    if my_string[ind] == '[':
        # if '[' is found, look for the next ']' but ind should not exceed n.
        # Your code does not do a ind < n check. It may enter an infinite loop.
        ind += 1 # this is done to skip the '[' in result list
        temp = '' # create a temporary string to store chars inside '[]'
        while ind < n and my_string[ind] != ']':
            temp = temp + my_string[ind]
            ind+=1
        lst.append(temp) # add this temp string to list
        ind += 1 # do this to skip the ending ']'.
    else:
        # If its not '[', simply append char to list.
        lst.append(my_string[ind])
        ind += 1

print(lst)
</code>```

Body:
lst = 'AB[CD]EF[GH]'

Output: ['A','B','CD','E','F','GH']

This is what I've tried but it's not working...

while(index < len(my_string)):
 curr_char = my_string[index]
 if(curr_char == '['):
      while(curr_char != ']'):
           multi = my_string[index + 1]
           index += 1
lst += multi

Can anybody please help? Without importing Regex or whatever. I wanna do this without using it.

Body:
Please try the following code snippet.

my_string = 'AB[CD]EF[GH]'

lst = []
ind = 0
n = len(my_string)

while (ind < n):
    if my_string[ind] == '[':
        # if '[' is found, look for the next ']' but ind should not exceed n.
        # Your code does not do a ind < n check. It may enter an infinite loop.
        ind += 1 # this is done to skip the '[' in result list
        temp = '' # create a temporary string to store chars inside '[]'
        while ind < n and my_string[ind] != ']':
            temp = temp + my_string[ind]
            ind+=1
        lst.append(temp) # add this temp string to list
        ind += 1 # do this to skip the ending ']'.
    else:
        # If its not '[', simply append char to list.
        lst.append(my_string[ind])
        ind += 1

print(lst)


问:
Is design now a subset of refactoring?
Looking at the cool new principles of software development:

Agile

You Ain't Gonna Need It

Less As A Competitive Advantage

Behaviour-Driven Development

The Evils Of Premature Optimization

The New Way seems to be to dive in and write what you need to achieve the first iteration of scope objectives, and refactor as necessary to have elegant solutions. Your codebase grows incrementally, and never has a big planning/hierarchical design stage. That, to me, suggests that software design (worthy though it is) has been subsumed into refactoring, because that's where the elegant code comes from, not the incremental additions to functionality.

Am I wrong?

答: Well the trouble with refactoring is that you need to know good design before you jump head first in. BDD/TDD are supposed to make the design emerge but without other factors, such as Domain knowledge and technical competence you will end up in trouble.</p>

OwnerDisplayName: Phil H

Title: Is design now a subset of refactoring?

LastEditorDisplayName: Phil H

OwnerDisplayName: John Nolan


问:
What's the Spring way of accessing properties from an entity?
I'm new to Spring and I'm building an application where some entities (JPA/Hibernate) need access to a property from application.properties. I do have a configuration class in which this is trivial:

```<code>@Configuration
public class FactoryBeanAppConfig {
    @Value("${aws.accessKeyId}")
    private String awsAccessKeyId;
    @Value("${aws.secretKey}")
    private String awsSecretKey;
}
</code>```

but since entities do not have and I think they should not have the annotations such as @Configuration or @Component, what's the Spring way for them to access the property?

Now, I know I can create my own class, my own bean, and make it as a simple wrapper around the properties; but is that the Spring way to do it or is there another way?

答:
There is no "Spring way", since JPA entities and Spring have nothing to do with each other. Most importantly, JPA entities are not Spring beans, so Spring doesn't know or care about them as they're not managed by Spring.

You can try to hack around, trying in vain to access Spring's configuration from code that should not be trying to access it, or you can accept the truth that your design is broken and you're trying to do something that's not meant to be done.

As was proposed several times, use a service class for this. It's managed by Spring, so it can access the Spring config, and it can handle entities, so there's no crossing boundaries.

Body:
I'm new to Spring and I'm building an application where some entities (JPA/Hibernate) need access to a property from application.properties. I do have a configuration class in which this is trivial:

@Configuration
public class FactoryBeanAppConfig {
    @Value("${aws.accessKeyId}")
    private String awsAccessKeyId;
    @Value("${aws.secretKey}")
    private String awsSecretKey;
}

but since entities do not have and I think they should not have the annotations such as @Configuration or @Component, what's the Spring way for them to access the property?

Now, I know I can create my own class, my own bean, and make it as a simple wrapper around the properties; but is that the Spring way to do it or is there another way?


答:
Persist error in component file and iterate the same in HTML

TS file

```<code>error : any ={
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}
</code>```

HTML file

```<code><div *ngFor="let err of error.error.error">{{err}}</div>
</code>```

Title: Break Array Values Into New Line in Angular

Body:
Persist error in component file and iterate the same in HTML

TS file

error : any ={
  "headers": {
    "normalizedNames": {},
    "lazyUpdate": null
  },
  "status": 404,
  "statusText": "Not Found",
  "url": "http://sample.com",
  "ok": false,
  "name": "HttpErrorResponse",
  "message": "Http failure response for http://sample.com: 404 Not Found",
  "error": {
    "error": [
      "Error1",
      "Error2",
      "Error3"
    ]
  }
}

HTML file

<div *ngFor="let err of error.error.error">{{err}}</div>


答:
From how it looks, I think grouping by multiple columns/fields wont hurt your result. Why don't you try adding to the group by like this:

```<code>GROUP BY `proof_type`, `id`
</code>```

This will group by proof_type first then id. I hope this does not alter the results. In some/most cases group by multiple columns gives wrong results.

Title: SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Body:
I'm using MySQL 5.7.13 on my windows PC with WAMP Server

My problem is while executing this query

SELECT *
FROM `tbl_customer_pod_uploads`
WHERE `load_id` = '78' AND
      `status` = 'Active'
GROUP BY `proof_type`

I'm getting always error like this

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'returntr_prod.tbl_customer_pod_uploads.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Can you please tell me the best solution.

I need result like

+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+
| id | user_id | load_id | bill_id | latitude | langitude | proof_type | document_type | file_name    | is_private | status | createdon           | updatedon           |
+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+
|  1 |       1 | 78      | 1       | 21.1212  | 21.5454   |          1 |             1 | id_Card.docx |          0 | Active | 2017-01-27 11:30:11 | 2017-01-27 11:30:14 |
+----+---------+---------+---------+----------+-----------+------------+---------------+--------------+------------+--------+---------------------+---------------------+

Body:
From how it looks, I think grouping by multiple columns/fields wont hurt your result. Why don't you try adding to the group by like this:

GROUP BY `proof_type`, `id`

This will group by proof_type first then id. I hope this does not alter the results. In some/most cases group by multiple columns gives wrong results.


问:
How does x86 pause instruction work in spinlock *and* can it be used in other scenarios?
The pause instruction is commonly used in the loop of testing spinlock, when some other thread owns the spinlock, to mitigate the tight loop. It's said that it is equivalent to some NOP instructions. Could somebody tell me how exactly it works for spinlock optimization? It seems to me that even the NOP instructions are a waste of CPU time. Will they decrease CPU usage?

Another question is that could I use pause instruction for other similar purposes. For example, I have a busy thread which keeps scanning some places (e.g. a queue) to retrieve new nodes; however, sometimes the queue is empty and the thread is just wasting cpu time. Sleep the thread and wake it up by other threads may be an option, however the thread is critical, so I don't want to make it sleep.

Could pause instruction work for my purpose to mitigate the CPU usage? Currently it uses 100% cpu of a physical core?

答:
PAUSE notifies the CPU that this is a spinlock wait loop so memory and cache accesses may be optimized.  See also pause instruction in x86 for some more details about avoiding the memory-order mis-speculation when leaving the spin-loop.

PAUSE may actually stop CPU for some time to save power.  Older CPUs decode it as REP NOP, so you don't have to check if its supported.  Older CPUs will simply do nothing (NOP) as fast as possible.

See also https://software.intel.com/en-us/articles/benefitting-power-and-performance-sleep-loops

Update: I don't think it's a good idea to use PAUSE in queue checking unless you are going to make your queue spinlock-like (and there is no obvious way to do it).

Spinning for a very long time is still very bad, even with PAUSE.


问:
Trying to work on responsiveness of login form
I am trying to make the page responsive and facing some issues I don't know what I did wrong. its just basic and I am not able to do it. Please check the plnkr link and let me know what I did wrong

Here's the plnkr link

```<code>    .login-btn, .btn.login-btn {
  border-radius: 8px;
  text-align: center;
  min-height: 44px;
  min-width: 140px;
  font-weight: 200;
  font-size: 20px;
  padding: 0 10px;
  margin: 20px;
}

.login-cont input[type="text"], .login-cont input[type="password"]  {
  border: 1px solid #61839C;
  height: 44px;
  font-size: 20px;
  width: 358px;
  font-size: 20px;
  padding: 0 10px;
  font-weight: 300;
  display: block;

  margin-top: 20px;
  padding-left: 20px;

}
</code>```

答:
You didn't include any bootstrap css or js links. And you need to give width: 100% to the input tag.
Check out this example.
It is responsive

.login-btn, .btn.login-btn {
  border-radius: 8px;
  text-align: center;
  min-height: 44px;
  min-width: 140px;
  font-weight: 200;
  font-size: 20px;
  padding: 0 10px;
  margin: 20px;
}

.login-cont input[type="text"], .login-cont input[type="password"]  {
  border: 1px solid #61839C;
  height: 44px;
  font-size: 20px;
  width: 100%;
  font-size: 20px;
  padding: 0 10px;
  font-weight: 300;
  display: block;
  margin-top: 20px;
  padding-left: 20px;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>

  <body>

<div class="container">
  <div class="row">
    <div class="centering text-center">
      <div class="login-cont col-md-4 col-md-offset-4 vcenter">
        <form id="login_form" name="login-form" #f="ngForm"  role="form" (ngSubmit)="f.form.valid && login()" novalidate>
          <label id="loginError" class="login-error"></label>

            <img src="https://www.islonline.com/static/v7/images/logo-islonline.svg"   class="img-responsive" alt="logo" width="334" height="100">

            <input id="username" class="form-control"  type="text" name="username" placeholder="Username" [(ngModel)]="username" required>
            <!--div *ngIf="f.submitted && username.invalid">Username is required</div-->
          <input id="userPassword" class="form-control"  type="password" name="userPassword" required placeholder="Password" [(ngModel)]="password">
          <div class="forgot-password-form">
            <span>Forgot Password ?</span>
          </div>
          <button type="submit" class="btn login-btn">Login</button>
        </form>
      </div>
    </div>
  </div>
</div></code>```

Body:
I am trying to make the page responsive and facing some issues I don't know what I did wrong. its just basic and I am not able to do it. Please check the plnkr link and let me know what I did wrong

Here's the plnkr link

    .login-btn, .btn.login-btn {
  border-radius: 8px;
  text-align: center;
  min-height: 44px;
  min-width: 140px;
  font-weight: 200;
  font-size: 20px;
  padding: 0 10px;
  margin: 20px;
}

.login-cont input[type="text"], .login-cont input[type="password"]  {
  border: 1px solid #61839C;
  height: 44px;
  font-size: 20px;
  width: 358px;
  font-size: 20px;
  padding: 0 10px;
  font-weight: 300;
  display: block;

  margin-top: 20px;
  padding-left: 20px;

}

Body:
You didn't include any bootstrap css or js links. And you need to give width: 100% to the input tag.
Check out this example.
It is responsive

.login-btn, .btn.login-btn {
  border-radius: 8px;
  text-align: center;
  min-height: 44px;
  min-width: 140px;
  font-weight: 200;
  font-size: 20px;
  padding: 0 10px;
  margin: 20px;
}

.login-cont input[type="text"], .login-cont input[type="password"]  {
  border: 1px solid #61839C;
  height: 44px;
  font-size: 20px;
  width: 100%;
  font-size: 20px;
  padding: 0 10px;
  font-weight: 300;
  display: block;
  margin-top: 20px;
  padding-left: 20px;

}

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>

  <body>

<div class="container">
  <div class="row">
    <div class="centering text-center">
      <div class="login-cont col-md-4 col-md-offset-4 vcenter">
        <form id="login_form" name="login-form" #f="ngForm"  role="form" (ngSubmit)="f.form.valid && login()" novalidate>
          <label id="loginError" class="login-error"></label>

            <img src="https://www.islonline.com/static/v7/images/logo-islonline.svg"   class="img-responsive" alt="logo" width="334" height="100">

            <input id="username" class="form-control"  type="text" name="username" placeholder="Username" [(ngModel)]="username" required>
            <!--div *ngIf="f.submitted && username.invalid">Username is required</div-->
          <input id="userPassword" class="form-control"  type="password" name="userPassword" required placeholder="Password" [(ngModel)]="password">
          <div class="forgot-password-form">
            <span>Forgot Password ?</span>
          </div>
          <button type="submit" class="btn login-btn">Login</button>
        </form>
      </div>
    </div>
  </div>
</div>


答:
Try this code bro,</p>

```<code>error => {
             alert("ERROR" + "\n" +  error.error[0] + "\n" +  error.error[1] + "\n" +  error.error[2]);
             console.log(error.error);
          });
</code>```

Body:
Try this code bro,

error => {
             alert("ERROR" + "\n" +  error.error[0] + "\n" +  error.error[1] + "\n" +  error.error[2]);
             console.log(error.error);
          });


问:
Xampp control panel is not showing
My Xampp control panel is not showing in the desktop (Windows 10), but can only up the servers through the shortcut (minimized option in the task bar).

As follows:

I have close the application without stopping the servers, will that be the case of this matter?

答:
There is also one temporary solution.

Open XAMPP, You cannot see its window but its icon will be shown in the windows task bar.

Hover your mouse over the XAMPP icon, a small popup will be shown.

Right click on popup and choose maximize. This will maximize the XAMPP Control Panel and you can see all the options and logs.

This fix is temporary and you may have to do repeat the steps often.

Title: Xampp control panel is not showing


问:
Could we build sth similar to Java NIO from Java IO?
I see that Java NIO is quite complicated. Could we create sth from Java IO that achieves the purpose of Java NIO?

I think it is easy to make buffer oriented and non-blocking IO - two main features of Java NIO. We could read data from stream into buffer instead of handling them immediately. About non-blocking IO, we could use setSoTimeout method of Java IO to allow a thread to give up waiting after an amount of time (e.g. 100ms).Based on that, we can create a thread that handle multiple connections.

If it is easy like above, is Java NIO redundant?

答:
At first glance, the solution you are proposing might appear to work. However, it would be just a simulation, and could never be as efficient as the actual NIO implementation.

The reason for this is that NIO works essentially different that Java IO. This "advanced" part requires support in operating system. When you're only working with small amounts of data, 10ms doesn't look much different than 60ms. But as others have said, an I/O that takes 10 seconds instead of 1 minute makes a world of difference.

There are several other subtleties, too. Socket timeout is not the same as waiting for data. Asynchronous I/O does not neccessarily use many threads. Typically, one thread per hardware device is enough. There is no waiting involved. There are fewer context switches. The data is processed as efficiently as possible, which includes not copying it from one buffer into another if that can be avoided. In the end, it all adds up.


问:
How to fix duplicated entry error related to: gms/internal/zzaso.class in Android Studio?
I'm having a hard time trying to build a signed apk of my app, but I have an error related with google/android/gms class. Do you have idea of what the problem could be?

One more thing, I get this error only when I try to generate the signed apk, but in develop mode it runs fine in my smartphone. (I want to generate my app so anyone can install it on their phone)

I googled it and I know is related to gms version, but I can't identify exactly where in the code is the incompatibility of dependencies.

This is the gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.test_app.myfinalapp"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

android {
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.firebaseui:firebase-ui:2.0.1'
    compile 'com.firebaseui:firebase-ui-auth:2.0.1'
    compile 'me.dm7.barcodescanner:zxing:1.8.4'
    compile 'com.loopj.android:android-async-http:1.4.9'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

And this is the error:

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForRelease'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzaso.class
</code>```

答:
Remove

```<code>compile 'com.google.firebase:firebase-auth:10.0.1'
</code>```

and

```<code>compile 'com.firebaseui:firebase-ui:2.0.1'
</code>```

if you are only using firebase-ui-auth, if you are using other firebase-ui components as well, then remove

```<code>compile 'com.firebaseui:firebase-ui-auth:2.0.1'
</code>```

Update firebase-ui dependency versions from 2.0.1 to 3.1.0

Body:
I'm having a hard time trying to build a signed apk of my app, but I have an error related with google/android/gms class. Do you have idea of what the problem could be?

One more thing, I get this error only when I try to generate the signed apk, but in develop mode it runs fine in my smartphone. (I want to generate my app so anyone can install it on their phone)

I googled it and I know is related to gms version, but I can't identify exactly where in the code is the incompatibility of dependencies.

This is the gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.test_app.myfinalapp"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

android {
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.firebaseui:firebase-ui:2.0.1'
    compile 'com.firebaseui:firebase-ui-auth:2.0.1'
    compile 'me.dm7.barcodescanner:zxing:1.8.4'
    compile 'com.loopj.android:android-async-http:1.4.9'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

And this is the error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForRelease'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/android/gms/internal/zzaso.class

Body:
Remove

compile 'com.google.firebase:firebase-auth:10.0.1'

and

compile 'com.firebaseui:firebase-ui:2.0.1'

if you are only using firebase-ui-auth, if you are using other firebase-ui components as well, then remove

compile 'com.firebaseui:firebase-ui-auth:2.0.1'

Update firebase-ui dependency versions from 2.0.1 to 3.1.0


问:
How to parse and manipulate a big chunk of string in the format key=value?
I'm fetching some data from an camera's API.

There's a big string returned in the response with this format VCA.Ch0.licenseid=0

Here's a part of the response

```<code>VCA.Ch0.licenseid=0\r\nVCA.Ch0.enable=yes\r\nVCA.Ch0.enablemovobj=yes\r\nVCA.Ch0.enablecntline=yes\r\nVCA.Ch0.trackmode=surv\r\n
</code>```

Is it possible to parse this string?

Let's say that I want to query about the param VCA.Ch0.enable.

How can I do that?

答:
```<code>▶ input.split.map { |kv| kv.split('=') }.to_h
#⇒ {
#         "VCA.Ch0.enable" => "yes",
#  "VCA.Ch0.enablecntline" => "yes",
#   "VCA.Ch0.enablemovobj" => "yes",
#      "VCA.Ch0.licenseid" => "0",
#      "VCA.Ch0.trackmode" => "surv"
# }
</code>```

Body:
I'm fetching some data from an camera's API.

There's a big string returned in the response with this format VCA.Ch0.licenseid=0

Here's a part of the response

VCA.Ch0.licenseid=0\r\nVCA.Ch0.enable=yes\r\nVCA.Ch0.enablemovobj=yes\r\nVCA.Ch0.enablecntline=yes\r\nVCA.Ch0.trackmode=surv\r\n

Is it possible to parse this string?

Let's say that I want to query about the param VCA.Ch0.enable.

How can I do that?


问:
Error "variable lengths differ" when assigning weights parameter in caret (R)
I want to apply weighted observation in caret using the code below:

```<code>model_weights <- ifelse(train$y == 0,
                        (1/table(train$y)[1]) * 0.5,
                        (1/table(train$y)[2]) * 0.5)

xgbT <- train(x = as.matrix(train[,-21]), y = make.names(as.factor(train$y)),
              method = "xgbTree",
              trControl = cctrl1,
              metric = "MCC",
              maximize = TRUE,
              weights = model_weights,
              preProc = c("center", "scale"),
              tuneGrid = expand.grid(nrounds = c(150), #number of trees
                                    max_depth = c(7), #max tree depth
                                    eta = c(0.03), #learning rate
                                    gamma = c(0.3), #min split loss
                                    colsample_bytree = c(0.7),
                                    min_child_weight = c(10, 1, 5), #min number of instances in the leaf
                                    subsample = c(0.6)), #subsample ratio of the training instance
              early_stop_round = c(3), #if no improvements over specified rounds
              objective = c("binary:logistic"),
              silent = 0)
</code>```

However, it gives me this error: Error in model.frame.default(formula = .outcome ~ ., data = dat, weights = wts) :
  variable lengths differ (found for '(weights)')

Though I have checked that their lengths are the same with code below:

```<code>> table(model_weights)
model_weights
0.0000277654375832963  0.000231481481481481
                18008                  2160
> table(train$y)

    0     1
18008  2160
</code>```

Any idea how to fix this?

NOTE: I can run the train function without weights parameter.

答:
After further debugging, I found the problem is because I apply sampling in the cctrl1. Thus, the length of weights differ, since I generate it before they apply re-sampling.

So, you can fix this by simply removing sampling from your trControl. If you still want to apply re-sampling, then you have to re-sample the data before running below code:

```<code>model_weights <- ifelse(train$y == 0,
                    (1/table(train$y)[1]) * 0.5,
                    (1/table(train$y)[2]) * 0.5)
</code>```

Body:
I want to apply weighted observation in caret using the code below:

model_weights <- ifelse(train$y == 0,
                        (1/table(train$y)[1]) * 0.5,
                        (1/table(train$y)[2]) * 0.5)

xgbT <- train(x = as.matrix(train[,-21]), y = make.names(as.factor(train$y)),
              method = "xgbTree",
              trControl = cctrl1,
              metric = "MCC",
              maximize = TRUE,
              weights = model_weights,
              preProc = c("center", "scale"),
              tuneGrid = expand.grid(nrounds = c(150), #number of trees
                                    max_depth = c(7), #max tree depth
                                    eta = c(0.03), #learning rate
                                    gamma = c(0.3), #min split loss
                                    colsample_bytree = c(0.7),
                                    min_child_weight = c(10, 1, 5), #min number of instances in the leaf
                                    subsample = c(0.6)), #subsample ratio of the training instance
              early_stop_round = c(3), #if no improvements over specified rounds
              objective = c("binary:logistic"),
              silent = 0)

However, it gives me this error: Error in model.frame.default(formula = .outcome ~ ., data = dat, weights = wts) :
  variable lengths differ (found for '(weights)')

Though I have checked that their lengths are the same with code below:

> table(model_weights)
model_weights
0.0000277654375832963  0.000231481481481481
                18008                  2160
> table(train$y)

    0     1
18008  2160

Any idea how to fix this?

NOTE: I can run the train function without weights parameter.

Body:
After further debugging, I found the problem is because I apply sampling in the cctrl1. Thus, the length of weights differ, since I generate it before they apply re-sampling.

So, you can fix this by simply removing sampling from your trControl. If you still want to apply re-sampling, then you have to re-sample the data before running below code:

model_weights <- ifelse(train$y == 0,
                    (1/table(train$y)[1]) * 0.5,
                    (1/table(train$y)[2]) * 0.5)


问:
Rails 5 if statement working on show but not working on index
I am creating a poll app. Users can vote, but if they have voted already they are not able to vote again.

This is the method voted_for that checks it:

user.rb

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes

def voted_for?(poll)
  vote_options.any? {|v| v.poll == poll }
end
end
</code>```

This wworks in my voting form:

polls/_voting_form.html.erb

```<code><%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>
  <%= hidden_field_tag 'poll[id]', @poll.id %>

  <%= render partial: 'polls/vote_option', collection: @poll.vote_options, as: :option %>

  <% if current_user.voted_for?(@poll) %>
    <p>You have already voted!</p>
  <% else %>
    <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
  <% end %>
<% end %>
</code>```

Now I want too do thee same on index page, which shows list  of polls and a button VOTE for each. I want to show a button VIEW if user already voted that poll.

polls/index.html.erb

```<code>        <div class="container">

<% content_for(:page_header) {"POLLS"} %>

  <%= render "filter_box" %>

  <% @polls.each do |poll| %>

    <div class="well">

      <div class="row">
        <h4><%= poll.question %>
          <small>(voted:
            <%= poll.votes_summary %>)</small>
        </h4>
      </div>

      <div class="row">
        <div class="col-sm-2"><%= 'OPEN' %>
          <p><%= poll.open_date %></p>
        </div>
        <div class="col-sm-2"><%= 'CLOSE' %>
          <p><%= poll.close_date %></p>
        </div>
        <div class="col-sm-2"><%= 'DIVISION' %>
          <p><%= poll.division.try(:name) %></p>
        </div>
        <div class="col-sm-2">
          <p>
            <% if  current_user.voted_for?(@poll) %>
              <%= link_to 'VIEW', poll_path(poll), class: 'btn btn-primary btn-lg block' %>

            <% else %>
                <%= link_to 'VOTE', poll_path(poll), class: 'btn btn-primary btn-lg block' %>
            <% end %>
          </p>
        </div>

        <div class="col-sm-3">
          <div class="btn-group">

            <%= link_to 'Edit', edit_poll_path(poll), class: 'btn btn-default' %>
            <%= link_to 'Delete', poll_path(poll), method: :delete, class: 'btn btn-danger', data: {confirm: 'Are you sure?'} %>

          </div>

        </div>

      </div>
        </div>
    <% end %>
</code>```

polls_controller

```<code>class PollsController < ApplicationController

  before_action :authenticate_user!

  def index
    @q = Poll.ransack(params[:q])
  @polls = @q.result.order('id ASC')
    respond_to do |format|
      format.html
  end
  end

  def new
    @poll = Poll.new
      @poll.vote_options.build
  end

  def create
      @poll = Poll.new(poll_params)
      if @poll.save
        flash[:success] = 'Poll was created!'
        redirect_to polls_path
      else
        render 'new'
      end
    end

  def edit
  @poll = Poll.find_by_id(params[:id])
end

def update
  @poll = Poll.find_by_id(params[:id])
  if @poll.update_attributes(poll_params)
    flash[:success] = 'Poll was updated!'
    redirect_to polls_path
  else
    render 'edit'
  end
end

def destroy
  @poll = Poll.find_by_id(params[:id])
  if @poll.destroy
    flash[:success] = 'Poll was destroyed!'
  else
    flash[:warning] = 'Error destroying poll...'
  end
  redirect_to polls_path
end

def show
  @poll = Poll.includes(:vote_options).find_by_id(params[:id])
  @vote = Vote.find_by_id(params[:id])

end

  private

  def poll_params
    params.require(:poll).permit(:question, :description, :division_id, :open_date, :close_date, vote_options_attributes: [:id, :title, :_destroy])
  end
end
</code>```

But if I use this it ignores the first condition and shows VOTE button for all. Even polls I voted already.

How cnn I fix it?

答: You didn’t post your controller actions, but you probably aren’t assigning @poll in your index action.  You probably have something along the lines of @polls assigned instead.  In which case, you will need to iterate over @polls in your view and run your conditional logic on each member of that collection.

Body:
I am creating a poll app. Users can vote, but if they have voted already they are not able to vote again.

This is the method voted_for that checks it:

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes

def voted_for?(poll)
  vote_options.any? {|v| v.poll == poll }
end
end

This wworks in my voting form:

polls/_voting_form.html.erb

<%= form_tag votes_path, method: :post, remote: true, id: 'voting_form' do %>
  <%= hidden_field_tag 'poll[id]', @poll.id %>

  <%= render partial: 'polls/vote_option', collection: @poll.vote_options, as: :option %>

  <% if current_user.voted_for?(@poll) %>

You have already voted!

  <% else %>
    <%= submit_tag 'Vote', class: 'btn btn-lg btn-primary' %>
  <% end %>
<% end %>

Now I want too do thee same on index page, which shows list  of polls and a button VOTE for each. I want to show a button VIEW if user already voted that poll.

polls/index.html.erb

<% content_for(:page_header) {"POLLS"} %>

  <%= render "filter_box" %>

  <% @polls.each do |poll| %>

<%= poll.question %>
          (voted:
            <%= poll.votes_summary %>)

<%= 'OPEN' %>

<%= poll.open_date %>

<%= 'CLOSE' %>

<%= poll.close_date %>

<%= 'DIVISION' %>

<%= poll.division.try(:name) %>

            <% if  current_user.voted_for?(@poll) %>
              <%= link_to 'VIEW', poll_path(poll), class: 'btn btn-primary btn-lg block' %>

            <% else %>
                <%= link_to 'VOTE', poll_path(poll), class: 'btn btn-primary btn-lg block' %>
            <% end %>

            <%= link_to 'Edit', edit_poll_path(poll), class: 'btn btn-default' %>
            <%= link_to 'Delete', poll_path(poll), method: :delete, class: 'btn btn-danger', data: {confirm: 'Are you sure?'} %>

    <% end %>

polls_controller

class PollsController < ApplicationController

  before_action :authenticate_user!

  def index
    @q = Poll.ransack(params[:q])
  @polls = @q.result.order('id ASC')
    respond_to do |format|
      format.html
  end
  end

  def new
    @poll = Poll.new
      @poll.vote_options.build
  end

  def create
      @poll = Poll.new(poll_params)
      if @poll.save
        flash[:success] = 'Poll was created!'
        redirect_to polls_path
      else
        render 'new'
      end
    end

  def edit
  @poll = Poll.find_by_id(params[:id])
end

def update
  @poll = Poll.find_by_id(params[:id])
  if @poll.update_attributes(poll_params)
    flash[:success] = 'Poll was updated!'
    redirect_to polls_path
  else
    render 'edit'
  end
end

def destroy
  @poll = Poll.find_by_id(params[:id])
  if @poll.destroy
    flash[:success] = 'Poll was destroyed!'
  else
    flash[:warning] = 'Error destroying poll...'
  end
  redirect_to polls_path
end

def show
  @poll = Poll.includes(:vote_options).find_by_id(params[:id])
  @vote = Vote.find_by_id(params[:id])

end

  private

  def poll_params
    params.require(:poll).permit(:question, :description, :division_id, :open_date, :close_date, vote_options_attributes: [:id, :title, :_destroy])
  end
end

But if I use this it ignores the first condition and shows VOTE button for all. Even polls I voted already.

How cnn I fix it?