问:
Unable to fetch html hidden input values into express app
I'm trying to fetch some hidden form values in post route of my express app,but getting undefined objects in post route,below is some code snippet</p>

```<code>const express = require("express")
const app   =   express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.listen(3000, () => {
    console.log('Authentication service started on port 3000');
});

app.get("/link",(req,res)=>{
    let token = 124578
   let link="http://"+req.get('host')+"/postmethod";
    console.log("hyperlink:"+link)
    let formHtmlPostLink="<form method='post' action='"+link+"'>    <input type='hidden' name='bearer' value='"+token+"'> <input type='hidden' name='test' value='test'> <button type='submit' name='submit_param' value='submit_value' class='link-button'>      Reset Password         </button>       </form>"
    res.send(formHtmlPostLink)
})
app.post("/postmethod",(req,res)=>{
    res.send(req.body)//undefined objects
})
</code>```

答:
If you are able to submit form to /postmethod, add middleware bodyParser.urlencoded()

```<code>app.use(bodyParser.urlencoded());
</code>```

If form is not being submitted, change link to relative url

```<code>  let link = "/postmethod";
</code>```

Check codesandbox

Body:
I'm trying to fetch some hidden form values in post route of my express app,but getting undefined objects in post route,below is some code snippet

const express = require("express")
const app   =   express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());

app.listen(3000, () => {
    console.log('Authentication service started on port 3000');
});

app.get("/link",(req,res)=>{
    let token = 124578
   let link="http://"+req.get('host')+"/postmethod";
    console.log("hyperlink:"+link)
    let formHtmlPostLink="<form method='post' action='"+link+"'>    <input type='hidden' name='bearer' value='"+token+"'> <input type='hidden' name='test' value='test'> <button type='submit' name='submit_param' value='submit_value' class='link-button'>      Reset Password         </button>       </form>"
    res.send(formHtmlPostLink)
})
app.post("/postmethod",(req,res)=>{
    res.send(req.body)//undefined objects
})

Body:
If you are able to submit form to /postmethod, add middleware bodyParser.urlencoded()

app.use(bodyParser.urlencoded());

If form is not being submitted, change link to relative url

  let link = "/postmethod";

Check codesandbox


来源: stackexchange

问:
Count categorical levels broken down into columns of aggregated table
I have a data.table containing a categorial variable and I am looking for an efficient way to count its categories in an aggregated table, whereas each category is broken down into columns.

Here's my data:

```<code>library(data.table)
DT <- data.table(x = c(1, 1, 2, 1, 1, 1, 3, 3, 3, 2, 2),
                 y = c("A", "A", "B", "A", "A", "B", "B", "B", "A", "C"))
> DT
    x y
 1: 1 A
 2: 1 A
 3: 2 B
 4: 1 A
 5: 1 A
 6: 1 B
 7: 3 B
 8: 3 B
 9: 3 A
10: 2 A
11: 2 C

</code>```

Now I want to aggregate DT by x and receive a data.table with columns named after each category found in y, displaying the corresponding frequency:

```<code>   x A B C
1: 1 4 1 NA
2: 2 1 1 1
3: 3 1 2 NA
</code>```

So far I only managed to solve this problem 'manually' by creating aggregations for each category, e.g. DT[y == "A", .N, by = x] and merging them together with a left join. I grazed the entire internet unsuccessfully for a much more dynamic solution such as a function that simply delivers the desired result just like:

```<code>DT1 <- aggfunc(DT, var = "y", by = "x")
</code>```

答:
Another possibility using summarise and pivot_wider:

DT %>%
  group_by(x,y) %>%
  summarise(num = n()) %>%
  pivot_wider(names_from=y, values_from=num) %>%
  as.data.table
```

<p>gives us</p>

<pre class="lang-r prettyprint-override"><code>   x A B  C
1: 1 4 1 NA
2: 2 1 1  1
3: 3 1 2 NA
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data.table containing a categorial variable and I am looking for an efficient way to count its categories in an aggregated table, whereas each category is broken down into columns.

Here's my data:

library(data.table)
DT <- data.table(x = c(1, 1, 2, 1, 1, 1, 3, 3, 3, 2, 2),
                 y = c("A", "A", "B", "A", "A", "B", "B", "B", "A", "C"))
> DT
    x y
 1: 1 A
 2: 1 A
 3: 2 B
 4: 1 A
 5: 1 A
 6: 1 B
 7: 3 B
 8: 3 B
 9: 3 A
10: 2 A
11: 2 C

Now I want to aggregate DT by x and receive a data.table with columns named after each category found in y, displaying the corresponding frequency:

   x A B C
1: 1 4 1 NA
2: 2 1 1 1
3: 3 1 2 NA

So far I only managed to solve this problem 'manually' by creating aggregations for each category, e.g. DT[y == "A", .N, by = x] and merging them together with a left join. I grazed the entire internet unsuccessfully for a much more dynamic solution such as a function that simply delivers the desired result just like:

DT1 <- aggfunc(DT, var = "y", by = "x")

Body:
Another possibility using summarise and pivot_wider:

DT %>%
  group_by(x,y) %>%
  summarise(num = n()) %>%
  pivot_wider(names_from=y, values_from=num) %>%
  as.data.table

gives us

   x A B  C
1: 1 4 1 NA
2: 2 1 1  1
3: 3 1 2 NA


问:
Operations in stack using dynamic memory allocation
I tried doing a program for implementing the various operations in stack such as pop,push,traverse,peek etc. But I used static memory allocation. How can I implement the program using dynamic memory allocation?

(I am a beginner in programming and don't have a thorough knowledge in dynamic memory allocation).

Here is my program which I used static memory allocation:

```<code>#include<stdio.h>
#define CAPACITY 5
int stack[CAPACITY] ,top=-1;

