问:
Creating an employee Permission DB
I work for a small company that has many different permissions for different apps. Right now we track all of this on a spreadsheet that is slowly getting out of control. We look in a column, to match of a job grouping (say accounting- finance might be a group), then look at each row below that to find out how many applications they need, and the needed permissions for each application. Then with this information we go about giving them the access. I'd like to automate this whole thing at some point. But for now I'm focused on removing the spreadsheet

I'd like to make a simple database that would allow me to query and search by Logical Job group, and pull back the permissions for each individual app that pertain to that job grouping. I haven't worked in building databases before but I've installed SQL express, just need some help logically thinking out the tables and how they would interact. Each application obviously can have different permission groups, but can also contain mutliple. For example, Employee A, needs application X installed, with permission groups 1, 2, and 4.

Thanks!

答: This requires more than installing SQL express. You need to figure out architecture i.e how your data relates to each other at different points. In your case granting permissions doesn't look like a database operation. Permissions for different applications should better be handled manually by admins(compliance). What you can do is you can store the job groupings and there required permissions in database, automate the front end i.e requesting access, for that you can use Microsoft Flow application which lets you connect to different apps, databases etc. and based on input provided by the user you can search for accesses to be given in database and send it to admin/automate if its a database application or if you can connect to any other application's admin console from MS Flow.</p>

Title: Creating an employee Permission DB


来源: stackexchange

问:
How do i implement the take function in Haskell using takeWhile?
So in my exam i had to implement the take function in Haskell using the takeWhile.

How can i do this?

What would be the condition in takeWhile so that it will only take the required number of elements from the list?

Because to my understanding in takeWhile the condition refers to the elements of the list, not the number of those.

答:
to my understanding in takeWhile the condition refers to the elements of the list, not the number of those

Yes! Except, maybe, perhaps, we could somehow make each element reflect the number of its preceding elements in the list, i.e. its index in the list.

So we would need to transform our argument list

  [ a,          b,         c,          .... ]

into a new, modified one, containing the extended information in its elements, e.g.

  [(a, what?), (b, goes?), (c, here?), .... ]

and then craft some kind of predicate on these pairs to do what we want; then recover the original elements from the pairs, following the decorate--transform--undecorate paradigm.

If you aren't familiar with the built-in higher-order functions that can accomplish these tasks, you can code them up with recursion, yourself. Or use list comprehensions.

ContentLicense: CC BY-SA 4.0


问:
Keeping text at center bottom in a cell of table
I want to place text at center and at the bottom of the cell in table. How can I do this?

This is what I want:

答:
table, th, td {
   border: 1px solid black;
   border-collapse: collapse;
}
td{
  vertical-align:bottom;
  text-align:center;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td rowspan="3" width="100%">bottom and center</td>
   </tr>
   <tr>
    <td rowspan="1">TOTAL</td>
   </tr>
   <tr>
    <td rowspan="1">TOTAL</td>
   </tr>
</table>

          </code>```

use style vertical-align:bottom;text-align:center; these can be helpful for your table.

Body:
table, th, td {
   border: 1px solid black;
   border-collapse: collapse;
}
td{
  vertical-align:bottom;
  text-align:center;
  }

<table>
  <tr>
    <td rowspan="3" width="100%">bottom and center</td>
   </tr>
   <tr>
    <td rowspan="1">TOTAL</td>
   </tr>
   <tr>
    <td rowspan="1">TOTAL</td>
   </tr>
</table>

use style vertical-align:bottom;text-align:center; these can be helpful for your table.


问:
Select a JSON attribute based on other elements within an array using JSONPath
I have a sample JSON array:

```<code>{
"data": {
    "list": [
        {
            "id": 192,
            "name": "John Black",
            "username": "jblack",
            "email": "jblack@myorganization.com",
            "extern_uid": "user distinguished name"
        },
        {
            "id": 63,
            "name": "Jane Doe",
            "username": "jadoe",
            "email": "jadoe@myorganization.com",
            "extern_uid": "user distinguished name"
        }
    ]
}}
</code>```

I want to extract an attribute based on another attribute using JSONPath expression,

For example:

I want to search for the name "Jane Doe" and extract values from the Jane Doe array like id: 63 or any other value in the Jane Doe array.  Is this possible in JSONPath? I am not an expert in JSONPath so I apologize if this may seem trivial for others

Thanks all

答:
found the solution:

$.data.list[?(@.username == "jblack")].id

Will return:

"id": 192

Body:
I have a sample JSON array:

{
"data": {
    "list": [
        {
            "id": 192,
            "name": "John Black",
            "username": "jblack",
            "email": "jblack@myorganization.com",
            "extern_uid": "user distinguished name"
        },
        {
            "id": 63,
            "name": "Jane Doe",
            "username": "jadoe",
            "email": "jadoe@myorganization.com",
            "extern_uid": "user distinguished name"
        }
    ]
}}

I want to extract an attribute based on another attribute using JSONPath expression,

For example:

I want to search for the name "Jane Doe" and extract values from the Jane Doe array like id: 63 or any other value in the Jane Doe array.  Is this possible in JSONPath? I am not an expert in JSONPath so I apologize if this may seem trivial for others

Thanks all


问:
How to sum COUNT values
I'm very new to SQLite so please forgive me asking something stupid.
From a database with a table containing aircraft data I can count the records with data from a manufacturer with my existing query:

```<code>SELECT Manufacturer, COUNT(Manufacturer) AS Number
FROM aircraft
WHERE Manufacturer like 'Airbus%'
GROUP BY Manufacturer
ORDER BY COUNT(Manufacturer) DESC;
</code>```

This gives me

```<code>Manufacturer        Number
Airbus              3473
Airbus Military     29
Airbus Helicopters  2
</code>```

Is there a way to get the calculated grand total (3504) in the results without removing the 'GROUP BY'clause?
I can't get SUM() and TOTAL() to work. The questions about this counting an aggregating seem to use values found in the tables.

答:
With UNION ALL:

```<code>SELECT t.*
FROM (
  SELECT Manufacturer, COUNT(Manufacturer) AS Number
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
  GROUP BY Manufacturer
  UNION ALL
  SELECT 'Total', COUNT(Manufacturer)
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
) t
ORDER BY Manufacturer = 'Total', Number DESC
</code>```

See the demo.

Or with a CTE:

```<code>WITH cte AS (
  SELECT Manufacturer, COUNT(Manufacturer) AS Number
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
  GROUP BY Manufacturer
)
SELECT t.*
FROM (
  SELECT * FROM cte
  UNION ALL
  SELECT 'Total', SUM(Number) FROM cte
) t
ORDER BY MAnufacturer = 'Total', Number DESC
</code>```

See the demo.

Title: How to sum COUNT values

Body:
I'm very new to SQLite so please forgive me asking something stupid.
From a database with a table containing aircraft data I can count the records with data from a manufacturer with my existing query:

SELECT Manufacturer, COUNT(Manufacturer) AS Number
FROM aircraft
WHERE Manufacturer like 'Airbus%'
GROUP BY Manufacturer
ORDER BY COUNT(Manufacturer) DESC;

This gives me

Manufacturer        Number
Airbus              3473
Airbus Military     29
Airbus Helicopters  2

Is there a way to get the calculated grand total (3504) in the results without removing the 'GROUP BY'clause?
I can't get SUM() and TOTAL() to work. The questions about this counting an aggregating seem to use values found in the tables.

Body:
With UNION ALL:

SELECT t.*
FROM (
  SELECT Manufacturer, COUNT(Manufacturer) AS Number
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
  GROUP BY Manufacturer
  UNION ALL
  SELECT 'Total', COUNT(Manufacturer)
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
) t
ORDER BY Manufacturer = 'Total', Number DESC

See the demo.

Or with a CTE:

WITH cte AS (
  SELECT Manufacturer, COUNT(Manufacturer) AS Number
  FROM aircraft
  WHERE Manufacturer like 'Airbus%'
  GROUP BY Manufacturer
)
SELECT t.*
FROM (
  SELECT * FROM cte
  UNION ALL
  SELECT 'Total', SUM(Number) FROM cte
) t
ORDER BY MAnufacturer = 'Total', Number DESC

See the demo.


问:
Implementing image slider with thumbs using ngx-swiper-wrapper
I'm trying to implement ngx-swiper-wrapper to build an image slider with thumbs similar to this:

https://idangero.us/swiper/demos/300-thumbs-gallery.html

Has anyone managed to do this? I can't see any good documentation on how to build all swiper sliders with this wrapper. Also, is the FlexLayoutModule that is used in the demo for ngx-swiper-wrapper a must or can it be implemented without?

答:
We have working demo in native JS.

https://stackblitz.com/edit/swiper-demo-31-thumbs-gallery-with-loop-mode?file=index.html

For Angular you only should add thumbs to SwiperConfigInterface like this:

```<code>galleryTopConfig: SwiperConfigInterface = {
    spaceBetween: 10,
    loop: true,
    loopedSlides: 5, //looped slides should be the same
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    thumbs: {
      swiper: Object.assign(this.galleryThumbsConfig, {el: '.gallery-thumbs'})
    }
  };
</code>```

and apply config

```<code><div class="swiper-container gallery-top" [swiper]="galleryTopConfig">
</code>```

For .gallery-thumbs you should apply config by the same way.

(from docs https://swiperjs.com/api/#thumbs)

Body:
We have working demo in native JS.

https://stackblitz.com/edit/swiper-demo-31-thumbs-gallery-with-loop-mode?file=index.html

For Angular you only should add thumbs to SwiperConfigInterface like this:

galleryTopConfig: SwiperConfigInterface = {
    spaceBetween: 10,
    loop: true,
    loopedSlides: 5, //looped slides should be the same
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    thumbs: {
      swiper: Object.assign(this.galleryThumbsConfig, {el: '.gallery-thumbs'})
    }
  };

and apply config

<div class="swiper-container gallery-top" [swiper]="galleryTopConfig">

For .gallery-thumbs you should apply config by the same way.

(from docs https://swiperjs.com/api/#thumbs)


问:
Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input'
I get the error "Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input' " when I run my angular project. Looked everywhere but couldn't find a solution.

Here is my html.

```<code><div class="kt-section__content">
    <label for="typeahead-basic">Search for a state:</label>
    <input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" />
</div>
</code>```

Here is the component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';

const states = ['Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado',
  'Connecticut', 'Delaware', 'District Of Columbia', 'Federated States Of Micronesia', 'Florida', 'Georgia',
  'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
  'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana',
  'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia',
  'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

@Component({
  selector: 'kt-grn',
  templateUrl: './grn.component.html',
  styleUrls: ['./grn.component.scss']
})
export class GrnComponent implements OnInit {
  public model: any;

  search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 2 ? []
        : states.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    )

  constructor() { }

  ngOnInit() {
  }

}
</code>```

And here's the code from app.module.ts

```<code>import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        NgbModule,
    ],
    exports: [],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

</code>```

Could somebody help me?

答:
You need to import the NgbTypeaheadModule as well.

```<code>import { NgbModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        NgbModule,
        NgbTypeaheadModule
    ],
    exports: [],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

Edit: this is more to do with how the library requires you to use their library rather than a pure Angular thing. Some libraries will give you everything in one module. UI component modules like Material and NgbBootstrap allow you to import component modules individually, so you can keep the size of the imported javascript down to a minimum.

Body:
I get the error "Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input' " when I run my angular project. Looked everywhere but couldn't find a solution.

Here is my html.

    Search for a state:
    <input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" />

Here is the component.ts

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';

const states = ['Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado',
  'Connecticut', 'Delaware', 'District Of Columbia', 'Federated States Of Micronesia', 'Florida', 'Georgia',
  'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
  'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana',
  'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia',
  'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

@Component({
  selector: 'kt-grn',
  templateUrl: './grn.component.html',
  styleUrls: ['./grn.component.scss']
})
export class GrnComponent implements OnInit {
  public model: any;

  search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 2 ? []
        : states.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    )

  constructor() { }

  ngOnInit() {
  }

}

And here's the code from app.module.ts

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        NgbModule,
    ],
    exports: [],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Could somebody help me?

Body:
You need to import the NgbTypeaheadModule as well.

import { NgbModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserAnimationsModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        NgbModule,
        NgbTypeaheadModule
    ],
    exports: [],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

Edit: this is more to do with how the library requires you to use their library rather than a pure Angular thing. Some libraries will give you everything in one module. UI component modules like Material and NgbBootstrap allow you to import component modules individually, so you can keep the size of the imported javascript down to a minimum.


问:
auto-selection default branch when Merge Request
I would like to know if in Gitlab, it's possible to create rule when we push a merge request.

For example, for source branch : HF-458, I want that target branch was auto-selected on : hot_fixe_rct when I push my merge request.

Thanks,

答:
You can use git alias to set something in your local so that every time you create MR, it takes the target branch in the alias.

https://docs.gitlab.com/ce/user/project/push_options.html#useful-git-aliases

Cheers!


问:
shiny: start the app with hidden tabs, with NO delay
I would like to build an application and some of the tabs will be hidden to the user until he types the right password. I know how to do this with shinyjs::hideTab:

```<code>library(shiny);library(shinyjs)
ui <- fluidPage(useShinyjs(),
  navbarPage("hello", id="hello",
             tabPanel("home", br(), h3("this is home"),passwordInput("pass", "enter 'password' to see the tabs: "),actionButton("enter", "enter")),
             tabPanel("tab2", br(), h4("this is tab2")),
             tabPanel("tab3 with a lot of stuff in it", br(), h4("this is tab3"))))
server <- function(input, output, session) {
  hideTab("hello", "tab2"); hideTab("hello", "tab3 with a lot of stuff in it")
  observeEvent(input$enter, {
    if (input$pass == "password"){showTab("hello", "tab2"); showTab("hello", "tab3 with a lot of stuff in it")}})}
shinyApp(ui, server)
</code>```

However there is a little "thing". In my application, the hidden tabs have a lot of stuff, like widgets, uiOutputs, plots, images, file reading in global.R, etc. The consequence is that the loading time is higher and during this loading time of the application (before the hideTab instruction gets run) the user actually sees the hidden tab and can even click on them and see what's inside. They stay "visible" for like 1 second and then get hidden.

Is there a way to make them immediately hidden, before the UI gets built? I'd prefer a solution without having to put all my ui code into the server.R script...

Thanks

答:
I'd go with renderUI (see @BertilBaron's answer) or appendTab because it's easy to bypass the password when hiding the tabs:

Here is how to achive the desired behaviour via appendTab avoiding the above with basic shiny, no additional JS:

```<code>library(shiny)

ui <- fluidPage(navbarPage("hello", id = "hello",
  tabPanel(
    "home",
    br(),
    h3("this is home"),
    passwordInput("pass", "enter 'password' to see the tabs: "),
    actionButton("enter", "enter")
  )
))

server <- function(input, output, session) {
  observeEvent(input$enter, {
    if (input$pass == "password") {
      appendTab(inputId = "hello", tab = tabPanel("tab2", value = "tab2_val", br(), h4("this is tab2")))
      appendTab(inputId = "hello", tab = tabPanel("tab3 with a lot of stuff in it",value = "tab3_val", br(), h4("this is tab3")))
    }
  })
}

shinyApp(ui, server)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to build an application and some of the tabs will be hidden to the user until he types the right password. I know how to do this with shinyjs::hideTab:

library(shiny);library(shinyjs)
ui <- fluidPage(useShinyjs(),
  navbarPage("hello", id="hello",
             tabPanel("home", br(), h3("this is home"),passwordInput("pass", "enter 'password' to see the tabs: "),actionButton("enter", "enter")),
             tabPanel("tab2", br(), h4("this is tab2")),
             tabPanel("tab3 with a lot of stuff in it", br(), h4("this is tab3"))))
server <- function(input, output, session) {
  hideTab("hello", "tab2"); hideTab("hello", "tab3 with a lot of stuff in it")
  observeEvent(input$enter, {
    if (input$pass == "password"){showTab("hello", "tab2"); showTab("hello", "tab3 with a lot of stuff in it")}})}
shinyApp(ui, server)

However there is a little "thing". In my application, the hidden tabs have a lot of stuff, like widgets, uiOutputs, plots, images, file reading in global.R, etc. The consequence is that the loading time is higher and during this loading time of the application (before the hideTab instruction gets run) the user actually sees the hidden tab and can even click on them and see what's inside. They stay "visible" for like 1 second and then get hidden.

Is there a way to make them immediately hidden, before the UI gets built? I'd prefer a solution without having to put all my ui code into the server.R script...

Thanks

Body:
I'd go with renderUI (see @BertilBaron's answer) or appendTab because it's easy to bypass the password when hiding the tabs:

Here is how to achive the desired behaviour via appendTab avoiding the above with basic shiny, no additional JS:

library(shiny)

ui <- fluidPage(navbarPage("hello", id = "hello",
  tabPanel(
    "home",
    br(),
    h3("this is home"),
    passwordInput("pass", "enter 'password' to see the tabs: "),
    actionButton("enter", "enter")
  )
))

server <- function(input, output, session) {
  observeEvent(input$enter, {
    if (input$pass == "password") {
      appendTab(inputId = "hello", tab = tabPanel("tab2", value = "tab2_val", br(), h4("this is tab2")))
      appendTab(inputId = "hello", tab = tabPanel("tab3 with a lot of stuff in it",value = "tab3_val", br(), h4("this is tab3")))
    }
  })
}

shinyApp(ui, server)


问:
Concurrent Modification Exception after setting all test project to work in parallel SpringBoot and junit
Running all the java tests takes so much time to finish.

So the solutions is to run all the tests in parallel using multiple threads to run functions using @RunWith(ParallelSuite.class) in all classes.

But the problem is that there is some functions when they run in parallel they use the same resources. So it throws a ConcurrentModificationException. The solutions is to set this functions and to run them sequentially.

How to isolate some function to work sequentially after configuring all junit test in a spring boot project to work in parallel using ParallelSuite otherwise is there any other solution for doing that.

答:
Use synchronized for functions that need to be accessed by one thread at a time or you can do within a single function using :

```<code>void runSync() {
    synchronized (this) {
        count = count + 1;
    }
}
</code>```

You probably also should read this.

Body:
Use synchronized for functions that need to be accessed by one thread at a time or you can do within a single function using :

void runSync() {
    synchronized (this) {
        count = count + 1;
    }
}

You probably also should read this.


