问:
How to csrf_token in asynchoronous post with jquery
I found several posts in relation to my question, but none of them solves my problem. I am sending data to the server but I keep getting a 403-error with an error-message that complains about the csrf_token.

Here is my html:

```<code>            <ul id="EditorNav" class="editor-nav">
                <form id="NavItemsEditorForm" class="nav-items-editor-form">
                    {% csrf_token %}
                        <!-- {{ form }} -->
                    {% for item in pages %}
                        <input class="editor-nav-input" type="text" value="{{ item }}"/>
                    {% endfor %}
                </form>
                <img id="Plus" class="plus" src="{% static 'img/plus.png' %}" alt="Plus" title="Een menu-item toevoegen" />
                <img id="Shuffle" class="shuffle" src="{% static 'img/shuffle.png' %}" alt="Shuffle" title="Verander de volgorde van de menu-items" />
                <button id="NavEditReady" class="nav-edit-ready">Klaar</button>
            </ul>
</code>```

I created a view and added that view to the urlpatterns-arrau in urls.py. Here is my javascript:

```<code>    jQuery.each( jQuery( '.editor-nav-input' ), function( i ){
        let data = {}

        if( jQuery( this ).val() === '' )
        {
            jQuery( this ).remove();
        }else{
            const idx = jQuery( '.editor-nav-input' ).index( this );
            const tekst = jQuery( '.editor-nav-input' ).eq( idx ).val();

            data = {
                "id": idx,
                "tekst": tekst,
                "href": tekst.replace(/\s/g, '_').toLowerCase(),
                "volgorde": idx + 1,
            };
            formdata.push( data );
        }
    });
    console.log( formdata );

    // Stuur de data naar de server:

    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { 'X-CSRFToken': '{{ csrf_token }}' },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });
</code>```

I have tried different ways of including the csrf-token to the data as a seperate object. But nothing works. Any help is appreciated.

答:
Here is the solution I found:

Javascript:

```<code>    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { "X-CSRFToken": jQuery('input[name=csrfmiddlewaretoken]').val() },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });
</code>```

And in views.py:

```<code>def PagesPost(request):
    if request.method == 'POST':
        tekst = request.POST.get( 'tekst' )
        href = request.POST.get( 'href' )
        volgorde = request.POST.get( 'volgorde' )

        return HttpResponse( 'Success' )
</code>```

I hope this will help somebody someday.

Body:
I found several posts in relation to my question, but none of them solves my problem. I am sending data to the server but I keep getting a 403-error with an error-message that complains about the csrf_token.

Here is my html:

                <form id="NavItemsEditorForm" class="nav-items-editor-form">
                    {% csrf_token %}

                    {% for item in pages %}
                        <input class="editor-nav-input" type="text" value="{{ item }}"/>
                    {% endfor %}
                </form>

                <button id="NavEditReady" class="nav-edit-ready">Klaar</button>

I created a view and added that view to the urlpatterns-arrau in urls.py. Here is my javascript:

    jQuery.each( jQuery( '.editor-nav-input' ), function( i ){
        let data = {}

        if( jQuery( this ).val() === '' )
        {
            jQuery( this ).remove();
        }else{
            const idx = jQuery( '.editor-nav-input' ).index( this );
            const tekst = jQuery( '.editor-nav-input' ).eq( idx ).val();

            data = {
                "id": idx,
                "tekst": tekst,
                "href": tekst.replace(/\s/g, '_').toLowerCase(),
                "volgorde": idx + 1,
            };
            formdata.push( data );
        }
    });
    console.log( formdata );

    // Stuur de data naar de server:

    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { 'X-CSRFToken': '{{ csrf_token }}' },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });

I have tried different ways of including the csrf-token to the data as a seperate object. But nothing works. Any help is appreciated.

Body:
Here is the solution I found:

Javascript:

    jQuery.ajax({
        method: "POST",
        url: "/pagepost/",
        headers: { "X-CSRFToken": jQuery('input[name=csrfmiddlewaretoken]').val() },
        data: formdata,
        dataType: "json",
        success: function( response ){
            console.log(response);
        },
        error: function( err ){
            console.log( err.responseText );
        }
    });

And in views.py:

def PagesPost(request):
    if request.method == 'POST':
        tekst = request.POST.get( 'tekst' )
        href = request.POST.get( 'href' )
        volgorde = request.POST.get( 'volgorde' )

        return HttpResponse( 'Success' )

I hope this will help somebody someday.


来源: stackexchange

问:
Vue props become null on $router.go(-1)
I am trying to route back on the 2nd page like this.
This is the 3rd page

```<code> <v-btn text small @click="$router.go(-1)">
   <v-icon>fas fa-arrow-left</v-icon>
 </v-btn>
</code>```

This is my App.vue

```<code><keep-alive :max="40">
  <router-view :key="$route.fullPath"></router-view>
</keep-alive>
</code>```

This are my 2nd page props.

```<code>props: {
    abc: {
      type: String,
      default() {
        return null;
      }
    },
    xyz: {
      type: Array,
      default() {
        return null;
      }
    }
  },
</code>```

Now the 2nd page has props in it. Now when i route back from 3rd page the props in the previous
component is set to null.
Is there a way to handle this props from being setting it to null on routing back.

答: Props works from parent to child only, if you are navigating back to that component having props via non parent then props will always be null, in this scenario you can use localStorage or try using https://v2.vuejs.org/v2/api/#keep-alive</p>

ContentLicense: CC BY-SA 4.0

Title: Vue props become null on $router.go(-1)

Body:
I am trying to route back on the 2nd page like this.
This is the 3rd page

 <v-btn text small @click="$router.go(-1)">
   <v-icon>fas fa-arrow-left</v-icon>
 </v-btn>

This is my App.vue

<keep-alive :max="40">
  <router-view :key="$route.fullPath"></router-view>
</keep-alive>

This are my 2nd page props.

props: {
    abc: {
      type: String,
      default() {
        return null;
      }
    },
    xyz: {
      type: Array,
      default() {
        return null;
      }
    }
  },

Now the 2nd page has props in it. Now when i route back from 3rd page the props in the previous
component is set to null.
Is there a way to handle this props from being setting it to null on routing back.


问:
Pandas cannot call function on a datetimeindex
I'm trying to call a dayofweek() on my datetimeindex in a dataframe. Here is my code:

```<code>v = [
[
    1582041084.72,
    "1989121.03"
],
[
    1582041684.72,
    "1989121.03"
]

df = pd.DataFrame.from_records(v, columns=['time', 'points'])
df = df.astype({'points': 'float'})
df['time'] = pd.to_datetime(df['time'], unit='s')
df = df.set_index('time')
filtered = df.between_time('10:00', '14:30')

print(filtered.index.dayofweek())
</code>```

This returns an error saying 'Int64Index' object is not callable.

Here's the output of df.index:

```<code>DatetimeIndex(['2020-02-19 10:01:24.720000029',
               '2020-02-19 10:11:24.720000029'],
              dtype='datetime64[ns]', name='time', freq=None)
</code>```

答:
dayofweek doesn't need ().
Simply do:

```<code>print(df.index.dayofweek)
</code>```

Body:
I'm trying to call a dayofweek() on my datetimeindex in a dataframe. Here is my code:

v = [
[
    1582041084.72,
    "1989121.03"
],
[
    1582041684.72,
    "1989121.03"
]

df = pd.DataFrame.from_records(v, columns=['time', 'points'])
df = df.astype({'points': 'float'})
df['time'] = pd.to_datetime(df['time'], unit='s')
df = df.set_index('time')
filtered = df.between_time('10:00', '14:30')

print(filtered.index.dayofweek())

This returns an error saying 'Int64Index' object is not callable.

Here's the output of df.index:

DatetimeIndex(['2020-02-19 10:01:24.720000029',
               '2020-02-19 10:11:24.720000029'],
              dtype='datetime64[ns]', name='time', freq=None)

Body:
dayofweek doesn't need ().
Simply do:

print(df.index.dayofweek)


问:
How to change words after match containing slash
Inside my file "input.txt" I have the following path written:

```<code>"/home/inputfiles/water_gen/5202_water.gen"
</code>```

I want to change "5202" by specific numbers (probably using a for loop) and save them as different files.

I thought the easiest way was to use sed to find "water_gen/" as a match and then change the rest.

But is there an easier approach? I've been having problems because of the slash.

答:
This might work for you (GNU sed & parallel):

```<code>parallel --dry sed -E 's/[0-9]+/{1}/' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt
</code>```

This produces the command set to replace the first group of numbers in file.txt with 1000 to 1005 and write the results to file1000.txt to file1005.txt.

Once the command set has been verified, remove the --dry short for --dry-run  option and rerun.

N.B. The original file is not changed.

The substitution can be more specific, i.e.:

```<code>parallel sed -E \''s#(/home/inputfiles/water_gen/)5202(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt
</code>```

N.B. The sed command quotes are quoted \' so that the back references are not mistaken for things in the shell.

Or, a little less specific:

```<code>parallel sed -E \''s#(/home/inputfiles/water_gen/)[0-9]+(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt
</code>```

The replacement numbers may be in a file:

```<code>cat <<\! > replacementsFile
1000
1001
1002
1003
1004
1005
!
parallel sed -E \''s#(/home/inputfiles/water_gen/)5202(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt :::: replacementsFile ::: file.txt
</code>```

Body:
Inside my file "input.txt" I have the following path written:

"/home/inputfiles/water_gen/5202_water.gen"

I want to change "5202" by specific numbers (probably using a for loop) and save them as different files.

I thought the easiest way was to use sed to find "water_gen/" as a match and then change the rest.

But is there an easier approach? I've been having problems because of the slash.

Body:
This might work for you (GNU sed & parallel):

parallel --dry sed -E 's/[0-9]+/{1}/' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt

This produces the command set to replace the first group of numbers in file.txt with 1000 to 1005 and write the results to file1000.txt to file1005.txt.

Once the command set has been verified, remove the --dry short for --dry-run  option and rerun.

N.B. The original file is not changed.

The substitution can be more specific, i.e.:

parallel sed -E \''s#(/home/inputfiles/water_gen/)5202(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt

N.B. The sed command quotes are quoted \' so that the back references are not mistaken for things in the shell.

Or, a little less specific:

parallel sed -E \''s#(/home/inputfiles/water_gen/)[0-9]+(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt ::: {1000..1005} ::: file.txt

The replacement numbers may be in a file:

cat <<\! > replacementsFile
1000
1001
1002
1003
1004
1005
!
parallel sed -E \''s#(/home/inputfiles/water_gen/)5202(_water.gen)#\1{1}\2#'\' {2} \> {2.}{1}.txt :::: replacementsFile ::: file.txt


问:
Best approach to make a fullscreen WPF app
I'm creating a full-screen application in WPF and i need to choose how to actually resize the contents to use all the available space on the screen.

As far as i know, there are 2 solutions:

Grids with stars-dimensions

ViewBox wrapper

I think they both do the job but depending on the application one is better than the other: when should the grid approach be used? And when the viewbox method is acceptable?

答:
I'd do some experimentation:

I agree with ColineE and karam:

Create a Grid using Stars for columnwidths and rows to help layout the program.

Then wrap the specific items you need to scale in viewboxes.

So, I guess this answer is 1/2 combined.

Check this sample code to see what I mean...

```<code><Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

<TextBlock Grid.Column ="0"  Text="Left"/>

    <Viewbox Grid.Column ="1" >
        <TextBlock  Text="Right"/>
    </Viewbox>
</Grid>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd do some experimentation:

I agree with ColineE and karam:

Create a Grid using Stars for columnwidths and rows to help layout the program.

Then wrap the specific items you need to scale in viewboxes.

So, I guess this answer is 1/2 combined.

Check this sample code to see what I mean...

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

<TextBlock Grid.Column ="0"  Text="Left"/>

    <Viewbox Grid.Column ="1" >
        <TextBlock  Text="Right"/>
    </Viewbox>
</Grid>


问:
How to send data via POST or GET in Mod_Python?
With JS, i send a AJAX post request.

```<code> $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'
</code>```

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

```<code>def index(req):
    # data = ??
</code>```

PS: here is how to reproduce the problem. Create testjson.html:

```<code><script type="text/javascript">
xhr = new XMLHttpRequest();
xhr.open("POST", "testjson.py");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function(res) { console.log(xhr.responseText); };
xhr.send(JSON.stringify({'foo': '0', 'bar': '1'}));
</script>
</code>```

and create testjson.py containing:

```<code>from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK
</code>```

Create a .htaccess containing:

```<code>AddHandler mod_python .py
PythonHandler mod_python.publisher
</code>```

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

答:
From the Mod Python docs here.

Here you can do, for example to get the data

```<code>def index(req):
    data = req.read()
</code>```

Additional Links : http://vandermerwe.co.nz/?p=9

Body:
With JS, i send a AJAX post request.

 $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

def index(req):
    # data = ??

PS: here is how to reproduce the problem. Create testjson.html:

and create testjson.py containing:

from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK

Create a .htaccess containing:

AddHandler mod_python .py
PythonHandler mod_python.publisher

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

Body:
From the Mod Python docs here.

Here you can do, for example to get the data

def index(req):
    data = req.read()

Additional Links : http://vandermerwe.co.nz/?p=9


问:
VBA skips cells when data is entered
I have an issue with my VBA code, maybe someone can explain where I made a mistake and how can it be fixed.
My goal is to create 7 columns without skipping cells.
I have 7 text boxes but not all of them has to be filled every time data is entered.
At the moment when data is added only in Name text box it creates new row but when only surname is added it skips first empty lines and enters diagonally under Name entry(as in attachment) Excel img

Also there is a mistake when I want to add entry in other text boxes, entered data is just moved around.

```<code>Private Sub CommandButton1_Click()

   Dim LR As Long

   LR = Cells(Rows.Count, 1).End(xlUp).Row + 1

   Cells(LR, 1).Value = Name.Value
   Cells(LR, 2).Value = Surname.Value
   Cells(LR, 3).Value = Address.Value
   Cells(LR, 4).Value = Phone.Value
   Cells(LR, 5).Value = City.Value
   Cells(LR, 6).Value = Car.Value
   Cells(LR, 7).Value = Job.Value

   Name.Value = ""
   Surname.Value = ""
   Address.Value = ""
   Phone.Value = ""
   City.Value = ""
   Car.Value = ""
   Job.Value = ""

End Sub

</code>```

答:
You are always looking for the last row in column A, thats why it adds the surname one row below the last row of column A. If you want to know the last row of another column, you need to change the 1 after Rows.Count into the corresponding number. You can also do this in one line, have a gander:</p>

```<code>Private Sub CommandButton1_Click()

   Cells(Cells(Rows.Count, 1).End(xlUp).Row + 1, 1).Value = Name.Value
   Cells(Cells(Rows.Count, 2).End(xlUp).Row + 1, 2).Value = Surname.Value
   Cells(Cells(Rows.Count, 3).End(xlUp).Row + 1, 3).Value = Address.Value
   Cells(Cells(Rows.Count, 4).End(xlUp).Row + 1, 4).Value = Phone.Value
   Cells(Cells(Rows.Count, 5).End(xlUp).Row + 1, 5).Value = City.Value
   Cells(Cells(Rows.Count, 6).End(xlUp).Row + 1, 6).Value = Car.Value
   Cells(Cells(Rows.Count, 7).End(xlUp).Row + 1, 7).Value = Job.Value

   Name.Value = ""
   Surname.Value = ""
   Address.Value = ""
   Phone.Value = ""
   City.Value = ""
   Car.Value = ""
   Job.Value = ""

End Sub
</code>```

Title: VBA skips cells when data is entered

Body:
I have an issue with my VBA code, maybe someone can explain where I made a mistake and how can it be fixed.
My goal is to create 7 columns without skipping cells.
I have 7 text boxes but not all of them has to be filled every time data is entered.
At the moment when data is added only in Name text box it creates new row but when only surname is added it skips first empty lines and enters diagonally under Name entry(as in attachment) Excel img

Also there is a mistake when I want to add entry in other text boxes, entered data is just moved around.

Private Sub CommandButton1_Click()

   Dim LR As Long

   LR = Cells(Rows.Count, 1).End(xlUp).Row + 1

   Cells(LR, 1).Value = Name.Value
   Cells(LR, 2).Value = Surname.Value
   Cells(LR, 3).Value = Address.Value
   Cells(LR, 4).Value = Phone.Value
   Cells(LR, 5).Value = City.Value
   Cells(LR, 6).Value = Car.Value
   Cells(LR, 7).Value = Job.Value

   Name.Value = ""
   Surname.Value = ""
   Address.Value = ""
   Phone.Value = ""
   City.Value = ""
   Car.Value = ""
   Job.Value = ""

End Sub

Body:
You are always looking for the last row in column A, thats why it adds the surname one row below the last row of column A. If you want to know the last row of another column, you need to change the 1 after Rows.Count into the corresponding number. You can also do this in one line, have a gander:

Private Sub CommandButton1_Click()

   Cells(Cells(Rows.Count, 1).End(xlUp).Row + 1, 1).Value = Name.Value
   Cells(Cells(Rows.Count, 2).End(xlUp).Row + 1, 2).Value = Surname.Value
   Cells(Cells(Rows.Count, 3).End(xlUp).Row + 1, 3).Value = Address.Value
   Cells(Cells(Rows.Count, 4).End(xlUp).Row + 1, 4).Value = Phone.Value
   Cells(Cells(Rows.Count, 5).End(xlUp).Row + 1, 5).Value = City.Value
   Cells(Cells(Rows.Count, 6).End(xlUp).Row + 1, 6).Value = Car.Value
   Cells(Cells(Rows.Count, 7).End(xlUp).Row + 1, 7).Value = Job.Value

   Name.Value = ""
   Surname.Value = ""
   Address.Value = ""
   Phone.Value = ""
   City.Value = ""
   Car.Value = ""
   Job.Value = ""

End Sub


Title: How to format different arrays to list out in table using modulo?

Body:
This is my array

$headers = '
    '2020-02-10' => [
        'DateShort' => 'Mon 10/02/2020',
    ],
    '2020-02-11' => [
        'DateShort' => 'Tue 11/02/2020',
    ],
    '2020-02-12' => [
        'DateShort' => 'Wed 12/02/2020',
    ],
    '2020-02-13' => [
        'DateShort' => 'Thu 13/02/2020',
    ],
    '2020-02-14' => [
        'DateShort' => 'Fri 14/02/2020',
    ],
    '2020-02-15' => [
        'DateShort' => 'Sat 15/02/2020',
    ],
    '2020-02-16' => [
        'DateShort' => 'Sun 16/02/2020',
    ],
    '2020-02-17' => [
        'DateShort' => 'Mon 17/02/2020',
    ],
    '2020-02-18' => [
        'DateShort' => 'Tue 18/02/2020',
    ],
    '2020-02-19' => [
        'DateShort' => 'Wed 19/02/2020',
    ],
];

$data = [
    [
        'RoomName' => 'RoomName1'
        'Days' => [
            '2020-02-10' => [
                    'NumRooms' => 10,
                    'AverageRate' => 'INR10.00',
                    'AverageRateText' =>  @ INR10.00
                ],
            '2020-02-11' => [
                    'NumRooms' => 20,
                    'AverageRate' => 'INR20.00',
                    'AverageRateText' =>  @ INR20.00
                ],
            '2020-02-12' => [
                    'NumRooms' => 30,
                    'AverageRate' => 'INR30.00',
                    'AverageRateText' =>  @ INR30.00
                ],
            '2020-02-13' => [
                    'NumRooms' => 40,
                    'AverageRate' => 'INR40.00',
                    'AverageRateText' =>  @ INR40.00
                ],
            '2020-02-14' => [
                    'NumRooms' => 50
                    'AverageRate' => INR5.00
                    'AverageRateText' =>  @ INR50.00
                ],
            '2020-02-15' => [
                    'NumRooms' => 60
                    'AverageRate' => INR60.00
                    'AverageRateText' =>  @ INR60.00
                ],
            '2020-02-16' => [
                    'NumRooms' => 70
                    'AverageRate' => INR70.00
                    'AverageRateText' =>  @ INR70.00
                ],
            '2020-02-17' => [
                    'NumRooms' => 80
                    'AverageRate' => INR80.00
                    'AverageRateText' =>  @ INR80.00
                ],
            '2020-02-18' => [
                    'NumRooms' => 90
                    'AverageRate' => INR90.00
                    'AverageRateText' =>  @ INR90.00
                ],
            '2020-02-19' => [
                    'NumRooms' => 100
                    'AverageRate' => INR100.00
                    'AverageRateText' =>  @ INR100.00
                ],
        ],
    ],
    [
        'RoomName' => 'RoomName2'
        'Days' => [
            '2020-02-10' => [
                    'NumRooms' => 100,
                    'AverageRate' => 'INR100.00',
                    'AverageRateText' =>  @ INR100.00
                ],
            '2020-02-11' => [
                    'NumRooms' => 200,
                    'AverageRate' => 'INR200.00',
                    'AverageRateText' =>  @ INR200.00
                ],
            '2020-02-12' => [
                    'NumRooms' => 300,
                    'AverageRate' => 'INR300.00',
                    'AverageRateText' =>  @ INR300.00
                ],
            '2020-02-13' => [
                    'NumRooms' => 400,
                    'AverageRate' => 'INR400.00',
                    'AverageRateText' =>  @ INR400.00
                ],
            '2020-02-14' => [
                    'NumRooms' => 500
                    'AverageRate' => INR500.00
                    'AverageRateText' =>  @ INR500.00
                ],
            '2020-02-15' => [
                    'NumRooms' => 600
                    'AverageRate' => INR600.00
                    'AverageRateText' =>  @ INR600.00
                ],
            '2020-02-16' => [
                    'NumRooms' => 700
                    'AverageRate' => INR700.00
                    'AverageRateText' =>  @ INR700.00
                ],
            '2020-02-17' => [
                    'NumRooms' => 800
                    'AverageRate' => INR800.00
                    'AverageRateText' =>  @ INR800.00
                ],
            '2020-02-18' => [
                    'NumRooms' => 900
                    'AverageRate' => INR900.00
                    'AverageRateText' =>  @ INR900.00
                ],
            '2020-02-19' => [
                    'NumRooms' => 1000
                    'AverageRate' => INR1000.00
                    'AverageRateText' =>  @ INR1000.00
                ],
        ]
    ],
    [
        'RoomName' => 'RoomName3'
        'Days' => [
            '2020-02-10' => [
                    'NumRooms' => 100,
                    'AverageRate' => 'INR100.00',
                    'AverageRateText' =>  @ INR100.00
                ],
            '2020-02-11' => [
                    'NumRooms' => 200,
                    'AverageRate' => 'INR200.00',
                    'AverageRateText' =>  @ INR200.00
                ],
            '2020-02-12' => [
                    'NumRooms' => 300,
                    'AverageRate' => 'INR300.00',
                    'AverageRateText' =>  @ INR300.00
                ],
            '2020-02-13' => [
                    'NumRooms' => 400,
                    'AverageRate' => 'INR400.00',
                    'AverageRateText' =>  @ INR400.00
                ],
            '2020-02-14' => [
                    'NumRooms' => 500
                    'AverageRate' => INR500.00
                    'AverageRateText' =>  @ INR500.00
                ],
            '2020-02-15' => [
                    'NumRooms' => 600
                    'AverageRate' => INR600.00
                    'AverageRateText' =>  @ INR600.00
                ],
            '2020-02-16' => [
                    'NumRooms' => 700
                    'AverageRate' => INR700.00
                    'AverageRateText' =>  @ INR700.00
                ],
            '2020-02-17' => [
                    'NumRooms' => 800
                    'AverageRate' => INR800.00
                    'AverageRateText' =>  @ INR800.00
                ],
            '2020-02-18' => [
                    'NumRooms' => 900
                    'AverageRate' => INR900.00
                    'AverageRateText' =>  @ INR900.00
                ],
            '2020-02-19' => [
                    'NumRooms' => 1000
                    'AverageRate' => INR1000.00
                    'AverageRateText' =>  @ INR1000.00
                ],
        ]
    ]
];

And I want to format it in this form

      Mon 10/02/2020
      Tue 11/02/2020
      Wed 12/02/2020
      Thu 13/02/2020
      Fri 14/02/2020

      RoomName1
      10 @ INR10.00
      20 @ INR20.00
      30 @ INR30.00
      40 @ INR40.00
      50 @ INR50.00

      RoomName2
      100 @ INR100.00
      200 @ INR200.00
      300 @ INR300.00
      400 @ INR400.00
      500 @ INR500.00

      RoomName3
      100 @ INR100.00
      200 @ INR200.00
      300 @ INR300.00
      400 @ INR400.00
      500 @ INR500.00

      Sat 15/02/2020
      Sun 16/02/2020
      Mon 17/02/2020
      Tue 18/02/2020
      Wed 19/02/2020

        RoomName1
      60 @ INR60.00
      70 @ INR7.00
      80 @ INR80.00
      90 @ INR90.00
      100 @ INR100.00

    RoomName2
      600 @ INR600.00
      700 @ INR700.00
      800 @ INR800.00
      900 @ INR900.00
      1000 @ INR1000.00

    RoomName3
      600 @ INR600.00
      700 @ INR700.00
      800 @ INR800.00
      900 @ INR900.00
      1000 @ INR1000.00

code i have written:

$html .= '
';

$columnIterator = 1;
$headerData = [];
$headerCols = 0;
foreach ($headerdatas as $sqlDate => $data) {
    if ($columnIterator % 5 == 1) {
        $headerData[$headerCols] = '
	';
    }
    if (!is_array($data)) {
        continue;
    }
    $headerData[$headerCols] .= '' . $data['DateShort'] . '	';
    $dates[] = $sqlDate;
    if ($columnIterator % 5 == 0) {
        $headerData[$headerCols] .= '
';
        $headerCols++;
    }
    $columnIterator++;
}

$tableRows = 0;
foreach ($tablerows as $roomData) {
    $columnIterator = 1;
    $html .= $headerData[$tableRows];
    foreach ($dates as $sqlDate) {
        if ($columnIterator % 5 == 1) {
            $html .=  '
' . $roomData['RoomName'] . '	';
        }
        $html .= '';
        if (array_key_exists($sqlDate, $roomData['Days'])) {
            $html .= $roomData['Days'][$sqlDate]['NumRooms']
                . $roomData['Days'][$sqlDate]['AverageRateText'];
        }
        else {
            $html .= '0';
        }
        $html .= '	';
        if ($columnIterator % 5 == 0) {
            $html .= '
';
        }
        $columnIterator++;
    }
    $tableRows++;
    $html .= '
';
}
$html .= '
';

Body:
Here is what I think you want, I had to fix a lot of errors for you since your roomDataDates is not a valid Array also some of the logic in the PHP you posted was not right, like looping through $tableRows while you already assigned it a value of 0:

<?php
$headers = [
    '2020-02-10' => [
        'DateShort' => 'Mon 10/02/2020',
    ],
    '2020-02-11' => [
        'DateShort' => 'Tue 11/02/2020',
    ],
    '2020-02-12' => [
        'DateShort' => 'Wed 12/02/2020',
    ],
    '2020-02-13' => [
        'DateShort' => 'Thu 13/02/2020',
    ],
    '2020-02-14' => [
        'DateShort' => 'Fri 14/02/2020',
    ],
    '2020-02-15' => [
        'DateShort' => 'Sat 15/02/2020',
    ],
    '2020-02-16' => [
        'DateShort' => 'Sun 16/02/2020',
    ],
    '2020-02-17' => [
        'DateShort' => 'Mon 17/02/2020',
    ],
    '2020-02-18' => [
        'DateShort' => 'Tue 18/02/2020',
    ],
    '2020-02-19' => [
        'DateShort' => 'Wed 19/02/2020',
    ],
];

$roomsDataDates = [
    [
        'RoomName' => 'RoomName1',
        'Days' => [
            '2020-02-10' => [
                    'NumRooms' => 10,
                    'AverageRate' => 'INR10.00',
                    'AverageRateText' =>  '@ INR10.00'
                ],
            '2020-02-11' => [
                    'NumRooms' => 20,
                    'AverageRate' => 'INR20.00',
                    'AverageRateText' =>  '@ INR20.00'
                ],
            '2020-02-12' => [
                    'NumRooms' => 30,
                    'AverageRate' => 'INR30.00',
                    'AverageRateText' =>  '@ INR30.00'
                ],
            '2020-02-13' => [
                    'NumRooms' => 40,
                    'AverageRate' => 'INR40.00',
                    'AverageRateText' =>  '@ INR40.00'
                ],
            '2020-02-14' => [
                    'NumRooms' => 50,
                    'AverageRate' => 'INR5.00',
                    'AverageRateText' =>  '@ INR50.00'
                ],
            '2020-02-15' => [
                    'NumRooms' => 60,
                    'AverageRate' => 'INR60.00',
                    'AverageRateText' =>  '@ INR60.00'
                ],
            '2020-02-16' => [
                    'NumRooms' => 70,
                    'AverageRate' => 'INR70.00',
                    'AverageRateText' =>  '@ INR70.00'
                ],
            '2020-02-17' => [
                    'NumRooms' => 80,
                    'AverageRate' => 'INR80.00',
                    'AverageRateText' =>  '@ INR80.00'
                ],
            '2020-02-18' => [
                    'NumRooms' => 90,
                    'AverageRate' => 'INR90.00',
                    'AverageRateText' =>  '@ INR90.00'
                ],
            '2020-02-19' => [
                    'NumRooms' => 100,
                    'AverageRate' => 'INR100.00',
                    'AverageRateText' =>  '@ INR100.00'
                ],
        ],
    ],
    [
        'RoomName' => 'RoomName2',
        'Days' => [
            '2020-02-10' => [
                    'NumRooms' => 100,
                    'AverageRate' => 'INR100.00',
                    'AverageRateText' =>  '@ INR100.00'
                ],
            '2020-02-11' => [
                    'NumRooms' => 200,
                    'AverageRate' => 'INR200.00',
                    'AverageRateText' =>  '@ INR200.00'
                ],
            '2020-02-12' => [
                    'NumRooms' => 300,
                    'AverageRate' => 'INR300.00',
                    'AverageRateText' =>  '@ INR300.00'
                ],
            '2020-02-13' => [
                    'NumRooms' => 400,
                    'AverageRate' => 'INR400.00',
                    'AverageRateText' =>  '@ INR400.00'
                ],
            '2020-02-14' => [
                    'NumRooms' => 500,
                    'AverageRate' => 'INR500.00',
                    'AverageRateText' =>  '@ INR500.00'
                ],
            '2020-02-15' => [
                    'NumRooms' => 600,
                    'AverageRate' => 'INR600.00',
                    'AverageRateText' =>  '@ INR600.00'
                ],
            '2020-02-16' => [
                    'NumRooms' => 700,
                    'AverageRate' => 'INR700.00',
                    'AverageRateText' =>  '@ INR700.00'
                ],
            '2020-02-17' => [
                    'NumRooms' => 800,
                    'AverageRate' => 'INR800.00',
                    'AverageRateText' =>  '@ INR800.00'
                ],
            '2020-02-18' => [
                    'NumRooms' => 900,
                    'AverageRate' => 'INR900.00',
                    'AverageRateText' =>  '@ INR900.00'
                ],
            '2020-02-19' => [
                    'NumRooms' => 1000,
                    'AverageRate' => 'INR1000.00',
                    'AverageRateText' =>  '@ INR1000.00'
                ],
        ]
    ]
];

$html = '<table cellspacing="0" cellpadding="0" border="1">';

$columnIterator = 1;
$headerData = [];
$headerCols = 0;

function createRow($data, $dates, $start, $length, $roomData)
{
    $html = "<tr><td>$roomData</td>";
    // To display data under the next row of headings.
    for ($i = $start; $i < $start + $length; $i++) {
        $sqlDate = $dates[$i];
        $html .= '<td>';
        if (array_key_exists($sqlDate, $data['Days'])) {
            $html .= $data['Days'][$sqlDate]['NumRooms'] . ' '
                . $data['Days'][$sqlDate]['AverageRateText'];
        }
        else {
            $html .= '0';
        }
        $html .= '</td>';
    }
    $html .= '</tr>';
    return $html;
}

foreach ($headers as $sqlDate => $data) {
    if ($columnIterator % 5 == 1) {
        $headerData[$headerCols] = '<tr><th></th>';
    }
    if (!is_array($data)) {
        continue;
    }
    $headerData[$headerCols] .= '<th>' . $data['DateShort'] . '</th>';
    $dates[] = $sqlDate;
    if ($columnIterator % 5 == 0) {
        $headerData[$headerCols] .= '</tr>';
        $headerCols++;
    }
    $columnIterator++;
}
$rooms = array_values_deep($venueRooms[$roomVenueId], 'RoomName');
$tableRows = 0;
foreach ($headerData as $header) {
   $html .= $header;
   $columnIterator = 1;
   $k = 0;
   foreach ($rooms as $roomData) {
      $html .= createRow($roomsDataDates[$k], $dates, $tableRows * 5, 5, $roomData);
      $columnIterator++;
      $k++;
    }
    $tableRows++;
}
$html .= '</table>';

echo $html;


问:
VB6 week of day function
I'm relatively new to VB6 and I've just been given an assignment where I have a date - for example '4/12/2016' - from this date, i'm trying to find out the day that it is. So let's say it's a wednesday. Now from this day, I'm trying to determine the dates for the week [sun(startdate) - sat(enddate)). How would I go about doing something like this?

EDIT: I have a pretty good idea about finding out the date for sunday and saturday, since I can simply do something along the lines...

```<code>dim dateStart,dateend as date

Ex of date given to me = '4/12/2016'

Dim dateDay as variant
dateDay = whatever I get here - i'm assuming that a date will return a number for whatever day it is ???? Not sure
Select Case dateDay
case 1 -Monday?
      dateStart=dateadd("d",-1,'4/12/2016)
      dateEnd = dateadd("d",6, '4/12/2016)
case 2 -Tuesday?
      datestart = dateadd("d",-2,'4/12/2016)
      dateend = dateadd("d",5,'4/12/2016)

End Select
</code>```

Basically do the SELECT statement for all cases. Am I on the right track?

答:
You can try below codes, The code will return name of the day.</p>

```<code>txtDateTime.Text = WeekdayName(Weekday(Now))
txtDateTime.Text = WeekdayName(Weekday(12 / 30 / 1995))
txtDateTime.Text = WeekdayName(Weekday(Date))
</code>```

Title: VB6 week of day function

Body:
I'm relatively new to VB6 and I've just been given an assignment where I have a date - for example '4/12/2016' - from this date, i'm trying to find out the day that it is. So let's say it's a wednesday. Now from this day, I'm trying to determine the dates for the week [sun(startdate) - sat(enddate)). How would I go about doing something like this?

EDIT: I have a pretty good idea about finding out the date for sunday and saturday, since I can simply do something along the lines...

dim dateStart,dateend as date

Ex of date given to me = '4/12/2016'

Dim dateDay as variant
dateDay = whatever I get here - i'm assuming that a date will return a number for whatever day it is ???? Not sure
Select Case dateDay
case 1 -Monday?
      dateStart=dateadd("d",-1,'4/12/2016)
      dateEnd = dateadd("d",6, '4/12/2016)
case 2 -Tuesday?
      datestart = dateadd("d",-2,'4/12/2016)
      dateend = dateadd("d",5,'4/12/2016)

End Select

Basically do the SELECT statement for all cases. Am I on the right track?

Body:
You can try below codes, The code will return name of the day.

txtDateTime.Text = WeekdayName(Weekday(Now))
txtDateTime.Text = WeekdayName(Weekday(12 / 30 / 1995))
txtDateTime.Text = WeekdayName(Weekday(Date))


问:
Is it possible to load new Javascript files with AJAX?
I'm building a new AJAX powered website with distinct sections.  Each section requires a new set of Javascript functions to run.  I'd rather not load every script at the start, as there might be quite a few.

Is there a way to load new scripts using AJAX and remove old ones (so as to make sure there are no compatibility issues with similar variable names or function signatures).

Thanks

Edit - JQuery is fine, it doesn't have to be old school Javascript

答:
Three things:

1) Yes, you can load new scripts. You don't even need AJAX in the XHR sense - simply include the script tag in your page dynamically. jQuery provides $.getScript() for things like this, or you can simply create a script element and append it to the head of your document. There are a gazillion examples if you google it.

2) Regarding removing the old (and conflicts, etc). Assuming you have control over these function names, just namespace them properly:

```<code>window.myapp = {};
window.myapp.mysection = {};
window.myapp.myothersection = {};
window.myapp.mysection.myfunction = function(){}
</code>```

Then you don't have to worry about conflicts.

3) Be careful about this. The overhead of loading all those scripts on-demand might be more than just compressing and loading the whole thing in one shot anyway.

Body:
Three things:

1) Yes, you can load new scripts. You don't even need AJAX in the XHR sense - simply include the script tag in your page dynamically. jQuery provides $.getScript() for things like this, or you can simply create a script element and append it to the head of your document. There are a gazillion examples if you google it.

2) Regarding removing the old (and conflicts, etc). Assuming you have control over these function names, just namespace them properly:

window.myapp = {};
window.myapp.mysection = {};
window.myapp.myothersection = {};
window.myapp.mysection.myfunction = function(){}

Then you don't have to worry about conflicts.

3) Be careful about this. The overhead of loading all those scripts on-demand might be more than just compressing and loading the whole thing in one shot anyway.


问:
Batch file explore directory for PostgreSQL connection
Once again, I am asking for your help to manage a small batch script.
As announced, in a previous post, I'm used to work on linux and automation tasks are more obvious to me but I have to work today under Microsoft environment.
Writting a Batch file is definitly not an easy things.
I am able with this script to be connected to a PostgreSQL database and load data via ogr2ogr. Until then, no problem.
Currently, the path of the folder is hard written in my code, but I would like to have the possibility of choosing the working directory through windows explorer.
Also, concerning this directory, I would like to have the possibility to process the subfolders at the same time.

Here, below the piece of my *.bat code:

```<code>TITLE Upload Shapefile Files to PostgreSQL
@echo off
cls
color 9
echo ******************************************************************************
echo *                   Upload Shapefile Files to PostgreSQL                     *
echo ******************************************************************************
set /P Host=Please enter your Server Host (default:localhost):
set /P Port=Please enter your PGSQL port (default:5432):
set /p Database=Please enter your PGSQL Database Name (default:postgres):
set /P Schema=Please enter your Edigeo Schema (default:public):
set /P User=Please enter your PGSQL username (default:postgres):
set /P Password=Please enter your PGSQL password (default:postgres):
For /F %%H In ("C:\Users\stephj\Desktop\SHP\*.shp") do ogr2ogr -overwrite -t_srs EPSG:2154 -s_srs EPSG:2154 -f "PostgreSQL" PG:"host=%Host% port=%Port% user=%User% password=%Password% dbname=%Database%" -lco schema=%Schema%
pause
</code>```

Thanks in advance for your time and your help.

答:
Ok, here is a way. This will just demonstrate by echoing the files, you need to amend it to follow your command structure:

Note!! This is a batch/PowerShell hybrid script. It needs to be saved with a batch file extension, preferably .cmd:

```<code>@echo off
set "pshell="(new-object -COM 'Shell.Application').BrowseForFolder(0,'Select Folder',0,0).self.path""

for /f "delims=" %%a in ('powershell %pshell%') do set "workdir=%%a"
for /r "%workdir%" %%i in (*.shp) do echo "%%~i"
</code>```

Body:
Once again, I am asking for your help to manage a small batch script.
As announced, in a previous post, I'm used to work on linux and automation tasks are more obvious to me but I have to work today under Microsoft environment.
Writting a Batch file is definitly not an easy things.
I am able with this script to be connected to a PostgreSQL database and load data via ogr2ogr. Until then, no problem.
Currently, the path of the folder is hard written in my code, but I would like to have the possibility of choosing the working directory through windows explorer.
Also, concerning this directory, I would like to have the possibility to process the subfolders at the same time.

Here, below the piece of my *.bat code:

TITLE Upload Shapefile Files to PostgreSQL
@echo off
cls
color 9
echo ******************************************************************************
echo *                   Upload Shapefile Files to PostgreSQL                     *
echo ******************************************************************************
set /P Host=Please enter your Server Host (default:localhost):
set /P Port=Please enter your PGSQL port (default:5432):
set /p Database=Please enter your PGSQL Database Name (default:postgres):
set /P Schema=Please enter your Edigeo Schema (default:public):
set /P User=Please enter your PGSQL username (default:postgres):
set /P Password=Please enter your PGSQL password (default:postgres):
For /F %%H In ("C:\Users\stephj\Desktop\SHP\*.shp") do ogr2ogr -overwrite -t_srs EPSG:2154 -s_srs EPSG:2154 -f "PostgreSQL" PG:"host=%Host% port=%Port% user=%User% password=%Password% dbname=%Database%" -lco schema=%Schema%
pause

Thanks in advance for your time and your help.

Body:
Ok, here is a way. This will just demonstrate by echoing the files, you need to amend it to follow your command structure:

Note!! This is a batch/PowerShell hybrid script. It needs to be saved with a batch file extension, preferably .cmd:

@echo off
set "pshell="(new-object -COM 'Shell.Application').BrowseForFolder(0,'Select Folder',0,0).self.path""

for /f "delims=" %%a in ('powershell %pshell%') do set "workdir=%%a"
for /r "%workdir%" %%i in (*.shp) do echo "%%~i"


问:
CSS how can I get an inline display with a working ::first-line pseudo-element
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>

<br><br>
<b>Display is out now that first-line works because of block (or inline-block) + margin left out too:</b>
<br><br>

<span class="heading">header: </span>
<span class="content block">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></code>```

答:
You didn't really describe what should be aligned how, but by combining float:left; and  a negative margin-top setting for that first-word span (also with values different from what I used below) you should be able to get what you want:

.heading {
  float:left;
  margin: -10px 0 0 0;
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span></code>```

Body:
This looks very simple, but I couldn't get it working, either with combinations of float, inline-block and so on. I am trying to get more space on the first line so that the second one doesn't "collide" with the header. I know that ::first-line doesn't work on inline elements. I want to keep this layout (the layout is what's important, not the inline display, so whatever works is OK). The solution should have a wide browser support.

My design must stay responsive, so the text shouldn't be cut in different parts. I could do it in javascript and keep it responsive by running a script on resize, but I really would like to avoid this solution.

EDIT: @TemaniAfif's comment about setting inline-block to the header does the trick for my special case, but for curiosity and future readers, it doesn't directly answer for the pseudo-element. For example if someone wanter to capitalize or change color, I feel the question is still valid, so I'm editing the snippet.

.heading {
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}
.content::first-line {
  line-height: 2;
  text-transform: uppercase;
  color: red;
}
.block {
  display: block;
}

Display is fine, first-line doesn't work because of inline + margin left works fine:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Display is out now that first-line works because of block (or inline-block) + margin left out too:

header:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
You didn't really describe what should be aligned how, but by combining float:left; and  a negative margin-top setting for that first-word span (also with values different from what I used below) you should be able to get what you want:

.heading {
  float:left;
  margin: -10px 0 0 0;
  padding: 5px;
  background-color: blue;
  color: white;
}
.content {
  margin-left: 5px;
}

<b>Display is fine, first-line doesn't work because of inline + margin left works fine:</b>
<br><br>

<span class="heading">header: </span>
<span class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>


问:
The entity type <type> is not part of the model for the current context
I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

But when I try to access or modify the entity I run into the following:

System.InvalidOperationException: The entity type Estate is not part
  of the model for the current context.

It happens when I am trying to access it from my repository:

```<code>public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}
</code>```

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

My Entity is:

```<code>public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
}
</code>```

My context is as so:

```<code>public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

}
</code>```

Is there any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.

答: For me it was caused because I renamed the entity class.When  I rolled it back it was Ok. </p>

Body:
I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

But when I try to access or modify the entity I run into the following:

System.InvalidOperationException: The entity type Estate is not part
  of the model for the current context.

It happens when I am trying to access it from my repository:

public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

My Entity is:

public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
}

My context is as so:

public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

}

Is there any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.


问:
"Extra argument" error when using CombineLatest from the Combine framework
The issue can be seen in the following playground. There are four published values that will be updated asynchronously (an image and three strings). When all four of them have been initialized or subsequently changed then the UI will need to be updated. When I try to capture this data flow using CombineLatest4 the compiler immediately objects to the fourth argument with the message Extra argument in call. (Note: the following code doesn't actually do anything since it only has a publisher, but it is sufficient to produce the error message in Playground).

```<code>import Combine
import UIKit

struct CustomerUpdates
{
    @Published var photo: UIImage!
    @Published var firstName: String!
    @Published var lastName: String!
    @Published var id: String!

    typealias customerTuple =
        (   photo: UIImage,
            firstName: String,
            lastName: String,
            id: String )
    var validatedCustomer: AnyPublisher< customerTuple, Never >
    {
        return Publishers.CombineLatest4( $photo,
                                          $firstName,
                                          $lastName,
                                          $id )
        {
            photo, firstName, lastName, id in
            if      photo == nil
                ||  firstName == nil
                ||  lastName == nil
                ||  id == nil
            {
                return nil
            }
            return ( photo!, firstName!, lastName!, id! )
        }
        .compactMap
        .return( on: RunLoop.main )
    }
}
</code>```

My question is, why does the compiler flag the fourth argument (the "id")? Apple's documentation for the CombineLatest4 generic struct says:

A publisher that receives and combines the latest elements from four
  publishers.

答:
The CombineLatest type (and its larger variants including CombineLatest4) don't take a transformation closure. But Publisher has combineLatest operators that do. So you can say this if you want:

```<code>    return $photo.combineLatest($firstName, $lastName, $id) {
        guard
            let photo = $0,
            let firstName = $1,
            let lastName = $2,
            let id = $3
            else { return nil }
        return ($0, $1, $2, $3)
    }
    .compactMap { $0 }
    .receive(on: RunLoop.main)
</code>```

Body:
The issue can be seen in the following playground. There are four published values that will be updated asynchronously (an image and three strings). When all four of them have been initialized or subsequently changed then the UI will need to be updated. When I try to capture this data flow using CombineLatest4 the compiler immediately objects to the fourth argument with the message Extra argument in call. (Note: the following code doesn't actually do anything since it only has a publisher, but it is sufficient to produce the error message in Playground).

import Combine
import UIKit

struct CustomerUpdates
{
    @Published var photo: UIImage!
    @Published var firstName: String!
    @Published var lastName: String!
    @Published var id: String!

    typealias customerTuple =
        (   photo: UIImage,
            firstName: String,
            lastName: String,
            id: String )
    var validatedCustomer: AnyPublisher< customerTuple, Never >
    {
        return Publishers.CombineLatest4( $photo,
                                          $firstName,
                                          $lastName,
                                          $id )
        {
            photo, firstName, lastName, id in
            if      photo == nil
                ||  firstName == nil
                ||  lastName == nil
                ||  id == nil
            {
                return nil
            }
            return ( photo!, firstName!, lastName!, id! )
        }
        .compactMap
        .return( on: RunLoop.main )
    }
}

My question is, why does the compiler flag the fourth argument (the "id")? Apple's documentation for the CombineLatest4 generic struct says:

A publisher that receives and combines the latest elements from four
  publishers.

Body:
The CombineLatest type (and its larger variants including CombineLatest4) don't take a transformation closure. But Publisher has combineLatest operators that do. So you can say this if you want:

    return $photo.combineLatest($firstName, $lastName, $id) {
        guard
            let photo = $0,
            let firstName = $1,
            let lastName = $2,
            let id = $3
            else { return nil }
        return ($0, $1, $2, $3)
    }
    .compactMap { $0 }
    .receive(on: RunLoop.main)


问:
Difference between Azure SQL Virtual Machine version and SQL Server Database version
Hi sorry if this question is confusing I have just recently upgraded one of the SQL datbases to Version 15 (which is SQL 2019) inside my SQL Virtual Machine. It is a different version from my Azure SQL Virtual Machine which is SQL server version 2016. I am wondering what the pros and cons of this are and if I should be worried at all about any problems.
Upgrade 2019 SQL DataBase
Azure SQL VM

edit: I updated the database to 2019 and it is not showing on sql server configuration manager SQL Services. I can see the database protocols (TCP), I can see the service through Windows Services, but it just does not show on SQL Services.
I need that for moving my master.mdf file. I am wondering what the solutions to this would be is downgrading the version from 2019 back to 2016 a solution?

答: I would suggest you upgrade your SQL Server in your VM to 2019, or in case it does not work, because of an incorrect upgrade to 2019 of your database, you can get your original 2016 version of your database, and run the Data Experimentation Assistant to assess the upgrade to 2019 and see if there are any issues with the upgrade. </p>


问:
lightSlider is not a function
In my website, I use lightSlider for product gallery. I loaded jquery and js for lightslider, but still, show error

"Uncaught TypeError: $(...).lightSlider is not a function"
  here is my head

```<code> <link  href="/css/bootstrap.css" rel="stylesheet">
 <link href="/plugins/revolution/css/settings.css" rel="stylesheet" type="text/css">
 <link href="/plugins/revolution/css/layers.css" rel="stylesheet" type="text/css">
 <link href="/plugins/revolution/css/navigation.css" rel="stylesheet" type="text/css">
 <link href="/css/style.css" rel="stylesheet">
 <link href="/css/responsive.css" rel="stylesheet">
 <link href="/css/custom.css" rel="stylesheet" type="text/css">
 <link id="color_scheme" href="/css/home3.css" rel="stylesheet">
 <link href="/js/lightslider/lightslider.css" rel="stylesheet">
 <link href="/js/owl-carousel/owl.carousel.css" rel="stylesheet">
 <link href="/css/lib.css" rel="stylesheet">
 <link rel="stylesheet" type="text/css" href="/js/jquery-ui/jquery-ui.css" media="all" />
<script type="text/javascript" src="/js/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="/js/jquery-ui/jquery-ui.js"></script>
<link href="/js/lightslider/lightslider.js" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/css/bootstrap-datetimepicker.min.css" media="all" />
</code>```

and after open body tag i add this script:

```<code><script>

    $("#thumb-slider-vertical .owl2-item").each(function() {
        $(this).find("[data-index='0']").addClass('active');
    });

    $('.product-options li.radio').click(function(){
        $(this).addClass(function() {
            if($(this).hasClass("active")) return "";
            return "active";
        });

        $(this).siblings("li").removeClass("active");
        $(this).parent().find('.selected-option').html('<span class="label label-success">'+ $(this).find('img').data('original-title') +'</span>');
    });

    var _isMobile = {
        iOS: function() {
            return navigator.userAgent.match(/iPhone/i);
        },
        any: function() {
            return (_isMobile.iOS());
        }
    };

    $(".thumb-vertical-outer .next-thumb").click(function () {
        $( ".thumb-vertical-outer .lSNext" ).trigger( "click" );
    });

    $(".thumb-vertical-outer .prev-thumb").click(function () {
        $( ".thumb-vertical-outer .lSPrev" ).trigger( "click" );
    });

    $(".thumb-vertical").lightSlider({
        gallery:true,
        item: 3,
        thumbItem:9,
        autoWidth: false,
        vertical:true,
        slideMargin: 15,
        verticalHeight:340,
        pager: false,
        controls: true,
        prevHtml: '<i class="fa fa-angle-up"></i>',
        nextHtml: '<i class="fa fa-angle-down"></i>',
        responsive: [
            {
                breakpoint: 1199,
                settings: {
                    verticalHeight: 330,
                    item: 3,
                }
            },
            {
                breakpoint: 1024,
                settings: {
                    verticalHeight: 235,
                    item: 2,
                    slideMargin: 5,
                }
            },
            {
                breakpoint: 768,
                settings: {
                    verticalHeight: 340,
                    item: 3,
                }
            }
            ,
            {
                breakpoint: 480,
                settings: {
                    verticalHeight: 100,
                    item: 1,
                }
            }

        ]

    });
 </script>
</code>```

in demo file for lightslider just load in head part js, jquery and CSS and everything is ok, but here is not working and I do not see why ... if someone can resolve this problem please help

答:
I was using WordPress, I got this same problem,
I had called the js in footer.php and in wp_enqueue_script in function.php also

And I had lightslider code in footer and custom.js both

I removed all the js from footer and used only wp_enqueue_script function and keep the lightslider activation code in custom.js

Title: lightSlider is not a function

Body:
In my website, I use lightSlider for product gallery. I loaded jquery and js for lightslider, but still, show error

"Uncaught TypeError: $(...).lightSlider is not a function"
  here is my head

 <link  href="/css/bootstrap.css" rel="stylesheet">
 <link href="/plugins/revolution/css/settings.css" rel="stylesheet" type="text/css">
 <link href="/plugins/revolution/css/layers.css" rel="stylesheet" type="text/css">
 <link href="/plugins/revolution/css/navigation.css" rel="stylesheet" type="text/css">
 <link href="/css/style.css" rel="stylesheet">
 <link href="/css/responsive.css" rel="stylesheet">
 <link href="/css/custom.css" rel="stylesheet" type="text/css">
 <link id="color_scheme" href="/css/home3.css" rel="stylesheet">
 <link href="/js/lightslider/lightslider.css" rel="stylesheet">
 <link href="/js/owl-carousel/owl.carousel.css" rel="stylesheet">
 <link href="/css/lib.css" rel="stylesheet">
 <link rel="stylesheet" type="text/css" href="/js/jquery-ui/jquery-ui.css" media="all" />

<link href="/js/lightslider/lightslider.js" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/css/bootstrap-datetimepicker.min.css" media="all" />

and after open body tag i add this script:

in demo file for lightslider just load in head part js, jquery and CSS and everything is ok, but here is not working and I do not see why ... if someone can resolve this problem please help


问:
how to mock namedJdbcTemplate to get two different result which are being used two times in one function
in my class namedJdbcTemplate is being used twice in single function to get different result. but mocking it only gives one result. how to prepare test case for it ?

my class:

```<code>public void Getsomething(){

Result1 = namedJdbcTemplate.queryForObject(
            "SomeSQLString1", params, String.class);

Result2 = namedJdbcTemplate.queryForObject(
    "SomeSQLString2", params, String.class);
</code>```

Test Class:

```<code>@Test
public void getNewRecordsTest2(){

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
            Mockito.any(String.class))).thenReturn(Result1);

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result2);

    /**calling actual*/
    SomeClass.Getsomething();

}
</code>```

i tried to call it twice but it will hold only one result.

mockito.doreturn fails to give any result and calls real method inside function, provide null result

```<code>    @Test
public void getNewRecordsTest2(){

Mockito.doReturn(Result1).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

Mockito.doReturn(Result2).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

    /**calling actual*/
    SomeClass.Getsomething();

}
</code>```

答:
i got the answer :

```<code>Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result1, Result2);
</code>```

this will give two different result Result1 and Result2 with a single mock

Body:
in my class namedJdbcTemplate is being used twice in single function to get different result. but mocking it only gives one result. how to prepare test case for it ?

my class:

public void Getsomething(){

Result1 = namedJdbcTemplate.queryForObject(
            "SomeSQLString1", params, String.class);

Result2 = namedJdbcTemplate.queryForObject(
    "SomeSQLString2", params, String.class);

Test Class:

@Test
public void getNewRecordsTest2(){

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
            Mockito.any(String.class))).thenReturn(Result1);

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result2);

    /**calling actual*/
    SomeClass.Getsomething();

}

i tried to call it twice but it will hold only one result.

mockito.doreturn fails to give any result and calls real method inside function, provide null result

    @Test
public void getNewRecordsTest2(){

Mockito.doReturn(Result1).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

Mockito.doReturn(Result2).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

    /**calling actual*/
    SomeClass.Getsomething();

}

Body:
i got the answer :

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result1, Result2);

this will give two different result Result1 and Result2 with a single mock


问:
How can I convert VectorSource to RasterSource
In OpenLayers ol.source.ImageVector has been deprecated since v5.

Docs recommended to use an ol.layer.Vector with renderMode: 'image' instead.

But what if I want to get an another raster source at output? (Not a layer)

Is there any workaround?

答:
The output from ol.source.Raster is always a raster source.  The input can be either a source or layer.

OpenLayers 4:

https://codepen.io/mike-000/pen/KKpgrmx

```<code>new ol.source.Raster({
  sources: [
    new ol.source.ImageVector({
      source: new ol.source.Vector()
    })
  ]
})
</code>```

OpenLayers 5:

```<code>new ol.source.Raster({
  sources: [
    new ol.layer.Vector({
      source: new ol.source.Vector()
    }),
    renderMode: 'image'
  ]
})
</code>```

OpenLayers 6:

https://codepen.io/mike-000/pen/BaNLvyq

```<code>new ol.source.Raster({
  sources: [
    new ol.layer.VectorImage({
      source: new ol.source.Vector()
    })
  ]
})
</code>```

Body:
The output from ol.source.Raster is always a raster source.  The input can be either a source or layer.

OpenLayers 4:

https://codepen.io/mike-000/pen/KKpgrmx

new ol.source.Raster({
  sources: [
    new ol.source.ImageVector({
      source: new ol.source.Vector()
    })
  ]
})

OpenLayers 5:

new ol.source.Raster({
  sources: [
    new ol.layer.Vector({
      source: new ol.source.Vector()
    }),
    renderMode: 'image'
  ]
})

OpenLayers 6:

https://codepen.io/mike-000/pen/BaNLvyq

new ol.source.Raster({
  sources: [
    new ol.layer.VectorImage({
      source: new ol.source.Vector()
    })
  ]
})


答:
Note that dayofweek is a property and not a method.

That means you should use it without the parens:

```<code>print(filtered.index.dayofweek)
</code>```

You can see that that's what the error message is telling you, 'Int64Index' object being the result of the property and it's complaining that you're trying to "call" it as a function, but it is not callable.

Title: Pandas cannot call function on a datetimeindex

Body:
I'm trying to call a dayofweek() on my datetimeindex in a dataframe. Here is my code:

v = [
[
    1582041084.72,
    "1989121.03"
],
[
    1582041684.72,
    "1989121.03"
]

df = pd.DataFrame.from_records(v, columns=['time', 'points'])
df = df.astype({'points': 'float'})
df['time'] = pd.to_datetime(df['time'], unit='s')
df = df.set_index('time')
filtered = df.between_time('10:00', '14:30')

print(filtered.index.dayofweek())

This returns an error saying 'Int64Index' object is not callable.

Here's the output of df.index:

DatetimeIndex(['2020-02-19 10:01:24.720000029',
               '2020-02-19 10:11:24.720000029'],
              dtype='datetime64[ns]', name='time', freq=None)

Body:
Note that dayofweek is a property and not a method.

That means you should use it without the parens:

print(filtered.index.dayofweek)

You can see that that's what the error message is telling you, 'Int64Index' object being the result of the property and it's complaining that you're trying to "call" it as a function, but it is not callable.


问:
numpy broadcasting with 3d arrays
Is it possible to apply numpy broadcasting (with 1D arrays),

```<code>x=np.arange(3)[:,np.newaxis]
y=np.arange(3)
x+y=
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])
</code>```

to 3d matricies similar to the one below, such that each element in a[i] is treated as a 1D vector like in the example above?

```<code>a=np.zeros((2,2,2))
a[0]=1
b=a
result=a+b
</code>```

resulting in

```<code>result[0,0]=array([[2, 2],
                   [2, 2]])