void main()
{
    int ch,item;
    while(1)
    {
        printf("1.push\n");
        printf("2.pop\n");
        printf("3.peek \n");
        printf("4.traverse\n");
        printf("5.Quit\n");

        printf("Enter your choice :\n");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                printf("Enter the element to push :\n");
                scanf("%d",&item);
                push(item);
                break;
            case 2:
                item = pop();
                if(item==0)
                {
                    printf("stack is underflow\n");
                }
                else
                {
                    printf("popped item : %d\n",item);
                }
                break;
            case 3: peek();
            break;
            case 4: traverse();
            break;
            case 5: exit(0);
            default:printf("Invalid input \n\n");

        }
    }

}
void push(int ele)
{
    if(isfull())
    {
        printf("Stack is overflow\n");
    }
    else
    {
        top++;
        stack[top] = ele;
        printf("%d pushed \n",ele);
    }
}
int isfull()
{
    if(top==CAPACITY-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int pop()
{
    if(isempty())
    {
        return 0;
    }
    else
    {
        return stack[top--];
    }
}
int isempty()
{
    if(top==-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void peek()
{
    if(isempty())
    {
        printf("stack is underflow\n");
    }
    else
    {
        printf("peek element :%d\n",stack[top]);
    }
}
void traverse()
{
    if(isempty())
    {
        printf("stack is empty\n");
    }
    else
    {
        int i;
        printf("Stack elements are : \n");
        for(i=0;i<=top;i++)
        {
            printf("%d \n",stack[i]);
        }
    }
}
</code>```

答:
How can I implement the program using dynamic memory allocation?

If you want to use DMA (dynamic memory allocation) in your program, here is the modified code. Now your progarm will initialize the stack at run-time. There were some warnings in your program which I also modified.

```<code>#include<stdio.h>
#include<stdlib.h>
//#define CAPACITY 5
//int stack[CAPACITY], top=-1;
int *stack, top = -1, CAPACITY;

// Prototype of Functions
void push(int ele);
int isfull();
int pop();
int isempty();
void peek();
void traverse();

// main()
int main(void)
{
    int ch,item;
    printf("Input Capacity of the stack: ");
    scanf("%d", &CAPACITY);
    // Dynamic Memory Allocation for the stack...
    stack = (int *)malloc(CAPACITY*sizeof(int));
    while(1)
    {
        printf("1.push\n");
        printf("2.pop\n");
        printf("3.peek \n");
        printf("4.traverse\n");
        printf("5.Quit\n");

        printf("Enter your choice :\n");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                printf("Enter the element to push :\n");
                scanf("%d",&item);
                push(item);
                break;
            case 2:
                item = pop();
                if(item==0)
                {
                    printf("stack is underflow\n");
                }
                else
                {
                    printf("popped item : %d\n",item);
                }
                break;
            case 3: peek();
            break;
            case 4: traverse();
            break;
            case 5: exit(0);
            default:printf("Invalid input \n\n");

        }
    }

}

// Definition of Functions.
void push(int ele)
{
    if(isfull())
    {
        printf("Stack is overflow\n");
    }
    else
    {
        top++;
        stack[top] = ele;
        printf("%d pushed \n",ele);
    }
}
int isfull()
{
    if(top==CAPACITY-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int pop()
{
    if(isempty())
    {
        return 0;
    }
    else
    {
        return stack[top--];
    }
}
int isempty()
{
    if(top==-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void peek()
{
    if(isempty())
    {
        printf("stack is underflow\n");
    }
    else
    {
        printf("peek element :%d\n",stack[top]);
    }
}
void traverse()
{
    if(isempty())
    {
        printf("stack is empty\n");
    }
    else
    {
        int i;
        printf("Stack elements are : \n");
        for(i=0;i<=top;i++)
        {
            printf("%d \n",stack[i]);
        }
    }
}
</code>```

Now, if you want explanation, then you should refer to this DMA

Body:
I tried doing a program for implementing the various operations in stack such as pop,push,traverse,peek etc. But I used static memory allocation. How can I implement the program using dynamic memory allocation?

(I am a beginner in programming and don't have a thorough knowledge in dynamic memory allocation).

Here is my program which I used static memory allocation:

#include<stdio.h>
#define CAPACITY 5
int stack[CAPACITY] ,top=-1;

void main()
{
    int ch,item;
    while(1)
    {
        printf("1.push\n");
        printf("2.pop\n");
        printf("3.peek \n");
        printf("4.traverse\n");
        printf("5.Quit\n");

        printf("Enter your choice :\n");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                printf("Enter the element to push :\n");
                scanf("%d",&item);
                push(item);
                break;
            case 2:
                item = pop();
                if(item==0)
                {
                    printf("stack is underflow\n");
                }
                else
                {
                    printf("popped item : %d\n",item);
                }
                break;
            case 3: peek();
            break;
            case 4: traverse();
            break;
            case 5: exit(0);
            default:printf("Invalid input \n\n");

        }
    }

}
void push(int ele)
{
    if(isfull())
    {
        printf("Stack is overflow\n");
    }
    else
    {
        top++;
        stack[top] = ele;
        printf("%d pushed \n",ele);
    }
}
int isfull()
{
    if(top==CAPACITY-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int pop()
{
    if(isempty())
    {
        return 0;
    }
    else
    {
        return stack[top--];
    }
}
int isempty()
{
    if(top==-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void peek()
{
    if(isempty())
    {
        printf("stack is underflow\n");
    }
    else
    {
        printf("peek element :%d\n",stack[top]);
    }
}
void traverse()
{
    if(isempty())
    {
        printf("stack is empty\n");
    }
    else
    {
        int i;
        printf("Stack elements are : \n");
        for(i=0;i<=top;i++)
        {
            printf("%d \n",stack[i]);
        }
    }
}

Body:
How can I implement the program using dynamic memory allocation?

If you want to use DMA (dynamic memory allocation) in your program, here is the modified code. Now your progarm will initialize the stack at run-time. There were some warnings in your program which I also modified.

#include<stdio.h>
#include<stdlib.h>
//#define CAPACITY 5
//int stack[CAPACITY], top=-1;
int *stack, top = -1, CAPACITY;

// Prototype of Functions
void push(int ele);
int isfull();
int pop();
int isempty();
void peek();
void traverse();

// main()
int main(void)
{
    int ch,item;
    printf("Input Capacity of the stack: ");
    scanf("%d", &CAPACITY);
    // Dynamic Memory Allocation for the stack...
    stack = (int *)malloc(CAPACITY*sizeof(int));
    while(1)
    {
        printf("1.push\n");
        printf("2.pop\n");
        printf("3.peek \n");
        printf("4.traverse\n");
        printf("5.Quit\n");

        printf("Enter your choice :\n");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                printf("Enter the element to push :\n");
                scanf("%d",&item);
                push(item);
                break;
            case 2:
                item = pop();
                if(item==0)
                {
                    printf("stack is underflow\n");
                }
                else
                {
                    printf("popped item : %d\n",item);
                }
                break;
            case 3: peek();
            break;
            case 4: traverse();
            break;
            case 5: exit(0);
            default:printf("Invalid input \n\n");

        }
    }

}

// Definition of Functions.
void push(int ele)
{
    if(isfull())
    {
        printf("Stack is overflow\n");
    }
    else
    {
        top++;
        stack[top] = ele;
        printf("%d pushed \n",ele);
    }
}
int isfull()
{
    if(top==CAPACITY-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
int pop()
{
    if(isempty())
    {
        return 0;
    }
    else
    {
        return stack[top--];
    }
}
int isempty()
{
    if(top==-1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
void peek()
{
    if(isempty())
    {
        printf("stack is underflow\n");
    }
    else
    {
        printf("peek element :%d\n",stack[top]);
    }
}
void traverse()
{
    if(isempty())
    {
        printf("stack is empty\n");
    }
    else
    {
        int i;
        printf("Stack elements are : \n");
        for(i=0;i<=top;i++)
        {
            printf("%d \n",stack[i]);
        }
    }
}

Now, if you want explanation, then you should refer to this DMA


问:
python flask javascript DELETE 405 (METHOD NOT ALLOWED)
I'm trying to add a button to delete a musical venue from my postgres database with flask-sqlalchemy on that venue's page and then redirect to the homepage but I'm getting the error

```<code>DELETE ip 405 (METHOD NOT ALLOWED)
</code>```

in my console and

```<code>[28/May/2020
14:12:49] "DELETE /deletevenue/1 HTTP/1.1" 302 -
72.133.209.13 - - [28/May/2020
14:12:50] "DELETE / HTTP/1.1" 405 -
</code>```

in my terminal.  I don't know what is going wrong.  I can see that the correct venue_id is being sent to the route but I'm still getting this error.  I don't know what's wrong here.  This is the relevant code:

app.py

```<code>@app.route('/deletevenue/<venue_id>', methods=['DELETE'])
def delete_venue(venue_id):
  error = False
  venue = db.session.query(Venue).filter_by(id=venue_id).one()
  name = venue.name
  try:
    Venue.query.filter_by(id=venue_id).delete()
    db.session.commit()
  except:
    error = True
    db.session.rollback()
  finally:
    db.session.close()
  if error:
    flash('An Error occured.  The venue ' + name + ' could not be deleted.')
    return redirect(url_for('index'))
  else:
    flash('Success.  Venue ' + name + ' was deleted.')
    return redirect(url_for('index'))

@app.route('/')
def index():
  return render_template('pages/home.html')
</code>```

show_venue.html

```<code>    <div class="row">
        <button class="btn btn-default btn-lg" id="deleteArtist" data-id="{{ venue.id }}">Delete this Artist</button>
    </div>
</section>

<script>
    const btn = document.getElementById('deleteArtist');
    btn.onclick = function(e) {
        venue_id = e.target.dataset['id'];
        console.log(venue_id)
        let r = confirm("Are you sure you want to delete this venue?");
        if (r == true) {
            fetch('/deletevenue/' + venue_id, {
                method: 'DELETE'
            })
        }
    }

</script>
</code>```

How can I get this button working?

答:
redirect() is flask => return response_code: 302 with same method it's recieved. (HERE is DELETE) => so it's redirect to index route with method DELETE => 405.

Method fetch() return a Promise => It's need a result response, you can not redirect code like:

return redirect(url_for('index'))
```

It should return json or something like value, then use your javascript code check value => redirect. - How TO - Redirect to Another Webpage

Body:
I'm trying to add a button to delete a musical venue from my postgres database with flask-sqlalchemy on that venue's page and then redirect to the homepage but I'm getting the error

DELETE ip 405 (METHOD NOT ALLOWED)

in my console and

[28/May/2020
14:12:49] "DELETE /deletevenue/1 HTTP/1.1" 302 -
72.133.209.13 - - [28/May/2020
14:12:50] "DELETE / HTTP/1.1" 405 -

in my terminal.  I don't know what is going wrong.  I can see that the correct venue_id is being sent to the route but I'm still getting this error.  I don't know what's wrong here.  This is the relevant code:

app.py

@app.route('/deletevenue/<venue_id>', methods=['DELETE'])
def delete_venue(venue_id):
  error = False
  venue = db.session.query(Venue).filter_by(id=venue_id).one()
  name = venue.name
  try:
    Venue.query.filter_by(id=venue_id).delete()
    db.session.commit()
  except:
    error = True
    db.session.rollback()
  finally:
    db.session.close()
  if error:
    flash('An Error occured.  The venue ' + name + ' could not be deleted.')
    return redirect(url_for('index'))
  else:
    flash('Success.  Venue ' + name + ' was deleted.')
    return redirect(url_for('index'))

@app.route('/')
def index():
  return render_template('pages/home.html')

show_venue.html

        <button class="btn btn-default btn-lg" id="deleteArtist" data-id="{{ venue.id }}">Delete this Artist</button>

How can I get this button working?

Body:
redirect() is flask => return response_code: 302 with same method it's recieved. (HERE is DELETE) => so it's redirect to index route with method DELETE => 405.

Method fetch() return a Promise => It's need a result response, you can not redirect code like:

return redirect(url_for('index'))

It should return json or something like value, then use your javascript code check value => redirect. - How TO - Redirect to Another Webpage


问:
JQuery - is there a way to make less calls to the dom
i have this jquery function

```<code>    function update_prices(that, current_id, quantity) {
         //that == $(this)
        var wrapper = that.parents(".wrapper");
        var standard = wrapper.find(".prettyCheckbox small:eq(0)").parents("span").parents("label").prev("input").val();
        var professional = wrapper.find(".prettyCheckbox small:eq(1)").parents("span").parents("label").prev("input").val();
        var premium = wrapper.find(".prettyCheckbox small:eq(2)").parents("span").parents("label").prev("input").val();
        $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;
            function(data) {
                var standard_price = data[0];
                var professional_price = data[0];
                var premium_price = data[0];
        });
        wrapper.find(".prettyCheckbox small:eq(0)").text(standard_price);
        wrapper.find(".prettyCheckbox small:eq(1)").text(professional_price);
        wrapper.find(".prettyCheckbox small:eq(2)").text(premium_price);
        return true;
    }
</code>```

and i feel like i am calling the same elements on the dom  more then i should ....is there anyone that can think of a better way to achieve what i want without making all these calls

答:
I would add CSS classes to those inputs such as standard, professional, and premium, and then all of your jQuery should look like:

```<code>function update_prices(that, current_id, quantity) {
     //that == $(this)
    var jqWrapper = that.closest(".wrapper");

    var jqStandard = jqWrapper.find("input.standard");
    var standard = jqStandard.val();

    var jqProfessional = jqWrapper.find("input.professional");
    var professional = jqProfessional.val();

    var jqPremium = jqWrapper.find("input.premium");
    var premium = jqPremium.val();

    var get = "/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;

    $.get(get, function(data) {
        jqStandard.val(data.standard_price);
        jqProfessional.val(data.professional_price);
        jqPremium.val(data.premium_price);
    });

    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have this jquery function

    function update_prices(that, current_id, quantity) {
         //that == $(this)
        var wrapper = that.parents(".wrapper");
        var standard = wrapper.find(".prettyCheckbox small:eq(0)").parents("span").parents("label").prev("input").val();
        var professional = wrapper.find(".prettyCheckbox small:eq(1)").parents("span").parents("label").prev("input").val();
        var premium = wrapper.find(".prettyCheckbox small:eq(2)").parents("span").parents("label").prev("input").val();
        $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;
            function(data) {
                var standard_price = data[0];
                var professional_price = data[0];
                var premium_price = data[0];
        });
        wrapper.find(".prettyCheckbox small:eq(0)").text(standard_price);
        wrapper.find(".prettyCheckbox small:eq(1)").text(professional_price);
        wrapper.find(".prettyCheckbox small:eq(2)").text(premium_price);
        return true;
    }

and i feel like i am calling the same elements on the dom  more then i should ....is there anyone that can think of a better way to achieve what i want without making all these calls

Body:
I would add CSS classes to those inputs such as standard, professional, and premium, and then all of your jQuery should look like:

function update_prices(that, current_id, quantity) {
     //that == $(this)
    var jqWrapper = that.closest(".wrapper");

    var jqStandard = jqWrapper.find("input.standard");
    var standard = jqStandard.val();

    var jqProfessional = jqWrapper.find("input.professional");
    var professional = jqProfessional.val();

    var jqPremium = jqWrapper.find("input.premium");
    var premium = jqPremium.val();

    var get = "/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&standard_id=" + standard + "&professional_id" + professional + "&premium_id" + premium + "&quantity" + quantity;

    $.get(get, function(data) {
        jqStandard.val(data.standard_price);
        jqProfessional.val(data.professional_price);
        jqPremium.val(data.premium_price);
    });

    return true;
}


问:
How to create a list of a number?
I am new to python and i was wondering how i could create a list of numbers in python as such

```<code>number = 123456
list_to_be_created = [1,2,3,4,5,6]
</code>```

Thank you in advance

答:
You can try with a list comprehension:

```<code>number = 123456
print([int(x) for x in str(number)])
</code>```

Returns:

```<code>[1, 2, 3, 4, 5, 6]
</code>```

Title: How to create a list of a number?

Body:
I am new to python and i was wondering how i could create a list of numbers in python as such

number = 123456
list_to_be_created = [1,2,3,4,5,6]

Thank you in advance

Body:
You can try with a list comprehension:

number = 123456
print([int(x) for x in str(number)])

Returns:

[1, 2, 3, 4, 5, 6]


问:
horizontal scrollbar on top and bottom of table
I've a very large table on my page. So I decided to put a horizontal scrollbar on the bottom of the table. But I would like this scrollbar to be also on top on the table.

What I have in the template is this:

```<code><div style="overflow:auto; width:100%; height:130%">
<table id="data" style="width:100%">...</table>
</div>
</code>```

Is this possible to do in HTML and CSS only?

答:
An AngularJs directive for achieving this:
To use it, add css class double-hscroll to your element. You will need jQuery and AngularJs for this.</p>

```<code>import angular from 'angular';

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $compile) {
  $scope.name = 'Dual wielded horizontal scroller';
});

app.directive('doubleHscroll', function($compile) {
  return {
restrict: 'C',
link: function(scope, elem, attr){

  var elemWidth = parseInt(elem[0].clientWidth);

  elem.wrap(`<div id='wrapscroll' style='width:${elemWidth}px;overflow:scroll'></div>`);
  //note the top scroll contains an empty space as a 'trick'
  $('#wrapscroll').before(`<div id='topscroll' style='height:20px; overflow:scroll;width:${elemWidth}px'><div style='min-width:${elemWidth}px'> </div></div>`);

  $(function(){
    $('#topscroll').scroll(function(){
      $("#wrapscroll").scrollLeft($("#topscroll").scrollLeft());
    });
    $('#wrapscroll').scroll(function() {
      $("#topscroll").scrollLeft($("#wrapscroll").scrollLeft());
    });

  });

}

  };

});
</code>```

Body:
I've a very large table on my page. So I decided to put a horizontal scrollbar on the bottom of the table. But I would like this scrollbar to be also on top on the table.

What I have in the template is this:

...

Is this possible to do in HTML and CSS only?

Body:
An AngularJs directive for achieving this:
To use it, add css class double-hscroll to your element. You will need jQuery and AngularJs for this.

import angular from 'angular';

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $compile) {
  $scope.name = 'Dual wielded horizontal scroller';
});

app.directive('doubleHscroll', function($compile) {
  return {
restrict: 'C',
link: function(scope, elem, attr){

  var elemWidth = parseInt(elem[0].clientWidth);

  elem.wrap(`<div id='wrapscroll' style='width:${elemWidth}px;overflow:scroll'></div>`);
  //note the top scroll contains an empty space as a 'trick'
  $('#wrapscroll').before(`<div id='topscroll' style='height:20px; overflow:scroll;width:${elemWidth}px'><div style='min-width:${elemWidth}px'> </div></div>`);

  $(function(){
    $('#topscroll').scroll(function(){
      $("#wrapscroll").scrollLeft($("#topscroll").scrollLeft());
    });
    $('#wrapscroll').scroll(function() {
      $("#topscroll").scrollLeft($("#wrapscroll").scrollLeft());
    });

  });

}

  };

});


问:
How do I only return SOME fields ($project) from Mongodb aggregation, while also using $match, $lookup AND $filter
I am VERY close to getting what I want out of this query... but I only want SOME of the fields returned and right now it is returning all of them

NOTE: This is a refinement : I am now asking how to return only certain fields, while my similar question asks how to return the data between a start and end date

In addition, can somebody please please provide an answer using the MongoDB Playground with MY data sets so I can try it out... I can't quite figure out how to "name" the data sets so they work in the playground !

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)
```

<p>Here is some register data</p>

<pre class="lang-js prettyprint-override"><code>[
  {
    "_id": "5eac9e815fc57b07f5d0d29f",
    "userId": "5ea108babb65b800172b11be",
    "accessToken": "111"
  },
  {
    "_id": "5ecaeba3c7b910d3276df839",
    "userId": "5e6c2dddad72870c84f8476b",
    "accessToken": "222"
  }
]
</code>```

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)
```

<p>Here is some notification data</p>

<pre class="lang-js prettyprint-override"><code>[{
    "_id": "5ebf0390c719e60004f42e74",
    "accessToken": "111",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e76",
    "accessToken": "222",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e78",
    "accessToken": "111",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e80",
    "accessToken": "222",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]
</code>```

Works, returns data between the two dates, but

This code returns everything, including the 'dontWantThis1' and 'dontWantThis2'

NOTE

I do not want the fields prefaced with 'dontWantThis' - but that is only to show which ones I don't want... I don't literally want to exclude fields prefaced with 'dontWantThis' ..... they could be named 'foo' or 'apple' or 'dog' they are just named that way to indicate that I don't want them

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-05-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var agg = [
            match,
            lookup,
            project
        ];

        Register.aggregate(agg)
        .then( ..... )
```

<h2>Try 1</h2>

<p>I thought I could do something like this, but it still returns ALL of the notification fields</p>

<pre class="lang-js prettyprint-override"><code>        var project = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,

                notifications : {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    },
            }}
        };
</code>```

SOLUTION

I created another projection and added that to the pipeline:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];
```

Thanks!!

答:
You need to convert notifications.dateCreated to ISODate, as your date is in string, by using $dateFromString and $map operator. i suggest you to do this, because I don't think that you can do date comparison with string formats. Also, make sure that dateStart and dateEnd should also be in ISODate format.

And you need two $project operator in order to achieve this. Also, I don't see any field with userAccessToken, I assume, it's accessToken. Check the below query.

db.Register.aggregate([
  {
    $lookup: {
      from: "my_Notifications",
      localField: "accessToken",
      foreignField: "accessToken",
      as: "notifications"
    }
  },
  {
    $project: {
      "_id": 1,
      "userId": 1,
      "accessToken": 1,
      notifications: {
        $map: {
          input: "$notifications",
          as: "n",
          in: {
            "_id": "$$n._id",
            "summaryId": "$$n.summaryId",
            "dateCreated": {
              $dateFromString: {
                dateString: "$$n.dateCreated"
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      "userId": 1,
      "accessToken": 1,
      "notifications": {
        $filter: {
          input: "$notifications",
          as: "item",
          cond: {
            $and: [
              {
                $gte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-24T00:00:00Z")
                ]
              },
              {
                $lte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-26T00:00:00Z")
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      "count": {
        $size: "$notifications"
      }
    }
  }
])
```

MongoPlayGroundLink

Body:
I am VERY close to getting what I want out of this query... but I only want SOME of the fields returned and right now it is returning all of them

NOTE: This is a refinement : I am now asking how to return only certain fields, while my similar question asks how to return the data between a start and end date

In addition, can somebody please please provide an answer using the MongoDB Playground with MY data sets so I can try it out... I can't quite figure out how to "name" the data sets so they work in the playground !

Register Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)

Here is some register data

[
  {
    "_id": "5eac9e815fc57b07f5d0d29f",
    "userId": "5ea108babb65b800172b11be",
    "accessToken": "111"
  },
  {
    "_id": "5ecaeba3c7b910d3276df839",
    "userId": "5e6c2dddad72870c84f8476b",
    "accessToken": "222"
  }
]

The next document contains data that is related to the Register schema via the accessToken

Notifications

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)

Here is some notification data

[{
    "_id": "5ebf0390c719e60004f42e74",
    "accessToken": "111",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e76",
    "accessToken": "222",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e78",
    "accessToken": "111",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e80",
    "accessToken": "222",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]

Works, returns data between the two dates, but

This code returns everything, including the 'dontWantThis1' and 'dontWantThis2'

NOTE

I do not want the fields prefaced with 'dontWantThis' - but that is only to show which ones I don't want... I don't literally want to exclude fields prefaced with 'dontWantThis' ..... they could be named 'foo' or 'apple' or 'dog' they are just named that way to indicate that I don't want them

        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-05-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var agg = [
            match,
            lookup,
            project
        ];

        Register.aggregate(agg)
        .then( ..... )

Try 1

I thought I could do something like this, but it still returns ALL of the notification fields

        var project = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,

                notifications : {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    },
            }}
        };

SOLUTION

I created another projection and added that to the pipeline:

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

Thanks!!

Body:
You need to convert notifications.dateCreated to ISODate, as your date is in string, by using $dateFromString and $map operator. i suggest you to do this, because I don't think that you can do date comparison with string formats. Also, make sure that dateStart and dateEnd should also be in ISODate format.

And you need two $project operator in order to achieve this. Also, I don't see any field with userAccessToken, I assume, it's accessToken. Check the below query.

db.Register.aggregate([
  {
    $lookup: {
      from: "my_Notifications",
      localField: "accessToken",
      foreignField: "accessToken",
      as: "notifications"
    }
  },
  {
    $project: {
      "_id": 1,
      "userId": 1,
      "accessToken": 1,
      notifications: {
        $map: {
          input: "$notifications",
          as: "n",
          in: {
            "_id": "$$n._id",
            "summaryId": "$$n.summaryId",
            "dateCreated": {
              $dateFromString: {
                dateString: "$$n.dateCreated"
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      "userId": 1,
      "accessToken": 1,
      "notifications": {
        $filter: {
          input: "$notifications",
          as: "item",
          cond: {
            $and: [
              {
                $gte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-24T00:00:00Z")
                ]
              },
              {
                $lte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-26T00:00:00Z")
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      "count": {
        $size: "$notifications"
      }
    }
  }
])

MongoPlayGroundLink


问:
What does Keras do when the number of inputs to an LSTM layer is greater than or less than the number of LSTM cells in that layer?
Please see python code below, I put comments in the code where I felt emphasis on information is required.

```<code>import keras
import numpy

def build_model():
    model = keras.models.Sequential()
    model.add(keras.layers.LSTM(3, input_shape = (3, 1), activation = 'elu'))# Number of LSTM cells in this layer = 3.
    return model

def build_data():
    inputs = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    outputs = [10, 11, 12, 13, 14, 15, 16, 17, 18]
    inputs = numpy.array(inputs)
    outputs = numpy.array(outputs)
    inputs = inputs.reshape(3, 3, 1)# Number of samples = 3, Number of input vectors in each sample  = 3, size of each input vector = 3.
    outputs = outputs.reshape(3, 3)# Number of target samples = 3, Number of outputs per target sample = 3.
    return inputs, outputs

def train():
    model = build_model()
    model.summary()
    model.compile(optimizer= 'adam', loss='mean_absolute_error', metrics=['accuracy'])
    x, y = build_data()
    model.fit(x, y, batch_size = 1, epochs = 4000)
    model.save("LSTM_testModel")

def apply():
    model = keras.models.load_model("LSTM_testModel")
    input = [[[7], [8], [9]]]
    input = numpy.array(input)
    print(model.predict(input))

def main():
    train()

main()
</code>```

My understanding is that for each input sample there are 3 input vectors. Each input vector goes to an LSTM cell. i.e. For sample 1, input vector 1 goes to LSTM cell 1, input vector 2 goes to LSTM cell 2 and so on.

Looking at tutorials on the internet, I've seen that the number of LSTM cells is much greater than the number of input vectors e.g. 300 LSTM cells.

So say for example I have 3 input vectors per sample what input goes to the 297 remaining LSTM cells?

I tried compiling the model to have 2 LSTM cells and it still accepted the 3 input vectors per sample, although I had to change the target outputs in the training data to accommodate for this(change the dimensions) . So what happened to the third input vector of each sample...is it ignored?

I believe the above image shows that each input vector (of an arbitrary scenario) is mapped to a specific RNN cell. I may be misinterpreting it. Above image taken from the following URL: http://karpathy.github.io/2015/05/21/rnn-effectiveness/

答:
I will try to answer some of your questions and then will consolidate the information provided in the comments for completeness, for the benefit of you as well as for the Community.

As mentioned by Matias in the comments, irrespective of whether the Number of Inputs are more than or less than the Number of Units/Neurons, it will be connected like a Fully Connected Network, as shown below.

To understand how RNN/LSTM work internally, let's assume we have

Number of Input Features => 3 => F1, F2 and F3

Number of Timesteps => 2 => 0 and 1

Number of Hidden Layers => 1

Number of Neurons in each Hidden Layer => 5

Then what actually happens inside can be represented in the screenshots shown below:

You have also asked about words being assigned to LSTM Cell. Not sure which link you are referring to and whether it is correct or not but in simple terms (words in this screenshot actually will be replaced by Embedding Vectors), you can understand how LSTM handles the Text as shown in the screenshot below:

For more information, please refer Beautiful Explanation by OverLordGoldDragon and Daniel Moller.

Hope this helps. Happy Learning!

Body:
Please see python code below, I put comments in the code where I felt emphasis on information is required.

import keras
import numpy

def build_model():
    model = keras.models.Sequential()
    model.add(keras.layers.LSTM(3, input_shape = (3, 1), activation = 'elu'))# Number of LSTM cells in this layer = 3.
    return model

def build_data():
    inputs = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    outputs = [10, 11, 12, 13, 14, 15, 16, 17, 18]
    inputs = numpy.array(inputs)
    outputs = numpy.array(outputs)
    inputs = inputs.reshape(3, 3, 1)# Number of samples = 3, Number of input vectors in each sample  = 3, size of each input vector = 3.
    outputs = outputs.reshape(3, 3)# Number of target samples = 3, Number of outputs per target sample = 3.
    return inputs, outputs

def train():
    model = build_model()
    model.summary()
    model.compile(optimizer= 'adam', loss='mean_absolute_error', metrics=['accuracy'])
    x, y = build_data()
    model.fit(x, y, batch_size = 1, epochs = 4000)
    model.save("LSTM_testModel")

def apply():
    model = keras.models.load_model("LSTM_testModel")
    input = [[[7], [8], [9]]]
    input = numpy.array(input)
    print(model.predict(input))

def main():
    train()

main()

My understanding is that for each input sample there are 3 input vectors. Each input vector goes to an LSTM cell. i.e. For sample 1, input vector 1 goes to LSTM cell 1, input vector 2 goes to LSTM cell 2 and so on.

Looking at tutorials on the internet, I've seen that the number of LSTM cells is much greater than the number of input vectors e.g. 300 LSTM cells.

So say for example I have 3 input vectors per sample what input goes to the 297 remaining LSTM cells?

I tried compiling the model to have 2 LSTM cells and it still accepted the 3 input vectors per sample, although I had to change the target outputs in the training data to accommodate for this(change the dimensions) . So what happened to the third input vector of each sample...is it ignored?

I believe the above image shows that each input vector (of an arbitrary scenario) is mapped to a specific RNN cell. I may be misinterpreting it. Above image taken from the following URL: http://karpathy.github.io/2015/05/21/rnn-effectiveness/


问:
I can't make a query select into in 2 table
"Make a query that having all orders by employees from employeeUK in the orderUK table"

my table of employeeUK:

```<code>select *
into employeeUK
from Employees
where Country = 'UK'
</code>```

then i want to make the orderUK table but i got confuse because my query always error.
How the query should be?

答:
you have to start with the table you going to insert the data into.</p>

```<code>into employeeUK
select *
from Employees
where Country = 'UK'
</code>```

Body:
"Make a query that having all orders by employees from employeeUK in the orderUK table"

my table of employeeUK:

select *
into employeeUK
from Employees
where Country = 'UK'

then i want to make the orderUK table but i got confuse because my query always error.
How the query should be?

Body:
you have to start with the table you going to insert the data into.

into employeeUK
select *
from Employees
where Country = 'UK'


问:
What does &H57 represent and how can I translate it for C#?
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

```<code>Const REQUEST_EFI As Byte = &H57
</code>```

What would this be in c#?  I tried:

```<code>const byte request_efi = &H57;
</code>```

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

答:
&H## is how VB represents hexadecimal numbers. In this case it is the hex number 57 or 87 in decimal. the C# equivalent would be:</p>

```<code>const byte request_efi = 0x57;
</code>```

Body:
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

Const REQUEST_EFI As Byte = &H57

What would this be in c#?  I tried:

const byte request_efi = &H57;

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

Body:
&H## is how VB represents hexadecimal numbers. In this case it is the hex number 57 or 87 in decimal. the C# equivalent would be:

const byte request_efi = 0x57;


问:
How to customize Stack height Flutter
I'm new here

just wondering how could I fit these 3 image into a stack in flutter, the first 2 fit good with row,
but the last is kinda offset the height of the stack.

ps* im sorry for the trashy code, i just started hehehe

```<code>import 'dart:ui';

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Image.asset(
          'assets/images/wp_logo.png',
          height: 250,
        ),
        Stack(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  'assets/images/text_bg.png',
                  height: 150,
                ),
                Image.asset(
                  'assets/images/text_bg.png',
                  height: 150,
                ),
              ],
            ),
            Positioned(
              top: 125,
              left: 125,
              child: Image.asset(
                'assets/images/text_bg.png',
                height: 150,
              ),
            ),
          ],
        ),
      ],
    )));
  }
}
</code>```

答:
You can set Overflow of Stack to visible:

Solution 1:

```<code>class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(
            'assets/wp_logo.png',
            height: 250,
          ),
          Stack(
            // Set overflow to visible like shown below
            overflow: Overflow.visible,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                  Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                ],
              ),
              Positioned(
                top: 125,
                left: 145,
                child: Image.asset(
                  'assets/text_bg.png',
                  height: 150,
                ),
              ),
            ],
          ),
        ],
      ))),
    );
  }
}