问:
Elastic Beanstalk instance profile not automatically created when using Terraform in eu-west-2 region
I am using Terraform to successfully spin up some Elastic Beanstalk apps (Single Docker configuration) and enable auto-scaling as part of the app / environment creation.

This works fine in most regions I’ve tried, but when I try to spin it up in London (eu-west-2) I get an error:

```
Error: Error applying plan:

1 error(s) occurred:

* aws_elastic_beanstalk_environment.my-service-env: 1 error(s) occurred:

* aws_elastic_beanstalk_environment.my-service-env: Error waiting for Elastic Beanstalk Environment (e-mt7f3i5bmq) to become ready: 2 error(s) occurred:

* 2018-06-11 19:31:29.28 +0000 UTC (e-mt7f3i5bmq) : Environment must have instance profile associated with it.
* 2018-06-11 19:31:29.39 +0000 UTC (e-mt7f3i5bmq) : Failed to launch environment.
```

I have found that if I manually attach the aws-elasticbeanstalk-ec2-role as the IamInstanceProfile it works fine - but this relies on the role having been automatically created previously...

Is there something about the eu-west-2 region which would mean the Beanstalk apps don’t get created with the instance profile as they do in other regions?

What am I missing?

Thanks for your help!

答:
For others stuck on this issue I have found a solution by adding the instance profile directly as a setting. This instance profile doesn't get automatically added like it does when creating an elastic beanstalk through the console. Below is the full beanstalk environment resource defined:

```<code>resource "aws_elastic_beanstalk_environment" "beanstalkenvironment" {
  name                = "dev-example"
  application         = aws_elastic_beanstalk_application.beanstalkapp.name
  solution_stack_name = "64bit Amazon Linux 2018.03 v2.14.1 running Docker 18.09.9-ce"
  version_label       = aws_elastic_beanstalk_application_version.beanstalkapplicationversion.name
  setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name = "IamInstanceProfile"
      value = "aws-elasticbeanstalk-ec2-role"
  }
  setting {
    namespace = "aws:autoscaling:launchconfiguration"
    name = "InstanceType"
    value = "t2.micro"
  }
  tags = {
    Name = "test"
    Environment = "test"
  }
}
</code>```

The exact setting used to fix this error was:

```<code>setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name = "IamInstanceProfile"
      value = "aws-elasticbeanstalk-ec2-role"
  }
</code>```

To find what the value "aws-elasticbeanstalk-ec2-role" that's required I checked an existing elastic beanstalk instance that was created through the console. Under the environment, in configuration there is a security section. The role name needed is listed as "IAM instance profile". Hopefully this helps others who get stuck on this issue.

Body:
I am using Terraform to successfully spin up some Elastic Beanstalk apps (Single Docker configuration) and enable auto-scaling as part of the app / environment creation.

This works fine in most regions I’ve tried, but when I try to spin it up in London (eu-west-2) I get an error:

Error: Error applying plan:

1 error(s) occurred:

* aws_elastic_beanstalk_environment.my-service-env: 1 error(s) occurred:

* aws_elastic_beanstalk_environment.my-service-env: Error waiting for Elastic Beanstalk Environment (e-mt7f3i5bmq) to become ready: 2 error(s) occurred:

* 2018-06-11 19:31:29.28 +0000 UTC (e-mt7f3i5bmq) : Environment must have instance profile associated with it.
* 2018-06-11 19:31:29.39 +0000 UTC (e-mt7f3i5bmq) : Failed to launch environment.

I have found that if I manually attach the aws-elasticbeanstalk-ec2-role as the IamInstanceProfile it works fine - but this relies on the role having been automatically created previously...

Is there something about the eu-west-2 region which would mean the Beanstalk apps don’t get created with the instance profile as they do in other regions?

What am I missing?

Thanks for your help!

Body:
For others stuck on this issue I have found a solution by adding the instance profile directly as a setting. This instance profile doesn't get automatically added like it does when creating an elastic beanstalk through the console. Below is the full beanstalk environment resource defined:

resource "aws_elastic_beanstalk_environment" "beanstalkenvironment" {
  name                = "dev-example"
  application         = aws_elastic_beanstalk_application.beanstalkapp.name
  solution_stack_name = "64bit Amazon Linux 2018.03 v2.14.1 running Docker 18.09.9-ce"
  version_label       = aws_elastic_beanstalk_application_version.beanstalkapplicationversion.name
  setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name = "IamInstanceProfile"
      value = "aws-elasticbeanstalk-ec2-role"
  }
  setting {
    namespace = "aws:autoscaling:launchconfiguration"
    name = "InstanceType"
    value = "t2.micro"
  }
  tags = {
    Name = "test"
    Environment = "test"
  }
}

The exact setting used to fix this error was:

setting {
      namespace = "aws:autoscaling:launchconfiguration"
      name = "IamInstanceProfile"
      value = "aws-elasticbeanstalk-ec2-role"
  }

To find what the value "aws-elasticbeanstalk-ec2-role" that's required I checked an existing elastic beanstalk instance that was created through the console. Under the environment, in configuration there is a security section. The role name needed is listed as "IAM instance profile". Hopefully this helps others who get stuck on this issue.


问:
Dynamically join pivoted table
Maybe the community could advise me on this Postgres question (PostgreSQL 9.5)

There is a big (1.5 mil rows) flightlog table with columns: action type (4 action types), timestamp and user_id.
The users table has 6K rows.

```<code>**flightlog**
user_id, time, action
2301    "2016-10-25 14:13:25.74668" "View"
8   "2016-04-25 15:02:13.916204"    "Download"
8   "2016-04-25 15:01:20.553475"    "Download"
8   "2016-04-25 14:57:02.430493"    "Download"
8   "2016-04-25 14:57:02.160002"    "Download"
8   "2016-04-25 14:57:01.397602"    "Download"
26  "2016-10-25 16:01:25.005285"    "View"
216 "2016-10-24 14:46:16.035242"    "View"
2182    "2016-10-24 14:47:43.713"   "View"
243 "2016-10-24 12:10:12.187181"    "View"
26  "2016-10-24 15:01:26.269981"    "View"
26  "2016-10-24 15:01:28.122361"    "View"

**users**
user_id, email
8 "ndoe@mysite.com"
26  "jdoe@mysite.com"
2301 "kdoe@mysite.com"

**subscriptions**
user_id, expires
8    "2017-08-30 15:48:06.827258"
26   "2017-08-10 00:00:00"
2301 "2017-09-28 09:09:17.56549"
</code>```

I need to have a table with counts for 4 different actions per month for a user,
so it would be user and then 4 actions per month and this is replicated 12 times.
The columns would look the following:

```<code>user1  period1_action1 period1_action2 period1_action3 period1_action4 period2_action1 etc
</code>```

To make it more complicated these 12 months should be dynamic for every user, calculated as +12 months from their subscription date in subscriptions table(10K).

So far I could come with a FILTER-based pivot on actions and join it with cte choosing username and start of the subscription.

```<code>with counters ( <doing counts using windowing functions>),
     pivot1   ( <pivoting counters using FILTER>
              ...sum(times) filter (where action = 'action1')...
              ),
     recent_subscription (<picking latest subscription for a user>),
     titles   (<using previous cte and adding more info from info table>)

select t.user, t.id, t.subscription_starts, t.expires_at, t.title, email,
                p."action1", p."action2", p."action3 ", p."action4"
      from titles t
      join pivot1 p
...
</code>```

Which correctly produces activity data of 12 months for a user in the following format:

```<code>user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4
user2 ... 1st_period_4user2 action1 action2 action3 action4
user2 ... 2nd_period_4user2 action1 action2 action3 action4
user3 ... 1st_period_4user3 action1 action2 action3 action4
user3 ... 2nd_period_4user3 action1 action2 action3 action4
</code>```

etc

But the challenge is now to pivot this again to get 12periods/4actions combinations.
Could be just 12 if as below done
with json_object_aggr as (period: and then 4 actions)

```<code> --using the piece above as another CTE called merged
 --this code does not work :(
select
        email, id, ends, subs, info,
        json_object_aggr(starts, s1,v1,p1,d1 ORDER BY starts) as P1,
        json_object_aggr(starts, s2,v2,p2,d2 ORDER BY starts) as P2,
        json_object_aggr(starts, s3,v3,p3,d3 ORDER BY starts) as P3,
        json_object_aggr(starts, s4,v4,p4,d4 ORDER BY starts) as P4,
        json_object_aggr(starts, s5,v5,p5,d5 ORDER BY starts) as P5,
        json_object_aggr(starts, s6,v6,p6,d6 ORDER BY starts) as P6,
        json_object_aggr(starts, s7,v7,p7,d7 ORDER BY starts) as P7,
        json_object_aggr(starts, s8,v8,p8,d8 ORDER BY starts) as P8,
        json_object_aggr(starts, s9,v9,p9,d9 ORDER BY starts) as P9,
        json_object_aggr(starts, s10,v10,p10,d10 ORDER BY starts) as P10,
        json_object_aggr(starts, s11,v11,p11,d11 ORDER BY starts) as P11,
        json_object_aggr(starts, s12,v12,p12,d12 ORDER BY starts) as P12
    from
            (select email, id,  starts, ends, subs, info, starts,
  sum("action1") as s1,sum("action2") as v1,sum("action3") as
  p1,sum("action4")
  as d1
              from merged
              group by email, id,  starts, ends, subs, info, starts

            ) m
    group by email, id,  starts, ends, subs, info
    order by email, id,  starts, ends, subs, info
</code>```

