问:
msbuild not compiling typescript in docker build, but works in azure pipeline
I'm in the process of attempting to containerize an asp.net .net framework web application.

I've mostly got it working. However I've found that for some reason it's not compiling my .ts files.

The build works correctly in an Azure DevOps Pipeline, but not in docker.

When I check the logs for the Azure DevOps build, I can see the following...

```<code>Processing resource file "My Project\Resources.resx" into "obj\Prod\Resources.resources".
PreComputeCompileTypeScriptWithTSConfig:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.1\tsc.exe   --project "D:\a\1\s\MyProject\tsconfig.json" --listEmittedFiles --listFiles --noEmit
CompileTypeScriptWithTSConfig:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.1\tsc.exe   --project "D:\a\1\s\MyProject\tsconfig.json" --listEmittedFiles
WebCompile:
...
</code>```

However in my docker build, I'm seeing...

```<code>Processing resource file "My Project\Resources.resx" into "obj\Prod\Resources.resources".
WebCompile:
...
</code>```

So it's obviously skipping the typescript bit.

I'm not sure what I'm supposed to do to make this run, as in Azure Devops it seemed to work automatically without me doing any extra configuration.

This is the msbuild command that Azure DevOps Pipeline is running...

```<code>"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\amd64\msbuild.exe" "D:\a\1\s\MyProject.sln" /nologo /nr:false /dl:CentralLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.166.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=|SolutionDir=D:\a\1\s"*ForwardingLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.166.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll" /m /p:MvcBuildViews=true /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="D:\a\1\a\\" /p:platform="any cpu" /p:configuration="prod"
</code>```

And this is what I'm using in my Dockerfile

```<code>msbuild ./MyProject.sln -target:MyProject -p:TargetFrameworkVersion=v4.7.2  -p:Configuration=prod -p:DeployIisAppPath='Default Web Site' -m -p:MvcBuildViews=true -p:DeployOnBuild=false -p:PackageAsSingleFile=true /p:OutDir=/artifacts /t:Package
</code>```

Obviously the Azure DevOps command has a lot of extra stuff declared, but I'm not sure what specifically in this causes the typescript to build, or if it's even related to do with the msbuild options.

My Dockerfile uses the following base image...

```<code>mcr.microsoft.com/dotnet/framework/sdk:4.7.2
</code>```

Just in case it's relevant, this is my tsconfig.json

```<code>{
  "compilerOptions": {
    "typeRoots": ["scripts/typings"],
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "none"
  }
}
</code>```

If there's any other information I need to include to make the question make sense, let me know. My project file is much too large to include, but if there are bits that would be relevant, I can add them.

答:
I found a solution, just in case it's helpful for others. I'm not sure if it's the best way to do it, but it works...

First, I added the following nuget package to the project...

```<code>Install-Package Microsoft.TypeScript.MSBuild -Version 3.9.2
</code>```

When I tried to build the project though, it complained that it needed nodejs. I installed this in my Dockerfile like so...

```<code>ADD https://nodejs.org/dist/v12.18.0/node-v12.18.0-x64.msi ./node-v12.18.0-x64.msi

RUN msiexec /i node-v12.18.0-x64.msi AGREETOLICENSE=yes ADDLOCAL=ALL /qn
</code>```

msbuild then ran the typescript correctly. One difference though, it ran the js version of the tsc compiler rather than the .exe, as Azure Devops does. It seems that the files have all compiled correctly though.

Body:
I'm in the process of attempting to containerize an asp.net .net framework web application.

I've mostly got it working. However I've found that for some reason it's not compiling my .ts files.

The build works correctly in an Azure DevOps Pipeline, but not in docker.

When I check the logs for the Azure DevOps build, I can see the following...

Processing resource file "My Project\Resources.resx" into "obj\Prod\Resources.resources".
PreComputeCompileTypeScriptWithTSConfig:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.1\tsc.exe   --project "D:\a\1\s\MyProject\tsconfig.json" --listEmittedFiles --listFiles --noEmit
CompileTypeScriptWithTSConfig:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.1\tsc.exe   --project "D:\a\1\s\MyProject\tsconfig.json" --listEmittedFiles
WebCompile:
...

However in my docker build, I'm seeing...

Processing resource file "My Project\Resources.resx" into "obj\Prod\Resources.resources".
WebCompile:
...

So it's obviously skipping the typescript bit.

I'm not sure what I'm supposed to do to make this run, as in Azure Devops it seemed to work automatically without me doing any extra configuration.

This is the msbuild command that Azure DevOps Pipeline is running...

"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\amd64\msbuild.exe" "D:\a\1\s\MyProject.sln" /nologo /nr:false /dl:CentralLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.166.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll";"RootDetailId=|SolutionDir=D:\a\1\s"*ForwardingLogger,"D:\a\_tasks\MSBuild_c6c4c611-aa2e-4a33-b606-5eaba2196824\1.166.0\ps_modules\MSBuildHelpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll" /m /p:MvcBuildViews=true /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="D:\a\1\a\\" /p:platform="any cpu" /p:configuration="prod"

And this is what I'm using in my Dockerfile

msbuild ./MyProject.sln -target:MyProject -p:TargetFrameworkVersion=v4.7.2  -p:Configuration=prod -p:DeployIisAppPath='Default Web Site' -m -p:MvcBuildViews=true -p:DeployOnBuild=false -p:PackageAsSingleFile=true /p:OutDir=/artifacts /t:Package

Obviously the Azure DevOps command has a lot of extra stuff declared, but I'm not sure what specifically in this causes the typescript to build, or if it's even related to do with the msbuild options.

My Dockerfile uses the following base image...

mcr.microsoft.com/dotnet/framework/sdk:4.7.2

Just in case it's relevant, this is my tsconfig.json

{
  "compilerOptions": {
    "typeRoots": ["scripts/typings"],
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "module": "none"
  }
}

If there's any other information I need to include to make the question make sense, let me know. My project file is much too large to include, but if there are bits that would be relevant, I can add them.

Body:
I found a solution, just in case it's helpful for others. I'm not sure if it's the best way to do it, but it works...

First, I added the following nuget package to the project...

Install-Package Microsoft.TypeScript.MSBuild -Version 3.9.2

When I tried to build the project though, it complained that it needed nodejs. I installed this in my Dockerfile like so...

ADD https://nodejs.org/dist/v12.18.0/node-v12.18.0-x64.msi ./node-v12.18.0-x64.msi

RUN msiexec /i node-v12.18.0-x64.msi AGREETOLICENSE=yes ADDLOCAL=ALL /qn

msbuild then ran the typescript correctly. One difference though, it ran the js version of the tsc compiler rather than the .exe, as Azure Devops does. It seems that the files have all compiled correctly though.


来源: stackexchange

问:
R Indicate If Group Has Value
```<code>data=data.frame(GROUP=c(1,1,1,2,2,2,3,3,3,4,4,4),
VAR=c('A','B','C','A','B','C','A','B','C','A','B','C'),
SCORE=c(3,6,NA,NA,NA,NA,1,NA,5,5,2,NA),
NEWVAR=c(1,1,1,NA,NA,NA,2,2,2,1,1,1))

score1 = c(2,3,7)
score2 = c(0,5,6)
</code>```

I have 'data' with all columns but 'NEWVAR' and I wish to create it like this:

If score1 %in% SCORE for a particular 'GROUP' then a value '1' is given to 'NEWVAR'

If score2 %in% SCORE & score1 is not in SCORE for a particular 'GROUP' then a value '2' is given to 'NEWVAR'

答:
Since you have tagged this data.table using ifelse in data.table syntax.

```<code>library(data.table)

setDT(data)[, NEWVAR := ifelse(any(SCORE %in% score1), 1,
                          ifelse(any(SCORE %in% score2), 2, NA_integer_)), GROUP]

data
#    GROUP VAR SCORE NEWVAR
# 1:     1   A     3      1
# 2:     1   B     6      1
# 3:     1   C    NA      1
# 4:     2   A    NA     NA
# 5:     2   B    NA     NA
# 6:     2   C    NA     NA
# 7:     3   A     1      2
# 8:     3   B    NA      2
# 9:     3   C     5      2
#10:     4   A     5      1
#11:     4   B     2      1
#12:     4   C    NA      1
</code>```

I think there is also fcase in development version of data.table which is similar to case_when in dplyr and makes writing such nested ifelse easy.

ContentLicense: CC BY-SA 4.0

Title: R Indicate If Group Has Value

Body:
data=data.frame(GROUP=c(1,1,1,2,2,2,3,3,3,4,4,4),
VAR=c('A','B','C','A','B','C','A','B','C','A','B','C'),
SCORE=c(3,6,NA,NA,NA,NA,1,NA,5,5,2,NA),
NEWVAR=c(1,1,1,NA,NA,NA,2,2,2,1,1,1))

score1 = c(2,3,7)
score2 = c(0,5,6)

I have 'data' with all columns but 'NEWVAR' and I wish to create it like this:

If score1 %in% SCORE for a particular 'GROUP' then a value '1' is given to 'NEWVAR'

If score2 %in% SCORE & score1 is not in SCORE for a particular 'GROUP' then a value '2' is given to 'NEWVAR'

Body:
Since you have tagged this data.table using ifelse in data.table syntax.

library(data.table)

setDT(data)[, NEWVAR := ifelse(any(SCORE %in% score1), 1,
                          ifelse(any(SCORE %in% score2), 2, NA_integer_)), GROUP]