</code>```

Your Stack block does not have height big enough to accommodate those last three images.
So can wrap the Stack in Container and give it a height of 300 or more as image height is 150 and there are two rows making it 300.

Here is the solution 2:

```<code>class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(
            'assets/wp_logo.png',
            height: 250,
          ),
          Container(
            height: 350,
            child: Stack(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset(
                      'assets/text_bg.png',
                      height: 150,
                    ),
                    Image.asset(
                      'assets/text_bg.png',
                      height: 150,
                    ),
                  ],
                ),
                Positioned(
                  top: 125,
                  left: 145,
                  child: Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                ),
              ],
            ),
          ),
        ],
      ))),
    );
  }
}
</code>```

Output:

Title: How to customize Stack height Flutter

Body:
I'm new here

just wondering how could I fit these 3 image into a stack in flutter, the first 2 fit good with row,
but the last is kinda offset the height of the stack.

ps* im sorry for the trashy code, i just started hehehe

import 'dart:ui';

import 'package:flutter/material.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Image.asset(
          'assets/images/wp_logo.png',
          height: 250,
        ),
        Stack(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  'assets/images/text_bg.png',
                  height: 150,
                ),
                Image.asset(
                  'assets/images/text_bg.png',
                  height: 150,
                ),
              ],
            ),
            Positioned(
              top: 125,
              left: 125,
              child: Image.asset(
                'assets/images/text_bg.png',
                height: 150,
              ),
            ),
          ],
        ),
      ],
    )));
  }
}

Body:
You can set Overflow of Stack to visible:

Solution 1:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(
            'assets/wp_logo.png',
            height: 250,
          ),
          Stack(
            // Set overflow to visible like shown below
            overflow: Overflow.visible,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                  Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                ],
              ),
              Positioned(
                top: 125,
                left: 145,
                child: Image.asset(
                  'assets/text_bg.png',
                  height: 150,
                ),
              ),
            ],
          ),
        ],
      ))),
    );
  }
}

Your Stack block does not have height big enough to accommodate those last three images.
So can wrap the Stack in Container and give it a height of 300 or more as image height is 150 and there are two rows making it 300.

Here is the solution 2:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Center(
              child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(
            'assets/wp_logo.png',
            height: 250,
          ),
          Container(
            height: 350,
            child: Stack(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset(
                      'assets/text_bg.png',
                      height: 150,
                    ),
                    Image.asset(
                      'assets/text_bg.png',
                      height: 150,
                    ),
                  ],
                ),
                Positioned(
                  top: 125,
                  left: 145,
                  child: Image.asset(
                    'assets/text_bg.png',
                    height: 150,
                  ),
                ),
              ],
            ),
          ),
        ],
      ))),
    );
  }
}

Output:


问:
Django manage.py: Migration applied before its dependency
When running python manage.py migrate I encounter this error:

```<code>django.db.migrations.exceptions.InconsistentMigrationHistory: Migration
<appname>.0016_auto_<date2>_<time2> is applied before its dependency
<appname>.0001_squashed_0015_auto_<date1>_<time1>
</code>```

running python manage.py showmigrations returns:

```<code><appname>
 [X] 0001_squashed_0015_auto_<date1>_<time1> (15 squashed migrations)
 [X] 0016_auto_<date2>_<time2>
 [ ] 0017_<modelname>_squashed_0019_auto_<date3>_<time3> (3 squashed migrations)
