问:
Powershell Tcp-IP, how to, Connect / SendData / ReadResult / Disconnect
I need to query printer over JetDirect protocol (Tcp-IP Port 9100)

I already write the code to connect and disconnect, but for put and read data i have some problem :(

```<code>'printer.local:9100' | Connect-TcpHost | Disconnect-TcpHost
</code>```

result

```<code>TcpDestNodes     IsOpen Latency Query
------------     ------ ------- -----
printer.local:9100   True  0,7065 {}
</code>```

My code

```<code>function Connect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$Dest,
    $TCPtimeout=250
    ) {
    Begin {

    } Process {
        ($HostName, $port) = $Dest.split(':')
        Write-Verbose "$HostName : $port"
        $tcpClient = New-Object System.Net.Sockets.TCPClient
        $connect = $tcpClient.BeginConnect($HostName,$port,$null,$null)

        Write-Verbose "Connecting..."
        $timeMs = (Measure-Command {
            $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
            Write-Verbose "Connecting 2..."
        }).TotalMilliseconds
        If (!$wait) {
            Write-error "$HostName : $Port"
            Write-Verbose "Close connections..."
            $tcpClient.Close()
            $tcpClient.Dispose()
            return;
        }
        [pscustomobject][ordered]@{
            TcpDestNodes = $dest
            tcpClient = $tcpClient
            connect = $connect
            IsOpen = $true
            Latency = $timeMs
            Query = @()
        }
    } End {

    }
}
function Disconnect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp
    ) {
    Begin {
    } Process {
        Write-Verbose "Disconnecting..."
        $ObjTcp.tcpClient.Close()
        $ObjTcp.tcpClient.Dispose()
        [pscustomobject][ordered]@{
            TcpDestNodes = $ObjTcp.TcpDestNodes
            IsOpen = $ObjTcp.IsOpen
            Latency = $ObjTcp.Latency
            Query = $ObjTcp.Query
        }
    } End {

    }
}
</code>```

答:
I Write 2 new function Put-TcpHost() and Read-TcpHost()

```<code>'printer.local:9100' | Connect-TcpHost -verbose | Put-TcpHost -query '@PJL INFO ID' -verbose | Read-TcpHost -verbose | Disconnect-TcpHost -verbose
</code>```

return

```<code>TcpDestNodes : 10.48.5.102:9100
IsOpen       : True
Latency      : 0,8351
Query        : {@{Type=Query; Data=System.Object[]}, @{Type=Answer; Data=System.Object[]}}
</code>```

my full Tcp-Tools.ps1

```<code>function Connect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$Dest,
    $TCPtimeout=250
    ) {
    Begin {

    } Process {
        ($HostName, $port) = $Dest.split(':')
        Write-Verbose "$HostName : $port"
        $tcpClient = New-Object System.Net.Sockets.TCPClient
        $connect = $tcpClient.BeginConnect($HostName,$port,$null,$null)

        Write-Verbose "Connecting..."
        $timeMs = (Measure-Command {
            $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
        }).TotalMilliseconds
        If (!$wait) {
            Write-error "$HostName : $Port"
            Write-Verbose "Echec, Close socket..."
            $tcpClient.Close()
            $tcpClient.Dispose()
            return;
        }
        Write-Verbose "Connection Available"
        [pscustomobject][ordered]@{
            TcpDestNodes = $dest
            tcpClient = $tcpClient
            connect = $connect
            IsOpen = $true
            Latency = $timeMs
            Query = @()
        }
    } End {

    }
}
function Put-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp,[string]$query
    ) {
    Begin {

    } Process {
        if ($ObjTcp.tcpClient.Connected) {
            Write-Verbose "Send > $query"
            $ObjTcp.query += [pscustomobject][ordered]@{
                    Type = 'Query'
                    Data = @($query)
            }
            $data = [System.Text.Encoding]::ASCII.GetBytes("$query`n")
            $stream = $ObjTcp.TcpClient.GetStream()
            $stream.Write($data, 0, $data.Length)
        } else {
            Write-error "N'est plus connecte !"
            $ObjTcp.tcpClient.Close()
            $ObjTcp.tcpClient.Dispose()
            return;
        }
        $ObjTcp
    } End {

    }
}
function Read-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp,
    $timeout=2500
    ) {
    Begin {
        $step = 25
    } Process {
        $i=$timeout/$step
        Write-Verbose ">  Waiting Answer"
        While ([int64]$ObjTcp.tcpClient.Available -le 0 -and $i--) {
            Start-Sleep -Milliseconds $step
        }
        Write-Verbose "Reply $($timeout-$i*$step)ms > Bytes available: $($ObjTcp.tcpClient.Available)"
        If ([int64]$ObjTcp.tcpClient.Available -gt 0) {
            $stringBuilder = New-Object Text.StringBuilder
            try {
                $stream = $ObjTcp.TcpClient.GetStream()
                $bindResponseBuffer = New-Object Byte[] -ArgumentList $ObjTcp.tcpClient.Available
                [Int]$response = $stream.Read($bindResponseBuffer, 0, $bindResponseBuffer.count)
                $Null = $stringBuilder.Append(($bindResponseBuffer | ForEach {[char][int]$_}) -join '')

                Write-Verbose "Read > $(@($stringBuilder.Tostring() -split("`n"))[1])"
                $ObjTcp.query += [pscustomobject][ordered]@{
                    Type = 'Answer'
                    Data = @($stringBuilder.Tostring() -split("`n"))
                 }
            } catch {
                Write-error "Probleme !"
                $ObjTcp.tcpClient.Close()
                $ObjTcp.tcpClient.Dispose()
                return;
            }
        }
        $ObjTcp
    } End {

    }
}
function Disconnect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp
    ) {
    Begin {
    } Process {
        Write-Verbose "Disconnecting..."
        $ObjTcp.tcpClient.Close()
        $ObjTcp.tcpClient.Dispose()
        [pscustomobject][ordered]@{
            TcpDestNodes = $ObjTcp.TcpDestNodes
            IsOpen = $ObjTcp.IsOpen
            Latency = $ObjTcp.Latency
            Query = $ObjTcp.Query
        }
    } End {

    }
}
</code>```

Body:
I need to query printer over JetDirect protocol (Tcp-IP Port 9100)

I already write the code to connect and disconnect, but for put and read data i have some problem :(

'printer.local:9100' | Connect-TcpHost | Disconnect-TcpHost

result

TcpDestNodes     IsOpen Latency Query
------------     ------ ------- -----
printer.local:9100   True  0,7065 {}

My code

function Connect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$Dest,
    $TCPtimeout=250
    ) {
    Begin {

    } Process {
        ($HostName, $port) = $Dest.split(':')
        Write-Verbose "$HostName : $port"
        $tcpClient = New-Object System.Net.Sockets.TCPClient
        $connect = $tcpClient.BeginConnect($HostName,$port,$null,$null)

        Write-Verbose "Connecting..."
        $timeMs = (Measure-Command {
            $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
            Write-Verbose "Connecting 2..."
        }).TotalMilliseconds
        If (!$wait) {
            Write-error "$HostName : $Port"
            Write-Verbose "Close connections..."
            $tcpClient.Close()
            $tcpClient.Dispose()
            return;
        }
        [pscustomobject][ordered]@{
            TcpDestNodes = $dest
            tcpClient = $tcpClient
            connect = $connect
            IsOpen = $true
            Latency = $timeMs
            Query = @()
        }
    } End {

    }
}
function Disconnect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp
    ) {
    Begin {
    } Process {
        Write-Verbose "Disconnecting..."
        $ObjTcp.tcpClient.Close()
        $ObjTcp.tcpClient.Dispose()
        [pscustomobject][ordered]@{
            TcpDestNodes = $ObjTcp.TcpDestNodes
            IsOpen = $ObjTcp.IsOpen
            Latency = $ObjTcp.Latency
            Query = $ObjTcp.Query
        }
    } End {

    }
}

Body:
I Write 2 new function Put-TcpHost() and Read-TcpHost()

'printer.local:9100' | Connect-TcpHost -verbose | Put-TcpHost -query '@PJL INFO ID' -verbose | Read-TcpHost -verbose | Disconnect-TcpHost -verbose

return

TcpDestNodes : 10.48.5.102:9100
IsOpen       : True
Latency      : 0,8351
Query        : {@{Type=Query; Data=System.Object[]}, @{Type=Answer; Data=System.Object[]}}

my full Tcp-Tools.ps1

function Connect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$Dest,
    $TCPtimeout=250
    ) {
    Begin {

    } Process {
        ($HostName, $port) = $Dest.split(':')
        Write-Verbose "$HostName : $port"
        $tcpClient = New-Object System.Net.Sockets.TCPClient
        $connect = $tcpClient.BeginConnect($HostName,$port,$null,$null)

        Write-Verbose "Connecting..."
        $timeMs = (Measure-Command {
            $wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
        }).TotalMilliseconds
        If (!$wait) {
            Write-error "$HostName : $Port"
            Write-Verbose "Echec, Close socket..."
            $tcpClient.Close()
            $tcpClient.Dispose()
            return;
        }
        Write-Verbose "Connection Available"
        [pscustomobject][ordered]@{
            TcpDestNodes = $dest
            tcpClient = $tcpClient
            connect = $connect
            IsOpen = $true
            Latency = $timeMs
            Query = @()
        }
    } End {

    }
}
function Put-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp,[string]$query
    ) {
    Begin {

    } Process {
        if ($ObjTcp.tcpClient.Connected) {
            Write-Verbose "Send > $query"
            $ObjTcp.query += [pscustomobject][ordered]@{
                    Type = 'Query'
                    Data = @($query)
            }
            $data = [System.Text.Encoding]::ASCII.GetBytes("$query`n")
            $stream = $ObjTcp.TcpClient.GetStream()
            $stream.Write($data, 0, $data.Length)
        } else {
            Write-error "N'est plus connecte !"
            $ObjTcp.tcpClient.Close()
            $ObjTcp.tcpClient.Dispose()
            return;
        }
        $ObjTcp
    } End {

    }
}
function Read-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp,
    $timeout=2500
    ) {
    Begin {
        $step = 25
    } Process {
        $i=$timeout/$step
        Write-Verbose ">  Waiting Answer"
        While ([int64]$ObjTcp.tcpClient.Available -le 0 -and $i--) {
            Start-Sleep -Milliseconds $step
        }
        Write-Verbose "Reply $($timeout-$i*$step)ms > Bytes available: $($ObjTcp.tcpClient.Available)"
        If ([int64]$ObjTcp.tcpClient.Available -gt 0) {
            $stringBuilder = New-Object Text.StringBuilder
            try {
                $stream = $ObjTcp.TcpClient.GetStream()
                $bindResponseBuffer = New-Object Byte[] -ArgumentList $ObjTcp.tcpClient.Available
                [Int]$response = $stream.Read($bindResponseBuffer, 0, $bindResponseBuffer.count)
                $Null = $stringBuilder.Append(($bindResponseBuffer | ForEach {[char][int]$_}) -join '')

                Write-Verbose "Read > $(@($stringBuilder.Tostring() -split("`n"))[1])"
                $ObjTcp.query += [pscustomobject][ordered]@{
                    Type = 'Answer'
                    Data = @($stringBuilder.Tostring() -split("`n"))
                 }
            } catch {
                Write-error "Probleme !"
                $ObjTcp.tcpClient.Close()
                $ObjTcp.tcpClient.Dispose()
                return;
            }
        }
        $ObjTcp
    } End {

    }
}
function Disconnect-TcpHost (
    [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$ObjTcp
    ) {
    Begin {
    } Process {
        Write-Verbose "Disconnecting..."
        $ObjTcp.tcpClient.Close()
        $ObjTcp.tcpClient.Dispose()
        [pscustomobject][ordered]@{
            TcpDestNodes = $ObjTcp.TcpDestNodes
            IsOpen = $ObjTcp.IsOpen
            Latency = $ObjTcp.Latency
            Query = $ObjTcp.Query
        }
    } End {

    }
}


来源: stackexchange

问:
react router 4 404 path in case of dynamic routes
I am working with the latest React Router ( 4 ) version. I have a dynamic config for my routes, just like it described in the tutorial. It works fine but when I has tried to add the 404 path (just like in the tutorial) it starts to show this 404 page right before loading any normal component with the correct path.

In case of nonexistent path the 404 route works correctly.

In case of move to an allowed route config)

