问:
how to pass same parameter multiple times in ruby
I have following index method in ruby

```<code>def index
  if params.key?(:item)
    @items = Item.get_items.where(item: params[:item])
  else
    @items = Item.get_items
end
</code>```

I am using postman for testing as follows

```<code>http://localhost:3000/items?item=some_item
</code>```

How can pass same param twice?

e.g

```<code>http://localhost:3000/items?item=some_item&item=other_item
</code>```

Edit: adding views

index.json.jbuilder

```<code>json.array! @items, partial: ‘items/item’, as: :item
</code>```

_item.json.jbuilder

```<code>json.something1 item.something1
json.item_layout do
  json.template_key item.layout
  json.merge! item.layout_config if item.layout_config.present?
end
json.something (item.item_details) do |item_detail|
  json.partial! ‘item_details/item_detail’, item_detail: item_detail
end
</code>```

答:
You mean, like an array? Try this way</p>

```<code>http://localhost:3000/items?item[]=some_item&item[]=other_item
</code>```

Body:
I have following index method in ruby

def index
  if params.key?(:item)
    @items = Item.get_items.where(item: params[:item])
  else
    @items = Item.get_items
end

I am using postman for testing as follows

http://localhost:3000/items?item=some_item

How can pass same param twice?

e.g

http://localhost:3000/items?item=some_item&item=other_item

Edit: adding views

index.json.jbuilder

json.array! @items, partial: ‘items/item’, as: :item

_item.json.jbuilder

json.something1 item.something1
json.item_layout do
  json.template_key item.layout
  json.merge! item.layout_config if item.layout_config.present?
end
json.something (item.item_details) do |item_detail|
  json.partial! ‘item_details/item_detail’, item_detail: item_detail
end

Body:
You mean, like an array? Try this way

http://localhost:3000/items?item[]=some_item&item[]=other_item


来源: stackexchange

问:
Why does a fixed background-image move when scrolling on IE?
I'm trying to make background-image fixed.

As you see in my blog, the background-image is moving when scrolling on IE 11.

How can I fix this?

This is my CSS:

```<code>background-image: url("./images/cover.jpg");
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
background-size: cover;
</code>```

答:
I tried twicejr's CSS solution but it is not working in Edge/15.15063. Dasha's answer solved the problem in Edge but not IE 11. I noticed that the document.documentMode condition was not complete. document.documentmode will return undefined for all browsers except for IE 8+ which will return the mode number. With that, the following code will detect both IE 8+ and Edge and solve the background image problem.

```<code>if ((document.documentMode != undefined) || (/Edge/.test(navigator.userAgent))) {
document.documentElement.style.overflow = "hidden";
document.documentElement.style.height = "100%";
document.body.style.overflow = "auto";
document.body.style.height = "100%";}
</code>```

JS Fiddle for the above code.
This also works with arrow key and track-pad scrolling.
I didn't give any consideration to IE7-

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make background-image fixed.

As you see in my blog, the background-image is moving when scrolling on IE 11.

How can I fix this?

This is my CSS:

background-image: url("./images/cover.jpg");
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
background-size: cover;

Body:
I tried twicejr's CSS solution but it is not working in Edge/15.15063. Dasha's answer solved the problem in Edge but not IE 11. I noticed that the document.documentMode condition was not complete. document.documentmode will return undefined for all browsers except for IE 8+ which will return the mode number. With that, the following code will detect both IE 8+ and Edge and solve the background image problem.

if ((document.documentMode != undefined) || (/Edge/.test(navigator.userAgent))) {
document.documentElement.style.overflow = "hidden";
document.documentElement.style.height = "100%";
document.body.style.overflow = "auto";
document.body.style.height = "100%";}

JS Fiddle for the above code.
This also works with arrow key and track-pad scrolling.
I didn't give any consideration to IE7-

ContentLicense: CC BY-SA 3.0


问:
how to extract a negative symbol from text
Below I have a piece of code that is able to extract the number values from a piece of text. So if I have string +12 is on same day, then it will extract 12.

However if I have a negative number like -12 is on the same day, I want it to extract -12, not 12.

How I can extract the minus symbol?

```<code>foreach (char c in alternativeAirportPrice.Text)
{
    if (char.IsNumber(c))
    {
        string test = "-12 on same day";
        string alternativeAirportPriceValue = string.Join("", test.ToCharArray()
                                             .Where(x => char.IsDigit(x)).ToArray());
        return alternativeAirportPriceValue;
    }
}
</code>```

答:
Try this:

```<code>public IEnumerable<int> ExtractNumbers(string text)
{
    text += " ";
    var temp = string.Empty;
    for (var i = 0; i < text.Length; i++)
    {
        if (char.IsDigit(text[i]))
        {
            if ('-'.Equals(text[i - 1]))
            {
                temp += text[i - 1];
            }
            temp += text[i];
        }
        else if (temp.Length > 0)
        {
            yield return int.Parse(temp);
            temp = string.Empty;
        }
    }
}
</code>```

This way you can handle cases where the string has multiple numbers in it, as observed by @Sir Rufo

The line:

```<code>text += " ";
</code>```

is there to ensure the loop will hit the "else if" block when a number is in the last position of the string, e.g. "-12 on the same day 123456"

Body:
Below I have a piece of code that is able to extract the number values from a piece of text. So if I have string +12 is on same day, then it will extract 12.

However if I have a negative number like -12 is on the same day, I want it to extract -12, not 12.

How I can extract the minus symbol?

foreach (char c in alternativeAirportPrice.Text)
{
    if (char.IsNumber(c))
    {
        string test = "-12 on same day";
        string alternativeAirportPriceValue = string.Join("", test.ToCharArray()
                                             .Where(x => char.IsDigit(x)).ToArray());
        return alternativeAirportPriceValue;
    }
}

Body:
Try this:

public IEnumerable<int> ExtractNumbers(string text)
{
    text += " ";
    var temp = string.Empty;
    for (var i = 0; i < text.Length; i++)
    {
        if (char.IsDigit(text[i]))
        {
            if ('-'.Equals(text[i - 1]))
            {
                temp += text[i - 1];
            }
            temp += text[i];
        }
        else if (temp.Length > 0)
        {
            yield return int.Parse(temp);
            temp = string.Empty;
        }
    }
}

This way you can handle cases where the string has multiple numbers in it, as observed by @Sir Rufo

The line:

text += " ";

is there to ensure the loop will hit the "else if" block when a number is in the last position of the string, e.g. "-12 on the same day 123456"


问:
Outer Join using multiple Google Sheets and the QUERY function
As an example, say I have the following sheets in the same workbook of a Google Doc:

```<code> SHEET1            |   SHEET2
 \   A  |  B       |   \   A   |   B   |   C   |   D
1|  ID  |Lookup    |  1| Lookup| Name  |Flavor | Color
2|  123 | 4445     |  2| 1234  |Whizzer|Cherry | Red
3|  234 | 4445     |  3| 4445  |Fizzer |Lemon  | Yellow
4|  124 | 1234     |  4| 9887  |Sizzle |Lime   | Blue
5|  767 | 1234     |
6|  555 | 9887     |
</code>```

Obviously, Google Docs isn't made with relational databases in mind, but I am trying to obtain results similar to the SQL query

```<code>SELECT
  SHEET1.ID,
  SHEET2.*
FROM
  SHEET1
    LEFT JOIN
      SHEET2
    ON SHEET1.Lookup = SHEET2.Lookup
</code>```

resulting in a table that looks like

```<code> SHEET3
 \   A    |   B   |   C   |   D   |   E
1|   ID   |Lookup | Name  |Flavor | Color
2|  123   | 4445  |Fizzer |Lemon  | Yellow
3|  234   | 4445  |Fizzer |Lemon  | Yellow
4|  124   | 1234  |Whizzer|Cherry | Red
5|  767   | 1234  |Whizzer|Cherry | Red
6|  555   | 9887  |Sizzle |Lime   | Blue
</code>```

but this is where I stand currently

```<code> SHEET3
 \   A    |   B   |   C   |   D   |   E
1|        |       |       |       |
2|  123   | 4445  | #N/A  |       |
3|  234   | 4445  |       |       |
4|  124   | 1234  |       |       |
5|  767   | 1234  |       |       |
6|  555   | 9887  |       |       |
</code>```

At the moment I have managed to use the QUERY function to grab the values from SHEET1 and have tried a few different QUERY functions in SHEET3!C1 in an attempt to "LEFT JOIN" the two sheets using this blog post as a reference. At this point, the two functions I am using are as follows.

SHEET3!A2=QUERY(SHEET1!A2:B20, "SELECT A,B")

