问:
Doing while with html and php
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

```<code><p>

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "<div class=\"pagination\">";         //previous button
            if ($page > 1)
                $pagination.= "<a href=\"$targetpage?page=$prev\">« previous</a>";
            else
                $pagination.= "<span class=\"disabled\">« previous</span>";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "<span class=\"current\">$counter</span>";
                    else
                        $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
                    }
                    $pagination.= "...";
                    $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>";
                    $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "<a href=\"$targetpage?page=1\">1</a>";
                    $pagination.= "<a href=\"$targetpage?page=2\">2</a>";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "<span class=\"current\">$counter</span>";
                        else
                            $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "<a href=\"$targetpage?page=$next\">next »</a>";
            else
                $pagination.= "<span class=\"disabled\">next »</span>";
            $pagination.= "</div>\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '<a href="http://geatzo.com/do123.php?uid='.$row['id'].'"><img src="http://www.geatzo.com/images/coins.jpg" height="100px" width="100px"/>';
            echo '"<p> </p>';
            echo '"You will earn<b>"'.$row['coins'].'"</b>Coins"<p> </p>';
            echo '"Posted By "'.$row['username'].'<p> </p>';
            echo '"Site you will be viewing "'.$row['url'].'<p> </p>';
        }
    ?>

    <?=$pagination?>

</p>
</code>```

I want to put that php in a a html div
here is the html

```<code><div class="ptcbox-link"><a href="http://www.mysite.com/gpt.php?v=entry&type=ptc&id=6960&sid=TWk0Mk1Ea3hORGc1TVRB&sid2=TWk0M&siduid=186998&"></a></div>
                <div class="ptcbox-value-w1">
                    <div class="ptcbox-value">$2</div>
                    <div class="ptcbox-seconds">30 seconds</div>
                </div>
</code>```

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while

答:
You are not using a Template Engine. You can't have not ugly looking code without a template engine.

By Template Engine I mean that you should seperate your logic application from your presentation. (ie: separating HTML from PHP)

You can use plain old PHP code to handle your template engine or a custom snytax by template engine already built:

Smarty

Savant3 http://phpsavant.com/

and many others

Title: Doing while with html and php

Body:
Hello i have done whiles with php but never html...
I have a script that works fine but looks ugly so a friend has made me a html layout.

Here is my php script.

    <?php
        /* Place code to connect to your DB here.     */

        $tbl_name="adds";        //your table name
        // How many adjacent pages should be shown on each side?
        $adjacents = 3;
        /*
        First get total number of rows in data table.
        If you have a WHERE clause in your query, make sure you mirror it here.
        */

        $query = "SELECT COUNT(*) as num FROM adds ";
        $total_pages = mysql_fetch_array(mysql_query($query));
        $total_pages = $total_pages['num'];
        /* Setup vars for query. */
        $targetpage = "earn.php";     //your file name  (the name of this file)
        $limit = 6;
        //how many items to show per page
        $page = isset($_GET['page']) ? $_GET['page'] : 0;
        if($page)
            $start = ($page - 1) * $limit;
        //first item to display on this page
        else
            $start = 0;                                //if no page var is given, set start to 0
        /* Get data. */
        $sql = "SELECT * FROM $tbl_name LIMIT $start, $limit ";
        $result = mysql_query($sql);
        /* Setup page vars for display. */
        if ($page == 0) $page = 1;                    //if no page var is given, default to 1.
        $prev = $page - 1;                            //previous page is page - 1
        $next = $page + 1;                            //next page is page + 1
        $lastpage = ceil($total_pages/$limit);        //lastpage is = total pages / items per page, rounded up.
        $lpm1 = $lastpage - 1;                        //last page minus 1
        /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case
        we want to draw it more than once.
        */

        $pagination = "";
        if($lastpage > 1)
        {
            $pagination .= "
";         //previous button
            if ($page > 1)
                $pagination.= "« previous";
            else
                $pagination.= "« previous";
            //pages
            if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
            {
                for ($counter = 1; $counter <= $lastpage; $counter++)             {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
            }         }         elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
            {
                //close to beginning; only hide later pages
                if($page < 1 + ($adjacents * 2))                     {
                    for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //in middle; hide some front and some back
                elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))             {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
                    }
                    $pagination.= "...";
                    $pagination.= "$lpm1";
                    $pagination.= "$lastpage";
                }             //close to end; only hide early pages
                else
                {
                    $pagination.= "1";
                    $pagination.= "2";
                    $pagination.= "...";
                    for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                    {
                        if ($counter == $page)
                            $pagination.= "$counter";
                        else
                            $pagination.= "$counter";
            }             }         }
            //next button
            if ($page < $counter - 1)
                $pagination.= "next »";
            else
                $pagination.= "next »";
            $pagination.= "
\n";
    } ?>

    <?php
        while($row = mysql_fetch_array($result))
        {
            echo '';
            echo '"

';
            echo '"You will earn"'.$row['coins'].'"Coins"

';
            echo '"Posted By "'.$row['username'].'

';
            echo '"Site you will be viewing "'.$row['url'].'

';
        }
    ?>

    <?=$pagination?>

I want to put that php in a a html div
here is the html

$2

30 seconds

I want there to be like http://img841.imageshack.us/img841/6651/unledfte.png the div tags for each different result a new box for each result

Thanks

P.s the html code and php code works both works i just wanna put them together in a while


来源: stackexchange

问:
how xdp ebpf change checksum tcphdr after update dest port
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;
```

<p>this is the function code with which i am trying to change the checksum of a tcp packet</p>

<pre class="lang-c prettyprint-override"><code>static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}
</code>```

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.