First - 404 component showed ( I don't know why )
Second - Normal component showed and the 404 component has disappeared.

Does anyone have any information how this issue can be fixed? Thanks for any information!

Here is my route config.

```<code>import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";

const navScheme = Config.navigationScheme;

const COMPLEX_ROUTES = route => {
    console.log("routesss ->> ", route);
    return (
        <Switch >
            <Route path={route.path} exact={!!route.exact} render={props => (
                // pass the sub-routes down to keep nesting
                <route.component {...props} routes={route.routes}/>
            )}/>
        </Switch>
    );
};

const generateRoutes = routes => routes.map((route, i) => (
    <COMPLEX_ROUTES key={i} {...route}/>
));

const PLATFORM_CHILD_ROUTES = [
    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../../modules/home/Home.module")),
        exact : true
    }
];

const ROUTES = [
    {
        path : navScheme.root,
        component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
        exact : true
    },

    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../components/Platform")),
        routes : PLATFORM_CHILD_ROUTES
    },

    {
        path : "*",
        component : lazyRoute(() => import("../../modules/errors/Error404.module"))
    },

];

export { generateRoutes, ROUTES };
</code>```

答:
I have found the solution for this issue.

In the react-router documentation we can see that:

A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches.

It's mean that we should add the Switch component into our route scheme to show only THE FIRST one matched component. I had the Switch but in a wrong place. It should wrap the generated routes but in my case it was "inner wrapper".

After these changes my config looks like this:

```<code>import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";

const navScheme = Config.navigationScheme;

const COMPLEX_ROUTES = route => {
    return (
            <Route path={route.path} exact={!!route.exact} render={props => (
                // pass the sub-routes down to keep nesting
                <route.component {...props} routes={route.routes}/>
            )}/>
    );
};

const generateRoutes = routes => {
    return (
        <Switch>
            {
                routes.map((route, i) => (
                    <COMPLEX_ROUTES key={i} {...route}/>
                ))
            }
        </Switch>
    );
};

const PLATFORM_CHILD_ROUTES = [
    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../../modules/home/Home.module")),
        exact : true
    }
];

const ROUTES = [
    {
        path : navScheme.root,
        component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
        exact : true
    },

    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../components/Platform")),
        routes : PLATFORM_CHILD_ROUTES
    },

    {
        path : "*",
        component : lazyRoute(() => import("../../modules/errors/Error404.module"))
    },

];

export { generateRoutes, ROUTES };
</code>```

Hope it helps someone.
Best regards. Velidan

ContentLicense: CC BY-SA 3.0

Body:
I am working with the latest React Router ( 4 ) version. I have a dynamic config for my routes, just like it described in the tutorial. It works fine but when I has tried to add the 404 path (just like in the tutorial) it starts to show this 404 page right before loading any normal component with the correct path.

In case of nonexistent path the 404 route works correctly.

In case of move to an allowed route config)

First - 404 component showed ( I don't know why )
Second - Normal component showed and the 404 component has disappeared.

Does anyone have any information how this issue can be fixed? Thanks for any information!

Here is my route config.

import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";

const navScheme = Config.navigationScheme;

const COMPLEX_ROUTES = route => {
    console.log("routesss ->> ", route);
    return (
        <Switch >
            <Route path={route.path} exact={!!route.exact} render={props => (
                // pass the sub-routes down to keep nesting
                <route.component {...props} routes={route.routes}/>
            )}/>
        </Switch>
    );
};

const generateRoutes = routes => routes.map((route, i) => (
    <COMPLEX_ROUTES key={i} {...route}/>
));

const PLATFORM_CHILD_ROUTES = [
    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../../modules/home/Home.module")),
        exact : true
    }
];

const ROUTES = [
    {
        path : navScheme.root,
        component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
        exact : true
    },

    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../components/Platform")),
        routes : PLATFORM_CHILD_ROUTES
    },

    {
        path : "*",
        component : lazyRoute(() => import("../../modules/errors/Error404.module"))
    },

];

export { generateRoutes, ROUTES };

Body:
I have found the solution for this issue.

In the react-router documentation we can see that:

A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches.

It's mean that we should add the Switch component into our route scheme to show only THE FIRST one matched component. I had the Switch but in a wrong place. It should wrap the generated routes but in my case it was "inner wrapper".

After these changes my config looks like this:

import React from "react";
import { Route, Switch } from "react-router-dom";
import { Config } from "shared/services";
import lazyRoute from "./lazyRoute";

const navScheme = Config.navigationScheme;

const COMPLEX_ROUTES = route => {
    return (
            <Route path={route.path} exact={!!route.exact} render={props => (
                // pass the sub-routes down to keep nesting
                <route.component {...props} routes={route.routes}/>
            )}/>
    );
};

const generateRoutes = routes => {
    return (
        <Switch>
            {
                routes.map((route, i) => (
                    <COMPLEX_ROUTES key={i} {...route}/>
                ))
            }
        </Switch>
    );
};

const PLATFORM_CHILD_ROUTES = [
    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../../modules/home/Home.module")),
        exact : true
    }
];

const ROUTES = [
    {
        path : navScheme.root,
        component : lazyRoute(() => import("../../modules/landing-page/LandingPage.module")),
        exact : true
    },

    {
        path : navScheme.platform,
        component : lazyRoute(() => import("../components/Platform")),
        routes : PLATFORM_CHILD_ROUTES
    },

    {
        path : "*",
        component : lazyRoute(() => import("../../modules/errors/Error404.module"))
    },

];

export { generateRoutes, ROUTES };

Hope it helps someone.
Best regards. Velidan


问:
Group by clause not working in DB2 (sql code -119)
I want to get the amount of results for each day of the past week. Unfortunately, I got this error for the query:

An expression starting with "APP_ID" specified in a SELECT clause,
  HAVING clause, or ORDER BY clause is not specified in the GROUP BY
  clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause
  with a column function and no GROUP BY clause is specified..
  SQLCODE=-119, SQLSTATE=42803, DRIVER=3.67.27

The query:

```<code>SELECT DAYNAME(created), app_id
FROM Annotation
WHERE app_id = 1 AND (created < CURRENT DATE - 7 DAYS)
GROUP BY DAYNAME(created) ORDER BY created
</code>```

The problem has something to do with the GROUP BY statement. What is wrong with it?

答:
I think the error is pretty clear -- appid is in the SELECT but not the GROUP BY.  The solution is that you need an aggregation function.  I would expect something like this:

```<code>SELECT DAYNAME(created), COUNT(*)
FROM Annotation a
WHERE app_id = 1 AND (created < CURRENT DATE - 7 DAYS)
GROUP BY DAYNAME(created)
ORDER BY MIN(created);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to get the amount of results for each day of the past week. Unfortunately, I got this error for the query:

An expression starting with "APP_ID" specified in a SELECT clause,
  HAVING clause, or ORDER BY clause is not specified in the GROUP BY
  clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause
  with a column function and no GROUP BY clause is specified..
  SQLCODE=-119, SQLSTATE=42803, DRIVER=3.67.27

The query:

SELECT DAYNAME(created), app_id
FROM Annotation
WHERE app_id = 1 AND (created < CURRENT DATE - 7 DAYS)
GROUP BY DAYNAME(created) ORDER BY created

The problem has something to do with the GROUP BY statement. What is wrong with it?

Body:
I think the error is pretty clear -- appid is in the SELECT but not the GROUP BY.  The solution is that you need an aggregation function.  I would expect something like this:

SELECT DAYNAME(created), COUNT(*)
FROM Annotation a
WHERE app_id = 1 AND (created < CURRENT DATE - 7 DAYS)
GROUP BY DAYNAME(created)
ORDER BY MIN(created);


问:
how can I use FirstOrDefault()?
I have this code and I want to set a value to Viewdate when the expression returns no data:

```<code>ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;
</code>```

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

答:
If you first select the numeric column, FirstOrDefault will work as you intend, returning either a value or 0 (the default for numeric types):

```<code>ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1");
</code>```

If NumCoefficientFix is a nullable type, then use the ?? operator to convert the null into 0:

```<code>ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1") ?? 0;
</code>```

Selecting the NumCoefficientFix first is also (slightly) more efficient for LINQ-to-database queries, in that the SQL generated will select only that column.

ContentLicense: CC BY-SA 2.5

Title: how can I use FirstOrDefault()?

Body:
I have this code and I want to set a value to Viewdate when the expression returns no data:

ViewData["Fix"] = db.PreStatusViws.Where(c => c.LkpNameFix == "1").FirstOrDefault().NumCoefficientFix;

can I set zero or a "Text" for that? I no, what can I do?!
note: FirstOrDefault(null) cause an error.

Body:
If you first select the numeric column, FirstOrDefault will work as you intend, returning either a value or 0 (the default for numeric types):

ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1");

If NumCoefficientFix is a nullable type, then use the ?? operator to convert the null into 0:

ViewData["Fix"] = db.PreStatus
  .Select (c => c.NumCoefficientFix)
  .FirstOrDefault (c => c.LkpNameFox == "1") ?? 0;

Selecting the NumCoefficientFix first is also (slightly) more efficient for LINQ-to-database queries, in that the SQL generated will select only that column.


问:
Symfony 3.3 from 3.2: Compile Error: Cannot declare class Symfony\Bundle\SecurityBundle\Security\FirewallMap
I'm experiencing some problems since I updated from symfony 3.2 to 3.3, I got this error

```<code>Compile Error: Cannot declare class Symfony\Bundle\SecurityBundle\Security\FirewallMap, because the name is already in use
in classes.php (line 1709)
in ClassCollectionLoader.php (line 99)
at ClassCollectionLoader::load()in Kernel.php (line 428)
at Kernel->doLoadClassCache()in Kernel.php (line 112)
at Kernel->boot()in Kernel.php (line 168)
at Kernel->handle()in app_dev.php (line 12)
at {main}()in app_dev.php (line 0)
</code>```

It's interesting because I only got this error accesing app_dev.php through the browser, If I directly exeucte

```<code>php app_dev.php
</code>```

Then the error doesn't appear and I just get redirect to the login page as I am suppossed to

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://:/login" />

        <title>Redirecting to http://:/login</title>
    </head>
    <body>
        Redirecting to <a href="http://:/login">http://:/login</a>.
    </body>
</html>
</code>```

Commands work fine, I can clear the cache, debout routes...

Any ideas?

Thanks!

Update: here's the content of the app_dev.php

```<code><?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
</code>```

答: I solved this removing vendor/symfony folder and running composer update</p>

Body:
I'm experiencing some problems since I updated from symfony 3.2 to 3.3, I got this error

Compile Error: Cannot declare class Symfony\Bundle\SecurityBundle\Security\FirewallMap, because the name is already in use
in classes.php (line 1709)
in ClassCollectionLoader.php (line 99)
at ClassCollectionLoader::load()in Kernel.php (line 428)
at Kernel->doLoadClassCache()in Kernel.php (line 112)
at Kernel->boot()in Kernel.php (line 168)
at Kernel->handle()in app_dev.php (line 12)
at {main}()in app_dev.php (line 0)

It's interesting because I only got this error accesing app_dev.php through the browser, If I directly exeucte

php app_dev.php

Then the error doesn't appear and I just get redirect to the login page as I am suppossed to

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://:/login" />

        <title>Redirecting to http://:/login</title>

        Redirecting to http://:/login.

Commands work fine, I can clear the cache, debout routes...

Any ideas?

Thanks!

Update: here's the content of the app_dev.php

<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__.'/../app/autoload.php';
Debug::enable();

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);


问:
OpenAPI 3.0 mock generator
I am learning OpenAPI Specification. Are there any tools to mock an API based on an OpenAPI definition in YAML format?</p>

答:
I'm currently working to add support on Eclipse Vert.x for automatic request validation and security validation. Check out this blog post i wrote, you can find a complete guide on how to write a rest api service with eclipse vert.x and OAS3. You can also give a look to this gist, there's a complete example. Ping me if you want other infos.