</code>```

I was trying out django-extensions yesterday, when it all got messed up after me running some direct SQL queries and I reset hard using git. I'm still learning about migrations, so I don't understand what is wrong, since it seems to me that both migrations already have been applied.

Thank you for your help!

答:
Delete the migration files.

Run:

```<code>python manage.py migrate
python manage.py makemigrations
python manage.py migrate
python manage.pyrunserver
</code>```

Body:
When running python manage.py migrate I encounter this error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration
<appname>.0016_auto_<date2>_<time2> is applied before its dependency
<appname>.0001_squashed_0015_auto_<date1>_<time1>

running python manage.py showmigrations returns:

<appname>
 [X] 0001_squashed_0015_auto_<date1>_<time1> (15 squashed migrations)
 [X] 0016_auto_<date2>_<time2>
 [ ] 0017_<modelname>_squashed_0019_auto_<date3>_<time3> (3 squashed migrations)

I was trying out django-extensions yesterday, when it all got messed up after me running some direct SQL queries and I reset hard using git. I'm still learning about migrations, so I don't understand what is wrong, since it seems to me that both migrations already have been applied.

Thank you for your help!

Body:
Delete the migration files.

Run:

python manage.py migrate
python manage.py makemigrations
python manage.py migrate
python manage.pyrunserver


问:
Replace value in dynamic list of dictionary loaded from alertmanager yml?
This question is quite specific, I successfully done want I want but it's very specific to my use case and probably ugly for Python expert so I'me curious if it can be more generic and/or clever.

I need to edit prometheus alertmanager routing stored in yml file (documentation here)

In my use case my routing is (extract):

```<code>route:
  routes:
    - match:
        product: my_product
        stage: prod
      routes:
        - continue: true
          match_re:
            severity: (info|warning|critical)
          receiver: mattermost
        - continue: true
          match_re:
            severity: (warning|critical)
          receiver: mail_infra
        - match:
            severity: critical
          receiver: sms_voidandnany