答:
```<code>INTERNAL void update_tcp_header_port(struct tcphdr* tcp, __u16 *new_val)
{
    __u16 old_check = tcp->check;
    __u32 new_csum_value;
    __u32 new_csum_comp;
    __u32 undo;

    /* Get old sum of headers by getting one's compliment and adding
     * one's compliment of old header value (effectively subtracking)
     */
    undo = ~((__u32) tcp->check) + ~((__u32) tcp->dest);

    /* Check for old header overflow and compensate
     * Add new header value
     */
    new_csum_value = undo + (undo < ~((__u32) tcp->dest)) + (__u32) *new_val;

    /* Check for new header overflow and compensate */
    new_csum_comp = new_csum_value + (new_csum_value < ((__u32) *new_val));

    /* Add any overflow of the 16 bit value to itself */
    new_csum_comp = (new_csum_comp & 0xFFFF) + (new_csum_comp >> 16);

    /* Check that overflow added above did not cause another overflow */
    new_csum_comp = (new_csum_comp & 0xFFFF) + (new_csum_comp >> 16);

    /* Cast to 16 bit one's compliment of sum of headers */
    // tcp->check = (__u16) ~new_csum_comp;
    tcp->check = (__u16)10494;

    printt("old check: %d, old dest: %d, new port: %d\n", old_check, (__u16)bpf_ntohs(tcp->dest), *new_val);
    /* Update header to new value */
    tcp->dest = (__u16)bpf_ntohs(*new_val);
    return;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how xdp ebpf change checksum tcphdr after update dest port ?

// Check tcp header size
struct tcphdr *tcph = data + nh_off;
nh_off += sizeof(struct tcphdr);
if (data + nh_off > data_end) {
    return XDP_PASS;
}
tcph->dest = bpf_ntohs(5555);
// ... i'm trying change checksum of tcphdr, it's not work for me.
tcph->check = 0;
tcph->check = checksum((unsigned short *)tcph, sizeof(struct tcphdr));

return XDP_TX;

this is the function code with which i am trying to change the checksum of a tcp packet

static inline unsigned short checksum(unsigned short *buf, int bufsz) {
    unsigned long sum = 0;

    while (bufsz > 1) {
        sum += *buf;
        buf++;
        bufsz -= 2;
    }

    if (bufsz == 1) {
        sum += *(unsigned char *)buf;
    }

    sum = (sum & 0xffff) + (sum >> 16);
    sum = (sum & 0xffff) + (sum >> 16);

    return ~sum;
}

I load an xdp program for the lo interface, and I want to proxy the packet to port 5555 in the same network interface.


问:
Replace null values with 0 in PIVOT
I tried to convert the (null) values with 0 (zeros) output in PIVOT function but have no success.

Below is the table and the syntax I've tried:

```<code>SELECT DISTINCT isnull([DayLoad],0) FROM #Temp1
</code>```

Data in the table #Temp1:

```<code>zone  dayB    templt cid  DayLoad
other 10      other   1    2020-05-28
other 10      other   1    2020-05-29
other 10      other   1    2020-05-30
other 10      other   1    2020-05-31
other 4       other   1    2020-06-02
other 10      other   1    2020-06-02
other 10      other   1    2020-06-01
</code>```

My request:

```<code>DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']',
                                  '[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']')
               FROM    (SELECT DISTINCT [DayLoad] FROM #Temp1) PV
               ORDER BY [DayLoad]

DECLARE @query NVARCHAR(MAX)
SET @query = '
              SELECT *
                      into #temptable
                      FROM
             (
                 SELECT

                ''''+[zone]+'' ''          + ''''+convert(varchar(50),[dayB])+''''+''+''           +'' ''+(case when [templt]=''Прочее'' then '''' else [templt] end)+''''    as [zone/dayB]
                ,[DayLoad]
                ,[cid]
                ,[dayB]
                ,[zone]
                FROM #Temp1
             ) x
             PIVOT
             (
                 sum([cid])
                 FOR [DayLoad] IN ('+ @cols + ')
            ) p

select *
from #temptable
order by [zone],[dayB]

drop table #temptable
            '
EXEC(@query)
DROP TABLE #Temp1
</code>```

答:
Please refer below example, when you have nulls and empty string, right option is to go with case statement,</p>

```<code>SELECT DISTINCT case when ([DayLoad] is null or [DayLoad] = '') then 0 else [DayLoad] end FROM #Temp1
</code>```

Title: Replace null values with 0 in PIVOT

Body:
I tried to convert the (null) values with 0 (zeros) output in PIVOT function but have no success.

Below is the table and the syntax I've tried:

SELECT DISTINCT isnull([DayLoad],0) FROM #Temp1

Data in the table #Temp1:

zone  dayB    templt cid  DayLoad
other 10      other   1    2020-05-28
other 10      other   1    2020-05-29
other 10      other   1    2020-05-30
other 10      other   1    2020-05-31
other 4       other   1    2020-06-02
other 10      other   1    2020-06-02
other 10      other   1    2020-06-01

My request:

DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']',
                                  '[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']')
               FROM    (SELECT DISTINCT [DayLoad] FROM #Temp1) PV
               ORDER BY [DayLoad]

DECLARE @query NVARCHAR(MAX)
SET @query = '
              SELECT *
                      into #temptable
                      FROM
             (
                 SELECT

                ''''+[zone]+'' ''          + ''''+convert(varchar(50),[dayB])+''''+''+''           +'' ''+(case when [templt]=''Прочее'' then '''' else [templt] end)+''''    as [zone/dayB]
                ,[DayLoad]
                ,[cid]
                ,[dayB]
                ,[zone]
                FROM #Temp1
             ) x
             PIVOT
             (
                 sum([cid])
                 FOR [DayLoad] IN ('+ @cols + ')
            ) p

select *
from #temptable
order by [zone],[dayB]

drop table #temptable
            '
EXEC(@query)
DROP TABLE #Temp1

Body:
Please refer below example, when you have nulls and empty string, right option is to go with case statement,

SELECT DISTINCT case when ([DayLoad] is null or [DayLoad] = '') then 0 else [DayLoad] end FROM #Temp1


问:
TechTalk.SpecFlow.BindingException: 'Parameter count mismatch! The binding method
I am trying to write a StepArgumentTransformation for specflow.

I have following gherkin

```<code>Scenario: Test Arguments
Given user enter once as 2
</code>```

And I have written this in step definition.

```<code>    [StepArgumentTransformation]
    public int GetOnces(string onces, string times)
    {
        return 1 * int.Parse(times);
    }

    [Given(@"user enter (.*) as (.*)")]
    public void GivenUserEnterOnce(int num)
    {
        Assert.Equal(2, num);
    }
</code>```

But GetOnces method is never called and I get the exception

TechTalk.SpecFlow.BindingException: 'Parameter count mismatch! The binding method 'GivenUserEnterOnce(Int32)' should have 2 parameters

答: For me the problem was just that I forgot/removed the "Then" line in my scenario</p>

Body:
I am trying to write a StepArgumentTransformation for specflow.

I have following gherkin

Scenario: Test Arguments
Given user enter once as 2

And I have written this in step definition.

    [StepArgumentTransformation]
    public int GetOnces(string onces, string times)
    {
        return 1 * int.Parse(times);
    }

    [Given(@"user enter (.*) as (.*)")]
    public void GivenUserEnterOnce(int num)
    {
        Assert.Equal(2, num);
    }

But GetOnces method is never called and I get the exception

TechTalk.SpecFlow.BindingException: 'Parameter count mismatch! The binding method 'GivenUserEnterOnce(Int32)' should have 2 parameters


问:
My build mode is Release but as a output I get Debug folder, what is the problem?
I need to build Release version of the project. In order to get Release version I switch at the top my build mode from Debug to Release, click Build and I get an output in Debug folder like ...\bin\x64\Debug and actually if I build in Debug I also get an output at the same location.

What I expect is if I build in Debug I get output at this location ...\bin\x64\Debug when I build a release I get an output at this location ``...\bin\x64\Release`.

What am I doing wrong?

答:
Actually my issue was here at the top you can see CPU configuration (x64, AnyCPU...), if you open this configuration you can see such pop up

In front of each project configuration you can see Debug. So in debug it should be Debug and if you switch it to release it should be Release, but for me it was still Debug... I don't know why. I changed this to Release and all is fine now


问:
How does ping -a know the hostname of my Raspberry Pi 4?
My Raspberry Pi 4 B is connected (for the first time) to the WiFi of my PC (running Windows). Then the raspberry(ip) showed up in the list in Network Scanner of MobaXterm. What surprised me is that the list also shows the name of my Pi. And ping -a ip also shows the name.

How does this work?

答:
When the Raspberry Pi connects to your WiFi it doesn't just get an IP address assigned. It also gets a host name assigned. It either sends its own host name to the DHCP server or the DHCP server assigns a host name.

Now, when you have an IP address, you can do a reverse search. Usually DNS works in the way that you give it a name and it returns the IP address. But there is also reverse search, give it an IP address and get a name back.

In your local network the DHCP server and your DNS resolver work together. Whenever a reverse search for a local IP address is made, the answer is fetched from the DHCP server. And the DHCP server answers with the host name from step one.

In most WiFi routers dnsmasq does this for you, on a Windows machine it is built into Windows.


问:
Filesystemwatcher file created event not decompressing files
I got a simple script that should watch for new files in specified folder and uncompress them on arriving. Simple, but my script only works under the debugger of Powershell ISE. When outside the debugger, on file creation it only prints "New file xxx found" and "Done", without decompressing it, nor deleting, but also no errors. I'm I missing something here?</p>

```<code># Folder you to monitor
$PathToMonitor = "C:\tmp1".
$OutputPath = "C:\tmp"
$Filter = "*.zip"  # Filter for zip files.

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Write-Host "New file " + $FullPath + " found"
        $TarProgram = "tar.exe"
        $TarArgs = 'xvf "' + $FullPath + '" -C ' + $OutputPath
        Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force
        Write-Host "Done"
    }
    catch [System.SystemException]
    {
        Write-Host $_.ScriptStackTrace
    }
}

# add event handlers
$handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateFtpGe
}

Write-Host "Watching for changes to $PathToMonitor"