data
#    GROUP VAR SCORE NEWVAR
# 1:     1   A     3      1
# 2:     1   B     6      1
# 3:     1   C    NA      1
# 4:     2   A    NA     NA
# 5:     2   B    NA     NA
# 6:     2   C    NA     NA
# 7:     3   A     1      2
# 8:     3   B    NA      2
# 9:     3   C     5      2
#10:     4   A     5      1
#11:     4   B     2      1
#12:     4   C    NA      1

I think there is also fcase in development version of data.table which is similar to case_when in dplyr and makes writing such nested ifelse easy.


问:
How to connect multiple PyQt Signals w/ variable arguments to single slot/signal repeater
Example:

```<code>class MyClass(QObject):
    signal_1 = pyqtSignal(str, int)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(str, int, int)
</code>```

Let's say each of these signals is connected elsewhere to perform various functions, however, there's a specific function I want to be performed as well when any of the signals are emitted. What this indiscriminate function does cares only about, say, the last int argument emitted with the signal. The slot would ostensibly look like:

```<code>class OtherClass(QObject):

    ...

    @pyqtSlot(int)
    def unifiedResponse(self, index):
        # Here I would do something with that index
</code>```

Is there a way to connect some arbitrary number of signals with arbitrary arguments either directly to a slot or to a repeater signal?

If there is a way to define a slot like so:

```<code>@pyqtSlot(???)
def unifiedResponse(self, *args):
    important_var = args[-1]
</code>```

Then I could simply capture the last argument as such. However, I have been unsuccessful in determining how to form the slot signature.

Update:

I may have answered my own question, using lambdas:

```<code>signal_1.connect(lambda _, source: OtherClass.unifiedResponse(source))
signal_2.connect(lambda _, source: OtherClass.unifiedResponse(source))
signal_3.connect(lambda _, _, source: OtherClass.unifiedResponse(source))
</code>```

The solution from @eyllanesc below however is preferred, as it allows for more flexibility the larger the signal count.

答:
You have to set all the signatures of the signals through several pyqtSlot:

```<code>from PyQt5.QtCore import pyqtSignal, pyqtSlot, QCoreApplication, QObject, QTimer

class MyClass(QObject):
    signal_1 = pyqtSignal(str, int)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(str, int, int)

class OtherClass(QObject):
    @pyqtSlot(str, int)
    @pyqtSlot(int, int)
    @pyqtSlot(str, int, int)
    def unifiedResponse(self, *args):
        print(args)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit("StackOverflow", 1)
        sender.signal_2.emit(1, 2)
        sender.signal_3.emit("StackOverflow", 1, 2)

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

If in general you want to send several types of data then it is best to use a more generic data type such as a list (or an object):

```<code>class MyClass(QObject):
    signal_1 = pyqtSignal(list)
    signal_2 = pyqtSignal(list)
    signal_3 = pyqtSignal(list)

class OtherClass(QObject):
    @pyqtSlot(list)
    def unifiedResponse(self, args):
        print(args)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit(["StackOverflow", 1])
        sender.signal_2.emit([1, 2])
        sender.signal_3.emit(["StackOverflow", 1, 2])

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())
</code>```

Update:

There is no elegant way to access the last element, but the first ones since the slot signature must be a subset of the signal signature, for example the slot with signature "int" can accept signals with a signature that has the first type to "int", the other arguments are discarded:

```<code>from PyQt5.QtCore import pyqtSignal, pyqtSlot, QCoreApplication, QObject, QTimer

class MyClass(QObject):
    signal_1 = pyqtSignal(int, str)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(int, str, int)

class OtherClass(QObject):
    @pyqtSlot(int)
    def unifiedResponse(self, index):
        print(index)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit(1, "StackOverflow")
        sender.signal_2.emit(2, 2)
        sender.signal_3.emit(3, "StackOverflow", 1)

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

Body:
Example:

class MyClass(QObject):
    signal_1 = pyqtSignal(str, int)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(str, int, int)

Let's say each of these signals is connected elsewhere to perform various functions, however, there's a specific function I want to be performed as well when any of the signals are emitted. What this indiscriminate function does cares only about, say, the last int argument emitted with the signal. The slot would ostensibly look like:

class OtherClass(QObject):

    ...

    @pyqtSlot(int)
    def unifiedResponse(self, index):
        # Here I would do something with that index

Is there a way to connect some arbitrary number of signals with arbitrary arguments either directly to a slot or to a repeater signal?

If there is a way to define a slot like so:

@pyqtSlot(???)
def unifiedResponse(self, *args):
    important_var = args[-1]

Then I could simply capture the last argument as such. However, I have been unsuccessful in determining how to form the slot signature.

Update:

I may have answered my own question, using lambdas:

signal_1.connect(lambda _, source: OtherClass.unifiedResponse(source))
signal_2.connect(lambda _, source: OtherClass.unifiedResponse(source))
signal_3.connect(lambda _, _, source: OtherClass.unifiedResponse(source))

The solution from @eyllanesc below however is preferred, as it allows for more flexibility the larger the signal count.

Body:
You have to set all the signatures of the signals through several pyqtSlot:

from PyQt5.QtCore import pyqtSignal, pyqtSlot, QCoreApplication, QObject, QTimer

class MyClass(QObject):
    signal_1 = pyqtSignal(str, int)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(str, int, int)

class OtherClass(QObject):
    @pyqtSlot(str, int)
    @pyqtSlot(int, int)
    @pyqtSlot(str, int, int)
    def unifiedResponse(self, *args):
        print(args)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit("StackOverflow", 1)
        sender.signal_2.emit(1, 2)
        sender.signal_3.emit("StackOverflow", 1, 2)

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

If in general you want to send several types of data then it is best to use a more generic data type such as a list (or an object):

class MyClass(QObject):
    signal_1 = pyqtSignal(list)
    signal_2 = pyqtSignal(list)
    signal_3 = pyqtSignal(list)

class OtherClass(QObject):
    @pyqtSlot(list)
    def unifiedResponse(self, args):
        print(args)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit(["StackOverflow", 1])
        sender.signal_2.emit([1, 2])
        sender.signal_3.emit(["StackOverflow", 1, 2])

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())

Update:

There is no elegant way to access the last element, but the first ones since the slot signature must be a subset of the signal signature, for example the slot with signature "int" can accept signals with a signature that has the first type to "int", the other arguments are discarded:

from PyQt5.QtCore import pyqtSignal, pyqtSlot, QCoreApplication, QObject, QTimer

class MyClass(QObject):
    signal_1 = pyqtSignal(int, str)
    signal_2 = pyqtSignal(int, int)
    signal_3 = pyqtSignal(int, str, int)

class OtherClass(QObject):
    @pyqtSlot(int)
    def unifiedResponse(self, index):
        print(index)

def main():
    import sys

    app = QCoreApplication(sys.argv)

    sender = MyClass()
    receiver = OtherClass()

    sender.signal_1.connect(receiver.unifiedResponse)
    sender.signal_2.connect(receiver.unifiedResponse)
    sender.signal_3.connect(receiver.unifiedResponse)

    def on_timeout():
        sender.signal_1.emit(1, "StackOverflow")
        sender.signal_2.emit(2, 2)
        sender.signal_3.emit(3, "StackOverflow", 1)

        QTimer.singleShot(1000, QCoreApplication.quit)

    QTimer.singleShot(1000, on_timeout)

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


问:
Angular 9 : Children routing inside lazy loaded component not working
I have app component in which i lazy load create-new-module with component profilecomponent. now in profile component i hit router.navigate and trying to load another children detail in place of profile but its not working also no error in console.

please help

// App component route

const routes: Routes = [
  {
    path: 'create-new-emp',
    loadChildren: () => import('./create-new-emp/create-new-emp.module').then(c => c.CreateNewEmpModule),
  },
  { path: '',  redirectTo: 'create-new-emp', pathMatch: 'full'},
  { path: '**',  redirectTo: 'create-new-emp'}
];

// Emp Module Route

const routes: Routes = [
  { path: '', component: ContainerComponent,
  children: [
    { path: '', component: ProfileComponent, outlet: 'form'},
    { path: 'profile', component: ProfileComponent, outlet: 'form'},
    { path: 'detail', component: DetailComponent, outlet: 'form' }] }
];

// Trying to hit below link but not working

this.router.navigate(['detail'])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component></code>```

答:
Its hard to say with this info, but may... you should define de router outlet name

```<code><router-outlet  name="form"></router-outlet>
</code>```

Hope it's help.

Body:
I have app component in which i lazy load create-new-module with component profilecomponent. now in profile component i hit router.navigate and trying to load another children detail in place of profile but its not working also no error in console.

please help

// App component route

const routes: Routes = [
  {
    path: 'create-new-emp',
    loadChildren: () => import('./create-new-emp/create-new-emp.module').then(c => c.CreateNewEmpModule),
  },
  { path: '',  redirectTo: 'create-new-emp', pathMatch: 'full'},
  { path: '**',  redirectTo: 'create-new-emp'}
];

// Emp Module Route

const routes: Routes = [
  { path: '', component: ContainerComponent,
  children: [
    { path: '', component: ProfileComponent, outlet: 'form'},
    { path: 'profile', component: ProfileComponent, outlet: 'form'},
    { path: 'detail', component: DetailComponent, outlet: 'form' }] }
];

// Trying to hit below link but not working

this.router.navigate(['detail'])

<app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component>

Body:
Its hard to say with this info, but may... you should define de router outlet name

<router-outlet  name="form"></router-outlet>

Hope it's help.


问:
Object discriminated union types are merged when using fallback
I am defining an array that needs to accept types of string, and object.  The object types must contain two properties: name and value.  value must be another object, containing an arbitrary set of key: value pairs.

I am trying to define some of the object types using a discriminated union, so that the properties of value for some specific name are known.  However, there always needs to remain a fallback so that when name is not a known string literal, value can still be any arbitrary set.

Here is what I'm working with so far:

interface IFallbackDef {
    name: string;
    value: object;
}
type ValueDef<TName extends string = string, TOptions extends object = {}> = {
    name: TName;
    value: TOptions;
};
type Merged<TValueDef extends ValueDef> = (string | TValueDef | IFallbackDef)[];

interface ITest1Options {
    foo: string;
    bar: string;
}
interface ITest2Options {
    baz: string;
    qux: string;
}

const test: Merged<
    | ValueDef<'test1', ITest1Options>
    | ValueDef<'test2', ITest2Options>
> = [
    'asdf',
    {
        name: 'test1',
        value: {
            foo: 'asdjfkl',
            bar: 'asdf',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            qux: 'asdfkljsdg' // This should be an error
        }
    },
    {
        name: 'test2',
        value: {
            baz: 'blah',
            qux: 'test',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            foo: 'salfdj' // This should be an error
        }
    },
    {
        name: 'asdf',
        value: {
            /**
             * Intellisense shows both sets of properties,
             * should show none.
             */
        },
    },
]
```

