问:
Click button doing the same as the CTRL-V event
I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

```<code>@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>
</code>```

答:
On CTRL-V you get event of type ClipboardEvent which has clipboardData on it. While your click event is of type MouseEvent which has no clipboardData on it.

I've created a stackblitz demo to reproduce it , you can try for yourself.

Body:
I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>


来源: stackexchange

问:
Tsql: LOWERCASE using with IN
I have a question concerning the lower function.

```<code>,case when lower(replace(producttitle, ‘ ‘, ‘‘)) in (‘microphone‘) then ‘YES‘ else ‘NO‘ end
</code>```

The statement above does select only YES, when column value = value in the IN function.

I want to get a YES when the value such as it is written in the IN function. When the column value is ‘Microphone‘, i want to get it lowercase —> microphone and because the IN containts ‘microphone‘, I should get a YES, right?

When the column value is Microphone (upper B), why do I not get it lower? Such as in the IN function.

Example: column value: ‘Microphone‘
I want to get a YES by making the column value lower and because the IN function contains the value (‘microphone‘)

Thank you

答:
You need to change the collation to make it case sensitive, by default it is case insensitive :

```<code>CASE WHEN REPLACE(producttitle, ' ', '') = 'microphone' COLLATE SQL_Latin1_General_CP1_CS_AS
     THEN 'YES' ELSE 'NO'
END
</code>```

ContentLicense: CC BY-SA 4.0

Title: Tsql: LOWERCASE using with IN

Body:
I have a question concerning the lower function.

,case when lower(replace(producttitle, ‘ ‘, ‘‘)) in (‘microphone‘) then ‘YES‘ else ‘NO‘ end

The statement above does select only YES, when column value = value in the IN function.

I want to get a YES when the value such as it is written in the IN function. When the column value is ‘Microphone‘, i want to get it lowercase —> microphone and because the IN containts ‘microphone‘, I should get a YES, right?

When the column value is Microphone (upper B), why do I not get it lower? Such as in the IN function.

Example: column value: ‘Microphone‘
I want to get a YES by making the column value lower and because the IN function contains the value (‘microphone‘)

Thank you

Body:
You need to change the collation to make it case sensitive, by default it is case insensitive :

CASE WHEN REPLACE(producttitle, ' ', '') = 'microphone' COLLATE SQL_Latin1_General_CP1_CS_AS
     THEN 'YES' ELSE 'NO'
END


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
```<code>sed -n '2p' < file.txt
</code>```

will print 2nd line

```<code>sed -n '2011p' < file.txt
</code>```

2011th line

```<code>sed -n '10,33p' < file.txt
</code>```

line 10 up to line 33

```<code>sed -n '1p;3p' < file.txt
</code>```

1st and 3th line

and so on...

For adding lines with sed, you can check this:

sed: insert a line in a certain position

ContentLicense: CC BY-SA 3.0

Title: Bash tool to get nth line from a file

Body:
sed -n '2p' < file.txt

will print 2nd line

sed -n '2011p' < file.txt

2011th line

sed -n '10,33p' < file.txt

line 10 up to line 33

sed -n '1p;3p' < file.txt

1st and 3th line

and so on...

For adding lines with sed, you can check this:

sed: insert a line in a certain position


问:
How Can i Implements 2FA(using OTP) in Strapi?
Is it Possible to Implements 2FA In Strapi? if yes then I want to Implements 2FA In My Strapi CMS How can I Do Anyone helps me.

I'm trying with that with lots of time.

But it's not working partially.

For frontend override it's work, but backend it does not work.

Exactly  I Want to modify our admin /auth/local routes in https://github.com/strapi/strapi/blob/master/packages/strapi-admin/config/routes.json.

I want to add one extra check for recatch validation  for handler: "Auth.callback" in  https://github.com/strapi/strapi/blob/master/packages/strapi-admin/controllers/Auth.js

答:
If you want to add this feature in your admin panel, you will have to customize it.

To do so, you will have to use the customization concept

https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html

The Admin extension is the part you will have to use.

https://github.com/strapi/strapi/tree/master/packages/strapi-admin/admin/src/containers/AuthPage

After that, I suggest you add a new endpoint that will send a validate your code.
You will have to check route and controller documentation.

This is really similar to this question:

Check Password in ContentType Controller

Here is a video that could help you:

https://www.loom.com/share/990d3f842ded4a879b27c0e77c5ac340


问:
Automation Testing of Spark pipeline in parallel
I need to check what are the technology options, we use for automation testing (QA) for the data engineering pipeline in Spark.

Problem Statement : To optimise functional testing of BigData spark job effectively through automation. Need to check effective data creation and validation with running the scenarios in parallel

答:
There are no automation testing tool/technology available to test data pipeline.

However,You can create a custom spark framework to perform data validation in different data zones(L0,L1,L2 etc..)

Spark can read different types of data(csv,xml,json,text,parquet,etc..) into dataframe.

And you can derive a logic to compare between two dataframes.


问:
Select min date value and calculate date value?
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

```<code>    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>
            <table class="table">
                <thead>
                    <tr>
                        <th>IN</th>
                        <th>OUT</th>
                        <th>LATECOME</th>
                    </tr>
                </thead>
                <tbody>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("STATUSIN") %></td>
                <td><%# Eval("STATUSOUT") %></td>
                <td><%# Eval("LATECOME") %></td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
                </tbody>
            </table>
        </FooterTemplate>
    </asp:Repeater>
</code>```

This is my code on backend:

```<code>     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }
</code>```

答:
```<code>select DATEADD(minute, -iif(CAST(STATUSIN as time) > CAST('08:00' as time), DATEDIFF(MINUTE,CAST('08:00' as time),CAST(STATUSIN as time)) ,0) , STATUSIN) as LATECOME
from SUMMARYDATA
</code>```

Body:
I have a table called "SUMMARYDATA" which has columns "STATUSIN,STATUSOUT,LATECOME" and I want to select min value on column "STATUSIN". And make a condition: IF MIN(STATUSIN) > "08.00 AM" Then LATECOME = MIN(STATUSIN) - "08.00 AM". How to select min date value? And how to calculate MIN(STATUSIN) - "08.00 AM"?

This is my code to display data from database:

    <asp:Repeater ID="rptrSUMMARYDATA" runat="server">
        <HeaderTemplate>

                        IN
                        OUT
                        LATECOME

        </HeaderTemplate>
        <ItemTemplate>

                <%# Eval("STATUSIN") %>
                <%# Eval("STATUSOUT") %>
                <%# Eval("LATECOME") %>

        </ItemTemplate>
        <FooterTemplate>

        </FooterTemplate>
    </asp:Repeater>

This is my code on backend:

     private void BindSUMMARYDATARptr()
    {
        String CS = ConfigurationManager.ConnectionStrings["MANHOURConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM SUMMARYDATA", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dtDaily = new DataTable();
                    sda.Fill(dtDaily);

                    rptrSUMMARYDATA.DataSource = dtDaily;
                    rptrSUMMARYDATA.DataBind();
                }

            }

        }
    }


问:
Laravel view foreach with two properties
i need help with my foreach loop in view

Controller.php

```<code>$expenses = Expense::groupBy('category_id')->selectRaw('sum(amount) as sum, category_id')->pluck('sum','category_id');

$categories = Category::all();

return view('dashboard.index', compact('expenses','categories'));
</code>```

index.php

```<code>          <table class="table">
            <thead>
              <th>Category</th>
              <th>Expenses</th>
            </thead>
            <tbody>
              @foreach($categories as $category)
              <tr>
                <td>{{ $category->name }}</td>
                @foreach($expenses as $expense)
              <td>{{ $expense }}</td>
              @endforeach
              </tr>
              @endforeach
            </tbody>
          </table>
</code>```

I get the output like this.

enter image description here

It outputs the expense 2 times, is there a limiter for "foreach loop" or is there another way on doing this?

答:
You need to add a condition for that $category->id is the same as category_id

```<code> @foreach($expenses as $key => $expense)
    @if($key == $category->id)
    <td>{{ $expense }}</td>
    @endif
@endforeach
</code>```

The right way to do it is by using join or relationship.

```<code>$expenses = Expense::join('categories','categories.category_id','expenses.category_id')->groupBy('expenses.category_id')->selectRaw('sum(expenses.amount) as sum, expenses.category_id','categories.name')->get();

<table class="table">
    <thead>
      <th>Category</th>
      <th>Expenses</th>
    </thead>
    <tbody>

         @foreach($expenses as $expense)
          <th>{{ $expense->name }}</th>
          <td>{{ $expense->sum }}</td>
         @endforeach
  </tbody>
</table>
</code>```

Body:
i need help with my foreach loop in view

Controller.php

$expenses = Expense::groupBy('category_id')->selectRaw('sum(amount) as sum, category_id')->pluck('sum','category_id');

$categories = Category::all();

return view('dashboard.index', compact('expenses','categories'));

index.php

              Category
              Expenses

              @foreach($categories as $category)

                {{ $category->name }}
                @foreach($expenses as $expense)
              {{ $expense }}
              @endforeach

              @endforeach

I get the output like this.

enter image description here

It outputs the expense 2 times, is there a limiter for "foreach loop" or is there another way on doing this?