Could this be json_object_agg for 4 actions per period?
Could I get help on how to pivot this?

Thank you.

答:
Is there a reason that you cannot use a series of CASE conditionals that result in either 1 or 0 and then SUM() them? It would make this process much simpler.

```<code>WITH subs AS (
      SELECT s.user_id, u.email, MAX(s.sub_date) AS recent_sub_date
      FROM subscriptions s
      JOIN users u ON s.userid = u.user_id
      GROUP BY s.user_id, u.email
)
SELECT s.user_id,
       SUM(CASE WHEN f.action = 'action1' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action1,
       SUM(CASE WHEN f.action = 'action2' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action2,
       SUM(CASE WHEN f.action = 'action3' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action3,
       SUM(CASE WHEN f.action = 'action4' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action4,
       SUM(CASE WHEN f.action = 'action1' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action1,
       SUM(CASE WHEN f.action = 'action2' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action2,
       SUM(CASE WHEN f.action = 'action3' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action3,
       SUM(CASE WHEN f.action = 'action4' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action4,
       ...
FROM flightlog f
JOIN subs s ON s.user_id = f.user_id
WHERE f.time > s.recent_sub_date
AND f.time <= DATE_TRUNC('month', s.recent_sub_date + INTERVAL '13 months') -- end of the 12 months after sub
GROUP BY s.user_id;
</code>```

NOTE: If you do not have indexes on your dates this will probably be pretty slow no matter how you write the query.

Title: Dynamically join pivoted table

Body:
Maybe the community could advise me on this Postgres question (PostgreSQL 9.5)

There is a big (1.5 mil rows) flightlog table with columns: action type (4 action types), timestamp and user_id.
The users table has 6K rows.

**flightlog**
user_id, time, action
2301    "2016-10-25 14:13:25.74668" "View"
8   "2016-04-25 15:02:13.916204"    "Download"
8   "2016-04-25 15:01:20.553475"    "Download"
8   "2016-04-25 14:57:02.430493"    "Download"
8   "2016-04-25 14:57:02.160002"    "Download"
8   "2016-04-25 14:57:01.397602"    "Download"
26  "2016-10-25 16:01:25.005285"    "View"
216 "2016-10-24 14:46:16.035242"    "View"
2182    "2016-10-24 14:47:43.713"   "View"
243 "2016-10-24 12:10:12.187181"    "View"
26  "2016-10-24 15:01:26.269981"    "View"
26  "2016-10-24 15:01:28.122361"    "View"

**users**
user_id, email
8 "ndoe@mysite.com"
26  "jdoe@mysite.com"
2301 "kdoe@mysite.com"

**subscriptions**
user_id, expires
8    "2017-08-30 15:48:06.827258"
26   "2017-08-10 00:00:00"
2301 "2017-09-28 09:09:17.56549"

I need to have a table with counts for 4 different actions per month for a user,
so it would be user and then 4 actions per month and this is replicated 12 times.
The columns would look the following:

user1  period1_action1 period1_action2 period1_action3 period1_action4 period2_action1 etc

To make it more complicated these 12 months should be dynamic for every user, calculated as +12 months from their subscription date in subscriptions table(10K).

So far I could come with a FILTER-based pivot on actions and join it with cte choosing username and start of the subscription.

with counters ( <doing counts using windowing functions>),
     pivot1   ( <pivoting counters using FILTER>
              ...sum(times) filter (where action = 'action1')...
              ),
     recent_subscription (<picking latest subscription for a user>),
     titles   (<using previous cte and adding more info from info table>)

select t.user, t.id, t.subscription_starts, t.expires_at, t.title, email,
                p."action1", p."action2", p."action3 ", p."action4"
      from titles t
      join pivot1 p
...

Which correctly produces activity data of 12 months for a user in the following format:

user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4
user2 ... 1st_period_4user2 action1 action2 action3 action4
user2 ... 2nd_period_4user2 action1 action2 action3 action4
user3 ... 1st_period_4user3 action1 action2 action3 action4
user3 ... 2nd_period_4user3 action1 action2 action3 action4

etc