result[0,1]=array([[1, 1],
                   [1, 1]])

result[1,0]=array([[1, 1],
                   [1, 1]])

result[1,1]=array([[0, 0],
                   [0, 0]])
</code>```

答:
Since a and b are of same shape, say (2,2,2), a+b will indeed work.
The way broadcasting works is that it matches the dimensions of the operands in reverse order, starting from the last dimension going up (e.g. considering columns before rows in a two-dimensional case). If the dimensions match then the next dimension is considered.

In case the dimensions don't match AND if one of the dimensions is 1 then that operand's dimension is repeated to match the other operand (e.g. if a.shape = (2,1,2) and b.shape = (2,2,2) then the values at the 1st dimension of a are repeated to make the shape (2,2,2))

Title: numpy broadcasting with 3d arrays

Body:
Is it possible to apply numpy broadcasting (with 1D arrays),

x=np.arange(3)[:,np.newaxis]
y=np.arange(3)
x+y=
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

to 3d matricies similar to the one below, such that each element in a[i] is treated as a 1D vector like in the example above?

a=np.zeros((2,2,2))
a[0]=1
b=a
result=a+b

resulting in

result[0,0]=array([[2, 2],
                   [2, 2]])

result[0,1]=array([[1, 1],
                   [1, 1]])

result[1,0]=array([[1, 1],
                   [1, 1]])

result[1,1]=array([[0, 0],
                   [0, 0]])


问:
Trying to install perl's Catalyst framework on debian 6. - Can't use an undefined value as a HASH
```<code>[14:27: /mnt/mydocuments/git_working_dir/cat_example$] catalyst.pl hello_world
Couldn't load class (Catalyst::Exception::Basic) because: Can't use an undefined value as a HASH reference at /usr/lib/perl5/MooseX/Role/WithOverloading/Meta/Role/Application.pm line 45.
Compilation failed in require at /usr/local/lib/perl/5.10.1/Class/MOP.pm line 117.
 at /usr/local/lib/perl/5.10.1/Class/MOP.pm line 123
    Class::MOP::__ANON__('Can\'t use an undefined value as a HASH reference at /usr/lib...') called at /usr/local/share/perl/5.10.1/Try/Tiny.pm line 100
    Try::Tiny::try('CODE(0x29021c8)', 'Try::Tiny::Catch=REF(0x28fca88)') called at /usr/local/lib/perl/5.10.1/Class/MOP.pm line 128
    Class::MOP::load_first_existing_class('Catalyst::Exception::Basic') called at /usr/local/lib/perl/5.10.1/Class/MOP.pm line 140
    Class::MOP::load_class('Catalyst::Exception::Basic', undef) called at /usr/local/lib/perl/5.10.1/Moose/Util.pm line 126
    Moose::Util::_apply_all_roles('Moose::Meta::Class=HASH(0x2b63fe0)', undef, 'Catalyst::Exception::Basic') called at /usr/local/lib/perl/5.10.1/Moose/Util.pm line 93
    Moose::Util::apply_all_roles('Moose::Meta::Class=HASH(0x2b63fe0)', 'Catalyst::Exception::Basic') called at /usr/local/lib/perl/5.10.1/Moose.pm line 60
    Moose::with('Moose::Meta::Class=HASH(0x2b63fe0)', 'Catalyst::Exception::Basic') called at /usr/local/lib/perl/5.10.1/Moose/Exporter.pm line 356
    Moose::with('Catalyst::Exception::Basic') called at /usr/share/perl5/Catalyst/Exception.pm line 50
    require Catalyst/Exception.pm called at /usr/share/perl5/Catalyst/Utils.pm line 4
    Catalyst::Utils::BEGIN() called at /usr/share/perl5/Catalyst/Exception.pm line 0
    eval {...} called at /usr/share/perl5/Catalyst/Exception.pm line 0
    require Catalyst/Utils.pm called at /usr/share/perl5/Catalyst/Helper.pm line 12
    Catalyst::Helper::BEGIN() called at /usr/share/perl5/Catalyst/Exception.pm line 0
    eval {...} called at /usr/share/perl5/Catalyst/Exception.pm line 0
    require Catalyst/Helper.pm called at /usr/bin/catalyst.pl line 26
    main::BEGIN() called at /usr/share/perl5/Catalyst/Exception.pm line 0
    eval {...} called at /usr/share/perl5/Catalyst/Exception.pm line 0
Compilation failed in require at /usr/share/perl5/Catalyst/Utils.pm line 4.
BEGIN failed--compilation aborted at /usr/share/perl5/Catalyst/Utils.pm line 4.
Compilation failed in require at /usr/share/perl5/Catalyst/Helper.pm line 12.
BEGIN failed--compilation aborted at /usr/share/perl5/Catalyst/Helper.pm line 12.
Compilation failed in require at /usr/bin/catalyst.pl line 26.
BEGIN failed--compilation aborted at /usr/bin/catalyst.pl line 26.
[14:27: /mnt/mydocuments/git_working_dir/cat_example$]
</code>```

答:
as root</p>

```<code>cpan Catalyst::Runtime
cpan Package::Stash
</code>```

Body:
as root

cpan Catalyst::Runtime
cpan Package::Stash


问:
Visual Basic connect database with ODBC setting with register
I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.

Thank you

```<code>Private Sub DsnLookup()

    Dim dsnNames As New List(Of String)
    Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")

    If reg IsNot Nothing Then
        reg = reg.OpenSubKey("ODBC")
        If reg IsNot Nothing Then
            reg = reg.OpenSubKey("ODBC.INI")
            If reg IsNot Nothing Then
                For Each dsn As String In reg.GetSubKeyNames
                    dsnNames.Add(dsn)
                Next
            End If
        End If
    End If

    For Each Name As String In dsnNames
        ComboBox1.Items.Add(Name)
    Next Name

End Sub

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DsnLookup()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
    & "User Id=root;Password=' odbc PWD"
</code>```

答:
You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password.  Either include a master password in your connectionstring (securely of course) or look into other authentication options.

This is how to get the Database and Server info from the registry.  Keeping your code the same, but replacing the Button1.Click event and adding an additional function:

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ComboBox1.SelectedIndex >= 0 Then  'Make sure something from dropdown selected

        Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))

    End If
End Sub

Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String

    Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
    reg = reg.OpenSubKey("ODBC")
    reg = reg.OpenSubKey("ODBC.INI")
    reg = reg.OpenSubKey(ODBCName)
    Return reg.GetValue(ValueName)

End Function
</code>```

Body:
I have the code written to connect to the ODBC registry.
The database name is written to the combobox.
I need to transfer my ip address and password from ODBC.ini to the connect string after selecting the database from the combobox.
This is a connection to MYSQL.

Thank you

Private Sub DsnLookup()

    Dim dsnNames As New List(Of String)
    Dim reg As Microsoft.Win32.RegistryKey = Registry.CurrentUser.OpenSubKey("Software")

    If reg IsNot Nothing Then
        reg = reg.OpenSubKey("ODBC")
        If reg IsNot Nothing Then
            reg = reg.OpenSubKey("ODBC.INI")
            If reg IsNot Nothing Then
                For Each dsn As String In reg.GetSubKeyNames
                    dsnNames.Add(dsn)
                Next
            End If
        End If
    End If

    For Each Name As String In dsnNames
        ComboBox1.Items.Add(Name)
    Next Name