The issue I have is that when I include IFallbackDef in the union, all of the types for the various value properties merge.  If I exclude IFallbackDef, the union works correctly, but the last index of the test array will be an error, because name: 'asdf' is unknown.

I assume that because IFallbackDef uses base types, and the shape is the same as IValueDef, it is merging the types... ?  At the moment, I'm kind of at a loss for how to make this work properly.  A fresh set of eyes would be very appreciated.

答:
Here's a start: playground

I use Exclude<string, 'test1'|'test2'> to denote "all strings other than test1 and test2".

I'm not sure if it's possible to make it error when an extra property is specified.

Body:
I am defining an array that needs to accept types of string, and object.  The object types must contain two properties: name and value.  value must be another object, containing an arbitrary set of key: value pairs.

I am trying to define some of the object types using a discriminated union, so that the properties of value for some specific name are known.  However, there always needs to remain a fallback so that when name is not a known string literal, value can still be any arbitrary set.

Here is what I'm working with so far:

interface IFallbackDef {
    name: string;
    value: object;
}
type ValueDef<TName extends string = string, TOptions extends object = {}> = {
    name: TName;
    value: TOptions;
};
type Merged<TValueDef extends ValueDef> = (string | TValueDef | IFallbackDef)[];

interface ITest1Options {
    foo: string;
    bar: string;
}
interface ITest2Options {
    baz: string;
    qux: string;
}

const test: Merged<
    | ValueDef<'test1', ITest1Options>
    | ValueDef<'test2', ITest2Options>
> = [
    'asdf',
    {
        name: 'test1',
        value: {
            foo: 'asdjfkl',
            bar: 'asdf',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            qux: 'asdfkljsdg' // This should be an error
        }
    },
    {
        name: 'test2',
        value: {
            baz: 'blah',
            qux: 'test',

            /**
             * Intellisense shows both sets of properties,
             * and typescript allows them all, too
             */
            foo: 'salfdj' // This should be an error
        }
    },
    {
        name: 'asdf',
        value: {
            /**
             * Intellisense shows both sets of properties,
             * should show none.
             */
        },
    },
]

The issue I have is that when I include IFallbackDef in the union, all of the types for the various value properties merge.  If I exclude IFallbackDef, the union works correctly, but the last index of the test array will be an error, because name: 'asdf' is unknown.

I assume that because IFallbackDef uses base types, and the shape is the same as IValueDef, it is merging the types... ?  At the moment, I'm kind of at a loss for how to make this work properly.  A fresh set of eyes would be very appreciated.

Body:
Here's a start: <a href="https://www.typescriptlang.org/play/?ssl=54&ssc=16&pln=54&pc=20#code/JYOwLgpgTgZghgYwgAgJIDE4BssCNEDWAIhDMgN4CwAUMnciHALYQBcyAzmFKAOYDcNesgBu2AK5tkAe1wArCAjCDqAXxpgAngAcUANQkQSMADwAVAHLMUEAB6QQAEw6dufZAF5XPELwA0yGYA8tpgwNIgLnYOzjLyimCeFKoAfElUtPSMLOyW1irCYliSuSFhERwqqipausgAstC8EI7mBsVGpMjREE4u7ZLGaV4AFFw+vMgAPoEDnTBC9DNzxiYAorYIxY4QJuN8AWYrpADaAOTZEGcAuikpAJQn1yo0NKCQsIgoqGYQXACMZXCkQoizoMGk0nY+18BXo+Cg0LcsJo6mo72g8CQaF+XAATECKqDMnR8AAvJETOF0ACO4lslL4VVe1AQFUSkC47EaUGarTB02Qx1MZ05YH+ZwCPz+4sJkRSAuWhlWopleMlOLVco4Cuow2QJwFZzgHEcMElAoywmEl3YqoBFpJ1qKJWJ1vdyAhUOQxtNchgBCwjo91oRdpNZsdApDAHoAFRx6MhuNocAQHDADi9LOcAAW0gA7i5cNIwLnOBAwC5pGRtFBpLooGE-n4kx6U3AnMhan8EDxQshsFhCy4yxAmIOcAEwJC2+64zG58I6QyfRGA1g5KbeGdkDGY4Fc5m89JxFhHMhcChO90oPWoHO0cJVK2nVaPbafWL1a+Qy6pO+IaknAFI+rgWBwLmwZAbS9J2mKUZOrGCZLsIKaoGmGZZpEKAcPmRaXqW5ZZlWMi1vWjbNhwv4wXQHZdj2HB9sAA5DiO3a5uOk5YNOs5Icmi78e6Xp2hw2AwI4ci7vuh7Hnhp7npe14gLe96PgKL6WnOn6+pGNHuv+7CAUB8aJkJ86ppAWHZrh+EuCA0jIHWDbQFRqH0Auj76cgmnUNcQA" rel="nofollow noreferrer">playground

I use Exclude<string, 'test1'|'test2'> to denote "all strings other than test1 and test2".

I'm not sure if it's possible to make it error when an extra property is specified.


问:
How do wait for a service to start on Android without using bindService
I know that I can wait for a service start by doing

```<code>bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
</code>```

where serviceConnection implements a callback that is called when the service starts. However, I need a service that is less killeable, that is, a service hat uses startForeground. But this can only work if I start my service with startService, which does not provide a way to pass a serviceConnection.

How can I wait for an android service to start?

Why I need it to start? Well, because I need to call things inside it by doing service.method1(); etc.

答:
You can try to use both methods, first start the service with startForeground() and then use bindService() to wait for the service connection.

The service starts in the foreground and you can use the service methods.

Starting Service:

```<code>listenServiceIntent = new Intent(getApplicationContext(), ListenService.class);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    //Start in Foreground
    ContextCompat.startForegroundService(this, listenServiceIntent);

    if (connection != null) {
        //Then bind service
        bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
    }
}
else {
    startService(listenServiceIntent);
    if (connection != null) {
        bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
    }
}
</code>```

Waiting Connection:

```<code>private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected");

            ListenService.LocalBinder binder = (ListenService.LocalBinder) service;
            listenService = binder.getService();

            //HERE you can use service methods

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected");
        }
};
</code>```

Create notificationChannel:

```<code>public static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL,
                    NOTIFICATION_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            );

            NotificationManager manager =    context.getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }
</code>```

Push notification:

```<code>public static Notification pushNotification(Context context, String notificationText, Class classNotification) {

        Intent notificationIntent = new Intent(context, classNotification);

        PendingIntent pendingIntent = PendingIntent.getActivity(context,
                0, notificationIntent, 0);

        return new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
                .setContentTitle(context.getString(R.string.notification_title))
                .setContentText(notificationText)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.logosinfondo_mini)
                .setColor(Color.MAGENTA)
                .setAutoCancel(true)
                .build();
    }
</code>```

In onCreate() inside your Service:

```<code>@Override
    public void onCreate() {
        super.onCreate();
        Lib.createNotificationChannel(this);
        startForeground(1, Lib.pushNotification(this, "Started", ListenActivity.class));
    }
</code>```

Body:
I know that I can wait for a service start by doing

bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

where serviceConnection implements a callback that is called when the service starts. However, I need a service that is less killeable, that is, a service hat uses startForeground. But this can only work if I start my service with startService, which does not provide a way to pass a serviceConnection.

How can I wait for an android service to start?

Why I need it to start? Well, because I need to call things inside it by doing service.method1(); etc.

Body:
You can try to use both methods, first start the service with startForeground() and then use bindService() to wait for the service connection.

The service starts in the foreground and you can use the service methods.

Starting Service:

listenServiceIntent = new Intent(getApplicationContext(), ListenService.class);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

    //Start in Foreground
    ContextCompat.startForegroundService(this, listenServiceIntent);

    if (connection != null) {
        //Then bind service
        bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
    }
}
else {
    startService(listenServiceIntent);
    if (connection != null) {
        bindService(listenServiceIntent, connection, Context.BIND_AUTO_CREATE);
    }
}

Waiting Connection:

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected");

            ListenService.LocalBinder binder = (ListenService.LocalBinder) service;
            listenService = binder.getService();

            //HERE you can use service methods

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected");
        }
};

Create notificationChannel:

public static void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    NOTIFICATION_CHANNEL,
                    NOTIFICATION_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            );

            NotificationManager manager =    context.getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

Push notification:

public static Notification pushNotification(Context context, String notificationText, Class classNotification) {

        Intent notificationIntent = new Intent(context, classNotification);

        PendingIntent pendingIntent = PendingIntent.getActivity(context,
                0, notificationIntent, 0);

        return new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL)
                .setContentTitle(context.getString(R.string.notification_title))
                .setContentText(notificationText)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.logosinfondo_mini)
                .setColor(Color.MAGENTA)
                .setAutoCancel(true)
                .build();
    }

In onCreate() inside your Service:

@Override
    public void onCreate() {
        super.onCreate();
        Lib.createNotificationChannel(this);
        startForeground(1, Lib.pushNotification(this, "Started", ListenActivity.class));
    }


问:
How to control the height of descendant box within a nested flexbox context?

.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}

.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  background: orange;
  border: 1px blue solid;
}
.box222 {
  background: white;
  border: 1px blue solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><md-content class="md-padding">
  <div class="main columns vertical">
    <nav class="box1">nav</nav>
    <div class="box columns vertical">
      <div class="b">asdasd</div>
      <div class="box2 columns vertical">
        <div class="box21 columns">
          box21
        </div>
        <div class="box22 columns">
          <div class="box221">box221</div>
          <div class="box222">
            <p>a</p>
            <p>a</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</md-content></code>```

I manually set the height of outermost box main and also set box22 with overflow:auto, however the box22 stretched out the main box and no scroll bar shows up.

What I want is to set height in the outermost box and the nested inner box can automitically control it's height thus all boxes are fitted. How to fix these kind of problem, should I set heights for all descendant boxes?

I tested setting overflow :auto at box(level1), box2(level2) and box22(level3), only box(level1) can automatically control it's height and shows up a scroll bar when it's height overlayed.

what I want is shown below, however, to achieve this, I need to manually specify the father box of box22. In other words, if I want to make a flex contaner scrollable, I have to at least set it's father box's height, which is toally unaccptable.

.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}
.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  height:64px;
  background: orange;
  border: 1px blue solid;
}
.box21 {
  background: yellow;
}
.box222 {
  background: white;
  border: 1px blue solid;
  margin-top: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><md-content class="md-padding">
  <div class="main columns vertical">
    <nav class="box1">nav</nav>
    <div class="box columns vertical">
      <div class="b">asdasd</div>
      <div class="box2 columns vertical">
        <div class="box21 columns">
          box21
        </div>
        <div class="box22 columns">
          <div class="box221">box221</div>
          <div class="box222">
            <p>a</p>
            <p>a</p>
            <p>a</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</md-content></code>```

答:
consider using max-height instead of height on main also... if you start with flexbox... best to keep display: flex through the whole chain

.top {
  position: static;
  height: 200px;
  width: 200px;
  max-height: 200px;
  max-width: 200px;
  overflow: auto;
}

.flexcol {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.mynav {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
  background-color: blue;
}

.box1 {
  display: flex;
  flex-grow: 1;
  background-color: red;
}

.box2 {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  background-color: green;
}

.box3 {
  display: flex;
  flex-grow: 1;
  background-color: yellow;
}

.box221 {
  min-height: 50px;
  background-color: pink;
  width: 100%;
}

.box222 {
  min-height: 50px;
  background-color: grey;
  width: 100%;
}

.darklink {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="top">
  <div class="flexcol">
    <nav class="mynav">
      Link1
      Link2
      Link3
   </nav>
    <div class="box1">
      <p>para</p>
    </div>
    <div class="box2">
      <div class="box221">
        <p>para</p>
        <p>para</p>
      </div>
      <div class="box222">
        <p>para</p>
        <p>para</p>
        <p>para</p>
      </div>
    </div>
    <div class="box3">
      <p>para</p>
    </div>
  </div>
</div></code>```

Body:
.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}

.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  background: orange;
  border: 1px blue solid;
}
.box222 {
  background: white;
  border: 1px blue solid;
}

<md-content class="md-padding">

    nav

asdasd

          box21

box221

a

a

</md-content>

I manually set the height of outermost box main and also set box22 with overflow:auto, however the box22 stretched out the main box and no scroll bar shows up.

What I want is to set height in the outermost box and the nested inner box can automitically control it's height thus all boxes are fitted. How to fix these kind of problem, should I set heights for all descendant boxes?

I tested setting overflow :auto at box(level1), box2(level2) and box22(level3), only box(level1) can automatically control it's height and shows up a scroll bar when it's height overlayed.

what I want is shown below, however, to achieve this, I need to manually specify the father box of box22. In other words, if I want to make a flex contaner scrollable, I have to at least set it's father box's height, which is toally unaccptable.

.main {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background: green;
}
.columns {
  display: flex;
}

.columns.vertical {
  flex-direction: column;
  flex-wrap: nowrap;
}
.box22 {
  overflow: auto;
}
.box1 {
  background: red;
}
.box2 {
  height:64px;
  background: orange;
  border: 1px blue solid;
}
.box21 {
  background: yellow;
}
.box222 {
  background: white;
  border: 1px blue solid;
  margin-top: auto;
}

<md-content class="md-padding">

    nav

asdasd

          box21

box221

a

a

a

</md-content>

Body:
consider using max-height instead of height on main also... if you start with flexbox... best to keep display: flex through the whole chain

.top {
  position: static;
  height: 200px;
  width: 200px;
  max-height: 200px;
  max-width: 200px;
  overflow: auto;
}

.flexcol {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.mynav {
  display: flex;
  flex-direction: row;
  flex-grow: 1;
  background-color: blue;
}

.box1 {
  display: flex;
  flex-grow: 1;
  background-color: red;
}

.box2 {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  background-color: green;
}

.box3 {
  display: flex;
  flex-grow: 1;
  background-color: yellow;
}

.box221 {
  min-height: 50px;
  background-color: pink;
  width: 100%;
}

.box222 {
  min-height: 50px;
  background-color: grey;
  width: 100%;
}

.darklink {
  color: white;
}

<div class="top">
  <div class="flexcol">
    <nav class="mynav">
      <a class="darklink" href="#" target="_">Link1</a>
      <a class="darklink" href="#" target="_">Link2</a>
      <a class="darklink" href="#" target="_">Link3</a>
   </nav>
    <div class="box1">
      <p>para</p>
    </div>
    <div class="box2">
      <div class="box221">
        <p>para</p>
        <p>para</p>
      </div>
      <div class="box222">
        <p>para</p>
        <p>para</p>
        <p>para</p>
      </div>
    </div>
    <div class="box3">
      <p>para</p>
    </div>
  </div>
</div>


问:
Getting a list of radio station URLs from iTunes?
I would like to get the same list of radio stations as displayed by iTunes. I think it's a dynamic list.

Any suggestions on how/where I can obtain the same list of radio stations? I would like to do this in objective-c.

答: www.shoutcast.com has a developer API.</p>

ContentLicense: CC BY-SA 3.0

Body: www.shoutcast.com has a developer API.


问:
facebook c# sdk - The user hasn't authorized the application to perform this action
I am building a console app that will publish streams to a page's wall.

Issue: I'm getting "The user hasn't authorized the application to perform this action".  I'm using opengraph to get the access token.

Am I missing something?  Any help is greatly appreciated.  Thanks!

```<code>// constants
string apiKey = "XXX";
string secret = "XXX";
string pageId = "XXX";

// get access token
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", apiKey, secret); // todo: figure out open graph url
WebRequest req = WebRequest.Create(url);
WebResponse resp = req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
string respStr = reader.ReadToEnd();
string accessToken = respStr.Replace("access_token=", "");

// construct the post
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.picture = "www.google.com/pic.png";
messagePost.link = "www.google.com";
messagePost.name = "some name";
messagePost.captiion = "some caption";
messagePost.description = "some description";
messagePost.req_perms = "publish_stream";
messagePost.scope = "publish_stream";

// using client
FacebookClient client = new FacebookClient(accessToken);

try // to post the post to the page's wall
{
    var result = client.Post(string.Format("/{0}/feed", pageId), messagePost);
}
    catch (FacebookOAuthException ex)
{
    // getting caught here, with error msg = "The user hasn't authorized the application to perform this action"
}
catch (FacebookApiException ex)
{
    // ignore
}
</code>```

答:
"Liking your application" and "allowing your application to post to his wall" are two different sentences. There is no magic wand that allows you to override a user's preference whether they like you or not.

Your best bet is to handle the "failure" and move on to the next person. If you want to know likers that don't want you to post to their wall, you can get that information in the return and store it in some type of "log".

Body:
I am building a console app that will publish streams to a page's wall.

Issue: I'm getting "The user hasn't authorized the application to perform this action".  I'm using opengraph to get the access token.

Am I missing something?  Any help is greatly appreciated.  Thanks!

// constants
string apiKey = "XXX";
string secret = "XXX";
string pageId = "XXX";

// get access token
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials", apiKey, secret); // todo: figure out open graph url
WebRequest req = WebRequest.Create(url);
WebResponse resp = req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
string respStr = reader.ReadToEnd();
string accessToken = respStr.Replace("access_token=", "");

// construct the post
dynamic messagePost = new ExpandoObject();
messagePost.access_token = accessToken;
messagePost.picture = "www.google.com/pic.png";
messagePost.link = "www.google.com";
messagePost.name = "some name";
messagePost.captiion = "some caption";
messagePost.description = "some description";
messagePost.req_perms = "publish_stream";
messagePost.scope = "publish_stream";

// using client
FacebookClient client = new FacebookClient(accessToken);

try // to post the post to the page's wall
{
    var result = client.Post(string.Format("/{0}/feed", pageId), messagePost);
}
    catch (FacebookOAuthException ex)
{
    // getting caught here, with error msg = "The user hasn't authorized the application to perform this action"
}
catch (FacebookApiException ex)
{
    // ignore
}


问:
Why is my app not working in background mode but foreground it is working?
I want to create an app as when a particular time comes it calls an API. I have done in it the foreground, but when the app is in the background, it is not executing. How can I solve the issue?

My code is below:

```<code>@objc func runCode() {
    print("runcode")
    timeLabel.text = "Pls select time"
}

@IBAction func dateChange(_ sender: UIDatePicker) {
    if (timer != nil) {
        timer.invalidate()
    }
    print("print \(sender.date)")

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm E, d MMM y"
    let somedateString = dateFormatter.string(from: sender.date)

    print(somedateString)
    timer = Timer(fireAt: sender.date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: .common)
    timeLabel.text = "api will trigger at \(somedateString)"
}

@IBAction func switchAction(_ sender: UISwitch) {
    if stateSwitch.isOn {
        date.isHidden = false
        print("The Switch is on")
        timeLabel.text = "Pls select time"
    } else {
        date.isHidden = true
        if (timer != nil) {
            timer.invalidate()
        }
        timeLabel.text = "Timer not activated"
        print("Timer not activated")
    }
}
</code>```

答: You can't.  You can register for background processing so that your app is allotted a little time in which to do some work.  You cannot control when that time allotment will arrive though.  It can be as frequent as every 20 minutes or so but it can also be much longer.  </p>

Body:
I want to create an app as when a particular time comes it calls an API. I have done in it the foreground, but when the app is in the background, it is not executing. How can I solve the issue?

My code is below:

@objc func runCode() {
    print("runcode")
    timeLabel.text = "Pls select time"
}

@IBAction func dateChange(_ sender: UIDatePicker) {
    if (timer != nil) {
        timer.invalidate()
    }
    print("print \(sender.date)")

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm E, d MMM y"
    let somedateString = dateFormatter.string(from: sender.date)

    print(somedateString)
    timer = Timer(fireAt: sender.date, interval: 0, target: self, selector: #selector(runCode), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: .common)
    timeLabel.text = "api will trigger at \(somedateString)"
}

@IBAction func switchAction(_ sender: UISwitch) {
    if stateSwitch.isOn {
        date.isHidden = false
        print("The Switch is on")
        timeLabel.text = "Pls select time"
    } else {
        date.isHidden = true
        if (timer != nil) {
            timer.invalidate()
        }
        timeLabel.text = "Timer not activated"
        print("Timer not activated")
    }
}


问:
Angular 9: how to re-render component
I have one parent and one child component. If the child component updates its value internally I am unable to update value back from Parent.

See the example in this Stackblitz: https://stackblitz.com/edit/angular-ivy-tynepp. When the child component loses focus I fire an event and the parent resets value of the child component. But I think that because the parent's "this.value" didn't change that the update doesn't trigger detection changes in the child.

How can I solve this dilemma?

答:
As you said, change detection is not triggered because the bound value has not changed. You can force an update of the data binding with the following steps:

Set a temporary value

Call ChangeDetectorRef.detectChanges()

Reset the value

constructor(private changeDetectorRef: ChangeDetectorRef) {}

resetValue() {
  this.value = "____TempValue____";
  this.changeDetectorRef.detectChanges();
  this.value = "";
}
```

See this stackblitz for a demo.

Title: Angular 9: how to re-render component

Body:
As you said, change detection is not triggered because the bound value has not changed. You can force an update of the data binding with the following steps:

Set a temporary value

Call ChangeDetectorRef.detectChanges()

Reset the value

constructor(private changeDetectorRef: ChangeDetectorRef) {}

resetValue() {
  this.value = "____TempValue____";
  this.changeDetectorRef.detectChanges();
  this.value = "";
}

See this stackblitz for a demo.


问:
How to show right-click context menu in WebView of Android app on Chromebook
I'm developing an Android app that has a WebView which shows various content. When I long-click with my finger (touch for a longer time) some text, a standard (horizontal) Android context menu popups up. However when I right-click with the mouse or touchpad in the same WebView no context menu is shown - and it doesn't matter if some text is selected or not.

I've tried looking through a lot of solutions, and even the the callback brought to setOnContextClickListener (as shown here) isn't called when right-clicking (however the generic motion event callbacks are called), so it seems like it's not supported at all in WebViews.

In the end it seems like I would have to create my own context menu. I'm just wondering if there isn't any standard one that just has to be enabled in some way.

What I would like to have is something similar to the EditText right-click context menu which is vertical, but I haven't been able to show either of the two when right-clicking. Both horizontal and vertical menus are shown here.

I'm testing on a HP Chromebook x360 11 G1 EE if that makes a difference.

答:
You can override the onTouchEvent(MotionEvent event) in the WebView and detect the event.getButtonState() to see which button was clicked.

```<code>    switch (event.getButtonState()) {
        case MotionEvent.BUTTON_PRIMARY:
            onMouseClickListener.onLeftClick();
            break;

        case MotionEvent.BUTTON_SECONDARY:
            onMouseClickListener.onRightClick();
            break;
    }
</code>```

Please note that the onMouseClickListener is a custom listener for this event.

Body:
You can override the onTouchEvent(MotionEvent event) in the WebView and detect the event.getButtonState() to see which button was clicked.

    switch (event.getButtonState()) {
        case MotionEvent.BUTTON_PRIMARY:
            onMouseClickListener.onLeftClick();
            break;

        case MotionEvent.BUTTON_SECONDARY:
            onMouseClickListener.onRightClick();
            break;
    }

Please note that the onMouseClickListener is a custom listener for this event.


问:
Using SQLDF to select specific values from a column
SQLDF newbie here.

I have a data frame which has about 15,000 rows and 1 column.
The data looks like:

```<code>cars
autocar
carsinfo
whatisthat
donnadrive
car
telephone
...
</code>```

I wanted to use the package sqldf to loop through the column and
pick all values which contain "car" anywhere in their value.
However, the following code generates an error.

```<code>> sqldf("SELECT Keyword FROM dat WHERE Keyword="car")
Error: unexpected symbol in "sqldf("SELECT Keyword FROM dat WHERE Keyword="car"
</code>```

There is no unexpected symbol, so I'm not sure whats wrong.

so first, I want to know all the values which contain 'car'.
then I want to know only those values which contain just 'car' by itself.

Can anyone help.

EDIT:

allright, there was an unexpected symbol, but it only gives me just car and not every
row which contains 'car'.

```<code>> sqldf("SELECT Keyword FROM dat WHERE Keyword='car'")
  Keyword
1     car
</code>```

答:
This has nothing to do with sqldf; your SQL statement is the problem.  You need:

```<code>dat <- data.frame(Keyword=c("cars","autocar","carsinfo",
  "whatisthat","donnadrive","car","telephone"))
sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")
#    Keyword
# 1     cars
# 2  autocar
# 3 carsinfo
# 4      car
</code>```

Body:
SQLDF newbie here.

I have a data frame which has about 15,000 rows and 1 column.
The data looks like:

cars
autocar
carsinfo
whatisthat
donnadrive
car
telephone
...

I wanted to use the package sqldf to loop through the column and
pick all values which contain "car" anywhere in their value.
However, the following code generates an error.

> sqldf("SELECT Keyword FROM dat WHERE Keyword="car")
Error: unexpected symbol in "sqldf("SELECT Keyword FROM dat WHERE Keyword="car"

There is no unexpected symbol, so I'm not sure whats wrong.

so first, I want to know all the values which contain 'car'.
then I want to know only those values which contain just 'car' by itself.

Can anyone help.

EDIT:

allright, there was an unexpected symbol, but it only gives me just car and not every
row which contains 'car'.

> sqldf("SELECT Keyword FROM dat WHERE Keyword='car'")
  Keyword
1     car

Body:
This has nothing to do with sqldf; your SQL statement is the problem.  You need:

dat <- data.frame(Keyword=c("cars","autocar","carsinfo",
  "whatisthat","donnadrive","car","telephone"))
sqldf("SELECT Keyword FROM dat WHERE Keyword like '%car%'")
#    Keyword
# 1     cars
# 2  autocar
# 3 carsinfo
# 4      car


问:
How do I get the value of a fetch call to pass to my component and have the component re-render?
I'm trying to build a React 16.13.0 application.  I have created the following FormContainer in which I'm trying to pass a value in a prop variable ("suggestions") after I load data in my "componentDidMount" method ...

```<code>class FormContainer extends Component {
  static DEFAULT_COUNTRY = 484
  static REACT_APP_PROXY = process.env.REACT_APP_PROXY

  constructor(props) {
    super(props);

    this.state = {
      countries: [],
      provinces: [],
      errors: [],
      newCoop: {
        name: '',
        types: [{
          name: ''
        }],
        address: {
          formatted: '',
          locality: {
            name: '',
            postal_code: '',
            state: ''
          },
          country: FormContainer.DEFAULT_COUNTRY,
        },
        enabled: true,
        email: '',
        phone: '',
        web_site: ''
      },

    }

...

  render() {
    return (
      <div>
        <form className="container-fluid" onSubmit={this.handleFormSubmit}>
            <FormGroup
                controlId="formBasicText">

                <Input inputType={'text'}
                   title= {'Name'}
                   name= {'name'}
                   value={this.state.newCoop.name}
                   placeholder = {'Enter cooperative name'}
                   handleChange = {this.handleInput}
                   errors = {this.state.errors}
                   /> {/* Name of the cooperative */}

                <CoopTypes
                  name={'types'}
                  suggestions = {this.state.coopTypes}
                  values = {this.state.newCoop.types}
                  placeholder = {'Enter coop type(s)'}
                  handleAddition = {this.handleCoopTypeAddition}
                  handleDeletion = {this.handleCoopTypeDeletion}
                  errors = {this.state.errors}
                /> {/* Coop Type Selection */}

        ...
  }

  componentDidMount() {
    let initialCountries = [];
    let initialProvinces = [];
    let coopTypes = [];
    ...
    // Get all possible coop types
    fetch(FormContainer.REACT_APP_PROXY + '/coop_types/')
        .then(response => {
            return response.json();
        }).then(data => {
        coopTypes = data.map((coopType) => {
            return coopType
        });
        console.log("coop types:");
        console.log(coopTypes);
        this.setState({
            coopTypes: coopTypes,
        });
    });
  }
}
</code>```

Below is the component definition invoked in the form ...

```<code>class CoopTypes extends React.Component {
    constructor(props) {
        super(props);

        console.log("sugestions:");
        console.log(props.suggestions);
        const tags = props.values.map(result => (
            {
                id: result.id,
                text: result.name
            }));
        this.state = {
            tags: tags,
            suggestions: props.values.map(result => ({
                id: result.id,
                text: result.name
            }))
        };
        this.handleDelete = props.handleDelete;
        this.handleAddition = props.handleAddition;
        this.handleDrag = this.handleDrag.bind(this);
    }

    handleDelete(i) {
        const { tags } = this.state;
        this.setState({
         tags: tags.filter((tag, index) => index !== i),
        });
    }

    handleAddition(tag) {
        this.setState(state => ({ tags: [...state.tags, tag] }));
    }

    handleDrag(tag, currPos, newPos) {
        const tags = [...this.state.tags];
        const newTags = tags.slice();

        newTags.splice(currPos, 1);
        newTags.splice(newPos, 0, tag);

        // re-render
        this.setState({ tags: newTags });
    }

    render() {
        const { tags, suggestions } = this.state;
        return (
            <div>
                <ReactTags tags={this.state.tags}
                    suggestions={this.state.suggestions}
                    handleDelete={this.handleDelete}
                    handleAddition={this.handleAddition}
                    handleDrag={this.handleDrag}
                    delimiters={delimiters} />
            </div>
        )
    }
};

export default CoopTypes;
</code>```

The problem is after the "fetch" call loads, the component doesn't re-render.  That is, it always renders with a value of "null" for the suggestions props.  What do I need to do so that after the fetch calls loads, the value is passed on to the component?

答:
suggestions: props.values.map(result

wrong prop used,

updated props (if updated) are not reflected to state (constructor called once)

You can use props.suggestions (.map) directly in render (using local variables) without 'buffering' in state (and taking care of props updates). Using functional components can be easier to follow [dependencies].

hint:
You can place console.log in render() to be sure it is rendered (or not) with current suggestion props.

This looks a bit strange:

```<code>    this.handleDelete = props.handleDelete;
    this.handleAddition = props.handleAddition;
    this.handleDrag = this.handleDrag.bind(this);
</code>```

This looks a bit strange - your class handlers (handleDelete, 'handleAddition' functions) are your this.handleDelete and this.handleAddition. Overwriting them (in constructor) with props-handlers makes a little [no?] sense. Both this-handlers should be binded as this.handleDrag is. You can use props-handlers from this-handlers (conditionally, if defined).

Body:
I'm trying to build a React 16.13.0 application.  I have created the following FormContainer in which I'm trying to pass a value in a prop variable ("suggestions") after I load data in my "componentDidMount" method ...

class FormContainer extends Component {
  static DEFAULT_COUNTRY = 484
  static REACT_APP_PROXY = process.env.REACT_APP_PROXY

  constructor(props) {
    super(props);

    this.state = {
      countries: [],
      provinces: [],
      errors: [],
      newCoop: {
        name: '',
        types: [{
          name: ''
        }],
        address: {
          formatted: '',
          locality: {
            name: '',
            postal_code: '',
            state: ''
          },
          country: FormContainer.DEFAULT_COUNTRY,
        },
        enabled: true,
        email: '',
        phone: '',
        web_site: ''
      },

    }

...

  render() {
    return (

        <form className="container-fluid" onSubmit={this.handleFormSubmit}>
            <FormGroup
                controlId="formBasicText">

                <Input inputType={'text'}
                   title= {'Name'}
                   name= {'name'}
                   value={this.state.newCoop.name}
                   placeholder = {'Enter cooperative name'}
                   handleChange = {this.handleInput}
                   errors = {this.state.errors}
                   /> {/* Name of the cooperative */}

                <CoopTypes
                  name={'types'}
                  suggestions = {this.state.coopTypes}
                  values = {this.state.newCoop.types}
                  placeholder = {'Enter coop type(s)'}
                  handleAddition = {this.handleCoopTypeAddition}
                  handleDeletion = {this.handleCoopTypeDeletion}
                  errors = {this.state.errors}
                /> {/* Coop Type Selection */}

        ...
  }

  componentDidMount() {
    let initialCountries = [];
    let initialProvinces = [];
    let coopTypes = [];
    ...
    // Get all possible coop types
    fetch(FormContainer.REACT_APP_PROXY + '/coop_types/')
        .then(response => {
            return response.json();
        }).then(data => {
        coopTypes = data.map((coopType) => {
            return coopType
        });
        console.log("coop types:");
        console.log(coopTypes);
        this.setState({
            coopTypes: coopTypes,
        });
    });
  }
}

Below is the component definition invoked in the form ...

class CoopTypes extends React.Component {
    constructor(props) {
        super(props);

        console.log("sugestions:");
        console.log(props.suggestions);
        const tags = props.values.map(result => (
            {
                id: result.id,
                text: result.name
            }));
        this.state = {
            tags: tags,
            suggestions: props.values.map(result => ({
                id: result.id,
                text: result.name
            }))
        };
        this.handleDelete = props.handleDelete;
        this.handleAddition = props.handleAddition;
        this.handleDrag = this.handleDrag.bind(this);
    }

    handleDelete(i) {
        const { tags } = this.state;
        this.setState({
         tags: tags.filter((tag, index) => index !== i),
        });
    }

    handleAddition(tag) {
        this.setState(state => ({ tags: [...state.tags, tag] }));
    }

    handleDrag(tag, currPos, newPos) {
        const tags = [...this.state.tags];
        const newTags = tags.slice();

        newTags.splice(currPos, 1);
        newTags.splice(newPos, 0, tag);

        // re-render
        this.setState({ tags: newTags });
    }

    render() {
        const { tags, suggestions } = this.state;
        return (

                <ReactTags tags={this.state.tags}
                    suggestions={this.state.suggestions}
                    handleDelete={this.handleDelete}
                    handleAddition={this.handleAddition}
                    handleDrag={this.handleDrag}
                    delimiters={delimiters} />

        )
    }
};

export default CoopTypes;

The problem is after the "fetch" call loads, the component doesn't re-render.  That is, it always renders with a value of "null" for the suggestions props.  What do I need to do so that after the fetch calls loads, the value is passed on to the component?

Body:
suggestions: props.values.map(result

wrong prop used,

updated props (if updated) are not reflected to state (constructor called once)

You can use props.suggestions (.map) directly in render (using local variables) without 'buffering' in state (and taking care of props updates). Using functional components can be easier to follow [dependencies].

hint:
You can place console.log in render() to be sure it is rendered (or not) with current suggestion props.

This looks a bit strange:

    this.handleDelete = props.handleDelete;
    this.handleAddition = props.handleAddition;
    this.handleDrag = this.handleDrag.bind(this);

This looks a bit strange - your class handlers (handleDelete, 'handleAddition' functions) are your this.handleDelete and this.handleAddition. Overwriting them (in constructor) with props-handlers makes a little [no?] sense. Both this-handlers should be binded as this.handleDrag is. You can use props-handlers from this-handlers (conditionally, if defined).


问:
Network connection was lost during `application:openURL:options`
We are using deep links to complete verification for an app we're working on. Said deep links cause the app delegate method:

```<code>- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
</code>```

To be called. This app is using React Native, using the in-build Linking API. Some of the time making a network request when we get the Linking callback works, but sometimes we get a networking error:

```<code>Task <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=53, NSUnderlyingError=0x283352ac0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x281ed9130 [0x1e9babcb0]>{length = 16, capacity = 16, bytes = 0x100201bb34d2847e0000000000000000}, _kCFStreamErrorCodeKey=53, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180>"
</code>```

I've had a pretty extensive google and it seems to be suggested that this can be caused when a network request is made in the background, however Apple quite clearly state in the docs for this method:

If a URL arrives while your app is suspended or running in the background, the system moves your app to the foreground prior to calling this method.

Is there something we shouldn't be doing here? Has anyone else seen similar issues?

Update

It seems this works fine first time the link is opened after app-launch, but subsequent calls fail. Nothing seems to be called in a different order, so it's very confusing why we'd see this sort of pattern!

答:
I've got same problem and I notice this happens only with a short-form of link. According to the document, a short link is related with network.

To create a short Dynamic Link, build a DynamicLinkComponents the same way, and then call shorten().

Building a short link requires a network call, so instead of directly returning the link, shorten() accepts a completion handler, which is called when the request completes. For example:

I am guessing there is a network problem with apple API or firebase API.

So here is my solution. I create a new category and function called handleUniversalLinkDelayNetorkCall. I moved all source code from handleUniversalLink and just call resolveShortLink after some delay.

Sorry for my english and see full source code.

```<code>@implementation FIRDynamicLinks (FIRDynamicLinks_HandleUniversalLink_BugFixed)

- (BOOL)handleUniversalLinkDelayNetorkCall:(NSURL *)universalLinkURL completion:(FIRDynamicLinkUniversalLinkHandler)completion {

    if ([self matchesShortLinkFormat:universalLinkURL]) {

        // delay call
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            __weak __typeof__(self) weakSelf = self;
            [self resolveShortLink:universalLinkURL
                        completion:^(NSURL *url, NSError *error) {
                __typeof__(self) strongSelf = weakSelf;
                if (strongSelf) {
                    FIRDynamicLink *dynamicLink = [strongSelf dynamicLinkFromCustomSchemeURL:url];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(dynamicLink, error);
                    });
                } else {
                    completion(nil, nil);
                }
            }];
        });

        return YES;
    } else {
        FIRDynamicLink *dynamicLink = [self dynamicLinkFromUniversalLinkURL:universalLinkURL];
        if (dynamicLink) {
            completion(dynamicLink, nil);
            return YES;
        }
    }

    return NO;
}
</code>```

This works for me. Cheers.

Body:
We are using deep links to complete verification for an app we're working on. Said deep links cause the app delegate method:

- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{

To be called. This app is using React Native, using the in-build Linking API. Some of the time making a network request when we get the Linking callback works, but sometimes we get a networking error:

Task <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=53, NSUnderlyingError=0x283352ac0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x281ed9130 [0x1e9babcb0]>{length = 16, capacity = 16, bytes = 0x100201bb34d2847e0000000000000000}, _kCFStreamErrorCodeKey=53, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <D47D1F90-E2D1-4AB7-8706-8737B68CC5E8>.<180>"

I've had a pretty extensive google and it seems to be suggested that this can be caused when a network request is made in the background, however Apple quite clearly state in the docs for this method:

If a URL arrives while your app is suspended or running in the background, the system moves your app to the foreground prior to calling this method.

Is there something we shouldn't be doing here? Has anyone else seen similar issues?

Update

It seems this works fine first time the link is opened after app-launch, but subsequent calls fail. Nothing seems to be called in a different order, so it's very confusing why we'd see this sort of pattern!

Body:
I've got same problem and I notice this happens only with a short-form of link. According to the document, a short link is related with network.

To create a short Dynamic Link, build a DynamicLinkComponents the same way, and then call shorten().

Building a short link requires a network call, so instead of directly returning the link, shorten() accepts a completion handler, which is called when the request completes. For example:

I am guessing there is a network problem with apple API or firebase API.

So here is my solution. I create a new category and function called handleUniversalLinkDelayNetorkCall. I moved all source code from handleUniversalLink and just call resolveShortLink after some delay.

Sorry for my english and see full source code.

@implementation FIRDynamicLinks (FIRDynamicLinks_HandleUniversalLink_BugFixed)

- (BOOL)handleUniversalLinkDelayNetorkCall:(NSURL *)universalLinkURL completion:(FIRDynamicLinkUniversalLinkHandler)completion {

    if ([self matchesShortLinkFormat:universalLinkURL]) {

        // delay call
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            __weak __typeof__(self) weakSelf = self;
            [self resolveShortLink:universalLinkURL
                        completion:^(NSURL *url, NSError *error) {
                __typeof__(self) strongSelf = weakSelf;
                if (strongSelf) {
                    FIRDynamicLink *dynamicLink = [strongSelf dynamicLinkFromCustomSchemeURL:url];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        completion(dynamicLink, error);
                    });
                } else {
                    completion(nil, nil);
                }
            }];
        });

        return YES;
    } else {
        FIRDynamicLink *dynamicLink = [self dynamicLinkFromUniversalLinkURL:universalLinkURL];
        if (dynamicLink) {
            completion(dynamicLink, nil);
            return YES;
        }
    }

    return NO;
}

This works for me. Cheers.


问:
How to copy a specific text from html attribute to a PHP String?
```<code><input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">
</code>```

This is the code which is generated, I made a string $payid, but it copies the whole code. All I need is hashValue=

$payid = getStr($html, '< input type="hidden" name="payFormParams" id="payFormParams" value="','">');
```

But I want to just copy the value of hashValue into $payid that is just 6a1562f5c4901522ab6926a4caf9f278
Can someone please help me how to do this? I am lost. I need help with it.

答:
You can use explode to get the value of the hash if it is the last key/value pair in the string using the following method...

Online PHP Editer:

https://3v4l.org/kUrJs

$html = '<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">';

//Explode the input tag as a string at the `=` operators.
$ex = explode('=', $html);

// now use the count of the exploded array as a reference and subtract the keys by one to get the value of the hash.
$target = $ex[count($ex) - 1];

// This leaves you with a value that has the hash followed by a double quote and the closing tag for the input, explode again using the double quote
$hash = explode('"', $target);

// This leaves the hash and the symbols in our array, use the first key of 0 to get the value of the hash as you want it.
$targetHash = $hash[0];
```

<p><strong><em>RETURNS:</em></strong> </p>

<p><code>6a1562f5c4901522ab6926a4caf9f278</code></p>

<p>If you are not sure where the hash is in the string, you could use the explode method and search for the key of <code>hash</code>, knowing the NEXT value will be the actual hash...So it would look something like the following... </p>

<p>Once you explode the string by <code>=</code>, you have the value <code>&hashValue</code> to search for, you know the next value in the exploded array will be the actual hash. So we run a foreach and look for that value and then locate the key of the <code>key</code> turned <code>value</code> and we use that to search for the hash, ie <code>key + 1</code>. This will give us the hash with double quotes explode those and get the hash.</p>

<pre class="lang-php prettyprint-override"><code>$html = '<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&hashValue=6a1562f5c4901522ab6926a4caf9f278=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=>';

//--> Explode at the `=` operator and create an array to hold the exploded values
$ex = explode('=', $html);

//--> Run a loop and iterate over the key/value pairs to search for our target
foreach($ex as $key => $value){
  //--> Since we exploded at the `=` operator, we know the target string is `&hashValue` iterate through array and find that key/value pair
  if($value === '&hashValue'){

    //--> We know the hash is the next value in the array, so use the current key + 1 to find the hash
    $targetKey = $key + 1;
    //--> The next step is not needed if you do not have double quotes after or before the hash.
    //--> Simply use the targetKey to get the value of the hash --> $ex[$targetKey]
    //--> The following only applies if there is a trailing double quote left on the hash
    //--> If you have 6a1562f5c4901522ab6926a4caf9f278" left over
    $hash = explode('"', $ex[$targetKey]);
    $targetHash = $hash[0];
    echo $targetHash;
  }
}
</code>```

RETURNS:

6a1562f5c4901522ab6926a4caf9f278

Now you can copy the value of the hash in $targetHash anywhere you'd like...

If you would like a better understanding of how this works, simply add a print_r() after each step and see how the explode returns the information with each step...

Body:
<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">

This is the code which is generated, I made a string $payid, but it copies the whole code. All I need is hashValue=

$payid = getStr($html, '< input type="hidden" name="payFormParams" id="payFormParams" value="','">');

But I want to just copy the value of hashValue into $payid that is just 6a1562f5c4901522ab6926a4caf9f278
Can someone please help me how to do this? I am lost. I need help with it.

Body:
You can use explode to get the value of the hash if it is the last key/value pair in the string using the following method...

Online PHP Editer:

https://3v4l.org/kUrJs

$html = '<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=&hashValue=6a1562f5c4901522ab6926a4caf9f278">';

//Explode the input tag as a string at the `=` operators.
$ex = explode('=', $html);

// now use the count of the exploded array as a reference and subtract the keys by one to get the value of the hash.
$target = $ex[count($ex) - 1];

// This leaves you with a value that has the hash followed by a double quote and the closing tag for the input, explode again using the double quote
$hash = explode('"', $target);

// This leaves the hash and the symbols in our array, use the first key of 0 to get the value of the hash as you want it.
$targetHash = $hash[0];

RETURNS:

6a1562f5c4901522ab6926a4caf9f278

If you are not sure where the hash is in the string, you could use the explode method and search for the key of hash, knowing the NEXT value will be the actual hash...So it would look something like the following...

Once you explode the string by =, you have the value &hashValue to search for, you know the next value in the exploded array will be the actual hash. So we run a foreach and look for that value and then locate the key of the key turned value and we use that to search for the hash, ie key + 1. This will give us the hash with double quotes explode those and get the hash.

$html = '<input type="hidden" name="payFormParams" id="payFormParams" value="payment_type=PaymentForm&merchant_id=117589463&trnType=P&errorPage=%2Fscripts%2Fpayment%2Fpayment%2Easp&approvedPage=&declinedPage=&epe_client_found=false&trnLanguage=eng&shipping_method=&ref1=&ref2=&ref3=&ref4=&ref5=&shippingMethod=&deliveryEstimate=&ordTax1Price=&ordTax2Price=&ordItemPrice=0&ordShippingPrice=0&trnOrderNumber=51029&trnAmount=5%2E00&ordName=Surreal+View&ordEmailAddress=xx%40gmail%2Ecom&ordPhoneNumber=2039581030&ordAddress1=3501+Jack+Northrop+Ave&ordCity=Hawthorne&ordProvince=CA&ordPostalCode=90250&ordCountry=US&paymentMethod=CC&trnCardOwner=Suyash&trnCardCvd=xxx&cavBirthMonth=&cavBirthDay=&cavBirthYear=&cavSin=&paymentAction=&hashValue=6a1562f5c4901522ab6926a4caf9f278=&trnCardNumber=xxxxxxxxx0412300&trnExpMonth=xx&trnExpYear=xx&aDFinancingType=&aDPlanNumber=&aDGracePeriod=&aDTerm=>';

//--> Explode at the `=` operator and create an array to hold the exploded values
$ex = explode('=', $html);

//--> Run a loop and iterate over the key/value pairs to search for our target
foreach($ex as $key => $value){
  //--> Since we exploded at the `=` operator, we know the target string is `&hashValue` iterate through array and find that key/value pair
  if($value === '&hashValue'){

    //--> We know the hash is the next value in the array, so use the current key + 1 to find the hash
    $targetKey = $key + 1;
    //--> The next step is not needed if you do not have double quotes after or before the hash.
    //--> Simply use the targetKey to get the value of the hash --> $ex[$targetKey]
    //--> The following only applies if there is a trailing double quote left on the hash
    //--> If you have 6a1562f5c4901522ab6926a4caf9f278" left over
    $hash = explode('"', $ex[$targetKey]);
    $targetHash = $hash[0];
    echo $targetHash;
  }
}

RETURNS:

6a1562f5c4901522ab6926a4caf9f278

Now you can copy the value of the hash in $targetHash anywhere you'd like...

If you would like a better understanding of how this works, simply add a print_r() after each step and see how the explode returns the information with each step...


问:
How to take information from a json file from the internet using requests
So, there's this file that I've uploaded in github, and I want my program to take it from there and then save the content written on it in the directory. I've been trying this code:

```<code>import json
import requests

r = requests.get('https://github.com/Gevez/gameficacao/blob/master/data.json')

with open('data.json','wb') as data:
    data.write(r.content)
</code>```

And the program puts a data.json file in the main directory, but instead of the info that was written in the original file, the json file is filled with the code from the entire githubb page, I will post bellow for reference:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
  <link rel="dns-prefetch" href="https://github.githubassets.com">
  <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com">
  <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
  <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">

  <link crossorigin="anonymous" media="all" integrity="sha512-veKG2ootplNGLwNEW5It4+lJXwpdOVR1Ry4MBDNvdgL6OgBkiAXaZAZnIKkw6sIygnfGqQhR5q7UdS1llqd6/g==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-bde286da8a2da653462f03445b922de3.css" />
  <link crossorigin="anonymous" media="all" integrity="sha512-SIdH/u1H0WymCGxSKvv9kCVqCpgpL7GuBc5dVtA1UApgTky3oIA6YLFIzjYiN7fjVk/vZcu/QX5sobbu5BCkmg==" rel="stylesheet" href="https://github.githubassets.com/assets/site-488747feed47d16ca6086c522afbfd90.css" />
    <link crossorigin="anonymous" media="all" integrity="sha512-yFRb1O2qllOz/OaFeBzmzWyBBviD8afa5Dc0KKyFZdGvwwzp+I9EFHwjUsNhh2fZp/LWptUugh8+JrE1rtq10A==" rel="stylesheet" href="https://github.githubassets.com/assets/github-c8545bd4edaa9653b3fce685781ce6cd.css" />
</code>```

And then it goes on. That's very much not what I was expecting, I really want to download a json.filwith exactly like the one I have uploaded at github.

Please help me.

答:
Have you tried using this url instead?

https://raw.githubusercontent.com/Gevez/gameficacao/master/data-teste-2.json

I think you need the raw output from github.

Body:
So, there's this file that I've uploaded in github, and I want my program to take it from there and then save the content written on it in the directory. I've been trying this code:

import json
import requests

r = requests.get('https://github.com/Gevez/gameficacao/blob/master/data.json')

with open('data.json','wb') as data:
    data.write(r.content)

And the program puts a data.json file in the main directory, but instead of the info that was written in the original file, the json file is filled with the code from the entire githubb page, I will post bellow for reference:

<!DOCTYPE html>

    <meta charset="utf-8">
  <link rel="dns-prefetch" href="https://github.githubassets.com">
  <link rel="dns-prefetch" href="https://avatars0.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars1.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars2.githubusercontent.com">
  <link rel="dns-prefetch" href="https://avatars3.githubusercontent.com">
  <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
  <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">

  <link crossorigin="anonymous" media="all" integrity="sha512-veKG2ootplNGLwNEW5It4+lJXwpdOVR1Ry4MBDNvdgL6OgBkiAXaZAZnIKkw6sIygnfGqQhR5q7UdS1llqd6/g==" rel="stylesheet" href="https://github.githubassets.com/assets/frameworks-bde286da8a2da653462f03445b922de3.css" />
  <link crossorigin="anonymous" media="all" integrity="sha512-SIdH/u1H0WymCGxSKvv9kCVqCpgpL7GuBc5dVtA1UApgTky3oIA6YLFIzjYiN7fjVk/vZcu/QX5sobbu5BCkmg==" rel="stylesheet" href="https://github.githubassets.com/assets/site-488747feed47d16ca6086c522afbfd90.css" />
    <link crossorigin="anonymous" media="all" integrity="sha512-yFRb1O2qllOz/OaFeBzmzWyBBviD8afa5Dc0KKyFZdGvwwzp+I9EFHwjUsNhh2fZp/LWptUugh8+JrE1rtq10A==" rel="stylesheet" href="https://github.githubassets.com/assets/github-c8545bd4edaa9653b3fce685781ce6cd.css" />

And then it goes on. That's very much not what I was expecting, I really want to download a json.filwith exactly like the one I have uploaded at github.

Please help me.


问:
Apache Cannot load modules/libphp5.so into server: when I installed php5-gd
I was trying to install php5-gd but after ran this command:

```<code>yum install php-gd php-tidy
</code>```

and tried to restart apache:

```<code>httpd -k restart
</code>```

I got the following error:

```<code>httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf: Syntax error on line 6 of /etc/httpd/conf.modules.d/10-php.conf: Cannot load modules/libphp5.so into server: /etc/httpd/modules/libphp5.so: symbol SSLeay_version, version OPENSSL_1.0.1 not defined in file libcrypto.so.10 with link time reference
</code>```

Any of you knows why or how can I fix this error?

答:
Try run

sudo dnf install libnsl

Body:
I was trying to install php5-gd but after ran this command:

yum install php-gd php-tidy

and tried to restart apache:

httpd -k restart

I got the following error:

httpd: Syntax error on line 56 of /etc/httpd/conf/httpd.conf: Syntax error on line 6 of /etc/httpd/conf.modules.d/10-php.conf: Cannot load modules/libphp5.so into server: /etc/httpd/modules/libphp5.so: symbol SSLeay_version, version OPENSSL_1.0.1 not defined in file libcrypto.so.10 with link time reference

Any of you knows why or how can I fix this error?

Body:
Try run

sudo dnf install libnsl


问:
SPA, Microservices and Kubernetes (Architectural Question)
First off, let me say that I'm fairly new to Kubernetes and Microservices architecture in general. Let me also say that this is more of a high-level architectural question versus seeking prescriptive, how-to advice related to the technology. I think I can figure the implementation details out, but I'm unsure what mechanisms exist to get me to where I want to go.

Application overview

Simple "e-commerce" sample application running on a K8s cluster. SPA Front end, with .NET Core services for the API.

Client (Front End)

Angular SPA built and deployed to an NGinx container that serves up the Angular App as a static site. It's running as a LoadBalancer service on the cluster.

Services (Back End)

Two simple services running as ClusterIP in the cluster. Let's call them Product and Order.

Problem

When the SPA is deployed, it's making requests to the services from the user's browser versus the container. The services aren't running in a LoadBalancer configuration, so they're not exposed outside the cluster. What's the best practice here for getting the client application talking to the services? Specifically:

Do I really need to expose every microservice externally?

Is there some kind of proxy technique, where I can expose a single <cluster>/api endpoint, that routes to the appropriate backend service?

Does Angular Universal (aka Server-side Rendering) have a part to play here?

Any referenceable repos I can look at for an example?

I've searched through SO and have found similar questions, but none that ask exactly this question. I'll gladly delete this question if someone points me to an existing one that enlightens me.

答:
Do I really need to expose every microservice externally?

No, you shouldn't.

Is there some kind of proxy technique, where I can expose a single /api endpoint, that routes to the appropriate backend service?

Standard way is to use nginx as a proxy.

Any referenceable repos I can look at for an example?

You can check my toy project:

Nginx part here - https://github.com/taleodor/mafia-vue/tree/master/nginx

Deployment wrapper project - https://github.com/taleodor/mafia-deployment

Write-up how everything fits together - https://itnext.io/building-kubernetes-cicd-pipeline-with-github-actions-argocd-and-reliza-hub-e7120b9be870

Specifically, this is how you reference back-end api in nginx from the toy project above (note it's using websockets, which may not be the case for you):

```<code>    location /api {
        proxy_pass http://backend;
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header        X-Forwarded-Proto $http_x_forwarded_proto; # aws version - essentially this sets https schema

        # enable WebSockets
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
</code>```

Body:
Do I really need to expose every microservice externally?

No, you shouldn't.

Is there some kind of proxy technique, where I can expose a single /api endpoint, that routes to the appropriate backend service?

Standard way is to use nginx as a proxy.

Any referenceable repos I can look at for an example?

You can check my toy project:

Nginx part here - https://github.com/taleodor/mafia-vue/tree/master/nginx

Deployment wrapper project - https://github.com/taleodor/mafia-deployment

Write-up how everything fits together - https://itnext.io/building-kubernetes-cicd-pipeline-with-github-actions-argocd-and-reliza-hub-e7120b9be870

Specifically, this is how you reference back-end api in nginx from the toy project above (note it's using websockets, which may not be the case for you):

    location /api {
        proxy_pass http://backend;
        proxy_set_header Host            $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header        X-Forwarded-Proto $http_x_forwarded_proto; # aws version - essentially this sets https schema

        # enable WebSockets
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }