问:
C++ "oldstyle container ": pointer/ array/ new - possible missconception?
Im just playing arround, just dont get why the first version works while the second one fails?

```<code>using namespace std;

#include <iostream>

int main(){

    int a,b;
    double d{3035.4534536};
    cout<<"Size of: int "<<sizeof (int)<<" double "<<sizeof (double)<<endl;

    a=*((int*)&d);
    b=((int*)&d)[1];
    int dd[2]; //{a,b};
    dd[0]=a; dd[1]=b;
    cout<<"a: "<<a<<" |b: "<<b<<endl;
    cout<<"d: "<<d<<" |: "<<*((double*)&dd)<<endl;

    // int  size=sizeof(d)/sizeof(int)+1, *temp= new int[size],
        // *f{(int*)(&d)}, *t{temp}, *s{t+size};
    // while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
    // cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
    // delete[] temp;

    int size=sizeof(d)/sizeof(int)+1, *temp= new int[size];
    char *f{(char*)&d}, *t{(char*)temp}, *s{t+sizeof(d)};
    while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
    cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
    delete[] temp;
}
</code>```

...im aware that, "thats exactly WHY there are containers", it pure curiosity, and i just wanna understand whats the problem with the second?

Is there a conversion somewhere that im not aware of?

Or is the pointer thats returned by new-Statement more than a plain pointer to the first element?

答:
```<code> a=*((int*)&d);
</code>```

Is incorrect. When you do (int*), you use a reinterpret_cast.

&d is a pointer-to-double. You cannot convert a pointer-to-double to a pointer-to-int. Well, you can, but you cannot do the next operation, dereferencing it. As soon as you try to read the memory point to by (int*)&d as an integer, you get undefined behaviour.

What happens from there is, well, complex and undefined. Don't go there.

Body:
Im just playing arround, just dont get why the first version works while the second one fails?

using namespace std;

#include <iostream>

int main(){

    int a,b;
    double d{3035.4534536};
    cout<<"Size of: int "<<sizeof (int)<<" double "<<sizeof (double)<<endl;

    a=*((int*)&d);
    b=((int*)&d)[1];
    int dd[2]; //{a,b};
    dd[0]=a; dd[1]=b;
    cout<<"a: "<<a<<" |b: "<<b<<endl;
    cout<<"d: "<<d<<" |: "<<*((double*)&dd)<<endl;

    // int  size=sizeof(d)/sizeof(int)+1, *temp= new int[size],
        // *f{(int*)(&d)}, *t{temp}, *s{t+size};
    // while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
    // cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
    // delete[] temp;

    int size=sizeof(d)/sizeof(int)+1, *temp= new int[size];
    char *f{(char*)&d}, *t{(char*)temp}, *s{t+sizeof(d)};
    while(t!=s) { *t=*f; ++f; ++t; cout<<"."; }
    cout<<"dOrig.: "<<d<<" |temp: "<<*((double*)&temp)<<endl;
    delete[] temp;
}

...im aware that, "thats exactly WHY there are containers", it pure curiosity, and i just wanna understand whats the problem with the second?

Is there a conversion somewhere that im not aware of?

Or is the pointer thats returned by new-Statement more than a plain pointer to the first element?

Body:
 a=*((int*)&d);

Is incorrect. When you do (int*), you use a reinterpret_cast.

&d is a pointer-to-double. You cannot convert a pointer-to-double to a pointer-to-int. Well, you can, but you cannot do the next operation, dereferencing it. As soon as you try to read the memory point to by (int*)&d as an integer, you get undefined behaviour.

What happens from there is, well, complex and undefined. Don't go there.


来源: stackexchange

问:
How to fix end of statement when trying to insert multiple values in SQL?
I just started a database course that is going over SQL using Access 2016.  I am getting a End of statement error and I am unsure how to fix it.

My table code is `

```<code>Create Table Pet_Owner (
OwnerID autoincrement Null,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone Int Null,
OwnerEmail VarChar(100) Not Null Unique,
Constraint Pet_Owner_PK Primary Key(OwnerID)
);
</code>```

and the insert query I have so far that I am trying to add is

```<code>Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com')
Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail) Values (
'Trent', 'Miles', 'Miles.Trent@somewhere.com') ;
</code>```

When I use append, it is saying I am missing a semicolon at the end of the first set of values, but if i add that then it says i have characters at the end of my statement. If anyone can help me out or point me into the right direction to solve the error I would greatly appreciate it. Thank you

答:
Your insert query includes 4 INSERT ... VALUES statements.  So when you attempt to run that query, you're asking Access to execute a batch of statements.  However Access will not execute batched statements.  You must execute them separately.

And when you execute them one at a time, you will discover another 2 problems:

OwnerPhone Int Null will not accept a text value such as '555-537-8765';  Make that a text instead of numeric type field.

The second insert statement does not include the INTO keyword.

I used this statement to create the table:

Create Table Pet_Owner (
OwnerID autoincrement Primary Key,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone VarChar(12) Null,
OwnerEmail VarChar(100) Not Null Unique
);
```

<p>(<code>OwnerPhone</code> was the critical change.  I changed the primary key assignment just to show you a different method for that.)</p>

<p>Then processed each insert statement separately by loading it into a variable, <code>strInsert</code>, and executing it like this:</p>

<pre class="lang-vb prettyprint-override"><code>CurrentDb.Execute strInsert, dbFailOnError
</code>```

That approach successfully added 4 rows to the Pet_Owner table.

ContentLicense: CC BY-SA 4.0

Body:
I just started a database course that is going over SQL using Access 2016.  I am getting a End of statement error and I am unsure how to fix it.

My table code is `

Create Table Pet_Owner (
OwnerID autoincrement Null,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone Int Null,
OwnerEmail VarChar(100) Not Null Unique,
Constraint Pet_Owner_PK Primary Key(OwnerID)
);

and the insert query I have so far that I am trying to add is

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com')
Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail) Values (
'Trent', 'Miles', 'Miles.Trent@somewhere.com') ;

When I use append, it is saying I am missing a semicolon at the end of the first set of values, but if i add that then it says i have characters at the end of my statement. If anyone can help me out or point me into the right direction to solve the error I would greatly appreciate it. Thank you

Body:
Your insert query includes 4 INSERT ... VALUES statements.  So when you attempt to run that query, you're asking Access to execute a batch of statements.  However Access will not execute batched statements.  You must execute them separately.

And when you execute them one at a time, you will discover another 2 problems:

OwnerPhone Int Null will not accept a text value such as '555-537-8765';  Make that a text instead of numeric type field.

The second insert statement does not include the INTO keyword.

I used this statement to create the table:

Create Table Pet_Owner (
OwnerID autoincrement Primary Key,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone VarChar(12) Null,
OwnerEmail VarChar(100) Not Null Unique
);

(OwnerPhone was the critical change.  I changed the primary key assignment just to show you a different method for that.)

Then processed each insert statement separately by loading it into a variable, strInsert, and executing it like this:

CurrentDb.Execute strInsert, dbFailOnError

That approach successfully added 4 rows to the Pet_Owner table.


问:
VB6 file append skipping lines
I have been coding VB6 since the TRex roamed the earth but suddenly some of our customers have started having problems with applications that have worked fine for decades.

The issues seems to be when a application repeatedly opens, appends and closes a file. I was never able to reproduce the error on any machine I had access to. I kind of guessed that this was the issue and changed the program to buffer the contents and write them all at once and the customers' problem seem to be resolved.

I have also, just recently, had a situation where lines were skipped and a line full of garbage characters was printed out. Like an old time C string buffer that had been allocated but never cleared.

The code is nothing special and standard VB6 file access code. My question is two parts.
1. Is this happening to anyone else?
2. If so, have you figured out the cause?

My guess at the cause is that the system is under some kind of resource strain and some deep level C code is misfiring.

Here is the code:

```<code>Dim nFileWrite As Integer
nFileWrite = FreeFile
Open fnAddBkSlash(sReadFilePath) & sWriteFileName For Append As #nFileWrite
Print #nFileWrite, sLineContents
Close nFileWrite
</code>```

答:
Is that snippet of code complete or have you left out the line to retrieve the next free file number?