End Sub

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DsnLookup()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connString As String = "Database='combobox data;Data Source='ip adres odbc;" _
    & "User Id=root;Password=' odbc PWD"

Body:
You can get the Server Name (or IP) and Database name from the ODBC.INI but it doesn't store the password.  Either include a master password in your connectionstring (securely of course) or look into other authentication options.

This is how to get the Database and Server info from the registry.  Keeping your code the same, but replacing the Button1.Click event and adding an additional function:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ComboBox1.SelectedIndex >= 0 Then  'Make sure something from dropdown selected

        Dim connString As String = String.Format("Database='{0}';Data Source='{1}';User Id=root;", GetODBCValue(ComboBox1.SelectedItem, "Database"), GetODBCValue(ComboBox1.SelectedItem, "Server"))

    End If
End Sub

Private Function GetODBCValue(ByVal ODBCName As String, ByVal ValueName As String) As String

    Dim reg As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software")
    reg = reg.OpenSubKey("ODBC")
    reg = reg.OpenSubKey("ODBC.INI")
    reg = reg.OpenSubKey(ODBCName)
    Return reg.GetValue(ValueName)

End Function


问:
Ingress controller NodePort not reachable from outside
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090
</code>```

kubectl get svc myservice gives me:

```<code>NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m
</code>```

kubectl get ingress test-ingress gives me

```<code>NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m
</code>```

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?

答:
You should be able to curl with a host header set to www.my.service.com</p>

```<code>curl --verbose --header 'Host: www.my.service.com' http://nodeip:nodeport/
</code>```

Body:
I have a cluster of 3 vm on which I install kubernetes and deployed some pods and services that I would like to be accessible from outside (my local pc for exemple)

I followed this tutorial https://kubernetes.github.io/ingress-nginx/deploy/#bare-metal to install my ingress controller.
I have created a service of type NodePort.
I have created a ingress that looks like this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  annotations:
      kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: my.service.com
    http:
      paths:
      - path: /
        backend:
          serviceName: myservice
          servicePort: 9090

kubectl get svc myservice gives me:

NAME        TYPE       CLUSTER-IP        EXTERNAL-IP   PORT(S)          AGE
myservice   NodePort   xxx.xxx.xxx.xxx   <none>        9090:31220/TCP   47m

kubectl get ingress test-ingress gives me

NAME            HOSTS            ADDRESS          PORTS   AGE
test-ingress    my.service.com   xx.xxx.xxx.xxx   80      49m

On my local computer I have added to /etc/hosts I have mapped the ip address of the ingress to the name my.service.com
When I try to ping my.service.com or directly the ip I go request timeout 100% packet loss.
I tried to reach my service visual interface with the web browser and it does not work either.

How can I investigate further why I can't access to my service from outside the cluster ?

Body:
You should be able to curl with a host header set to www.my.service.com

curl --verbose --header 'Host: www.my.service.com' http://nodeip:nodeport/


问:
Why my state does not change on click event with setState
I'm learning React, and actually don't understand why my state does not change immediately when I press a button, with a click event. I mean, I created a state "test: false", but when I click on my button, I just want to change the state, so I used setState. But the console still shows me the "false" when I click for the first time.

Here's a Codesandbox to illustrate my example.

```<code>import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
    this.display.bind(this);
  }
  display() {
    this.setState({
      test: true
    });
    console.log(this.state.test)
  }
  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
      </div>
    );
  }
}