But the challenge is now to pivot this again to get 12periods/4actions combinations.
Could be just 12 if as below done
with json_object_aggr as (period: and then 4 actions)

 --using the piece above as another CTE called merged
 --this code does not work :(
select
        email, id, ends, subs, info,
        json_object_aggr(starts, s1,v1,p1,d1 ORDER BY starts) as P1,
        json_object_aggr(starts, s2,v2,p2,d2 ORDER BY starts) as P2,
        json_object_aggr(starts, s3,v3,p3,d3 ORDER BY starts) as P3,
        json_object_aggr(starts, s4,v4,p4,d4 ORDER BY starts) as P4,
        json_object_aggr(starts, s5,v5,p5,d5 ORDER BY starts) as P5,
        json_object_aggr(starts, s6,v6,p6,d6 ORDER BY starts) as P6,
        json_object_aggr(starts, s7,v7,p7,d7 ORDER BY starts) as P7,
        json_object_aggr(starts, s8,v8,p8,d8 ORDER BY starts) as P8,
        json_object_aggr(starts, s9,v9,p9,d9 ORDER BY starts) as P9,
        json_object_aggr(starts, s10,v10,p10,d10 ORDER BY starts) as P10,
        json_object_aggr(starts, s11,v11,p11,d11 ORDER BY starts) as P11,
        json_object_aggr(starts, s12,v12,p12,d12 ORDER BY starts) as P12
    from
            (select email, id,  starts, ends, subs, info, starts,
  sum("action1") as s1,sum("action2") as v1,sum("action3") as
  p1,sum("action4")
  as d1
              from merged
              group by email, id,  starts, ends, subs, info, starts

            ) m
    group by email, id,  starts, ends, subs, info
    order by email, id,  starts, ends, subs, info

Could this be json_object_agg for 4 actions per period?
Could I get help on how to pivot this?

Thank you.

Body:
Is there a reason that you cannot use a series of CASE conditionals that result in either 1 or 0 and then SUM() them? It would make this process much simpler.

WITH subs AS (
      SELECT s.user_id, u.email, MAX(s.sub_date) AS recent_sub_date
      FROM subscriptions s
      JOIN users u ON s.userid = u.user_id
      GROUP BY s.user_id, u.email
)
SELECT s.user_id,
       SUM(CASE WHEN f.action = 'action1' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action1,
       SUM(CASE WHEN f.action = 'action2' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action2,
       SUM(CASE WHEN f.action = 'action3' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action3,
       SUM(CASE WHEN f.action = 'action4' AND f.time <= s.recent_sub_date + INTERVAL '1 month' THEN 1 ELSE 0 END) AS period1_action4,
       SUM(CASE WHEN f.action = 'action1' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action1,
       SUM(CASE WHEN f.action = 'action2' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action2,
       SUM(CASE WHEN f.action = 'action3' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action3,
       SUM(CASE WHEN f.action = 'action4' AND f.time <= s.recent_sub_date + INTERVAL '2 months' THEN 1 ELSE 0 END) AS period2_action4,
       ...
FROM flightlog f
JOIN subs s ON s.user_id = f.user_id
WHERE f.time > s.recent_sub_date
AND f.time <= DATE_TRUNC('month', s.recent_sub_date + INTERVAL '13 months') -- end of the 12 months after sub
GROUP BY s.user_id;

NOTE: If you do not have indexes on your dates this will probably be pretty slow no matter how you write the query.


问:
How to get the exact child element with corresponding parent only from multilevel embedded MongoDB document using C#
Trying to get exact child document with it's corresponding parent document from embedded MongoDB document using C#  but query return all the child and corresponding parent and others . how to set parameter to
get the exact match with Filter and findOptions. My expected result will be Channel 1 -> Episode 1 & it's Child Track which id is given .
Here is my code:

```<code>// Class
namespace CrudWithMultilvelNestedDoc
{
    public class Channel
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Episode[] Episodes { get; set; }
    }

    public class Episode
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Track[] Tracks { get; set; }
    }

    public class Track
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Like[] Likes { get; set; }
    }

    public class Like
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

//Code
var chanelId = "5e4606e6ae7b090688671416";
var episodeId = "5e46071d385a672b0cea0f86";
var trackId = "5e460dbe2bc5e70c9cfeac21";

var filter = Builders<Channel>.Filter.And(
             Builders<Channel>.Filter.Where(x => x.Id == chanelId),
             Builders<Channel>.Filter.Eq("Episodes._id", episodeId),
             Builders<Channel>.Filter.Eq("Episodes.Tracks._id", trackId));
var result = collection.Find(filter).ToList();

// Data
{"_id":"5e4606e6ae7b090688671416","Name":"Channel 1","Episodes":[{"_id":"5e46071d385a672b0cea0f86","Name":"Episode 1","Tracks":[{"_id":"5e460dbe2bc5e70c9cfeac21","Name":"Trak 1","Likes":[{"_id":"5e4635d41f949d43a8194790","Name":"Like 1"},{"_id":"5e464e1ccfa17a25181234f6","Name":"Like 2"},{"_id":"5e464e94776dc808383326d5","Name":"Like 3"}]},{"_id":"5e4612d60747a2121870c815","Name":"Trak 2","Likes":[]}]},{"_id":"5e460851d29c1b3df4d27b7d","Name":"Episode 2","Tracks":[{"_id":"5e460e307ca6843758ce814e","Name":"Trak 1","Likes":[{"_id":"5e4686aa2813d41fa428b621","Name":"Like 1"}]}]}]}
</code>```

答:
Since your document is multilevel you have to use $filter operator. In C# it's easy to use LINQ for such query since it automatically generates $filter behind the scenes and you preserve strongly-typed query:

```<code>var q = from channel in mongoDBCollection.AsQueryable()
        from episode in channel.Episodes
        select new Episode()
        {
            Id = episode.Id,
            Name = episode.Name,
            Tracks = episode.Tracks.Where(x => x.Id == trackId)
        };

var query = q.Where(x => x.Tracks.Any());
var result = query.ToList();
</code>```

The Aggregation Pipeline that gets generated by MongoDB .NET driver looks like below:

```<code>{
    "aggregate" : "col",
    "pipeline" : [
        { "$unwind" : "$Episodes" },
        {
            "$project" : {
                "Id" : "$Episodes._id",
                "Name" : "$Episodes.Name",
                "Tracks" : {
                    "$filter" : {
                        "input" : "$Episodes.Tracks",
                        "as" : "x",
                        "cond" : { "$eq" : ["$$x._id", "5e460dbe2bc5e70c9cfeac21"] }
                    }
                },
                "_id" : 0
            }
        },
        {
            "$match" : {
                "Tracks" : {
                    "$ne" : null,
                    "$not" : { "$size" : 0 }
                }
            }
        }],
    "cursor" : { },
}
</code>```

EDIT:

To improve the performance of above query you can consider filtering on channel level by adding where statement:

```<code>from channel in mongoDBCollection.AsQueryable()
where channel.Id == channelId
</code>```

EDIT: it becomes a little bit more tricky when you want to return Channel as well. My suggestion would be to return an anomyous type which contains both Channel and Episode and combine them in memory since it will allow you to run most of filtering on the database side and get the best performance:

```<code>var q = from channel in mongoDBCollection.AsQueryable()
        where channel.Id == "5e4606e6ae7b090688671416"
        from episode in channel.Episodes
        select new
        {
            Channel = new Channel(){ Id = channel.Id, Name = channel.Name},
            Episode = new Episode()
            {
                Id = episode.Id,
                Name = episode.Name,
                Tracks = episode.Tracks.Where(x => x.Id == trackId)
            }
        };

var query = q.Where(x => x.Episode.Tracks.Any());
var result = query.ToList();
</code>```

Body:
Trying to get exact child document with it's corresponding parent document from embedded MongoDB document using C#  but query return all the child and corresponding parent and others . how to set parameter to
get the exact match with Filter and findOptions. My expected result will be Channel 1 -> Episode 1 & it's Child Track which id is given .
Here is my code:

// Class
namespace CrudWithMultilvelNestedDoc
{
    public class Channel
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Episode[] Episodes { get; set; }
    }

    public class Episode
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Track[] Tracks { get; set; }
    }

    public class Track
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Like[] Likes { get; set; }
    }

    public class Like
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

//Code
var chanelId = "5e4606e6ae7b090688671416";
var episodeId = "5e46071d385a672b0cea0f86";
var trackId = "5e460dbe2bc5e70c9cfeac21";

var filter = Builders<Channel>.Filter.And(
             Builders<Channel>.Filter.Where(x => x.Id == chanelId),
             Builders<Channel>.Filter.Eq("Episodes._id", episodeId),
             Builders<Channel>.Filter.Eq("Episodes.Tracks._id", trackId));
var result = collection.Find(filter).ToList();

// Data
{"_id":"5e4606e6ae7b090688671416","Name":"Channel 1","Episodes":[{"_id":"5e46071d385a672b0cea0f86","Name":"Episode 1","Tracks":[{"_id":"5e460dbe2bc5e70c9cfeac21","Name":"Trak 1","Likes":[{"_id":"5e4635d41f949d43a8194790","Name":"Like 1"},{"_id":"5e464e1ccfa17a25181234f6","Name":"Like 2"},{"_id":"5e464e94776dc808383326d5","Name":"Like 3"}]},{"_id":"5e4612d60747a2121870c815","Name":"Trak 2","Likes":[]}]},{"_id":"5e460851d29c1b3df4d27b7d","Name":"Episode 2","Tracks":[{"_id":"5e460e307ca6843758ce814e","Name":"Trak 1","Likes":[{"_id":"5e4686aa2813d41fa428b621","Name":"Like 1"}]}]}]}

Body:
Since your document is multilevel you have to use $filter operator. In C# it's easy to use LINQ for such query since it automatically generates $filter behind the scenes and you preserve strongly-typed query:

var q = from channel in mongoDBCollection.AsQueryable()
        from episode in channel.Episodes
        select new Episode()
        {
            Id = episode.Id,
            Name = episode.Name,
            Tracks = episode.Tracks.Where(x => x.Id == trackId)
        };

var query = q.Where(x => x.Tracks.Any());
var result = query.ToList();

The Aggregation Pipeline that gets generated by MongoDB .NET driver looks like below:

{
    "aggregate" : "col",
    "pipeline" : [
        { "$unwind" : "$Episodes" },
        {
            "$project" : {
                "Id" : "$Episodes._id",
                "Name" : "$Episodes.Name",
                "Tracks" : {
                    "$filter" : {
                        "input" : "$Episodes.Tracks",
                        "as" : "x",
                        "cond" : { "$eq" : ["$$x._id", "5e460dbe2bc5e70c9cfeac21"] }
                    }
                },
                "_id" : 0
            }
        },
        {
            "$match" : {
                "Tracks" : {
                    "$ne" : null,
                    "$not" : { "$size" : 0 }
                }
            }
        }],
    "cursor" : { },
}

EDIT:

To improve the performance of above query you can consider filtering on channel level by adding where statement:

from channel in mongoDBCollection.AsQueryable()
where channel.Id == channelId

EDIT: it becomes a little bit more tricky when you want to return Channel as well. My suggestion would be to return an anomyous type which contains both Channel and Episode and combine them in memory since it will allow you to run most of filtering on the database side and get the best performance:

var q = from channel in mongoDBCollection.AsQueryable()
        where channel.Id == "5e4606e6ae7b090688671416"
        from episode in channel.Episodes
        select new
        {
            Channel = new Channel(){ Id = channel.Id, Name = channel.Name},
            Episode = new Episode()
            {
                Id = episode.Id,
                Name = episode.Name,
                Tracks = episode.Tracks.Where(x => x.Id == trackId)
            }
        };

var query = q.Where(x => x.Episode.Tracks.Any());
var result = query.ToList();


问:
Page view in php
I have to make a small adjustment on a website, the problem comes on the page.

For example I have a page with 11 button, these 1 I do not have to show them at once, but I have for example I have to show the first 5 and then the page has to be moving but I never have to stop showing 5 results on the page.

I leave reference images:

This is the way the page does NOT have to look:

This is the way the page should look:

for example if I get to 7 that 3 is no longer shown and shows me 8

This is my code

```<code>    <nav>

    <ul class="pagination">
        <?php if ($pagina == 1) : ?>
            <li class="page-item disabled">
                <a class="page-link" href="">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php else : ?>
            <li class="page-item">
                <a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php endif; ?>

        <!---------------------------------------------------------------------->

        <?php
        for ($i = 1; $i <= $numeroDePaginas; $i++) {
            if ($pagina == $i) {
                echo "<li class='page-item active'>
        <a class='page-link' href='?pagina=$i'>$i</a>
    </li>";
            } else {
                if (($i + 2) < $pagina || ($i - 2) > $pagina) {
                    echo "<li class='page-item'>
        <a class='page-link' href='?pagina=$i'>$i</a>
        </li>";
                }
            }
        }
        ?>

        <!---------------------------------------------------------------------->

        <?php if ($pagina == $numeroDePaginas) : ?>
            <li class='page-item disabled'>
                <a class='page-link' href=''>
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php else : ?>
            <li class='page-item'>
                <a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php endif; ?>

    </ul>
</nav>
</code>```

答:
Here you go. I have added next_pages variable and previous_pages variables, which will make sure to get the pagina - 2 and pagina + 2 if exists. Let me know if you need help understanding it.

```<code>    <nav>

    <?php
    $next_pages = ($pagina + 2) <= $numeroDePaginas ? $pagina + 2 : $numeroDePaginas;
    $previous_pages = ($pagina - 2) >= 1 ? $pagina - 2 : 1;
    ?>
    <ul class="pagination">
        <?php if ($pagina == 1) : ?>
            <li class="page-item disabled">
                <a class="page-link" href="">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php else : ?>
            <li class="page-item">
                <a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php endif; ?>

        <!---------------------------------------------------------------------->

        <?php
        for ($i = $previous_pages; $i <= $next_pages; $i++) {
            if ($pagina == $i) {
                echo "<li class='page-item active'>
    <a class='page-link' href='?pagina=$i'>$i</a>
</li>";
            } else {
                     echo "<li class='page-item'>
    <a class='page-link' href='?pagina=$i'>$i</a>
    </li>";
             }
        }
        ?>

        <!---------------------------------------------------------------------->

        <?php if ($pagina == $numeroDePaginas) : ?>
            <li class='page-item disabled'>
                <a class='page-link' href=''>
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php else : ?>
            <li class='page-item'>
                <a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php endif; ?>

    </ul>
</nav>
</code>```

Edit with more explaination:

I have added a variable called next_pages, this variable checks if the current page (ex: 9) + 2 is smaller than or equal to "numeroDePaginas" variable, I have done this to make sure that we never show any pages exceeding the number of pages we have, in case 9+2 is bigger than "numeroDePaginas" we set the variable equal to "numeroDePaginas"

For the previous_pages variable, we make sure that the current page(ex: 3) - 2 is never less than 1, (so it doesn't show 0 or negative pages for example), in case

3-2 is smaller than 1, we set the variable to 1.

Now, I have edited the for loop, to make sure that it starts from the previous_pages variable, and ends with next_pages variable.

Here are a test case:

```<code>$pagina = 7;
$numeroDePaginas = 9;

//$next_pages will be = 9  (i.e 7+2)
//$previous_pages will be = 5 (i.e 7-2)
</code>```

for loop would print pages from 5 to 9.

Title: Page view in php

Body:
I have to make a small adjustment on a website, the problem comes on the page.

For example I have a page with 11 button, these 1 I do not have to show them at once, but I have for example I have to show the first 5 and then the page has to be moving but I never have to stop showing 5 results on the page.

I leave reference images:

This is the way the page does NOT have to look:

This is the way the page should look:

for example if I get to 7 that 3 is no longer shown and shows me 8

This is my code

        <?php if ($pagina == 1) : ?>

        <?php else : ?>

                <a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">

        <?php endif; ?>

        <?php
        for ($i = 1; $i <= $numeroDePaginas; $i++) {
            if ($pagina == $i) {
                echo "

        $i

";
            } else {
                if (($i + 2) < $pagina || ($i - 2) > $pagina) {
                    echo "

        $i

";
                }
            }
        }
        ?>

        <?php if ($pagina == $numeroDePaginas) : ?>

        <?php else : ?>

                <a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">

        <?php endif; ?>

Body:
Here you go. I have added next_pages variable and previous_pages variables, which will make sure to get the pagina - 2 and pagina + 2 if exists. Let me know if you need help understanding it.

    <nav>

    <?php
    $next_pages = ($pagina + 2) <= $numeroDePaginas ? $pagina + 2 : $numeroDePaginas;
    $previous_pages = ($pagina - 2) >= 1 ? $pagina - 2 : 1;
    ?>
    <ul class="pagination">
        <?php if ($pagina == 1) : ?>
            <li class="page-item disabled">
                <a class="page-link" href="">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php else : ?>
            <li class="page-item">
                <a class="page-link" href="?pagina=<?php echo $pagina - 1 ?>">
                    <span class="ti-arrow-left"></span>
                </a>
            </li>
        <?php endif; ?>

        <!---------------------------------------------------------------------->

        <?php
        for ($i = $previous_pages; $i <= $next_pages; $i++) {
            if ($pagina == $i) {
                echo "<li class='page-item active'>
    <a class='page-link' href='?pagina=$i'>$i</a>
</li>";
            } else {
                     echo "<li class='page-item'>
    <a class='page-link' href='?pagina=$i'>$i</a>
    </li>";
             }
        }
        ?>

        <!---------------------------------------------------------------------->

        <?php if ($pagina == $numeroDePaginas) : ?>
            <li class='page-item disabled'>
                <a class='page-link' href=''>
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php else : ?>
            <li class='page-item'>
                <a class='page-link' href="?pagina=<?php echo $pagina + 1 ?>">
                    <span class='ti-arrow-right'></span>
                </a>
            </li>
        <?php endif; ?>

    </ul>
</nav>

Edit with more explaination:

I have added a variable called next_pages, this variable checks if the current page (ex: 9) + 2 is smaller than or equal to "numeroDePaginas" variable, I have done this to make sure that we never show any pages exceeding the number of pages we have, in case 9+2 is bigger than "numeroDePaginas" we set the variable equal to "numeroDePaginas"

For the previous_pages variable, we make sure that the current page(ex: 3) - 2 is never less than 1, (so it doesn't show 0 or negative pages for example), in case

3-2 is smaller than 1, we set the variable to 1.

Now, I have edited the for loop, to make sure that it starts from the previous_pages variable, and ends with next_pages variable.

Here are a test case:

$pagina = 7;
$numeroDePaginas = 9;

//$next_pages will be = 9  (i.e 7+2)
//$previous_pages will be = 5 (i.e 7-2)

for loop would print pages from 5 to 9.


问:
Using a hierarchy from one table to another
!]1

Hi I am doing a graph with data from one table , I would like to use in the filter a hierarchy from another table but I don't know how to do it.
Anyway could help? I just begin in Power BI

答:
It looks like you already have a relationship established between the two tables. If you just want to use the fields within the hierarchy as a filter, you can drag and drop the fields into the filter pane and use it there. If you want to use a slicer and the entire hierarchy, you would have to use the "Hierarchy Slicer" from the marketplace. If you haven't imported visuals from the marketplace before, you can do it by clicking on the three dots (...) at the end of the "Visualizations" pane and selecting "Import from marketplace". Then search for Hierarchy slicer and import it.

https://appsource.microsoft.com/en-us/product/power-bi-visuals/WA104380820?tab=Overview

Hope this helps.


问:
Reduce the oracle PL/SQL statement
I am a new in PL/SQL. After hours of learning, I have some
I have a few curious questions. Example I have a SQL statement like this:

```<code>SELECT ShipperName, OrderID, NumberOfOrders, ...
FROM Orders
</code>```

Can we declare a variable that hold the "list select" like list_select = 'ShipperName, OrderID, NumberOfOrders, ... '
And then replace the select statement with the "list select" we was declared?

```<code>SELECT list_select
FROM Orders
</code>```

And other question, Can we reduce the SQL statement like the Image . I was try this in Oracle SQL Developer, the compiler is ok but when I ran the test I was got an error "by segment".

Any help is appreciated and thank for help.

答:
For your second question: You don't want joins here, because you only select from table1. You rather want [NOT] EXISTS or [NOT] IN. E.g.:

```<code>SELECT orderid, clientid
FROM orders o
WHERE EXISTS -- We are looking for orders containing expensive items
(
  SELECT null
  FROM orderposition op
  WHERE op.orderid = o.orderid
  AND op.price > 1000
)
AND -- and the client ...
(
  NOT EXISTS -- ... must have paid all their invoices (there exists no unpaid invoice)
  (
    SELECT null
    FROM invoices i
    WHERE i.clientid = o.clientid
    AND i.paid_date IS NULL
  )
  OR clientid IN -- ... or be known as reliable client (they are in the set of reliable ones)
  (
    SELECT c.clientid
    FROM clients c
    WHERE c.reliable = 'YES'
  )
);
</code>```

Title: Reduce the oracle PL/SQL statement

Body:
I am a new in PL/SQL. After hours of learning, I have some
I have a few curious questions. Example I have a SQL statement like this:

SELECT ShipperName, OrderID, NumberOfOrders, ...
FROM Orders

Can we declare a variable that hold the "list select" like list_select = 'ShipperName, OrderID, NumberOfOrders, ... '
And then replace the select statement with the "list select" we was declared?

SELECT list_select
FROM Orders

And other question, Can we reduce the SQL statement like the Image . I was try this in Oracle SQL Developer, the compiler is ok but when I ran the test I was got an error "by segment".

Any help is appreciated and thank for help.

Body:
For your second question: You don't want joins here, because you only select from table1. You rather want [NOT] EXISTS or [NOT] IN. E.g.:

SELECT orderid, clientid
FROM orders o
WHERE EXISTS -- We are looking for orders containing expensive items
(
  SELECT null
  FROM orderposition op
  WHERE op.orderid = o.orderid
  AND op.price > 1000
)
AND -- and the client ...
(
  NOT EXISTS -- ... must have paid all their invoices (there exists no unpaid invoice)
  (
    SELECT null
    FROM invoices i
    WHERE i.clientid = o.clientid
    AND i.paid_date IS NULL
  )
  OR clientid IN -- ... or be known as reliable client (they are in the set of reliable ones)
  (
    SELECT c.clientid
    FROM clients c
    WHERE c.reliable = 'YES'
  )
);


问:
Action cable unable to connect (Failed to upgrade to WebSocket )
I am having a issue in connecting to websocket in non-development environments with these log messages

```<code>Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )

Finished "/cable/"[non-WebSocket] for 127.0.0.1 at 2016-07-06 09:44:29 +1000
</code>```

I debuggged a little and figured out the request sent by the browser/javascript is not exactly the same as the request received by unicorn(running with nginx).

The request header by the browser is

```<code>GET ws://cc-uat.com.au/cable HTTP/1.1
Host: cc-uat.com.au
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://cc-uat.com.au
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: <Lot of cookies>
Sec-WebSocket-Key: QGdJkYIA2u7vtmMVXfHKtQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: actioncable-v1-json, actioncable-unsupported
</code>```

The connection here is 'upgrade' but the websocket request has the connection 'closed'(probably nginx is messing it up?)

And this piece of code in websocket driver is failing

```<code>def self.websocket?(env)
      connection = env['HTTP_CONNECTION'] || ''
      upgrade    = env['HTTP_UPGRADE']    || ''

      env['REQUEST_METHOD'] == 'GET' and
      connection.downcase.split(/ *, */).include?('upgrade') and
      upgrade.downcase == 'websocket'
end
</code>```

Updates

This is my nginx configuration

```<code>upstream app {
    server unix:/home/osboxes/sites/actioncable-examples/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/osboxes/sites/actioncable-example/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}
</code>```

I have mounted actioncable server on /cable

```<code>mount ActionCable.server => "/cable"
</code>```

With the nginx changes i am able to successfully have the handshake but the server is not able to send the heart beats and the connection keeps dropping.

```<code>Started GET "/cable" for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)
</code>```

答: Thanks to above answer i was getting the similar error. Issue was that i kept backend url address in config.action_cable.allowed_request_origins on changing it to frontend url issue got resolved. To be more clear i am having font-end,backend in entirely different domains

Body:
I am having a issue in connecting to websocket in non-development environments with these log messages

Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: close, HTTP_UPGRADE: )

Finished "/cable/"[non-WebSocket] for 127.0.0.1 at 2016-07-06 09:44:29 +1000

I debuggged a little and figured out the request sent by the browser/javascript is not exactly the same as the request received by unicorn(running with nginx).

The request header by the browser is

GET ws://cc-uat.com.au/cable HTTP/1.1
Host: cc-uat.com.au
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: http://cc-uat.com.au
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: <Lot of cookies>
Sec-WebSocket-Key: QGdJkYIA2u7vtmMVXfHKtQ==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Protocol: actioncable-v1-json, actioncable-unsupported

The connection here is 'upgrade' but the websocket request has the connection 'closed'(probably nginx is messing it up?)

And this piece of code in websocket driver is failing

def self.websocket?(env)
      connection = env['HTTP_CONNECTION'] || ''
      upgrade    = env['HTTP_UPGRADE']    || ''

      env['REQUEST_METHOD'] == 'GET' and
      connection.downcase.split(/ *, */).include?('upgrade') and
      upgrade.downcase == 'websocket'
end

Updates

This is my nginx configuration

upstream app {
    server unix:/home/osboxes/sites/actioncable-examples/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/osboxes/sites/actioncable-example/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "upgrade";
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

I have mounted actioncable server on /cable

mount ActionCable.server => "/cable"

With the nginx changes i am able to successfully have the handshake but the server is not able to send the heart beats and the connection keeps dropping.

Started GET "/cable" for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2016-07-07 05:48:06 +0100
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: upgrade, HTTP_UPGRADE: websocket)


问:
How to store 300M records in Postgresql to run efficiency queries
I have following table:

```<code>CREATE TABLE public.shop_prices
(
    shop_name text COLLATE pg_catalog."default",
    product text COLLATE pg_catalog."default",
    product_category text COLLATE pg_catalog."default",
    price text COLLATE pg_catalog."default"
)
</code>```

and for this table i have a dataset from 18 months. In each file there are about 15M records. I have to some analysis, like in which month a shop has increased or decreased their price. I imported two months in a table and run following query just to test:

```<code>select shop, product from shop_prices group by shop, product limit 10
</code>```

I waited more than 5 minutes, but no any result and response. It was still on working. What is the best way the store these datasets and run efficiency queries? Is it a good idea if I create for each dataset a seperate tables?

答:
Using explain analyze select shop_name, product from shop_prices group by shop, product limit 10 you can see how Postgres is planning and executing the query and the time the execution takes.  You'll see it needs to read the whole table (with the time consuming disk reads) and then sort it in memory - which will probably need to be cached on disk, before returning the results.  In the next run you might discover the same query is very snappy if the number of shop_name+product combinations are very limited and thus stored in pg_stats after that explain analyze.  The point being that a simple query like this can be deceiving.

You will faster execution by creating an index on the columns you are using (create index shop_prices_shop_prod_idx on public.shop_prices(shop_name,product)).

You should definitely change the price column type to numeric (or float/float8)) if you plan to do any numerical calculations on it.

Having said all that, I suspect this table is not what you will be using as it does not have any timestamp to compare prices between months to begin with.

I suggest you complete the table design and speculate on indices to improve performance.  You might even want consider table partitioning https://www.postgresql.org/docs/current/ddl-partitioning.html

You will probably be doing all sorts of queries on this data so there is no simple solution to them all.

By all means return with perhaps more specific questions with complete table description and the output from the explain analyze statement for queries you are trying out and get some good advice.

Best regards,

Bjarni

Body:
I have following table:

CREATE TABLE public.shop_prices
(
    shop_name text COLLATE pg_catalog."default",
    product text COLLATE pg_catalog."default",
    product_category text COLLATE pg_catalog."default",
    price text COLLATE pg_catalog."default"
)

and for this table i have a dataset from 18 months. In each file there are about 15M records. I have to some analysis, like in which month a shop has increased or decreased their price. I imported two months in a table and run following query just to test:

select shop, product from shop_prices group by shop, product limit 10

I waited more than 5 minutes, but no any result and response. It was still on working. What is the best way the store these datasets and run efficiency queries? Is it a good idea if I create for each dataset a seperate tables?


问:
Reactjs "Error: ENOENT: no such file or directory, open.." after converting jsx file to tsx
I have a create-react-app app and I am translation files from jsx to typescript. For example, one file is called /code/app_react/src/common/Action.jsx and I renamed it to /code/app_react/src/common/Action.tsx. I made the necessary changes to successfully convert it to tsx, but I am getting an error related to the name change:

./src/common/Action.jsx Error: ENOENT: no such file or
  directory, open
  '/code/src/common/Action.jsx'

rebuilding the does not help

for some reason, the old version of the file is expected

The file importing this file is a jsx file, but now I am importing a tsx file into it.

This is a CRA app, so is there a correct way to clear this error?

SOLUTION:
I had to remove them from the git repository, using the git rm command, like this:

```<code>git rm /code/src/common/Action.jsx
</code>```

Once I did that, it removed the jsx from the committed files and then I was able to use the new tsx files

答: Killed my yarn process running, killed vscode, re-started both and it works</p>

Body:
I have a create-react-app app and I am translation files from jsx to typescript. For example, one file is called /code/app_react/src/common/Action.jsx and I renamed it to /code/app_react/src/common/Action.tsx. I made the necessary changes to successfully convert it to tsx, but I am getting an error related to the name change:

./src/common/Action.jsx Error: ENOENT: no such file or
  directory, open
  '/code/src/common/Action.jsx'

rebuilding the does not help

for some reason, the old version of the file is expected

The file importing this file is a jsx file, but now I am importing a tsx file into it.

This is a CRA app, so is there a correct way to clear this error?

SOLUTION:
I had to remove them from the git repository, using the git rm command, like this:

git rm /code/src/common/Action.jsx

Once I did that, it removed the jsx from the committed files and then I was able to use the new tsx files


问:
tokenizer.texts_to_sequences Keras Tokenizer gives almost all zeros
I am working to create a text classification code but I having problems in encoding documents using the tokenizer.

1) I started by fitting a tokenizer on my document as in here:

```<code>vocabulary_size = 20000
tokenizer = Tokenizer(num_words= vocabulary_size, filters='')
tokenizer.fit_on_texts(df['data'])
</code>```

2) Then I wanted to check if my data is fitted correctly so I converted into sequence as in here:

```<code>sequences = tokenizer.texts_to_sequences(df['data'])
data = pad_sequences(sequences, maxlen= num_words)
print(data)
</code>```

which gave me fine output. i.e. encoded words into numbers

```<code>[[ 9628  1743    29 ...   161    52   250]
 [14948     1    70 ...    31   108    78]
 [ 2207  1071   155 ... 37607 37608   215]
 ...
 [  145    74   947 ...     1    76    21]
 [   95 11045  1244 ...   693   693   144]
 [   11   133    61 ...    87    57    24]]
</code>```

Now, I wanted to convert a text into a sequence using the same method.
Like this:

```<code>sequences = tokenizer.texts_to_sequences("physics is nice ")
text = pad_sequences(sequences, maxlen=num_words)
print(text)
</code>```

it gave me weird output:

```<code>[[   0    0    0    0    0    0    0    0    0  394]
 [   0    0    0    0    0    0    0    0    0 3136]
 [   0    0    0    0    0    0    0    0    0 1383]
 [   0    0    0    0    0    0    0    0    0  507]
 [   0    0    0    0    0    0    0    0    0    1]
 [   0    0    0    0    0    0    0    0    0 1261]
 [   0    0    0    0    0    0    0    0    0    0]
 [   0    0    0    0    0    0    0    0    0 1114]
 [   0    0    0    0    0    0    0    0    0    1]
 [   0    0    0    0    0    0    0    0    0 1261]
 [   0    0    0    0    0    0    0    0    0  753]]
</code>```

According to Keras documentation (Keras):

texts_to_sequences(texts)

Arguments: texts: list of texts to turn to sequences.

Return: list of
  sequences (one per text input).

is it not supposed to encode each word to its corresponding number? then pad the text if it shorter than 50 to 50?
Where is the mistake ?

答:
You should call the method like this:</p>

```<code>new_sample = ['A new sample to be classified']
seq = tokenizer.texts_to_sequences(new_sample )
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = model.predict(padded)
</code>```

Body:
I am working to create a text classification code but I having problems in encoding documents using the tokenizer.

1) I started by fitting a tokenizer on my document as in here:

vocabulary_size = 20000
tokenizer = Tokenizer(num_words= vocabulary_size, filters='')
tokenizer.fit_on_texts(df['data'])

2) Then I wanted to check if my data is fitted correctly so I converted into sequence as in here:

sequences = tokenizer.texts_to_sequences(df['data'])
data = pad_sequences(sequences, maxlen= num_words)
print(data)

which gave me fine output. i.e. encoded words into numbers

[[ 9628  1743    29 ...   161    52   250]
 [14948     1    70 ...    31   108    78]
 [ 2207  1071   155 ... 37607 37608   215]
 ...
 [  145    74   947 ...     1    76    21]
 [   95 11045  1244 ...   693   693   144]
 [   11   133    61 ...    87    57    24]]

Now, I wanted to convert a text into a sequence using the same method.
Like this:

sequences = tokenizer.texts_to_sequences("physics is nice ")
text = pad_sequences(sequences, maxlen=num_words)
print(text)

it gave me weird output:

[[   0    0    0    0    0    0    0    0    0  394]
 [   0    0    0    0    0    0    0    0    0 3136]
 [   0    0    0    0    0    0    0    0    0 1383]
 [   0    0    0    0    0    0    0    0    0  507]
 [   0    0    0    0    0    0    0    0    0    1]
 [   0    0    0    0    0    0    0    0    0 1261]
 [   0    0    0    0    0    0    0    0    0    0]
 [   0    0    0    0    0    0    0    0    0 1114]
 [   0    0    0    0    0    0    0    0    0    1]
 [   0    0    0    0    0    0    0    0    0 1261]
 [   0    0    0    0    0    0    0    0    0  753]]