```<code>Dim nFileWrite As Integer

nFileWrite = FreeFile 'retrieve free file number

Open fnAddBkSlash(sReadFilePath) & sWriteFileName For Append As #nFileWrite
Print #nFileWrite, sLineContents
Close nFileWrite
</code>```

Just wondering if the output is occasionally getting lost if you don't specifically retrieve a new file number before trying to write the line.

Title: VB6 file append skipping lines

Body:
I have been coding VB6 since the TRex roamed the earth but suddenly some of our customers have started having problems with applications that have worked fine for decades.

The issues seems to be when a application repeatedly opens, appends and closes a file. I was never able to reproduce the error on any machine I had access to. I kind of guessed that this was the issue and changed the program to buffer the contents and write them all at once and the customers' problem seem to be resolved.

I have also, just recently, had a situation where lines were skipped and a line full of garbage characters was printed out. Like an old time C string buffer that had been allocated but never cleared.

The code is nothing special and standard VB6 file access code. My question is two parts.
1. Is this happening to anyone else?
2. If so, have you figured out the cause?

My guess at the cause is that the system is under some kind of resource strain and some deep level C code is misfiring.

Here is the code:

Dim nFileWrite As Integer
nFileWrite = FreeFile
Open fnAddBkSlash(sReadFilePath) & sWriteFileName For Append As #nFileWrite
Print #nFileWrite, sLineContents
Close nFileWrite

Body:
Is that snippet of code complete or have you left out the line to retrieve the next free file number?

Dim nFileWrite As Integer

nFileWrite = FreeFile 'retrieve free file number

Open fnAddBkSlash(sReadFilePath) & sWriteFileName For Append As #nFileWrite
Print #nFileWrite, sLineContents
Close nFileWrite

Just wondering if the output is occasionally getting lost if you don't specifically retrieve a new file number before trying to write the line.


问:
Insert element into list at specific index
How do I insert an item into a list at a specific index? Without using:

```<code>index = 3
list = [:3] + [item] + [3:]
</code>```

Help!

答:
Use the list.insert function:

```<code>list.insert(index, element)
</code>```

Body:
How do I insert an item into a list at a specific index? Without using:

index = 3
list = [:3] + [item] + [3:]

Help!

Body:
Use the list.insert function:

list.insert(index, element)


问:
how to disable header media in wordpress?
I am facing header media issues. I don't want that header area on my top of the website. I tried CSS code

```<code>.home #wp-custom-header {
    display: none;"
}
</code>```

but it's not working. please check my site for more details hindizone.in

答:
It would be a better solution to change your theme template file so there is no such div container to be hidden. This can normally be found in header.php file of your theme. Delete the div with the class header-bottom.

Another way would be using CSS as you already tried. But you do not have an element with id wp-custom-header so this code is doing nothing. You can find out the right element to target with using the inspector of your browser.

I did this with your code and therefore found the classes you need to address in your css file.

Add following code to your custom css in the theme editor, or inside style.css of your theme:

```<code>#site-header.top-header .header-bottom {
    display: none !important;
}
</code>```

With the !important statement you make sure, that the display value is not being overwritten somewhere else in your stylesheet.

Body:
I am facing header media issues. I don't want that header area on my top of the website. I tried CSS code

.home #wp-custom-header {
    display: none;"
}

but it's not working. please check my site for more details hindizone.in

Body:
It would be a better solution to change your theme template file so there is no such div container to be hidden. This can normally be found in header.php file of your theme. Delete the div with the class header-bottom.

Another way would be using CSS as you already tried. But you do not have an element with id wp-custom-header so this code is doing nothing. You can find out the right element to target with using the inspector of your browser.

I did this with your code and therefore found the classes you need to address in your css file.

Add following code to your custom css in the theme editor, or inside style.css of your theme:

#site-header.top-header .header-bottom {
    display: none !important;
}

With the !important statement you make sure, that the display value is not being overwritten somewhere else in your stylesheet.


问:
.ajax load remote page content to javascript var
I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:

```<code><script>
$(document).ready(function(){
$("button").click(function(){
  $.ajax({url:"http://url:8888/data", success:function(result){
    $("div").html(result);
  }});
});});
</script>
</code>```

I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?

I am sure JQuery is working correctly.

答:
The answer would be to long to post here (really). But look those up:

Same Origin Policy

Padded JSON

If you have no control over the remote site, you have lost - you will not get any data from it by Ajax (which is actually a feature, not a limitation of the technology). One way of circumventing the protection would be to build a proxy that just mirrors the remote service you need to reach and makes it available in the same domain that your main HTML came from.

ContentLicense: CC BY-SA 3.0

Body:
I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:

I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?

I am sure JQuery is working correctly.


问:
List combination challenge in Python 3
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

```<code>['01101001', '01110110', '01100101', '01101011']
</code>```

I want to get the list combined with each value like below. (result list)

```<code>['00001111', '11110100', '10010110', '01011011']
</code>```

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

Title: List combination challenge in Python 3

Body:
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

['01101001', '01110110', '01100101', '01101011']

I want to get the list combined with each value like below. (result list)

['00001111', '11110100', '10010110', '01011011']

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

Body:
Simple Solution

lt = ['01101001', '01110110', '01100101', '01101011']

def list_combination(lt,new=[],num=""):
  for i in range(len(lt[0])):
    if len(num)==8:
      num = ""
    for j in lt:
      num += j[i]
    if len(num)==len(lt[0]):
      new.append(num)
  return new
print(list_combination(lt))
#['00001111', '11110100', '10010110', '01011011']


问:
Woocommerce related products section shows the same products
I would like to display the related products section on my product pages, but it shows the actual product in all columns.
Here is my code:

```<code><?php
    while ($loop->have_posts()): $loop->the_post();
        $featured_image = wp_get_attachment_image_src(get_post_thumbnail_id($product->get_id()), 'single-post-thumbnail'); ?>
        <div class="col-lg-3 related-tour">
            <article>
                <div class="featured-image" style="background-image: url(<?php echo (!empty($featured_image)) ? $featured_image[0] : '';?>);"></div>
                <div class="article-info">
                    <h2>
                        <a href="<?php echo $product->get_permalink();?>"><?php echo $product->get_name();?></a>
                    </h2>
                    <p class="category">
                        <span><?php pll_e( 'Categories:' ); ?></span>
                        <?php echo $product->get_categories(', ', ' ' . __(' ', '  ', $cat_count, 'woocommerce') . ' ', ' ');?>
                    </p>
                </div>
            </article>
        </div>
    <?php endwhile;?>
    <?php wp_reset_query();?>
</code>```

What should I change to fix this?

答:
DON'T use a custom function for showing a related product.

So function woocommerce_output_related_products show related product.

View inside this file /single-product/related.php. (https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/related.php)

You can change product arguments for the related products query which using woocommerce_output_related_products_args filter.

```<code>add_filter( 'woocommerce_output_related_products_args', 'my_woocommerce_output_related_products_args' );
function woocommerce_output_related_products_args( $args ) {
    $args['post__not_in'] = [ get_the_ID() ];

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

Body:
I would like to display the related products section on my product pages, but it shows the actual product in all columns.
Here is my code:

<?php
    while ($loop->have_posts()): $loop->the_post();
        $featured_image = wp_get_attachment_image_src(get_post_thumbnail_id($product->get_id()), 'single-post-thumbnail'); ?>

                <div class="featured-image" style="background-image: url(<?php echo (!empty($featured_image)) ? $featured_image[0] : '';?>);">

                        <a href="<?php echo $product->get_permalink();?>"><?php echo $product->get_name();?>

                        <?php pll_e( 'Categories:' ); ?>
                        <?php echo $product->get_categories(', ', ' ' . __(' ', '  ', $cat_count, 'woocommerce') . ' ', ' ');?>

    <?php endwhile;?>
    <?php wp_reset_query();?>

What should I change to fix this?

Body:
DON'T use a custom function for showing a related product.

So function woocommerce_output_related_products show related product.

View inside this file /single-product/related.php. (https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/related.php)

You can change product arguments for the related products query which using woocommerce_output_related_products_args filter.

add_filter( 'woocommerce_output_related_products_args', 'my_woocommerce_output_related_products_args' );
function woocommerce_output_related_products_args( $args ) {
    $args['post__not_in'] = [ get_the_ID() ];

    return $args;
}


问:
Date subtraction leading to "TypeError: cannot perform truediv with this index type datetimeindex"
I am trying to subtract a date from a date column and calculating difference in terms of months:

```<code>pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])/np.timedelta64(1,'M')
</code>```

But I get

```<code>> TypeError: cannot perform __truediv__ with this index type datetimeindex
</code>```

How could I correct my code in order to find the difference in months?

答:
Here is a short workaround using UNIX timestamps.

```<code>import pandas as pd
import numpy as np
x = (pd.Timestamp('2020-01-20'))
y = pd.to_datetime('2019-01-20')
print(f"Approximately {int((x.value - y.value)/2592000/ (10 ** 9))} months have passed.")
</code>```

Note: I changed the second date since you are taking it from the df and we don't know what the df value is.
Output

Body:
I am trying to subtract a date from a date column and calculating difference in terms of months:

pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])/np.timedelta64(1,'M')

But I get

> TypeError: cannot perform __truediv__ with this index type datetimeindex

How could I correct my code in order to find the difference in months?

Body:
Here is a short workaround using UNIX timestamps.

import pandas as pd
import numpy as np
x = (pd.Timestamp('2020-01-20'))
y = pd.to_datetime('2019-01-20')
print(f"Approximately {int((x.value - y.value)/2592000/ (10 ** 9))} months have passed.")

Note: I changed the second date since you are taking it from the df and we don't know what the df value is.
Output


问:
Discrepancy between Kepler GL coordinates and Google Maps
I'm trying to create a map layer with a point in https://kepler.gl/demo, but I'm facing that the coordinates that I'm using are rendering differently in Google Maps and in Kepler GL.

This is the geojson that I am loading in kepler gl:

{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [42.2812989, -8.7366615]
    },
    "properties": {
      "name": "foo"
    }
  }

This puts a point in the middle of the sea...but if I put those coordinates in Google Maps the point is in Galicia (Spain), which is the 'real' location.

Maybe there is something that I'm not taking in count?

答: You need to switch the coordinates. First the longitude and then the latitude. Then you will see your point in its real location.</p>


答:
You can use the insert method:

```<code>lst = ['a','b','c']
lst.insert(2,'d')
print(lst)
</code>```

Output:

```<code>['a','b','d','c']
</code>```

Title: Insert element into list at specific index

Body:
You can use the insert method:

lst = ['a','b','c']
lst.insert(2,'d')
print(lst)

Output:

['a','b','d','c']


问:
How do you create an fmt file using the bcp command and only selecting a subset of columns from the target table?
I am creating .fmt files with the bcp command using the template below:

```<code>bcp schema.dbo.table format nul -S servername\sqlserver-engine -f filename.fmt -c -T
</code>```

This command creates a tab separated file with all the columns from the target table along with appropriate data type/length specifications.

However, in my use case, only a subset of columns will have data, so in order to complete the bulk insert a manual process is needed to eliminate the columns that will be null and renumber the items left on the .fmt file.  Is there a way to create the .fmt file with a subset of columns (only what is needed) in order to eliminate this manual process?

答:
three options:

create the format file yourself, programmatically. Do not use BCP with "format" option. Write a query against information_schema for the table you want. Put that query into a built bcp command and execute the command on the os. fyi,  just need a single space between each "column" of format file. dont need to have it look exactly like what the BCP "format" command gives you.

create a view on top of your table to be exported. eliminate unwanted columns there. bcp out that view.

leave all as is for your export and just ignore the columns you dont like on the way into your destination. Cant set destination to "0" in the format file and it will be ignored.

Body:
I am creating .fmt files with the bcp command using the template below:

bcp schema.dbo.table format nul -S servername\sqlserver-engine -f filename.fmt -c -T

This command creates a tab separated file with all the columns from the target table along with appropriate data type/length specifications.

However, in my use case, only a subset of columns will have data, so in order to complete the bulk insert a manual process is needed to eliminate the columns that will be null and renumber the items left on the .fmt file.  Is there a way to create the .fmt file with a subset of columns (only what is needed) in order to eliminate this manual process?


问:
Rectangular Prism Collision
I want to make a game where the character is a rectangular prism that can be rotated, and the rest of the map are axis-aligned rectangular prisms.  Everything other than the character will be static, so I was wondering what would be the best algorithm for finding if the character is colliding with any parts in the map.  Any tutorials/code/advice would be much appreciated :)

Also, the character will only be rotated on the Y axis, if that helps.

答:
I believe one way to test for this is to check the 16 cases of line intersections:

http://www.math.niu.edu/~rusin/known-math/95/line_segs

If you want to optimize you could also check if the rectangles have no chance of overlapping, i.e. if all corners are to the right/left/above/below of the other rectangle.

Edit:

Se comment below.

Title: Rectangular Prism Collision


答:
I think you are missing a pair of parentheses:</p>

```<code>(pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])) / pd.to_timedelta(`1min')

^                                                       ^
this                                             and this
</code>```

Title: Date subtraction leading to "TypeError: cannot perform truediv with this index type datetimeindex"

Body:
I think you are missing a pair of parentheses:

(pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])) / pd.to_timedelta(`1min')

^                                                       ^
this                                             and this


问:
Header html errors
I have been creating the menu for the main page of my website. First I made it in a drawing I wanted to pass it to html with figma it did not go well.

Now I want to create it pure code. But it doesn't turn out the way I want either.
link:
https://codepen.io/R3DW0LF/pen/ExVqYbo?

```<code>        <div class="page-header">
            <div class="page-content-wrap">
                <div class="page-header-content">
                    <div class="dyna_logo img kfuwufhd">
                        <span>Dynamo</span>
                    </div>
                    <div class="search__box">
                        <div class="srch_inpt" style="display: block;">
                            <input class="search_input efh473e" type="text" placeholder="Search">
                        </div>
                    </div>
                    <div class="inpts-tpbar">
                        <div class="tpbar login-top jfhejdyd" style="display: inline-flex;">
                            <div class="control-input login">
                                <a href="/signin">Hello</a>
                            </div>
                            <div class="control-input register">
                                <a href="/singup">Hello 2</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>`
</code>```

I want something like this:
Design of what i want

答:
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #edeef0;
    font-family: system, BlinkMacSystemFont, Roboto, Open Sans, Helvetica Neue, "Noto Sans Armenian", "Noto Sans Bengali", "Noto Sans Cherokee", "Noto Sans Devanagari", "Noto Sans Ethiopic", "Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Kannada", "Noto Sans Khmer", "Noto Sans Lao", "Noto Sans Osmanya", "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Thai", sans-serif;
}

.page-header {
    position: absolute;
    height: 54px;
    width: 100%;
}

.page-header-content {
    background: #4A76A8;
    width: 100%;
    display: inline-flex;
    padding: 10px;
}

.page-header-content .dyna_logo {
    /* position: absolute; */
    margin-left: 10%;
  margin-top:5px;
    font-style: normal;
    font-weight: bold;
    font-size: 20px;
    line-height: 23px;
    /* identical to box height */
    color: #FFFFFF;
}

.search__box {
    margin-left: 10px;
    margin-top:5px;
}

.search__box .search_input {
    border: 0;
    width: 275px;
    line-height: 16px;
    transition: background-color 0.05s, color 0.05s;
    background: #224B7A url('/images/head_loupe.svg') no-repeat;
    background-position-x: left;
    background-position-y: 8px;
    background-position: left 8px;
    padding-left: 18px;
    border-radius: 14px;
}

.search__box .efh473e {
    box-sizing: border-box;
    height: 28px;
    line-height: 16px;
    color: #ddd;
    padding: 6px 6px 6px 19px;
    height: 28px;
    border: none;
    border-left: 8px solid transparent;
}

.search__box .efh473e:focus {
    outline: none;
    background-color: #fff;
    color: #000;
}

.tpbar .control-input {
    padding:5px;
}

.login-top .control-input > a {
  color:black;
  align-self: center !important;
  text-decoration:none;
}

.linkButton{
  margin-top:3px;
  margin-left:15px;
  border-color:#f0f0f0;
  border-style:solid;
  height:16px;
  width:100px;
  background-color:#f0f0f0;
  color:black;
  text-align:center;
  align-self: center;
}

/* Responsive style */

@media screen and (max-width: 920px) {
    .inpts-tpbar {
        display: none;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="app">
  <div class="page-header">
    <div class="page-content-wrap">
      <div class="page-header-content">
        <div class="dyna_logo img kfuwufhd">
          <span>Dynamo</span>
        </div>
        <div class="search__box">
          <div class="srch_inpt" style="display: block;">
            <input class="search_input efh473e" type="text" placeholder="Search">
          </div>
        </div>
        <div class="inpts-tpbar">
          <div class="tpbar login-top jfhejdyd" style="display: inline-flex;">
            <div class="control-input linkButton">
              Sign in
            </div>
            <div class="control-input linkButton">
              Sign Up
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section></code>```

Title: Header html errors

Body:
I have been creating the menu for the main page of my website. First I made it in a drawing I wanted to pass it to html with figma it did not go well.

Now I want to create it pure code. But it doesn't turn out the way I want either.
link:
https://codepen.io/R3DW0LF/pen/ExVqYbo?

                        Dynamo

                            <input class="search_input efh473e" type="text" placeholder="Search">

                                Hello

                                Hello 2

`

I want something like this:
Design of what i want

Body:
* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #edeef0;
    font-family: system, BlinkMacSystemFont, Roboto, Open Sans, Helvetica Neue, "Noto Sans Armenian", "Noto Sans Bengali", "Noto Sans Cherokee", "Noto Sans Devanagari", "Noto Sans Ethiopic", "Noto Sans Georgian", "Noto Sans Hebrew", "Noto Sans Kannada", "Noto Sans Khmer", "Noto Sans Lao", "Noto Sans Osmanya", "Noto Sans Tamil", "Noto Sans Telugu", "Noto Sans Thai", sans-serif;
}

.page-header {
    position: absolute;
    height: 54px;
    width: 100%;
}

.page-header-content {
    background: #4A76A8;
    width: 100%;
    display: inline-flex;
    padding: 10px;
}

.page-header-content .dyna_logo {
    /* position: absolute; */
    margin-left: 10%;
  margin-top:5px;
    font-style: normal;
    font-weight: bold;
    font-size: 20px;
    line-height: 23px;
    /* identical to box height */
    color: #FFFFFF;
}

.search__box {
    margin-left: 10px;
    margin-top:5px;
}

.search__box .search_input {
    border: 0;
    width: 275px;
    line-height: 16px;
    transition: background-color 0.05s, color 0.05s;
    background: #224B7A url('/images/head_loupe.svg') no-repeat;
    background-position-x: left;
    background-position-y: 8px;
    background-position: left 8px;
    padding-left: 18px;
    border-radius: 14px;
}

.search__box .efh473e {
    box-sizing: border-box;
    height: 28px;
    line-height: 16px;
    color: #ddd;
    padding: 6px 6px 6px 19px;
    height: 28px;
    border: none;
    border-left: 8px solid transparent;
}

.search__box .efh473e:focus {
    outline: none;
    background-color: #fff;
    color: #000;
}

.tpbar .control-input {
    padding:5px;
}

.login-top .control-input > a {
  color:black;
  align-self: center !important;
  text-decoration:none;
}

.linkButton{
  margin-top:3px;
  margin-left:15px;
  border-color:#f0f0f0;
  border-style:solid;
  height:16px;
  width:100px;
  background-color:#f0f0f0;
  color:black;
  text-align:center;
  align-self: center;
}

/* Responsive style */

@media screen and (max-width: 920px) {
    .inpts-tpbar {
        display: none;
    }
}

<section class="app">
  <div class="page-header">
    <div class="page-content-wrap">
      <div class="page-header-content">
        <div class="dyna_logo img kfuwufhd">
          <span>Dynamo</span>
        </div>
        <div class="search__box">
          <div class="srch_inpt" style="display: block;">
            <input class="search_input efh473e" type="text" placeholder="Search">
          </div>
        </div>
        <div class="inpts-tpbar">
          <div class="tpbar login-top jfhejdyd" style="display: inline-flex;">
            <div class="control-input linkButton">
              <a href="/signin">Sign in</a>
            </div>
            <div class="control-input linkButton">
              <a href="/singup">Sign Up</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


问:
What to do If I can't assign Future functions to onPressed in flutter?
I have a proplem in assigning a sign in future method to onpressed :The argument type 'Future' can't be assigned to the parameter type 'void Function()'.</p>

答:
you have to assign it like this:

```<code>onpressed: () => FunctionName()
</code>```

Because the handler expects a function with no return. So we just call your function inside an anonymous void function.

Body:
you have to assign it like this:

onpressed: () => FunctionName()

Because the handler expects a function with no return. So we just call your function inside an anonymous void function.


问:
Could not load file or assembly 'Microsoft.Web.Infrastructure,
I tried to upload my web site to a server. It was working fine with my local host, so I uploaded everything in my localhost wwwroot folder to the server and changed the connection string.

But there is this error:

```<code>Exception information:
    Exception type: InvalidOperationException
    Exception message: The pre-application start initialization method Start on type RouteDebug.PreApplicationStart threw an exception with the following error message: Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
   at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods)
   at System.Web.Compilation.BuildManager.CallPreStartInitMethods()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)

Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
   at RouteDebug.PreApplicationStart.Start()
</code>```

The project was nopcommerce.

What should be done to resolve this error?

答: So, here's what worked for me using VS2019.  I was getting this error trying to update Nuget packages on one project while the Microsoft.Web.Infrastructure was in a different project in the same solution.  I had to delete the Microsoft.Web.Infrastructure.1.0.0.0 folder from my project's Packages folder.  Reinstalled it via nuget and then everything started working again.  Crazy stuff.</p>

Body:
I tried to upload my web site to a server. It was working fine with my local host, so I uploaded everything in my localhost wwwroot folder to the server and changed the connection string.

But there is this error:

Exception information:
    Exception type: InvalidOperationException
    Exception message: The pre-application start initialization method Start on type RouteDebug.PreApplicationStart threw an exception with the following error message: Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..
   at System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods)
   at System.Web.Compilation.BuildManager.CallPreStartInitMethods()
   at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)

Could not load file or assembly 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
   at RouteDebug.PreApplicationStart.Start()

The project was nopcommerce.

What should be done to resolve this error?


问:
Parse email content from quoted reply
I'm trying to figure out how to parse out the text of an email from any quoted reply text that it might include.  I've noticed that usually email clients will put an "On such and such date so and so wrote" or prefix the lines with an angle bracket.  Unfortunately, not everyone does this.  Does anyone have any idea on how to programmatically detect reply text?  I am using C# to write this parser.</p>

答: If you control the original message (e.g. notifications from a web application), you can put a distinct, identifiable header in place, and use that as the delimiter for the original post.</p>

OwnerDisplayName: VanOrman

ContentLicense: CC BY-SA 2.5

Title: Parse email content from quoted reply

LastEditorDisplayName: VanOrman


问:
How to add REST API to console app written in .NET Framework 4.8 using .NET generic host?
I've written a small Windows service that hosts a number of IHostedService based classes using the .NET generic host. I'd like to add the ability to talk to the service through a REST API, and thought the .NET generic host setup should let me do that fairly easily: just add Microsoft.AspNetCore, Microsoft.AspNetCore.Hosting and start with adding a .ConfigureWebHost to the IHostBuilder. But it seems like the combination of .NET Framework and .NET generic host prohibits that from working.... The program.cs looks roughly like:

```<code>using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Myservice
{
  class Program
  {
    static async Task Main(string[] args)
    {
      IHostBuilder builder = Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(...)
        .ConfigureAppConfiguration(...)
        // ConfigureWebHost can't be found by the compiler
        // Neither can .ConfigureWebHostDefaults
        .ConfigureWebHost(...)
        .ConfigureLogging(...)
        .ConfigureServices(...);

      if (CommandLine.RunAsService)
      {
        builder.UseWindowsService();
      }

      await builder.Build().RunAsync();
    }
  }
}
</code>```

I've seen some hints that the particular project type matters. I started out with a standard .NET Framework Console App - so project file looking something like:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
...
</code>```

but have also tried with a project built from the ASP.NET Core Web Application template using .NET Framework. (.NET Framework is a requirement to make use of particular assemblies the service needs.) That looked something like:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net48</TargetFramework>
  </PropertyGroup>
  ...
</code>```

It seems like this ought to work somehow, but I can't find the right combination....

答: Under the hood, it looks like the .NET Generic Host was brought to .NET Framework, but that the portion of it which held the web host was in AspNetCore, specifically in version 3, and that has yet to be supported in .NET Framework. So although it'd be nice if this worked, it likely isn't going to until .NET 5.</p>

Body:
I've written a small Windows service that hosts a number of IHostedService based classes using the .NET generic host. I'd like to add the ability to talk to the service through a REST API, and thought the .NET generic host setup should let me do that fairly easily: just add Microsoft.AspNetCore, Microsoft.AspNetCore.Hosting and start with adding a .ConfigureWebHost to the IHostBuilder. But it seems like the combination of .NET Framework and .NET generic host prohibits that from working.... The program.cs looks roughly like:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Myservice
{
  class Program
  {
    static async Task Main(string[] args)
    {
      IHostBuilder builder = Host.CreateDefaultBuilder(args)
        .ConfigureHostConfiguration(...)
        .ConfigureAppConfiguration(...)
        // ConfigureWebHost can't be found by the compiler
        // Neither can .ConfigureWebHostDefaults
        .ConfigureWebHost(...)
        .ConfigureLogging(...)
        .ConfigureServices(...);

      if (CommandLine.RunAsService)
      {
        builder.UseWindowsService();
      }

      await builder.Build().RunAsync();
    }
  }
}

I've seen some hints that the particular project type matters. I started out with a standard .NET Framework Console App - so project file looking something like:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
...

but have also tried with a project built from the ASP.NET Core Web Application template using .NET Framework. (.NET Framework is a requirement to make use of particular assemblies the service needs.) That looked something like:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net48</TargetFramework>
  </PropertyGroup>
  ...

It seems like this ought to work somehow, but I can't find the right combination....


问:
Correlation Coefficient over Correlation Determination in linear regression
i am new to machine learning and i am using housing price dataset from kaggle.com to solve regression problem. i want to know the difference between Correlation Coefficient and Correlation Determination and why people use one over the other. for instance, i can see the relation between YearBuild and SalePrice like this

now, what is the use of Coefficient Determination, why is it used

if R= Coeffiecient Corellation
  then Coefficient Determination = R x R

is the percentage view of the Corellation Coeffiecient?

is it the relation of an individual feature with the rest of the feature?

答: The coefficient R squared tells you how much of the variance the regression model explains. If it is equal to 0.01 for example, it means that you have explained one percent of the variance. This is useful to know for obvious reasons. Unlike the correlation coefficient, R squared is always positive so just tells you that there is (or is not) a linear relationship, but not what its form is.


问:
Spring Retry in non-spring apps?
I was wondering if Spring Retry framework can be used in a regular Java application?
I'd like to use the retry framework in a legacy non-Spring application.

Can this be done? I've seen most of the articles online talking about using it in a Spring/Spring Boot application.

If it can be, are there any examples of using it?

Thanks..

答: I found my answer at https://github.com/spring-projects/spring-retry and I made a small example project which shows you can use it outside of Spring based applications.</p>

Title: Spring Retry in non-spring apps?


问:
How do I take the content of the Ace code editor with a laravel form
as the question says, I want to submit the code from the editor,but I don't know how can I do this using a laravel form. I found that I can use editor.getValue() here but don't know how to use it with laravel. I have the following code

```<code>
<style type="text/css" media="screen">
    #editor {
        position: absolute;
        top: 150px;
        right: 150px;
        bottom: 150px;
        left: 150px;
    }
    .ace_editor {
        border: 1px solid lightgray;
        margin: auto;
        height: 65%;
        width: 55%;
    }
    .scrollmargin {
        height: 80px;
        text-align: center;
    }
</style>

{!! Form::open(['action' => 'ProblemsController@store']) !!}
  <div id="editor">
    //Your code goes here
  </div>
  {{Form::submit('Submit')}}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.3.3/ace.js" type="text/javascript" charset="utf-8"></script>
  <script>
      var editor = ace.edit("editor");
      editor.setTheme("ace/theme/chrome");
      editor.session.setMode("ace/mode/c_cpp");
  </script>
{!! Form::close() !!}

</code>```

答:
You can use the change session event to update a hidden textarea field with contents of the Ace editor (untested code following):

JavaScript:

```<code>const $formElement = $('.js-ace-code');

editor.getSession().on('change', function () {
    $formElement.val(editor.getSession().getValue());
});
</code>```

Add a additional textarea to your desired form in which the Ace editor resides:

```<code><form>
    <textarea name="code" class="js-ace-code" style="display: none;"></textarea>
</form>
</code>```

There's apparently also a method where you can add a button with a trigger to update the code via an AJAX request.

Body:
as the question says, I want to submit the code from the editor,but I don't know how can I do this using a laravel form. I found that I can use editor.getValue() here but don't know how to use it with laravel. I have the following code

{!! Form::open(['action' => 'ProblemsController@store']) !!}

    //Your code goes here

  {{Form::submit('Submit')}}

{!! Form::close() !!}

Body:
You can use the change session event to update a hidden textarea field with contents of the Ace editor (untested code following):

JavaScript:

const $formElement = $('.js-ace-code');

editor.getSession().on('change', function () {
    $formElement.val(editor.getSession().getValue());
});

Add a additional textarea to your desired form in which the Ace editor resides:

<form>
    <textarea name="code" class="js-ace-code" style="display: none;"></textarea>
</form>

There's apparently also a method where you can add a button with a trigger to update the code via an AJAX request.


问:
List of Bluetooth devices on iPhone
I'm develop iphone app, what need connect to bluetooth device and handle disconnection of device.

I'm tryied to use ExternalAccessory framework, but it don't show any device (in settings I have paired A2DP device), on apple site I see " Specifically, you must include the UISupportedExternalAccessoryProtocols key to declare the specific hardware protocols your application supports.", I think problem in this, but I don't know what is protocol strings for A2DP example.

Few questions:

have any idea how make what I want via other tech (GameKit or Bonjour example);

somebody maybe know standart protocol strings for A2DP like devices.

Thanks.

答: Unless you have signed up for Apple's "Made for iPod" program you will have no access to bluetooth, beyond the API's offered by the GameKit framework, which can only communicate with other iOS devices, running your software,</p>

Title: List of Bluetooth devices on iPhone


问:
Python: Which method to use for file operations?
I am interested in performing file operations, such as move/copy/delete, on my Linux system. I understand that one way to achieve this is using os.system() combined with a bash command (mv, cp, rm). I also have discovered other modules that seem to be dedicated to such operations, namely the shutil module. I am having trouble deciding between these options. I am only interested in performance and reliability; I am not interested in compatibility (with other systems).

What are the use cases of each option? Advantages/Disadvantages?

Are there any other options that you would recommend?

答:
I would suggest using the modules as they are typically faster. shutil is the main python module that I've come across but if you do need to directly access the terminal/command line, try using subprocess.popen or os.popen as they return useful information.

Also, there are many disadvantages to os.system() which can be found here.
Including the fact that you cannot handle errors, as  Maurice Meyer said.


问:
Problem with filling 5th column in GridLayout
When I add the 5th column, the button with the number 5 half crawls out of the screen. When I add value to the buttons: android:layout_columnWeight="1", then the button with number 1 is stretched out of the screen.

How can I fit all 5 columns on the screen?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="0"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="3"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="4"/>
    </GridLayout>
</RelativeLayout>
</code>```

答:
Try this code :</p>

```<code> <LinearLayout
    android:id="@+id/footer"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal"
    android:visibility="gone">

    <LinearLayout
        android:id="@+id/lay1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/lay4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