try
{
    do
    {
        Wait-Event -Timeout 10
    } while ($true)
}
catch [System.SystemException]
{
    Write-Host $_.ScriptStackTrace
}
finally
{
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Write-Host "Cleaning up"
    Unregister-Event -SourceIdentifier FSCreateFtpGe
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
}
</code>```

答:
Just for the records, I found the issue. It's somehow related to variables scopes in Powershell.
If instead of using a variable declared at the begin of the script to hold the value of $OutputPath I use a literal string then it works. Otherwise, it complains that the value is null at runtime (In Powershell ISE it shows a value)

So, the action block now looks like this:

```<code>$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Expand-Archive -LiteralPath $FullPath -DestinationPath "C:\Temp"
        Remove-Item -LiteralPath "$FullPath" -Force
    }
    catch [System.SystemException]
    {
        Write-Host $_
    }
}
</code>```

I would prefer to have all my vars at the begin, so they can be easily changed if needed, but at least this version works.

Body:
I got a simple script that should watch for new files in specified folder and uncompress them on arriving. Simple, but my script only works under the debugger of Powershell ISE. When outside the debugger, on file creation it only prints "New file xxx found" and "Done", without decompressing it, nor deleting, but also no errors. I'm I missing something here?

# Folder you to monitor
$PathToMonitor = "C:\tmp1".
$OutputPath = "C:\tmp"
$Filter = "*.zip"  # Filter for zip files.

$FileSystemWatcher = New-Object System.IO.FileSystemWatcher
$FileSystemWatcher.Path  = $PathToMonitor
$FileSystemWatcher.IncludeSubdirectories = $false
$FileSystemWatcher.Filter = $Filter

# make sure the watcher emits events
$FileSystemWatcher.EnableRaisingEvents = $true

# define the code that should execute when a file change is detected
$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Write-Host "New file " + $FullPath + " found"
        $TarProgram = "tar.exe"
        $TarArgs = 'xvf "' + $FullPath + '" -C ' + $OutputPath
        Start-Process $TarProgram $TarArgs -Wait -WindowStyle hidden
        Remove-Item -Path $FullPath -Force
        Write-Host "Done"
    }
    catch [System.SystemException]
    {
        Write-Host $_.ScriptStackTrace
    }
}

# add event handlers
$handlers = . {
    Register-ObjectEvent -InputObject $FileSystemWatcher -EventName Created -Action $Action -SourceIdentifier FSCreateFtpGe
}

Write-Host "Watching for changes to $PathToMonitor"

try
{
    do
    {
        Wait-Event -Timeout 10
    } while ($true)
}
catch [System.SystemException]
{
    Write-Host $_.ScriptStackTrace
}
finally
{
    # this gets executed when user presses CTRL+C
    # remove the event handlers
    Write-Host "Cleaning up"
    Unregister-Event -SourceIdentifier FSCreateFtpGe
    # remove background jobs
    $handlers | Remove-Job
    # remove filesystemwatcher
    $FileSystemWatcher.EnableRaisingEvents = $false
    $FileSystemWatcher.Dispose()
    "Event Handler disabled."
}

Body:
Just for the records, I found the issue. It's somehow related to variables scopes in Powershell.
If instead of using a variable declared at the begin of the script to hold the value of $OutputPath I use a literal string then it works. Otherwise, it complains that the value is null at runtime (In Powershell ISE it shows a value)

So, the action block now looks like this:

$Action = {
    $details = $event.SourceEventArgs
    $FullPath = $details.FullPath
    $OldName = $details.OldName
    $Timestamp = $event.TimeGenerated
    try
    {
        Expand-Archive -LiteralPath $FullPath -DestinationPath "C:\Temp"
        Remove-Item -LiteralPath "$FullPath" -Force
    }
    catch [System.SystemException]
    {
        Write-Host $_
    }
}

I would prefer to have all my vars at the begin, so they can be easily changed if needed, but at least this version works.


问:
KSQL says it expects existing topic to have 2 partitions (topic has 1),
I am facing below error when trying to create Stream in KSQL from an existing Kafka topic.

io.confluent.ksql.exception.KafkaTopicExistsException: A Kafka topic with the name 'test-data' already exists, with different partition/replica configuration than required. KSQL expects 2 partitions (topic has 1), and 1 replication factor (topic has 1).

Is it mandatory to have 2 partitions for creating a stream in KSQL?

答:
I'm guessing you're running a command such as:

```<code>CREATE TABLE FOO (<some column defs>)
  WITH (
     partitions=<some-value>, <-- explicitly setting partition count
     kafka_topic='test-data',
     value_format='<something>'
 );
</code>```

Specifically, are you explicitly setting the partition count in the WITH clause?

Neither the PARTITIONS nor the REPLICAS properties need to be set in the WITH clause when creating a TABLE or STREAM over an existing topic.  These only need to be set when you wish ksqlDB to create a new topic for your data.  If they are set, they must match any existing topic.

These doc pages provide more information on this subject:

https://docs.ksqldb.io/en/latest/developer-guide/create-a-stream/
https://docs.ksqldb.io/en/latest/developer-guide/create-a-table/

If this explanation does not cover your error, then please provide more information. E.g. ksql version, statements used, details of existing topics in Kafka etc.

Body:
I'm guessing you're running a command such as:

CREATE TABLE FOO (<some column defs>)
  WITH (
     partitions=<some-value>, <-- explicitly setting partition count
     kafka_topic='test-data',
     value_format='<something>'
 );

Specifically, are you explicitly setting the partition count in the WITH clause?

Neither the PARTITIONS nor the REPLICAS properties need to be set in the WITH clause when creating a TABLE or STREAM over an existing topic.  These only need to be set when you wish ksqlDB to create a new topic for your data.  If they are set, they must match any existing topic.

These doc pages provide more information on this subject:

https://docs.ksqldb.io/en/latest/developer-guide/create-a-stream/
https://docs.ksqldb.io/en/latest/developer-guide/create-a-table/

If this explanation does not cover your error, then please provide more information. E.g. ksql version, statements used, details of existing topics in Kafka etc.


问:
ToggleButton status
I am using Excel Ribbon toggleButton. Based on it's on/off status I do some processing in the Excel cell in the SheetSelectionChange event. I am not able to get the status of the toggleButton from the cell without accessing my settings file which is an unnecessary overhead. Let me present a snippet of the code.

Global variable could be an option. But can I have something better?

```<code>Private Sub mExcel_SheetSelectionChange(ByVal theSheet As Object, ByVal Target As Range)
'++
' Call the C++ Code.
'--
'If (isbtnpressed) Then  ** <-- This is where i want to check the ToglgeButton status
' I don't want to read the settings file for every cell click. **
    Dim flagVal As Boolean
    'IsValidData goes to C++ for validation
    If IsValidData(Target.Application.ActiveCell) Then
        LoadMyListForm Target.Application.ActiveCell
    End If
'End If

End Sub
</code>```

onAction Events (two)

```<code>Public Sub IxlRibbonGetButtonStateByTag(theControl As IRibbonControl, ByRef isbtnpressed)
'++
'Get ShowOnClick button state, callback for getPressed
'
' Arguments:
'    theControl - The ribbon control that fired the OnAction request.
'    IsPressed - Button status
'--
On Error Resume Next
isbtnpressed = (ReadFromSettingsFile (theControl.Tag, "0") <> "0")

End Sub
</code>```

And

```<code>Public Sub IxlRibbonToggleSettingByTag(control As IRibbonControl, IsPressed As Boolean)
'++
'callback for onAction
'
' Arguments:
'    theControl - The ribbon control that fired the OnAction request.
'    IsPressed - Button status
'--
On Error Resume Next

If IsPressed Then
    WriteToSettingsFile control.Tag, "1"
Else
    WriteToSettingsFile control.Tag, "0"
End If

End Sub
</code>```

the UI XML looks like

```<code>            <toggleButton id="tb_IxlToggleButton"
                label="My Label"
                tag="MyLabel"
                getPressed="IxlRibbonGetButtonStateByTag"
                onAction="IxlRibbonToggleSettingByTag"
                imageMso="ControlToggleButton" />
                <button id="MyLabel"
                    tag="MyLabel"
                    onAction="IxlRibbonToggleSettingByTag"/>
</code>```

I have gone ahead and used global variable as the way out as has been
  suggested in the comment section by @Pᴇʜ

答:
If Public variable not wished, a convenient way would be to keep and reed its status in Registry. The Toggle button can also be set when the application starts, according to the memorized status:

Create some constants at the module level:

```<code>Public const MyApp as string = "MyApp Name"
Public const MyAppSett as string = "MyApp Settings"
Public const TglVal as string = "Toggle_Val"
</code>```

Transform your event code in:

```<code>Public Sub IxlRibbonToggleSettingByTag(control As IRibbonControl, IsPressed As Boolean)
 SaveSetting MyApp, MyAppSett, TglVal, cStr(IsPressed)
End Sub
</code>```

Create a function to rapidly return the status (reading in Registry):

```<code>Function TglStatus() As Boolean
    Dim strToggle As String
    strToggle = GetSetting(MyApp, MyAppSett, TglVal, "Nothing...")
   If strToggle <> "Nothing..." Then
        TglStatus = CBool(strToggle)
   Else
        TglStatus = False 'for the case before memorizing of something...
   End If
End Function
</code>```

And use it like this:

```<code>If TglStatus Then
     'do something for true
Else
     'do something else for false