According to Keras documentation (Keras):

texts_to_sequences(texts)

Arguments: texts: list of texts to turn to sequences.

Return: list of
  sequences (one per text input).

is it not supposed to encode each word to its corresponding number? then pad the text if it shorter than 50 to 50?
Where is the mistake ?

Body:
You should call the method like this:

new_sample = ['A new sample to be classified']
seq = tokenizer.texts_to_sequences(new_sample )
padded = pad_sequences(seq, maxlen=MAX_SEQUENCE_LENGTH)
pred = model.predict(padded)


问:
jQuery, optimal usage question
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

```<code>var thingy = $('#thingy');
</code>```

Further down in the code, is there any difference in reusing thingy:

```<code>thingy.empty();
</code>```

versus just making the jQuery again? :

```<code>$('#thingy').empty();
</code>```

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.

答:
It's not so bad if your selector is a single object, but what if your selector is $('.thingy')?  Each time you create it again, it iterates the entire doc looking for that class, rather than using the stored selection.  Not so bad, but then it creates a new DOM object for that selection.  If there's 500 instances of .thingy, that can get really bogged down really quick.

ETA: as no.good.at.coding points out, every time you use a selector of any sort, the entire DOM is traversed.  So yup - store it in a variable, call the variable.

Title: jQuery, optimal usage question