export default App;
</code>```

I also want to show  "Hello" if state is true and "Goodbye" if the state is false.
Can anyone help me, please?

答:
I have checked your code and found you are doing mistake there.

As setState() is async. One easy way to handle that is to give it a callback.
To print the state just after the setState(), you need to use the code as follows:

```<code>display() {
 this.setState({
  test: true
 }, console.log(this.state.test));
}
</code>```

and about your updated query, you need to use ternary operator as follows:

```<code>  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
        {(this.state.test) ? <p>Hello</p> : <p>Bye</p>}

      </div>
    );
  }
</code>```

Body:
I'm learning React, and actually don't understand why my state does not change immediately when I press a button, with a click event. I mean, I created a state "test: false", but when I click on my button, I just want to change the state, so I used setState. But the console still shows me the "false" when I click for the first time.

Here's a Codesandbox to illustrate my example.

import React from "react";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
    this.display.bind(this);
  }
  display() {
    this.setState({
      test: true
    });
    console.log(this.state.test)
  }
  render() {
    return (

        <button onClick={() => this.display()}>Click me!</button>

    );
  }
}

export default App;

I also want to show  "Hello" if state is true and "Goodbye" if the state is false.
Can anyone help me, please?

Body:
I have checked your code and found you are doing mistake there.

As setState() is async. One easy way to handle that is to give it a callback.
To print the state just after the setState(), you need to use the code as follows:

display() {
 this.setState({
  test: true
 }, console.log(this.state.test));
}

and about your updated query, you need to use ternary operator as follows:

  render() {
    return (
      <div className="App">
        <button onClick={() => this.display()}>Click me!</button>
        {(this.state.test) ? <p>Hello</p> : <p>Bye</p>}

      </div>
    );
  }


问:
fpdf Tables: Cell Splitting/Merging
I am trying to generate a PDF which contains a table with split/merged cells looking like so:

Cell | Cell       | Cell

Cell | C1 | C2 | Cell

       | C1 | C2 | Cell

I am using fpdf and was referred to the multicell table script, which I have used previously in similar pdfs. I looked at the code and can't think of a way to make the cells split or merge according to what I need. Does anyone know how to do this?

答:
You can use EasyTable
https://github.com/fpdf-easytable/fpdf-easytable

A simple example:

```<code>$table=new easyTable($pdf, 3, 'width:100;');

 $table->easyCell('Text 1', 'rowspan:2; valign:T');
 $table->easyCell('Text 2', 'bgcolor:#b3ccff; rowspan:2');
 $table->easyCell('Text 3');
 $table->printRow();

 $table->rowStyle('min-height:20');
 $table->easyCell('Text 4', 'bgcolor:#3377ff; rowspan:2');
 $table->printRow();

 $table->easyCell('Text 5', 'bgcolor:#99bbff;colspan:2');
 $table->printRow();

 $table->endTable();