</LinearLayout>
</code>```

Body:
When I add the 5th column, the button with the number 5 half crawls out of the screen. When I add value to the buttons: android:layout_columnWeight="1", then the button with number 1 is stretched out of the screen.

How can I fit all 5 columns on the screen?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rowCount="5"
        android:columnCount="5">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="0"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="1"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="2"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="3"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/white"
            android:background="@color/black"
            android:layout_row="0"
            android:layout_column="4"/>
    </GridLayout>
</RelativeLayout>

Body:
Try this code :

 <LinearLayout
    android:id="@+id/footer"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal"
    android:visibility="gone">

    <LinearLayout
        android:id="@+id/lay1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="1"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="2"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="3"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/lay4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="4"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/lay5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:text="5"
            android:textSize="25dp"
            android:textColor="@color/colorAccent"
            android:background="@color/cardview_shadow_start_color"

            android:layout_row="0"
            android:layout_column="0"/>
    </LinearLayout>

</LinearLayout>


问:
Where mongoose execute the queries?
I want to understand better how mongoose work.

I have nodejs in serverA and mongodb in serverB.

When I run .find(..) or any others mongoose function, Did they run on serverB and return the result using tcp to my nodejs application? or ask for serverB to get all the rows and then in serverA is run the functions?

答: Mongoose only transforms your object oriented code into various MongoDB queries. The queries are always run on the server - the database engine will do the computations and the Node.js client will receive the ready made results. Mongoose (serverA) tries to optimise most of the queries (like classic relational database ORMs) and offload CPU expensive tasks to MongoDB (server B) - sorting, filtering, aggregations etc. As long as you specify the logic you want to execute in your queries and do not run client-side filtering/sorting, you shouldn't be worried that your Node.js main thread will get blocked by CPU intensive tasks.</p>

Title: Where mongoose execute the queries?


问:
Markers which are meant to move on google map creates two pairs. One that moves and one that is stuck on initial position
I've been trying to implement a web-application in React that shows all airbourne aircrafts on a map.
For this I've used React-Google-Maps together with the Opensky Network API.

My problem is very weird. When the application first loads and all markers are positioned, it looks fine. But when the markers start moving, the initial marker (the marker that is supposed to move) is still there while a new copy of the marker is moving from the initial position instead. Hence (after the movements of the markers) I have 2 sets of markers for every airplane on my map. One for the initial load (that is not moving), and one live that is moving.

I've coded my Map-component to fetch the data from the API every second and update the state after the fetch is done.

Any idea of why the first-loaded marker does not get removed when the state get's updated?

```<code>import React, { useState, useEffect } from 'react';
import { GoogleMap, withScriptjs, withGoogleMap, Marker, InfoWindow } from 'react-google-maps';
//import * as aircrafts from '../../data/aircrafts.json';