</code>```

I need to edit receiver "sms_voidandnany" (the receiver depend on a google calendar).

Here is my first draft:

with open('alertmanager.yml') as f:
    data = yaml.safe_load(f)
    routes=data['route']['routes']

    for item in routes:
        if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod':
            for subitem in item.get('routes'):
                if 'match' in subitem:
                    if subitem.get('match').get('severity') == 'critical':
                        subitem['receiver'] = 'sms_another_user'

with open("alertmanager2.yaml", "w") as f:
    yaml.dump(data, f)
```

3 ifs, 2 loops even me, not a python expert neither full time developer I think it's ugly.

Do you see a better way, more Pythonistic way to achieve that?

Cherry on the cake, do you think there a "simple" way to make replacement generic?
Routing structure is dynamic, we can make routing - matching - routing - matching and so on...
Recursive function?

答:
Your Queries seems to be more specific here, so we will not be able to rewrite much. But here is my try</p>

```<code>import yaml
with open('alertmanager.yml') as f:
    data = yaml.safe_load(f)
    subitems = [subitem for item in data['route']['routes'] for subitem in item.get('routes') if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod']

    for subitem in subitems:
        if 'match' in subitem and subitem.get('match').get('severity') == 'critical':
            subitem['receiver'] = 'sms_another_user'

with open("alertmanager2.yaml", "w") as f:
    yaml.dump(data, f)

</code>```

Body:
This question is quite specific, I successfully done want I want but it's very specific to my use case and probably ugly for Python expert so I'me curious if it can be more generic and/or clever.

I need to edit prometheus alertmanager routing stored in yml file (documentation here)

In my use case my routing is (extract):

route:
  routes:
    - match:
        product: my_product
        stage: prod
      routes:
        - continue: true
          match_re:
            severity: (info|warning|critical)
          receiver: mattermost
        - continue: true
          match_re:
            severity: (warning|critical)
          receiver: mail_infra
        - match:
            severity: critical
          receiver: sms_voidandnany

