问:
Applying an ellipsis to multiline text
Is there a solution to add ellipsis on last line inside a div with a fluid height (20%)?

I found the -webkit-line-clamp function in CSS, but in my case the line number will be depending on window size.

p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p></code>```

I have this JSFiddle to illustrate the issue.
https://jsfiddle.net/96knodm6/

答:
```<code><!DOCTYPE html>
<html>
<head>
    <style>
        /* styles for '...' */
        .block-with-text {
            width: 50px;
            height: 50px;
            /* hide text if it more than N lines  */
            overflow: hidden;
            /* for set '...' in absolute position */
            position: relative;
            /* use this value to count block height */
            line-height: 1.2em;
            /* max-height = line-height (1.2) * lines max number (3) */
            max-height: 3.6em;
            /* fix problem when last visible word doesn't adjoin right side  */
            text-align: justify;
            /* place for '...' */
            margin-right: -1em;
            padding-right: 1em;
        }
            /* create the ... */
            .block-with-text:before {
                /* points in the end */
                content: '...';
                /* absolute position */
                position: absolute;
                /* set position to right bottom corner of block */
                right: 0;
                bottom: 0;
            }
            /* hide ... if we have text, which is less than or equal to max lines */
            .block-with-text:after {
                /* points in the end */
                content: '';
                /* absolute position */
                position: absolute;
                /* set position to right bottom corner of text */
                right: 0;
                /* set width and height */
                width: 1em;
                height: 1em;
                margin-top: 0.2em;
                /* bg color = bg color under block */
                background: white;
            }
    </style>
</head>
<body>
    a
    <div class="block-with-text">g fdsfkjsndasdasd asd asd asdf asdf asdf asdfas dfa sdf asdflk jgnsdlfkgj nsldkfgjnsldkfjgn sldkfjgnls dkfjgns ldkfjgn sldkfjngl sdkfjngls dkfjnglsdfkjng lsdkfjgn sdfgsd</div>
    <p>This is a paragraph.</p>

</body>
</html>
</code>```

Title: Applying an ellipsis to multiline text

Body:
Is there a solution to add ellipsis on last line inside a div with a fluid height (20%)?

I found the -webkit-line-clamp function in CSS, but in my case the line number will be depending on window size.

p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.

I have this JSFiddle to illustrate the issue.
https://jsfiddle.net/96knodm6/


来源: stackexchange

问:
CarrierWave not work with Cloudinary

In user.rb

class User < ApplicationRecord
    mount_uploader :picture, PictureUploader
end

In picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base

include Cloudinary::CarrierWave

storage :file

# This is a sensible default for uploaders that are meant to be mounted:

def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

In environement.rb

require_relative 'application'

initialize the Rails application

Rails.application.initialize!

require 'carrierwave/orm/activerecord'

In _form.html.erb

```<code><%= form.label :picture %>

<%= form.file_field :picture, id: :user_picture %>
</code>```

In migration

class CreateUsers < ActiveRecord::Migration[5.1]

def change

create_table :users do |t|

```<code>  t.string :email

  t.string :picture

  t.timestamps

end
</code>```

end

end

Finally User.picture_url is an url on Cloudinary but there isn't any image uploaded in this url.

And it works if I type in rails c
Cloudinary::Uploader.upload('/home/my_image.jpg')

答:
Have you in your app/assets/javascript/application.jsadded

```<code>//= require cloudinary/jquery.cloudinary
</code>```

and in  app/views/layouts/application.html.erb

```<code>    <%= yield(:after_js) %>
    <%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
    <%= cloudinary_js_config %>
</code>```

And in application.yml ( you will find yours in your cloudinary settings)

```<code>CLOUDINARY_URL: "cloudinary:/`/768932967533141:wF2ZZZrTuQ6R2Ynf_1mH3zk@dtrucdxbug"
#this a fake url ;-)
</code>```

You problem is more in your show.html.erb  :)

```<code>  <%= cl_image_tag(@user.picture.path, :secure => true,
                    :width => 100, :height => 150, :crop => :fill) %>
</code>```

The setting here is just an exemple but you need @user.picture.path to display your picture :)

More info here https://cloudinary.com/documentation/rails_image_manipulation

ContentLicense: CC BY-SA 3.0

Title: CarrierWave not work with Cloudinary

Body:
In user.rb

class User < ApplicationRecord
    mount_uploader :picture, PictureUploader
end

In picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base

include Cloudinary::CarrierWave

storage :file

# This is a sensible default for uploaders that are meant to be mounted:

def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

In environement.rb

require_relative 'application'

initialize the Rails application

Rails.application.initialize!

require 'carrierwave/orm/activerecord'

In _form.html.erb

<%= form.label :picture %>

<%= form.file_field :picture, id: :user_picture %>

In migration

class CreateUsers < ActiveRecord::Migration[5.1]

def change

create_table :users do |t|

  t.string :email

  t.string :picture

  t.timestamps

end

end

end

Finally User.picture_url is an url on Cloudinary but there isn't any image uploaded in this url.

And it works if I type in rails c
Cloudinary::Uploader.upload('/home/my_image.jpg')

Body:
Have you in your app/assets/javascript/application.jsadded

//= require cloudinary/jquery.cloudinary

and in  app/views/layouts/application.html.erb

    <%= yield(:after_js) %>
    <%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
    <%= cloudinary_js_config %>

And in application.yml ( you will find yours in your cloudinary settings)

CLOUDINARY_URL: "cloudinary:/`/768932967533141:wF2ZZZrTuQ6R2Ynf_1mH3zk@dtrucdxbug"
#this a fake url ;-)

You problem is more in your show.html.erb  :)

  <%= cl_image_tag(@user.picture.path, :secure => true,
                    :width => 100, :height => 150, :crop => :fill) %>

The setting here is just an exemple but you need @user.picture.path to display your picture :)

More info here https://cloudinary.com/documentation/rails_image_manipulation


问:
Import Excel Macro and run it with VBS
I would like to create a vbs script that will open an .xlsx document, import a macro and run the macro. For my use, the .xlsx document's name will vary - so I may need a wildcard for the filename. This is what I have so far:

```<code>Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "\\path\Missed_Scans\Report\Report.xlsx"
xl.Application.Visible = True
x1.VBProject.VBComponents.Import "\\path\Missed_Scans\Missed_Scans.bas"
x1.Save
xl.Application.run "'Report.xlsx'!Missed_Scans"
Set xl = Nothing
</code>```

The above script will open 'report.xlsx' but it does not seem to correctly import or run the macro. It is not necessary for report.xlsx to be opened (visibly or otherwise) so long as the macro is imported and run.

EDIT

Here is the macro:

```<code>Attribute VB_Name = "Module1"
Sub Missed_Scans()
Attribute Missed_Scans.VB_ProcData.VB_Invoke_Func = " \n14"
'
' Missed_Scans Macro
'

'
    Sheets("Incomplete_ASINs").Select
    ActiveSheet.Range("$A$1:$J$52951").AutoFilter Field:=1, Criteria1:="SDF8"
    Columns("B:D").Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Rows("1:1").Select
    Application.CutCopyMode = False
    Selection.AutoFilter
    ActiveWorkbook.SaveAs Filename:="\\path\Missed_Scans\Report\Missed_Scans.xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWindow.Close
End Sub
</code>```

Thanks!

答:
Your code may well be giving issues due to the use of x1 which hasn't been set.

You probably intended to use

```<code>Set x1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")
</code>```

But I would have expected that to actually crash rather than just not correctly importing the macro.

I suspect that you can avoid using the VBA macro if you just use the equivalent code in VBS:

```<code>Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set wb1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs "\\path\Missed_Scans\Report\Missed_Scans.xlsx", 51, , , , False
wb2.Close
wb1.close
xl.Quit
Set xl = Nothing
</code>```

Note: I'm not an expert in VBS, so I hope that code works.  Let me know if it doesn't.

Title: Import Excel Macro and run it with VBS

Body:
I would like to create a vbs script that will open an .xlsx document, import a macro and run the macro. For my use, the .xlsx document's name will vary - so I may need a wildcard for the filename. This is what I have so far:

Set xl = CreateObject("Excel.application")
xl.Application.Workbooks.Open "\\path\Missed_Scans\Report\Report.xlsx"
xl.Application.Visible = True
x1.VBProject.VBComponents.Import "\\path\Missed_Scans\Missed_Scans.bas"
x1.Save
xl.Application.run "'Report.xlsx'!Missed_Scans"
Set xl = Nothing

The above script will open 'report.xlsx' but it does not seem to correctly import or run the macro. It is not necessary for report.xlsx to be opened (visibly or otherwise) so long as the macro is imported and run.

EDIT

Here is the macro:

Attribute VB_Name = "Module1"
Sub Missed_Scans()
Attribute Missed_Scans.VB_ProcData.VB_Invoke_Func = " \n14"
'
' Missed_Scans Macro
'

'
    Sheets("Incomplete_ASINs").Select
    ActiveSheet.Range("$A$1:$J$52951").AutoFilter Field:=1, Criteria1:="SDF8"
    Columns("B:D").Select
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Rows("1:1").Select
    Application.CutCopyMode = False
    Selection.AutoFilter
    ActiveWorkbook.SaveAs Filename:="\\path\Missed_Scans\Report\Missed_Scans.xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWindow.Close
End Sub

Thanks!

Body:
Your code may well be giving issues due to the use of x1 which hasn't been set.

You probably intended to use

Set x1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")

But I would have expected that to actually crash rather than just not correctly importing the macro.

I suspect that you can avoid using the VBA macro if you just use the equivalent code in VBS:

Set xl = CreateObject("Excel.application")
xl.Application.Visible = True

Dim wb1
Set wb1 = xl.Application.Workbooks.Open("\\path\Missed_Scans\Report\Report.xlsx")
Dim wb2
Set wb2 = xl.Workbooks.Add