SHEET3!C2=QUERY(SHEET2!A2:E20, "SELECT B,C,D WHERE A="""&B2&"""")

and hovering over the error in C2 reads "Query completed with an empty output". How can I join these sheets?

Additional references:

Google Docs syntax page for QUERY

答:
The following Add-on will provide all you need: Formulas by Top Contributors, by using both the build-in SQL join types and the MATRIX formula:

```<code>=MATRIX(SQLINNERJOIN(Sheet1!A1:B6,2,Sheet2!A1:D4,1, TRUE),,"3")
</code>```

It will yield the following outcome:

I've created an example file for you: SQL JOINS

Affiliation: as a Google Top Contributor I helped creating the Add-on

Body:
As an example, say I have the following sheets in the same workbook of a Google Doc:

 SHEET1            |   SHEET2
 \   A  |  B       |   \   A   |   B   |   C   |   D
1|  ID  |Lookup    |  1| Lookup| Name  |Flavor | Color
2|  123 | 4445     |  2| 1234  |Whizzer|Cherry | Red
3|  234 | 4445     |  3| 4445  |Fizzer |Lemon  | Yellow
4|  124 | 1234     |  4| 9887  |Sizzle |Lime   | Blue
5|  767 | 1234     |
6|  555 | 9887     |

Obviously, Google Docs isn't made with relational databases in mind, but I am trying to obtain results similar to the SQL query

SELECT
  SHEET1.ID,
  SHEET2.*
FROM
  SHEET1
    LEFT JOIN
      SHEET2
    ON SHEET1.Lookup = SHEET2.Lookup

resulting in a table that looks like

 SHEET3
 \   A    |   B   |   C   |   D   |   E
1|   ID   |Lookup | Name  |Flavor | Color
2|  123   | 4445  |Fizzer |Lemon  | Yellow
3|  234   | 4445  |Fizzer |Lemon  | Yellow
4|  124   | 1234  |Whizzer|Cherry | Red
5|  767   | 1234  |Whizzer|Cherry | Red
6|  555   | 9887  |Sizzle |Lime   | Blue

but this is where I stand currently

 SHEET3
 \   A    |   B   |   C   |   D   |   E
1|        |       |       |       |
2|  123   | 4445  | #N/A  |       |
3|  234   | 4445  |       |       |
4|  124   | 1234  |       |       |
5|  767   | 1234  |       |       |
6|  555   | 9887  |       |       |

At the moment I have managed to use the QUERY function to grab the values from SHEET1 and have tried a few different QUERY functions in SHEET3!C1 in an attempt to "LEFT JOIN" the two sheets using this blog post as a reference. At this point, the two functions I am using are as follows.

SHEET3!A2=QUERY(SHEET1!A2:B20, "SELECT A,B")

SHEET3!C2=QUERY(SHEET2!A2:E20, "SELECT B,C,D WHERE A="""&B2&"""")

and hovering over the error in C2 reads "Query completed with an empty output". How can I join these sheets?

Additional references:

Google Docs syntax page for QUERY

Body:
The following Add-on will provide all you need: Formulas by Top Contributors, by using both the build-in SQL join types and the MATRIX formula:

=MATRIX(SQLINNERJOIN(Sheet1!A1:B6,2,Sheet2!A1:D4,1, TRUE),,"3")

It will yield the following outcome:

I've created an example file for you: SQL JOINS

Affiliation: as a Google Top Contributor I helped creating the Add-on


问:
Dereferencing pointer C++
I just managed to write a global CBT hook in c++, usable with c#.
It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#.

I'm not able to dereference a pointer inside a struct pointed to by the lParam.

It looks like this: the lParam is a long Pointer to a CBT_CREATEWND struct, which in turn holds a member "lpcs", and a pointer to a CREATESTRUCT. This struct contains a member "x", which I want to read. I tried the following, but I get invalid values for x:

```<code>CREATESTRUCT str = *(LPCREATESTRUCT)(((LPCBT_CREATEWND)lParam)->lpcs);
int normal = str.x;
PostMessage(FindWindow(NULL, L"Process Watcher Window"), RegisterWindowMessage(L"ALEXX_SEINE_WNDMESSAGE_C"), wParam, normal);
</code>```

could someone please help me?

答:
Well I can't really speak towards the fine details of why you get invalid x values, but I would likely write this code differently:

```<code>// the way you had it, it was making a copy of the CREATESTRUCT and storing it in str
// this just uses a pointer
LPCREATESTRUCT str = ((LPCBT_CREATEWND)lParam)->lpcs;
// when you have a pointer, use -> to use a member
int normal = str->x;
</code>```

Since you said you are new to pointers, I'll explain -> a bit. When you write x->y, it is really the same as (*x).y but with nicer syntax.

Also a note of advice, while the casts in this code seem reasonable. In general, if you find that you are casting a lot, you probably are doing it either the hard way, or the wrong way. So make sure you take the time to understand any casts that you do.

ContentLicense: CC BY-SA 2.5

Title: Dereferencing pointer C++

Body:
I just managed to write a global CBT hook in c++, usable with c#.
It may sound stupid but my knowledge of pointers and dereferencing of those is very bad due to my work with c#.

I'm not able to dereference a pointer inside a struct pointed to by the lParam.

It looks like this: the lParam is a long Pointer to a CBT_CREATEWND struct, which in turn holds a member "lpcs", and a pointer to a CREATESTRUCT. This struct contains a member "x", which I want to read. I tried the following, but I get invalid values for x:

CREATESTRUCT str = *(LPCREATESTRUCT)(((LPCBT_CREATEWND)lParam)->lpcs);
int normal = str.x;
PostMessage(FindWindow(NULL, L"Process Watcher Window"), RegisterWindowMessage(L"ALEXX_SEINE_WNDMESSAGE_C"), wParam, normal);

could someone please help me?

Body:
Well I can't really speak towards the fine details of why you get invalid x values, but I would likely write this code differently:

// the way you had it, it was making a copy of the CREATESTRUCT and storing it in str
// this just uses a pointer
LPCREATESTRUCT str = ((LPCBT_CREATEWND)lParam)->lpcs;
// when you have a pointer, use -> to use a member
int normal = str->x;

Since you said you are new to pointers, I'll explain -> a bit. When you write x->y, it is really the same as (*x).y but with nicer syntax.

Also a note of advice, while the casts in this code seem reasonable. In general, if you find that you are casting a lot, you probably are doing it either the hard way, or the wrong way. So make sure you take the time to understand any casts that you do.


问:
UI Automation - How to distinguish image being displayed
I am very new to UI Automation and using Inspect tool (Inspect.exe Microsoft tool), so please explain.

I have a UWP application showing a list view, each list view item looks like this

The little circle in Image block above is the InteriorColor Image that is a solid color circle (black, gray or brown).

If I use Inspect.exe tool and hover over the little circle InteriorColor Image, it shows AutomationId = InteriorColorIcon which is the name I give it in my XAML:

```<code><Image x:Name="InteriorColorIcon" Source="{Binding InteriorColor, Converter={Static Resource InteriorColorImageConverter}"
</code>```

Above, bindable property InteriorColor is of string type and I use a converter to convert that string into the image of correct color.

So, if InteriorColor == "black", my converter returns resource image Black.png like:

```<code>return new BitmapImage(new Uri("ms-appx:///Black.png"));
</code>```

I would like to write UI Automation to detect if the little circle InteriorColorIcon image is the image of correct color.  If I hover over the image in Inspect.exe tool, it shows its AutomationId = InteriorColorIcon, that is great.

But how do I confirm that the image is Black, or Gray, or Brown?

Is there a way to add somehow a property to the image in XAML that Inspect tool can see and that I can use in my UI test to verify that the image showing is the correct image?

I assume that detecting color would be difficult, but is there a way to add a string property or something along these lines that could be used for this purpose?

答:
Always set the AutomationProperties.Name for an Image. This is necessary for your Image to be read correctly from a screen reader. The Automation Name being "InteriorColorIcon" is an accessibility bug in your app. It should be something more descriptive, such as "Black image" (or whatever a black image indicates). Similarly, you can set the AutomationProperties.AutomationId to something useful to your testing.

See Expose basic accessibility information

```<code><Image x:Name="InteriorColorIcon"
       AutomationProperties.Id="{Binding InteriorColor}"
       AutomationProperties.Name="{Binding InteriorColor}, Converter={Static Resource InteriorColorDescriptiveNameConverter}"
       Source="{Binding InteriorColor, Converter={Static Resource InteriorColorImageConverter}"
</code>```

If you want to check the actual image then that's more difficult. You'll need to screencapture the Image's location (see UIA_BoundingRectanglePropertyId) and then compare the pixels of the capture with your reference image.

Body:
I am very new to UI Automation and using Inspect tool (Inspect.exe Microsoft tool), so please explain.

I have a UWP application showing a list view, each list view item looks like this

The little circle in Image block above is the InteriorColor Image that is a solid color circle (black, gray or brown).

If I use Inspect.exe tool and hover over the little circle InteriorColor Image, it shows AutomationId = InteriorColorIcon which is the name I give it in my XAML:

<Image x:Name="InteriorColorIcon" Source="{Binding InteriorColor, Converter={Static Resource InteriorColorImageConverter}"

Above, bindable property InteriorColor is of string type and I use a converter to convert that string into the image of correct color.

So, if InteriorColor == "black", my converter returns resource image Black.png like:

return new BitmapImage(new Uri("ms-appx:///Black.png"));

I would like to write UI Automation to detect if the little circle InteriorColorIcon image is the image of correct color.  If I hover over the image in Inspect.exe tool, it shows its AutomationId = InteriorColorIcon, that is great.

But how do I confirm that the image is Black, or Gray, or Brown?

Is there a way to add somehow a property to the image in XAML that Inspect tool can see and that I can use in my UI test to verify that the image showing is the correct image?

I assume that detecting color would be difficult, but is there a way to add a string property or something along these lines that could be used for this purpose?

Body:
Always set the AutomationProperties.Name for an Image. This is necessary for your Image to be read correctly from a screen reader. The Automation Name being "InteriorColorIcon" is an accessibility bug in your app. It should be something more descriptive, such as "Black image" (or whatever a black image indicates). Similarly, you can set the AutomationProperties.AutomationId to something useful to your testing.

See Expose basic accessibility information

<Image x:Name="InteriorColorIcon"
       AutomationProperties.Id="{Binding InteriorColor}"
       AutomationProperties.Name="{Binding InteriorColor}, Converter={Static Resource InteriorColorDescriptiveNameConverter}"
       Source="{Binding InteriorColor, Converter={Static Resource InteriorColorImageConverter}"

If you want to check the actual image then that's more difficult. You'll need to screencapture the Image's location (see UIA_BoundingRectanglePropertyId) and then compare the pixels of the capture with your reference image.


问:
Ionic 2 App Conflict "Public" vs "Public Static"
I'm an amateur to this thing, tryin' to code an app and I found conflictin' parts on my code. I don't have a clean code just makin' things work, I tried it out like this:

```<code>    constructor(platform: Platform, public nativeStorage: NativeStorage) {
    platform.ready().then(() => {
    this.nativeStorage.getItem('NoTaleDB').then(function (json) {
    if (json) {
      GlobalVariables.novelList = JSON.parse(json);
    }
    });
    });
    }

    public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}
</code>```

And got this error:

```<code>Property 'nativeStorage' does not exist on type 'typeof StorageService'
</code>```

When I modify the function into this:

```<code>public save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}
</code>```

It finds the nativeStorage but I get this error instead from Pages and the service itself:

```<code>Property 'save' does not exist on type 'typeof StorageService'.
</code>```

I've been tryin' to finish this app for a long time now but ends up only tryin' to fix bugs. Please, provide a simple solution, something a newbie can understand. Thanks. <3

答:
Assuming that you want the function body for this to function:

```<code>public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
}
</code>```

this is not available for static member as static members exit on the class and not the instance (the thing referenced by this).

Fixed code

Has to be :

```<code>public save() {
        this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
    }
</code>```

Now you are getting the error:

Property 'save' does not exist on type 'typeof StorageService'.

You are calling StorageService.save. This is wrong. You should be calling save on an instance e.g.

```<code>new StoargeService(pass in the stuff it needs).save(); // Works now
</code>```

More

Some docs on TypeScript classes : https://basarat.gitbooks.io/typescript/content/docs/classes.html

Body:
I'm an amateur to this thing, tryin' to code an app and I found conflictin' parts on my code. I don't have a clean code just makin' things work, I tried it out like this:

    constructor(platform: Platform, public nativeStorage: NativeStorage) {
    platform.ready().then(() => {
    this.nativeStorage.getItem('NoTaleDB').then(function (json) {
    if (json) {
      GlobalVariables.novelList = JSON.parse(json);
    }
    });
    });
    }

    public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}

And got this error:

Property 'nativeStorage' does not exist on type 'typeof StorageService'

When I modify the function into this:

public save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {});
}

It finds the nativeStorage but I get this error instead from Pages and the service itself:

Property 'save' does not exist on type 'typeof StorageService'.

I've been tryin' to finish this app for a long time now but ends up only tryin' to fix bugs. Please, provide a simple solution, something a newbie can understand. Thanks. <3

Body:
Assuming that you want the function body for this to function:

public static save() {
    this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
}

this is not available for static member as static members exit on the class and not the instance (the thing referenced by this).

Fixed code

Has to be :

public save() {
        this.nativeStorage.setItem('NoTaleDB', JSON.stringify(GlobalVariables.novelList)).then(() => {}, () => {})
    }

Now you are getting the error:

Property 'save' does not exist on type 'typeof StorageService'.

You are calling StorageService.save. This is wrong. You should be calling save on an instance e.g.

new StoargeService(pass in the stuff it needs).save(); // Works now

More

Some docs on TypeScript classes : https://basarat.gitbooks.io/typescript/content/docs/classes.html


问:
Installing migrations from engine won't work
I created a new engine in Rails 3.1.3 and apparently there's that rake task that copies over all migrations. I tried following rake abc:install:migrations which threw:

```<code>rake aborted!
Don't know how to build task 'abc:install:migrations'

(See full trace by running task with --trace)
</code>```

I also tried rake abc_engine:install:migrations with the same result.

Then I read bundle exec rake railties:install:migrations or bundle exec rake railties:install:migrations FROM=abc_engine should do the trick too but no success. Nothing was copied even though no error was thrown.

My migrations are located in db/migrate/ within the engine folder and I ran all commands above from spec/dummy/

Does anyone know how to use this new rake task in order to copy migrations from the engine?

答:
If the app you're mounting the engine to doesn't already have ActiveRecord (i.e. you're introducing ActiveRecord to your host app for the first time by mounting the engine), you can get this error as well. Specifically, you'll get this error if you don't have require "active_record/railtie" in your application.rb, or if it's commented out. That line is what enables the rake railties:install:migrations task, which is defined here. rake railties:install:migrations is, in turn, called by the rake abc_engine:install:migrations task here.

Tl;dr: try adding require "active_record/railtie" to your application.rb if it's not already there.

Body:
I created a new engine in Rails 3.1.3 and apparently there's that rake task that copies over all migrations. I tried following rake abc:install:migrations which threw:

rake aborted!
Don't know how to build task 'abc:install:migrations'

(See full trace by running task with --trace)

I also tried rake abc_engine:install:migrations with the same result.

Then I read bundle exec rake railties:install:migrations or bundle exec rake railties:install:migrations FROM=abc_engine should do the trick too but no success. Nothing was copied even though no error was thrown.

My migrations are located in db/migrate/ within the engine folder and I ran all commands above from spec/dummy/

Does anyone know how to use this new rake task in order to copy migrations from the engine?


问:
Logging .net core 2 write in same console from two project
I need to write in the same console from two or more project and so I rolling all content from the console in a text file. Is it possible?

I need this because I would like to know what happened concurrently in more project.

what is the best approach to managing the log in a business context?

I use .net core 2 with logging built-in

Is it possible use another tool for to do this? Some Extention.
What is the

BR

答:
Your question isn't entirely clear. This has little to do with how many projects are at play and more to do with what kind of projects those are. In particular console applications (of which ASP.NET Core projects are) cannot write to the same console because each runs in their own console window. That's fairly logical and understandable.

However, if you're talking about class library projects and such, those can easily output to the same console window as the console app that's referencing them. In fact, that just happens naturally. If you pass in a console logger, the library methods will end up logging to whatever is the active console.

As a result, depending on the project types, what you're talking about either happens naturally or is totally impossible. Given that you're here asking this question in the first place, I have to assume you're talking about multiple console projects; in which case, what you want is not possible. Plain and simple.

However, if your ultimate goal is to dump to a text file, then utilize a logger that actually writes to the text file. Theoretically, if you feed each project's logger the same text file, you can merge all the output together. Logistically, you may have concurrency issues to deal with as well as file locks, so I can't say for sure that that approach will just work. For the best chance, I'd recommend using an actual logging solution that supports writing to a text file, rather than trying to roll your own text file logger. Regardless, that's your best and pretty much only option.


问:
Prestashop module development - How can I call a controller initMethod at module installation?
In controllers/front I created a controller named abandonedCarts:

```<code>class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{

public function __construct()
{
    parent::__construct();
    $this->context = Context::getContext();
    $this->store_debug('Controller - __construct');
}

public function initContent()
{
    parent::initContent();
    $this->store_debug('Controller - init');
}

}
</code>```

where store_debug is a function that simply logs on the db something (just for check).
Thanks to this I know that when I call the controller from URL in this way

```<code>site/index.php?fc=module&module=olyo&controller=abandonedCarts
</code>```

the construct and init methods are being called, but what I need is the controller being called when the module is installed (or at its first start).

In the main file I also put in the constructor this line:

```<code>$this->controllers = array('abandonedCarts');
</code>```

But I'm not sure I even need it

答:
You can include the Controller and just call the object method like following :

```<code><?php
class MyModule extends Module {

  public install(){
     $file = _PS_MODULE_DIR_.'/'.$this->name.'/controllers/front/default.php';
     require_once $file;
     $obj = new ObjectController();
     $obj->my_super_method();
     return true;
  }
}
</code>```

You don't need the controller parameter. You shall stick to what is include by default with Prestashop's Generator here : https://validator.prestashop.com/

Body:
In controllers/front I created a controller named abandonedCarts:

class <moduleName>AbandonedCartsModuleFrontController extends ModuleFrontController
{

public function __construct()
{
    parent::__construct();
    $this->context = Context::getContext();
    $this->store_debug('Controller - __construct');
}

public function initContent()
{
    parent::initContent();
    $this->store_debug('Controller - init');
}

}

where store_debug is a function that simply logs on the db something (just for check).
Thanks to this I know that when I call the controller from URL in this way

site/index.php?fc=module&module=olyo&controller=abandonedCarts

the construct and init methods are being called, but what I need is the controller being called when the module is installed (or at its first start).

In the main file I also put in the constructor this line:

$this->controllers = array('abandonedCarts');

But I'm not sure I even need it

Body:
You can include the Controller and just call the object method like following :

<?php
class MyModule extends Module {

  public install(){
     $file = _PS_MODULE_DIR_.'/'.$this->name.'/controllers/front/default.php';
     require_once $file;
     $obj = new ObjectController();
     $obj->my_super_method();
     return true;
  }
}

You don't need the controller parameter. You shall stick to what is include by default with Prestashop's Generator here : https://validator.prestashop.com/


问:
gdb on OSX unable to recognize 32bit unstripped ELF
This gdb was installed via Homebrew on my OSX.

I wonder why gdb doesn't work on this file(I was playing pwn)on my OSX, while I can run it on Kali linux through VirtualBox.
I saw some people mentioned "Apple version gdb", is that the problem?

And how do I solve this?

I searched for answer quite a while and even asked my proffessor, please give me a hand!

```<code>➜ file bof
bof: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV),
dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24,
BuildID[sha1]=ed643dfe8d026b7238d3033b0d0bcc499504f273, not stripped

➜ gdb bof
GNU gdb (GDB) 8.0
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
.
.
.
"/Users/me/Desktop/test/bof": not in executable format: File     format not recognized
(gdb)
</code>```

答:
This gdb was installed via Homebrew on my OSX.

...

bof: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV),
  dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24,

There are many ways to configure gdb.  The default -- if you don't pass any special options to configure -- is to configure in just what is needed for the host platform.

In this case, probably what has happened is that your gdb is configured for OSX -- meaning Mach-O and not ELF -- and so gdb can't read ELF files.  You can test this theory by typing set gnutarget <TAB> <TAB> at the gdb prompt (the tabs will cause completion, which is the only way I know of to list what was compiled in here).  Alternatively, you can try show configuration, though that just says what options were passed to configure, and so it needs interpretation.

One simple way to get out of this is to reconfigure with --enable-targets=all.  Then gdb will be able to read ELF files and other things as well.

Body:
This gdb was installed via Homebrew on my OSX.

I wonder why gdb doesn't work on this file(I was playing pwn)on my OSX, while I can run it on Kali linux through VirtualBox.
I saw some people mentioned "Apple version gdb", is that the problem?

And how do I solve this?

I searched for answer quite a while and even asked my proffessor, please give me a hand!

➜ file bof
bof: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV),
dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24,
BuildID[sha1]=ed643dfe8d026b7238d3033b0d0bcc499504f273, not stripped

➜ gdb bof
GNU gdb (GDB) 8.0
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
.
.
.
"/Users/me/Desktop/test/bof": not in executable format: File     format not recognized
(gdb)


问:
nuxt can I manually show the loading indicator?
I would like to use the loading indicator that is displayed in nuxt when I navigate between routes for all my ajax calls.

Can I somehow trigger the indicator to show?

答:
```<code>methods: {
  async onSubmit() {
    try {
      this.$root.$loading.start();
      const result = await someAsyncMethod();
    } catch (err) {
      // this.$toast.error(err.message);
    } finally {
      this.$root.$loading.finish();
    }
},
</code>```

<p>This could be a typical async method using the default loading indicator. </p>

Body:
methods: {
  async onSubmit() {
    try {
      this.$root.$loading.start();
      const result = await someAsyncMethod();
    } catch (err) {
      // this.$toast.error(err.message);
    } finally {
      this.$root.$loading.finish();
    }
},

This could be a typical async method using the default loading indicator.


问:
How can I combine/split properties with AutoMapper?
we're using Automapper (http://automapper.codeplex.com/) to map between entities and dto's. We have a situation where one property on an entity corresponds to three different properties on the dto, and we need to write some custom logic to do the mapping. Anyone know how we can do that? (We need to map both ways, from entity and from dto).

I notice that AutoMapper supports custom resolvers to do custom mapping logic, but as far as I can tell from the documentation, they only allow you to map a single property to another single property.

Thx

答: You can create a custom type converter.  It allows you to define a converter for an entire type, not just a single property.</p>


问:
Finding which code segment is faster than the other
Say that we have two C++ code segments, for doing the same task. How can we determine which code will run faster?

As an example lets say there is this global array "some_struct_type numbers[]". Inside a function, I can read a location of this array in two ways(I do not want to alter the content of the array)

some_struct_type val = numbers[i];

some_struct_type* val = &numbers[i]

I assume the second one is faster. but I can't measure the time to make sure because it will be a negligible difference.

So in this type of a situation, how do I figure out which code segment runs faster? Is there a way to compile a single line of code or set of lines and view
how many lines of assembly instructions are there?

I would appreciate your thoughts on this matter.

答:
The basics are to run the piece of code so many times that it takes a few seconds at least to complete, and measure the time.

But it's hard, very hard, to get any meaningful figures this way, for many reasons:

Todays compilers are very good at optimizing code, but the optimizations depend on the context. It often does not make sense to look at a single line and try to optimize it. When the same line appears in a different context, the optimizations applied may be different.

Short pieces of code can be much faster than the surrounding looping code.

Not only the compiler makes optimizations, the processor has a cache, an instruction pipeline, and tries to predict branching code. A value which has been read before will be read much faster the next time, for example.

...

Because of this, it's usually better to leave the code in its place in your program, and use a profiling tool to see which parts of your code use the most processing resources. Then, you can change these parts and profile again.

While writing new code, prefer readable code to seemingly optimal code. Choose the right algorithm, this also depends on your input sizes. For example, insertion sort can be faster than quicksort, if the input is very small. But don't write your own sorting code, if your input is not special, use the libraries available in general. And don't optimize prematurely.


问:
service cannot be cast to android.app.Activity
I am trying to access a editText and a Button in a Service.
I've seen this answer and this answer, and tried to merge and work out, but no gain. What am I missing here? I have seen other similar answers too and been trying to get it done from last 2 days but all in vain. Any other way of accomplishing it will also be welcome.

Here is the relevant code:
MainActivity.java

```<code>btn_start.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        });
</code>```

MyService.java

```<code>        Context context = MyService.this;
        Activity activity = (Activity) context;
        Button stopButton = activity.findViewById(R.id.btn_stop);
        EditText editTextUsername = activity.findViewById(R.id.edit_name);
</code>```

AndroidManifest.xml

```<code>        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
        </service>
</code>```

But I get this error:
LOGCAT

11-14 02:55:07.835 5906-5906/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.nwagh.myapplication, PID: 5906
                                                   java.lang.RuntimeException: Unable to start service
  com.example.nwagh.myapplication.MyService@32189af with Intent {
  cmp=com.example.nwagh.myapplication/.MyService }:
  java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3060)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                    Caused by: java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at com.example.nwagh.myapplication.MyService.onStartCommand(MyService.java:68)
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3043)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)  11-14
  02:55:07.844 5906-5906/? E/MQSEventManagerDelegate: failed to get
  MQSService.

Here is the complete code if you need any more reference.

答:
You are barking up the wrong tree ;-) Your Service shouldn't know anything about your UI, nor should it want to muck around with it. If you want to change the UI from your Service then you need to delegate that task to the Activity. Activity is responsible for the UI. There are several well documented approaches you can use:

Activity binds to Service and Service executes a callback on the Activity

Service sends a broadcast Intent and Activity registers a listener that reacts to the Intent when it is broadcast

Use an Event Bus implementation

Body:
I am trying to access a editText and a Button in a Service.
I've seen this answer and this answer, and tried to merge and work out, but no gain. What am I missing here? I have seen other similar answers too and been trying to get it done from last 2 days but all in vain. Any other way of accomplishing it will also be welcome.

Here is the relevant code:
MainActivity.java

btn_start.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View view) {
                startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

MyService.java

        Context context = MyService.this;
        Activity activity = (Activity) context;
        Button stopButton = activity.findViewById(R.id.btn_stop);
        EditText editTextUsername = activity.findViewById(R.id.edit_name);

AndroidManifest.xml

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">
        </service>

But I get this error:
LOGCAT

11-14 02:55:07.835 5906-5906/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.nwagh.myapplication, PID: 5906
                                                   java.lang.RuntimeException: Unable to start service
  com.example.nwagh.myapplication.MyService@32189af with Intent {
  cmp=com.example.nwagh.myapplication/.MyService }:
  java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3060)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                    Caused by: java.lang.ClassCastException:
  com.example.nwagh.myapplication.MyService cannot be cast to
  android.app.Activity
                                                       at com.example.nwagh.myapplication.MyService.onStartCommand(MyService.java:68)
                                                       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3043)
                                                       at android.app.ActivityThread.access$2300(ActivityThread.java:153)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)  11-14
  02:55:07.844 5906-5906/? E/MQSEventManagerDelegate: failed to get
  MQSService.

Here is the complete code if you need any more reference.


问:
Is it possible to assign variable to default value to select form in Laravel
So my question is, I have a form and I want this form to have default value and thats why I assigned $s variable. This variable comes from Controller, but It always gives error ;

(2/2) ErrorException Undefined variable: s (View: C:\xampp\htdocs\X-GOTL\resources\views\actions\activity.blade.php)

I know that this cant work because in the beginning there is no default value because its not sent by controller yet. I tried some ifs to fix it but anyways its not working. Also this $s value is equals to number of selected value in this form. Any ideas how I can fix this problem?

{!! Form::select('number', ['1' => 'Koşuya Çıkmak', '2' => 'Yoga
   Yapmak'], $s) !!}

This is code in controller.

```<code>    $activity = $request->number;

    $user_stat = Auth::user()->stat;
    $job_user = Auth::user()->stat;

    $userInfo = Auth::user();
    $id = $userInfo->id;
    $user = User::find($userInfo->id);

    if($activity == 1){

        $s = $request->number;

        $user_stat->str = Auth::user()->stat->str + 4;
        $user_stat->dex = Auth::user()->stat->dex + 4;

        $job_user->save();

        return redirect('/activity')->with('stat', '4 Güç ve 4 Beceri Kazandın!')->with(compact('s'));

    }
    elseif($activity == 2){

        $s = $request->number;

        $user_stat->str = Auth::user()->stat->str + 4;
        $user_stat->int = Auth::user()->stat->int + 4;

        $job_user->save();

        return redirect('/activity')->with('stat', '4 Güç ve 4 Zeka Kazandın!')
            ->with(compact('s'));

    }
</code>```

答:
The answer was so easy guys.. Just to add withInput()

return redirect('/activity')->with('stat', 'xxx')->withInput();

Body:
So my question is, I have a form and I want this form to have default value and thats why I assigned $s variable. This variable comes from Controller, but It always gives error ;

(2/2) ErrorException Undefined variable: s (View: C:\xampp\htdocs\X-GOTL\resources\views\actions\activity.blade.php)

I know that this cant work because in the beginning there is no default value because its not sent by controller yet. I tried some ifs to fix it but anyways its not working. Also this $s value is equals to number of selected value in this form. Any ideas how I can fix this problem?

{!! Form::select('number', ['1' => 'Koşuya Çıkmak', '2' => 'Yoga
   Yapmak'], $s) !!}

This is code in controller.

    $activity = $request->number;

    $user_stat = Auth::user()->stat;
    $job_user = Auth::user()->stat;

    $userInfo = Auth::user();
    $id = $userInfo->id;
    $user = User::find($userInfo->id);

    if($activity == 1){

        $s = $request->number;

        $user_stat->str = Auth::user()->stat->str + 4;
        $user_stat->dex = Auth::user()->stat->dex + 4;

        $job_user->save();

        return redirect('/activity')->with('stat', '4 Güç ve 4 Beceri Kazandın!')->with(compact('s'));

    }
    elseif($activity == 2){

        $s = $request->number;

        $user_stat->str = Auth::user()->stat->str + 4;
        $user_stat->int = Auth::user()->stat->int + 4;

        $job_user->save();

        return redirect('/activity')->with('stat', '4 Güç ve 4 Zeka Kazandın!')
            ->with(compact('s'));

    }


问:
Case insensitive comparison in Contains under nUnit
I'm trying to assert that a list contains a certain string. Since I'd need the condition to be evaluated case insensitively, I used a workaround (something along this blog post).

However, I'd like to know why there seems not to be a way to make the Assert.Contains method perform the comparison without regard of case sensitivity. Or is there a way to do that? (When I googled it, I only got hits on constraints for the Assert.That method on the official page for nUnit.)

答:
In NUnit 3, the following syntax can be used:

Assert.That(new[] {"red", "green", "blue"}, Does.Contain("RED").IgnoreCase);
```


问:
COPY . . command in Dockerfile for ASP.NET
The Visual Studio tooling for Docker creates a Dockerfile for ASP.NET projects containing a COPY . . command as below:

```<code>WORKDIR /src
COPY *.sln ./
...
COPY . .
</code>```

From what I've read, the <src> parameter is relative to the context, so isn't affected by the WORKDIR /src command. The <dest> however is relative to the WORKDIR so will be pointing at /src.

Is this command just bringing over the remaining files from the root for packaging (docker-compose.yml, .dockerignore, etc.)? If so, then why is this done ahead of the RUN dotnet build... command?

Full Dockerfile below:

```<code>FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY *.sln ./
COPY MyProject/MyProject.csproj MyProject/
RUN dotnet restore
COPY . . # The line mentioned above
WORKDIR /src/MyProject
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "MyProject.dll"]
</code>```

答:
The COPY . . copies the entire project, recursively into the container for the build.

The reason for the separation of the first 2 COPY commands with dotnet restore and then the complete COPY . . with dotnet build is a Docker caching trick to speed up container image builds. It is done this way so the project dependencies don't need to be reinstalled every time a code change is made.

Docker images are built in layers. Docker compares the contents and instructions that would make up the each new layer to previous builds. If they match the SHA256 checksum for the existing layer, the build step for that layer can be skipped.

Code changes a lot more than dependencies, and dependencies are usually fetched from a slow(ish) network now. If you copy the code after the dependency installs are completed then you don't bust the cached dependency layer for every other change.

This is a common theme across many languages with a dependency manager. Go, Python, Node.js etc. The Node.js equivalent does the package.json and package-lock.json before the rest of the application contents:

```<code>WORKDIR /app
COPY package.json package-lock.json /app/
RUN npm install
COPY . /app/
CMD ["node", "app/index.js"]
</code>```

Body:
The Visual Studio tooling for Docker creates a Dockerfile for ASP.NET projects containing a COPY . . command as below:

WORKDIR /src
COPY *.sln ./
...
COPY . .

From what I've read, the <src> parameter is relative to the context, so isn't affected by the WORKDIR /src command. The <dest> however is relative to the WORKDIR so will be pointing at /src.

Is this command just bringing over the remaining files from the root for packaging (docker-compose.yml, .dockerignore, etc.)? If so, then why is this done ahead of the RUN dotnet build... command?

Full Dockerfile below:

FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY *.sln ./
COPY MyProject/MyProject.csproj MyProject/
RUN dotnet restore
COPY . . # The line mentioned above
WORKDIR /src/MyProject
RUN dotnet build -c Release -o /app

FROM build AS publish
RUN dotnet publish -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "MyProject.dll"]

Body:
The COPY . . copies the entire project, recursively into the container for the build.

The reason for the separation of the first 2 COPY commands with dotnet restore and then the complete COPY . . with dotnet build is a Docker caching trick to speed up container image builds. It is done this way so the project dependencies don't need to be reinstalled every time a code change is made.

Docker images are built in layers. Docker compares the contents and instructions that would make up the each new layer to previous builds. If they match the SHA256 checksum for the existing layer, the build step for that layer can be skipped.

Code changes a lot more than dependencies, and dependencies are usually fetched from a slow(ish) network now. If you copy the code after the dependency installs are completed then you don't bust the cached dependency layer for every other change.

This is a common theme across many languages with a dependency manager. Go, Python, Node.js etc. The Node.js equivalent does the package.json and package-lock.json before the rest of the application contents:

WORKDIR /app
COPY package.json package-lock.json /app/
RUN npm install
COPY . /app/
CMD ["node", "app/index.js"]


问:
What's the ugliest code you were forced to write by outside limitations?
What is the ugliest code that you wrote - not because you didn't know better, but because of limitations of the software, the hardware or the company policy?

Because of unusual choices in database layouts and programming languages, I once built a C program that read in a SQL database structure and generated another C program that'd read that database and back it up into a file, or copy it into a second database that shared more or less the same columns. It was a monster clunky code generator.

答:
I have my pride and do not write extreme ugly code (although the definition of ugly changes with experience). My boss pays me to write code and he expects it to be good.

Sometimes you have to write hacks. But you always have to claim the right to fix these later on else you will be faced with the concequences later on.

OwnerDisplayName: Gamecat


问:
How do I make my Perl scripts act like normal programs on Windows?
I want my Perl scripts to behave just like any other executable (*.exe file).

When I double-click on myscript.pl I want it to execute instead of opening in a text editor.

I want to run myscript.pl instead of perl myscript.pl.

I really want to run myscript instead of myscript.pl.

I want to run program | myscript instead of program | perl myscript.pl.

I want to be able to run my script via drag & drop.

There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.

Related questions:

How do I make Perl scripts recognize parameters in the Win32 cmd console?

Running a perl script on windows without extension

Perl execution from command line question

How can I read piped input in Perl on Windows?

Perl on Windows, file associations and I/O redirection

How do I create drag-and-drop Strawberry Perl programs?

答:
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.

Associate *.pl files with perl

Run the following commands at a shell prompt:

```<code>assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
</code>```

Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.

Default install locations are:

ActivePerl: C:\Perl

Strawberry Perl: C:\Strawberry

Add .PL to your PATHEXT environment variable.

This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.

You can set it for the current cmd session

```<code>set PATHEXT=%PATHEXT%;.PL
</code>```

To set it permanently (under Windows Vista or Windows 7)

```<code>setx PATHEXT %PATHEXT%;.PL
</code>```

Under Windows XP you have to use the GUI:

Right-click My Computer, and then click Properties.

Click the Advanced tab.

Click Environment variables.

Select PATHEXT, then click Edit.

Append ;.PL to the current value.

Make I/O redirection work

I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.

Start Registry Editor.

Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

On the Edit menu, click Add Value, and then add the following registry value:

Value name: InheritConsoleHandles

Data type: REG_DWORD

Radix: Decimal

Value data: 1

Quit Registry Editor.

Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.

See also:

STDIN/STDOUT Redirection May Not Work If Started from a File Association

Perl Scripts on Windows 10 run from Explorer but not Command Prompt

If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.

Add a drop handler

Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:

```<code>use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
    "DropHandler/" =>  {
        "/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};
</code>```

Body:
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.

Associate *.pl files with perl

Run the following commands at a shell prompt:

assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*

Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.

Default install locations are:

ActivePerl: C:\Perl

Strawberry Perl: C:\Strawberry

Add .PL to your PATHEXT environment variable.

This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.

You can set it for the current cmd session

set PATHEXT=%PATHEXT%;.PL

To set it permanently (under Windows Vista or Windows 7)

setx PATHEXT %PATHEXT%;.PL

Under Windows XP you have to use the GUI:

Right-click My Computer, and then click Properties.

Click the Advanced tab.

Click Environment variables.

Select PATHEXT, then click Edit.

Append ;.PL to the current value.

Make I/O redirection work

I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.

Start Registry Editor.

Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer

On the Edit menu, click Add Value, and then add the following registry value:

Value name: InheritConsoleHandles

Data type: REG_DWORD

Radix: Decimal

Value data: 1

Quit Registry Editor.

Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.

See also:

STDIN/STDOUT Redirection May Not Work If Started from a File Association

Perl Scripts on Windows 10 run from Explorer but not Command Prompt

If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.

Add a drop handler

Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:

use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
    "DropHandler/" =>  {
        "/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};


问:
How to use the comparator method in Rhino Java environment
I am trying to override the compareTo() method for my class so as to sort the instances based on their dates.

When I run this program, I get incorrect results.
I am writing in Javascript because I am working in a Rhino environment. I am not sure if it helps, but I am using the execute-rhino-online online editor to write the code:

```<code>var arrayList = java.util.ArrayList();
var Object1 = new java.util.HashMap();
var Object2 = new java.util.HashMap();
var Object3 = new java.util.HashMap();
Object1.put("Job Number", "222");
Object1.put("Date", java.util.Date(2017, 10, 11));
Object2.put("Job Number", "333");
Object2.put("Date", java.util.Date(2017, 10, 13));
Object3.put("Job Number", "111");
Object3.put("Date", java.util.Date(2017, 10, 10));
arrayList.add(Object1);
arrayList.add(Object2);
arrayList.add(Object3);

var comp = java.util.Comparator({
  compareTo: function(o1, o2) {
    var d1 = o1.get("Date");
    print(d1);
    var d2 = o2.get("Date");
    if (d1.before(d2)) {
      return -1;
    } else if (d1.after(d2)) {
      return 1;
    } else {
      return 0;
    }
  }
});
java.util.Collections.sort(arrayList, comp);
print(arrayList);
</code>```

答:
It's because you're overriding a non existent method

Change compareTo: to compare:

Check the javadocs for https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

Body:
I am trying to override the compareTo() method for my class so as to sort the instances based on their dates.

When I run this program, I get incorrect results.
I am writing in Javascript because I am working in a Rhino environment. I am not sure if it helps, but I am using the execute-rhino-online online editor to write the code:

var arrayList = java.util.ArrayList();
var Object1 = new java.util.HashMap();
var Object2 = new java.util.HashMap();
var Object3 = new java.util.HashMap();
Object1.put("Job Number", "222");
Object1.put("Date", java.util.Date(2017, 10, 11));
Object2.put("Job Number", "333");
Object2.put("Date", java.util.Date(2017, 10, 13));
Object3.put("Job Number", "111");
Object3.put("Date", java.util.Date(2017, 10, 10));
arrayList.add(Object1);
arrayList.add(Object2);
arrayList.add(Object3);

var comp = java.util.Comparator({
  compareTo: function(o1, o2) {
    var d1 = o1.get("Date");
    print(d1);
    var d2 = o2.get("Date");
    if (d1.before(d2)) {
      return -1;
    } else if (d1.after(d2)) {
      return 1;
    } else {
      return 0;
    }
  }
});
java.util.Collections.sort(arrayList, comp);
print(arrayList);


问:
Obtaining the index of the top visible element of a list of items with ui-grid
Is it possible to obtain the index of the top element of a ui-grid that is currently visible/displayed by the client/browser?

For example, take a look at (an edited) ui-grid's infinite scrolling example  in this plunkr example. Is it possible to obtain that that top index somehow?

This would be the app.js code, which is exactly the same as the infinite-scroll example:

```<code>var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.infiniteScroll']);

app.controller('MainCtrl', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
  $scope.gridOptions = {
    infiniteScrollRowsFromEnd: 40,
    infiniteScrollUp: true,
    infiniteScrollDown: true,
    columnDefs: [
      { name:'id'},
      { name:'name' },
      { name:'age' }
    ],
    data: 'data',
    onRegisterApi: function(gridApi){
      gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown);
      gridApi.infiniteScroll.on.needLoadMoreDataTop($scope, $scope.getDataUp);
      $scope.gridApi = gridApi;
    }
  };

  $scope.data = [];

  $scope.firstPage = 2;
  $scope.lastPage = 2;

  $scope.getFirstData = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      var newData = $scope.getPage(response.data, $scope.lastPage);
      $scope.data = $scope.data.concat(newData);
    });
  };

  $scope.getDataDown = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      $scope.lastPage++;
      var newData = $scope.getPage(response.data, $scope.lastPage);
      $scope.gridApi.infiniteScroll.saveScrollPercentage();
      $scope.data = $scope.data.concat(newData);
      return $scope.gridApi.infiniteScroll.dataLoaded($scope.firstPage > 0, $scope.lastPage < 4).then(function() {$scope.checkDataLength('up');});
    })
    .catch(function(error) {
      return $scope.gridApi.infiniteScroll.dataLoaded();
    });
  };

  $scope.getDataUp = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      $scope.firstPage--;
      var newData = $scope.getPage(response.data, $scope.firstPage);
      $scope.gridApi.infiniteScroll.saveScrollPercentage();
      $scope.data = newData.concat($scope.data);
      return $scope.gridApi.infiniteScroll.dataLoaded($scope.firstPage > 0, $scope.lastPage < 4).then(function() {$scope.checkDataLength('down');});
    })
    .catch(function(error) {
      return $scope.gridApi.infiniteScroll.dataLoaded();
    });
  };

  $scope.getPage = function(data, page) {
    var res = [];
    for (var i = (page * 100); i < (page + 1) * 100 && i < data.length; ++i) {
      res.push(data[i]);
    }
    return res;
  };

  $scope.checkDataLength = function( discardDirection) {
    // work out whether we need to discard a page, if so discard from the direction passed in
    if( $scope.lastPage - $scope.firstPage > 3 ){
      // we want to remove a page
      $scope.gridApi.infiniteScroll.saveScrollPercentage();

      if( discardDirection === 'up' ){
        $scope.data = $scope.data.slice(100);
        $scope.firstPage++;
        $timeout(function() {
          // wait for grid to ingest data changes
          $scope.gridApi.infiniteScroll.dataRemovedTop($scope.firstPage > 0, $scope.lastPage < 4);
        });
      } else {
        $scope.data = $scope.data.slice(0, 400);
        $scope.lastPage--;
        $timeout(function() {
          // wait for grid to ingest data changes
          $scope.gridApi.infiniteScroll.dataRemovedBottom($scope.firstPage > 0, $scope.lastPage < 4);
        });
      }
    }
  };

  $scope.reset = function() {
    $scope.firstPage = 2;
    $scope.lastPage = 2;

    // turn off the infinite scroll handling up and down - hopefully this won't be needed after @swalters scrolling changes
    $scope.gridApi.infiniteScroll.setScrollDirections( false, false );
    $scope.data = [];

    $scope.getFirstData().then(function(){
      $timeout(function() {
        // timeout needed to allow digest cycle to complete,and grid to finish ingesting the data
        $scope.gridApi.infiniteScroll.resetScroll( $scope.firstPage > 0, $scope.lastPage < 4 );
      });
    });
  };

  $scope.getFirstData().then(function(){
    $timeout(function() {
      // timeout needed to allow digest cycle to complete,and grid to finish ingesting the data
      // you need to call resetData once you've loaded your data if you want to enable scroll up,
      // it adjusts the scroll position down one pixel so that we can generate scroll up events
      $scope.gridApi.infiniteScroll.resetScroll( $scope.firstPage > 0, $scope.lastPage < 4 );
    });
  });

}]);
</code>```

HTML

```<code><!doctype html>
<html ng-app="app">
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-touch.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
    <script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
    <script src="http://ui-grid.info/release/ui-grid.js"></script>
    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">
  </head>
  <body>

<div ng-controller="MainCtrl">
  <button id="reset" class="button" ng-click="reset()">Reset</button>
  <span>     First page: {{ firstPage }}     Last page: {{ lastPage }}      data.length: {{ data.length }} </span>
  <div ui-grid="gridOptions" class="grid" ui-grid-infinite-scroll></div>
</div>

    <script src="app.js"></script>
  </body>
</html>
</code>```

答:
Have a look at this npm package:

Once installed:

```<code><ul style="width: 200px; height: 200px" viewport>
   <li ng-repeat="item in items" style="width: 200px; height: 200px" viewport-leave="item.visible = false" viewport-enter="item.visible = true">
</ul>
</code>```

Body:
Is it possible to obtain the index of the top element of a ui-grid that is currently visible/displayed by the client/browser?

For example, take a look at (an edited) ui-grid's infinite scrolling example  in this plunkr example. Is it possible to obtain that that top index somehow?

This would be the app.js code, which is exactly the same as the infinite-scroll example:

var app = angular.module('app', ['ngTouch', 'ui.grid', 'ui.grid.infiniteScroll']);

app.controller('MainCtrl', ['$scope', '$http', '$timeout', function ($scope, $http, $timeout) {
  $scope.gridOptions = {
    infiniteScrollRowsFromEnd: 40,
    infiniteScrollUp: true,
    infiniteScrollDown: true,
    columnDefs: [
      { name:'id'},
      { name:'name' },
      { name:'age' }
    ],
    data: 'data',
    onRegisterApi: function(gridApi){
      gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.getDataDown);
      gridApi.infiniteScroll.on.needLoadMoreDataTop($scope, $scope.getDataUp);
      $scope.gridApi = gridApi;
    }
  };

  $scope.data = [];

  $scope.firstPage = 2;
  $scope.lastPage = 2;

  $scope.getFirstData = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      var newData = $scope.getPage(response.data, $scope.lastPage);
      $scope.data = $scope.data.concat(newData);
    });
  };

  $scope.getDataDown = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      $scope.lastPage++;
      var newData = $scope.getPage(response.data, $scope.lastPage);
      $scope.gridApi.infiniteScroll.saveScrollPercentage();
      $scope.data = $scope.data.concat(newData);
      return $scope.gridApi.infiniteScroll.dataLoaded($scope.firstPage > 0, $scope.lastPage < 4).then(function() {$scope.checkDataLength('up');});
    })
    .catch(function(error) {
      return $scope.gridApi.infiniteScroll.dataLoaded();
    });
  };

  $scope.getDataUp = function() {
    return $http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pageshttps://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/10000_complex.json')
    .then(function(response) {
      $scope.firstPage--;
      var newData = $scope.getPage(response.data, $scope.firstPage);
      $scope.gridApi.infiniteScroll.saveScrollPercentage();
      $scope.data = newData.concat($scope.data);
      return $scope.gridApi.infiniteScroll.dataLoaded($scope.firstPage > 0, $scope.lastPage < 4).then(function() {$scope.checkDataLength('down');});
    })
    .catch(function(error) {
      return $scope.gridApi.infiniteScroll.dataLoaded();
    });
  };

  $scope.getPage = function(data, page) {
    var res = [];
    for (var i = (page * 100); i < (page + 1) * 100 && i < data.length; ++i) {
      res.push(data[i]);
    }
    return res;
  };

  $scope.checkDataLength = function( discardDirection) {
    // work out whether we need to discard a page, if so discard from the direction passed in
    if( $scope.lastPage - $scope.firstPage > 3 ){
      // we want to remove a page
      $scope.gridApi.infiniteScroll.saveScrollPercentage();

      if( discardDirection === 'up' ){
        $scope.data = $scope.data.slice(100);
        $scope.firstPage++;
        $timeout(function() {
          // wait for grid to ingest data changes
          $scope.gridApi.infiniteScroll.dataRemovedTop($scope.firstPage > 0, $scope.lastPage < 4);
        });
      } else {
        $scope.data = $scope.data.slice(0, 400);
        $scope.lastPage--;
        $timeout(function() {
          // wait for grid to ingest data changes
          $scope.gridApi.infiniteScroll.dataRemovedBottom($scope.firstPage > 0, $scope.lastPage < 4);
        });
      }
    }
  };

  $scope.reset = function() {
    $scope.firstPage = 2;
    $scope.lastPage = 2;

    // turn off the infinite scroll handling up and down - hopefully this won't be needed after @swalters scrolling changes
    $scope.gridApi.infiniteScroll.setScrollDirections( false, false );
    $scope.data = [];

    $scope.getFirstData().then(function(){
      $timeout(function() {
        // timeout needed to allow digest cycle to complete,and grid to finish ingesting the data
        $scope.gridApi.infiniteScroll.resetScroll( $scope.firstPage > 0, $scope.lastPage < 4 );
      });
    });
  };

  $scope.getFirstData().then(function(){
    $timeout(function() {
      // timeout needed to allow digest cycle to complete,and grid to finish ingesting the data
      // you need to call resetData once you've loaded your data if you want to enable scroll up,
      // it adjusts the scroll position down one pixel so that we can generate scroll up events
      $scope.gridApi.infiniteScroll.resetScroll( $scope.firstPage > 0, $scope.lastPage < 4 );
    });
  });

}]);

HTML

<!doctype html>

    <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid.css" type="text/css">
    <link rel="stylesheet" href="main.css" type="text/css">

  <button id="reset" class="button" ng-click="reset()">Reset</button>
       First page: {{ firstPage }}     Last page: {{ lastPage }}      data.length: {{ data.length }}

Body:
Have a look at this npm package:

Once installed:

<ul style="width: 200px; height: 200px" viewport>
   <li ng-repeat="item in items" style="width: 200px; height: 200px" viewport-leave="item.visible = false" viewport-enter="item.visible = true">
</ul>


问:
KendoUI autocomplete server filtering with .net Core and no odata
I'm trying to implement server filtering in a .net Core mvc web app. MVC core does not support Odata out of the box and i cannot implement it.

Autocomplete seems to send query filtering along the request for data as a querystring. The querystring is a multidimensional array format.

How can i extract the value i need to filter from this querstring that looks something like:

filter%5Bfilters%5D%5B0%5D%5Bvalue%5D=l6j&filter%5Bfilters%5D%5B0%5D%5Boperator%5D=contains&filter%5Bfilters%5D%5B0%5D%5Bfield%5D=&filter%5Bfilters%5D%5B0%5D%5BignoreCase%5D=true&filter%5Blogic%5D=and"

filter[filters][0][value]=l6j&filter[filters][0][operator]=contains&filter[filters][0][field]=&filter[filters][0][ignoreCase]=true&filter[logic]=and

答:
I think you can do something like this
var searchValue =  Request.Query["filter[filters][0][value]"];</p>


问:
Kivy - Error Unable permissions?
I need some help. I'm studying kivy and I use pycharm as IDE for development.
To work with kivy I created a virtualenvs with requeriments:

```<code>kivy = 1.10
Cython = 0.23
Python = 3.5
</code>```

As for setup I did not have too much trouble. It came later when I tried to generate a layout and it did not appear.
Is my code:

```<code># coding = utf-8

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.core.window import Window

def click():
    print (ed.text)

def build():

    layout = FloatLayout()

    ed = TextInput(text="USER.COM")
    global ed
    ed.size_hint = None, None
    ed.height = 300
    ed.width = 400
    ed.y = 60
    ed.x = 250

    bt = Button(text="Click Me")
    bt.size_hint = None, None
    bt.height = 50
    bt.width = 200
    bt.y = 150
    bt.x = 170
    bt.size_hint = None, None
    bt.on_press = click()

    layout.add_widget(ed)
    layout.add_widget(bt)

    return layout

Window.size=600,600
open= App()
open.title = "USER_FREE_AS"
open.buid=build
open.run()
</code>```

The log reports that pycharm is not allowed to access the function. Is my log:

```<code>/home/user/.virtualenvs/k35/bin/python /home/user/Projetos/Python/kivy/source/tela_layout/main.py
/home/user/Projetos/Python/kivy/source/tela_layout/main.py:18: SyntaxWarning: name 'ed' is assigned to before global declaration
  global ed
[INFO   ] [Logger      ] Record log in /home/victorpenna/.kivy/logs/kivy_17-11-13_11.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [OSC         ] using <multiprocessing> for socket
[INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored)
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] Backend used <gl>
[INFO   ] [GL          ] OpenGL version <b'3.0 Mesa 17.3.0-rc2 - padoka PPA'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel Open Source Technology Center'>
[INFO   ] [GL          ] OpenGL renderer <b'Mesa DRI Intel(R) HD Graphics 5500 (Broadwell GT2) '>
[INFO   ] [GL          ] OpenGL parsed version: 3, 0
[INFO   ] [GL          ] Shading version <b'1.30'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event8
[INFO   ] [MTD         ] Read event from </dev/input/event8>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event13
[INFO   ] [MTD         ] Read event from </dev/input/event13>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event14
[INFO   ] [MTD         ] Read event from </dev/input/event14>
[INFO   ] [Base        ] Start application main loop
[WARNING] [MTD         ] Unable to open device "/dev/input/event8". Please ensure you have the appropriate permissions.
[WARNING] [MTD         ] Unable to open device "/dev/input/event13". Please ensure you have the appropriate permissions.
[WARNING] [MTD         ] Unable to open device "/dev/input/event14". Please ensure you have the appropriate permissions.
[INFO   ] [Base        ] Leaving application in progress...

Process finished with exit code 0
</code>```

How can I solve this problem?

P.S: My linux is ubuntu 16.04, Intel GPU.

答:
You have a typo:

```<code>open.buid=build
</code>```

should probably be

```<code>open.build=build
</code>```

But don't do that. Putting methods to an instance afterwards (monkeypatching) gets very confusing fast. Other developers will not expect it in this situation. Also kivy does some magic with the classname of the app, it will locate the .kv file following a naming convention. So instead write:

```<code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.core.window import Window

class MyApp(App):

    def click(self):
        print(self.ed.text)

    def build(self):

        layout = FloatLayout()

        self.ed = TextInput(text="USER.COM")
        ed.size_hint = None, None
        ed.height = 300
        ed.width = 400
        ed.y = 60
        ed.x = 250

        bt = Button(text="Click Me")
        bt.size_hint = None, None
        bt.height = 50
        bt.width = 200
        bt.y = 150
        bt.x = 170
        bt.size_hint = None, None
        bt.on_press = click()

        layout.add_widget(ed)
        layout.add_widget(bt)

        return layout

Window.size=600,600
open= MyApp()
open.title = "USER_FREE_AS"
open.run()
</code>```

That way you also avoid the global variable, which is most of the time a sign that you do something suboptimal.

If you are still new to kivy I recommend going through the kivy tutorials.

Title: Kivy - Error Unable permissions?

Body:
I need some help. I'm studying kivy and I use pycharm as IDE for development.
To work with kivy I created a virtualenvs with requeriments:

kivy = 1.10
Cython = 0.23
Python = 3.5

As for setup I did not have too much trouble. It came later when I tried to generate a layout and it did not appear.
Is my code:

# coding = utf-8

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.core.window import Window

def click():
    print (ed.text)

def build():

    layout = FloatLayout()

    ed = TextInput(text="USER.COM")
    global ed
    ed.size_hint = None, None
    ed.height = 300
    ed.width = 400
    ed.y = 60
    ed.x = 250

    bt = Button(text="Click Me")
    bt.size_hint = None, None
    bt.height = 50
    bt.width = 200
    bt.y = 150
    bt.x = 170
    bt.size_hint = None, None
    bt.on_press = click()

    layout.add_widget(ed)
    layout.add_widget(bt)

    return layout

Window.size=600,600
open= App()
open.title = "USER_FREE_AS"
open.buid=build
open.run()

The log reports that pycharm is not allowed to access the function. Is my log:

/home/user/.virtualenvs/k35/bin/python /home/user/Projetos/Python/kivy/source/tela_layout/main.py
/home/user/Projetos/Python/kivy/source/tela_layout/main.py:18: SyntaxWarning: name 'ed' is assigned to before global declaration
  global ed
[INFO   ] [Logger      ] Record log in /home/victorpenna/.kivy/logs/kivy_17-11-13_11.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [OSC         ] using <multiprocessing> for socket
[INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored)
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] Backend used <gl>
[INFO   ] [GL          ] OpenGL version
[INFO   ] [GL          ] OpenGL vendor
[INFO   ] [GL          ] OpenGL renderer
[INFO   ] [GL          ] OpenGL parsed version: 3, 0
[INFO   ] [GL          ] Shading version
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event8
[INFO   ] [MTD         ] Read event from </dev/input/event8>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event13
[INFO   ] [MTD         ] Read event from </dev/input/event13>
[INFO   ] [ProbeSysfs  ] device match: /dev/input/event14
[INFO   ] [MTD         ] Read event from </dev/input/event14>
[INFO   ] [Base        ] Start application main loop
[WARNING] [MTD         ] Unable to open device "/dev/input/event8". Please ensure you have the appropriate permissions.
[WARNING] [MTD         ] Unable to open device "/dev/input/event13". Please ensure you have the appropriate permissions.
[WARNING] [MTD         ] Unable to open device "/dev/input/event14". Please ensure you have the appropriate permissions.
[INFO   ] [Base        ] Leaving application in progress...

Process finished with exit code 0

How can I solve this problem?

P.S: My linux is ubuntu 16.04, Intel GPU.

Body:
You have a typo:

open.buid=build

should probably be

open.build=build

But don't do that. Putting methods to an instance afterwards (monkeypatching) gets very confusing fast. Other developers will not expect it in this situation. Also kivy does some magic with the classname of the app, it will locate the .kv file following a naming convention. So instead write:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.core.window import Window

class MyApp(App):

    def click(self):
        print(self.ed.text)

    def build(self):

        layout = FloatLayout()

        self.ed = TextInput(text="USER.COM")
        ed.size_hint = None, None
        ed.height = 300
        ed.width = 400
        ed.y = 60
        ed.x = 250

        bt = Button(text="Click Me")
        bt.size_hint = None, None
        bt.height = 50
        bt.width = 200
        bt.y = 150
        bt.x = 170
        bt.size_hint = None, None
        bt.on_press = click()

        layout.add_widget(ed)
        layout.add_widget(bt)

        return layout

Window.size=600,600
open= MyApp()
open.title = "USER_FREE_AS"
open.run()

That way you also avoid the global variable, which is most of the time a sign that you do something suboptimal.

If you are still new to kivy I recommend going through the kivy tutorials.


问:
How should I format a post_filter query to match a string inside of a string in Elasticsearch?
I have an array of articles in a MongoDB database that is indexed into Elasticsearch. Each article in MongoDB contains an array of author names like so: ['Michael Jordan', '...']. Each article is then indexed into Es.

In Es, I have aggregation by author working, but I also want to apply a post_filter to filter results by author. How should a post_filter query be designed to handle this?

Es Schema (can be changed):

```<code>{
  authors: ['Michael Jordan', 'Kobe Bryant'],
  authorsString: 'Michael Jordan;Kobe Bryant;'
}
</code>```

This is an example query before applying the post_filter:

```<code>{
  ...
  aggs: {
    authors: {
      terms: {
        field: 'authorsArray.keyword',
      },
    },
  },
  post_filter: {},
}
</code>```

If I want to find articles of which at least one of the authors is "Michael Jordan", how do I use post_filter to do so?

答:
If the author field is not analyzed you can always just simply filter by term like so </p>

```<code>"post_filter": {
    "term": { "authors": "Michael Jordan" }
 }
</code>```

Body:
I have an array of articles in a MongoDB database that is indexed into Elasticsearch. Each article in MongoDB contains an array of author names like so: ['Michael Jordan', '...']. Each article is then indexed into Es.

In Es, I have aggregation by author working, but I also want to apply a post_filter to filter results by author. How should a post_filter query be designed to handle this?

Es Schema (can be changed):

{
  authors: ['Michael Jordan', 'Kobe Bryant'],
  authorsString: 'Michael Jordan;Kobe Bryant;'
}

This is an example query before applying the post_filter:

{
  ...
  aggs: {
    authors: {
      terms: {
        field: 'authorsArray.keyword',
      },
    },
  },
  post_filter: {},
}

If I want to find articles of which at least one of the authors is "Michael Jordan", how do I use post_filter to do so?

Body:
If the author field is not analyzed you can always just simply filter by term like so

"post_filter": {
    "term": { "authors": "Michael Jordan" }
 }


问:
Sum of specific values grouped by other values inside an array
I have this array structure in which at $arr[5]index I have a value that represents a number of occurrences for each object of my array $arr:

```<code>$arr=[
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_2",
    "some_value",
    "1"
  ],
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_2",
    "some_value",
    "2"
  ],
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_3",
    "some_value",
    "1"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_3",
    "some_value",
    "3"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_4",
    "some_value",
    "2"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_4",
    "some_value",
    "2"
  ]
];
</code>```

What I'm trying to obtain is to sum each of those$arr[5] values grouping by $arr[2](the cluster) and the $arr[3](the area).

Here's the expected output

```<code>$res=[
  [
    "cluster_0",
    "area_2",
    3
  ],
  [
    "cluster_0",
    "area_3",
    1
  ],
  [
    "cluster_1",
    "area_3",
    3
  ],
  [
    "cluster_1",
    "area_4",
    4
  ]
];
</code>```

As you can see I have the sum of that specific value according to area and cluster matching. Is there any good approach in javascript for perform this kind of operation? I thought about a simple for loop and inside the loop an if condition for sum just the value that share the same $arr[2](the cluster) and the $arr[3](the area) values.

答:
Consider also this solution,

```<code>var data = $arr.reduce(function(acc, item) {
  var clusterName = item[2],
      areaName = item[3];
  acc[clusterName] = acc[clusterName] || {};
  acc[clusterName][areaName] = acc[clusterName][areaName] || 0;
  acc[clusterName][areaName] += parseInt(item[5]);
  return acc;
}, {});

console.log(data);

var array = Object.keys(data).reduce(function(acc, clusterItem) {
  Object.keys(data[clusterItem]).forEach(function(areaItem) {
    var item = [];
    item.push(clusterItem);
    item.push(areaItem);
    item.push(data[clusterItem][areaItem]);
    acc.push(item);
  });
  return acc;
}, []);

console.log(array);
</code>```

Here at the first step all the items are calculated and added to the object. The second one converts the object to the required structure (array).

Body:
I have this array structure in which at $arr[5]index I have a value that represents a number of occurrences for each object of my array $arr:

$arr=[
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_2",
    "some_value",
    "1"
  ],
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_2",
    "some_value",
    "2"
  ],
  [
    "some_value",
    "some_value",
    "cluster_0",
    "area_3",
    "some_value",
    "1"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_3",
    "some_value",
    "3"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_4",
    "some_value",
    "2"
  ],
  [
    "some_value",
    "some_value",
    "cluster_1",
    "area_4",
    "some_value",
    "2"
  ]
];

What I'm trying to obtain is to sum each of those$arr[5] values grouping by $arr[2](the cluster) and the $arr[3](the area).

Here's the expected output

$res=[
  [
    "cluster_0",
    "area_2",
    3
  ],
  [
    "cluster_0",
    "area_3",
    1
  ],
  [
    "cluster_1",
    "area_3",
    3
  ],
  [
    "cluster_1",
    "area_4",
    4
  ]
];

As you can see I have the sum of that specific value according to area and cluster matching. Is there any good approach in javascript for perform this kind of operation? I thought about a simple for loop and inside the loop an if condition for sum just the value that share the same $arr[2](the cluster) and the $arr[3](the area) values.

Body:
Consider also this solution,

var data = $arr.reduce(function(acc, item) {
  var clusterName = item[2],
      areaName = item[3];
  acc[clusterName] = acc[clusterName] || {};
  acc[clusterName][areaName] = acc[clusterName][areaName] || 0;
  acc[clusterName][areaName] += parseInt(item[5]);
  return acc;
}, {});

console.log(data);

var array = Object.keys(data).reduce(function(acc, clusterItem) {
  Object.keys(data[clusterItem]).forEach(function(areaItem) {
    var item = [];
    item.push(clusterItem);
    item.push(areaItem);
    item.push(data[clusterItem][areaItem]);
    acc.push(item);
  });
  return acc;
}, []);

console.log(array);

Here at the first step all the items are calculated and added to the object. The second one converts the object to the required structure (array).


问:
Appending to cell array matlab
I am new to matlab. I have one question about datatypes.

I have an array of the cell array type. In the variables window it shows me it as 190x1 double.

I have two questions.

What is the purpose of the cell array type if there is the matrix type ?

How to append another similar array to the column of an existing array. For example I have two arrays 190x1 double I wan't a new array to be 380x1 double

I would be grateful for any help.

Thanks

答:
I'd encourage you to browse the documentation for cell arrays.  One of the most common uses as it states is mixed size or mixed type data...among other uses.

Cell arrays commonly contain either lists of text strings,
  combinations of text and numbers, or numeric arrays of different
  sizes.

To append two arrays you could do this.  It will place the two vectors end to end.

```<code>X=ones(190,1);
X =[X; X];
</code>```

Title: Appending to cell array matlab

Body:
I'd encourage you to browse the documentation for cell arrays.  One of the most common uses as it states is mixed size or mixed type data...among other uses.

Cell arrays commonly contain either lists of text strings,
  combinations of text and numbers, or numeric arrays of different
  sizes.

To append two arrays you could do this.  It will place the two vectors end to end.

X=ones(190,1);
X =[X; X];


问:
Python 3 | Locations arround a point (lat/long)
Is there a way to verify that a tuple of latitude and longitude values (for example, (-32.0321, -72.3213)) is whithin a R radius (in miles, kilometers, etc) of another tuple of latitude, longitude using some sort of api or function?</p>

答:
https://www.movable-type.co.uk/scripts/latlong.html This site shows how to calculate the distance

And here is a pypi module for the harversine distance:
https://pypi.python.org/pypi/haversine


问:
Add more space (padding) into NVD3 line chart max and min
Let's take the example below:

krispo.github.io/angular-nvd3/#/lineChart

I want to add more space (kind of padding) between the min/max of the line chart and the x-axis/top.

There is this an option called yDomain:

Defines the whole Y scale's domain. Using this will disable calculating the domain based on the data.

The bold part means if I set the min to be -100, if my chart goes below that level, I won't see it anymore. Or, if the min of my chart is actually -50, then -100 would be too much.

So basically I want the min and the max of the Y-Axis to be 10% of the (respectively) min and max of the chart.

答:
Found the solution. It was just math. :/

We need to get the y-min/y-max first:

```<code>const min = Math.min(...data.map(d => d.y));
const max = Math.max(...data.map(d => d.y));
</code>```

And then (if we want 15% margins):

```<code>{
    ...
    yDomain: [min - (max - min) * 0.15, max + (max - min) * 0.15]
    ...
}
</code>```

Body:
Found the solution. It was just math. :/

We need to get the y-min/y-max first:

const min = Math.min(...data.map(d => d.y));
const max = Math.max(...data.map(d => d.y));

And then (if we want 15% margins):

{
    ...
    yDomain: [min - (max - min) * 0.15, max + (max - min) * 0.15]
    ...
}