</code>```

OwnerDisplayName: lmg

Title: fpdf Tables: Cell Splitting/Merging

Body:
You can use EasyTable
https://github.com/fpdf-easytable/fpdf-easytable

A simple example:

$table=new easyTable($pdf, 3, 'width:100;');

 $table->easyCell('Text 1', 'rowspan:2; valign:T');
 $table->easyCell('Text 2', 'bgcolor:#b3ccff; rowspan:2');
 $table->easyCell('Text 3');
 $table->printRow();

 $table->rowStyle('min-height:20');
 $table->easyCell('Text 4', 'bgcolor:#3377ff; rowspan:2');
 $table->printRow();

 $table->easyCell('Text 5', 'bgcolor:#99bbff;colspan:2');
 $table->printRow();

 $table->endTable();


问:
Cannot read property 'disable' of undefined: this.ngControl.control is undefined in Ivy
Just as this issue states, if you try to access an ngControl.control with a Directive:

```<code>export class DisabledDirective {
  @Input()
  set opDisabled(condition: boolean) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor(private ngControl: NgControl) {}
}
</code>```

You will reach an error upon first rendering:

```<code>core.js:5828 ERROR TypeError: Cannot read property 'disable' of undefined
</code>```

答:
The solution in the given link is quite hacky and unreliable.

Until they fix the issue, simply guard the expression with if-s for the first rendering:

```<code>export class DisabledDirective {
  @Input()
  set opDisabled(condition: boolean) {
    const action = condition ? 'disable' : 'enable';
    if(this.ngControl?.control){
       this.ngControl.control[action]();
    }
  }

  constructor(private ngControl: NgControl) {}
}
</code>```

ps.: notice the new safe/elvis operator which you can use in Angular 9 in the TS code too :)

Body:
Just as this issue states, if you try to access an ngControl.control with a Directive:

export class DisabledDirective {
  @Input()
  set opDisabled(condition: boolean) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor(private ngControl: NgControl) {}
}

You will reach an error upon first rendering:

core.js:5828 ERROR TypeError: Cannot read property 'disable' of undefined

Body:
The solution in the given link is quite hacky and unreliable.

Until they fix the issue, simply guard the expression with if-s for the first rendering:

export class DisabledDirective {
  @Input()
  set opDisabled(condition: boolean) {
    const action = condition ? 'disable' : 'enable';
    if(this.ngControl?.control){
       this.ngControl.control[action]();
    }
  }

  constructor(private ngControl: NgControl) {}
}

ps.: notice the new safe/elvis operator which you can use in Angular 9 in the TS code too :)


问:
bash: Unable to run build commands via bash scripts
I am trying to run 'make' command from my bash script to build the code.

I can see that all parameters got assigned and able to display the command that i am trying to run. I could not see any issue with the command. But the issue is when it tries to run the command via bash script it fails.

My command is :- ./build_script LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm"

Script Snippet of parsing all the arguments and constructing make command:-

```<code>makeargs=""
for build_flag do
   if [[ "$build_flag " = "PROJECTS="* ]]; then
          apps =`echo $build_flag |sed "s/PROJECTS=//" `
          makeargs="$makeargs PROJECTS=\"$apps \""
   else
        makeargs="$makeargs $build_flag"
    fi
done
echo "make DCOV=1 $makeargs $maketest"
make DCOV=1 $makeargs $maketest
</code>```

When i run the script, I can see the build command has constructed properly.

Output :-

```<code>make DCOV=1 LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm" run_all
GNUmakefile:16: warning: overriding commands for target `/'
GNUmakefile:19: warning: ignoring old commands for target `/'
make: *** No rule to make target `bfm"'.  Stop.
</code>```

I try to print PROJECTS variable in my 'GNUmakefile' present in build_main folder. I can see the output : PROJECTS is "bfm . It is not taking whole "cuda bfm" as a whole string.

Note:- When i try to run the same build command :- make DCOV=1 LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm" run_all explicitly it works fine.

Seems like issue with Interpreting variables with makefile.

Any solution for this ? Please help.
Thanks!

答:
Change makeargs string to array before passing it as an arguments group.

```<code>eval makeargs_array=( $makeargs )
make UVC=1 "${makeargs_array[@]}" $maketest
</code>```

Without converting to array, if you enable debug, it shows last line interpretation as

```<code>make DCOV=1 LIC=1 DOCUMNETS=1 'PROJECTS="cuda' bfm '"'
</code>```

Which is clearly ignoring double-quote and considering space as separator.
Even double-quote is getting passed as a separate argument in this case.

Explanation:

Word-splitting
It says,

The shell scans the results of parameter expansion, command
  substitution, and arithmetic expansion that did not occur within
  double quotes for word splitting.

If we use "$makeargs" i.e. surrounded by double-quote, it is not considered by word-splitting and results in LIC=1 DOCUMNETS=1 "PROJECTS=cuda bfm"

But again its a complete string, while requirement is to split the string to use as arguments.

So now using $makeargs.

Word-splitting gets in action as per the default IFS (space, tab, newline), we get result as LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm "

Double-quoted part of string didn't affect the word-splitting since, subject to splitting is complete string here.

Why array worked here?

Array itself expands each element as separate word when using @ and here no further word-splitting requires after expansion.

Arrays

Body:
I am trying to run 'make' command from my bash script to build the code.

I can see that all parameters got assigned and able to display the command that i am trying to run. I could not see any issue with the command. But the issue is when it tries to run the command via bash script it fails.

My command is :- ./build_script LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm"

Script Snippet of parsing all the arguments and constructing make command:-

makeargs=""
for build_flag do
   if [[ "$build_flag " = "PROJECTS="* ]]; then
          apps =`echo $build_flag |sed "s/PROJECTS=//" `
          makeargs="$makeargs PROJECTS=\"$apps \""
   else
        makeargs="$makeargs $build_flag"
    fi
done
echo "make DCOV=1 $makeargs $maketest"
make DCOV=1 $makeargs $maketest

When i run the script, I can see the build command has constructed properly.

Output :-

make DCOV=1 LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm" run_all
GNUmakefile:16: warning: overriding commands for target `/'
GNUmakefile:19: warning: ignoring old commands for target `/'
make: *** No rule to make target `bfm"'.  Stop.

I try to print PROJECTS variable in my 'GNUmakefile' present in build_main folder. I can see the output : PROJECTS is "bfm . It is not taking whole "cuda bfm" as a whole string.

Note:- When i try to run the same build command :- make DCOV=1 LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm" run_all explicitly it works fine.

Seems like issue with Interpreting variables with makefile.

Any solution for this ? Please help.
Thanks!

Body:
Change makeargs string to array before passing it as an arguments group.

eval makeargs_array=( $makeargs )
make UVC=1 "${makeargs_array[@]}" $maketest

Without converting to array, if you enable debug, it shows last line interpretation as

make DCOV=1 LIC=1 DOCUMNETS=1 'PROJECTS="cuda' bfm '"'

Which is clearly ignoring double-quote and considering space as separator.
Even double-quote is getting passed as a separate argument in this case.

Explanation:

Word-splitting
It says,

The shell scans the results of parameter expansion, command
  substitution, and arithmetic expansion that did not occur within
  double quotes for word splitting.

If we use "$makeargs" i.e. surrounded by double-quote, it is not considered by word-splitting and results in LIC=1 DOCUMNETS=1 "PROJECTS=cuda bfm"

But again its a complete string, while requirement is to split the string to use as arguments.

So now using $makeargs.

Word-splitting gets in action as per the default IFS (space, tab, newline), we get result as LIC=1 DOCUMNETS=1 PROJECTS="cuda bfm "

Double-quoted part of string didn't affect the word-splitting since, subject to splitting is complete string here.

Why array worked here?

Array itself expands each element as separate word when using @ and here no further word-splitting requires after expansion.

Arrays