I need to edit receiver "sms_voidandnany" (the receiver depend on a google calendar).

Here is my first draft:

with open('alertmanager.yml') as f:
    data = yaml.safe_load(f)
    routes=data['route']['routes']

    for item in routes:
        if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod':
            for subitem in item.get('routes'):
                if 'match' in subitem:
                    if subitem.get('match').get('severity') == 'critical':
                        subitem['receiver'] = 'sms_another_user'

with open("alertmanager2.yaml", "w") as f:
    yaml.dump(data, f)

3 ifs, 2 loops even me, not a python expert neither full time developer I think it's ugly.

Do you see a better way, more Pythonistic way to achieve that?

Cherry on the cake, do you think there a "simple" way to make replacement generic?
Routing structure is dynamic, we can make routing - matching - routing - matching and so on...
Recursive function?

Body:
Your Queries seems to be more specific here, so we will not be able to rewrite much. But here is my try

import yaml
with open('alertmanager.yml') as f:
    data = yaml.safe_load(f)
    subitems = [subitem for item in data['route']['routes'] for subitem in item.get('routes') if item.get('match').get('product') == 'my_product' and item.get('match').get('stage') == 'prod']

    for subitem in subitems:
        if 'match' in subitem and subitem.get('match').get('severity') == 'critical':
            subitem['receiver'] = 'sms_another_user'

with open("alertmanager2.yaml", "w") as f:
    yaml.dump(data, f)


问:
code2flow can't find graphviz in the path
I'm trying to get some code to run and I'm triggering an error:

```<code>if not isInstalled('dot') and not isInstalled('dot.exe'):
    print "You must have graphviz (specifically dot) installed to run code2flow"
    sys.exit(1)
</code>```

which calls

```<code>def isInstalled(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    for path in os.environ["PATH"].split(os.pathsep):
        path = path.strip('"')
        exe_file = os.path.join(path, program)
        if is_exe(exe_file):
            return True

    return False
</code>```

But I don't understand why this is failing. My path contains graphviz

> echo %PATH%

...;c:\Program Files (x86)\Graphviz2.38\bin;...

and the file is present

> dir "c:\Program Files (x86)\Graphviz2.38\bin\dot.exe"

Directory of c:\Program Files (x86)\Graphviz2.38\bin

04/14/2014  09:22 AM             7,680 dot.exe

Any ideas of what is going wrong?

答:
I have this error, too.

I try to run the command:

```<code>sudo python setup.py install
</code>```

It's okay now.

My way to install code2flow is by using pip install.

But the codes inside ./ur/path/to/code2flow is written with python2.

Thus!

Body:
I'm trying to get some code to run and I'm triggering an error:

if not isInstalled('dot') and not isInstalled('dot.exe'):
    print "You must have graphviz (specifically dot) installed to run code2flow"
    sys.exit(1)

which calls

def isInstalled(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    for path in os.environ["PATH"].split(os.pathsep):
        path = path.strip('"')
        exe_file = os.path.join(path, program)
        if is_exe(exe_file):
            return True

    return False

But I don't understand why this is failing. My path contains graphviz

> echo %PATH%

...;c:\Program Files (x86)\Graphviz2.38\bin;...

and the file is present

> dir "c:\Program Files (x86)\Graphviz2.38\bin\dot.exe"

Directory of c:\Program Files (x86)\Graphviz2.38\bin

04/14/2014  09:22 AM             7,680 dot.exe

Any ideas of what is going wrong?

Body:
I have this error, too.

I try to run the command:

sudo python setup.py install

It's okay now.

My way to install code2flow is by using pip install.

But the codes inside ./ur/path/to/code2flow is written with python2.

Thus!


问:
Is it possible to have a shared global variable for inter-process communication?
I need to solve a concurrency assignment for my operating systems class. I don't want the solution here, but I am lacking one part.

We should write a process that writes to file, reads from it and then deltetes it. This process we should run two times in two different shells. No fork here for simplicity. Process A should write, Process B then read and then Process should delete the file. Afterwards they switch roles.

I understand that you can achieve atomicity easily by locking. With while loops around the read-, and write sections etc. you can also get further control. But when I run process A and then process B, process B will spin before the write seciton until it achieves the lock and not got into reading when process A releases the lock. So my best guess is to have a read and a write lock. This information must be shared somehow between the processes. The only way I can think of is some global variable, but since both processes hold copies of the variables, I think this is not possible. Another way would be to have a read lock file and a write lock file, but that seems overly complicated to me.

Is there a better way?

答: You can use file as a lock. Two processes try to create a file with a previously agreed upon name using the O_EXCL flag. Only one will succeed. The one that succeeds gets the access to the resource. So in this case process A should try to create a file with name say, foo, with O_EXCL flag and, if successful, it should go ahead and write to file the information. After its work is complete, Process A should unlink foo. Process B should try to create file foo with O_EXCL flag, and if successful, try to read the file created by Process A. After its attempt is over, Process B should unlink the file foo. That way only one process will be accessing the file at any time.


问:
How to fill areas with two different colors using step lines (step curves) in pylab (pyplot)?
This is my first question, so be kind!

I've plotted two lines (step lines), y1 and y2, where y1 is a list with some random numbers and y2 is each previous number from y1 list.

```<code>from pylab import *

y1 = ([100, 101, 102, 103, 102, 101, 102, 103])
y2 = ([100, 100, 101, 102, 103, 102, 101, 102])
x = (list(range(len(y1))))

plot(x, y1,  linestyle='steps', drawstyle="steps")
plot(x, y2,  linestyle='steps', drawstyle="steps")
xlabel('No.')
ylabel('Level')
title('Step Lines Chart')
grid(True)
fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3, step="pre")
show()
</code>```

From here I want to fill between these lines with two colors, when y1 > y2 with a color and when y1 < y2 with another color, but I am able to fill only with one color...

I tried with where=(y1 < y2)... condition, also tried to replicate the docs example from here, but for no reason will not pop up the window with the chart.

So I'm kinda stuck...

答:
Ok, I used numpy array and it worked partially, if y1 and y2 are like in the example, both colors will be plotted only when the square rise or fall, but when two squares are at the same level, there is no fill...

```<code>from pylab import *
import numpy as np

y1 = np.array([100, 101, 102, 103, 102, 101, 102, 103])
y2 = np.array([100, 100, 101, 102, 103, 102, 101, 102])

#y1 = np.array([100,100, 101,101, 102,102, 103,103, 102,102, 101,101, 102,102, 103,103])
#y2 = np.array([100,100, 100,100, 101,101, 102,102, 103,103, 102,102, 101,101, 102,102])

x = np.array(list(range(len(y1))))

plot(x, y1, '-', drawstyle="steps")
plot(x, y2, '-', drawstyle="steps")
xlabel('No.')
ylabel('Level')
title('Step Lines Chart')
grid(True)
fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 == y2), color='yellow', alpha=0.3, step="pre")
show()
</code>```

I tried to double all numbers (see commented syntax) and worked a little bit better, but not still is not perfect, now will plot well, but when two squares are at the same level, will fill only half of the square

All I need is when y1(blue line) is greater than y2(orange line), the square to be filled with blue and y1 < y2 filled with orange color

Body:
This is my first question, so be kind!

I've plotted two lines (step lines), y1 and y2, where y1 is a list with some random numbers and y2 is each previous number from y1 list.

from pylab import *

y1 = ([100, 101, 102, 103, 102, 101, 102, 103])
y2 = ([100, 100, 101, 102, 103, 102, 101, 102])
x = (list(range(len(y1))))

plot(x, y1,  linestyle='steps', drawstyle="steps")
plot(x, y2,  linestyle='steps', drawstyle="steps")
xlabel('No.')
ylabel('Level')
title('Step Lines Chart')
grid(True)
fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3, step="pre")
show()

From here I want to fill between these lines with two colors, when y1 > y2 with a color and when y1 < y2 with another color, but I am able to fill only with one color...

I tried with where=(y1 < y2)... condition, also tried to replicate the docs example from here, but for no reason will not pop up the window with the chart.

So I'm kinda stuck...

Body:
Ok, I used numpy array and it worked partially, if y1 and y2 are like in the example, both colors will be plotted only when the square rise or fall, but when two squares are at the same level, there is no fill...

from pylab import *
import numpy as np

y1 = np.array([100, 101, 102, 103, 102, 101, 102, 103])
y2 = np.array([100, 100, 101, 102, 103, 102, 101, 102])

#y1 = np.array([100,100, 101,101, 102,102, 103,103, 102,102, 101,101, 102,102, 103,103])
#y2 = np.array([100,100, 100,100, 101,101, 102,102, 103,103, 102,102, 101,101, 102,102])

x = np.array(list(range(len(y1))))

plot(x, y1, '-', drawstyle="steps")
plot(x, y2, '-', drawstyle="steps")
xlabel('No.')
ylabel('Level')
title('Step Lines Chart')
grid(True)
fill_between(x, y1, y2, where=(y1 > y2), color='C0', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 < y2), color='C1', alpha=0.3, step="pre")
fill_between(x, y1, y2, where=(y1 == y2), color='yellow', alpha=0.3, step="pre")
show()

I tried to double all numbers (see commented syntax) and worked a little bit better, but not still is not perfect, now will plot well, but when two squares are at the same level, will fill only half of the square