wb1.Sheets("Incomplete_ASINs").Range("$A$1:$J$52951").AutoFilter 1, "SDF8"
wb1.Sheets("Incomplete_ASINs").Columns("B:D").Copy
wb2.Worksheets(1).Paste
wb2.Worksheets(1).Rows(1).AutoFilter
wb2.SaveAs "\\path\Missed_Scans\Report\Missed_Scans.xlsx", 51, , , , False
wb2.Close
wb1.close
xl.Quit
Set xl = Nothing

Note: I'm not an expert in VBS, so I hope that code works.  Let me know if it doesn't.


问:
Select Tag Helper in ASP.NET Core MVC
I need some help with the select tag helper in ASP.NET Core.

I have a list of employees that I'm trying to bind to a select tag helper. My employees are in a List<Employee> EmployeesList and selected value will go into EmployeeId property. My view model looks like this:

```<code>public class MyViewModel
{
   public int EmployeeId { get; set; }
   public string Comments { get; set; }
   public List<Employee> EmployeesList {get; set; }
}
</code>```

My employee class looks like this:

```<code>public class Employee
{
   public int Id { get; set; }
   public string FullName { get; set; }
}
</code>```

My question is how do I tell my select tag helper to use the Id as the value while displaying FullName in the drop down list?

```<code><select asp-for="EmployeeId" asp-items="???" />
</code>```

I'd appreciate some help with this. Thanks.

答:
In Get:

```<code>public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}
</code>```

In Post:

```<code>var selectedIds= Request.Form["Tags"];
</code>```

In View :

```<code><label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>
</code>```

Title: Select Tag Helper in ASP.NET Core MVC

Body:
I need some help with the select tag helper in ASP.NET Core.

I have a list of employees that I'm trying to bind to a select tag helper. My employees are in a List<Employee> EmployeesList and selected value will go into EmployeeId property. My view model looks like this:

public class MyViewModel
{
   public int EmployeeId { get; set; }
   public string Comments { get; set; }
   public List<Employee> EmployeesList {get; set; }
}

My employee class looks like this:

public class Employee
{
   public int Id { get; set; }
   public string FullName { get; set; }
}

My question is how do I tell my select tag helper to use the Id as the value while displaying FullName in the drop down list?

<select asp-for="EmployeeId" asp-items="???" />

I'd appreciate some help with this. Thanks.

Body:
In Get:

public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}

In Post:

var selectedIds= Request.Form["Tags"];

In View :

<label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>

ContentLicense: CC BY-SA 4.0


问:
Dojo aspect before not working on dojo request
I have a Dojo class that uses dojo/request to submit various requests to the server.

I need to use dojo/aspect to add a before advice to those requests.

The docs seem relatively easy to understand.

My class declaration looks something like this:

```<code>'myPackage/MyClass':function(){
    define("myPackage/MyClass", [
        "dojo/request",
        // etc. etc.
        "dojo/aspect"
    ], function(request, ..., aspect) {
        return declare("myPackage.MyClass", null, {
            constructor: function(options){
                aspect.before(dojo, "request",
                    function(url, args){
                        // TODO
                        alert("before advice applied");
                    }
                );
            },
            // various functions that use dojo request
        });
    }

);
}
</code>```

My problem is that the before advice is never executed.

I've tried a few variants, such as targeting this instead of dojo, or targeting request directly and its only visible function when inspected, xhr.

I even went back to the doc page in desperation and tried targeting dojo with method "xhr" to see if it couldn't by chance be invoked internally, but nothing ever worked.

Is there maybe something obvious that I've overlooked?

Edit

I tried modifying my code so that the before advice was executed targeting this and a frequently used function.

Something like: aspect.before(this, "theFrequentlyUsedFunction",

That worked just fine right out of the box, which means I can use a cumbersome workaround and add a before advice for each of the functions invoking request, assuming the time complexity of statements preceding the request call in those functions is trivial.

My conclusion so far is that I'm not referencing the right target and function name when applying advice before Dojo request calls, but I'm still baffled as per why this doesn't work.

答:
In your case "request" is not a property of "dojo" object. It's just a name of argument passed in function. So you can assign it to any property of any object, even to property of your module. So you was close to solution. Take a look on my example:</p>

```<code>define([
    "dojo/_base/declare",
    .....
    "dojo/request",
    "dojo/aspect"
], function (
    declare,
    .....
    request,
    aspect
) {

    return declare("Test", [...], {
        request: request,
        constructor: function () {
            aspect.before(this, "request", function () {
                console.log("before advice applied");
            });
        }
        ......
    });
});
</code>```

Body:
I have a Dojo class that uses dojo/request to submit various requests to the server.

I need to use dojo/aspect to add a before advice to those requests.

The docs seem relatively easy to understand.

My class declaration looks something like this:

'myPackage/MyClass':function(){
    define("myPackage/MyClass", [
        "dojo/request",
        // etc. etc.
        "dojo/aspect"
    ], function(request, ..., aspect) {
        return declare("myPackage.MyClass", null, {
            constructor: function(options){
                aspect.before(dojo, "request",
                    function(url, args){
                        // TODO
                        alert("before advice applied");
                    }
                );
            },
            // various functions that use dojo request
        });
    }

);
}

My problem is that the before advice is never executed.

I've tried a few variants, such as targeting this instead of dojo, or targeting request directly and its only visible function when inspected, xhr.

I even went back to the doc page in desperation and tried targeting dojo with method "xhr" to see if it couldn't by chance be invoked internally, but nothing ever worked.

Is there maybe something obvious that I've overlooked?

Edit

I tried modifying my code so that the before advice was executed targeting this and a frequently used function.

Something like: aspect.before(this, "theFrequentlyUsedFunction",

That worked just fine right out of the box, which means I can use a cumbersome workaround and add a before advice for each of the functions invoking request, assuming the time complexity of statements preceding the request call in those functions is trivial.

My conclusion so far is that I'm not referencing the right target and function name when applying advice before Dojo request calls, but I'm still baffled as per why this doesn't work.

Body:
In your case "request" is not a property of "dojo" object. It's just a name of argument passed in function. So you can assign it to any property of any object, even to property of your module. So you was close to solution. Take a look on my example:

define([
    "dojo/_base/declare",
    .....
    "dojo/request",
    "dojo/aspect"
], function (
    declare,
    .....
    request,
    aspect
) {

    return declare("Test", [...], {
        request: request,
        constructor: function () {
            aspect.before(this, "request", function () {
                console.log("before advice applied");
            });
        }
        ......
    });
});


问:
Asymptotic notation properties proofs?
I am trying to prove that if f(n) and g(n) are asymptotically positive functions, then:

f(n) = O((f(n))^2)

f(n) = O(g(n)) implies 2^(f(n)) = O(2^(g(n)))

f(n) = O(g(n)) implies g(n) = O(f(n))

答:
1) Theorem: If f(n) is an asymptotically positive function from natural numbers to natural numbers, then f(n) = O((f(n))^2) (note I have added an extra, perhaps implied, assumption).

Proof: Because f(n) is an asymptotically positive function from natural numbers to natural numbers, it is guaranteed that for all natural numbers n greater than or equal to some natural number n0, f(n) > 0, hence f(n) >= 1. Because f(n) is guaranteed to be positive we are free to multiply both sides of the inequality by f(n) without changing the direction to get f(n)^2 >= f(n). Therefore, we can choose c = 1 and use the n0 from the assumption to show that f(n) = O((f(n))^2). (Recall that by the definition of Big-Oh, f(n) = O(g(n)) if and only if there exist constants c > 0, n0 such that for n >= n0, f(n) <= c * g(n)).

2) Theorem: if f(n) and g(n) are asymptotically positive functions from natural numbers to natural numbers and f(n) = O(g(n)), then it is not necessarily true that 2^(f(n)) = O(2^(g(n)).

Proof: The proof is by example. It can be shown that 4n = O(2n). 4n and 2n are both asymptotically positive functions from naturals to naturals. However, it can also be shown that 2^(4n) = 16^n is not O(2^(2n)) = O(4^n).

3) Theorem: if f(n) and g(n) are asymptotically positive functions from natural numbers to natural numbers and f(n) = O(g(n)), then it is not necessarily true that g(n) = O(f(n)).

Proof: The proof is by example. It can be shown that n = O(n^2). n and n^2 are both asymptotically positive functions from naturals to naturals. However, it can also be shown that n^2 is not O(n).

Title: Asymptotic notation properties proofs?


问:
Moving Folders in Laravel 5.5
Scenario

Im trying to allow users to move folders around in laravel 5.5, but Laravels site does not have example code for moving folders only files. I looked elsewhere and came across a couple other answers on stackoverflow and other places and tried them all.

Laravel move all files directory

https://laracasts.com/discuss/channels/laravel/laravel-cannot-use-movedirectory-and-copydirectory-problem

Laravel, unable to copyDirectory or moveDirectory

When I try to move a folder i get this response in Devtools:

```<code>0:"I want to move this /public/Gallery"
1:"To here /public/Images"
2:false
</code>```

From this code in the backend

```<code>$item ['path' => '/public/Gallery']
$path = '/public/Images'
$success = File::moveDirectory($item['path'], $path);
return [
    "I want to move this ".$item['path'],
    "To here $path",
    $success,
];
</code>```

Earlier i was getting a response that said the file already exists although it didnt but ive not since been able to replicate that.

EDIT

using Storage::move() i was able to replicate the 'already exists error'

```<code>exception:"League\Flysystem\FileExistsException"
file:"C:\Users\user.name\Desktop\electron-api\vendor\league\flysystem\src\Filesystem.php"
line:402
message:"File already exists at path: public/Images"
</code>```

Question

How to move folders around in laravel 5 storage, NOT FILES. Preferably using the Storage Facade.