End If
</code>```

Title: ToggleButton status

Body:
I am using Excel Ribbon toggleButton. Based on it's on/off status I do some processing in the Excel cell in the SheetSelectionChange event. I am not able to get the status of the toggleButton from the cell without accessing my settings file which is an unnecessary overhead. Let me present a snippet of the code.

Global variable could be an option. But can I have something better?

Private Sub mExcel_SheetSelectionChange(ByVal theSheet As Object, ByVal Target As Range)
'++
' Call the C++ Code.
'--
'If (isbtnpressed) Then  ** <-- This is where i want to check the ToglgeButton status
' I don't want to read the settings file for every cell click. **
    Dim flagVal As Boolean
    'IsValidData goes to C++ for validation
    If IsValidData(Target.Application.ActiveCell) Then
        LoadMyListForm Target.Application.ActiveCell
    End If
'End If

End Sub

onAction Events (two)

Public Sub IxlRibbonGetButtonStateByTag(theControl As IRibbonControl, ByRef isbtnpressed)
'++
'Get ShowOnClick button state, callback for getPressed
'
' Arguments:
'    theControl - The ribbon control that fired the OnAction request.
'    IsPressed - Button status
'--
On Error Resume Next
isbtnpressed = (ReadFromSettingsFile (theControl.Tag, "0") <> "0")

End Sub

And

Public Sub IxlRibbonToggleSettingByTag(control As IRibbonControl, IsPressed As Boolean)
'++
'callback for onAction
'
' Arguments:
'    theControl - The ribbon control that fired the OnAction request.
'    IsPressed - Button status
'--
On Error Resume Next

If IsPressed Then
    WriteToSettingsFile control.Tag, "1"
Else
    WriteToSettingsFile control.Tag, "0"
End If

End Sub

the UI XML looks like

            <toggleButton id="tb_IxlToggleButton"
                label="My Label"
                tag="MyLabel"
                getPressed="IxlRibbonGetButtonStateByTag"
                onAction="IxlRibbonToggleSettingByTag"
                imageMso="ControlToggleButton" />
                <button id="MyLabel"
                    tag="MyLabel"
                    onAction="IxlRibbonToggleSettingByTag"/>

I have gone ahead and used global variable as the way out as has been
  suggested in the comment section by @Pᴇʜ

Body:
If Public variable not wished, a convenient way would be to keep and reed its status in Registry. The Toggle button can also be set when the application starts, according to the memorized status:

Create some constants at the module level:

Public const MyApp as string = "MyApp Name"
Public const MyAppSett as string = "MyApp Settings"
Public const TglVal as string = "Toggle_Val"

Transform your event code in:

Public Sub IxlRibbonToggleSettingByTag(control As IRibbonControl, IsPressed As Boolean)
 SaveSetting MyApp, MyAppSett, TglVal, cStr(IsPressed)
End Sub

Create a function to rapidly return the status (reading in Registry):

Function TglStatus() As Boolean
    Dim strToggle As String
    strToggle = GetSetting(MyApp, MyAppSett, TglVal, "Nothing...")
   If strToggle <> "Nothing..." Then
        TglStatus = CBool(strToggle)
   Else
        TglStatus = False 'for the case before memorizing of something...
   End If
End Function

And use it like this:

If TglStatus Then
     'do something for true
Else
     'do something else for false
End If


问:
How can I always display the placeholder in mat-select intependently of the current selection
I want the mat-select element to always show the placeholder, even if an option is selected.

My HTML code:

```<code><mat-select [formControlName]="'language'" placeholder="Language">
    <mat-option value="de">Deutsch</mat-option>
    <mat-option value="en">English</mat-option>
</mat-select>
</code>```

The current behavior is: A soon as a language is selected, the placeholder is made small, moved to the top and the selected language is displayed is displayed big.

What I want to have: When a language is selected, still the placeholder should be displayed in big size, the selected language should not be shown.

How can I do that?

答:
You are not providing a label, and in that case, "If not specified, the placeholder will be used as label." (from documentation).

To disable it, provide a Label, and hide it.

```<code><mat-label hidden></mat-label>
<mat-select [formControlName]="'language'" placeholder="Language">
    <mat-option value="de">Deutsch</mat-option>
    <mat-option value="en">English</mat-option>
</mat-select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want the mat-select element to always show the placeholder, even if an option is selected.

My HTML code:

<mat-select [formControlName]="'language'" placeholder="Language">
    <mat-option value="de">Deutsch</mat-option>
    <mat-option value="en">English</mat-option>
</mat-select>

The current behavior is: A soon as a language is selected, the placeholder is made small, moved to the top and the selected language is displayed is displayed big.

What I want to have: When a language is selected, still the placeholder should be displayed in big size, the selected language should not be shown.

How can I do that?

Body:
You are not providing a label, and in that case, "If not specified, the placeholder will be used as label." (from documentation).

To disable it, provide a Label, and hide it.

<mat-label hidden></mat-label>
<mat-select [formControlName]="'language'" placeholder="Language">
    <mat-option value="de">Deutsch</mat-option>
    <mat-option value="en">English</mat-option>
</mat-select>


问:
Get react-select selected option when using multi dropdown
I have two working react-select drop downs on my page, one that allows the user to select A or B, and one that allows them to choose multiple items from "blue, yellow , red".

When they have chosen these items, I want to use them. For now I just want to check the values that have been selected, so I'm just printing them to screen. For the single selection drop down I have used the example code from the github successfully. This is as follows:

```<code>import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    document.write(`Option selected:`, selectedOption.value); //this prints the selected option
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
        //isMulti //added when the user can pick more than one
      />
    );
  }
}
</code>```

My question is how do I successfully do this for the multi option? The user can select as many as they wish, but an 'undefined' error is thrown when it prints the option that has been selected. I think this is because the option is stored in an array but I'm not sure.

Thanks all.

答:
For store value in array try this one
 [ "purple", "red", "blue" ]

```<code> handleChange = (selectedOptions) => {
    let catArray = [];
    selectedOptions.map(o =>
       catArray.push(o.value)
   );

   this.setState({selectedOptions:catArray});
}
</code>```

onChange={this.handleChange}

Body:
I have two working react-select drop downs on my page, one that allows the user to select A or B, and one that allows them to choose multiple items from "blue, yellow , red".

When they have chosen these items, I want to use them. For now I just want to check the values that have been selected, so I'm just printing them to screen. For the single selection drop down I have used the example code from the github successfully. This is as follows:

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'a', label: 'a' },
  { value: 'b', label: 'b' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  }
  handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    document.write(`Option selected:`, selectedOption.value); //this prints the selected option
  }
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
        //isMulti //added when the user can pick more than one
      />
    );
  }
}

My question is how do I successfully do this for the multi option? The user can select as many as they wish, but an 'undefined' error is thrown when it prints the option that has been selected. I think this is because the option is stored in an array but I'm not sure.

Thanks all.

Body:
For store value in array try this one
 [ "purple", "red", "blue" ]

 handleChange = (selectedOptions) => {
    let catArray = [];
    selectedOptions.map(o =>
       catArray.push(o.value)
   );

   this.setState({selectedOptions:catArray});
}

onChange={this.handleChange}


问:
Node.js Express - Module vs Middleware
I got an express rest api and want to generate a pdf and return a link to the file. I already figured out how to gernerate the pdf. Now I want to have a route that just returns the pdf link and other routes that do their own stuff but also generate a pdf. Should I use a normal node module for the pdf generator or make a middleware that does it?</p>

答: Preferably normal node module because you're not going to generate various pdf templates you can have a common util to generate but for templating purpose keep it seperate.</p>

Title: Node.js Express - Module vs Middleware


问:
Add fixed size of card in CSS
I've tried and failed to adjust a fixed size for a card I'm implementing in my page.

The thing is that, it only gets adjusted based in the amount of characters the "progress" has in the description.

Here is a picture of what I mean, and where I want it to have (the red line represents the desired size):

Here is my code:

```<code><div class="container-xl container-fluid py-3">
               <div class="row">
                     <div class="card card-progress">
                        <div class="card-body">
                           <h3 class="pb-3">A title</h3>
                           <div class="h3 mb-2">A description</div>
                           <hr/>
                           <div style="padding-top: 2%"></div>
                           <div class="h5">Updated progress:</div>
                           <div class="progress mb-4">
                              <div
                                 role="progressbar"
                                 style="width: {{ $progress->progress }}%"
                                 aria-valuenow="{{ $progress->progress }}"
                                 aria-valuemin="0"
                                 aria-valuemax="100"
                                 class="progress-bar progress-bar bg-primary"
                              ></div>
                           </div>
                           <div class="d-flex justify-content-between">
                              <div class="text-left">
                                 <div>Progress made by:</div>
                                 <div class="text-primary h3 mb-0">
                                  <p>
                                  Daniel
                                </p>
                                </div>
                              </div>
                              <div class="text-right">
                                 <div>Current progress of the homework after this addition:</div>
                                 <div class="text-primary h3 mb-0">
                                  <p>
                                  87%
                                </p>
                                </div>
                              </div>
                           </div>
                           <a href="#" class="btn btn-danger"><i data-feather="trash" class="icon-light icons-sm"></i></a>
                           <a href="#" class="btn btn-warning"><i data-feather="edit" class="icon-light icons-sm"></i></a>
                        </div>
                     </div>
                  </div>
            </div>
</code>```