I will add as soon as possible the generator for client and server for Vert.x (i'm waiting swagger-codegen support to OAS 3)

Title: OpenAPI 3.0 mock generator


问:
SciKit-Learn: Trouble with TfidfVectorizer
I'm trying to use TFIDF to get features from titles of text articles.  I'm doing the following:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
corpus_title = result_df['_title'].tolist()
tfidf_transformer_title = TfidfVectorizer(min_df = 1, ngram_range = (1,1), use_idf = True, stop_words='english')
tfidf_df_title = tfidf_transformer_title.fit_transform(corpus_title)
tfidf_df_title
</code>```

However, I get an error at this line:

```<code>----> 4 tfidf_df_title = tfidf_transformer_title.fit_transform(corpus_title)
</code>```

The error is:

```<code>    205
    206         if self.lowercase:
--> 207             return lambda x: strip_accents(x.lower())
    208         else:
    209             return strip_accents

AttributeError: 'NoneType' object has no attribute 'lower'
</code>```

I'm not sure how it's possible to get this error.  I checked the docs and it looks like TfidfVectorizer uses UTF-8 as its default encoding.

Any idea how to fix?

Thanks!

答:
try this:</p>

```<code>tfidf_transformer_title = TfidfVectorizer(min_df = 1,lowercase = False, ngram_range = (1,1), use_idf = True, stop_words='english')
</code>```

Body:
I'm trying to use TFIDF to get features from titles of text articles.  I'm doing the following:

from sklearn.feature_extraction.text import TfidfVectorizer
corpus_title = result_df['_title'].tolist()
tfidf_transformer_title = TfidfVectorizer(min_df = 1, ngram_range = (1,1), use_idf = True, stop_words='english')
tfidf_df_title = tfidf_transformer_title.fit_transform(corpus_title)
tfidf_df_title

However, I get an error at this line:

----> 4 tfidf_df_title = tfidf_transformer_title.fit_transform(corpus_title)

The error is:

    205
    206         if self.lowercase:
--> 207             return lambda x: strip_accents(x.lower())
    208         else:
    209             return strip_accents

AttributeError: 'NoneType' object has no attribute 'lower'

I'm not sure how it's possible to get this error.  I checked the docs and it looks like TfidfVectorizer uses UTF-8 as its default encoding.

Any idea how to fix?

Thanks!

Body:
try this:

tfidf_transformer_title = TfidfVectorizer(min_df = 1,lowercase = False, ngram_range = (1,1), use_idf = True, stop_words='english')


问:
android recyclerview load more item upon scrolling using volley
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.

Here is my code.

```<code>    private void populateRecycleView() {
    if (Utility.checkNetworkConnection(this)) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Searching...");
        progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
        progressDialog.setCancelable(false);
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            int count = 0;
                            while (count < jsonArray.length()) {
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                String firstName = jsonObject.getString("fName");
                                String secondName = jsonObject.getString("sName");
                                String email = jsonObject.getString("emailid");
                                String password = jsonObject.getString("pass");
                                String mobile = jsonObject.getString("mobile");
                                String bloodRt = jsonObject.getString("blood");
                                String age = jsonObject.getString("age");
                                String gender = jsonObject.getString("gender");
                                String country = jsonObject.getString("country");
                                String location = jsonObject.getString("location");
                                String latitude = jsonObject.getString("latitude");
                                String longitude = jsonObject.getString("longitude");
                                String profilePicFIleName = jsonObject.getString("picname");
                                String profilePicURL = jsonObject.getString("pic");

                                Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
                                        country, location, latitude, longitude, profilePicFIleName, profilePicURL);
                                donorsList.add(donor);
                                count++;
                            }
                            donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
                            recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
                            recyclerView.setHasFixedSize(true);
                            recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
                            recyclerView.setItemAnimator(new DefaultItemAnimator());
                            recyclerView.setAdapter(donorsAdapter);

                            donorsAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();

                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("bloodGroup", bloodGroup);
                return params;
            }
        };
        NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
    } else {
        Utility.checkNetworkConnectionFound(this);
    }
}
</code>```

And this is my RecyclerView  adapter...

```<code>public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {

private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;

public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
    this.context = context;
    this.donorList = donorList;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
            parent, false);
    return new CustomViewHolder(view);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {

    final Donor donor = donorList.get(position);
    String displayName = donor.getFirstName() + " " + donor.getSecondName();
    holder.tvDisplayName.setText(displayName);
    holder.tvEmailID.setText(donor.getEmail());

    String userProfileURL = donor.getProfilePicURL();
    if (!userProfileURL.equals("")) {
        Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
                into(holder.ivProfilePic);
    } else {
        holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
    }

    bloodGroup = donor.getBloodGroup();
    if (bloodGroup.equals("A+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
    else if (bloodGroup.equals("A-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
    else if (bloodGroup.equals("B+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
    else if (bloodGroup.equals("B-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
    else if (bloodGroup.equals("O+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
    else if (bloodGroup.equals("O-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
    else if (bloodGroup.equals("AB+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
    else if (bloodGroup.equals("AB-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);

    if(Utility.isNetworkEnabled){
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DisplayDonorDetails.class);
                intent.putExtra("donor", donor);
                context.startActivity(intent);
            }
        });
    }else {
        Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
    }

}

@Override
public int getItemCount() {
    if(donorList != null){
        return donorList.size();
    }else {
        return 0;
    }
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
    TextView tvDisplayName;
    TextView tvEmailID;
    ConstraintLayout constraintLayout;

    public CustomViewHolder(View itemView) {
        super(itemView);
        ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
        ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
        ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
        tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
        tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
        constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
    }
}

}
</code>```

答:
Finally, I sort this out. I have got an awesome tutorial from this blog.

http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.

I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.

Body:
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.

Here is my code.

    private void populateRecycleView() {
    if (Utility.checkNetworkConnection(this)) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Searching...");
        progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
        progressDialog.setCancelable(false);
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            int count = 0;
                            while (count < jsonArray.length()) {
                                JSONObject jsonObject = jsonArray.getJSONObject(count);

                                String firstName = jsonObject.getString("fName");
                                String secondName = jsonObject.getString("sName");
                                String email = jsonObject.getString("emailid");
                                String password = jsonObject.getString("pass");
                                String mobile = jsonObject.getString("mobile");
                                String bloodRt = jsonObject.getString("blood");
                                String age = jsonObject.getString("age");
                                String gender = jsonObject.getString("gender");
                                String country = jsonObject.getString("country");
                                String location = jsonObject.getString("location");
                                String latitude = jsonObject.getString("latitude");
                                String longitude = jsonObject.getString("longitude");
                                String profilePicFIleName = jsonObject.getString("picname");
                                String profilePicURL = jsonObject.getString("pic");

                                Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
                                        country, location, latitude, longitude, profilePicFIleName, profilePicURL);
                                donorsList.add(donor);
                                count++;
                            }
                            donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
                            recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
                            recyclerView.setHasFixedSize(true);
                            recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
                            recyclerView.setItemAnimator(new DefaultItemAnimator());
                            recyclerView.setAdapter(donorsAdapter);

                            donorsAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();

                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("bloodGroup", bloodGroup);
                return params;
            }
        };
        NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
    } else {
        Utility.checkNetworkConnectionFound(this);
    }
}

And this is my RecyclerView  adapter...

public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {

private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;

public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
    this.context = context;
    this.donorList = donorList;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
            parent, false);
    return new CustomViewHolder(view);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {

    final Donor donor = donorList.get(position);
    String displayName = donor.getFirstName() + " " + donor.getSecondName();
    holder.tvDisplayName.setText(displayName);
    holder.tvEmailID.setText(donor.getEmail());

    String userProfileURL = donor.getProfilePicURL();
    if (!userProfileURL.equals("")) {
        Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
                into(holder.ivProfilePic);
    } else {
        holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
    }

    bloodGroup = donor.getBloodGroup();
    if (bloodGroup.equals("A+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
    else if (bloodGroup.equals("A-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
    else if (bloodGroup.equals("B+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
    else if (bloodGroup.equals("B-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
    else if (bloodGroup.equals("O+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
    else if (bloodGroup.equals("O-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
    else if (bloodGroup.equals("AB+"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
    else if (bloodGroup.equals("AB-"))
        holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);

    if(Utility.isNetworkEnabled){
        holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, DisplayDonorDetails.class);
                intent.putExtra("donor", donor);
                context.startActivity(intent);
            }
        });
    }else {
        Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
    }

}

@Override
public int getItemCount() {
    if(donorList != null){
        return donorList.size();
    }else {
        return 0;
    }
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
    TextView tvDisplayName;
    TextView tvEmailID;
    ConstraintLayout constraintLayout;

    public CustomViewHolder(View itemView) {
        super(itemView);
        ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
        ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
        ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
        tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
        tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
        constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
    }
}

}


问:
Defining variable inside a tag attribute for JSF template
Is it possible to do in my template something like:

```<code><shiro:hasPermission name="<ui:insert name="pagepermission"></ui:insert>">
</code>```

And then optionally define the pagepermission in each page?

EDIT

So I need to write the following in my template.xhtml:

```<code><shiro:hasPermission name="my string">
</code>```

Where "my string" is defined in any page X.xhtml that uses the template. Writing a variable in my template coming from X.xhtml works fine if I define a variable var in page X.xthml and I just use:

```<code><ui:insert name="var"></ui:insert>
</code>```

in the template. However, since I need to write that variable inside an attribute (i.e. inside <shiro:hasPermission name="**HERE**">, then JSF complains.

答:
You could use wrap the content within some container, then use the rendered attribute:

```<code><h:panelGroup rendered="#{hasPermission}">
    <ui:insert name="pagepermission" />
</h:panelGroup>
</code>```

For even better reuse, you could create your own custom component. See JSF 2 fu, Part 2: Templating and composite components

Body:
Is it possible to do in my template something like:

<shiro:hasPermission name="<ui:insert name="pagepermission"></ui:insert>">

And then optionally define the pagepermission in each page?

EDIT

So I need to write the following in my template.xhtml:

<shiro:hasPermission name="my string">

Where "my string" is defined in any page X.xhtml that uses the template. Writing a variable in my template coming from X.xhtml works fine if I define a variable var in page X.xthml and I just use:

<ui:insert name="var"></ui:insert>

in the template. However, since I need to write that variable inside an attribute (i.e. inside <shiro:hasPermission name="**HERE**">, then JSF complains.

Body:
You could use wrap the content within some container, then use the rendered attribute:

<h:panelGroup rendered="#{hasPermission}">
    <ui:insert name="pagepermission" />
</h:panelGroup>

For even better reuse, you could create your own custom component. See JSF 2 fu, Part 2: Templating and composite components


问:
How do I get @vimeo/player to work on my Angular2/Typescript project?

Question:

How do I get @vimeo/player to work on my Angular2/Typescript project (specifically Ionic2) ?

Description:

Trying to get the vimeo player to work with Angular2/Typescript.

```<code>npm install --save @vimeo/player
</code>```

According to their documentation the library can be used like so:

If you’re using a module bundler like webpack or rollup, the exported
  object will be the Player constructor (unlike the browser where it is
  attached to window.Vimeo):

```<code>import Player from '@vimeo/player';

const player = new Player('handstick', {
    id: 19231868,
    width: 640
});

player.on('play', function() {
    console.log('played the video!');
});
</code>```

Which looks super promising ! But doesn't work.

What I've tried:

I've installed @vimeo/player and @types/vimeo__player
I created a player component in my Ionic2 app.

player.ts:

```<code>import {Component, ViewChild} from '@angular/core';
import {NavController} from "ionic-angular/index";

//noinspection TypeScriptCheckImport,TypeScriptCheckImport
import Player from "@vimeo/player";

@Component({
  selector: 'player-component',
  templateUrl: 'player.html'
})
export class PlayerComponent {

  @ViewChild('player_container') playerContainer;
  private player: Player;

  constructor(public navCtrl: NavController){}

  ngAfterViewInit() {
    // child is set
    this.player = new Player(this.playerContainer);
    console.log(Player);
  }

}
</code>```

I use view child, but I've also tried with the element's ID.

player.html

```<code><div #player_container></div>
</code>```

And get the following error:

Uncaught (in promise): TypeError: You must pass either a valid element
  or a valid id. Player@http://localhost:8100/build/main.js:102846:32
  ngAfterViewInit@http://localhost:8100/build/main.js:74715:80
  callProviderLifecycles@http://localhost:8100/build/main.js:11417:33
  callElementProvidersLifecycles@http://localhost:8100/build/main.js:11392:35
  callLifecycleHooksChildrenFirst@http://localhost:8100/build/main.js:11376:47
  checkAndUpdateView@http://localhost:8100/build/main.js:12408:36
  callWithDebugContext@http://localhost:8100/build/main.js:13462:47
  detectChanges@http://localhost:8100/build/main.js:10474:81
  _viewAttachToDOM@http://localhost:8100/build/main.js:43884:53 _transition@http://localhost:8100/build/main.js:43976:34 onInvoke@http://localhost:8100/build/main.js:4406:43
  run@http://localhost:8100/build/polyfills.js:3:4146
  http://localhost:8100/build/polyfills.js:3:13734
  onInvokeTask@http://localhost:8100/build/main.js:4397:47
  runTask@http://localhost:8100/build/polyfills.js:3:4841
  o@http://localhost:8100/build/polyfills.js:3:1898
  invoke@http://localhost:8100/build/polyfills.js:3:10674

As you can see it compiles but crashes at runtime.

@types/vimeo__player Just doesn't seem to be finished, and doesn't even seem to be noticed when I import @vimeo/player

The issue on github regarding vimeo__player seems show that this is true.

It looks like module resolution is correctly resolving it as a JS
  module, but only because it didn't find the types first. Are you sure
  you've correctly included those types? --listFiles would show you if
  it's lincluded.

Extras:

Issued opened on Vimeo's github player page.

答:
For a standard typescript project this import statement works.</p>

```<code>import * as Player from "@vimeo/player/dist/player.js";
</code>```

Body:
Question:

How do I get @vimeo/player to work on my Angular2/Typescript project (specifically Ionic2) ?

Description:

Trying to get the vimeo player to work with Angular2/Typescript.

npm install --save @vimeo/player

According to their documentation the library can be used like so:

If you’re using a module bundler like webpack or rollup, the exported
  object will be the Player constructor (unlike the browser where it is
  attached to window.Vimeo):

import Player from '@vimeo/player';

const player = new Player('handstick', {
    id: 19231868,
    width: 640
});

player.on('play', function() {
    console.log('played the video!');
});

Which looks super promising ! But doesn't work.

What I've tried:

I've installed @vimeo/player and @types/vimeo__player
I created a player component in my Ionic2 app.

player.ts:

import {Component, ViewChild} from '@angular/core';
import {NavController} from "ionic-angular/index";

//noinspection TypeScriptCheckImport,TypeScriptCheckImport
import Player from "@vimeo/player";

@Component({
  selector: 'player-component',
  templateUrl: 'player.html'
})
export class PlayerComponent {

  @ViewChild('player_container') playerContainer;
  private player: Player;

  constructor(public navCtrl: NavController){}

  ngAfterViewInit() {
    // child is set
    this.player = new Player(this.playerContainer);
    console.log(Player);
  }

}

I use view child, but I've also tried with the element's ID.

player.html

And get the following error:

Uncaught (in promise): TypeError: You must pass either a valid element
  or a valid id. Player@http://localhost:8100/build/main.js:102846:32
  ngAfterViewInit@http://localhost:8100/build/main.js:74715:80
  callProviderLifecycles@http://localhost:8100/build/main.js:11417:33
  callElementProvidersLifecycles@http://localhost:8100/build/main.js:11392:35
  callLifecycleHooksChildrenFirst@http://localhost:8100/build/main.js:11376:47
  checkAndUpdateView@http://localhost:8100/build/main.js:12408:36
  callWithDebugContext@http://localhost:8100/build/main.js:13462:47
  detectChanges@http://localhost:8100/build/main.js:10474:81
  _viewAttachToDOM@http://localhost:8100/build/main.js:43884:53 _transition@http://localhost:8100/build/main.js:43976:34 onInvoke@http://localhost:8100/build/main.js:4406:43
  run@http://localhost:8100/build/polyfills.js:3:4146
  http://localhost:8100/build/polyfills.js:3:13734
  onInvokeTask@http://localhost:8100/build/main.js:4397:47
  runTask@http://localhost:8100/build/polyfills.js:3:4841
  o@http://localhost:8100/build/polyfills.js:3:1898
  invoke@http://localhost:8100/build/polyfills.js:3:10674

As you can see it compiles but crashes at runtime.

@types/vimeo__player Just doesn't seem to be finished, and doesn't even seem to be noticed when I import @vimeo/player

The issue on github regarding vimeo__player seems show that this is true.

It looks like module resolution is correctly resolving it as a JS
  module, but only because it didn't find the types first. Are you sure
  you've correctly included those types? --listFiles would show you if
  it's lincluded.

Extras:

Issued opened on Vimeo's github player page.

Body:
For a standard typescript project this import statement works.

import * as Player from "@vimeo/player/dist/player.js";


问:
How do I build this block matrix in python?
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

```<code>1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1
</code>```

For 3 points the matrix is

```<code>1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1
</code>```

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

答:
Here is code that will work for you:

```<code>import string
n = 3
letters = string.ascii_lowercase
block1 = letters[:4]
block2 = letters[4:8]
matrix = [[1 if b == 0 and i == 0 or b == 2*n+1 and i == 2*n + 1 else 0 for b in range(2*n+2)] for i in range(2*n+2)]
count = 0

for i, a in enumerate(matrix[1:-1]): #fix to account for the fact that we are starting at 2, not 0

    if i%2 == 0:
        matrix[i+1][count:count+4] = list(block1)

    else:
        matrix[i+1][count:count+4] = list(block2)

        count += 2

for i in matrix:
    print i
</code>```

Output for when n == 3:

```<code>[1, 0, 0, 0, 0, 0, 0, 0]
['a', 'b', 'c', 'd', 0, 0, 0, 0]
['e', 'f', 'g', 'h', 0, 0, 0, 0]
[0, 0, 'a', 'b', 'c', 'd', 0, 0]
[0, 0, 'e', 'f', 'g', 'h', 0, 0]
[0, 0, 0, 0, 'a', 'b', 'c', 'd']
[0, 0, 0, 0, 'e', 'f', 'g', 'h']
[0, 0, 0, 0, 0, 0, 0, 1]
</code>```

Output for when n == 2:

```<code>[1, 0, 0, 0, 0, 0]
['a', 'b', 'c', 'd', 0, 0]
['e', 'f', 'g', 'h', 0, 0]
[0, 0, 'a', 'b', 'c', 'd']
[0, 0, 'e', 'f', 'g', 'h']
[0, 0, 0, 0, 0, 1]
</code>```

I realize that you are not actually using the strings "a", "b", "c", etc., but when you want to use variables, replace block1 with a list of your first four variables and block2 with a list of your last four variables.

Body:
I want to build a block matrix for a system of equation with n points.
The result is an (2n+2)x(2n+2) matrix. In example, for 2 points the matrix is:

1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1

For 3 points the matrix is

1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1

Here, a, b, c, d, e, f, g, h are float values known ahead of time.
But I don't know value of n ahead of time. Is there a library in python to do this? I've looked at scipy.sparse.diag, scipy.linalg.block_diag and numpy.bat, but these do not achieve what I want.

Body:
Here is code that will work for you:

import string
n = 3
letters = string.ascii_lowercase
block1 = letters[:4]
block2 = letters[4:8]
matrix = [[1 if b == 0 and i == 0 or b == 2*n+1 and i == 2*n + 1 else 0 for b in range(2*n+2)] for i in range(2*n+2)]
count = 0

for i, a in enumerate(matrix[1:-1]): #fix to account for the fact that we are starting at 2, not 0

    if i%2 == 0:
        matrix[i+1][count:count+4] = list(block1)

    else:
        matrix[i+1][count:count+4] = list(block2)

        count += 2

for i in matrix:
    print i

Output for when n == 3:

[1, 0, 0, 0, 0, 0, 0, 0]
['a', 'b', 'c', 'd', 0, 0, 0, 0]
['e', 'f', 'g', 'h', 0, 0, 0, 0]
[0, 0, 'a', 'b', 'c', 'd', 0, 0]
[0, 0, 'e', 'f', 'g', 'h', 0, 0]
[0, 0, 0, 0, 'a', 'b', 'c', 'd']
[0, 0, 0, 0, 'e', 'f', 'g', 'h']
[0, 0, 0, 0, 0, 0, 0, 1]

Output for when n == 2:

[1, 0, 0, 0, 0, 0]
['a', 'b', 'c', 'd', 0, 0]
['e', 'f', 'g', 'h', 0, 0]
[0, 0, 'a', 'b', 'c', 'd']
[0, 0, 'e', 'f', 'g', 'h']
[0, 0, 0, 0, 0, 1]

I realize that you are not actually using the strings "a", "b", "c", etc., but when you want to use variables, replace block1 with a list of your first four variables and block2 with a list of your last four variables.


问:
Faster matching code
I have a code that takes a list of Airline flightlegs and matches them up to give me full lines of flight.  The code works but.....  it takes a very long time (45-60 min for just 35,000 rows) due to the amount of data it has to go through.  This is compounded and the overall code takes about 2 hours to run.  Is there a faster method to get the same results?

Here is my current code that really bogs down the entire process:

```<code>Sub BuildingLines()
'strings together segments into trip

Dim i As Long
Dim z As Long
Dim T As Long
Dim c As Long
Dim a As Long
Dim f As Long
Dim l As Long
Dim g As Long

Dim y As String
Dim b As String

Set ref = Sheets("Ref")

With Sheets("MoveData")
z = .Cells(1, 1).End(xlDown).Row
x = .Cells(2, 1).End(xlToRight).Column
Range(.Cells(1, 3), (.Cells(z, x + 3))).Clear
z = .Cells(1, 1).End(xlDown).Row
g = ref.Cells(24, 1).End(xlDown).Row

For a = 24 To g

    If ref.Cells(a, 2) = "" Then GoTo nexta

    f = ref.Cells(a, 2)
    c = ref.Cells(a, 3)
    l = ref.Cells(a, 4)
    Set LegTable = Range(.Cells(f, 1), .Cells(l, 1))

    For i = f To l

        Application.StatusBar = "Progress: Step 5 of 20 - Building lines for " & ref.Cells(a, 1) & " (" & (a - 23) & " A/C types of " & (g - 23) & ") : " & (i - f) + 1 & " Legs of " & c & " analyzed. (" & Format(((i - f) + 1) / c, "Percent") & ")"
    DoEvents

    'On Error GoTo NextI

    If IsError(Application.Match(.Cells(i, 2), LegTable, 0)) Then
        GoTo nexti

    Else
            y = Application.Match(.Cells(i, 2), LegTable, 0) + f - 1
            .Cells(i, 1).End(xlToRight).Offset(0, 1).Value2 = .Cells(y, 2)

                Do
                'On Error GoTo NextI
                If IsError(Application.Match(.Cells(y, 2), LegTable, 0)) Then

                GoTo nexti
                Else
                    b = Application.Match(.Cells(y, 2), LegTable, 0) + f - 1
                    h = .Cells(b, 2)
                    .Cells(i, 1).End(xlToRight).Offset(0, 1) = h
                    y = b
                End If
                Loop
nexti:

        End If

    b = ""
    y = ""

    Next i
nexta:
Next a
End With
End Sub
</code>```

The data is all string data of about 50+ chars.

Thank you for any recomendations.

答:
Thank you very much A.S.H.  with your help, I not only learned alot about using arrays, but also ended up cutting my runtime from about 90 minutes to just over 3 minutes.  This is my final working code that used a combination of your suggestions.

```<code>Sub BuildingLines()
'strings together segments into trip

Dim i As Long
Dim z As Long
Dim c As Long
Dim f As Long
Dim l As Long
Dim LegTable As Range
Dim TurnTable As Range
Dim FirstTurn() As Variant
Dim NextTurn() As Variant
Dim y As String
Dim b As String
Dim FTtext As String
Dim wb As Workbook
Dim ref As Worksheet

Set wb = ThisWorkbook
Set ref = wb.Sheets("Ref")

With Sheets("MoveData")
z = .Cells(1, 1).End(xlDown).Row
x = .Cells(2, 1).End(xlToRight).Column
Range(.Cells(1, 3), (.Cells(z, x + 3))).Clear
z = .Cells(1, 1).End(xlDown).Row
g = ref.Cells(24, 1).End(xlDown).Row

For a = 24 To g

    If ref.Cells(a, 2) = "" Then GoTo NextA

    f = ref.Cells(a, 2)
    c = ref.Cells(a, 3)
    l = ref.Cells(a, 4)
    Set LegTable = Range(.Cells(f, 1), .Cells(l, 1))
    Set TurnTable = Range(.Cells(f, 1), .Cells(l, 2))

    FirstTurn = TurnTable

        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=LegTable, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With .Sort
        .SetRange TurnTable
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    For i = f To l

        Application.StatusBar = "Progress: Step 5 of 20 - Building lines for " & ref.Cells(a, 1) & " (" & (a - 23) & " A/C types of " & (g - 23) & ") : " & (i - f) + 1 & " Legs of " & c & " analyzed. (" & Format(((i - f) + 1) / c, "Percent") & ")"
    DoEvents

    y = 0
    b = 0

        y = Application.Match(.Cells(i, 2), LegTable, 1)
        If .Cells(i, 2) <> FirstTurn(y, 1) Then GoTo NextI

        NextLeg = NextLeg + 1
        ReDim Preserve NextTurn(0, 1 To NextLeg)
        NextTurn(0, NextLeg) = FirstTurn(y, 2)

            Do
                FTtext = FirstTurn(y, 2)
                On Error GoTo errhdlr
                b = Application.WorksheetFunction.Match(FTtext, LegTable, 1)
                If FTtext <> FirstTurn(b, 1) Then GoTo NextI

                NextLeg = NextLeg + 1
                ReDim Preserve NextTurn(0, 1 To NextLeg)
                NextTurn(0, NextLeg) = FirstTurn(b, 2)
                y = b
            Loop

errhdlr:
    Resume NextI
NextI:

    If NextLeg > 0 Then Range(.Cells(i, 3), .Cells(i, NextLeg + 2)).Value = NextTurn
    Erase NextTurn
    NextLeg = 0
    Next i

Set LegTable = Nothing
Set TurnTable = Nothing
Erase NextTurn
Erase FirstTurn

NextA:
Next a
End With

End Sub
</code>```

I first tried using just the arrays, but the Match function was WAY SLOWER in the arrays.  So I ended up using the Match to find the index and then grabbed the data from the array to build my second array which then became my output.  I can't wait to adapt my new found knowledge with the rest of this project and cut my runtime from 2+ hours to just minutes!! Thanks, again!!!

Title: Faster matching code

Body:
I have a code that takes a list of Airline flightlegs and matches them up to give me full lines of flight.  The code works but.....  it takes a very long time (45-60 min for just 35,000 rows) due to the amount of data it has to go through.  This is compounded and the overall code takes about 2 hours to run.  Is there a faster method to get the same results?

Here is my current code that really bogs down the entire process:

Sub BuildingLines()
'strings together segments into trip

Dim i As Long
Dim z As Long
Dim T As Long
Dim c As Long
Dim a As Long
Dim f As Long
Dim l As Long
Dim g As Long

Dim y As String
Dim b As String

Set ref = Sheets("Ref")

With Sheets("MoveData")
z = .Cells(1, 1).End(xlDown).Row
x = .Cells(2, 1).End(xlToRight).Column
Range(.Cells(1, 3), (.Cells(z, x + 3))).Clear
z = .Cells(1, 1).End(xlDown).Row
g = ref.Cells(24, 1).End(xlDown).Row

For a = 24 To g

    If ref.Cells(a, 2) = "" Then GoTo nexta

    f = ref.Cells(a, 2)
    c = ref.Cells(a, 3)
    l = ref.Cells(a, 4)
    Set LegTable = Range(.Cells(f, 1), .Cells(l, 1))

    For i = f To l

        Application.StatusBar = "Progress: Step 5 of 20 - Building lines for " & ref.Cells(a, 1) & " (" & (a - 23) & " A/C types of " & (g - 23) & ") : " & (i - f) + 1 & " Legs of " & c & " analyzed. (" & Format(((i - f) + 1) / c, "Percent") & ")"
    DoEvents

    'On Error GoTo NextI

    If IsError(Application.Match(.Cells(i, 2), LegTable, 0)) Then
        GoTo nexti

    Else
            y = Application.Match(.Cells(i, 2), LegTable, 0) + f - 1
            .Cells(i, 1).End(xlToRight).Offset(0, 1).Value2 = .Cells(y, 2)

                Do
                'On Error GoTo NextI
                If IsError(Application.Match(.Cells(y, 2), LegTable, 0)) Then

                GoTo nexti
                Else
                    b = Application.Match(.Cells(y, 2), LegTable, 0) + f - 1
                    h = .Cells(b, 2)
                    .Cells(i, 1).End(xlToRight).Offset(0, 1) = h
                    y = b
                End If
                Loop
nexti:

        End If

    b = ""
    y = ""

    Next i
nexta:
Next a
End With
End Sub

The data is all string data of about 50+ chars.

Thank you for any recomendations.

Body:
Thank you very much A.S.H.  with your help, I not only learned alot about using arrays, but also ended up cutting my runtime from about 90 minutes to just over 3 minutes.  This is my final working code that used a combination of your suggestions.

Sub BuildingLines()
'strings together segments into trip

Dim i As Long
Dim z As Long
Dim c As Long
Dim f As Long
Dim l As Long
Dim LegTable As Range
Dim TurnTable As Range
Dim FirstTurn() As Variant
Dim NextTurn() As Variant
Dim y As String
Dim b As String
Dim FTtext As String
Dim wb As Workbook
Dim ref As Worksheet

Set wb = ThisWorkbook
Set ref = wb.Sheets("Ref")

With Sheets("MoveData")
z = .Cells(1, 1).End(xlDown).Row
x = .Cells(2, 1).End(xlToRight).Column
Range(.Cells(1, 3), (.Cells(z, x + 3))).Clear
z = .Cells(1, 1).End(xlDown).Row
g = ref.Cells(24, 1).End(xlDown).Row

For a = 24 To g

    If ref.Cells(a, 2) = "" Then GoTo NextA

    f = ref.Cells(a, 2)
    c = ref.Cells(a, 3)
    l = ref.Cells(a, 4)
    Set LegTable = Range(.Cells(f, 1), .Cells(l, 1))
    Set TurnTable = Range(.Cells(f, 1), .Cells(l, 2))

    FirstTurn = TurnTable

        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=LegTable, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With .Sort
        .SetRange TurnTable
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    For i = f To l

        Application.StatusBar = "Progress: Step 5 of 20 - Building lines for " & ref.Cells(a, 1) & " (" & (a - 23) & " A/C types of " & (g - 23) & ") : " & (i - f) + 1 & " Legs of " & c & " analyzed. (" & Format(((i - f) + 1) / c, "Percent") & ")"
    DoEvents

    y = 0
    b = 0

        y = Application.Match(.Cells(i, 2), LegTable, 1)
        If .Cells(i, 2) <> FirstTurn(y, 1) Then GoTo NextI

        NextLeg = NextLeg + 1
        ReDim Preserve NextTurn(0, 1 To NextLeg)
        NextTurn(0, NextLeg) = FirstTurn(y, 2)

            Do
                FTtext = FirstTurn(y, 2)
                On Error GoTo errhdlr
                b = Application.WorksheetFunction.Match(FTtext, LegTable, 1)
                If FTtext <> FirstTurn(b, 1) Then GoTo NextI

                NextLeg = NextLeg + 1
                ReDim Preserve NextTurn(0, 1 To NextLeg)
                NextTurn(0, NextLeg) = FirstTurn(b, 2)
                y = b
            Loop

errhdlr:
    Resume NextI
NextI:

    If NextLeg > 0 Then Range(.Cells(i, 3), .Cells(i, NextLeg + 2)).Value = NextTurn
    Erase NextTurn
    NextLeg = 0
    Next i

Set LegTable = Nothing
Set TurnTable = Nothing
Erase NextTurn
Erase FirstTurn

NextA:
Next a
End With

End Sub

I first tried using just the arrays, but the Match function was WAY SLOWER in the arrays.  So I ended up using the Match to find the index and then grabbed the data from the array to build my second array which then became my output.  I can't wait to adapt my new found knowledge with the rest of this project and cut my runtime from 2+ hours to just minutes!! Thanks, again!!!


问:
Replacing Golang standard package and calling the original within
Assume that there is a special hardware that can make
certain standard library functionality faster.

Hardware might be present or not.

I can write a package that would utilize this hardware with the same
function signatures as in the standard one, but it will force all the applications and other packages to decide which package to import based on the availability of the hardware on the specific target. At build time and with code modifications in all the applications and packages.

Ideally, I would prefer to make the decision of which package to use at runtime and without requiring applications to change their imports.

The package would check for the availability of the hardware and would either use it or execute standard functionality instead.

Is there any way to achieve it?

Any other ways to "intercept" the calls to the standard package functions?

答: It sounds like you're talking about a library that will be used by other applications. You can't (thankfully!) modify the standard library this way - otherwise just importing a package could have incredibly broad and potentially disastrous side-effects. If you want to apply some special hardware-specific optimizations to the standard library, for use by other people in a broad range of projects, your best bet is to make your changes to the standard library and submit a patch.</p>


问:
Mysql query issues when passing string or date
I have a mysql query that works fine in phpmyadmin, but does not give the expected results on my php page.  I am sure that I have something wrong in the code.

Here is the php code that passes the variable

```<code>print "<td><a href='transactions_by_transaction_date.php?var=\''".urlencode(
$row['transaction_date'])."'\''>".$row['transaction_date']."</a></td></tr><tr>";
</code>```

And here is where I create my query

```<code>$var = $_GET['var'];
echo $var;
$stmt2 = $db->prepare("SELECT * FROM bo_transactions WHERE
transaction_date=:var ORDER BY transaction_id");
$stmt2->bindParam(':var',$var,PDO::PARAM_STR);
$stmt2->execute();
// set the resulting array to associative
$result = $stmt2->setFetchMode(PDO::FETCH_ASSOC);
</code>```

I have the echo $var line to verify that it is passing the correct date and it appears to be.  The field transaction_date is a date type.

What have I missed?

答:
I thing you have issue in single quotes and double quotes data passing

Just use this one

```<code>print "<td><a href='transactions_by_transaction_date.php?var='".urlencode($
row['transaction_date'])."'>".$row['transaction_date']."</a></td></tr><tr>";
</code>```

Body:
I have a mysql query that works fine in phpmyadmin, but does not give the expected results on my php page.  I am sure that I have something wrong in the code.

Here is the php code that passes the variable

print "".$row['transaction_date']."

";

And here is where I create my query

$var = $_GET['var'];
echo $var;
$stmt2 = $db->prepare("SELECT * FROM bo_transactions WHERE
transaction_date=:var ORDER BY transaction_id");
$stmt2->bindParam(':var',$var,PDO::PARAM_STR);
$stmt2->execute();
// set the resulting array to associative
$result = $stmt2->setFetchMode(PDO::FETCH_ASSOC);

I have the echo $var line to verify that it is passing the correct date and it appears to be.  The field transaction_date is a date type.

What have I missed?

Body:
I thing you have issue in single quotes and double quotes data passing

Just use this one

print "<td><a href='transactions_by_transaction_date.php?var='".urlencode($
row['transaction_date'])."'>".$row['transaction_date']."</a></td></tr><tr>";


问:
Browser-Sync does not Sync HTML and CSS files at once
I have a HTML file named index.html and a CSS file named style.cssin a directory named CSS3 for everybody like so.

C:\Users\a\Desktop\Web-Design for everybody specialization\CSS3 for everybody

I am trying to make Browser-Sync recognize that there is a .html and a .css file by running browser-sync start --server 'CSS3 for everybody' --files 'CSS3 for everybody' but nothing happens. It says "Connected to Browser Sync" and the page remains the same.

答:
Browser-Sync was confused due to incorrect file name in the <link> tag.

Earlier it was <link rel="stylesheet" type="text/css" href="style1.css">

After changing it to <link rel="stylesheet" type="text/css" href="style.css"> CSS started getting injected.


问:
Stored Procedure Parameter Type
I have a question about the in parameter type of a stored procedure. Normally the definition of a parameter will look like this:

```<code>in param_test VARCHAR(100)
</code>```

Do you know if I can defined a parameter like this?:

```<code>in param_test table.column%type
</code>```

This way the parameter will be the same type as the column of an specific table. So if the column type change from varchar(100) to varchar(250) I don't have to change the parameter type in the stored procedure.

I know It's possible in Oracle, but I don't know if it is in MySQL.

Thank you very much for your time and help.

Regards.

答:
how to pass parameter value to database of text datatype..
i am using this code
mysql_CommandLtp.Parameters.Add("@prmName", MySqlDbType.Text);
mysql_CommandLtp.Parameters["@prmName"].Value = prmName.ToString().Trim();</p>

Title: Stored Procedure Parameter Type

Body:
I have a question about the in parameter type of a stored procedure. Normally the definition of a parameter will look like this:

in param_test VARCHAR(100)

Do you know if I can defined a parameter like this?:

in param_test table.column%type

This way the parameter will be the same type as the column of an specific table. So if the column type change from varchar(100) to varchar(250) I don't have to change the parameter type in the stored procedure.

I know It's possible in Oracle, but I don't know if it is in MySQL.

Thank you very much for your time and help.

Regards.


问:
Appending a div onclick
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button></code>```

答:
The issue is the
 you append to .appendme also has a class of .appendme. So when you click the button, the new
 is being appended to every other new
 that has been appended.

To fix this, remove the class or rename the class of the new
 being appended.

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button></code>```

Title: Appending a div onclick

Body:
I have a button and a div, i want to append this div once every time i click on the button, but i have a problem, the HTML code for this div is very large and i don't want that, so my question is there another method to append this div without putting the whole code in my js code? and another problem i want to append the div once only on each click but it appends it multiple times, Here is an example of what I'm talking about, i replaced my large HTML code with a small one, so here is my code:

$(".appendbtn").click(function () {
   $(".appendme").append('
The div that should be appended
');
});

The div that should be appended

<button class="appendbtn" type="button">Click to append</button>

Body:
The issue is the <div> you append to .appendme also has a class of .appendme. So when you click the button, the new <div> is being appended to every other new <div class="appendme"> that has been appended.

To fix this, remove the class or rename the class of the new <div> being appended.

$(".appendbtn").click(function () {
   $(".appendme").append('<div>The div that should be appended</div>');
});

<script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button>


问:
how to disable a tab in android screen?
hi can you tell me how to disable a tab in the UI of android code.. (eclair code)</p>

答:
If you mean to disable one tab button on TabWidget, then try this code:

```<code>// tabHost = ... (get TabHost)
tabHost.getTabWidget().getChildTabViewAt(your_index).setEnabled(false);
</code>```

If you want to disable tab widget in overall, then:

```<code>// tabWidget = ... (get TabWidget)
tabWidget.setEnabled(false);
</code>```

Read SDK Help for references:

TabHost

TabWidget

Title: how to disable a tab in android screen?

Body:
If you mean to disable one tab button on TabWidget, then try this code:

// tabHost = ... (get TabHost)
tabHost.getTabWidget().getChildTabViewAt(your_index).setEnabled(false);

If you want to disable tab widget in overall, then:

// tabWidget = ... (get TabWidget)
tabWidget.setEnabled(false);

Read SDK Help for references:

TabHost

TabWidget


问:
Duplicating an image from a file path, changing name and saving it to a different table in laravel
I have a file path on a table, what I am trying to do is create the image from the file path and then save the 'new' file with a different name.

Because I have only the file path, I do not now how to create the image object so that I can then getClientOriginalExtension(); and save that to the database. I have tried the following:

```<code>$img = $var->image_path;
$file = file_get_contents($img);
$filename = time() . '.' . $file->getExtension();

Image::make($file)->resize(300, 300)->save( public_path('/test' . $filename ) );
</code>```

However the script errors: Call to a member function getExtension() on string what would be the right way with the file path, create the object, change the name of the file, ensure the right extension is set (maybe outside scope of this q) and then save the newly created image to a different folder and save the newly created image path to the database.

I hope that makes sense.

Update: should I use file_put_contents() instead?

答:
Achieved what I wanted using the copy() and iterating over each image and adjusting the image relatively.

```<code>$title = $var->name;
$string = str_replace(' ', '-', $title); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

copy($img, public_path('/test' . $string . time()));
</code>```

http://php.net/manual/en/function.copy.php

Body:
I have a file path on a table, what I am trying to do is create the image from the file path and then save the 'new' file with a different name.

Because I have only the file path, I do not now how to create the image object so that I can then getClientOriginalExtension(); and save that to the database. I have tried the following:

$img = $var->image_path;
$file = file_get_contents($img);
$filename = time() . '.' . $file->getExtension();

Image::make($file)->resize(300, 300)->save( public_path('/test' . $filename ) );

However the script errors: Call to a member function getExtension() on string what would be the right way with the file path, create the object, change the name of the file, ensure the right extension is set (maybe outside scope of this q) and then save the newly created image to a different folder and save the newly created image path to the database.

I hope that makes sense.

Update: should I use file_put_contents() instead?

Body:
Achieved what I wanted using the copy() and iterating over each image and adjusting the image relatively.

$title = $var->name;
$string = str_replace(' ', '-', $title); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

copy($img, public_path('/test' . $string . time()));

http://php.net/manual/en/function.copy.php


问:
C# Identify parent,child elements in XML file
I found this on internet.

```<code>string xml = @"
<food>
  <child>
    <nested />
  </child>
  <child>
    <other>
    </other>
  </child>
</food>
";

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
  if (rdr.NodeType == XmlNodeType.Element)
  {
  Console.WriteLine(rdr.LocalName);
  }
}
</code>```

The result of the above will be

```<code>food
child
nested
child
other
</code>```

This is working perfect, Just i need to identify which elements contains child elements.

for example, I need this output

```<code>startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food
</code>```

答:
You can do this with XmlReader, but it won't be particularly easy. You can't know if an element has children without continuing to read further, so you'd have to buffer and track various things (as XmlReader is forward-only). Unless you have a good reason to use such a low level API then I'd strongly suggest you avoid it.

This is fairly trivial with LINQ to XML

```<code>private static void Dump(XElement element, int level)
{
    var space = new string(' ', level * 4);

    if (element.HasElements)
    {
        Console.WriteLine("{0}startParent_{1}", space, element.Name);

        foreach (var child in element.Elements())
        {
            Dump(child, level + 1);
        }

        Console.WriteLine("{0}endParent_{1}", space, element.Name);
    }
    else
    {
        Console.WriteLine("{0}{1}", space, element.Name);
    }
}
</code>```

If, as you imply in your comment, your actual requirement is to modify some values then you can do this without any need to process the details of the XML structure. For example, to modify the value of your nested element:

```<code>var doc = XDocument.Parse(xml);

var target = doc.Descendants("nested").Single();

target.Value = "some text";

var result = doc.ToString();
</code>```

See this fiddle for a demo of both.

Body:
I found this on internet.

string xml = @"
<food>
  <child>
    <nested />
  </child>
  <child>
    <other>
    </other>
  </child>
</food>
";

XmlReader rdr = XmlReader.Create(new System.IO.StringReader(xml));
while (rdr.Read())
{
  if (rdr.NodeType == XmlNodeType.Element)
  {
  Console.WriteLine(rdr.LocalName);
  }
}

The result of the above will be

food
child
nested
child
other

This is working perfect, Just i need to identify which elements contains child elements.

for example, I need this output

startParent_food
    startParent_child
        nested
    endParent_child
    startParent_child
        other
    endParent_child
endParent_food

Body:
You can do this with XmlReader, but it won't be particularly easy. You can't know if an element has children without continuing to read further, so you'd have to buffer and track various things (as XmlReader is forward-only). Unless you have a good reason to use such a low level API then I'd strongly suggest you avoid it.

This is fairly trivial with LINQ to XML

private static void Dump(XElement element, int level)
{
    var space = new string(' ', level * 4);

    if (element.HasElements)
    {
        Console.WriteLine("{0}startParent_{1}", space, element.Name);

        foreach (var child in element.Elements())
        {
            Dump(child, level + 1);
        }

        Console.WriteLine("{0}endParent_{1}", space, element.Name);
    }
    else
    {
        Console.WriteLine("{0}{1}", space, element.Name);
    }
}

If, as you imply in your comment, your actual requirement is to modify some values then you can do this without any need to process the details of the XML structure. For example, to modify the value of your nested element:

var doc = XDocument.Parse(xml);

var target = doc.Descendants("nested").Single();

target.Value = "some text";

var result = doc.ToString();

See this fiddle for a demo of both.


问:
Is there any method of making local 'defonce'? (Clojure)
Let's say I need to make a simple counter and I want counter to be incremented each time I call this function, but here is one unpleasant thing: defined 'counter' is not local and I can easily change its value from another space, that breaks encapsulation.

```<code>(defn next []
  (defonce counter (atom 0))
  (println @counter)
  (reset! counter (inc @counter)))
</code>```

Many say, it will be correct if I place 'private' meta tag. So function will look like this:

```<code>(defn next []
  (defonce ^:private counter (atom 0))
  (println @counter)
  (reset! counter (inc @counter)))
</code>```

But I still have access to 'counter' from another space.

Is there any way to implement this encapsulation or it's only at the agreement level?

答:
Here's how you should write your next function:

```<code>(def ^{:arglists '([])} next
  (let [counter (atom 0)]
    #(let [after (swap! counter inc)
           before (dec after)]
       (println before)
       after)))
</code>```

This is the same as the one in your question, except that it is thread-safe and completely encapsulates the counter atom.

Body:
Let's say I need to make a simple counter and I want counter to be incremented each time I call this function, but here is one unpleasant thing: defined 'counter' is not local and I can easily change its value from another space, that breaks encapsulation.

(defn next []
  (defonce counter (atom 0))
  (println @counter)
  (reset! counter (inc @counter)))

Many say, it will be correct if I place 'private' meta tag. So function will look like this:

(defn next []
  (defonce ^:private counter (atom 0))
  (println @counter)
  (reset! counter (inc @counter)))

But I still have access to 'counter' from another space.

Is there any way to implement this encapsulation or it's only at the agreement level?

Body:
Here's how you should write your next function:

(def ^{:arglists '([])} next
  (let [counter (atom 0)]
    #(let [after (swap! counter inc)
           before (dec after)]
       (println before)
       after)))

This is the same as the one in your question, except that it is thread-safe and completely encapsulates the counter atom.


答:
I would do like that :

$(".appendbtn").click(function () {
   $(".appendme:last").append(getHtml());
});

function getHtml(){
  return '
The div that should be appended
';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button></code>```

upd: function for html (from comment)

Title: Appending a div onclick

Body:
I would do like that :

$(".appendbtn").click(function () {
   $(".appendme:last").append(getHtml());
});

function getHtml(){
  return '<div class="appendme">The div that should be appended</div>';
}

<script
  src="https://code.jquery.com/jquery-2.2.3.min.js"
  integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
  crossorigin="anonymous"></script>
<div class="appendme">The div that should be appended</div>
<button class="appendbtn" type="button">Click to append</button>

upd: function for html (from comment)


问:
Django setting TIME_ZONE in DATABASES has no effect with 'date' lookup
UPDATE April 8th, 2019

This is a known bug for django<=2.2, fixed as of this PR

=================================

(We assume the mysql backends)

I can set TIME_ZONE several times in settings.py, one for the global django app, and one for each database (see https://docs.djangoproject.com/en/1.11/ref/settings/#time-zone (ref1))

Typical usage would be for a legacy database where datetimes are not stored in UTC.

No date lookup

Querying my database takes this setting into account, e.g. :

In settings.py

```<code>USE_TZ = True
TIME_ZONE = 'Europe/Paris' # tz1
DATABASES = {
    'legacy': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
        'TIME_ZONE': 'Europe/Paris', # tz2
    },
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
    }
}
</code>```

In the manage.py shell

```<code>>>> dt = timezone.make_aware(datetime.datetime(2017, 7, 6, 20, 50))
>>> dt
datetime.datetime(2017, 7, 6, 20, 50, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> MyModel.objects.filter(my_datetime_field=dt).exists()
True
</code>```

This works because my database reads '2017-07-06 20:50:00'

With date lookup

Related doc https://docs.djangoproject.com/en/1.11/ref/models/querysets/#date (ref2)

But this does not work, while it logically should

```<code>>>> MyModel.objects.filter(my_datetime_field__date=dt.date()).exists()
False*
</code>```

The related SQL query from DEBUG is :

```<code>SELECT (1) AS `a` FROM `my_model` WHERE DATE(CONVERT_TZ(`my_model`.`my_datetime_field`, 'UTC', 'Europe/Paris')) = '2017-07-06' LIMIT 1;
</code>```

(*) Note that I haven't filled the timezone table in MySQL, so the result should be True in this case, but could be False close to midnight.
Related doc is https://dev.mysql.com/doc/refman/5.7/en/mysql-tzinfo-to-sql.html

Two things are wrong. First, conversion should be from Paris to Paris, instead of UTC to Paris. The conversion should go from the database timezone tz2 to the django app one tz1.

Indeed from ref1 :

When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t.

and ref2 :

When USE_TZ is True, fields are converted to the current time zone before filtering

Secondly, when tz1 == tz2, there should be no need to use CONVERT_TZ and the query will work without timezone tables in MySQL.

The explicit queries are :

```<code>mysql> SELECT (1) AS `a` FROM `my_model` WHERE `my_model`.`my_datetime_field` = '2017-07-06 20:50:00' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> SELECT (1) AS `a` FROM `my_model` WHERE DATE(`my_model`.`my_datetime_field`) = '2017-07-06' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
</code>```

Why is 'UTC' appearing in the query? Should it not be 'Europe/Paris'?

Am I misunderstanding something from the doc, or is it a bug?

Thank you.

EDIT : My system tz is not UTC, if this is any help

```<code>mysql> SELECT @@global.time_zone, @@session.time_zone, @@system_time_zone;
+--------------------+---------------------+--------------------+
| @@global.time_zone | @@session.time_zone | @@system_time_zone |
+--------------------+---------------------+--------------------+
| SYSTEM             | SYSTEM              | CEST               |
+--------------------+---------------------+--------------------+
</code>```

答:
This behaviour is to be expected since Django's code reads

django/db/backends/mysql/operations.py

```<code>def _convert_field_to_tz(self, field_name, tzname):
    if settings.USE_TZ:
        field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
        params = [tzname]
    else:
        params = []
    return field_name, params
</code>```

The database specific time zone is ignored to the profit of 'UTC'.

For what it's worth, I've opened a ticket on djangoproject and it's related pull request

Replaced it by:

```<code>def _convert_field_to_tz(self, field_name, tzname):
    if settings.USE_TZ and self.connection.timezone_name != tzname:
        field_name = "CONVERT_TZ(%s, '%s', %%s)" % (field_name, self.connection.timezone_name)
        params = [tzname]
    else:
        params = []
    return field_name, params
</code>```

Body:
UPDATE April 8th, 2019

This is a known bug for django<=2.2, fixed as of this PR

=================================

(We assume the mysql backends)

I can set TIME_ZONE several times in settings.py, one for the global django app, and one for each database (see https://docs.djangoproject.com/en/1.11/ref/settings/#time-zone (ref1))

Typical usage would be for a legacy database where datetimes are not stored in UTC.

No date lookup

Querying my database takes this setting into account, e.g. :

In settings.py

USE_TZ = True
TIME_ZONE = 'Europe/Paris' # tz1
DATABASES = {
    'legacy': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
        'TIME_ZONE': 'Europe/Paris', # tz2
    },
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
    }
}

In the manage.py shell

>>> dt = timezone.make_aware(datetime.datetime(2017, 7, 6, 20, 50))
>>> dt
datetime.datetime(2017, 7, 6, 20, 50, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> MyModel.objects.filter(my_datetime_field=dt).exists()
True

This works because my database reads '2017-07-06 20:50:00'

With date lookup

Related doc https://docs.djangoproject.com/en/1.11/ref/models/querysets/#date (ref2)

But this does not work, while it logically should

>>> MyModel.objects.filter(my_datetime_field__date=dt.date()).exists()
False*

The related SQL query from DEBUG is :

SELECT (1) AS `a` FROM `my_model` WHERE DATE(CONVERT_TZ(`my_model`.`my_datetime_field`, 'UTC', 'Europe/Paris')) = '2017-07-06' LIMIT 1;

(*) Note that I haven't filled the timezone table in MySQL, so the result should be True in this case, but could be False close to midnight.
Related doc is https://dev.mysql.com/doc/refman/5.7/en/mysql-tzinfo-to-sql.html

Two things are wrong. First, conversion should be from Paris to Paris, instead of UTC to Paris. The conversion should go from the database timezone tz2 to the django app one tz1.

Indeed from ref1 :

When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t.

and ref2 :

When USE_TZ is True, fields are converted to the current time zone before filtering

Secondly, when tz1 == tz2, there should be no need to use CONVERT_TZ and the query will work without timezone tables in MySQL.

The explicit queries are :

mysql> SELECT (1) AS `a` FROM `my_model` WHERE `my_model`.`my_datetime_field` = '2017-07-06 20:50:00' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> SELECT (1) AS `a` FROM `my_model` WHERE DATE(`my_model`.`my_datetime_field`) = '2017-07-06' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

Why is 'UTC' appearing in the query? Should it not be 'Europe/Paris'?

Am I misunderstanding something from the doc, or is it a bug?

Thank you.

EDIT : My system tz is not UTC, if this is any help

mysql> SELECT @@global.time_zone, @@session.time_zone, @@system_time_zone;
+--------------------+---------------------+--------------------+
| @@global.time_zone | @@session.time_zone | @@system_time_zone |
+--------------------+---------------------+--------------------+
| SYSTEM             | SYSTEM              | CEST               |
+--------------------+---------------------+--------------------+

Body:
This behaviour is to be expected since Django's code reads

django/db/backends/mysql/operations.py

def _convert_field_to_tz(self, field_name, tzname):
    if settings.USE_TZ:
        field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
        params = [tzname]
    else:
        params = []
    return field_name, params

The database specific time zone is ignored to the profit of 'UTC'.

For what it's worth, I've opened a ticket on djangoproject and it's related pull request

Replaced it by:

def _convert_field_to_tz(self, field_name, tzname):
    if settings.USE_TZ and self.connection.timezone_name != tzname:
        field_name = "CONVERT_TZ(%s, '%s', %%s)" % (field_name, self.connection.timezone_name)
        params = [tzname]
    else:
        params = []
    return field_name, params