Body:
You need to add a condition for that $category->id is the same as category_id

 @foreach($expenses as $key => $expense)
    @if($key == $category->id)
    <td>{{ $expense }}</td>
    @endif
@endforeach

The right way to do it is by using join or relationship.

$expenses = Expense::join('categories','categories.category_id','expenses.category_id')->groupBy('expenses.category_id')->selectRaw('sum(expenses.amount) as sum, expenses.category_id','categories.name')->get();

<table class="table">
    <thead>
      <th>Category</th>
      <th>Expenses</th>
    </thead>
    <tbody>

         @foreach($expenses as $expense)
          <th>{{ $expense->name }}</th>
          <td>{{ $expense->sum }}</td>
         @endforeach
  </tbody>
</table>


问:
Automate "yes" to Popen SSH command
Hi i am writing a C++ program to automate SSH connection to an AWS instance with the popen function.

```<code>void initiate_ssh(char ip[100]){

char ssh[250];
FILE* fp;
strcpy(ssh,"ssh -i theKey.pem ec2-user@");
strcat(ssh,ip);
fp=popen(ssh,"w");
if(fp){
 // respond yes automatically
    }
pclose(fp);

}
</code>```

I have searched through numerous threads but i can only find similar situations in python but i am not too familiar with python. So i need to automatically pipe "yes" to the popen  in order to get access remote access to the instance.

答:
Here we see an "XY problem". You want to automatically accept host keys (this is "X"). You think that you can do that by automatically typing "yes" at the prompt (this is "Y"). You are stuck on that, so you ask how to do Y. But there is an even easier way to do X.

Here's how to do X:

add the option -o StrictHostKeyChecking=no to your SSH command.

```<code>strcpy(ssh,"ssh -o StrictHostKeyChecking=no -i theKey.pem ec2-user@");
//              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

I assume the ssh buffer is already long enough to contain this extra option.

Title: Automate "yes" to Popen SSH command

Body:
Hi i am writing a C++ program to automate SSH connection to an AWS instance with the popen function.

void initiate_ssh(char ip[100]){

char ssh[250];
FILE* fp;
strcpy(ssh,"ssh -i theKey.pem ec2-user@");
strcat(ssh,ip);
fp=popen(ssh,"w");
if(fp){
 // respond yes automatically
    }
pclose(fp);

}

I have searched through numerous threads but i can only find similar situations in python but i am not too familiar with python. So i need to automatically pipe "yes" to the popen  in order to get access remote access to the instance.

Body:
Here we see an "XY problem". You want to automatically accept host keys (this is "X"). You think that you can do that by automatically typing "yes" at the prompt (this is "Y"). You are stuck on that, so you ask how to do Y. But there is an even easier way to do X.

Here's how to do X:

add the option -o StrictHostKeyChecking=no to your SSH command.

strcpy(ssh,"ssh -o StrictHostKeyChecking=no -i theKey.pem ec2-user@");
//              ^^^^^^^^^^^^^^^^^^^^^^^^^^^

I assume the ssh buffer is already long enough to contain this extra option.


问:
Checkbox that submits form on click
I'm using Codeigniter and wants to know how I can make a checkbox that submits the form on click?

Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3

答:
Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:</p>

```<code><form id="something">
    <input type="checkbox" name="foo" id="foo" value="yes" />
</form>

<script type="text/javascript">
$("#foo").click(function() {
    if ($(this).is(":checked"))
        $("#something").submit();
});
</script>
</code>```

Title: Checkbox that submits form on click

Body:
Haven't worked with Codeigniter much, but I can answer how to make the form submit on checking the checkbox with JS:

<form id="something">
    <input type="checkbox" name="foo" id="foo" value="yes" />
</form>

<script type="text/javascript">
$("#foo").click(function() {
    if ($(this).is(":checked"))
        $("#something").submit();
});
</script>


问:
Is there any way to quickly view a Visual Studio Code HTML page on a Mac in different browsers like in Sublime Text
I learned how to open HTML files on a Mac in Chrome via Cmd + shift + b from the accepted answer here, but I miss being able to easily choose any browser like I can by right clicking in Sublime Text. How to view my HTML code in browser with Visual Studio Code?

Is there anyway to make shortcuts to do this in Visual Studio Code?

I'm stuck because I don't know why cmd + shift + b is the shortcut to open the HTML page in Chrome (I'm assuming it has something to do with "building" the app) so I don't know how I'd be able to make separate build commands / shortcuts for each browser.

答:
The only way I've found to view HTML files in a different browser on Mac is to change my default browser (by clicking on the Apple menu and selecting System Preferences >> General >> Default web browser >> choose the browser you want) select default browser, then in VSCode right clicking on the html.index file and selecting either "Open With Live Server" or "View In Browser"
view in browser</p>


问:
Can not pass Data To ContainerView
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

```<code> class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }
</code>```

ContainerView

```<code>class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}
</code>```

result: favposid has Nill Value

UPDATE this is with segue method

```<code>class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}
</code>```

答:
Pass your data like. User prepare(for:sender:)</p>

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if
        segue.identifier == "MyIdentifierInStorybiard", // Set that
        let controller = segue.destination as? MenuBookReviewVC {
        controller.favpostid = postid
    }
}
</code>```

Title: Can not pass Data To ContainerView

Body:
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

 class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }

ContainerView

class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}

result: favposid has Nill Value

UPDATE this is with segue method

class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}

Body:
Pass your data like. User prepare(for:sender:)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if
        segue.identifier == "MyIdentifierInStorybiard", // Set that
        let controller = segue.destination as? MenuBookReviewVC {
        controller.favpostid = postid
    }
}


问:
Require is not defined nodejs
Trying to use this smartsheet api: http://smartsheet-platform.github.io/api-docs/?javascript#node.js-sample-code

and its telling me to do this for nodejs:

```<code>var client = require('smartsheet');
var smartsheet = client.createClient({accessToken:'ACCESSTOKEN'});
</code>```

So i do this in my main.js file but I get the error: Uncaught ReferenceError: require is not defined

I think its because im new to nodejs/npm but I cannot find it anywhere where to actually put this require function.  I think i need to mess with my node.js file but im note entirely sure.  Any link to documentation or suggestions are greatly appreciated!

答: Try Removing "type": "module", from package.json</p>

Title: Require is not defined nodejs

Body:
Trying to use this smartsheet api: http://smartsheet-platform.github.io/api-docs/?javascript#node.js-sample-code

and its telling me to do this for nodejs:

var client = require('smartsheet');
var smartsheet = client.createClient({accessToken:'ACCESSTOKEN'});

So i do this in my main.js file but I get the error: Uncaught ReferenceError: require is not defined

I think its because im new to nodejs/npm but I cannot find it anywhere where to actually put this require function.  I think i need to mess with my node.js file but im note entirely sure.  Any link to documentation or suggestions are greatly appreciated!


问:
Is there a way to block EasyMock's nice control in a java project?
In my project we use EasyMock in tests for createing mock objects.
We decided to prevent the usage of createNiceControl() in every tests.
Is there a way to prevent it in a Java 11 application?

答: Not directly with EasyMock no. But you can easily add a ArchUnit or a Checkstyle rule.</p>


问:
How to retrieve value from json output
I would like to retrieve transcript value from below shared output of console.log.But only that transcript value required which has another key is confidence.

Output of console.log :

```<code>  Data: {
    "results": [
    {
    "keywords_result": {
    "blocked": [
    {
    "normalized_text": "blocked",
    "start_time": 1.1,
    "confidence": 0.64,
    "end_time": 1.68
    }
    ]
    },
    "alternatives": [
    {
    "confidence": 0.81,
    "transcript": "your Name is Charlie "
    },
    {
    "transcript": "your Name is Charlie and "
    },
    {
    "transcript": "your Name is Charlies "
    }
    ],
    "final": true
    }
    ],
    "result_index": 0
    }
    Close: 1000
</code>```

Expected output:

```<code>your Name is Charlie
</code>```

Please note, I am expected value should be come from console.log output to a variable which I can use further.

答:
you could do something like this:</p>

```<code>const confidenceObj = event.Data.results[0].alternatives.filter((ele)=>ele.confidence)
if(confidenceObj.length>0){console.log(confidenceObj[0].transcript);}
</code>```

Title: How to retrieve value from json output

Body:
I would like to retrieve transcript value from below shared output of console.log.But only that transcript value required which has another key is confidence.

Output of console.log :

  Data: {
    "results": [
    {
    "keywords_result": {
    "blocked": [
    {
    "normalized_text": "blocked",
    "start_time": 1.1,
    "confidence": 0.64,
    "end_time": 1.68
    }
    ]
    },
    "alternatives": [
    {
    "confidence": 0.81,
    "transcript": "your Name is Charlie "
    },
    {
    "transcript": "your Name is Charlie and "
    },
    {
    "transcript": "your Name is Charlies "
    }
    ],
    "final": true
    }
    ],
    "result_index": 0
    }
    Close: 1000

Expected output:

your Name is Charlie

Please note, I am expected value should be come from console.log output to a variable which I can use further.

Body:
you could do something like this:

const confidenceObj = event.Data.results[0].alternatives.filter((ele)=>ele.confidence)
if(confidenceObj.length>0){console.log(confidenceObj[0].transcript);}


问:
JS, Datatables: wait until HTML table fully loads
In my webapp I render a large (> 1000 rows) table using html, boostrap and jquery datatables...