All I need is when y1(blue line) is greater than y2(orange line), the square to be filled with blue and y1 < y2 filled with orange color


问:
Global variables changing whilst setTimeout() in operation
I've been looking for hours for a solution to this but with no luck.
1) The user clicks a button and an image file name is saved to a global variable.
2) The user clicks on another div on the page and first an animated image plays for 5 seconds.
3) After 5 seconds the animated image is replaced (at same 'src' location) by the image file reference saved to a global variable in stage 1.

This all works great as long as the user doesn't click a different image (thus changing the variable in stage 1) during those 5 seconds, if they do then the variable is updated before the second image is placed.

I've tried using bracket notation to send the contents of the variable to another function, because I thought this would make the variable 'pause' somehow unique, but that doesn't work. I've also split the functions up but that doesn't help.
I've never used an array before but I also tried pushing each selection into the back of an array and pulling out the first item when required, but this was a little beyond me. Can anyone suggest the best way to store each variable uniquely for those 5 seconds?

```<code>  function makeSelection(iGCode) {
    var itemGroupVar = $(event.target).attr('id');
    /*var itemGroupGet = document.getElementById(itemGroup);*/
    var groupIDBColor = document.getElementById(itemGroupVar).style.backgroundColor;
    selectedItemCache = iGCode;
    if (groupIDBColor == '') {
      resetHighlighted();
      document.getElementById(itemGroupVar).style.backgroundColor = 'rgba(255, 0, 0)';
    } else {
      document.getElementById(itemGroupVar).style.backgroundColor = '';
      selectedItemCache = '';
    }
  }

  function populateCell(clicked_id)
  {
      var clicked_id2 = "i"+clicked_id;
      document.getElementById(clicked_id2).src = 'images/constructionAnim/constructionAnim1.svg';
      pauseBuild([clicked_id2]);
  }
  function pauseBuild(pause)
  {
    setTimeout(function()
    {
      document.getElementById(pause).src = selectedItemCache;
    }, 4000);
  }
</code>```

```<code><div class="itemGroup itemsRes" id="group1" onclick="makeSelection('images/h100-500-1f-01.svg')">

<div class="r1d allCells" id="c0001" onClick="populateCell(this.id)"><img id="ic0001" src=""></div>
<div class="r1d allCells" id="c0002" onClick="populateCell(this.id)"><img id="ic0002" src=""></div>
</code>```

答:
Taplar nailed it. I needed to make both variable names unique with []. I hadn't realised this as the contents of only one was unique but of course it was the variable name which was causing an issue. Thanks all for your help.</p>

```<code>  function populateCell(clicked_id)
  {
      var clicked_id2 = "i"+clicked_id;
      document.getElementById(clicked_id2).src = 'images/constructionAnim/constructionAnim1.svg';
      var selectedItemCache2 = selectedItemCache;
      pauseBuild([clicked_id2],[selectedItemCache2]);
  }
  function pauseBuild(pause,pause2)
  {
    setTimeout(function()
    {
      document.getElementById(pause).src = pause2;
    }, 4000);
  }
</code>```

Body:
I've been looking for hours for a solution to this but with no luck.
1) The user clicks a button and an image file name is saved to a global variable.
2) The user clicks on another div on the page and first an animated image plays for 5 seconds.
3) After 5 seconds the animated image is replaced (at same 'src' location) by the image file reference saved to a global variable in stage 1.

This all works great as long as the user doesn't click a different image (thus changing the variable in stage 1) during those 5 seconds, if they do then the variable is updated before the second image is placed.

I've tried using bracket notation to send the contents of the variable to another function, because I thought this would make the variable 'pause' somehow unique, but that doesn't work. I've also split the functions up but that doesn't help.
I've never used an array before but I also tried pushing each selection into the back of an array and pulling out the first item when required, but this was a little beyond me. Can anyone suggest the best way to store each variable uniquely for those 5 seconds?

  function makeSelection(iGCode) {
    var itemGroupVar = $(event.target).attr('id');
    /*var itemGroupGet = document.getElementById(itemGroup);*/
    var groupIDBColor = document.getElementById(itemGroupVar).style.backgroundColor;
    selectedItemCache = iGCode;
    if (groupIDBColor == '') {
      resetHighlighted();
      document.getElementById(itemGroupVar).style.backgroundColor = 'rgba(255, 0, 0)';
    } else {
      document.getElementById(itemGroupVar).style.backgroundColor = '';
      selectedItemCache = '';
    }
  }

  function populateCell(clicked_id)
  {
      var clicked_id2 = "i"+clicked_id;
      document.getElementById(clicked_id2).src = 'images/constructionAnim/constructionAnim1.svg';
      pauseBuild([clicked_id2]);
  }
  function pauseBuild(pause)
  {
    setTimeout(function()
    {
      document.getElementById(pause).src = selectedItemCache;
    }, 4000);
  }

Body:
Taplar nailed it. I needed to make both variable names unique with []. I hadn't realised this as the contents of only one was unique but of course it was the variable name which was causing an issue. Thanks all for your help.

  function populateCell(clicked_id)
  {
      var clicked_id2 = "i"+clicked_id;
      document.getElementById(clicked_id2).src = 'images/constructionAnim/constructionAnim1.svg';
      var selectedItemCache2 = selectedItemCache;
      pauseBuild([clicked_id2],[selectedItemCache2]);
  }
  function pauseBuild(pause,pause2)
  {
    setTimeout(function()
    {
      document.getElementById(pause).src = pause2;
    }, 4000);
  }


问:
Using a search function for arrays of different types of structs in C
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

```<code>typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;
</code>```

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

```<code>book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}
</code>```

And instead be able to perform the search for both data structures in a single function?

答:
You might consider using a struct like this and writing a function to check for the type and then either call one of the specialized functions that know how to search for books and magazines.

```<code>typedef enum { INVALID, BOOK, MAGAZINE } itemType;

typedef struct {
  union {
  book b;
  magazine m;
  } u;

  itemType type;
} Item;
</code>```

You can initialize your array with your items, also setting the type for each one. The last item can be one with type INVALID to signify the end of the array, or you can pass a size to your search function.

The function might loosely look like this:

```<code>Item *search(Item *array, int key){
    Item * result = NULL;
    ...
    switch (array[i].type)
    {
       case BOOK: < do book search here using array[i].u.b >
                  if (found) result = array[i];
       break;
       case MAGAZINE: < do magazine search here using array[i].u.m>
                  if (found) result = array[i];
       break;
       default: // handle invalid case here
       break;
    }
    ...
    return result;
}
</code>```

Body:
I'm currently working in my beginner's programming course project and in it I have to perform several searches in arrays of structures, for example I have these two different structures:

typedef struct{
  char name[SIZE];
  int number, year, isbn;
}magazine;

typedef struct{
  char title[SIZE];
  char author[SIZE];
  int isbn, year;
}book;

As you can see, both book and magazine have isbn as a common element, and queries made with the isbn can be made for both data structures, my question is, how can I make (or use a glibc) function that is general purpose, without having to do this:

book *search_book(book *array, int key){
   //We search a book by its isbn and return the pointer.
}

magazine *search_mag(magazine *array, int key){
  //We search a magazine by its isbn and return the pointer
}

And instead be able to perform the search for both data structures in a single function?

Body:
You might consider using a struct like this and writing a function to check for the type and then either call one of the specialized functions that know how to search for books and magazines.

typedef enum { INVALID, BOOK, MAGAZINE } itemType;

typedef struct {
  union {
  book b;
  magazine m;
  } u;

  itemType type;
} Item;

You can initialize your array with your items, also setting the type for each one. The last item can be one with type INVALID to signify the end of the array, or you can pass a size to your search function.

The function might loosely look like this:

Item *search(Item *array, int key){
    Item * result = NULL;
    ...
    switch (array[i].type)
    {
       case BOOK: < do book search here using array[i].u.b >
                  if (found) result = array[i];
       break;
       case MAGAZINE: < do magazine search here using array[i].u.m>
                  if (found) result = array[i];
       break;
       default: // handle invalid case here
       break;
    }
    ...
    return result;
}


问:
Deleting 50 rows in 3 tables using IN () in SQL Server so slow
I'm running a pretty straight forward delete statement query. I have 50 'file' keys and I want to delete them.  Our database schema looks like this:

File - UID (int) column is primary key (with unique, clustered index)

Version - File column is foreign key to File.UID, DataLockerToken column is foreign key to Cache.UID

Cache - UID (uniqueidentifier) column is primary key (with unique, non-clustered index)

Version had to index suggestions from SQL that I applied:

```<code>CREATE NONCLUSTERED INDEX [nc_VersionFile_DataLockerToken]
ON [dbo].[Version] ([File] ASC) INCLUDE([DataLockerToken])

CREATE NONCLUSTERED INDEX [nc_VersionFile_UID]
ON [dbo].[Version] ([File] ASC) INCLUDE([UID])
</code>```

Relationships: File 1:M to Version 1:1 to Cache

Here is the query I try to execute:

```<code>DELETE [Cache]
FROM [Cache] c
INNER JOIN Version v ON c.UID = v.DataLockerToken
WHERE v.[File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE Version
WHERE [File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE [File]
WHERE UID IN ( 241647, ... 50 ids in total ..., 244038 );
</code>```