答:
Feel really stupid was using the Method wrongly, Because i didnt see it explicitly referenced anywhere that you had to include the folder name in both the "move from" and "move to" directories essentially, i've been putting this:

Storage::move('Folder', 'OtherFolder');

But this doesnt work, i need to do it like this

Storage::move('Folder', 'OtherFolder/Folder');

The folder being moved into OtherFolder still needs to be named folder, so the name needs to append at the end, laravel wasnt throwing any specific errors that allowed me to understand what i was doing wrong properly.

Hopefully this helps anyone as daft as me in the future.

Title: Moving Folders in Laravel 5.5

Body:
Scenario

Im trying to allow users to move folders around in laravel 5.5, but Laravels site does not have example code for moving folders only files. I looked elsewhere and came across a couple other answers on stackoverflow and other places and tried them all.

Laravel move all files directory

https://laracasts.com/discuss/channels/laravel/laravel-cannot-use-movedirectory-and-copydirectory-problem

Laravel, unable to copyDirectory or moveDirectory

When I try to move a folder i get this response in Devtools:

0:"I want to move this /public/Gallery"
1:"To here /public/Images"
2:false

From this code in the backend

$item ['path' => '/public/Gallery']
$path = '/public/Images'
$success = File::moveDirectory($item['path'], $path);
return [
    "I want to move this ".$item['path'],
    "To here $path",
    $success,
];

Earlier i was getting a response that said the file already exists although it didnt but ive not since been able to replicate that.

EDIT

using Storage::move() i was able to replicate the 'already exists error'

exception:"League\Flysystem\FileExistsException"
file:"C:\Users\user.name\Desktop\electron-api\vendor\league\flysystem\src\Filesystem.php"
line:402
message:"File already exists at path: public/Images"

Question

How to move folders around in laravel 5 storage, NOT FILES. Preferably using the Storage Facade.


问:
It is possible to add values to an inline style using interpolation in Angular 4
I'm learning angular 4 by myself, and I want to know if is it possible to do this:

```<code><div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-
valuemin="0" aria-valuemax="100" style="width {{ item.percent_position}}%;">
{{ item.percent_position }}</div>
</div>
</code>```

What I want to achieve is to extend the width in relation to the value thrown by {{item.percent_position}}

When I use [style]="width: {{ item.percent_position }}%;" I got this error:
Uncaught Error: Quotes are not supported for evaluation!
        Statement: {{item.percent_position}}%;

What I want is this:

The result I get with the code above is this:

答:
When you use square brackets, you're binding to an expression, so you're suggested solution doesn't work, as Angular expects this to be executable JS:

```<code> [style]="width: {{ item.percent_position }}%;"
</code>```

In contrast, the following should work perfectly fine:

```<code> [style.width]="item.percent_position + '%' "
</code>```

If you have multiple styles to bind to, you can use ngStyle to bind to an object:

```<code> [ngStyle]="{ 'width': item.percent_position + '%' }"
</code>```

In any case: If you use square brackets, make sure what is bound to it is an executable expression!

Body:
I'm learning angular 4 by myself, and I want to know if is it possible to do this:

{{ item.percent_position }}

What I want to achieve is to extend the width in relation to the value thrown by {{item.percent_position}}

When I use [style]="width: {{ item.percent_position }}%;" I got this error:
Uncaught Error: Quotes are not supported for evaluation!
        Statement: {{item.percent_position}}%;

What I want is this:

The result I get with the code above is this:

Body:
When you use square brackets, you're binding to an expression, so you're suggested solution doesn't work, as Angular expects this to be executable JS:

 [style]="width: {{ item.percent_position }}%;"

In contrast, the following should work perfectly fine:

 [style.width]="item.percent_position + '%' "

If you have multiple styles to bind to, you can use ngStyle to bind to an object:

 [ngStyle]="{ 'width': item.percent_position + '%' }"

In any case: If you use square brackets, make sure what is bound to it is an executable expression!


问:
how do i setup the run time environment of microsoft visual fox pro on windows 7?
how do i setup the run time environment of microsoft visual fox pro on windows 7 ?
 I tried a lot after google the problem but still facing the same problem that is "Cannot find the runtime library of mirosoft visual foxpro".
Edit:
I am trying to install a standalone software that is made in foxpro in my laptop. And i never use foxpro so i don't know about it's runtime library or it's environment. So How do i setup it ? So that i can use that software. It is always showing me "Cannot find the runtime library of mirosoft visual foxpro"</p>

答:
It is very simple. Generally just having the 3 dlls in the same folder where your exe is sufficient (VFP9t.dll, VFP9r.dll and VFP9ENU.dll). These files are normally located in "C:\Program Files (x86)\Common Files\Microsoft Shared\VFP" folder (and VFP9ENU.dll is the English resource file, there are others).

Or you might go to Christof's site to download:
VFP runtime files


问:
"NOAUTH Authentication required" error is seen sometimes
org.springframework.dao.InvalidDataAccessApiUsageException: NOAUTH Authentication required.;
nested exception is redis.clients.jedis.exceptions.JedisDataException: NOAUTH Authentication required.

The above error occurs sometimes when I try to login into my application.

My set up is:

Tomcat is the application server

Redis is used to maintain session.

After restarting the redis, it starts working fine for a day or two after which the error is occurring again.

Please help in resolving this permanently..

答:
Try setting your Redis password after using pool.
I was having some problem with AUTH as well and then saw someone having similar problem with Lettuce by setting redis password before using pool.
Change the order, once you set your factory to use pool, then set the password.
The solution worked fine for me.
Link to similar problem with Lettuce</p>


问:
python script in microsoft ser

Hi everyone,

I'm trying to wrap my head around microsoft server 2017 and python script.
In general - I'm trying to store a table I took from a website (using bs4),
storing it in a panda df , and then simply put the results in a temp sql table.