Body:
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

var thingy = $('#thingy');

Further down in the code, is there any difference in reusing thingy:

thingy.empty();

versus just making the jQuery again? :

$('#thingy').empty();

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.


问:
Create a global variable in TypeScript
In JavaScript I can just do this:

```<code> something = 'testing';
</code>```

And then in another file:

```<code> if (something === 'testing')
</code>```

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

```<code>interface Window { something: string; }
</code>```

Then in my main.ts file:

```<code> window.something = 'testing';
</code>```

then in another file:

```<code> if (window.something  === 'testing')
</code>```

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

答:
I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

```<code>import * as lodash from 'lodash';

(global as any)._ = lodash;
</code>```

Title: Create a global variable in TypeScript

Body:
In JavaScript I can just do this:

 something = 'testing';

And then in another file:

 if (something === 'testing')

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

interface Window { something: string; }

Then in my main.ts file:

 window.something = 'testing';

then in another file:

 if (window.something  === 'testing')

And this works.  But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application.  I want to be able to call log.Debug from any file without having to import and create objects.)

Body:
I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

import * as lodash from 'lodash';

(global as any)._ = lodash;


问:
How to solve problem with Two Date Fields and multiple cases
I have two tables

```<code>(CREATE TABLE ta_product_discount_details(
  RowID int(10) NOT NULL AUTO_INCREMENT,
  DiscountID int(11) DEFAULT NULL,
  SKU varchar(50) DEFAULT NULL,
  FromDate date DEFAULT NULL,
  ToDate date DEFAULT NULL,
  Price double DEFAULT,
  Timestamp timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (RowID)
)
</code>```

and
anotheer temp table with the same structure that i use as a temp table to insert new rows.

Now, my problem is this:

For example:
In main list i have Product1 with Discount Price that goes active between two dates (FromDate, ToDate). Everything is OK by far.
But, when i create another list with the same product but different dates, i want do "disable" the first product but the problem is when i start checking dates which one is bigger so price from that list is Enabled. It is hard to explain everything because we could have multiple cases:

Example

What if the first list is like this

FromDate: 02/14/2020, ToDate: 06/24/2020.

And then the second list is created like this -

FromDate: 02/16/2020, ToDate: 06/30/2020.....

and much more cases like this one.

Please help if someone knows what shoul i do.
By the way, i am using MySQL 5.6.

答: Yes, but when i insert new product i want to “disable” previous prices. And oh, i forgot to mention that also i need to update prices for each marketplace. So, if the list is created for Amazon DE, and the second list is for Amazon DE also, than update only the prices that belongs to the list of marketplace. </p>

Body:
I have two tables

(CREATE TABLE ta_product_discount_details(
  RowID int(10) NOT NULL AUTO_INCREMENT,
  DiscountID int(11) DEFAULT NULL,
  SKU varchar(50) DEFAULT NULL,
  FromDate date DEFAULT NULL,
  ToDate date DEFAULT NULL,
  Price double DEFAULT,
  Timestamp timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (RowID)
)

and
anotheer temp table with the same structure that i use as a temp table to insert new rows.

Now, my problem is this:

For example:
In main list i have Product1 with Discount Price that goes active between two dates (FromDate, ToDate). Everything is OK by far.
But, when i create another list with the same product but different dates, i want do "disable" the first product but the problem is when i start checking dates which one is bigger so price from that list is Enabled. It is hard to explain everything because we could have multiple cases:

Example

What if the first list is like this

FromDate: 02/14/2020, ToDate: 06/24/2020.

And then the second list is created like this -

FromDate: 02/16/2020, ToDate: 06/30/2020.....

and much more cases like this one.

Please help if someone knows what shoul i do.
By the way, i am using MySQL 5.6.


问:
What is the rough "Cost" of a Thread in CPU cycles and memory?
What is the rough "cost" of using threads in java? Are the any rule of thumbs/empirical values, how much memory the creation of one thread costs? Is there a rough estimate how many CPU cycles it costs to create a thread?

Context: In a servlet of a webapplication I want to parallelize the content creation as parts of the content are file based, database based as well as webservices based. But this would mean that for every "http-request-thread" (of my serlvet container) I will have two-to-four additional threads. Note that I will be using the ExecutorService in Java 6.

What should I expect when I use hundreds to thousands of Java threads on a web-server?

答:
During preparation of a magazine article about Fibers (aka project loom) I run some simple tests (Windows 10, JDK-Loom 15.b3):

```<code>AtomicInteger counter = new AtomicInteger(T);
AtomicBoolean go = new AtomicBoolean(false);
for (int i = 0; i < 10000; i++) {
  Thread.newThread(Thread.VIRTUAL, () -> { // <-- remove Thread.VIRTUAL for plain Threads
    while (!go.get()) Thread.sleep(1);
    counter.decrementAndGet();
  }).start();
}
</code>```

My Windows desktop (i7-8700K) needs about 400000 ms to create all the 10000 threads and additional 200 ms to run the counter down.

Surprisingly I could not confirm the memory consumption of 512k per thread (1Mb according to some other sources). Windows memory monitor shows additional memory consumption of only about 500Mb for all the 10000 threads (50k per thread)

Project Loom Fibers manage to run the test in 30 respectively 50 ms and show no measurable memory consumption.

Body:
During preparation of a magazine article about Fibers (aka project loom) I run some simple tests (Windows 10, JDK-Loom 15.b3):

AtomicInteger counter = new AtomicInteger(T);
AtomicBoolean go = new AtomicBoolean(false);
for (int i = 0; i < 10000; i++) {
  Thread.newThread(Thread.VIRTUAL, () -> { // <-- remove Thread.VIRTUAL for plain Threads
    while (!go.get()) Thread.sleep(1);
    counter.decrementAndGet();
  }).start();
}

My Windows desktop (i7-8700K) needs about 400000 ms to create all the 10000 threads and additional 200 ms to run the counter down.

Surprisingly I could not confirm the memory consumption of 512k per thread (1Mb according to some other sources). Windows memory monitor shows additional memory consumption of only about 500Mb for all the 10000 threads (50k per thread)

Project Loom Fibers manage to run the test in 30 respectively 50 ms and show no measurable memory consumption.