Please do not offer hard-coded solutions.

答:
It looks like you're Bootstrap 4.

So, the simplest solution would be to add the .w-100 class to the card. Which sets the width of the card to 100% of the container.

Title: Add fixed size of card in CSS

Body:
I've tried and failed to adjust a fixed size for a card I'm implementing in my page.

The thing is that, it only gets adjusted based in the amount of characters the "progress" has in the description.

Here is a picture of what I mean, and where I want it to have (the red line represents the desired size):

Here is my code:

A title

A description

Updated progress:

progress }}%"
                                 aria-valuenow="{{ $progress->progress }}"
                                 aria-valuemin="0"
                                 aria-valuemax="100"
                                 class="progress-bar progress-bar bg-primary"
                              >

Progress made by:

                                  Daniel

Current progress of the homework after this addition:

                                  87%

Please do not offer hard-coded solutions.


问:
How to extend Equatable to a class which has extend and mixin with already?
How can I extend and implement Equatable to the class CategoryListPage ?
https://pub.dev/packages/equatable

Here is my class declaration code:

```<code>class CategoryListPage extends StatefulWidget with NavigationStates {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

  @override
  _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
}
</code>```

答:
```<code>class CategoryListPage extends StatefulWidget with NavigationStates, Equatable {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

  @override
  _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
}
</code>```

This will work. If you want to know more about with keyword, see this

Body:
How can I extend and implement Equatable to the class CategoryListPage ?
https://pub.dev/packages/equatable

Here is my class declaration code:

class CategoryListPage extends StatefulWidget with NavigationStates {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

  @override
  _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
}

Body:
class CategoryListPage extends StatefulWidget with NavigationStates, Equatable {

  List<LanguageObject> _languagelistcategorydata;
  String _titleappbar;

  CategoryListPage(List<LanguageObject> languagelistcategorydata, String titleappbar) {
    _languagelistcategorydata = languagelistcategorydata;
    _titleappbar = titleappbar;
  }

  @override
  _CategoryListPageState createState() => _CategoryListPageState(_languagelistcategorydata, _titleappbar);
}

This will work. If you want to know more about with keyword, see this


问:
could not convert string to float: '10,000' Using Django
How do i convert string to float in django?

this is my views.py

```<code>def UpdateFamilyIncomes(request):
   id = request.POST.get('id')
   Amount_From = int(float(request.POST.get("Amount_From")))
   Amount_To = int(float(request.POST.get("Amount_To")))
   Family_Total_Income = FamilyTotalIncome.objects.get(id=id)
   Family_Total_Income.Amount_From = Amount_From
   Family_Total_Income.Amount_To = Amount_To
</code>```

this is my models.py

```<code>class FamilyTotalIncome(models.Model):
    Description = models.CharField(max_length=500,null=True,blank=True)
    Amount_From=models.FloatField()
    Amount_To = models.FloatField()
    Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True)
</code>```

this is my error

答:
try this:</p>

```<code>float(a.replace(',',''))
</code>```

Body:
How do i convert string to float in django?

this is my views.py

def UpdateFamilyIncomes(request):
   id = request.POST.get('id')
   Amount_From = int(float(request.POST.get("Amount_From")))
   Amount_To = int(float(request.POST.get("Amount_To")))
   Family_Total_Income = FamilyTotalIncome.objects.get(id=id)
   Family_Total_Income.Amount_From = Amount_From
   Family_Total_Income.Amount_To = Amount_To

this is my models.py

class FamilyTotalIncome(models.Model):
    Description = models.CharField(max_length=500,null=True,blank=True)
    Amount_From=models.FloatField()
    Amount_To = models.FloatField()
    Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True)

this is my error

Body:
try this:

float(a.replace(',',''))


问:
How to declare SCSS <length> type attribute selector by REACT property
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

```<code>...
<FooComponent width={200}>
...
</code>```

FooComponent.tsx

```<code>interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (
          <div className="foo-component"
              data-width={this.props.width + 'px'}
          >
          ...
</code>```

FooComponent.scss

```<code>.foo-component {
    ...
    width: attr(data-width length);
    ...
</code>```

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

答:
With attr you need to specify the attribute by providing the selector in your scss styles

```<code>.foo-component[data-width] {
    ...
    width: attr(data-width length);
    ...
</code>```

If you have multiple such attribute you can write them like

```<code>.foo-component[data-width][data-margin] {
    ...
    width: attr(data-width length);
    margin: attr(data-margin number);
    ...
</code>```

Please check the MDN docs for more details

Body:
Basically I want to create a reusable component which can be slightly modified from the outside in react:

SomewhereElse.tsx

...
<FooComponent width={200}>
...

FooComponent.tsx

interface IFooProps {
  //default width of 150px
  width?: 150;
  //default margin of 5px
  margin?: 5;
}

interface IFooState{
  checked: boolean;
}

class FooComponent extends Component<IFooProps, IFooState> {
    constructor(props: IFooProps) {
        super(props);
        ...
    }

...