This takes almost 1 minute and I'd expect it to be practically immediate. The File and Version tables are simply metadata, while the Cache table actually holds the binary info for the file.

Here is a screen shot of the execution plan:

UPDATE: It must be something with the Cache table or the binary info inside, because if I run the query in SQL Server Management Studio, as I said it takes ~1 minute. Then if I run the exact same query (same keys, so obviously they are not there) again in Management Studio or even a C# console app, the query is immediate, so unless there is some sort of 'query caching' which I don't think there is, this points to the fact that the data being deleted is the problem versus a problem with the query?

With that minimal info, anyone see and glaring problems in the execution plan?  I usually rely on SQL to give me an index hint if needed (and I know you can't always trust SQL), but it isn't like this db schema is so complicated.

Let me know if there is a better platform to ask this question on if this is not the correct place.

答:
SQL will cache the query plans, so the 2nd time it will be much faster. you can clean the buffers and rerun the queries to see the difference (DBCC FREEPROCCACHE)

also notice the query cost for the deletes themselves. you dont have to do those anymore. and depending on what you query you barely get any information. for example, a select count(*) will result a lot faster since count is simpler then removing a row

comparing a delete on a fresh table vs a delete with no result is not really a valid comparison.

you could put the 50 id's in a clustered table. the IN clause isnt the best and you're re-using the same set several times. but i doubt that makes that much of a difference tbh

Body:
I'm running a pretty straight forward delete statement query. I have 50 'file' keys and I want to delete them.  Our database schema looks like this:

File - UID (int) column is primary key (with unique, clustered index)

Version - File column is foreign key to File.UID, DataLockerToken column is foreign key to Cache.UID

Cache - UID (uniqueidentifier) column is primary key (with unique, non-clustered index)

Version had to index suggestions from SQL that I applied:

CREATE NONCLUSTERED INDEX [nc_VersionFile_DataLockerToken]
ON [dbo].[Version] ([File] ASC) INCLUDE([DataLockerToken])

CREATE NONCLUSTERED INDEX [nc_VersionFile_UID]
ON [dbo].[Version] ([File] ASC) INCLUDE([UID])

Relationships: File 1:M to Version 1:1 to Cache

Here is the query I try to execute:

DELETE [Cache]
FROM [Cache] c
INNER JOIN Version v ON c.UID = v.DataLockerToken
WHERE v.[File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE Version
WHERE [File] IN ( 241647, ... 50 ids in total ..., 244038 );

DELETE [File]
WHERE UID IN ( 241647, ... 50 ids in total ..., 244038 );

This takes almost 1 minute and I'd expect it to be practically immediate. The File and Version tables are simply metadata, while the Cache table actually holds the binary info for the file.

Here is a screen shot of the execution plan:

UPDATE: It must be something with the Cache table or the binary info inside, because if I run the query in SQL Server Management Studio, as I said it takes ~1 minute. Then if I run the exact same query (same keys, so obviously they are not there) again in Management Studio or even a C# console app, the query is immediate, so unless there is some sort of 'query caching' which I don't think there is, this points to the fact that the data being deleted is the problem versus a problem with the query?

With that minimal info, anyone see and glaring problems in the execution plan?  I usually rely on SQL to give me an index hint if needed (and I know you can't always trust SQL), but it isn't like this db schema is so complicated.

Let me know if there is a better platform to ask this question on if this is not the correct place.


问:
Exception has occurred: TypeError 'in <string>' requires string as left operand, not Series
I am working with Pandas in python I have 2 Dataframes that I am trying to pull infromation from one to the other.  Here is a example of the code.

```<code>    import pandas as pd

employees = {'Names': ['John','Jack','Frank','Mike'],
             'Employee_id': ['123', '124', '125', '126'],
             'Leader': ['','','','']}

df1 = pd.DataFrame(employees, columns = ['Names', 'Employee_id', 'Leader'])

print(df1)

leader = {'Employee_id': ['123', '124', '125', '126'],
          'Supervisor': ['Nick', 'Jeff', 'Nick', 'Jeff']}

df2 = pd.DataFrame(leader, columns = ['Employee_id', 'Supervisor'])
print(df2)

df1['Leader'] = df1['Employee_id'].map(lambda x: df2['Supervisor'] if df2['Employee_id'] in x else "")

print(df1)
</code>```

Here is the error.

```<code>Exception has occurred: TypeError
'in <string>' requires string as left operand, not Series
</code>```

Not sure what I am doing wrong.

Thank you for your help.

答:
Use df.merge:

```<code>In [79]: df = df1.merge(df2, on='Employee_id')

In [80]: df
Out[80]:
   Names Employee_id Leader Supervisor
0   John         123              Nick
1   Jack         124              Jeff
2  Frank         125              Nick
3   Mike         126              Jeff
</code>```

Body:
I am working with Pandas in python I have 2 Dataframes that I am trying to pull infromation from one to the other.  Here is a example of the code.

    import pandas as pd

employees = {'Names': ['John','Jack','Frank','Mike'],
             'Employee_id': ['123', '124', '125', '126'],
             'Leader': ['','','','']}

df1 = pd.DataFrame(employees, columns = ['Names', 'Employee_id', 'Leader'])

print(df1)

leader = {'Employee_id': ['123', '124', '125', '126'],
          'Supervisor': ['Nick', 'Jeff', 'Nick', 'Jeff']}

df2 = pd.DataFrame(leader, columns = ['Employee_id', 'Supervisor'])
print(df2)

df1['Leader'] = df1['Employee_id'].map(lambda x: df2['Supervisor'] if df2['Employee_id'] in x else "")

print(df1)

Here is the error.

Exception has occurred: TypeError
'in <string>' requires string as left operand, not Series

Not sure what I am doing wrong.

Thank you for your help.

Body:
Use df.merge:

In [79]: df = df1.merge(df2, on='Employee_id')

In [80]: df
Out[80]:
   Names Employee_id Leader Supervisor
0   John         123              Nick
1   Jack         124              Jeff
2  Frank         125              Nick
3   Mike         126              Jeff


问:
How to handle long tap on ListView item?
How can I catch such event? onCreateContextMenu is quite similiar, but I don't need menu.

答:
It's hard to know what you need to achieve. But my guess is that you want to perform some acion over the item that receives the long click. For that, you have two options:

add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.

.

```<code>listView.setOnItemLongClickListener (new OnItemLongClickListener() {
  public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
    //do your stuff here
  }
});
</code>```

if you are creating a custom adapter, add a View.OnLongClickListener when creating the View in the method Adapter#getView(...)

Body:
It's hard to know what you need to achieve. But my guess is that you want to perform some acion over the item that receives the long click. For that, you have two options:

add an AdapterView.OnItemLongClickListener. See setOnItemLongClickListener.

.

listView.setOnItemLongClickListener (new OnItemLongClickListener() {
  public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
    //do your stuff here
  }
});

if you are creating a custom adapter, add a View.OnLongClickListener when creating the View in the method Adapter#getView(...)


问:
Embed Jitsi video conference into Vuejs app
I am trying embed Jitsi into my vuejs app.

I have follow the docs in https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-iframe.

But I have no success. I always get an error

Jitsi Meet API script not loaded

What am I doing wrong?

```<code><template>
  <v-card class="ma-2">
    <v-container>
      <v-layout>
        {{ message }}
        <div id="meet"></div>
        <!-- missing -->
      </v-layout>
    </v-container>
  </v-card>
</template>

<script src="https://meet.jit.si/external_api.js"></script>

<script>
export default {
  name: "AtendimentoMedico",
  data: () => ({
    search: "",
    message: "Hello",
    api: null,
    room: "test romm",
    username: "rabie",
  }),

  mounted() {
    this.openRoom();
  },

  methods: {
    startConference() {
      var _this = this;
      try {
        const domain = "meet.jit.si";
        const options = {
          roomName: this.room,
          height: 500,
          parentNode: document.querySelector("#meet"),
          interfaceConfigOverwrite: {
            filmStripOnly: false,
            SHOW_JITSI_WATERMARK: false,
          },
          configOverwrite: {
            disableSimulcast: false,
          },
        };

        this.api = new JitsiMeetExternalAPI(domain, options);
        this.api.addEventListener("videoConferenceJoined", () => {
          console.log("Local User Joined");

          _this.api.executeCommand("displayName", _this.username);
        });
      } catch (error) {
        console.error("Failed to load Jitsi API", error);
      }
    },
    openRoom() {
      // verify the JitsiMeetExternalAPI constructor is added to the global..
      if (window.JitsiMeetExternalAPI) {
        var person = prompt("Please enter your name:", "Rabie");
        if (person != null || person != "") this.username = person;
        var room = prompt("Please enter your room:", "Test Room");
        if (room != null || room != "") this.room = room;
        this.startConference();
      } else alert("Jitsi Meet API script not loaded");
    },
  },
};
</script>
</code>```

答: Load the script in your index.html</p>

Body:
I am trying embed Jitsi into my vuejs app.

I have follow the docs in https://jitsi.github.io/handbook/docs/dev-guide/dev-guide-iframe.

But I have no success. I always get an error

Jitsi Meet API script not loaded

What am I doing wrong?

<template>
  <v-card class="ma-2">
    <v-container>
      <v-layout>
        {{ message }}

      </v-layout>
    </v-container>
  </v-card>
</template>

Body: Load the script in your index.html