```<code><script type="text/javascript">
  $(document).ready(function () {
    var table_tab = $('#tab').DataTable({ ... });
  });
</script>

<table id="tab" class="table responsive table-striped table-bordered" width="100%">
  <?php foreach... ?>
</table>
</code>```

All rows are loaded at the first time, no ajax is used, and all search / filter operations are provided on the client by datatables.

The table is responsive and is correctly formatted by datatables. However, it takes a while (few seconds) until page is loaded. And because datatables javascript is not triggered yet, table displays unformatted and inresponsive until its html is loaded.

What I want

Hide the table until html is fully loaded and display a loading image in the meantime.

Do this without css display none, because i want the table to be shown in a browser without javascript support.

What I tried

I created two divs one that holds the table and second for the loading image...

```<code><div id="details_tab">
  <script type="text/javascript">$("#details_tab").hide();</script>
  <table id="tab" class="table responsive table-striped table-bordered" width="100%">
    ...
  </table>
</div>
<div id="loading_tab" class="jsonly">
  <div class="text-center vspace-20 bmarg-20">
    <img src="./images/loader.gif" width="40px" /><br/>
    <big>Loading data...</big>
  </div>
</div>
</code>```

After window is loaded I hide image and show div with table...

```<code>$(window).load(function() {
  $("#details_tab").show();
  $("#loading_tab").hide();
});
</code>```

It works. Nevertheless, the datatable is damaged. It doesn't fit to a proper bootstrap column and is stretched over other elements. Moreover the table isn't responsive and doesn't react to window size change.

Can you help me?

答: in DataTable you can add "initComplete": function(){the code to show the table or else}</p>

Body:
In my webapp I render a large (> 1000 rows) table using html, boostrap and jquery datatables...

  <?php foreach... ?>

All rows are loaded at the first time, no ajax is used, and all search / filter operations are provided on the client by datatables.

The table is responsive and is correctly formatted by datatables. However, it takes a while (few seconds) until page is loaded. And because datatables javascript is not triggered yet, table displays unformatted and inresponsive until its html is loaded.

What I want

Hide the table until html is fully loaded and display a loading image in the meantime.

Do this without css display none, because i want the table to be shown in a browser without javascript support.

What I tried

I created two divs one that holds the table and second for the loading image...

    ...

    <big>Loading data...</big>

After window is loaded I hide image and show div with table...

$(window).load(function() {
  $("#details_tab").show();
  $("#loading_tab").hide();
});

It works. Nevertheless, the datatable is damaged. It doesn't fit to a proper bootstrap column and is stretched over other elements. Moreover the table isn't responsive and doesn't react to window size change.

Can you help me?


问:
Fastest way to flush a hashmap to disk into an sorted set
I have a Map<byte[], Element> and I want to sort it and write it to disk, so that I have a file with all the elements sorted by key through Guava's UnsignedBytes.lexicographicalComparator.

What I'm doing right now is:

```<code>HashMap<byte[], Element> memory;

// ... code creating and populating memory ...

TreeMap<byte[], Element> sortedMap = new TreeMap<byte[], Element>(UnsignedBytes.lexicographicalComparator());
sortedMap.putAll(memory.getMap());

MyWriter writer = new MyWriter("myfile.dat");
for (Element element: sortedMap.values())
    writer.write(element);
writer.close();
</code>```

It's probably difficult to make the sorting faster (O(nlogn)), the question is whether I can improve on the navigation of the sorted list. Ideally I'd sort into an ArrayList instead of a TreeMap, so that iterating through it would be very fast.

I thought about putting the HashMap into an ArrayList and Collections.sort() it, but that would require more copying than the actual solution.

Any ideas?

Edit:

I add here my test with ArrayList which is 2x faster, but I assume it uses more memory. Maybe some comments on this assumption?

```<code>// ArrayList-based implementation 2x faster
ArrayList<Element> sorted = new ArrayList<Element>(memory.size());
sorted.addAll(memory.values());

final Comparator<byte[]> lexic = UnsignedBytes.lexicographicalComparator();

Collections.sort(sorted, new Comparator<Element>(){
    public int compare(Element arg0, Element arg1) {
        return lexic.compare(arg0.getKey(), arg1.getKey());
    }
});
MyWriter writer = new MyWriter(filename);

for (Element element: sorted)
    writer.write(element);
writer.close();
</code>```

答:
Your question was "Any ideas?". I guess anything I could write would be an answer.

I had the same problem as you, and extensively benchmarked the two solutions: use a treemap so items were sorted in advance, or sort them after the fact. My benchmark showed the same result as yours. It's faster to sort after the fact.

I wouldn't be concerned about the fact that the second approach requires more copying. First, faster is faster, right? If the second approach takes fewer CPU cycles then it's better.

If memory is a concern, then keep in mind that treemaps and hashmaps take far more memory per item than an ArrayList, which is backed by a simple object array. Each element in a treemap or hashmap requires at least one object, and usually more. Objects have a lot of overhead, 32 or more bytes. In a flat array each element takes only 4 bytes.

My benchmarks showed that the time to allocate an array from memory was roughly proportional to the size of the array, once you got to an array size over a few dozen bytes. So allocating the ArrayList may be slow if it's really large. Still, I think it's the better bet, so long as there's no danger of running out of memory.

Body:
I have a Map<byte[], Element> and I want to sort it and write it to disk, so that I have a file with all the elements sorted by key through Guava's UnsignedBytes.lexicographicalComparator.

What I'm doing right now is:

HashMap<byte[], Element> memory;

// ... code creating and populating memory ...

TreeMap<byte[], Element> sortedMap = new TreeMap<byte[], Element>(UnsignedBytes.lexicographicalComparator());
sortedMap.putAll(memory.getMap());

MyWriter writer = new MyWriter("myfile.dat");
for (Element element: sortedMap.values())
    writer.write(element);
writer.close();

It's probably difficult to make the sorting faster (O(nlogn)), the question is whether I can improve on the navigation of the sorted list. Ideally I'd sort into an ArrayList instead of a TreeMap, so that iterating through it would be very fast.

I thought about putting the HashMap into an ArrayList and Collections.sort() it, but that would require more copying than the actual solution.

Any ideas?

Edit:

I add here my test with ArrayList which is 2x faster, but I assume it uses more memory. Maybe some comments on this assumption?

// ArrayList-based implementation 2x faster
ArrayList<Element> sorted = new ArrayList<Element>(memory.size());
sorted.addAll(memory.values());

final Comparator<byte[]> lexic = UnsignedBytes.lexicographicalComparator();

Collections.sort(sorted, new Comparator<Element>(){
    public int compare(Element arg0, Element arg1) {
        return lexic.compare(arg0.getKey(), arg1.getKey());
    }
});
MyWriter writer = new MyWriter(filename);

for (Element element: sorted)
    writer.write(element);
writer.close();


答:
You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty</p>

```<code>@foreach ($element['subs'] as $item)
    @if($loop->index < 10)
        // Your code
    @endif
@endforeach
</code>```

Title: Laravel view foreach with two properties

Body:
You should limit the results in controller, but here's how you can accomplish this in a blade. Not pretty

@foreach ($element['subs'] as $item)
    @if($loop->index < 10)
        // Your code
    @endif
@endforeach


问:
How can I show multiple videos with React Native Video in React Native?
How can I show multiple videos with the React Native Video component of React Native?

Here is the React Native Video GitHub repository.

答:
You can store videos in Array like you stored array in var array and use Flatlist and pass data as the array you stored in array variable, then render the Flat list items as video tag.

The flat list will show all the videos in a list.

```<code>import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text } from 'react-native';

const Videos = [
  {
    Videourl: 'url1',
  },
  {
    Videourl: 'url2',
  },
  {
    Videourl: 'url3',
  },
];

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={({ item }) =>
      <Video source={item.Videourl}
   ref={(ref) => {
     this.player = ref
   }}
   onBuffer={this.onBuffer}
   onError={this.videoError}
   style={styles.backgroundVideo} />}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 10,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});
</code>```

Body:
You can store videos in Array like you stored array in var array and use Flatlist and pass data as the array you stored in array variable, then render the Flat list items as video tag.

The flat list will show all the videos in a list.

import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text } from 'react-native';

const Videos = [
  {
    Videourl: 'url1',
  },
  {
    Videourl: 'url2',
  },
  {
    Videourl: 'url3',
  },
];

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={({ item }) =>
      <Video source={item.Videourl}
   ref={(ref) => {
     this.player = ref
   }}
   onBuffer={this.onBuffer}
   onError={this.videoError}
   style={styles.backgroundVideo} />}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 10,
  },
  item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});


问:
Object not callable error | Where function
I am trying to run below query:

```<code>df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"]\
          .where(df1["DID"]== "BIG123")).show()
</code>```

I get error as shown below:

TypeError: 'Column' object is not callable TypeError

  Traceback (most recent call last)

What is the issue with the query and how do I fix it?

答:
There is syntax issue in your query. Closing bracket for select is coming after where  block.  Below is syntactically query . </p>

```<code>df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"])\
          .where(df1["DID"]== "BIG123").show()
</code>```

Body:
I am trying to run below query:

df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"]\
          .where(df1["DID"]== "BIG123")).show()

I get error as shown below:

TypeError: 'Column' object is not callable TypeError

  Traceback (most recent call last)

What is the issue with the query and how do I fix it?

Body:
There is syntax issue in your query. Closing bracket for select is coming after where  block.  Below is syntactically query .

df3 = df1.join(df2, df1["DID"] == df2["JID"],'inner')\
          .select(df1["DID"],df1["amt"]-df2["amt"])\
          .where(df1["DID"]== "BIG123").show()


问:
Laravel having column name in where clause static method
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

```<code>$user = User::whereName('john')->first(); // added `name` as a column name
</code>```

When called this code to SQL it generates

```<code>$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?
</code>```

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

答:
If you're asking where is the code responsible for it to work, it's using the magic method __call() (__callStatic() before that to make an instance) in the class Illuminate\Database\Query\Builder

/**
     * Handle dynamic method calls into the method.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return mixed
     *
     * @throws \BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        if (static::hasMacro($method)) {
            return $this->macroCall($method, $parameters);
        }

        if (Str::startsWith($method, 'where')) {
            return $this->dynamicWhere($method, $parameters);
        }

        static::throwBadMethodCallException($method);
    }
```

<p>precisely in the condition <code>Str::startsWith($method, 'where')</code> which redirect the call to <code>dynamicWhere()</code></p>

<pre class="lang-php prettyprint-override"><code>/**
     * Handles dynamic "where" clauses to the query.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return $this
     */
    public function dynamicWhere($method, $parameters)
    {
        $finder = substr($method, 5);

        $segments = preg_split(
            '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE
        );

        // The connector variable will determine which connector will be used for the
        // query condition. We will change it as we come across new boolean values
        // in the dynamic method strings, which could contain a number of these.
        $connector = 'and';

        $index = 0;

        foreach ($segments as $segment) {
            // If the segment is not a boolean connector, we can assume it is a column's name
            // and we will add it to the query as a new constraint as a where clause, then
            // we can keep iterating through the dynamic method string's segments again.
            if ($segment !== 'And' && $segment !== 'Or') {
                $this->addDynamic($segment, $connector, $parameters, $index);

                $index++;
            }

            // Otherwise, we will store the connector so we know how the next where clause we
            // find in the query should be connected to the previous ones, meaning we will
            // have the proper boolean connector to connect the next where clause found.
            else {
                $connector = $segment;
            }
        }

        return $this;
    }
</code>```

Body:
Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case

example

$user = User::whereName('john')->first(); // added `name` as a column name

When called this code to SQL it generates

$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

Body:
If you're asking where is the code responsible for it to work, it's using the magic method __call() (__callStatic() before that to make an instance) in the class Illuminate\Database\Query\Builder

/**
     * Handle dynamic method calls into the method.
     *
     * @param  string  $method
     * @param  array   $parameters
     * @return mixed
     *
     * @throws \BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        if (static::hasMacro($method)) {
            return $this->macroCall($method, $parameters);
        }

        if (Str::startsWith($method, 'where')) {
            return $this->dynamicWhere($method, $parameters);
        }

        static::throwBadMethodCallException($method);
    }

precisely in the condition Str::startsWith($method, 'where') which redirect the call to dynamicWhere()

/**
     * Handles dynamic "where" clauses to the query.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return $this
     */
    public function dynamicWhere($method, $parameters)
    {
        $finder = substr($method, 5);

        $segments = preg_split(
            '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE
        );

        // The connector variable will determine which connector will be used for the
        // query condition. We will change it as we come across new boolean values
        // in the dynamic method strings, which could contain a number of these.
        $connector = 'and';

        $index = 0;

        foreach ($segments as $segment) {
            // If the segment is not a boolean connector, we can assume it is a column's name
            // and we will add it to the query as a new constraint as a where clause, then
            // we can keep iterating through the dynamic method string's segments again.
            if ($segment !== 'And' && $segment !== 'Or') {
                $this->addDynamic($segment, $connector, $parameters, $index);

                $index++;
            }

            // Otherwise, we will store the connector so we know how the next where clause we
            // find in the query should be connected to the previous ones, meaning we will
            // have the proper boolean connector to connect the next where clause found.
            else {
                $connector = $segment;
            }
        }

        return $this;
    }


问:
How to update CRM Plugins - I get "Plug-in assembly does not contain the required types or assembly content cannot be updated"
So I'm trying to migrate to CRM 2016 and would like to update the CRM plugins.

For this I'm using the CRM Plugin Registration Tool. One exemplary plugin that I'd like to update would be this one: https://crm2011distributewf.codeplex.com/

In the tool I select the assembly -> right click "Update" -> select the dll (link above) -> check the boxes of its step 2 (either all or just the ones included in the earlier version) -> "Update Selected Plugins" then I'll get this error:

```<code>Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Plug-in assembly does not contain the required types or assembly content cannot be updated.
Detail: <OrganizationServiceFault xmlns="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ActivityId>00000000-0000-0000-0000-000000000000</ActivityId>
  <ErrorCode>-2147204725</ErrorCode>
  <ErrorDetails xmlns:a="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
  <Message>Plug-in assembly does not contain the required types or assembly content cannot be updated.</Message>
  <Timestamp>2017-05-03T15:10:55.5223643Z</Timestamp>
  <ExceptionSource i:nil="true" />
  <InnerFault>
    <ActivityId>00000000-0000-0000-0000-000000000000</ActivityId>
    <ErrorCode>-2147204725</ErrorCode>
    <ErrorDetails xmlns:a="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
    <Message>Plug-in assembly does not contain the required types or assembly content cannot be updated.</Message>
    <Timestamp>2017-05-03T15:10:55.5223643Z</Timestamp>
    <ExceptionSource i:nil="true" />
    <InnerFault i:nil="true" />
    <OriginalException i:nil="true" />
    <TraceText i:nil="true" />
  </InnerFault>
  <OriginalException i:nil="true" />
  <TraceText i:nil="true" />
</OrganizationServiceFault>

Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at Microsoft.Crm.Tools.Libraries.RegistrationHelper.UpdateAssembly(CrmOrganization org, String pathToAssembly, CrmPluginAssembly assembly, PluginType[] type)
   at Microsoft.Crm.Tools.AssemblyRegistration.PluginRegistrationViewModel.btnregisterClick()
</code>```

Any idea for how to update them? I'm also getting this error for the other plugins.

Do I have to unregister the plugins an register them anew? And if so where can I find where they're used and readd them?

Note: this question is similar but didn't help me a cm.

答: Verify that have you change the name of any pugin, in that case you have to unregister plugin from old name first.</p>

Body:
So I'm trying to migrate to CRM 2016 and would like to update the CRM plugins.

For this I'm using the CRM Plugin Registration Tool. One exemplary plugin that I'd like to update would be this one: https://crm2011distributewf.codeplex.com/

In the tool I select the assembly -> right click "Update" -> select the dll (link above) -> check the boxes of its step 2 (either all or just the ones included in the earlier version) -> "Update Selected Plugins" then I'll get this error:

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Plug-in assembly does not contain the required types or assembly content cannot be updated.
Detail: <OrganizationServiceFault xmlns="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ActivityId>00000000-0000-0000-0000-000000000000</ActivityId>
  <ErrorCode>-2147204725</ErrorCode>
  <ErrorDetails xmlns:a="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
  <Message>Plug-in assembly does not contain the required types or assembly content cannot be updated.</Message>
  <Timestamp>2017-05-03T15:10:55.5223643Z</Timestamp>
  <ExceptionSource i:nil="true" />
  <InnerFault>
    <ActivityId>00000000-0000-0000-0000-000000000000</ActivityId>
    <ErrorCode>-2147204725</ErrorCode>
    <ErrorDetails xmlns:a="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
    <Message>Plug-in assembly does not contain the required types or assembly content cannot be updated.</Message>
    <Timestamp>2017-05-03T15:10:55.5223643Z</Timestamp>
    <ExceptionSource i:nil="true" />
    <InnerFault i:nil="true" />
    <OriginalException i:nil="true" />
    <TraceText i:nil="true" />
  </InnerFault>
  <OriginalException i:nil="true" />
  <TraceText i:nil="true" />
</OrganizationServiceFault>

Server stack trace:
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at Microsoft.Crm.Tools.Libraries.RegistrationHelper.UpdateAssembly(CrmOrganization org, String pathToAssembly, CrmPluginAssembly assembly, PluginType[] type)
   at Microsoft.Crm.Tools.AssemblyRegistration.PluginRegistrationViewModel.btnregisterClick()

Any idea for how to update them? I'm also getting this error for the other plugins.

Do I have to unregister the plugins an register them anew? And if so where can I find where they're used and readd them?

Note: this question is similar but didn't help me a cm.


问:
How to connect 2 queries SQL
How to connect these 2 queries to receive one that gives such a response:

```<code>user_name  room_name_reserved    room_name_biggest_time

user_1       room_1                  room_2
</code>```

room_name_reserved - most often reserved room by user

room_name_biggest_time  - room when user spent the most time

1 query:

```<code> SELECT
        us.name as user_name
        ,ro.name as room_name_reserved
    FROM reservation re
    INNER JOIN user us on us.id = re.userid
    INNER JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    HAVING COUNT(room_name_reser) = (SELECT COUNT(*) FROM reservation re1
        WHERE re1.userid = re.userid
        GROUP BY re1.roomid
        ORDER BY COUNT(*) DESC
        LIMIT 1
        )
</code>```

2 query :

```<code>SELECT
    us.name as user_name
    ,ro.name as room_name_biggest_time
from Reservation re
INNER JOIN user us on us.id = re.userid
INNER JOIN room ro on ro.id = re.roomid
WHERE (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (SELECT MAX((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time FROM Reservation re1 where re1.UserId = re.userid
</code>```

ORDER BY time DESC
LIMIT 1 )

答:
Use the two query as subquery  in join</p>

```<code>select t1.user_name, t1.room_name_reserved , t2.room_name_biggest_time
from (
  select
      us.name as user_name,
      ro.name as room_name_reserved
  from reservation re
  inner join user us on us.id = re.userid
  inner join room ro on ro.id = re.roomid
  group by us.name, ro.name
  having count(room_name_reser) = (
      select count(*)
      from reservation re1
      where re1.userid = re.userid
      group by re1.roomid
      order by count(*) desc
      limit 1)
) t1
left  join  (
select
    us.name as user_name,
    ro.name as room_name_biggest_time
from Reservation re
inner join user us on us.id = re.userid
inner join room ro on ro.id = re.roomid
Where (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (
    SELECT Max((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time
    from Reservation re1
    where re1.UserId = re.userid
    order by time desc limit 1
    )
) t2 on t1.user_name = t2.user_name
</code>```

Title: How to connect 2 queries SQL

Body:
How to connect these 2 queries to receive one that gives such a response:

user_name  room_name_reserved    room_name_biggest_time

user_1       room_1                  room_2

room_name_reserved - most often reserved room by user

room_name_biggest_time  - room when user spent the most time

1 query:

 SELECT
        us.name as user_name
        ,ro.name as room_name_reserved
    FROM reservation re
    INNER JOIN user us on us.id = re.userid
    INNER JOIN room ro on ro.id = re.roomid
    GROUP BY us.name, ro.name
    HAVING COUNT(room_name_reser) = (SELECT COUNT(*) FROM reservation re1
        WHERE re1.userid = re.userid
        GROUP BY re1.roomid
        ORDER BY COUNT(*) DESC
        LIMIT 1
        )

2 query :

SELECT
    us.name as user_name
    ,ro.name as room_name_biggest_time
from Reservation re
INNER JOIN user us on us.id = re.userid
INNER JOIN room ro on ro.id = re.roomid
WHERE (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (SELECT MAX((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time FROM Reservation re1 where re1.UserId = re.userid

ORDER BY time DESC
LIMIT 1 )

Body:
Use the two query as subquery  in join

select t1.user_name, t1.room_name_reserved , t2.room_name_biggest_time
from (
  select
      us.name as user_name,
      ro.name as room_name_reserved
  from reservation re
  inner join user us on us.id = re.userid
  inner join room ro on ro.id = re.roomid
  group by us.name, ro.name
  having count(room_name_reser) = (
      select count(*)
      from reservation re1
      where re1.userid = re.userid
      group by re1.roomid
      order by count(*) desc
      limit 1)
) t1
left  join  (
select
    us.name as user_name,
    ro.name as room_name_biggest_time
from Reservation re
inner join user us on us.id = re.userid
inner join room ro on ro.id = re.roomid
Where (strftime('%s', re.EndsAt) - strftime('%s', re.StartsAt)) = (
    SELECT Max((strftime('%s', re1.EndsAt) - strftime('%s', re1.StartsAt))) as time
    from Reservation re1
    where re1.UserId = re.userid
    order by time desc limit 1
    )
) t2 on t1.user_name = t2.user_name


问:
Javascript call nested function
I have the following piece of code:

```<code>function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }
}
</code>```

Is there any way I can call the validate() function outside the initValidation() function? I've tried calling validate() but I think it's only visible inside the parent function.

答:
Function definition:

```<code>function initValidation() {
   // code here
   function validate(_block){
     // code here
     console.log(_block);
   }
   return validate;
}
</code>```

Call it as below:

```<code>initValidation()("hello");
</code>```

Title: Javascript call nested function

Body:
I have the following piece of code:

function initValidation()
{
    // irrelevant code here
    function validate(_block){
        // code here
    }
}

Is there any way I can call the validate() function outside the initValidation() function? I've tried calling validate() but I think it's only visible inside the parent function.

Body:
Function definition:

function initValidation() {
   // code here
   function validate(_block){
     // code here
     console.log(_block);
   }
   return validate;
}

Call it as below:

initValidation()("hello");


问:
Why my interrupt in AVR does not work correctly?
EDIT: IT'S WORKING

I'm programming Atmega8 communication with PC. I use Treminal v1.9b to send and receive "messages". Here's my code:

```<code>#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
#include <string.h>
#include <avr/interrupt.h>
#include <stdlib.h>

void print_char(char letter)
{
    if( bit_is_set(UCSRA, UDRE) )
    {
        _delay_ms(10);
        UDR=letter;
        loop_until_bit_is_set(UCSRA, TXC);
    }
}

volatile char what = 'x';

int main(void)
{
    DDRC |= (1<<PC0);
    DDRC |= (1<<PC1);
    DDRC |= (1<<PC2);

    UBRRL = 12;//4800 1mhz
    UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);

    sei();

    PORTC ^= (1<<PC1);

    while(1)
    {
        print_char(what);
        PORTC ^= (1<<PC0);
        _delay_ms(100);
    }
}

ISR(USART_RXC_vect)
{
    what = UDR;
    PORTC ^= (1<<PC2);
}
</code>```

After switch on uC, in the console (Terminal v1.9b) 'x' appear, after trying to send anything, the 'x' stops popping up. It's like the program hung or the interrupt did not return to the main program. (after sending anything to the uC, the given value should be displaying in the console).

When the uC is switch on, led at PC1 is shining, at PC0 is winking, at PC2 is dark. After send any char to uC: led at PC0 is dark, at PC1 is shining, at PC2 is dark. As though the funcktion ISR() doesn't start.

Where is the problem?

.iss file:

```<code>usb2.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000106  00000000  00000000  00000074  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .data         00000002  00800060  00000106  0000017a  2**0
                  CONTENTS, ALLOC, LOAD, DATA

Disassembly of section .text:

00000000 <__vectors>:
   0:   29 c0           rjmp    .+82        ; 0x54 <__ctors_end>
   2:   00 00           nop
   4:   3a c0           rjmp    .+116       ; 0x7a <__bad_interrupt>
   6:   00 00           nop
   8:   38 c0           rjmp    .+112       ; 0x7a <__bad_interrupt>
   a:   00 00           nop
   c:   36 c0           rjmp    .+108       ; 0x7a <__bad_interrupt>
   e:   00 00           nop
  10:   34 c0           rjmp    .+104       ; 0x7a <__bad_interrupt>
  12:   00 00           nop
  14:   32 c0           rjmp    .+100       ; 0x7a <__bad_interrupt>
  16:   00 00           nop
  18:   30 c0           rjmp    .+96        ; 0x7a <__bad_interrupt>
  1a:   00 00           nop
  1c:   2e c0           rjmp    .+92        ; 0x7a <__bad_interrupt>
  1e:   00 00           nop
  20:   2c c0           rjmp    .+88        ; 0x7a <__bad_interrupt>
  22:   00 00           nop
  24:   2a c0           rjmp    .+84        ; 0x7a <__bad_interrupt>
  26:   00 00           nop
  28:   28 c0           rjmp    .+80        ; 0x7a <__bad_interrupt>
  2a:   00 00           nop
  2c:   55 c0           rjmp    .+170       ; 0xd8 <__vector_11>
  2e:   00 00           nop
  30:   24 c0           rjmp    .+72        ; 0x7a <__bad_interrupt>
  32:   00 00           nop
  34:   22 c0           rjmp    .+68        ; 0x7a <__bad_interrupt>
  36:   00 00           nop
  38:   20 c0           rjmp    .+64        ; 0x7a <__bad_interrupt>
  3a:   00 00           nop
  3c:   1e c0           rjmp    .+60        ; 0x7a <__bad_interrupt>
  3e:   00 00           nop
  40:   1c c0           rjmp    .+56        ; 0x7a <__bad_interrupt>
  42:   00 00           nop
  44:   1a c0           rjmp    .+52        ; 0x7a <__bad_interrupt>
  46:   00 00           nop
  48:   18 c0           rjmp    .+48        ; 0x7a <__bad_interrupt>
  4a:   00 00           nop
  4c:   16 c0           rjmp    .+44        ; 0x7a <__bad_interrupt>
  4e:   00 00           nop
  50:   14 c0           rjmp    .+40        ; 0x7a <__bad_interrupt>
    ...

00000054 <__ctors_end>:
  54:   11 24           eor r1, r1
  56:   1f be           out 0x3f, r1    ; 63
  58:   cf e5           ldi r28, 0x5F   ; 95
  5a:   d4 e0           ldi r29, 0x04   ; 4
  5c:   de bf           out 0x3e, r29   ; 62
  5e:   cd bf           out 0x3d, r28   ; 61

00000060 <__do_copy_data>:
  60:   10 e0           ldi r17, 0x00   ; 0
  62:   a0 e6           ldi r26, 0x60   ; 96
  64:   b0 e0           ldi r27, 0x00   ; 0
  66:   e6 e0           ldi r30, 0x06   ; 6
  68:   f1 e0           ldi r31, 0x01   ; 1
  6a:   02 c0           rjmp    .+4         ; 0x70 <.do_copy_data_start>

0000006c <.do_copy_data_loop>:
  6c:   05 90           lpm r0, Z+
  6e:   0d 92           st  X+, r0

00000070 <.do_copy_data_start>:
  70:   a2 36           cpi r26, 0x62   ; 98
  72:   b1 07           cpc r27, r17
  74:   d9 f7           brne    .-10        ; 0x6c <.do_copy_data_loop>
  76:   0c d0           rcall   .+24        ; 0x90 <main>
  78:   44 c0           rjmp    .+136       ; 0x102 <_exit>

0000007a <__bad_interrupt>:
  7a:   c2 cf           rjmp    .-124       ; 0x0 <__vectors>

0000007c <_Z10print_charc>:
  7c:   5d 9b           sbis    0x0b, 5 ; 11
  7e:   07 c0           rjmp    .+14        ; 0x8e <_Z10print_charc+0x12>
  80:   e4 ec           ldi r30, 0xC4   ; 196
  82:   f9 e0           ldi r31, 0x09   ; 9
  84:   31 97           sbiw    r30, 0x01   ; 1
  86:   f1 f7           brne    .-4         ; 0x84 <_Z10print_charc+0x8>
  88:   8c b9           out 0x0c, r24   ; 12
  8a:   5e 9b           sbis    0x0b, 6 ; 11
  8c:   fe cf           rjmp    .-4         ; 0x8a <_Z10print_charc+0xe>
  8e:   08 95           ret

00000090 <main>:
  90:   1f 93           push    r17
  92:   cf 93           push    r28
  94:   df 93           push    r29
  96:   a0 9a           sbi 0x14, 0 ; 20
  98:   a1 9a           sbi 0x14, 1 ; 20
  9a:   a2 9a           sbi 0x14, 2 ; 20
  9c:   8c e0           ldi r24, 0x0C   ; 12
  9e:   89 b9           out 0x09, r24   ; 9
  a0:   88 e9           ldi r24, 0x98   ; 152
  a2:   8a b9           out 0x0a, r24   ; 10
  a4:   86 e8           ldi r24, 0x86   ; 134
  a6:   80 bd           out 0x20, r24   ; 32
  a8:   85 b7           in  r24, 0x35   ; 53
  aa:   81 60           ori r24, 0x01   ; 1
  ac:   85 bf           out 0x35, r24   ; 53
  ae:   8b b7           in  r24, 0x3b   ; 59
  b0:   80 64           ori r24, 0x40   ; 64
  b2:   8b bf           out 0x3b, r24   ; 59
  b4:   78 94           sei
  b6:   85 b3           in  r24, 0x15   ; 21
  b8:   92 e0           ldi r25, 0x02   ; 2
  ba:   89 27           eor r24, r25
  bc:   85 bb           out 0x15, r24   ; 21
  be:   11 e0           ldi r17, 0x01   ; 1
  c0:   c8 ea           ldi r28, 0xA8   ; 168
  c2:   d1 e6           ldi r29, 0x61   ; 97
  c4:   80 91 60 00     lds r24, 0x0060
  c8:   d9 df           rcall   .-78        ; 0x7c <_Z10print_charc>
  ca:   85 b3           in  r24, 0x15   ; 21
  cc:   81 27           eor r24, r17
  ce:   85 bb           out 0x15, r24   ; 21
  d0:   ce 01           movw    r24, r28
  d2:   01 97           sbiw    r24, 0x01   ; 1
  d4:   f1 f7           brne    .-4         ; 0xd2 <main+0x42>
  d6:   f6 cf           rjmp    .-20        ; 0xc4 <main+0x34>

000000d8 <__vector_11>:
  d8:   1f 92           push    r1
  da:   0f 92           push    r0
  dc:   0f b6           in  r0, 0x3f    ; 63
  de:   0f 92           push    r0
  e0:   11 24           eor r1, r1
  e2:   8f 93           push    r24
  e4:   9f 93           push    r25
  e6:   85 b3           in  r24, 0x15   ; 21
  e8:   94 e0           ldi r25, 0x04   ; 4
  ea:   89 27           eor r24, r25
  ec:   85 bb           out 0x15, r24   ; 21
  ee:   8c b1           in  r24, 0x0c   ; 12
  f0:   80 93 60 00     sts 0x0060, r24
  f4:   9f 91           pop r25
  f6:   8f 91           pop r24
  f8:   0f 90           pop r0
  fa:   0f be           out 0x3f, r0    ; 63
  fc:   0f 90           pop r0
  fe:   1f 90           pop r1
 100:   18 95           reti

00000102 <_exit>:
 102:   f8 94           cli

00000104 <__stop_program>:
 104:   ff cf           rjmp    .-2         ; 0x104 <__stop_program>
</code>```

答:
As you can see, in the generated vector table:

00000000 <__vectors>:
   0:   29 c0           rjmp    .+82        ; 0x54 <__ctors_end>
   2:   00 00           nop
   4:   3a c0           rjmp    .+116       ; 0x7a <__bad_interrupt>
   6:   00 00           nop
   8:   38 c0           rjmp    .+112       ; 0x7a <__bad_interrupt>
   a:   00 00           nop
...
  2c:   55 c0           rjmp    .+170       ; 0xd8 <__vector_11>
  2e:   00 00           nop
```

<p>each interrupt vector uses 2 words: one for <code>rjmp</code> and one filled with <code>nop</code>.</p>

<p>Thus 12th vector is located at addrees 0x002C (or 0x16 word address).</p>

<p>In the datasheet in <em>table 18</em>, section <em>Interrupt Vectors
in ATmega8</em> at page <em>46</em> you can see, in ATmega8 for each vector only one word is allocated (it is enough for <code>rjmp</code> instruction, which allows to jump to any address within 4Kwords address space).</p>

<p>Thus, the <em>USART, RXC</em> vector should be placed at 0x0B word address (or 0x0016 byte address).</p>

<p>In other words, you have incorrect setup for the compiling environment, probably you have selected wrong CPU.</p>

<p>When actual interrupt happens, vector at(byte-address <code>0x0016</code> is executed:</p>

```  16:   00 00           nop
  18:   30 c0           rjmp    .+96        ; 0x7a <__bad_interrupt>
```

<p>causing skipping of <code>nop</code> operation and jumping to <code>__bad_interrupt</code> label:</p>

```0000007a <__bad_interrupt>:
  7a:   c2 cf           rjmp    .-124       ; 0x0 <__vectors>
```

which causes the program to halt

Body:
EDIT: IT'S WORKING

I'm programming Atmega8 communication with PC. I use Treminal v1.9b to send and receive "messages". Here's my code:

#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
#include <string.h>
#include <avr/interrupt.h>
#include <stdlib.h>

void print_char(char letter)
{
    if( bit_is_set(UCSRA, UDRE) )
    {
        _delay_ms(10);
        UDR=letter;
        loop_until_bit_is_set(UCSRA, TXC);
    }
}

volatile char what = 'x';

int main(void)
{
    DDRC |= (1<<PC0);
    DDRC |= (1<<PC1);
    DDRC |= (1<<PC2);

    UBRRL = 12;//4800 1mhz
    UCSRB = (1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
    UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);

    sei();

    PORTC ^= (1<<PC1);

    while(1)
    {
        print_char(what);
        PORTC ^= (1<<PC0);
        _delay_ms(100);
    }
}

ISR(USART_RXC_vect)
{
    what = UDR;
    PORTC ^= (1<<PC2);
}

After switch on uC, in the console (Terminal v1.9b) 'x' appear, after trying to send anything, the 'x' stops popping up. It's like the program hung or the interrupt did not return to the main program. (after sending anything to the uC, the given value should be displaying in the console).

When the uC is switch on, led at PC1 is shining, at PC0 is winking, at PC2 is dark. After send any char to uC: led at PC0 is dark, at PC1 is shining, at PC2 is dark. As though the funcktion ISR() doesn't start.

Where is the problem?

.iss file:

usb2.elf:     file format elf32-avr

Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .text         00000106  00000000  00000000  00000074  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 .data         00000002  00800060  00000106  0000017a  2**0
                  CONTENTS, ALLOC, LOAD, DATA

Disassembly of section .text:

00000000 <__vectors>:
   0:   29 c0           rjmp    .+82        ; 0x54 <__ctors_end>
   2:   00 00           nop
   4:   3a c0           rjmp    .+116       ; 0x7a <__bad_interrupt>
   6:   00 00           nop
   8:   38 c0           rjmp    .+112       ; 0x7a <__bad_interrupt>
   a:   00 00           nop
   c:   36 c0           rjmp    .+108       ; 0x7a <__bad_interrupt>
   e:   00 00           nop
  10:   34 c0           rjmp    .+104       ; 0x7a <__bad_interrupt>
  12:   00 00           nop
  14:   32 c0           rjmp    .+100       ; 0x7a <__bad_interrupt>
  16:   00 00           nop
  18:   30 c0           rjmp    .+96        ; 0x7a <__bad_interrupt>
  1a:   00 00           nop
  1c:   2e c0           rjmp    .+92        ; 0x7a <__bad_interrupt>
  1e:   00 00           nop
  20:   2c c0           rjmp    .+88        ; 0x7a <__bad_interrupt>
  22:   00 00           nop
  24:   2a c0           rjmp    .+84        ; 0x7a <__bad_interrupt>
  26:   00 00           nop
  28:   28 c0           rjmp    .+80        ; 0x7a <__bad_interrupt>
  2a:   00 00           nop
  2c:   55 c0           rjmp    .+170       ; 0xd8 <__vector_11>
  2e:   00 00           nop
  30:   24 c0           rjmp    .+72        ; 0x7a <__bad_interrupt>
  32:   00 00           nop
  34:   22 c0           rjmp    .+68        ; 0x7a <__bad_interrupt>
  36:   00 00           nop
  38:   20 c0           rjmp    .+64        ; 0x7a <__bad_interrupt>
  3a:   00 00           nop
  3c:   1e c0           rjmp    .+60        ; 0x7a <__bad_interrupt>
  3e:   00 00           nop
  40:   1c c0           rjmp    .+56        ; 0x7a <__bad_interrupt>
  42:   00 00           nop
  44:   1a c0           rjmp    .+52        ; 0x7a <__bad_interrupt>
  46:   00 00           nop
  48:   18 c0           rjmp    .+48        ; 0x7a <__bad_interrupt>
  4a:   00 00           nop
  4c:   16 c0           rjmp    .+44        ; 0x7a <__bad_interrupt>
  4e:   00 00           nop
  50:   14 c0           rjmp    .+40        ; 0x7a <__bad_interrupt>
    ...

00000054 <__ctors_end>:
  54:   11 24           eor r1, r1
  56:   1f be           out 0x3f, r1    ; 63
  58:   cf e5           ldi r28, 0x5F   ; 95
  5a:   d4 e0           ldi r29, 0x04   ; 4
  5c:   de bf           out 0x3e, r29   ; 62
  5e:   cd bf           out 0x3d, r28   ; 61

00000060 <__do_copy_data>:
  60:   10 e0           ldi r17, 0x00   ; 0
  62:   a0 e6           ldi r26, 0x60   ; 96
  64:   b0 e0           ldi r27, 0x00   ; 0
  66:   e6 e0           ldi r30, 0x06   ; 6
  68:   f1 e0           ldi r31, 0x01   ; 1
  6a:   02 c0           rjmp    .+4         ; 0x70 <.do_copy_data_start>

0000006c <.do_copy_data_loop>:
  6c:   05 90           lpm r0, Z+
  6e:   0d 92           st  X+, r0

00000070 <.do_copy_data_start>:
  70:   a2 36           cpi r26, 0x62   ; 98
  72:   b1 07           cpc r27, r17
  74:   d9 f7           brne    .-10        ; 0x6c <.do_copy_data_loop>
  76:   0c d0           rcall   .+24        ; 0x90
  78:   44 c0           rjmp    .+136       ; 0x102 <_exit>

0000007a <__bad_interrupt>:
  7a:   c2 cf           rjmp    .-124       ; 0x0 <__vectors>

0000007c <_Z10print_charc>:
  7c:   5d 9b           sbis    0x0b, 5 ; 11
  7e:   07 c0           rjmp    .+14        ; 0x8e <_Z10print_charc+0x12>
  80:   e4 ec           ldi r30, 0xC4   ; 196
  82:   f9 e0           ldi r31, 0x09   ; 9
  84:   31 97           sbiw    r30, 0x01   ; 1
  86:   f1 f7           brne    .-4         ; 0x84 <_Z10print_charc+0x8>
  88:   8c b9           out 0x0c, r24   ; 12
  8a:   5e 9b           sbis    0x0b, 6 ; 11
  8c:   fe cf           rjmp    .-4         ; 0x8a <_Z10print_charc+0xe>
  8e:   08 95           ret

00000090 :
  90:   1f 93           push    r17
  92:   cf 93           push    r28
  94:   df 93           push    r29
  96:   a0 9a           sbi 0x14, 0 ; 20
  98:   a1 9a           sbi 0x14, 1 ; 20
  9a:   a2 9a           sbi 0x14, 2 ; 20
  9c:   8c e0           ldi r24, 0x0C   ; 12
  9e:   89 b9           out 0x09, r24   ; 9
  a0:   88 e9           ldi r24, 0x98   ; 152
  a2:   8a b9           out 0x0a, r24   ; 10
  a4:   86 e8           ldi r24, 0x86   ; 134
  a6:   80 bd           out 0x20, r24   ; 32
  a8:   85 b7           in  r24, 0x35   ; 53
  aa:   81 60           ori r24, 0x01   ; 1
  ac:   85 bf           out 0x35, r24   ; 53
  ae:   8b b7           in  r24, 0x3b   ; 59
  b0:   80 64           ori r24, 0x40   ; 64
  b2:   8b bf           out 0x3b, r24   ; 59
  b4:   78 94           sei
  b6:   85 b3           in  r24, 0x15   ; 21
  b8:   92 e0           ldi r25, 0x02   ; 2
  ba:   89 27           eor r24, r25
  bc:   85 bb           out 0x15, r24   ; 21
  be:   11 e0           ldi r17, 0x01   ; 1
  c0:   c8 ea           ldi r28, 0xA8   ; 168
  c2:   d1 e6           ldi r29, 0x61   ; 97
  c4:   80 91 60 00     lds r24, 0x0060
  c8:   d9 df           rcall   .-78        ; 0x7c <_Z10print_charc>
  ca:   85 b3           in  r24, 0x15   ; 21
  cc:   81 27           eor r24, r17
  ce:   85 bb           out 0x15, r24   ; 21
  d0:   ce 01           movw    r24, r28
  d2:   01 97           sbiw    r24, 0x01   ; 1
  d4:   f1 f7           brne    .-4         ; 0xd2
  d6:   f6 cf           rjmp    .-20        ; 0xc4

000000d8 <__vector_11>:
  d8:   1f 92           push    r1
  da:   0f 92           push    r0
  dc:   0f b6           in  r0, 0x3f    ; 63
  de:   0f 92           push    r0
  e0:   11 24           eor r1, r1
  e2:   8f 93           push    r24
  e4:   9f 93           push    r25
  e6:   85 b3           in  r24, 0x15   ; 21
  e8:   94 e0           ldi r25, 0x04   ; 4
  ea:   89 27           eor r24, r25
  ec:   85 bb           out 0x15, r24   ; 21
  ee:   8c b1           in  r24, 0x0c   ; 12
  f0:   80 93 60 00     sts 0x0060, r24
  f4:   9f 91           pop r25
  f6:   8f 91           pop r24
  f8:   0f 90           pop r0
  fa:   0f be           out 0x3f, r0    ; 63
  fc:   0f 90           pop r0
  fe:   1f 90           pop r1
 100:   18 95           reti

00000102 <_exit>:
 102:   f8 94           cli

00000104 <__stop_program>:
 104:   ff cf           rjmp    .-2         ; 0x104 <__stop_program>

Body:
As you can see, in the generated vector table:

00000000 <__vectors>:
   0:   29 c0           rjmp    .+82        ; 0x54 <__ctors_end>
   2:   00 00           nop
   4:   3a c0           rjmp    .+116       ; 0x7a <__bad_interrupt>
   6:   00 00           nop
   8:   38 c0           rjmp    .+112       ; 0x7a <__bad_interrupt>
   a:   00 00           nop
...
  2c:   55 c0           rjmp    .+170       ; 0xd8 <__vector_11>
  2e:   00 00           nop

each interrupt vector uses 2 words: one for rjmp and one filled with nop.

Thus 12th vector is located at addrees 0x002C (or 0x16 word address).

In the datasheet in table 18, section Interrupt Vectors
in ATmega8 at page 46 you can see, in ATmega8 for each vector only one word is allocated (it is enough for rjmp instruction, which allows to jump to any address within 4Kwords address space).

Thus, the USART, RXC vector should be placed at 0x0B word address (or 0x0016 byte address).

In other words, you have incorrect setup for the compiling environment, probably you have selected wrong CPU.

When actual interrupt happens, vector at(byte-address 0x0016 is executed:

  16:   00 00           nop
  18:   30 c0           rjmp    .+96        ; 0x7a <__bad_interrupt>

causing skipping of nop operation and jumping to __bad_interrupt label:

0000007a <__bad_interrupt>:
  7a:   c2 cf           rjmp    .-124       ; 0x0 <__vectors>

which causes the program to halt


问:
Regex Find the File name without extension including the exceptions such as tar.gz
I am trying to parse the file name from an URL (e.g. .tar.gz or .zip). For example,

```<code>*URL:* https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz

*Desired Output:* google-cloud-storage-1.13.0

*URL:* https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip

*Desired Output:* google-cloud-storage-1.13.0
</code>```

So far, with Javascript I have the following:

```<code>tar_name = url.split('/').pop().replace(/\..+$/, '');
</code>```

Which does not work when filename has dots in it.

Any help regarding how to get the file name from such an url with javascript is well appreciated.
Thanks.

答:
One option is to be specific and replace the part ending on .tar.gz or .zip with an empty string.

```<code>(?:\.tar\.gz|\.zip)$
</code>```

Regex demo

["https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz",
  "https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip"
].forEach(url => {
  url = url.split('/').pop().replace(/(?:\.tar\.gz|\.zip)$/, '');
  console.log(url);
});```
</div>
</div>
</p>

<p>Or you could for example capture the digits separated by dots at the end and match the chars a-z that follow keeping group 1 in the replacement.</p>

```(\d+(?:\.\d+)+)\.[a-z]+(?:\.[a-z]+)*$
```

<p>Regex demo</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>["https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz",
  "https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip"
].forEach(url => {
  url = url.split('/').pop().replace(/(\d+(?:\.\d+)+)\.[a-z]+(?:\.[a-z]+)*$/, "$1");
  console.log(url);
});</code>```

Body:
I am trying to parse the file name from an URL (e.g. .tar.gz or .zip). For example,

*URL:* https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz

*Desired Output:* google-cloud-storage-1.13.0

*URL:* https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip

*Desired Output:* google-cloud-storage-1.13.0

So far, with Javascript I have the following:

tar_name = url.split('/').pop().replace(/\..+$/, '');

Which does not work when filename has dots in it.

Any help regarding how to get the file name from such an url with javascript is well appreciated.
Thanks.

Body:
One option is to be specific and replace the part ending on .tar.gz or .zip with an empty string.

(?:\.tar\.gz|\.zip)$

Regex demo

["https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz",
  "https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip"
].forEach(url => {
  url = url.split('/').pop().replace(/(?:\.tar\.gz|\.zip)$/, '');
  console.log(url);
});

Or you could for example capture the digits separated by dots at the end and match the chars a-z that follow keeping group 1 in the replacement.

(\d+(?:\.\d+)+)\.[a-z]+(?:\.[a-z]+)*$

Regex demo

["https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.tar.gz",
  "https://files.pythonhosted.org/packages/00/51/f3afa784d73d1f35dce99f6138eaa779e2098a8dde4e7085ecf6295254bb/google-cloud-storage-1.13.0.zip"
].forEach(url => {
  url = url.split('/').pop().replace(/(\d+(?:\.\d+)+)\.[a-z]+(?:\.[a-z]+)*$/, "$1");
  console.log(url);
});


问:
Axios jsonp request not resolving and blocking code
I wrote a function to get Google suggestions :

```<code>const getGoogleSuggestions = async (searchInput: string) => {
  const results = await axios({
    url: `https://suggestqueries.google.com/complete/search?client=chrome&q=${searchInput}`,
    adapter: jsonpAdapter,
    callbackParamName: "jsonCallback"
  });
  console.log("test")
  return results.data[1];
};
</code>```

It once worked but now it seems not to and I don't understand why.
The console.log isn't executed at all. It seems the promise decided not to resolve. Also, when I check the "Network" tab on my browser every request is sent and has a 200 response code.

I tried with a try, catch block, I tried to resolve the promise with then... It just doesn't work. Any idea?

答:
With this parameter "client=chrome" the url sends you a text file to download.
Try with replace this by "output=toolbar" for getting an xml in your response.</p>

Body:
I wrote a function to get Google suggestions :

const getGoogleSuggestions = async (searchInput: string) => {
  const results = await axios({
    url: `https://suggestqueries.google.com/complete/search?client=chrome&q=${searchInput}`,
    adapter: jsonpAdapter,
    callbackParamName: "jsonCallback"
  });
  console.log("test")
  return results.data[1];
};