function Map() {
  const [selectedAirplane, setSelectedAirplane] = useState(null);
  // Set state (locations of airplanes) to initial request as markers
  const [airplanes, setAirplanes] = useState([]);

  useEffect(() => {
    const interval = setInterval(() => {
      // Update state (markers) every second
      fetch('https://opensky-network.org/api/states/all', { method: "GET" })
      .then(res => res.json())
      .then(response => {
        setAirplanes(response["states"]);
        //console.log(response["states"])
      });

    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (
    <div>
    <GoogleMap
        defaultZoom={10}
        defaultCenter={{ lat:  57.041401, lng: 12.401050 }}
    >
    { airplanes.map((airplane) => (
       <Marker
          key={airplane[0]}
          position={{
            lat: airplane[6],
            lng: airplane[5]
          }}
          onClick={() => {
            setSelectedAirplane(airplane);
          }}
       />
    ))}

    {selectedAirplane && (
      <InfoWindow
        position={{
          lat: selectedAirplane[6],
          lng: selectedAirplane[5]
         }}
         onCloseClick={() => {
          setSelectedAirplane(null);
         }}
      >
        <div>Airplane Details</div>
      </InfoWindow>
    )}
    </GoogleMap>
    </div>
  );
}

const WrappedMap = withScriptjs(withGoogleMap(Map));

export default WrappedMap;
</code>```

Edit:
This is what it looks like on initial load:
Initial load

And this is what it looks like when the API has started to fetch data:
Some seconds after initial load

And this is what it looks like when some minutes have passed:
Minute or two after initial load

As you see, the initial marker that first loads is not disappearing. I don't really understand why. I have looked for resources to remove this but can't find any :/

The second marker is moving just fine as I want it to.

Any tip here is greatly appreciated, since I'm getting nowhere :(
I've uploaded my project to Github and it's located here: https://github.com/emilwallgren/Flight-Tracker

答:
Solved it:
Had to remove React.StrictMode that surrounds App from index.js.

Now it works :)

Body:
I've been trying to implement a web-application in React that shows all airbourne aircrafts on a map.
For this I've used React-Google-Maps together with the Opensky Network API.

My problem is very weird. When the application first loads and all markers are positioned, it looks fine. But when the markers start moving, the initial marker (the marker that is supposed to move) is still there while a new copy of the marker is moving from the initial position instead. Hence (after the movements of the markers) I have 2 sets of markers for every airplane on my map. One for the initial load (that is not moving), and one live that is moving.

I've coded my Map-component to fetch the data from the API every second and update the state after the fetch is done.

Any idea of why the first-loaded marker does not get removed when the state get's updated?

import React, { useState, useEffect } from 'react';
import { GoogleMap, withScriptjs, withGoogleMap, Marker, InfoWindow } from 'react-google-maps';
//import * as aircrafts from '../../data/aircrafts.json';

function Map() {
  const [selectedAirplane, setSelectedAirplane] = useState(null);
  // Set state (locations of airplanes) to initial request as markers
  const [airplanes, setAirplanes] = useState([]);

  useEffect(() => {
    const interval = setInterval(() => {
      // Update state (markers) every second
      fetch('https://opensky-network.org/api/states/all', { method: "GET" })
      .then(res => res.json())
      .then(response => {
        setAirplanes(response["states"]);
        //console.log(response["states"])
      });

    }, 1000);
    return () => clearInterval(interval);
  }, []);

  return (

    <GoogleMap
        defaultZoom={10}
        defaultCenter={{ lat:  57.041401, lng: 12.401050 }}
    >
    { airplanes.map((airplane) => (
       <Marker
          key={airplane[0]}
          position={{
            lat: airplane[6],
            lng: airplane[5]
          }}
          onClick={() => {
            setSelectedAirplane(airplane);
          }}
       />
    ))}

    {selectedAirplane && (
      <InfoWindow
        position={{
          lat: selectedAirplane[6],
          lng: selectedAirplane[5]
         }}
         onCloseClick={() => {
          setSelectedAirplane(null);
         }}
      >

Airplane Details

      </InfoWindow>
    )}
    </GoogleMap>

  );
}

const WrappedMap = withScriptjs(withGoogleMap(Map));

export default WrappedMap;

Edit:
This is what it looks like on initial load:
Initial load

And this is what it looks like when the API has started to fetch data:
Some seconds after initial load

And this is what it looks like when some minutes have passed:
Minute or two after initial load

As you see, the initial marker that first loads is not disappearing. I don't really understand why. I have looked for resources to remove this but can't find any :/

The second marker is moving just fine as I want it to.

Any tip here is greatly appreciated, since I'm getting nowhere :(
I've uploaded my project to Github and it's located here: https://github.com/emilwallgren/Flight-Tracker


问:
Priority Queue in Parallel Jobs task
I tried the question PS mentioned here.

Task.

You have a program which is parallelized and uses n independent threads to process the given list of m
jobs. Threads take jobs in the order they are given in the input. If there is a free thread, it immediately
takes the next job from the list.

If a thread has started processing a job, it doesn’t interrupt or stop
until it finishes processing the job.

If several threads try to take jobs from the list simultaneously, the
thread with smaller index takes the job. For each job you know exactly how long will it take any thread
to process this job, and this time is the same for all the threads.

You need to determine for each job
which thread will process it and when will it start processing.

Input Format.

The first line of the input contains integers n and m.
The second line contains m integers t_i — the times in seconds it takes any thread to process i-th job.
The times are given in the same order as they are in the list from which threads take jobs.
Threads are indexed starting from 0.

Constraints.

1 ≤ n ≤ 10^5 ; 1 ≤ m ≤ 10^5 ; 0 ≤ t i ≤ 10^9 .

Output Format.

Output exactly m lines. i-th line (0-based index is used) should contain two space-
separated integers — the 0-based index of the thread which will process the i-th job and the time
in seconds when it will start processing that job.

My implementation works fine for basic test cases.
However, this is going to fail in some test. What is the mistake that I didn't see here.

Sample Input

2 5

1 2 3 4 5

Output

0 0

1 0

0 1

1 2

0 4

Here's my code.

#include <iostream>
#include <queue>

using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
using std::pair;
using std::priority_queue;
using std::queue;
using std::vector;

#define For(i,a,n) for (int i = a; i < n; i++)
typedef pair<int,int> PII;

int main() {

    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    int n,m,t,val;
    PII p;
    priority_queue<PII> pq;
    queue<int> q;

    // inputs >> number of treads, jobs
    cin >> n >> m;
    // time to process each job
    For(i,0,m){
        cin >> t;
        q.push(t);
    }
    // priority_queue
    // contains pair {-time, -tread}
    For(i,0,n) pq.push({0, -i});

    // untill finish all jobs
    while(!q.empty()){
        // get the smallest time tread
        p = pq.top();
        pq.pop();
        // print the output << tread no , start time
        cout << -p.second << " " << -p.first << endl;
        // get the next value in the queue
        val = q.front();
        q.pop();
        // push the given tread with new end time
        pq.push({ -val + p.first, p.second });

    }

    return 0;
}
```
<p>The following python3 code works fine for the problem. However, I cannot find any functionality difference in both of these. What is the problem with the c++ implementation.</p>
<pre class="lang-py prettyprint-override"><code>import sys
import heapq

def read():
    return [int(i) for i in sys.stdin.readline().strip().split()]

n, m = read()
arr = read()

q = []

for i in range(n):
    heapq.heappush(q, (0, i))

for i in range(m):
    x, y = heapq.heappop(q)
    print(y, x)
    heapq.heappush(q, (x+arr[i], y))

</code>```

Thank you for every answer.

答:
If several threads try to take jobs from the list simultaneously, the thread with smaller index takes the job.

If two (or more) threads finish their jobs at the same time, you are not guaranteed that the thread you pop first has the minimal index among them. Fix is simple: pop all the threads, which terminate at that time, and sort them by index.

Title: Priority Queue in Parallel Jobs task

Body:
I tried the question PS mentioned here.

Task.

You have a program which is parallelized and uses n independent threads to process the given list of m
jobs. Threads take jobs in the order they are given in the input. If there is a free thread, it immediately
takes the next job from the list.

If a thread has started processing a job, it doesn’t interrupt or stop
until it finishes processing the job.

If several threads try to take jobs from the list simultaneously, the
thread with smaller index takes the job. For each job you know exactly how long will it take any thread
to process this job, and this time is the same for all the threads.

You need to determine for each job
which thread will process it and when will it start processing.

Input Format.

The first line of the input contains integers n and m.
The second line contains m integers t_i — the times in seconds it takes any thread to process i-th job.
The times are given in the same order as they are in the list from which threads take jobs.
Threads are indexed starting from 0.

Constraints.

1 ≤ n ≤ 10^5 ; 1 ≤ m ≤ 10^5 ; 0 ≤ t i ≤ 10^9 .

Output Format.

Output exactly m lines. i-th line (0-based index is used) should contain two space-
separated integers — the 0-based index of the thread which will process the i-th job and the time
in seconds when it will start processing that job.

My implementation works fine for basic test cases.
However, this is going to fail in some test. What is the mistake that I didn't see here.

Sample Input

2 5

1 2 3 4 5

Output

0 0

1 0

0 1

1 2

0 4

Here's my code.

#include <iostream>
#include <queue>

using std::cin;
using std::cout;
using std::endl;
using std::ios_base;
using std::pair;
using std::priority_queue;
using std::queue;
using std::vector;

#define For(i,a,n) for (int i = a; i < n; i++)
typedef pair<int,int> PII;

int main() {

    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    int n,m,t,val;
    PII p;
    priority_queue<PII> pq;
    queue<int> q;

    // inputs >> number of treads, jobs
    cin >> n >> m;
    // time to process each job
    For(i,0,m){
        cin >> t;
        q.push(t);
    }
    // priority_queue
    // contains pair {-time, -tread}
    For(i,0,n) pq.push({0, -i});

    // untill finish all jobs
    while(!q.empty()){
        // get the smallest time tread
        p = pq.top();
        pq.pop();
        // print the output << tread no , start time
        cout << -p.second << " " << -p.first << endl;
        // get the next value in the queue
        val = q.front();
        q.pop();
        // push the given tread with new end time
        pq.push({ -val + p.first, p.second });

    }

    return 0;
}

The following python3 code works fine for the problem. However, I cannot find any functionality difference in both of these. What is the problem with the c++ implementation.

import sys
import heapq

def read():
    return [int(i) for i in sys.stdin.readline().strip().split()]

n, m = read()
arr = read()

q = []

for i in range(n):
    heapq.heappush(q, (0, i))

for i in range(m):
    x, y = heapq.heappop(q)
    print(y, x)
    heapq.heappush(q, (x+arr[i], y))

Thank you for every answer.


答:
You are trying to iterate through the dictionary value which is causing you error. You can append dict to the list if the value is not present already.

```<code>unique_solutions=[]
[unique_solutions.append(val) for val in lst if val not in unique_solutions]
</code>```

Result:

```<code>>>> print(unique_solutions)
[{'101': ['A', 'B'], '102': ['C'], '103': ['D'], '104': [], '105': [], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}, {'101': ['A'], '102': ['C'], '103': ['B'], '104': ['D'], '105': ['E'], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}]
</code>```

Title: Python - List of unique dictionaries where each dictionary value is a list

Body:
Let's say I got a list of dictionaries like this:

[
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
{'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E','F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

and I need to obtain a list of unique dictionaries (removing the duplicates):

[
 {'101': ['A','B'],
  '102': ['C'],
  '103': ['D'],
  '104': [],
  '105': [],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']},
 {'101': ['A'],
  '102': ['C'],
  '103': ['B'],
  '104': ['D'],
  '105': ['E'],
  'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}
]

I tried

unique_solutions = list(set(val for dic in full_solutions_list for val in dic.values()))

But the 'list' type of dictionary values are unhashable.

What would be an efficient way to do this? (the number of dictionaries is relatively large).

Body:
You are trying to iterate through the dictionary value which is causing you error. You can append dict to the list if the value is not present already.

unique_solutions=[]
[unique_solutions.append(val) for val in lst if val not in unique_solutions]

Result:

>>> print(unique_solutions)
[{'101': ['A', 'B'], '102': ['C'], '103': ['D'], '104': [], '105': [], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}, {'101': ['A'], '102': ['C'], '103': ['B'], '104': ['D'], '105': ['E'], 'deck': ['E', 'F', 'G', 'H', 'I', 'J', 'K', 'L']}]


问:
How to drop rows by condition on string value in pandas dataframe?
Consider a Pandas Dataframe like:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df
</code>```

Giving:

```<code>                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com
</code>```

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

```<code>                   url
0   http://ww.url3.com
</code>```

I do this

```<code>domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))
</code>```

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

```<code>import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)
</code>```

答:
you can use pd.Series.str.contains here.

```<code>df[~df.url.str.contains('|'.join(domainToCheck))]

                   url
3  http://www.url3.com
</code>```

If you want to reset index use this

```<code>df[~df.url.str.contains('|'.join(domainToCheck))].reset_index(drop=True)

                   url
0  http://www.url3.com
</code>```

Body:
Consider a Pandas Dataframe like:

>>> import pandas as pd
>>> df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com', 'http://www.url2.com','http://www.url3.com','http://www.url1.com']))
>>> df

Giving:

                   url
0      http://url1.com
1  http://www.url1.com
2  http://www.url2.com
3  http://www.url3.com
4  http://www.url1.com

I want to remove all rows containing url1.com and url2.com to obtain dataframe result like:

                   url
0   http://ww.url3.com

I do this

domainToCheck = ('url1.com', 'url2.com')
goodUrl = df['url'].apply(lambda x : any(domain in x for domain in domainToCheck))

But this give me no result.

Any idea how to solve the above problem?

Edit: Solution

import pandas as pd
import tldextract

df = pd.DataFrame(dict(url=['http://url1.com', 'http://www.url1.com','http://www.url2.com','http://www.url3.com','http://www.url1.com']))
domainToCheck = ['url1', 'url2']
s = df.url.map(lambda x : tldextract.extract(x).domain).isin(domainToCheck)
df = df[~s].reset_index(drop=True)

Body:
you can use pd.Series.str.contains here.

df[~df.url.str.contains('|'.join(domainToCheck))]

                   url
3  http://www.url3.com

If you want to reset index use this

df[~df.url.str.contains('|'.join(domainToCheck))].reset_index(drop=True)

                   url
0  http://www.url3.com


问:
Expression Changed after it has been checked Angular
I have this input for uploading a document, and i'm trying to check if it's empty to show an alert.

This is my code:

```<code><div class="form-group">
    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">
</div>
<div *ngIf="!documentLink.value" class="alert alert-danger">
   Imaginea de coperta este necesara!
</div>

</code>```

I have this error:

```<code>ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.
</code>```

I use this viewchild to take the value

```<code>@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;
</code>```

and that's in my method for adding it in the database:

```<code>const link = this.inputDocumentLink.nativeElement.value;
...
</code>```

Can you help me? Thank you very much!

答:
The problem is that your *ngIf condition depends on a property of the input element that is updated with data binding. To avoid the exception, you should refer to the original data instead of the element property.

The code below shows how to keep using the async pipe without repeating it. The async result is stored in a doc object set in the *ngIf condition of an encompassing ng-container (creating an object ensures that the condition is always true). We then use doc.url as the value in the input and in the *ngIf condition of the div element.

```<code><ng-container *ngIf="{ url: urlDocument | async } as doc">
  <div class="form-group">
    ...
    <input type="text" #documentLink [value]="doc.url" ...>
  </div>
  <div *ngIf="!doc.url" ...>
     Imaginea de coperta este necesara!
  </div>
</ng-container>
</code>```

See this stackblitz for a demo.

Body:
I have this input for uploading a document, and i'm trying to check if it's empty to show an alert.

This is my code:

    <input type="file" name="file" accept="application/pdf, application/msword, application/vnd.ms-powerpoint"
    (change)="onUpload($event)">
    <input type="text" #documentLink class="form-control" name="urlDocument" [value]="urlDocument | async">

   Imaginea de coperta este necesara!

I have this error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.
Previous value: 'ngIf: true'. Current value: 'ngIf: false'.

I use this viewchild to take the value

@ViewChild('documentLink', {static: false}) inputDocumentLink : ElementRef;

and that's in my method for adding it in the database:

const link = this.inputDocumentLink.nativeElement.value;
...

Can you help me? Thank you very much!

Body:
The problem is that your *ngIf condition depends on a property of the input element that is updated with data binding. To avoid the exception, you should refer to the original data instead of the element property.

The code below shows how to keep using the async pipe without repeating it. The async result is stored in a doc object set in the *ngIf condition of an encompassing ng-container (creating an object ensures that the condition is always true). We then use doc.url as the value in the input and in the *ngIf condition of the div element.

<ng-container *ngIf="{ url: urlDocument | async } as doc">
  <div class="form-group">
    ...
    <input type="text" #documentLink [value]="doc.url" ...>
  </div>
  <div *ngIf="!doc.url" ...>
     Imaginea de coperta este necesara!
  </div>
</ng-container>

See this stackblitz for a demo.


问:
How do I add a button on right side of the toolbar in a UISplitViewController?
Trying to add a button to the right side of the toolbar of the detailviewcontroller in a split-view based app. I used flexible space to get it to the right side. In portrait it works fine, but in landscape (when the menu button disappears), the button gets moved so that half of it is off the screen.

Here's the relevant code (in DetailViewController.m):

```<code>- (void) viewDidLoad
{
    // initialize toolbar
    toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake( 0, 0, 768, 44 )];
    titleLabel = [[UILabel alloc] initWithFrame: CGRectMake( 284, 3, 200, 35 )];
    titleLabel.text = @"Title & Location";
    titleLabel.textAlignment = UITextAlignmentCenter;
    [toolbar addSubview: titleLabel];
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle: @"Add Event" style: UIBarButtonItemStyleDone target: rootController action: @selector(parseDone)];
    NSArray *buttonArray = [NSArray arrayWithObjects: flexibleSpace, doneButton, nil];
    [toolbar setItems: buttonArray];
    [doneButton release];
    [flexibleSpace release];
    [self.view addSubview: toolbar];
}
- (void)showRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem
{
    NSMutableArray *itemsArray = [toolbar.items mutableCopy];
    [itemsArray insertObject: barButtonItem atIndex: 0];
    [toolbar setItems:itemsArray animated:NO];
}
- (void)invalidateRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem
{
    NSMutableArray *itemsArray = [toolbar.items mutableCopy];
    [itemsArray removeObject:barButtonItem];
    [toolbar setItems:itemsArray animated:NO];
    [itemsArray release];
}
</code>```

答:
I recognize this problem from a project I worked on a while back. I think it only happened occasionally and I don't remember if we actually fixed it.

In your case it seems like it would be easier to just use the navigation bar and set rightBarButtonItem and leftBarButtonItem. That should solve your problem.

Body:
Trying to add a button to the right side of the toolbar of the detailviewcontroller in a split-view based app. I used flexible space to get it to the right side. In portrait it works fine, but in landscape (when the menu button disappears), the button gets moved so that half of it is off the screen.

Here's the relevant code (in DetailViewController.m):

- (void) viewDidLoad
{
    // initialize toolbar
    toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake( 0, 0, 768, 44 )];
    titleLabel = [[UILabel alloc] initWithFrame: CGRectMake( 284, 3, 200, 35 )];
    titleLabel.text = @"Title & Location";
    titleLabel.textAlignment = UITextAlignmentCenter;
    [toolbar addSubview: titleLabel];
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target: nil action: nil];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle: @"Add Event" style: UIBarButtonItemStyleDone target: rootController action: @selector(parseDone)];
    NSArray *buttonArray = [NSArray arrayWithObjects: flexibleSpace, doneButton, nil];
    [toolbar setItems: buttonArray];
    [doneButton release];
    [flexibleSpace release];
    [self.view addSubview: toolbar];
}
- (void)showRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem
{
    NSMutableArray *itemsArray = [toolbar.items mutableCopy];
    [itemsArray insertObject: barButtonItem atIndex: 0];
    [toolbar setItems:itemsArray animated:NO];
}
- (void)invalidateRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem
{
    NSMutableArray *itemsArray = [toolbar.items mutableCopy];
    [itemsArray removeObject:barButtonItem];
    [toolbar setItems:itemsArray animated:NO];
    [itemsArray release];
}


问:
Jest - import a node module
I have an Angular component that imports a node module (in this case it's prismjs).

```<code>import Prism from 'prismjs';
import 'prismjs/components/prism-markup';
...
</code>```

I have a piece of code that references Prism.highlightElement()

However, when I run my tests I get the error:
TypeError: Cannot read property 'highlightElement' of undefined

I assume that Jest is mocking the node_module, but any idea how to stop it.

I'm using the Angular Preset Jest library and I've tried:

unmockedModulePathPatterns: ['./node_modules/prismjs'] in the config and it doesn't work.

I've also tried:
unmockedModulePathPatterns: ['prismjs']
Any ideas?

答:
I fixed this by changing my import statement to:

```<code>import * as Prism from 'prismjs';
</code>```

I have no idea why this works.

Title: Jest - import a node module

Body:
I have an Angular component that imports a node module (in this case it's prismjs).

import Prism from 'prismjs';
import 'prismjs/components/prism-markup';
...

I have a piece of code that references Prism.highlightElement()

However, when I run my tests I get the error:
TypeError: Cannot read property 'highlightElement' of undefined

I assume that Jest is mocking the node_module, but any idea how to stop it.

I'm using the Angular Preset Jest library and I've tried:

unmockedModulePathPatterns: ['./node_modules/prismjs'] in the config and it doesn't work.

I've also tried:
unmockedModulePathPatterns: ['prismjs']
Any ideas?

Body:
I fixed this by changing my import statement to:

import * as Prism from 'prismjs';

I have no idea why this works.