    render(): ReactElement {
        return (

          ...

FooComponent.scss

.foo-component {
    ...
    width: attr(data-width length);
    ...

But it always gives me the following error when running the application (chrome):

... Please consider that I need a "number" as property because I am doing some calculations based on that number for some of the inner components so everything fits together.

EDIT:

Using "style" is not working for me because I have some ::before ::after features in my scss which are broken when using style because they occasionally modify "right:" based on the width.

For better understanding, this is my base:
https://www.sitepoint.com/react-toggle-switch-reusable-component/

Body:
With attr you need to specify the attribute by providing the selector in your scss styles

.foo-component[data-width] {
    ...
    width: attr(data-width length);
    ...

If you have multiple such attribute you can write them like

.foo-component[data-width][data-margin] {
    ...
    width: attr(data-width length);
    margin: attr(data-margin number);
    ...

Please check the MDN docs for more details


答:
If you know how to genarate pdf so

Just use res.download

It's common express method

```<code>res.download('/report-12345.pdf', 'report.pdf', function (err) {
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
})
</code>```

Title: Node.js Express - Module vs Middleware

Body: I got an express rest api and want to generate a pdf and return a link to the file. I already figured out how to gernerate the pdf. Now I want to have a route that just returns the pdf link and other routes that do their own stuff but also generate a pdf. Should I use a normal node module for the pdf generator or make a middleware that does it?

Body:
If you know how to genarate pdf so

Just use res.download

It's common express method

res.download('/report-12345.pdf', 'report.pdf', function (err) {
  if (err) {
    // Handle error, but keep in mind the response may be partially-sent
    // so check res.headersSent
  } else {
    // decrement a download credit, etc.
  }
})


问:
Rails render in controller#create is not loading the page
I have a form being submitted by the resident of a condominium to apply a pass for a visitor.

Upon submission I have setup the controller to render a template or redirect it to another path depending on the input of the form and display a flash message on the top of the page after clicking the submit button.

Somehow redirect works fine but render does nothing to the page.

Did try flash.now with render but no flash and it looks like it is not loading anything new on the page.

```<code>class VisitorPassesController < ApplicationController
  def new
    @visitor_pass = VisitorPass.new
    @controller = "visitor_passes"
  end

  def create
    unless resident && correct_resident_key?
     flash[:danger] = "Invalid resident key."
     # render 'new'                     doesn't work
     # render action: 'new'             doesn't work
     redirect_to new_visitor_pass_path  works
     redirect_to '/visitor_passes/new'  works
     return
    end
    .
    .
    .
  end
end
</code>```

Here is the output of the console.

```<code>Rendering visitor_passes/new.html.erb within layouts/application
Rendered visitor_passes/new.html.erb within layouts/application
Rendered layouts/_rails_default.html.erb
Rendered layouts/_shim.html.erb
Resident Load (0.3ms)  SELECT "residents".* FROM "residents" WHERE "residents"."id" = ? LIMIT ?  [["id", 155], ["LIMIT", 1]] app/helpers/sessions_helper.rb:17:in 'current_user'
Rendered layouts/_header.html.erb (Duration: 3.1ms | Allocations: 760)
Completed 200 OK in 429ms (Views: 59.6ms | ActiveRecord: 2.3ms | Allocations: 33936)
</code>```

答:
Flash messages are displayed in the next response cycle (ie after a redirect). If you want to display a flash message in response to the current request use ActionDispatch::Flash::FlashHash#now.

```<code>class VisitorPassesController < ApplicationController
  def new
    @visitor_pass = VisitorPass.new
    # just use the controller_name method provided by rails instead
  end

  def create
    # ...
    # prefer positive conditions instead of negative
    if resident && correct_resident_key?
      # do something awesome
    else
      flash.now[:danger] = "Invalid resident key."
      render :new
    end
  end
end
</code>```

Also make sure you are using the local: true option on the form if using form_with as it defaults to those pesky XHR remote: true requests.

Body:
I have a form being submitted by the resident of a condominium to apply a pass for a visitor.

Upon submission I have setup the controller to render a template or redirect it to another path depending on the input of the form and display a flash message on the top of the page after clicking the submit button.

Somehow redirect works fine but render does nothing to the page.

Did try flash.now with render but no flash and it looks like it is not loading anything new on the page.

class VisitorPassesController < ApplicationController
  def new
    @visitor_pass = VisitorPass.new
    @controller = "visitor_passes"
  end

  def create
    unless resident && correct_resident_key?
     flash[:danger] = "Invalid resident key."
     # render 'new'                     doesn't work
     # render action: 'new'             doesn't work
     redirect_to new_visitor_pass_path  works
     redirect_to '/visitor_passes/new'  works
     return
    end
    .
    .
    .
  end
end

Here is the output of the console.

Rendering visitor_passes/new.html.erb within layouts/application
Rendered visitor_passes/new.html.erb within layouts/application
Rendered layouts/_rails_default.html.erb
Rendered layouts/_shim.html.erb
Resident Load (0.3ms)  SELECT "residents".* FROM "residents" WHERE "residents"."id" = ? LIMIT ?  [["id", 155], ["LIMIT", 1]] app/helpers/sessions_helper.rb:17:in 'current_user'
Rendered layouts/_header.html.erb (Duration: 3.1ms | Allocations: 760)
Completed 200 OK in 429ms (Views: 59.6ms | ActiveRecord: 2.3ms | Allocations: 33936)

Body:
Flash messages are displayed in the next response cycle (ie after a redirect). If you want to display a flash message in response to the current request use ActionDispatch::Flash::FlashHash#now.

class VisitorPassesController < ApplicationController
  def new
    @visitor_pass = VisitorPass.new
    # just use the controller_name method provided by rails instead
  end

  def create
    # ...
    # prefer positive conditions instead of negative
    if resident && correct_resident_key?
      # do something awesome
    else
      flash.now[:danger] = "Invalid resident key."
      render :new
    end
  end
end

Also make sure you are using the local: true option on the form if using form_with as it defaults to those pesky XHR remote: true requests.


问:
How to apply model.fit() function over an CNN-LSTM model?
I am trying to use this to classify the images into two categories. Also I applied model.fit() function but its showing error.

ValueError: A target array with shape (90, 1) was passed for an output of shape (None, 10) while using as loss binary_crossentropy. This loss expects targets to have the same shape as the output.

```<code>import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, LSTM
import pickle
import numpy as np

X = np.array(pickle.load(open("X.pickle","rb")))
Y = np.array(pickle.load(open("Y.pickle","rb")))

#scaling our image data
X = X/255.0
model = Sequential()

model.add(Conv2D(64 ,(3,3), input_shape = (300,300,1)))

# model.add(MaxPooling2D(pool_size = (2,2)))

model.add(tf.keras.layers.Reshape((16, 16*512)))
model.add(LSTM(128, activation='relu', return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)

model.compile(loss='binary_crossentropy', optimizer=opt,
             metrics=['accuracy'])

# model.summary()
model.fit(X, Y, batch_size=32, epochs = 2, validation_split=0.1)
</code>```

答:
If your problem is categorical, your issue is that you are using binary_crossentropy instead of categorical_crossentropy; ensure that you do have a categorical instead of a binary classification problem.

Also, please note that if your labels are in simple integer format like [1,2,3,4...] and not one-hot-encoded, your loss_function should be sparse_categorical_crossentropy, not categorical_crossentropy.

If you do have a binary classification problem, like said in the error of the above ensure that:

Loss is binary_crossentroy + Dense(1,activation='sigmoid')

Loss is categorical_crossentropy + Dense(2,activation='softmax')

Body:
I am trying to use this to classify the images into two categories. Also I applied model.fit() function but its showing error.

ValueError: A target array with shape (90, 1) was passed for an output of shape (None, 10) while using as loss binary_crossentropy. This loss expects targets to have the same shape as the output.

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, LSTM
import pickle
import numpy as np

X = np.array(pickle.load(open("X.pickle","rb")))
Y = np.array(pickle.load(open("Y.pickle","rb")))

#scaling our image data
X = X/255.0
model = Sequential()

model.add(Conv2D(64 ,(3,3), input_shape = (300,300,1)))

# model.add(MaxPooling2D(pool_size = (2,2)))

model.add(tf.keras.layers.Reshape((16, 16*512)))
model.add(LSTM(128, activation='relu', return_sequences=True))
model.add(Dropout(0.2))

model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(10, activation='softmax'))

opt = tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5)

model.compile(loss='binary_crossentropy', optimizer=opt,
             metrics=['accuracy'])

# model.summary()
model.fit(X, Y, batch_size=32, epochs = 2, validation_split=0.1)


问:
Align mutliple textview to both center and similar left alignment for all screens

I am working on a bottom sheet dialog and was wondering how to align all 3 textviews to the center as well as align them with the same left margin. Please note that there is also an imageview left to the textview for all 3 rows(Here 3 rows are rename, share and delete).
gravity center makes them align to center but their left margin won't be same. I want their left margin to also be same

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:id="@+id/btmsheet"
    android:background="@color/white"
    android:layout_marginLeft="@dimen/pad_5dp"
    android:layout_marginRight="@dimen/pad_5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:id="@+id/dragView"
        android:layout_marginTop="@dimen/pad_10dp">

        <View
            android:layout_width="@dimen/pad_50dp"
            android:layout_height="@dimen/pad_5dp"
            android:background="@color/grey_color" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="15dp">

            <TextView
                android:id="@+id/bottom_sheet_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textSize="@dimen/text_20sp"
                android:textColor="@color/black"
                android:text=""
                tools:text="RB000019.JPG"
                android:textStyle="bold"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_duplicate"
            android:orientation="horizontal"
            android:padding="15dp"
       >

            <TextView
                android:id="@+id/bottom_sheet_rename"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableStart="@drawable/edit"
                android:drawablePadding="@dimen/pad_15dp"
                android:paddingStart="@dimen/pad_20dp"
                android:text="@string/rename_project_name"
                android:textColor="@color/black"
                android:textSize="@dimen/text_16sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_rename"
            android:orientation="horizontal"
            android:padding="15dp"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/share_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/ic_share"
                android:drawablePadding="@dimen/pad_15dp"/>
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal"
            android:padding="15dp"
            android:id="@+id/lyt_move"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/delete_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/delete"
                android:layout_marginStart="@dimen/pad_5dp"
                android:drawablePadding="@dimen/pad_20dp"
               />
        </android.support.constraint.ConstraintLayout>

    </LinearLayout>

</LinearLayout>
</code>```

答:
There are many ways to accomplish the above.

You can use vertical LinearLayout and have 3 horizontal LinearLayout's inside, wrapping icon and text view.

You could also use ConstraintLayout - you'd then have smaller depth of your layout tree.

You could use RecyclerView where each item would be horizontal LinearLayout, or ConstraintLayout - representing row

Updated as per chat with user:

This is to give you an idea:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.4" />

    <ImageView
        android:id="@+id/renameIcon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_margin="16dp"
        android:background="#ff0000"
        app:layout_constraintEnd_toStartOf="@+id/guide"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/renameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rename Project"
        app:layout_constraintBottom_toBottomOf="@+id/renameIcon"
        app:layout_constraintStart_toEndOf="@+id/guide"
        app:layout_constraintTop_toTopOf="@+id/renameIcon" />

    <ImageView
        android:id="@+id/shareProjectIcon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_margin="16dp"
        android:background="#ff0000"
        app:layout_constraintEnd_toStartOf="@+id/guide"
        app:layout_constraintTop_toBottomOf="@+id/renameIcon" />

    <TextView
        android:id="@+id/shareProject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Project"
        app:layout_constraintBottom_toBottomOf="@+id/shareProjectIcon"
        app:layout_constraintStart_toEndOf="@+id/guide"
        app:layout_constraintTop_toTopOf="@+id/shareProjectIcon" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Here is how it's going to look:

Body:
I am working on a bottom sheet dialog and was wondering how to align all 3 textviews to the center as well as align them with the same left margin. Please note that there is also an imageview left to the textview for all 3 rows(Here 3 rows are rename, share and delete).
gravity center makes them align to center but their left margin won't be same. I want their left margin to also be same

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:id="@+id/btmsheet"
    android:background="@color/white"
    android:layout_marginLeft="@dimen/pad_5dp"
    android:layout_marginRight="@dimen/pad_5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:id="@+id/dragView"
        android:layout_marginTop="@dimen/pad_10dp">

        <View
            android:layout_width="@dimen/pad_50dp"
            android:layout_height="@dimen/pad_5dp"
            android:background="@color/grey_color" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="15dp">

            <TextView
                android:id="@+id/bottom_sheet_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textSize="@dimen/text_20sp"
                android:textColor="@color/black"
                android:text=""
                tools:text="RB000019.JPG"
                android:textStyle="bold"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_duplicate"
            android:orientation="horizontal"
            android:padding="15dp"
       >

            <TextView
                android:id="@+id/bottom_sheet_rename"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableStart="@drawable/edit"
                android:drawablePadding="@dimen/pad_15dp"
                android:paddingStart="@dimen/pad_20dp"
                android:text="@string/rename_project_name"
                android:textColor="@color/black"
                android:textSize="@dimen/text_16sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_rename"
            android:orientation="horizontal"
            android:padding="15dp"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/share_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/ic_share"
                android:drawablePadding="@dimen/pad_15dp"/>
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal"
            android:padding="15dp"
            android:id="@+id/lyt_move"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/delete_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/delete"
                android:layout_marginStart="@dimen/pad_5dp"
                android:drawablePadding="@dimen/pad_20dp"
               />
        </android.support.constraint.ConstraintLayout>

    </LinearLayout>

</LinearLayout>

Body:
There are many ways to accomplish the above.

You can use vertical LinearLayout and have 3 horizontal LinearLayout's inside, wrapping icon and text view.

You could also use ConstraintLayout - you'd then have smaller depth of your layout tree.

You could use RecyclerView where each item would be horizontal LinearLayout, or ConstraintLayout - representing row

Updated as per chat with user:

This is to give you an idea:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.4" />

    <ImageView
        android:id="@+id/renameIcon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_margin="16dp"
        android:background="#ff0000"
        app:layout_constraintEnd_toStartOf="@+id/guide"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/renameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rename Project"
        app:layout_constraintBottom_toBottomOf="@+id/renameIcon"
        app:layout_constraintStart_toEndOf="@+id/guide"
        app:layout_constraintTop_toTopOf="@+id/renameIcon" />

    <ImageView
        android:id="@+id/shareProjectIcon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_margin="16dp"
        android:background="#ff0000"
        app:layout_constraintEnd_toStartOf="@+id/guide"
        app:layout_constraintTop_toBottomOf="@+id/renameIcon" />

    <TextView
        android:id="@+id/shareProject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Project"
        app:layout_constraintBottom_toBottomOf="@+id/shareProjectIcon"
        app:layout_constraintStart_toEndOf="@+id/guide"
        app:layout_constraintTop_toTopOf="@+id/shareProjectIcon" />
</androidx.constraintlayout.widget.ConstraintLayout>

Here is how it's going to look:


问:
Create wiki page in HCL Connections programatically using API
Using Tampermonkey, I want to create a wiki page in an existing wiki in HCL Connections 6.6. According to the documentation, I build this function:

```<code>function createWikiPage(cnxBase) {
    let wikiLabel = 'API Test Wiki'
    let url = `${cnxBase}/wikis/basic/api/wiki/${wikiLabel}/feed`
    let body = `
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Matt's Page6</title>
  <summary type="text">My test</summary>
  <content type="text">This is James's wiki page.</content>
  <category term="wikipagetag1" />
  <category term="wikipagetag2" />
  <category term="wikipagetag3" />
  <category scheme="tag:ibm.com,2006:td/type" term="page" label="page" />
</entry>
`
    let args = {
        method: "POST",
        url: url,
        data: body,
        headers: {
            "Content-Type": "application/atom+xml"
        },
        onload: function(response) {
            alert(response.status + ' ' + response.responseText);
        }
    }
    GM_xmlhttpRequest(args)
}
</code>```

The wiki page with tags got created after calling createWikiPage('https://cnx-host') but without any content. Also when I edit the page in the browser and switch to html sourcecode I can't see any character in the content.

Why the official example doesn't work?

答:
I figured out that some additional data is required in the body (mainly use CDATA, which wasn't documented. The following entry gave me the right hints: https://andydunkel.net/2017/08/30/use-c-to-post-to-ibm-connections-blogs-and-wikis/

```<code>  function createWikiPage(wikiLabel, title, text) {
    let url = `${cnxBase}/wikis/basic/api/wiki/${wikiLabel}/feed`
    console.log(`Post to ${url}`)
    let body = `
      <entry xmlns="http://www.w3.org/2005/Atom">
      <category term="page" label="page" scheme="tag:ibm.com,2006:td/type"></category>
      <label xmlns="urn:ibm.com/td">${title}</label>
      <category term="etherpad" />
      <category term="notizen" />
      <category term="entwurf" />
      <content type="text/html"><![CDATA[<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html [<!ENTITY amp
      "&#38;"><!ENTITY lt "<#60;"><!ENTITY gt
      ">#62;"><!ENTITY nbsp " "><!ENTITY apos
      "'"><!ENTITY quot """>]><div>${text}</div>]]></content>
      </entry>`
    let args = {
      method: "POST",
      url: url,
      data: body,
      headers: {
        "Content-Type": "application/atom+xml"
      },
      onload: function (response) {
        // ToDo: Return status
        alert(response.status + ' ' + response.responseText);
        console.log(response.responseText)
      }
    }
    GM_xmlhttpRequest(args)
  }
</code>```

Body:
Using Tampermonkey, I want to create a wiki page in an existing wiki in HCL Connections 6.6. According to the documentation, I build this function:

function createWikiPage(cnxBase) {
    let wikiLabel = 'API Test Wiki'
    let url = `${cnxBase}/wikis/basic/api/wiki/${wikiLabel}/feed`
    let body = `
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Matt's Page6</title>
  My test
  <content type="text">This is James's wiki page.</content>
  <category term="wikipagetag1" />
  <category term="wikipagetag2" />
  <category term="wikipagetag3" />
  <category scheme="tag:ibm.com,2006:td/type" term="page" label="page" />
</entry>
`
    let args = {
        method: "POST",
        url: url,
        data: body,
        headers: {
            "Content-Type": "application/atom+xml"
        },
        onload: function(response) {
            alert(response.status + ' ' + response.responseText);
        }
    }
    GM_xmlhttpRequest(args)
}

The wiki page with tags got created after calling createWikiPage('https://cnx-host') but without any content. Also when I edit the page in the browser and switch to html sourcecode I can't see any character in the content.

Why the official example doesn't work?

Body:
I figured out that some additional data is required in the body (mainly use CDATA, which wasn't documented. The following entry gave me the right hints: https://andydunkel.net/2017/08/30/use-c-to-post-to-ibm-connections-blogs-and-wikis/

  function createWikiPage(wikiLabel, title, text) {
    let url = `${cnxBase}/wikis/basic/api/wiki/${wikiLabel}/feed`
    console.log(`Post to ${url}`)
    let body = `
      <entry xmlns="http://www.w3.org/2005/Atom">
      <category term="page" label="page" scheme="tag:ibm.com,2006:td/type"></category>
      <label xmlns="urn:ibm.com/td">${title}</label>
      <category term="etherpad" />
      <category term="notizen" />
      <category term="entwurf" />
      <content type="text/html"><![CDATA[<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html [<!ENTITY amp
      "&#38;#38;"><!ENTITY lt "&#60;#60;"><!ENTITY gt
      "&#62;#62;"><!ENTITY nbsp "&#160;"><!ENTITY apos
      "&#39;"><!ENTITY quot "&#34;">]><div>${text}</div>]]></content>
      </entry>`
    let args = {
      method: "POST",
      url: url,
      data: body,
      headers: {
        "Content-Type": "application/atom+xml"
      },
      onload: function (response) {
        // ToDo: Return status
        alert(response.status + ' ' + response.responseText);
        console.log(response.responseText)
      }
    }
    GM_xmlhttpRequest(args)
  }


问:
Database schema Desigining
Relations:

Student(s_id,name),
Dept(d_id,name),
course(d_id,c_id,name) d_id FK, refrenced from Dept,
Enrolledin(s_id,d_id).

With the given schema, how to form a relation registeredin which should contain information of courses registered by a student but with the constraint that student can only register in the course offered by dept student has been enrolled in.

Thanks in advance!

答:
Your data model uses single technical IDs. Now you are looking for a way to guarantee consistency through your table tree. This is not possible with singe surrogate keys and is indeed the main drawback of this design. Use composite keys instead:

student (student_no, name)

Primary key: (student_no)

department (department_no, name)

Primary key: (department_no)

course (department_no, course_no, name)

Primary key: (department_no, course_no)

Foreign key: (department_no) references department (department_no)

enrolled_in (student_no, department_no)

Primary key: (student_no, department_no)

Foreign key: (student_no) references student (student_no)

Foreign key: (department_no) references department (department_no)

registered_in (student_no, department_no, course_no)

Primary key: (student_no, department_no, course_no)

Foreign key: (student_no, department_no) references enrolled_in (student_no, department_no)

Foreign key: (department_no, course_no) references course (department_no, course_no)

Title: Database schema Desigining


问:
Sorting query output by Month name
I am trying to extract values from Excel using an SQL Query, but what I've been struggling with is sorting the months in their respective order. Right now the table is being sorted A-Z, I tried playing around with DATEPART, but was not very successful as I was getting an Int16 error.

```<code>Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1;
</code>```

This is the query that works, but the result is:

I am also open to any suggestions that could improve my query speed as the document is quite big, about 50k rows, thanks.

For anyone wondering the final query that worked was:

```<code>Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY SWITCH(
F1='January', 1,
F1='February', 2,
F1='March', 3,
F1='April', 4,
F1='May', 5,
F1='June', 6,
F1='July', 7,
F1='August', 8,
F1='September', 9,
F1='October', 10,
F1='November', 11,
F1='December', 12
);
</code>```

答:
You could do:</p>

```<code>order by datepart(mm, f1 + ' 1 2000')
</code>```

Title: Sorting query output by Month name

Body:
I am trying to extract values from Excel using an SQL Query, but what I've been struggling with is sorting the months in their respective order. Right now the table is being sorted A-Z, I tried playing around with DATEPART, but was not very successful as I was getting an Int16 error.

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1;

This is the query that works, but the result is:

I am also open to any suggestions that could improve my query speed as the document is quite big, about 50k rows, thanks.

For anyone wondering the final query that worked was:

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY SWITCH(
F1='January', 1,
F1='February', 2,
F1='March', 3,
F1='April', 4,
F1='May', 5,
F1='June', 6,
F1='July', 7,
F1='August', 8,
F1='September', 9,
F1='October', 10,
F1='November', 11,
F1='December', 12
);

Body:
You could do:

order by datepart(mm, f1 + ' 1 2000')


问:
How to align side by side 2 differents component in angular with Flexbox
How can I align 2 different Component side by side using flexbox ?

I have my 1st component "nav-menu" and the 2nd "homepage" I would like it to be side by side.

homepage.component.html

```<code>    <app-nav-menu></app-nav-menu>
<div class="container">
    <div>
        <img src="https://colorlib.com/preview/theme/amado/img/product-img/pro-big-1.jpg">
    </div>
</div>
</code>```

I gave a width to my container

homepage.component.css

```<code>.container {
    display: flex;
    width: 50%;
}

div.container>div {
    flex-grow: 1;
}

img {
    width: 20%;
    height: auto;
}
</code>```

nav-menu.component.html

```<code>    <h1>Furniture</h1>
<nav class="nav" role="navigation">
    <ul clas="menu">
        <li><a href="#">Home</a></li>
        <li><a href="#">Shop</a></li>
        <li><a href="#">Product</a></li>
        <li><a href="#">Cart</a></li>
    </ul>
</nav>
</code>```

I gave a width to my nav

nav-menu.component.css

```<code>    * {
    box-sizing: border-box;
}

h1 {
    display: flex;
    justify-content: space-between;
    margin-left: 30px;
    margin-bottom: 100px;
}

nav {
    width: 40%;
}

.nav ul {
    margin: 0px;
    padding: 0px;
    background: white;
    list-style: none;
}

.nav a {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 0.5em;
    text-decoration: none;
    color: black;
    font-size: 2em;
    width: 10px;
}

.nav a:hover {
    color: #FFA500;
    transition: 0.1s;
}
</code>```

whats the next step ?

thanks.

答:
you have to wrap your both components in a flex

```<code><div style="display: flex; flex-grow: grow">
  <app-component-1></app-component-1>
  <app-component-2></app-component-2>
</div>
</code>```

Body:
How can I align 2 different Component side by side using flexbox ?

I have my 1st component "nav-menu" and the 2nd "homepage" I would like it to be side by side.

homepage.component.html

    <app-nav-menu></app-nav-menu>

I gave a width to my container

homepage.component.css

.container {
    display: flex;
    width: 50%;
}

div.container>div {
    flex-grow: 1;
}

img {
    width: 20%;
    height: auto;
}

nav-menu.component.html

Furniture

Home

Shop

Product

Cart

I gave a width to my nav

nav-menu.component.css

    * {
    box-sizing: border-box;
}

h1 {
    display: flex;
    justify-content: space-between;
    margin-left: 30px;
    margin-bottom: 100px;
}

nav {
    width: 40%;
}

.nav ul {
    margin: 0px;
    padding: 0px;
    background: white;
    list-style: none;
}

.nav a {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 0.5em;
    text-decoration: none;
    color: black;
    font-size: 2em;
    width: 10px;
}

.nav a:hover {
    color: #FFA500;
    transition: 0.1s;
}

whats the next step ?

thanks.

Body:
you have to wrap your both components in a flex

<div style="display: flex; flex-grow: grow">
  <app-component-1></app-component-1>
  <app-component-2></app-component-2>
</div>


问:
Excel: Find words of certain length in string?
I have this file where I want to make a conditional check for any cell that contains the letter combination "_SOL", or where the string is followed by any numeric character like "_SOL1524", and stop looking after that. So I don't want matches for "_SOLUTION" or "_SOLothercharactersthannumeric".

So when I use the following formula, I also get results for words like "_SOLUTION":

```<code>=IF(ISNUMBER(FIND("_SOL",A1))=TRUE,"Yay","")
</code>```

How can I avoid this, and only get matches if the match is "_SOL" or "_SOLnumericvalue" (one numeric character)

Clarification: The whole strings may be "Blabla_SOL_BLABLA", "Blabla_SOLUTION_BLABLA" or "Blabla_SOL1524_BLABLA"

答:
Here is an alternative way to check if your string contains SOL followed by either nothing or any numeric value up to any characters after SOL:

```<code>=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","1</s><s>")&"</s></t>","//s[substring-after(.,'SOL')*0=0]")>0),"Yey","Nay")
</code>```

Just to use in an unfortunate event where you would encounter SOL1TEXT for example. Or, maybe saver (in case you have text like AEROSOL):

```<code>=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","</s><s>")&"</s></t>","//s[translate(.,'1234567890','')='SOL']")>0),"Yey","Nay")
</code>```

And to prevent that you have text like 123SOL123 you could even do:

```<code>=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","1</s><s>")&"</s></t>","//s[starts-with(., 'SOL') and substring(., 4)*0=0]")>0),"Yey","Nay")
</code>```

Body:
I have this file where I want to make a conditional check for any cell that contains the letter combination "_SOL", or where the string is followed by any numeric character like "_SOL1524", and stop looking after that. So I don't want matches for "_SOLUTION" or "_SOLothercharactersthannumeric".

So when I use the following formula, I also get results for words like "_SOLUTION":

=IF(ISNUMBER(FIND("_SOL",A1))=TRUE,"Yay","")

How can I avoid this, and only get matches if the match is "_SOL" or "_SOLnumericvalue" (one numeric character)

Clarification: The whole strings may be "Blabla_SOL_BLABLA", "Blabla_SOLUTION_BLABLA" or "Blabla_SOL1524_BLABLA"

Body:
Here is an alternative way to check if your string contains SOL followed by either nothing or any numeric value up to any characters after SOL:

=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","1</s><s>")&"</s></t>","//s[substring-after(.,'SOL')*0=0]")>0),"Yey","Nay")

Just to use in an unfortunate event where you would encounter SOL1TEXT for example. Or, maybe saver (in case you have text like AEROSOL):

=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","</s><s>")&"</s></t>","//s[translate(.,'1234567890','')='SOL']")>0),"Yey","Nay")

And to prevent that you have text like 123SOL123 you could even do:

=IF(COUNT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"_","1</s><s>")&"</s></t>","//s[starts-with(., 'SOL') and substring(., 4)*0=0]")>0),"Yey","Nay")