It once worked but now it seems not to and I don't understand why.
The console.log isn't executed at all. It seems the promise decided not to resolve. Also, when I check the "Network" tab on my browser every request is sent and has a 200 response code.

I tried with a try, catch block, I tried to resolve the promise with then... It just doesn't work. Any idea?


问:
Helm failed test job keeps restarting
I run my django unit tests in my cluster with helm command.
They are correctly launched, but when the unit tests fail, kubernetes keeps restarting them again and again, despite "restartPolicy: Never".

How can I force kubernetes/helm to run my unit tests only once, failed or not?

django-test.yml:

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: "{{ .Release.Name }}-django-test"
  labels:
    app: {{ template "myproject.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
  annotations:
    "helm.sh/hook": test
spec:
  template:
    metadata:
      name: "{{ .Release.Name }}-django-test"
    spec:
      containers:
        - name: main
          image: {{ template "myproject.django.image" . }}
          args:
            - test
      restartPolicy: Never
</code>```

```<code>➜  ~ kubectl get pods --namespace mynamespace
NAME                            READY   STATUS      RESTARTS   AGE
myrel-django-install-jhspp   0/1     Completed   0          78m
myrel-django-test-6dzrq      0/1     Error       0          47m
myrel-django-test-7hpwm      0/1     Error       0          67m
myrel-django-test-nd74f      0/1     Error       0          73m
myrel-django-test-np5qd      0/1     Error       0          39m
myrel-django-test-nqjdw      0/1     Error       0          60m
myrel-django-test-tjbhc      0/1     Error       0          53m
...
</code>```

答:
Have a look at backoffLimit option.

Pod backoff failure policy

There are situations where you want to fail a Job after some amount of
  retries due to a logical error in configuration etc. To do so, set
  .spec.backoffLimit to specify the number of retries before considering
  a Job as failed. The back-off limit is set by default to 6.

I have not tried this, but I believe it will get you the behaviour you want.

```<code>    spec:
      containers:
        - name: main
          image: {{ template "myproject.django.image" . }}
          args:
            - test
      backoffLimit: 1
      restartPolicy: Never
</code>```

You may also find the following post useful:
Understanding backoffLimit in Kubernetes Job

Title: Helm failed test job keeps restarting

Body:
I run my django unit tests in my cluster with helm command.
They are correctly launched, but when the unit tests fail, kubernetes keeps restarting them again and again, despite "restartPolicy: Never".

How can I force kubernetes/helm to run my unit tests only once, failed or not?

django-test.yml:

apiVersion: batch/v1
kind: Job
metadata:
  name: "{{ .Release.Name }}-django-test"
  labels:
    app: {{ template "myproject.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
  annotations:
    "helm.sh/hook": test
spec:
  template:
    metadata:
      name: "{{ .Release.Name }}-django-test"
    spec:
      containers:
        - name: main
          image: {{ template "myproject.django.image" . }}
          args:
            - test
      restartPolicy: Never

➜  ~ kubectl get pods --namespace mynamespace
NAME                            READY   STATUS      RESTARTS   AGE
myrel-django-install-jhspp   0/1     Completed   0          78m
myrel-django-test-6dzrq      0/1     Error       0          47m
myrel-django-test-7hpwm      0/1     Error       0          67m
myrel-django-test-nd74f      0/1     Error       0          73m
myrel-django-test-np5qd      0/1     Error       0          39m
myrel-django-test-nqjdw      0/1     Error       0          60m
myrel-django-test-tjbhc      0/1     Error       0          53m
...

Body:
Have a look at backoffLimit option.

Pod backoff failure policy

There are situations where you want to fail a Job after some amount of
  retries due to a logical error in configuration etc. To do so, set
  .spec.backoffLimit to specify the number of retries before considering
  a Job as failed. The back-off limit is set by default to 6.

I have not tried this, but I believe it will get you the behaviour you want.

    spec:
      containers:
        - name: main
          image: {{ template "myproject.django.image" . }}
          args:
            - test
      backoffLimit: 1
      restartPolicy: Never

You may also find the following post useful:
Understanding backoffLimit in Kubernetes Job


问:
Elastic Search SQL Server Synchronization
I'm currently doing real time synchronization with elastic search (upon save in database, I save on elastic search).

The problem that I have is synchronization of all entitites through some tool (probably Logstash) - though I'm not sure about best practices. I would like to be able to synchronize specific entity (or all entities), which is not a problem since I have DB View for each entity but I'm not sure about performance of whole DB synchronization, and are there any limitations on logstash/other tools?

Basically the idea is to run full synchronization on initial project setup, and then just run synchronization if something goes wrong or model changes and needs elastic search update. I don't have too many records for now (<1M overall I'd say).

Any suggestion would be well appreciated!

答:
You can use the JDBC plugin of logstash. You can even use the cron job style scheduler that is built in the plugin.

The documentation is here JDBC input Plugin

But you have to understand that Elasticsearch is a Search Engine. So real-time is not possible but near real time is.


问:
Equal space after li of unordered list
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

```<code>ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}
</code>```

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>My abc</li>
<li>LiveColor</li>
<li>LiveFood</li>
<li>Ola</li>
<li>Uber</li>
<li>Good Chat</li>
<li>Food Panda</li>
<li>Domino'd</li>
<li>Clickfood</li>
<li>Smartyo</li>
<li>Tide</li>
<li>Webseries</li>
<li>GoPro</li>
<li>Liveshow</li>
</ol></code>```

In addition to it, the font-family is such a way that all the numbers have different spaces.

答:
If you want to target only certain items, you could use the :nth-of-type selector:</p>

```<code>ol li:nth-of-type(n+10)::before {

}
</code>```

Title: Equal space after li of unordered list

Body:
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}

My abc

LiveColor

LiveFood

Ola

Uber

Good Chat

Food Panda

Domino'd

Clickfood

Smartyo

Tide

Webseries

GoPro

Liveshow

In addition to it, the font-family is such a way that all the numbers have different spaces.

Body:
If you want to target only certain items, you could use the :nth-of-type selector:

ol li:nth-of-type(n+10)::before {

}