I entered the following code (I'm skipping parts of the code because the python script
does work in python. Keep in mind I'm calling the script from microsoft sql server 2017):

```<code>    CREATE PROC OTC
AS
BEGIN
EXEC sp_execute_external_script
@language = N'Python',
@script = N'

import bs4 as bs
import pandas as pd
import requests
....
r = requests.get(url, verify = False)
html = r.text
soup = bs.BeautifulSoup(html, "html.parser")
data_date = str(soup.find(id="ctl00_SPWebPartManager1_g_4be2cf24_5a47_472d_a6ab_4248c8eb10eb_ctl00_lDate").contents)
t_tab1 = soup.find(id="ctl00_SPWebPartManager1_g_4be2cf24_5a47_472d_a6ab_4248c8eb10eb_ctl00_NiaROGrid1_DataGrid1")
df = parse_html_table(1,t_tab1)
print(df)
OutputDataSet=df
'
</code>```

I tried the microsoft tutorials and simply couldn't understand how to
handle the inputs/outputs to get the result as a sql table.

Furthermore, I get the error

"
  import bs4 as bs
ImportError: No module named 'bs4'
"

I'm obviously missing a lot here.
What am I to add to the sql code?
does the sql server even supports bs4? or only pandas?
and then I need to find another solution like write as csv?

Thanks for any help or advice you can offer

答:
To use pip to install a Python package on SQL Server 2017:

On the server, open a command prompt as administrator.

Then cd to {instance directory}\PYTHON_SERVICES\Scripts

(for example: C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\PYTHON_SERVICES\Scripts).

Then execute pip install {package name}.

One you have the necessary package(s) installed and the script executes successfully, simply setting variable OutputDataSet to a pandas data frame will result in the contents of that data frame being returned as a result set from the stored procedure.

If you want to capture that result set in a table (perhaps a temporary table), you can use INSERT...EXEC (e.g. INSERT MyTable(Col1, Col2) EXEC sp_execute_external_script ...).

Title: python script in microsoft ser

Body:
Hi everyone,

I'm trying to wrap my head around microsoft server 2017 and python script.
In general - I'm trying to store a table I took from a website (using bs4),
storing it in a panda df , and then simply put the results in a temp sql table.

I entered the following code (I'm skipping parts of the code because the python script
does work in python. Keep in mind I'm calling the script from microsoft sql server 2017):

    CREATE PROC OTC
AS
BEGIN
EXEC sp_execute_external_script
@language = N'Python',
@script = N'

import bs4 as bs
import pandas as pd
import requests
....
r = requests.get(url, verify = False)
html = r.text
soup = bs.BeautifulSoup(html, "html.parser")
data_date = str(soup.find(id="ctl00_SPWebPartManager1_g_4be2cf24_5a47_472d_a6ab_4248c8eb10eb_ctl00_lDate").contents)
t_tab1 = soup.find(id="ctl00_SPWebPartManager1_g_4be2cf24_5a47_472d_a6ab_4248c8eb10eb_ctl00_NiaROGrid1_DataGrid1")
df = parse_html_table(1,t_tab1)
print(df)
OutputDataSet=df
'

I tried the microsoft tutorials and simply couldn't understand how to
handle the inputs/outputs to get the result as a sql table.

Furthermore, I get the error

"
  import bs4 as bs
ImportError: No module named 'bs4'
"

I'm obviously missing a lot here.
What am I to add to the sql code?
does the sql server even supports bs4? or only pandas?
and then I need to find another solution like write as csv?

Thanks for any help or advice you can offer


问:
gnu ld/gdb: separate debug files. How to produce the debug file when there's too much debug info to link?
There's now gdb and binutils support for separating debug info from the binaries to be debugged.  Docs describing this can be found in:

gdb: separate debug files

objcopy --add-gnu-debuglink, --only-keep-debug

ld --build-id

After a bit of experimenting, I'm able to get gdb (7.6) to find the debug info using either the build-id and debug-link methods.  Here's two gdb fragments that show the debugger finding the debug info in the non-standard locations, using the build-id and debug-link methods respectively:

```<code>(gdb)  set debug-file-directory .
(gdb) file uWithBuildId
Reading symbols from /home/peeterj/build-id/uWithBuildId...Reading symbols from /home/peeterj/build-id/.build-id/2d/41caac1bcbeb65255abc3f35624cf9ed37791a.debug...done.

Reading symbols from /home/peeterj/build-id/uWithDebugLink...Reading symbols from /home/peeterj/build-id/uWithDebugLink.debug...done.
</code>```

To create the debug info files I've used objcopy and strip.  I've included details of such commands below for reference.

However, the reason I'm looking at this at all is with the hope of being able to build all of our product code with -g.  Currently this breaks the debugger if we try since our shared-lib is too big with relocation truncated to fit messages like:

```<code>/usr/lib64/gcc/x86_64-suse-linux/4.1.2/../../../../lib64/crtn.o:(.debug_aranges+0x6):     relocation truncated to fit: R_X86_64_32 against `.debug_info'
</code>```

(and subsequent link failure)

Does anybody know of a way to do one of:

Generate a standalone file containing all the debug info from the sources that contribute to the binary (i.e all the .o's and .a's that end up in the ld command that generates the binary).

Or, instruct ld to link without including this debug info in the binary itself, and generate a standalone debug file that can be identified with a build-id or debug-link?  I don't see anything in the docs for a single pass method to do this with ld, but the ld docs are big and perhaps I missed it.

Some way to deal with the truncation error above (such a method would allow either the build-id or debug-link methods to work).

 sample commands to generate separate debug files for an executable

Here's a sample command line sequence using both the --build-id and --add-gnu-debuglink methods:

```<code>g++ -g   -c -o u.o u.cpp
g++ -o uWithBuildId -Wl,--build-id u.o
g++ -o uWithDebugLink u.o
copyDebugAndStrip uWithBuildId
objcopy --only-keep-debug uWithDebugLink uWithDebugLink.debug
objcopy --add-gnu-debuglink=uWithDebugLink.debug uWithDebugLink
strip -g uWithDebugLink
</code>```

where copyDebugAndStrip is the following perl code:

```<code>#!/usr/bin/perl

my $binary = $ARGV[0] ;
my @p = `objdump --section .note.gnu.build-id -s $binary | tail -2` ;
foreach (@p)
{
   chomp ;
   s/^ *[\da-f]+ *// ;
   s/  .*// ;
   s/ //g ;
}

my $buildid = "$p[0]$p[1]" ;
$buildid =~ /^(..)(.*)/ ;

my ($d, $r) = ($1, $2) ;

print "build-id for '$binary': $buildid\n" ;

my $cmd =
"mkdir -p .build-id/$d
rm -f .build-id/$d/$r.debug
objcopy --only-keep-debug $binary .build-id/$d/$r.debug
strip -g $binary
" ;

print $cmd ;
system $cmd ;
</code>```

答:
I had similar issue  with linker when compiling with g++ (v6.3.0) + gold linker (v2.27) + “-g” parameter.

staticlib.a(sharedlib.o):(.debug_loc+0x1d38): relocation truncated to fit: R_X86_64_32 against `.debug_info'
staticlib.a(sharedlib.o):(.debug_loc+0x6c8c): additional relocation overflows omitted from the output
collect2: error: ld returned 1 exit status
gmake: *** [exec_file] Error 1
287.760u 35.837s 7:30.37 71.8%  0+0k 17217048+14932696io 0pf+0w

Adding the parameter "-fdebug-types-section" fixed this issue.

More details at: https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html

Body:
There's now gdb and binutils support for separating debug info from the binaries to be debugged.  Docs describing this can be found in:

gdb: separate debug files

objcopy --add-gnu-debuglink, --only-keep-debug

ld --build-id

After a bit of experimenting, I'm able to get gdb (7.6) to find the debug info using either the build-id and debug-link methods.  Here's two gdb fragments that show the debugger finding the debug info in the non-standard locations, using the build-id and debug-link methods respectively:

(gdb)  set debug-file-directory .
(gdb) file uWithBuildId
Reading symbols from /home/peeterj/build-id/uWithBuildId...Reading symbols from /home/peeterj/build-id/.build-id/2d/41caac1bcbeb65255abc3f35624cf9ed37791a.debug...done.

Reading symbols from /home/peeterj/build-id/uWithDebugLink...Reading symbols from /home/peeterj/build-id/uWithDebugLink.debug...done.

To create the debug info files I've used objcopy and strip.  I've included details of such commands below for reference.

However, the reason I'm looking at this at all is with the hope of being able to build all of our product code with -g.  Currently this breaks the debugger if we try since our shared-lib is too big with relocation truncated to fit messages like:

/usr/lib64/gcc/x86_64-suse-linux/4.1.2/../../../../lib64/crtn.o:(.debug_aranges+0x6):     relocation truncated to fit: R_X86_64_32 against `.debug_info'

(and subsequent link failure)

Does anybody know of a way to do one of:

Generate a standalone file containing all the debug info from the sources that contribute to the binary (i.e all the .o's and .a's that end up in the ld command that generates the binary).

Or, instruct ld to link without including this debug info in the binary itself, and generate a standalone debug file that can be identified with a build-id or debug-link?  I don't see anything in the docs for a single pass method to do this with ld, but the ld docs are big and perhaps I missed it.

Some way to deal with the truncation error above (such a method would allow either the build-id or debug-link methods to work).

 sample commands to generate separate debug files for an executable

Here's a sample command line sequence using both the --build-id and --add-gnu-debuglink methods:

g++ -g   -c -o u.o u.cpp
g++ -o uWithBuildId -Wl,--build-id u.o
g++ -o uWithDebugLink u.o
copyDebugAndStrip uWithBuildId
objcopy --only-keep-debug uWithDebugLink uWithDebugLink.debug
objcopy --add-gnu-debuglink=uWithDebugLink.debug uWithDebugLink
strip -g uWithDebugLink

where copyDebugAndStrip is the following perl code:

#!/usr/bin/perl

my $binary = $ARGV[0] ;
my @p = `objdump --section .note.gnu.build-id -s $binary | tail -2` ;
foreach (@p)
{
   chomp ;
   s/^ *[\da-f]+ *// ;
   s/  .*// ;
   s/ //g ;
}

my $buildid = "$p[0]$p[1]" ;
$buildid =~ /^(..)(.*)/ ;

my ($d, $r) = ($1, $2) ;

print "build-id for '$binary': $buildid\n" ;

my $cmd =
"mkdir -p .build-id/$d
rm -f .build-id/$d/$r.debug
objcopy --only-keep-debug $binary .build-id/$d/$r.debug
strip -g $binary
" ;

print $cmd ;
system $cmd ;


问:
Ajax submit doesn't work (can't read $_POST in php)
I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php

$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])

test.php

```<code><?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
    }
?>
<html>
    <body>
            <form action="index.php" method="post" align="center" id="form" name="form">

                <script type="text/javascript" src="test2.js"> </script>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>

                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>
    </body>
    </div>
</html>
</code>```

test2.js

```<code>function hit() {
        var inputText = $("#input").val();
        var inputTextString = "textbox=" + inputText;
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: inputTextString,
            success: function () {
              alert('form was submitted');
            }
        });

}
</code>```

答:
you will get the desired results in the response.

```<code>function hit() {

        var inputText = $("#input").val();

        $.ajax({
            type: 'post',
            url: 'test.php',
            data: {textbox : inputText},
            success: function (res) {
              alert(res);
            }
        });

}
</code>```

And you need to change in your test.php file.

```<code><?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];exit;
    }
?>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="test2.js"> </script>
</head>

    <body>
            <form action="index.php" method="post" align="center" id="form" name="form">
                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>
    </body>
    </div>
</html>
</code>```

Body:
I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php

$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])

test.php

<?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
    }
?>

            <form action="index.php" method="post" align="center" id="form" name="form">

                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>

test2.js

function hit() {
        var inputText = $("#input").val();
        var inputTextString = "textbox=" + inputText;
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: inputTextString,
            success: function () {
              alert('form was submitted');
            }
        });

}

Body:
you will get the desired results in the response.

function hit() {

        var inputText = $("#input").val();

        $.ajax({
            type: 'post',
            url: 'test.php',
            data: {textbox : inputText},
            success: function (res) {
              alert(res);
            }
        });

}

And you need to change in your test.php file.

<?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];exit;
    }
?>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="test2.js"> </script>
</head>

    <body>
            <form action="index.php" method="post" align="center" id="form" name="form">
                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>
    </body>
    </div>
</html>


问:
Generic Selection sort that can check object fields
What I need to do is take a file that would contain a name field and then also have data with them and sort them based on a given number that represents a certain set of that data. Here is an example text file. This would be like cities and their average temperature for each month(not actually accurate).

```<code>NewYork: 35, 28, 99, 39, 3, 15, 52, 5, 6, 97, 36, 32
Baltimore: 1, 59, 55, 0, 92, 82, 23, 60, 23, 16, 75, 75
Seattle: 19, 18, 10, 36, 50, 2, 8, 36, 56, 86, 14, 91
Atlanta: 57, 75, 52, 66, 28, 58, 53, 5, 21, 30, 81, 58
</code>```

I want to be able to sort these based on a given data point, so if 2 was selected it should be sorted by the second point in ascending order so it would look like this. The actual data for each city is not being sorted, the whole data set is being either moved up or down based on the data point that is being used.

```<code>Seattle: 19, 18, 10, 36, 50, 2, 8, 36, 56, 86, 14, 91
NewYork: 35, 28, 99, 39, 3, 15, 52, 5, 6, 97, 36, 32
Baltimore: 1, 59, 55, 0, 92, 82, 23, 60, 23, 16, 75, 75
Atlanta: 57, 75, 52, 66, 28, 58, 53, 5, 21, 30, 81, 58
              ^
             This is the second data point row that was sorted.
</code>```

Here is what the selectionsort class is looking like, and I could get it to work without generics but I want to be able to use generics.

```<code>public class SelectionSort{

private SelectionSort(){

}

public static <T extends Comparable<T>> void sort(ArrayList <T> arrayList, int key){

    for(int i=0; i<arrayList.size() -1; i++)
    {
        int smallestIndex = i;

        for(int j=i+1; j<arrayList.size(); j++)
        {
            if(arrayList.get(smallestIndex).compareTo((arrayList.get(j))) > 0  )
            {
                smallestIndex = j;
            }
        }
        T temp = arrayList.get(i);
        arrayList.add(i,arrayList.get(smallestIndex));
        arrayList.add(smallestIndex, temp);

    }

}
</code>```

Then for the actual objects I have this where the input to the constructor is simply one whole line from the text file. Then the data handle and name handle help to split the String up and set name to the name from the text file, and set the arraylist to be all the numbers that the name had with it.

```<code>public class ObjectData<T> {
private ArrayList<Integer> list;
private String name;

public ObjectData(String objectInfo){

    String array[] = allData(objectInfo);
    this.name = nameHandle(array[0]);
    list = new ArrayList<Integer>(Arrays.asList(dataHandle(array[1])));
}

private static String[] allData(String string){

    String array[] = string.split(":");

    return array;

}

private static String nameHandle(String string){
    String name = string.trim();

    return name;

}

private Integer[] dataHandle(String string){
    String array[] = string.split(",");
    String trimmedArray[] = new String[array.length];
    Integer integerArray[] = new Integer[trimmedArray.length];

    for (int i = 0; i < array.length; i++){
        trimmedArray[i] = array[i].trim();
    }

    for (int i = 0; i < trimmedArray.length; i++){
        integerArray[i] = Integer.valueOf(trimmedArray[i]);
    }

    return integerArray;
}

public String getName(){

    return this.name;

}

public Integer getIndex(int index){

    return list.get(index);

}
</code>```

}

In main all the objects are put into an arraylist, and that would be the arraylist of objects that is then inputed into the SelectionSort class. The problem I am having is figuring out how to use a the generic selection sort with an object like this. I was planning on just calling for example if the key was 2 like above. I would call

if(arrayList.get(smallestIndex).getIndex(2).compareTo((arrayList.get(smallestIndex).getIndex(2))) > 0  )

instead of if(arrayList.get(smallestIndex).compareTo((arrayList.get(j))) > 0  )

The only other way I was thinking about being able to do this was instead of creating objects I would just put all the information into a 2d array and then be able to compare them, but then I lose the name for the data. If anyone can suggest how I should change this to make it work, or a totally different way to accomplish this, that would be great.

答:
One way you might consider is creating an object that implements the Comparator interface and takes the index to sort on as a parameter:

```<code>public class DataComparator implements Comparator<ObjectData>{
    private int sortIndex;

    public DataComparator(int sortIndex){
        this.sortIndex = sortIndex;
    }

    public int compare(ObjectData t1, ObjectData t2) {
        return (t1.getIndex(sortIndex) < t2.getDataIndex(sortIndex)) ? -1 : 1;
    }
}
</code>```

If you then have a List<ObjectData> of your cities, let's call it cityList for the sake of example, you can sort it using Collections.sort(cityList, new DataComparator(2)).

Body:
What I need to do is take a file that would contain a name field and then also have data with them and sort them based on a given number that represents a certain set of that data. Here is an example text file. This would be like cities and their average temperature for each month(not actually accurate).

NewYork: 35, 28, 99, 39, 3, 15, 52, 5, 6, 97, 36, 32
Baltimore: 1, 59, 55, 0, 92, 82, 23, 60, 23, 16, 75, 75
Seattle: 19, 18, 10, 36, 50, 2, 8, 36, 56, 86, 14, 91
Atlanta: 57, 75, 52, 66, 28, 58, 53, 5, 21, 30, 81, 58

I want to be able to sort these based on a given data point, so if 2 was selected it should be sorted by the second point in ascending order so it would look like this. The actual data for each city is not being sorted, the whole data set is being either moved up or down based on the data point that is being used.

Seattle: 19, 18, 10, 36, 50, 2, 8, 36, 56, 86, 14, 91
NewYork: 35, 28, 99, 39, 3, 15, 52, 5, 6, 97, 36, 32
Baltimore: 1, 59, 55, 0, 92, 82, 23, 60, 23, 16, 75, 75
Atlanta: 57, 75, 52, 66, 28, 58, 53, 5, 21, 30, 81, 58
              ^
             This is the second data point row that was sorted.

Here is what the selectionsort class is looking like, and I could get it to work without generics but I want to be able to use generics.

public class SelectionSort{

private SelectionSort(){

}

public static <T extends Comparable<T>> void sort(ArrayList <T> arrayList, int key){

    for(int i=0; i<arrayList.size() -1; i++)
    {
        int smallestIndex = i;

        for(int j=i+1; j<arrayList.size(); j++)
        {
            if(arrayList.get(smallestIndex).compareTo((arrayList.get(j))) > 0  )
            {
                smallestIndex = j;
            }
        }
        T temp = arrayList.get(i);
        arrayList.add(i,arrayList.get(smallestIndex));
        arrayList.add(smallestIndex, temp);

    }

}

Then for the actual objects I have this where the input to the constructor is simply one whole line from the text file. Then the data handle and name handle help to split the String up and set name to the name from the text file, and set the arraylist to be all the numbers that the name had with it.

public class ObjectData<T> {
private ArrayList<Integer> list;
private String name;

public ObjectData(String objectInfo){

    String array[] = allData(objectInfo);
    this.name = nameHandle(array[0]);
    list = new ArrayList<Integer>(Arrays.asList(dataHandle(array[1])));
}

private static String[] allData(String string){

    String array[] = string.split(":");

    return array;

}

private static String nameHandle(String string){
    String name = string.trim();

    return name;

}

private Integer[] dataHandle(String string){
    String array[] = string.split(",");
    String trimmedArray[] = new String[array.length];
    Integer integerArray[] = new Integer[trimmedArray.length];

    for (int i = 0; i < array.length; i++){
        trimmedArray[i] = array[i].trim();
    }

    for (int i = 0; i < trimmedArray.length; i++){
        integerArray[i] = Integer.valueOf(trimmedArray[i]);
    }

    return integerArray;
}

public String getName(){

    return this.name;

}

public Integer getIndex(int index){

    return list.get(index);

}

}

In main all the objects are put into an arraylist, and that would be the arraylist of objects that is then inputed into the SelectionSort class. The problem I am having is figuring out how to use a the generic selection sort with an object like this. I was planning on just calling for example if the key was 2 like above. I would call

if(arrayList.get(smallestIndex).getIndex(2).compareTo((arrayList.get(smallestIndex).getIndex(2))) > 0  )

instead of if(arrayList.get(smallestIndex).compareTo((arrayList.get(j))) > 0  )

The only other way I was thinking about being able to do this was instead of creating objects I would just put all the information into a 2d array and then be able to compare them, but then I lose the name for the data. If anyone can suggest how I should change this to make it work, or a totally different way to accomplish this, that would be great.

Body:
One way you might consider is creating an object that implements the Comparator interface and takes the index to sort on as a parameter:

public class DataComparator implements Comparator<ObjectData>{
    private int sortIndex;

    public DataComparator(int sortIndex){
        this.sortIndex = sortIndex;
    }

    public int compare(ObjectData t1, ObjectData t2) {
        return (t1.getIndex(sortIndex) < t2.getDataIndex(sortIndex)) ? -1 : 1;
    }
}

If you then have a List<ObjectData> of your cities, let's call it cityList for the sake of example, you can sort it using Collections.sort(cityList, new DataComparator(2)).


问:
PgBouncer and auth to PostgreSQL
pgbouncer version 1.7.2

psql (9.5.6)

I try use auth_hba_file (/var/lib/pgsql/9.5/data/pg_hba.conf) in PgBouncer.

Config pgbouncer.ini

```<code>postgres = host=localhost port=5432 dbname=postgres user=postgres
test = host=localhost port=5432 dbname=test user=test
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_type = hba
auth_hba_file = /var/lib/pgsql/9.5/data/pg_hba.conf
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20
</code>```

cat pg_hba.conf | grep -v "#" | grep -v "^$"

```<code>local   all             all                              trust
host    all             all             127.0.0.1/32     trust
host    all             all             ::1/128          trust
host    test            test            10.255.4.0/24    md5
</code>```

psql -h 10.233.4.16 -p 5432 -U test

```<code>Password for user test:
psql (9.5.6)
Type "help" for help.

test=> \q
</code>```

psql -h 10.233.4.16 -p 6432 -U test

```<code>psql: ERROR:  No such user: test
</code>```

tail -fn10 /var/log/pgbouncer/pgbouncer.log

```<code>LOG C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 closing because: No such user: test (age=0)
WARNING C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 Pooler Error: No such user: test
LOG C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 login failed: db=test user=test
</code>```

But i cannot connect to postgresql (using PgBouncer) using pg_hba.conf

Can somebody help?
May you have example for use auth_hba_file.
Thanks

I changed config:

[root@dev-metrics2 pgbouncer]# cat pgbouncer.ini | grep -v ";" | grep -v "^$" | grep -v "#"

```<code>[databases]
postgres = host=localhost port=5432 dbname=postgres user=postgres
test = host=localhost port=5432 dbname=test auth_user=test
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20
</code>```

Drop and Create user and DB

```<code>[local]:5432 postgres@postgres # DROP DATABASE test;
DROP DATABASE
[local]:5432 postgres@postgres # DROP USER test ;
DROP ROLE
[local]:5432 postgres@postgres # CREATE USER test with password 'test';
CREATE ROLE
[local]:5432 postgres@postgres # CREATE DATABASE test with owner test;
CREATE DATABASE
</code>```

PGPASSWORD=test psql -h 10.233.4.16 -p 6432 -U test

```<code>Password for user test:
psql: ERROR:  Auth failed
</code>```

tail -fn1 /var/log/pgbouncer/pgbouncer.log

```<code>LOG Stats: 0 req/s, in 0 b/s, out 0 b/s,query 0 us
LOG C-0x17b57a0: test/test@10.255.4.245:3069 login attempt: db=test user=test tls=no
LOG C-0x17b57a0: test/test@10.255.4.245:3069 closing because: client unexpected eof (age=0)
LOG C-0x17b57a0: test/test@10.255.4.245:3070 login attempt: db=test user=test tls=no
LOG C-0x17b57a0: test/test@10.255.4.245:3070 closing because: Auth failed (age=0)
WARNING C-0x17b57a0: test/test@10.255.4.245:3070 Pooler Error: Auth failed
</code>```

Work config:

cat pgbouncer.ini | grep -v ";" | grep -v "^$" | grep -v "#"

```<code>[databases]
*= port=5432 auth_user=postgres
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20
</code>```

答:
Try put space

```<code>*= port=5432 auth_user=postgres  # old string
* = port=5432 auth_user=postgres # new string
</code>```

work for me

Title: PgBouncer and auth to PostgreSQL

Body:
pgbouncer version 1.7.2

psql (9.5.6)

I try use auth_hba_file (/var/lib/pgsql/9.5/data/pg_hba.conf) in PgBouncer.

Config pgbouncer.ini

postgres = host=localhost port=5432 dbname=postgres user=postgres
test = host=localhost port=5432 dbname=test user=test
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_type = hba
auth_hba_file = /var/lib/pgsql/9.5/data/pg_hba.conf
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20

cat pg_hba.conf | grep -v "#" | grep -v "^$"

local   all             all                              trust
host    all             all             127.0.0.1/32     trust
host    all             all             ::1/128          trust
host    test            test            10.255.4.0/24    md5

psql -h 10.233.4.16 -p 5432 -U test

Password for user test:
psql (9.5.6)
Type "help" for help.

test=> \q

psql -h 10.233.4.16 -p 6432 -U test

psql: ERROR:  No such user: test

tail -fn10 /var/log/pgbouncer/pgbouncer.log

LOG C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 closing because: No such user: test (age=0)
WARNING C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 Pooler Error: No such user: test
LOG C-0x78f7e0: (nodb)/(nouser)@10.255.4.245:8963 login failed: db=test user=test

But i cannot connect to postgresql (using PgBouncer) using pg_hba.conf

Can somebody help?
May you have example for use auth_hba_file.
Thanks

I changed config:

[root@dev-metrics2 pgbouncer]# cat pgbouncer.ini | grep -v ";" | grep -v "^$" | grep -v "#"

[databases]
postgres = host=localhost port=5432 dbname=postgres user=postgres
test = host=localhost port=5432 dbname=test auth_user=test
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20

Drop and Create user and DB

[local]:5432 postgres@postgres # DROP DATABASE test;
DROP DATABASE
[local]:5432 postgres@postgres # DROP USER test ;
DROP ROLE
[local]:5432 postgres@postgres # CREATE USER test with password 'test';
CREATE ROLE
[local]:5432 postgres@postgres # CREATE DATABASE test with owner test;
CREATE DATABASE

PGPASSWORD=test psql -h 10.233.4.16 -p 6432 -U test

Password for user test:
psql: ERROR:  Auth failed

tail -fn1 /var/log/pgbouncer/pgbouncer.log

LOG Stats: 0 req/s, in 0 b/s, out 0 b/s,query 0 us
LOG C-0x17b57a0: test/test@10.255.4.245:3069 login attempt: db=test user=test tls=no
LOG C-0x17b57a0: test/test@10.255.4.245:3069 closing because: client unexpected eof (age=0)
LOG C-0x17b57a0: test/test@10.255.4.245:3070 login attempt: db=test user=test tls=no
LOG C-0x17b57a0: test/test@10.255.4.245:3070 closing because: Auth failed (age=0)
WARNING C-0x17b57a0: test/test@10.255.4.245:3070 Pooler Error: Auth failed

Work config:

cat pgbouncer.ini | grep -v ";" | grep -v "^$" | grep -v "#"

[databases]
*= port=5432 auth_user=postgres
[pgbouncer]
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pid
listen_addr = *
listen_port = 6432
auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1
admin_users = postgres
stats_users = stats, postgres
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 100
default_pool_size = 20

Body:
Try put space

*= port=5432 auth_user=postgres  # old string
* = port=5432 auth_user=postgres # new string

work for me


问:
Are there any guarantees about C struct packing?
Are there any guarantees regarding packing of structs in C?

Just as an example, provided that sizeof(double) == 8, is it guaranteed that sizeof(struct { double x, y; }) == 16?

I am aware that the intention behind this question conflicts with strict aliasing rules, therefore assume strict aliasing is disabled, e.g. in the case of gcc with -fno-strict-aliasing.

To avoid any further speculations: The intention is knowing about compatibility of a struct with its explicitly packed counterpart. Note that aliasing is relevant even in the following case: Are C-structs with the same members types guaranteed to have the same layout in memory?
. No need to worry about me wanting to access single bytes.

答:
The only thing the C standard says regarding struct packing is that no padding  may exist at the start of a struct.  It makes no guarantees regarding padding between fields or at the end.

Section 6.7.2.1 of the C standard says the following regarding structures:

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the
  order in which they are declared. A pointer to a structure object,
  suitably converted, points to its initial member (or if that member is
  a bit-field, then to the unit in which it resides), and vice versa.
  There may be unnamed padding within a structure object, but not at its
  beginning.

...

17 There may be unnamed padding at the end of a structure or union.

That being said, most implementations tend to be fairly consistent with how structures are packed.  Non-struct variables n bytes in size (or arrays such variables) will tend to start on an n byte boundary.  A struct within a struct will tend to be aligned based on the alignment of its subfields.

The Lost Art of C Structure Packing goes into this in much more detail.


问:
No way to get ListView to show initial selected item
There seems to be no way to get an initial selection to be show in a Xamarin Forms ListView.  I see that this question has been asked a few times, however in each case there is either no relevant answer or the unanswered question is too complicated to be analyzed properly or the question is answered but the answer does not work.  So I thought I would pose a simplified version of this question in the hope that someone can show me a workaround.  A workaround is all that can be done because it has become clear to be that the SelectedItem cannot be bound and it cannot be set from code.  Here are the SO question I have examined...

:Why can't I set the SelectedItem property of Xamarin.Forms.ListView?

Xamarin Forms ListView SelectedItem Binding Issue

Xamarin.Forms ListView set SelectedItem by Code

Xamarin XAML ListView - How to select programatically

Here is the XAML...

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XamarinFormsBench"
         x:Class="XamarinFormsBench.ListViewPage1">
    <ContentPage.BindingContext>
        <local:ViewModel1/>
    </ContentPage.BindingContext>
    <ListView x:Name="MyListView" Margin="0,20,0,0"
        ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
          BindingContextChanged="MyListView_BindingContextChanged">
    </ListView>
</ContentPage>
</code>```

Here is the code...

```<code>public class Item
{
    public Item(string name, string description)
    {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public override string ToString()
    {
        return Name + " = " + Description;
    }
}

public class ViewModel1 : INotifyPropertyChanged
{
    public ObservableCollection<Item> Items { get; set; }
    public ViewModel1()
    {

        Items = new ObservableCollection<Item>
        {
            new Item("Item 1","First item"),
            new Item("Item 2","Second item"),
            new Item("Item 3","Third item"),
            new Item("Item 4","Fourth item"),
            new Item("Item 5","Fifth item")
        };
        _selectedItem = Items[2];
    }
    Item _selectedItem;
    public event PropertyChangedEventHandler PropertyChanged;
    public Item SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            _selectedItem = value;
            NotifyPropertyChanged(nameof(SelectedItem));
        }
    }
    public void NotifyPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListViewPage1 : ContentPage
{
    public ListViewPage1()
    {
        InitializeComponent();
    }
    public ViewModel1 ViewModel
    {
        get
        {
            return BindingContext as ViewModel1;
        }
    }

    private void MyListView_BindingContextChanged(object sender, EventArgs e)
    {
    //         MyListView.SelectedItem = ViewModel.SelectedItem;
    }
}
</code>```

My expectation is that a list of 5 items appears and the 3rd item will be highlighted.  What happens is that 5 items appears but no item is highlighted.  The binding clearly works because the selected item is updated each time I click on an item.

Now if I remove the binding and try to set the selected item in code by uncommenting the line near the end, that does not work either.

So I am out of ideas.  I've been looking at simulating a mouse click but this is really a kluge beyond where I am willing to go.

I have run this code on UWP and Android.  Haven't tried iOS.

答:
Ok, it turns out this is only a problem on UWP.  The workaround to get this working for UWP is as follows in ListViewPage1 :</p>

```<code>    protected override void OnAppearing()
    {
        base.OnAppearing();
        // *STANDARD MASSIVE KLUGE* Needed to get initial selection to show.
        Item m = MyListView.SelectedItem as Item;
        MyListView.SelectedItem = null;
        MyListView.SelectedItem = m;
    }
</code>```

Body:
There seems to be no way to get an initial selection to be show in a Xamarin Forms ListView.  I see that this question has been asked a few times, however in each case there is either no relevant answer or the unanswered question is too complicated to be analyzed properly or the question is answered but the answer does not work.  So I thought I would pose a simplified version of this question in the hope that someone can show me a workaround.  A workaround is all that can be done because it has become clear to be that the SelectedItem cannot be bound and it cannot be set from code.  Here are the SO question I have examined...

:Why can't I set the SelectedItem property of Xamarin.Forms.ListView?

Xamarin Forms ListView SelectedItem Binding Issue

Xamarin.Forms ListView set SelectedItem by Code

Xamarin XAML ListView - How to select programatically

Here is the XAML...

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XamarinFormsBench"
         x:Class="XamarinFormsBench.ListViewPage1">
    <ContentPage.BindingContext>
        <local:ViewModel1/>
    </ContentPage.BindingContext>
    <ListView x:Name="MyListView" Margin="0,20,0,0"
        ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
          BindingContextChanged="MyListView_BindingContextChanged">
    </ListView>
</ContentPage>

Here is the code...

public class Item
{
    public Item(string name, string description)
    {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public override string ToString()
    {
        return Name + " = " + Description;
    }
}

public class ViewModel1 : INotifyPropertyChanged
{
    public ObservableCollection<Item> Items { get; set; }
    public ViewModel1()
    {

        Items = new ObservableCollection<Item>
        {
            new Item("Item 1","First item"),
            new Item("Item 2","Second item"),
            new Item("Item 3","Third item"),
            new Item("Item 4","Fourth item"),
            new Item("Item 5","Fifth item")
        };
        _selectedItem = Items[2];
    }
    Item _selectedItem;
    public event PropertyChangedEventHandler PropertyChanged;
    public Item SelectedItem
    {
        get
        {
            return _selectedItem;
        }
        set
        {
            _selectedItem = value;
            NotifyPropertyChanged(nameof(SelectedItem));
        }
    }
    public void NotifyPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ListViewPage1 : ContentPage
{
    public ListViewPage1()
    {
        InitializeComponent();
    }
    public ViewModel1 ViewModel
    {
        get
        {
            return BindingContext as ViewModel1;
        }
    }

    private void MyListView_BindingContextChanged(object sender, EventArgs e)
    {
    //         MyListView.SelectedItem = ViewModel.SelectedItem;
    }
}

My expectation is that a list of 5 items appears and the 3rd item will be highlighted.  What happens is that 5 items appears but no item is highlighted.  The binding clearly works because the selected item is updated each time I click on an item.

Now if I remove the binding and try to set the selected item in code by uncommenting the line near the end, that does not work either.

So I am out of ideas.  I've been looking at simulating a mouse click but this is really a kluge beyond where I am willing to go.

I have run this code on UWP and Android.  Haven't tried iOS.

Body:
Ok, it turns out this is only a problem on UWP.  The workaround to get this working for UWP is as follows in ListViewPage1 :

    protected override void OnAppearing()
    {
        base.OnAppearing();
        // *STANDARD MASSIVE KLUGE* Needed to get initial selection to show.
        Item m = MyListView.SelectedItem as Item;
        MyListView.SelectedItem = null;
        MyListView.SelectedItem = m;
    }


问:
How to send JSON file as part of request body in CURL POST command
I am using CURL command line to send HTTP POST to a web service. I want to include a file's contents as a PART of the body of the POST command. Is this possible? I know I can send a file as the entire body as answered here. But I only want a part of the body to be the content of the file.

For example

```<code>curl -d '{ "name": "rahul", "speed": "fast", "data": { "number": 1, "letter": "abd", "letter2": "efg"} }' 'http://...'
</code>```

Here I only want data as the file's content. Not the entire body. How can I do this?

答:
Set a variable to contain the file contents:

```<code>data=$(cat /path/to/file)
</code>```

then substitute it into the JSON:

```<code>curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'
</code>```

Body:
I am using CURL command line to send HTTP POST to a web service. I want to include a file's contents as a PART of the body of the POST command. Is this possible? I know I can send a file as the entire body as answered here. But I only want a part of the body to be the content of the file.

For example

curl -d '{ "name": "rahul", "speed": "fast", "data": { "number": 1, "letter": "abd", "letter2": "efg"} }' 'http://...'

Here I only want data as the file's content. Not the entire body. How can I do this?

Body:
Set a variable to contain the file contents:

data=$(cat /path/to/file)

then substitute it into the JSON:

curl -d '{ "name": "rahul", "speed": "fast", "data": "'$data'" }' 'http://...'


问:
C# Vector3's get the remaining area in percentage
I have two Vector3, that each represent the size of an area. First one is the total amount of the area. Second one is just a part of the first one. How do i get the percentage, that remains of the total area, when i subtract the smaller area? </p>

答:
If both represents size (they are positive in components by definition) and fully interesects (one fully lies in borders of another), then you just need to calculate percentage of their volume difference:

```<code>|v1.volume - v2.volume|/max(v1.volume, v2.volume)
</code>```

So in code it will look like this:

```<code>double v1Volume = v1.x * v1.y * v1.z;
double v2Volume = v2.x * v2.y * v2.z;
double percentageDiff = 100 * Math.Abs(v1Volume - v2Volume) / Math.Max(v1Volume, v2Volume);
</code>```

This way, it doesn't even matter which one small and which one big, just put both in this function and it will show correct answer.

Body:
If both represents size (they are positive in components by definition) and fully interesects (one fully lies in borders of another), then you just need to calculate percentage of their volume difference:

|v1.volume - v2.volume|/max(v1.volume, v2.volume)

So in code it will look like this:

double v1Volume = v1.x * v1.y * v1.z;
double v2Volume = v2.x * v2.y * v2.z;
double percentageDiff = 100 * Math.Abs(v1Volume - v2Volume) / Math.Max(v1Volume, v2Volume);

This way, it doesn't even matter which one small and which one big, just put both in this function and it will show correct answer.


问:
MVC ListBoxFor missing special char
I have an MVC4 app that uses bootstrap
on one view I have

```<code>@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}
</code>```

Model.OPtions have a string value that has special characters in it.
These are being stripped out

It is an IEmumerable<SelectListItem>

any ideas?

答:
Have you tried to use HttpUtility.HtmlEncode as Luke Duddridge pointed out here?
ASP MVC Razor encode special characters in input placeholder</p>

Title: MVC ListBoxFor missing special char

Body:
I have an MVC4 app that uses bootstrap
on one view I have

@Html.ListBoxFor(x=>x.ids,Model.OPtions,new {@class = "form-control",multiple ="multiple",id ="optionid",data_placeHolder ="Something}

Model.OPtions have a string value that has special characters in it.
These are being stripped out

It is an IEmumerable<SelectListItem>

any ideas?


问:
Keeping the same background across multiple activities in Android and excluding them from activity transitions
I'm working on an Android application at the moment. Basically, I have multiple ViewFlippers which will be used to create sets of 'panels'. For example, I have a ViewFlipper to simulate a home screen environment (multiple panels that can be accessed by swiping left or right), as well as a different ViewFlipper to simulate an application launcher (panels for favorite apps, all apps, settings etc). I've done this by creating each set of panels, or each ViewFlipper in it's own activity, to preserve memory when a set of panels aren't being used.

Basically, I want to keep the same background image across all the activities. Now, I know this can be done by creating a style, and applying it in the  tags in the manifest, but my issue is that the background image is included in the activity transition animation (my own custom animation has been set, but regardless, using stock transition animations or not, the background image is included).

So, what I am asking is, is there a way to keep a common background image across multiple activities that is NOT animated when switching between activities?

At the moment, my style xml file looks like this:

```<code><style name="Theme" parent="android:Theme">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/background_port</item>
</style>
</code>```

So as you can see, the same drawable is being set as the background for all activities, but it is included in the transition animations between activities, which I don't want. I also have tried android:detachWallpaper="true", but that seems useless in this case.

I'm fairly experienced in Android code, so no need to explain things in simple manners. If I don't understand something, I'll ask.

Thanks for all your help, it's really appreciated.

答: Don't use activities.  You are just making what you want to do super-complicated by trying to wrench an Activity into behaving like it is integrated like that.  Use Views.  You say you want to use activities to save memory, but they will not save you memory and are in pretty every way more heavy-weight than simple views.  With views you have complete control going on in your UI, which is basically what you are asking for.  If you want to be as efficient as possible inflate the views you want to have shown at the time you are showing them, and remove the old part of the view hierarchy that is no longer shown so it can be GCed.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm working on an Android application at the moment. Basically, I have multiple ViewFlippers which will be used to create sets of 'panels'. For example, I have a ViewFlipper to simulate a home screen environment (multiple panels that can be accessed by swiping left or right), as well as a different ViewFlipper to simulate an application launcher (panels for favorite apps, all apps, settings etc). I've done this by creating each set of panels, or each ViewFlipper in it's own activity, to preserve memory when a set of panels aren't being used.

Basically, I want to keep the same background image across all the activities. Now, I know this can be done by creating a style, and applying it in the  tags in the manifest, but my issue is that the background image is included in the activity transition animation (my own custom animation has been set, but regardless, using stock transition animations or not, the background image is included).

So, what I am asking is, is there a way to keep a common background image across multiple activities that is NOT animated when switching between activities?

At the moment, my style xml file looks like this:

So as you can see, the same drawable is being set as the background for all activities, but it is included in the transition animations between activities, which I don't want. I also have tried android:detachWallpaper="true", but that seems useless in this case.

I'm fairly experienced in Android code, so no need to explain things in simple manners. If I don't understand something, I'll ask.

Thanks for all your help, it's really appreciated.


问:
Microsoft bond service inheritance
Is it possible to perform inheritance between bond services?

In particular, I have several services with a common endpoint in each. Can I make them inherit from a service containing that common endpoint?

答:
No, as of December 2017 inheritance of services is not currently supported in C++ or C#.

There are some details that need to be decided on (e.g., what is the name of the inherited method "baseservice.method"? "derivedservice.method"? both?, does inheritance model containment or substitution? how are multiple implementations of the same base hosted on the same endpoint dispatched?) before implementation can move forward. If you'd like to move this forward faster, opening an issue on the GitHub project to start the design process would help.

Title: Microsoft bond service inheritance


问:
Nginx on Fedora 26: could not build optimal types_hash error message
I've installed Fedora and Ngnix, added all the configuration files for my local development, when I started to see this error

```<code>nginx: [warn] could not build optimal types_hash, you should increase either types_hash_max_size: 2048 or types_hash_bucket_size: 64; ignoring types_hash_bucket_size
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
</code>```

I found solutions saying that I should add types_hash_bucket_size to nginx.conf, but I've added it, removed the default one, removed both and added both, it insists on showing this error.

```<code>http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile                            on;
    tcp_nopush                          on;
    tcp_nodelay                         on;
    keepalive_timeout                   65;

    # I tried leaving both, removing both and one of each. The error persists.
    types_hash_max_size                2048;
    server_names_hash_bucket_size      128;
</code>```

types_hash_max_size was there by default when I installed nginx, though.

My files from sites-enabled:

```<code>server {
  listen 80;
  server_name devapi.hporder.com;

  root /home/gabriel/Sites/hp-order-system/workspace/api;

  client_max_body_size 10M;

  location ~ ^/(images|javascript|js|css|flash|media|static)/  {
    expires 30d;
  }

  location / {
    index  index.php index.html index.htm;
    try_files $uri $uri/ /index.php$is_args$args;
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/local/Cellar/nginx/1.10.1/html;
  }

  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    fastcgi_param FF_BOOTSTRAP_ENVIRONMENT dev;
    fastcgi_param FF_BOOTSTRAP_CONFIG api/dev;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    # include /usr/local/etc/nginx/fastcgi.conf;

    fastcgi_buffer_size 1024k;
    fastcgi_buffers 1024 1024k;
    fastcgi_busy_buffers_size 1024k;
  }
}
</code>```

答:
On Fedora 25, I had this problem as well. types_hash_max_size was set to 2048 (nginx documentation indicate it defaults to 1024).  I simply increased it to 4096 and nginx was happy (checked with nginx -t).

FWIW, in my configuration there is no setting related to the hash bucket size. It's just the default.

Body:
I've installed Fedora and Ngnix, added all the configuration files for my local development, when I started to see this error

nginx: [warn] could not build optimal types_hash, you should increase either types_hash_max_size: 2048 or types_hash_bucket_size: 64; ignoring types_hash_bucket_size
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

I found solutions saying that I should add types_hash_bucket_size to nginx.conf, but I've added it, removed the default one, removed both and added both, it insists on showing this error.

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile                            on;
    tcp_nopush                          on;
    tcp_nodelay                         on;
    keepalive_timeout                   65;

    # I tried leaving both, removing both and one of each. The error persists.
    types_hash_max_size                2048;
    server_names_hash_bucket_size      128;

types_hash_max_size was there by default when I installed nginx, though.

My files from sites-enabled:

server {
  listen 80;
  server_name devapi.hporder.com;

  root /home/gabriel/Sites/hp-order-system/workspace/api;

  client_max_body_size 10M;

  location ~ ^/(images|javascript|js|css|flash|media|static)/  {
    expires 30d;
  }

  location / {
    index  index.php index.html index.htm;
    try_files $uri $uri/ /index.php$is_args$args;
  }

  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/local/Cellar/nginx/1.10.1/html;
  }

  location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;

    fastcgi_param FF_BOOTSTRAP_ENVIRONMENT dev;
    fastcgi_param FF_BOOTSTRAP_CONFIG api/dev;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    # include /usr/local/etc/nginx/fastcgi.conf;

    fastcgi_buffer_size 1024k;
    fastcgi_buffers 1024 1024k;
    fastcgi_busy_buffers_size 1024k;
  }
}


问:
Is there a way to configure the default mirror for App::cpanminus (cpanm)?
I am aware you can easily configure cpan to use a specific mirror.  However I recently started using cpanm at the advice of a friend, and I can't seem to find a way to set the default mirror without specifying --mirror http://cpan.metacpan.org on the command line each time.

Is there an environment variable or a config file that I can set the default mirror?

As for why I would want to simply not use the default list of mirrors, I am an FI and we are firewalled to no end.  Only one mirror has been allowed through our firewall.

答:
Cite from the cpanm docs

ENVIRONMENT VARIABLES

PERL_CPANM_OPT If set, adds a set of default options to every cpanm
  command. These options come first, and so are overridden by
  command-line options.

So try: export PERL_CPANM_OPT="--mirror http://cpan.metacpan.org"


问:
Getting the name of a JRadioButton in Java

I am trying to get the names of all selected JRadioButtons from my graphics interface. As such I create the allFacilities array in which I include all of my JRadioButtons.

The first for loop serves to find the number of selected radio buttons.

The second for loop aspires to get the name of each selected button.

When checking what the .getName() returns:
    System.out.println("A##" + button.getName());, only null is returned for all cases.

Here is my code:

```<code>    JRadioButton[] allFacilities = {restaurant, laundry, parking};
    int selectedFacilitiesCounter = 0;
    for(JRadioButton check : allFacilities) {
        if(check.isSelected()) {
            selectedFacilitiesCounter += 1;
        }
    }
    String[] selectedFacilities = new String[selectedFacilitiesCounter];
    int index = 0;
    for(JRadioButton button : allFacilities) {
        if(button.isSelected()) {
            System.out.println("A##" + button.getName());
            switch(button.getName()) {
                case "restaurant":
                    selectedFacilities[index] = "restaurant";
                    break;
                case "laundry":
                    selectedFacilities[index] = "laundry";
                    break;
                case "parking":
                    selectedFacilities[index] = "parking";
                    break;
                default:
                    System.out.println("Facility Not Found");
            }
            index += 1;
        }
     }
</code>```

Does anybody have any ideas on how I can solve my problem?

答:
I believe that what you want is this:

```<code>    JRadioButton button = new JRadioButton("test");
    System.out.println(button.getText());
</code>```

Which will print test.

The method getName retrieves the name of the component, which you should've set with setName, which I believe you didn't.

Body:
I am trying to get the names of all selected JRadioButtons from my graphics interface. As such I create the allFacilities array in which I include all of my JRadioButtons.

The first for loop serves to find the number of selected radio buttons.

The second for loop aspires to get the name of each selected button.

When checking what the .getName() returns:
    System.out.println("A##" + button.getName());, only null is returned for all cases.

Here is my code:

    JRadioButton[] allFacilities = {restaurant, laundry, parking};
    int selectedFacilitiesCounter = 0;
    for(JRadioButton check : allFacilities) {
        if(check.isSelected()) {
            selectedFacilitiesCounter += 1;
        }
    }
    String[] selectedFacilities = new String[selectedFacilitiesCounter];
    int index = 0;
    for(JRadioButton button : allFacilities) {
        if(button.isSelected()) {
            System.out.println("A##" + button.getName());
            switch(button.getName()) {
                case "restaurant":
                    selectedFacilities[index] = "restaurant";
                    break;
                case "laundry":
                    selectedFacilities[index] = "laundry";
                    break;
                case "parking":
                    selectedFacilities[index] = "parking";
                    break;
                default:
                    System.out.println("Facility Not Found");
            }
            index += 1;
        }
     }

Does anybody have any ideas on how I can solve my problem?

Body:
I believe that what you want is this:

    JRadioButton button = new JRadioButton("test");
    System.out.println(button.getText());

Which will print test.

The method getName retrieves the name of the component, which you should've set with setName, which I believe you didn't.


问:
Pandas Python: Slice / Transform URL to get item and item counts
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

```<code>http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1
</code>```

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

答:
In pure Python, one way to do this is by splitting the string at '?', taking the second component, and splitting again at '='.

```<code>url = 'http://mysportswebsite.com/shop/?Baseball+Bat=5'
item, count = url.split('?')[1].split('=')
</code>```

You can use apply to run this operation over a column, however if you have a large number of URLs, it is more efficient to use the built in string methods for the same operation. The syntax is quite similar.

```<code>data = pd.Series([
    'http://mysportswebsite.com/shop/?Baseball+Bat=5',
    'http//memoribilia.com/checkout?autograph=1'])
df = data.str.split('?', expand=True)[1].str.split('=', expand=True)
df.columns = ['item', 'count']
</code>```

Body:
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

Body:
In pure Python, one way to do this is by splitting the string at '?', taking the second component, and splitting again at '='.

url = 'http://mysportswebsite.com/shop/?Baseball+Bat=5'
item, count = url.split('?')[1].split('=')

You can use apply to run this operation over a column, however if you have a large number of URLs, it is more efficient to use the built in string methods for the same operation. The syntax is quite similar.

data = pd.Series([
    'http://mysportswebsite.com/shop/?Baseball+Bat=5',
    'http//memoribilia.com/checkout?autograph=1'])
df = data.str.split('?', expand=True)[1].str.split('=', expand=True)
df.columns = ['item', 'count']


问:
What is the difference between tensors and sparse tensors?
I am having troubles understanding the meaning and usages for Tensorflow Tensors and Sparse Tensors.

According to the documentation

Tensor

Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of floating point numbers with dimensions [batch, height, width, channels].

Sparse Tensor

TensorFlow represents a sparse tensor as three separate dense tensors: indices, values, and shape. In Python, the three tensors are collected into a SparseTensor class for ease of use. If you have separate indices, values, and shape tensors, wrap them in a SparseTensor object before passing to the ops below.

My understandings are Tensors are used for operations, input and output. And Sparse Tensor is just another representation of a Tensor(dense?). Hope someone can further explain the differences, and the use cases for them.

答:
The difference involves computational speed. If a large tensor has many, many zeroes, it's faster to perform computation by iterating through the non-zero elements. Therefore, you should store the data in a SparseTensor and use the special operations for SparseTensors.

The relationship is similar for matrices and sparse matrices. Sparse matrices are common in dynamic systems, and mathematicians have developed many special methods for operating on them.