问:
C# How to Hide PowerShell Window
I have met a problem using PowerShell command in a WPF app. The basic requirement here is PowerShell should run in the background without popping up any console window.

However, if I create a RunSpace and run the command in the Pipeline, I can't hide the console window at all. Following is my codes:

```<code>private void RunAppCapture()
{
    var initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new[] { "vmware.appcapture" });

    var runSpace = RunspaceFactory.CreateRunspace(initial);
    runSpace.Open();

    Pipeline pipeline = runSpace.CreatePipeline();

    Command capture = new Command("Start-AVAppCapture");
    capture.Parameters.Add("Name", "Test");
    pipeline.Commands.Add(capture);

    StringBuilder stringBuilder = new StringBuilder();

    pipeline.Invoke();
    if (pipeline.Error.Count > 0)
    {
        while (!pipeline.Error.EndOfPipeline)
        {
            stringBuilder.AppendLine(pipeline.Error.Read().ToString());
        }
    }
    runSpace.Close();

    try
    {
        Result.Dispatcher.Invoke(new Action(() =>
        {
            Result.Text = stringBuilder.ToString();
        }));
    }
    catch (Exception e)
    {
    }
}
</code>```

The only way to hide the window is to run the PowerShell in a process. However, by doing so, I can't reuse the context because I have launch a brand-new PowerShell process every time. Here is my codes:

```<code>private void RunPowerShellProcess()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    Process p = new Process();

    startInfo.CreateNoWindow = true;
    startInfo.RedirectStandardOutput = true;
    startInfo.RedirectStandardInput = true;
    startInfo.RedirectStandardError = true;

    startInfo.UseShellExecute = false;
    startInfo.Arguments = "import-module vmware.appcapture;Start-AVAppCapture -Name Test";
    startInfo.FileName = "Powershell.exe";

    p.StartInfo = startInfo;
    StringBuilder stringBuilder = new StringBuilder();
    p.OutputDataReceived += new DataReceivedEventHandler
    (
        delegate(object sender, DataReceivedEventArgs e)
        {
            using (StreamReader output = p.StandardOutput)
            {
                stringBuilder.AppendLine(output.ReadToEnd());
            }
        }
    );
    p.ErrorDataReceived += new DataReceivedEventHandler
    (
        delegate(object sender, DataReceivedEventArgs e)
        {
            using (StreamReader output = p.StandardError)
            {
                stringBuilder.AppendLine(output.ReadToEnd());
            }
        }
    );

    p.Start();
    p.WaitForExit();

    string finalStdOuputLine = p.StandardOutput.ReadToEnd();
    string finalStdErrorLine = p.StandardError.ReadToEnd();
    try
    {
        Result.Dispatcher.Invoke(new Action(() =>
        {
            Result.Text = String.Format("Result: {0}, Error: {1}", finalStdOuputLine, finalStdErrorLine);
        }));
    }
    catch (Exception e)
    {
    }
}
</code>```

I really would like to use RunSpace. But how can I on the one hand reuse a PowerShell context, but on the other hand hide the console window?

答:
I created a console app with the following and experienced no powershell windows visible at all. I routinely use the RunSpace and RunSpacePool classes and have never experienced a powershell instance becoming visible.

```<code> public static void Main(string[] args)
    {
        var initial = InitialSessionState.CreateDefault();
        initial.ImportPSModule(new[] { "BITSTransfer" });

        var runSpace = RunspaceFactory.CreateRunspace(initial);
        runSpace.Open();

        for (int i = 0; i < 5; i++)
        {
            using (Pipeline pipeline = runSpace.CreatePipeline())
            {
                Command capture = new Command("Get-Command");
                capture.Parameters.Add("Module", "BITSTransfer");
                pipeline.Commands.Add(capture);
                    Console.WriteLine(string.Format("In loop {0}", i));
                    System.Collections.ObjectModel.Collection<PSObject> outputCollection = pipeline.Invoke();
                    foreach (PSObject item in outputCollection)
                    {
                        Console.WriteLine(item.BaseObject.ToString());
                    }
                }
            }
        }

        runSpace.Close();
        Console.ReadLine();
    }
</code>```

As you can see this creates a runspace and imports a module. It then creates a pipeline and writes the commands in that module to screen 5 times. Each time using the same runspace. No powershell windows were spawned.

I'm not sure what this is doing though, nor am I sure if its responsible for spawning the window you reference.

```<code> Result.Dispatcher.Invoke(new Action(() =>
    {
        Result.Text = stringBuilder.ToString();
    }));
</code>```

Title: C# How to Hide PowerShell Window

Body:
I have met a problem using PowerShell command in a WPF app. The basic requirement here is PowerShell should run in the background without popping up any console window.

However, if I create a RunSpace and run the command in the Pipeline, I can't hide the console window at all. Following is my codes:

private void RunAppCapture()
{
    var initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new[] { "vmware.appcapture" });

    var runSpace = RunspaceFactory.CreateRunspace(initial);
    runSpace.Open();

    Pipeline pipeline = runSpace.CreatePipeline();

    Command capture = new Command("Start-AVAppCapture");
    capture.Parameters.Add("Name", "Test");
    pipeline.Commands.Add(capture);

    StringBuilder stringBuilder = new StringBuilder();

    pipeline.Invoke();
    if (pipeline.Error.Count > 0)
    {
        while (!pipeline.Error.EndOfPipeline)
        {
            stringBuilder.AppendLine(pipeline.Error.Read().ToString());
        }
    }
    runSpace.Close();

    try
    {
        Result.Dispatcher.Invoke(new Action(() =>
        {
            Result.Text = stringBuilder.ToString();
        }));
    }
    catch (Exception e)
    {
    }
}

The only way to hide the window is to run the PowerShell in a process. However, by doing so, I can't reuse the context because I have launch a brand-new PowerShell process every time. Here is my codes:

private void RunPowerShellProcess()
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    Process p = new Process();

    startInfo.CreateNoWindow = true;
    startInfo.RedirectStandardOutput = true;
    startInfo.RedirectStandardInput = true;
    startInfo.RedirectStandardError = true;

    startInfo.UseShellExecute = false;
    startInfo.Arguments = "import-module vmware.appcapture;Start-AVAppCapture -Name Test";
    startInfo.FileName = "Powershell.exe";

    p.StartInfo = startInfo;
    StringBuilder stringBuilder = new StringBuilder();
    p.OutputDataReceived += new DataReceivedEventHandler
    (
        delegate(object sender, DataReceivedEventArgs e)
        {
            using (StreamReader output = p.StandardOutput)
            {
                stringBuilder.AppendLine(output.ReadToEnd());
            }
        }
    );
    p.ErrorDataReceived += new DataReceivedEventHandler
    (
        delegate(object sender, DataReceivedEventArgs e)
        {
            using (StreamReader output = p.StandardError)
            {
                stringBuilder.AppendLine(output.ReadToEnd());
            }
        }
    );

    p.Start();
    p.WaitForExit();

    string finalStdOuputLine = p.StandardOutput.ReadToEnd();
    string finalStdErrorLine = p.StandardError.ReadToEnd();
    try
    {
        Result.Dispatcher.Invoke(new Action(() =>
        {
            Result.Text = String.Format("Result: {0}, Error: {1}", finalStdOuputLine, finalStdErrorLine);
        }));
    }
    catch (Exception e)
    {
    }
}

I really would like to use RunSpace. But how can I on the one hand reuse a PowerShell context, but on the other hand hide the console window?

Body:
I created a console app with the following and experienced no powershell windows visible at all. I routinely use the RunSpace and RunSpacePool classes and have never experienced a powershell instance becoming visible.

 public static void Main(string[] args)
    {
        var initial = InitialSessionState.CreateDefault();
        initial.ImportPSModule(new[] { "BITSTransfer" });

        var runSpace = RunspaceFactory.CreateRunspace(initial);
        runSpace.Open();

        for (int i = 0; i < 5; i++)
        {
            using (Pipeline pipeline = runSpace.CreatePipeline())
            {
                Command capture = new Command("Get-Command");
                capture.Parameters.Add("Module", "BITSTransfer");
                pipeline.Commands.Add(capture);
                    Console.WriteLine(string.Format("In loop {0}", i));
                    System.Collections.ObjectModel.Collection<PSObject> outputCollection = pipeline.Invoke();
                    foreach (PSObject item in outputCollection)
                    {
                        Console.WriteLine(item.BaseObject.ToString());
                    }
                }
            }
        }

        runSpace.Close();
        Console.ReadLine();
    }

As you can see this creates a runspace and imports a module. It then creates a pipeline and writes the commands in that module to screen 5 times. Each time using the same runspace. No powershell windows were spawned.

I'm not sure what this is doing though, nor am I sure if its responsible for spawning the window you reference.

 Result.Dispatcher.Invoke(new Action(() =>
    {
        Result.Text = stringBuilder.ToString();
    }));


来源: stackexchange

问:
Evaluate Excel VBA boolean condition (not a formula)
I have text in a cell A1 as below

```<code>((True And False Or True) And (True And (Not True))) And (False Or True)
</code>```

I need to evaluate this text and put Boolean result (True / False) in another cell B1 using VBA code.

I tried to use Evaluate function, it is not working.

When I read this cell, it always return string type with double quote enclose in both side. Hence it is treated as string and not evaluating the Boolean expression.

```<code>"((True And True Or True) And (True And (True))) And (True Or True)"
</code>```

I want to write this way, but it is not working

```<code>If Range("A1").Value = True Then
    Range("B1").Value = True
Else
    Range("B1").Value = False
End If
</code>```

I tried to store in Boolean variable also

```<code>Dim Result as Boolean
Result = CBool(Range("A1").Value)
</code>```

as it is string, I am getting type mismatch when I tried to convert using CBool.

答:
Further to the accepted answer for this question you can use this code:

```<code>Option Explicit

Sub Test()

    Debug.Print VBABooleanEvaluateOnTheFly("((True And False Or True) And (True And (Not True))) And (False Or True)")
    Debug.Print VBABooleanEvaluateOnTheFly("((True And True Or True) And (True And (True))) And (True Or True)")
    Debug.Print VBABooleanEvaluateOnTheFly("True")
    Debug.Print VBABooleanEvaluateOnTheFly("False")
    Debug.Print VBABooleanEvaluateOnTheFly("False Or True")

End Sub

Function VBABooleanEvaluateOnTheFly(strExpression As String) As Boolean

    Dim blnResult As Boolean
    Dim objVBComponent As Object

    Set objVBComponent = ThisWorkbook.VBProject.VBComponents.Add(1)
    With objVBComponent
        .CodeModule.AddFromString "Function foo() As Boolean: foo = " & strExpression & ": End Function"
        If Application.Run(.Name & ".foo") Then
            blnResult = True
        Else
            blnResult = False
        End If
    End With
    ThisWorkbook.VBProject.VBComponents.Remove objVBComponent

    VBABooleanEvaluateOnTheFly = blnResult

End Function
</code>```

You will need to tick the Trust access to the VBA project object model checkbox in the Trust Center settings.

Just to note a couple of things with this technique:

it is slow

there are likely a lot of ways it will break other things

it is vulnerable to code injection by a malicious user e.g. they may enter something like Sheet1.Cells.Delete instead of (True And False etc)

ContentLicense: CC BY-SA 4.0

Body:
I have text in a cell A1 as below

((True And False Or True) And (True And (Not True))) And (False Or True)

I need to evaluate this text and put Boolean result (True / False) in another cell B1 using VBA code.

I tried to use Evaluate function, it is not working.

When I read this cell, it always return string type with double quote enclose in both side. Hence it is treated as string and not evaluating the Boolean expression.

"((True And True Or True) And (True And (True))) And (True Or True)"

I want to write this way, but it is not working

If Range("A1").Value = True Then
    Range("B1").Value = True
Else
    Range("B1").Value = False
End If

I tried to store in Boolean variable also

Dim Result as Boolean
Result = CBool(Range("A1").Value)

as it is string, I am getting type mismatch when I tried to convert using CBool.

Body:
Further to the accepted answer for this question you can use this code:

Option Explicit

Sub Test()

    Debug.Print VBABooleanEvaluateOnTheFly("((True And False Or True) And (True And (Not True))) And (False Or True)")
    Debug.Print VBABooleanEvaluateOnTheFly("((True And True Or True) And (True And (True))) And (True Or True)")
    Debug.Print VBABooleanEvaluateOnTheFly("True")
    Debug.Print VBABooleanEvaluateOnTheFly("False")
    Debug.Print VBABooleanEvaluateOnTheFly("False Or True")

End Sub

Function VBABooleanEvaluateOnTheFly(strExpression As String) As Boolean

    Dim blnResult As Boolean
    Dim objVBComponent As Object

    Set objVBComponent = ThisWorkbook.VBProject.VBComponents.Add(1)
    With objVBComponent
        .CodeModule.AddFromString "Function foo() As Boolean: foo = " & strExpression & ": End Function"
        If Application.Run(.Name & ".foo") Then
            blnResult = True
        Else
            blnResult = False
        End If
    End With
    ThisWorkbook.VBProject.VBComponents.Remove objVBComponent

    VBABooleanEvaluateOnTheFly = blnResult

End Function

You will need to tick the Trust access to the VBA project object model checkbox in the Trust Center settings.

Just to note a couple of things with this technique:

it is slow

there are likely a lot of ways it will break other things

it is vulnerable to code injection by a malicious user e.g. they may enter something like Sheet1.Cells.Delete instead of (True And False etc)

ContentLicense: CC BY-SA 3.0


问:
Manage puppet master using puppet
Has anyone experience with creating and managing puppet masters through puppet itself?

We are running a control-repo and currently some of the puppet masters files (mainly for plugins) are managed through a puppet role. I would like to take this one step further and allow automatic creation of a new puppet master and manage the complete puppet master configuration through puppet, including installation. This would make it easy to create masters for testing and upgrade purposes. We have all the code to bootstrap a new server with a particular role.

I'm trying to automate this: https://puppet.com/docs/pe/2017.3/installing/installing_pe.html#install-using-text-mode-split-configuration

But having difficulty making things occur in the correct sequence, because I don't know how to get a puppet agent to repeat the puppet agent run immediately, from within puppet. I suppose mcollective might help, by sending the commands to the local and remote hosts, but again would that work from within puppet?. Does anyone have experience with this? Or should I just give up and add the initial installation of the master and the coordination of other actions to our bootstrap code? Perhaps using mcollective?

答:
I personally use AWS CF to do this. You can create and ec2 instance quickly with CloudFormation and bootstrape the node with puppet server and agent installed. You can also terminate and repeat the process as many times you want.

See process here https://s3.amazonaws.com/cloudformation-examples/IntegratingAWSCloudFormationWithPuppet.pdf

Title: Manage puppet master using puppet


问:
Why does my getColor function always return false?
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false. </p>

```<code>    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }
</code>```

答:
I would prefer doing this way

function validate() {
    return acceptableColors.indexOf(color) !== -1;
}```

Body:
I have a function that gets user input and its supposed to validate the user input from a list of options. The last part of the function, where I cycle through results and return true, if there's a true boolean value in results doesn't seem to be working properly. It keeps returning false.

    function getColor(){
        //gets user color and makes all characters lower case;
        let color=prompt("Pick a color, your options are white, yellow, brown, black, tan, red, orange").toLowerCase();

        //stores acceptable colors
        let acceptableColors=["white","yellow", "brown", "black","tan","red","orange"];

        function validate(){
            let results=[];
            for(let i=0; i<acceptableColors.length; i++){//loops through and stores a true value in results if user color is in list of acceptableColors
                    if(color===acceptableColors[i]){
                        results.push(true);
                    }
                    else{
                        results.push(false);
                    }

            }

            results.forEach(function(item){//loops through results to search for true value and returns true, if it finds one
                if(item===true){
                    return true
                }
            });
             return false;//returns false if user entered invalid color

        }
        return validate();

    }


问:
How to convert 128 AES encryption to 256 in java
I am trying to convert a 128 AES encryption to 256 in java.Previously i was using 126 and that was working fine, but i wqnt to upgrade the encryption to 256.Here is the previous code that i was using for 128

```<code>     private  Key generateKey() throws Exception {

     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

      char[] password = listOfDecodedkeys.get(1).toCharArray();
      byte[] salt = listOfDecodedkeys.get(2).getBytes(AbstractSecurity.UTF_ENCODING);
      KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
      SecretKey tmp = factory.generateSecret(spec);
      byte[] encoded = tmp.getEncoded();
      return new SecretKeySpec(encoded, "AES");

  }
</code>```

I am now using

```<code>       SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
</code>```

and i have also changed the keySpec to 256

```<code>KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
</code>```

But when i am trying to run i am getting NoSuchAlgorithmException exception. Here is the complete stacktrace

```<code> Exception in thread "main" java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA256 SecretKeyFactory not available
at javax.crypto.SecretKeyFactory.<init>(Unknown Source)
at javax.crypto.SecretKeyFactory.getInstance(Unknown Source)
at com.aes.security.AbstractSecurity.generateKey(AbstractSecurity.java:193)
at com.aes.security.AbstractSecurity.getCipher(AbstractSecurity.java:182)
at com.aes.security.SecurityService.encrypt(SecurityService.java:76)
at com.aes.security.SecurityService.main(SecurityService.java:165)
</code>```

Please help i am new to encryption.

答:
The standard version of the JRE/JDK are under export restrictions. That also includes that some cryptographic algorithms are not allowed to be shipped in the standard version.

For those who are allowed to use stronger cryptography there are the Java Cryptography Extensions. If you install those to your JRE/JDK you can also use e.g. AES with 256 Bit keys.

Edit: Better explanation why to install the JCE.

Body:
I am trying to convert a 128 AES encryption to 256 in java.Previously i was using 126 and that was working fine, but i wqnt to upgrade the encryption to 256.Here is the previous code that i was using for 128

     private  Key generateKey() throws Exception {

     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

      char[] password = listOfDecodedkeys.get(1).toCharArray();
      byte[] salt = listOfDecodedkeys.get(2).getBytes(AbstractSecurity.UTF_ENCODING);
      KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
      SecretKey tmp = factory.generateSecret(spec);
      byte[] encoded = tmp.getEncoded();
      return new SecretKeySpec(encoded, "AES");

  }

I am now using

       SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

and i have also changed the keySpec to 256

KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);

But when i am trying to run i am getting NoSuchAlgorithmException exception. Here is the complete stacktrace

 Exception in thread "main" java.security.NoSuchAlgorithmException: PBKDF2WithHmacSHA256 SecretKeyFactory not available
at javax.crypto.SecretKeyFactory.<init>(Unknown Source)
at javax.crypto.SecretKeyFactory.getInstance(Unknown Source)
at com.aes.security.AbstractSecurity.generateKey(AbstractSecurity.java:193)
at com.aes.security.AbstractSecurity.getCipher(AbstractSecurity.java:182)
at com.aes.security.SecurityService.encrypt(SecurityService.java:76)
at com.aes.security.SecurityService.main(SecurityService.java:165)

Please help i am new to encryption.


问:
Displaying and sizing a grayscale from a QImage in Qt
I have been able to display an image in a label in Qt using something like the following:

```<code>transformPixels(0,0,1,imheight,imwidth,1);//sets unsigned char** imageData

unsigned char* fullCharArray = new unsigned char[imheight * imwidth];
     for (int i = 0 ; i < imheight ; i++)
         for (int j = 0 ; j < imwidth ; j++)
                fullCharArray[(i*imwidth)+j] = imageData[i][j];

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);

ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));
</code>```

So fullCharArray is an array of unsigned chars that have been mapped from the 2D array imageData, in other words, it is imheight * imwidth bytes.

The problem is, it seems like only a portion of my image is showing in the label. The image is very large. I would like to display the full image, scaled down to fit in the label, with the aspect ratio preserved.

Also, that QImage format was the only one I could find that seemed to give me a close representation of the image I am wanting to display, is that what I should expect? I am only using one byte per pixel (unsigned char - values from 0 to 255), and it seems liek RGB32 doesnt make much sense for that data type, but none of the other ones displayed anything remotely correct

edit:
Following dan gallaghers advice, I implemented this code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);
int labelWidth = ui->viewLabel->width();
int labelHeight = ui->viewLabel->height();

QImage small = qi->scaled(labelWidth, labelHeight,Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small,Qt::AutoColor));
</code>```

But this causes my program to "unexpectedly finish" with code 0

答:
Qt doesn't support grayscale image construction directly. You need to use 8-bit indexed color image:</p>

```<code>QImage * qi = new QImage(imageData, imwidth, imheight, QImage::Format_Indexed8);
for(int i=0;i<256;++i) {
    qi->setColor(i, qRgb(i,i,i));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have been able to display an image in a label in Qt using something like the following:

transformPixels(0,0,1,imheight,imwidth,1);//sets unsigned char** imageData

unsigned char* fullCharArray = new unsigned char[imheight * imwidth];
     for (int i = 0 ; i < imheight ; i++)
         for (int j = 0 ; j < imwidth ; j++)
                fullCharArray[(i*imwidth)+j] = imageData[i][j];

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);

ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));

So fullCharArray is an array of unsigned chars that have been mapped from the 2D array imageData, in other words, it is imheight * imwidth bytes.

The problem is, it seems like only a portion of my image is showing in the label. The image is very large. I would like to display the full image, scaled down to fit in the label, with the aspect ratio preserved.

Also, that QImage format was the only one I could find that seemed to give me a close representation of the image I am wanting to display, is that what I should expect? I am only using one byte per pixel (unsigned char - values from 0 to 255), and it seems liek RGB32 doesnt make much sense for that data type, but none of the other ones displayed anything remotely correct

edit:
Following dan gallaghers advice, I implemented this code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_RGB32);
int labelWidth = ui->viewLabel->width();
int labelHeight = ui->viewLabel->height();

QImage small = qi->scaled(labelWidth, labelHeight,Qt::KeepAspectRatio);
ui->viewLabel->setPixmap(QPixmap::fromImage(small,Qt::AutoColor));

But this causes my program to "unexpectedly finish" with code 0

Body:
Qt doesn't support grayscale image construction directly. You need to use 8-bit indexed color image:

QImage * qi = new QImage(imageData, imwidth, imheight, QImage::Format_Indexed8);
for(int i=0;i<256;++i) {
    qi->setColor(i, qRgb(i,i,i));
}


问:
How to filter over a PrimeNg DataTable column with ng-template?
This is my column:

```<code><p-column header="Roles" sortable="true" [filter]="true" filterMatchMode="contains">
  <ng-template let-user="rowData" pTemplate="body">
    <div *ngFor="let role of user.roles">
      {{role.name}}
    </div>
  </ng-template>
</p-column>
</code>```

Examples of user.roles JSON:

```<code>[ { "id": 3, "name": "A single role" } ]
[ { "id": 4, "name": "A role name" }, { "id": 6, "name": "Another role name" } ]
</code>```

I would like to add a filter on it - I tried adding this ng-template:

```<code><ng-template pTemplate="filter" let-col let-test="rowData">
        <p-multiSelect [options]="roles" defaultLabel="All roles" (onChange)="dt.filter($event.value,test.roles,col.filterMatchMode)"
          styleClass="ui-column-filter"></p-multiSelect>
 </ng-template>
</code>```

The multiselect's options are in a separate roles array:

```<code>this.roles = [];
this.roles.push({ label: 'A role', value: 'aRole' });
this.roles.push({ label: 'Another role', value: 'anotherRole' });
</code>```

... but for some reason, I get this error:

Cannot read property 'roles' of undefined

How can I achieve this ?

How can I debug inline function calls like dt.filter($event.value,test.roles,col.filterMatchMode) ?

I think that my main problem is that my column does not have a "field" value which can be used for filtering.

答: According to the official forum, what I wanted is not possible. A "field" is required. As a workaround, I flattened my roles array into a string and displayed this in a field. I can now filter it with the matchmode "contains"</p>

Body:
This is my column:

  <ng-template let-user="rowData" pTemplate="body">

      {{role.name}}

  </ng-template>

Examples of user.roles JSON:

[ { "id": 3, "name": "A single role" } ]
[ { "id": 4, "name": "A role name" }, { "id": 6, "name": "Another role name" } ]

I would like to add a filter on it - I tried adding this ng-template:

<ng-template pTemplate="filter" let-col let-test="rowData">

 </ng-template>

The multiselect's options are in a separate roles array:

this.roles = [];
this.roles.push({ label: 'A role', value: 'aRole' });
this.roles.push({ label: 'Another role', value: 'anotherRole' });

... but for some reason, I get this error:

Cannot read property 'roles' of undefined

How can I achieve this ?

How can I debug inline function calls like dt.filter($event.value,test.roles,col.filterMatchMode) ?

I think that my main problem is that my column does not have a "field" value which can be used for filtering.


问:
Can I access metadata annotations of a type or parameter in flutter?
Or is that capability lost with the loss of the reflect package?

What I'm curious about is can I use annotations in my own flutter app? Or is that a feature only available in dart, but not flutter?

答:
Annotations can only be used for static analysis in Flutter.

For example the analyzer that generates hints and warnings in your IDE, code generation tools like built_value, built_redux, json_serializable, and other packages that use https://github.com/dart-lang/build make use of this.

There is no way to get metadata information at runtime without dart:mirrors.

There is work in progress to make the reflectable package work with code generation. This might work with Flutter eventually to generate code that allows to access predefined metadata at runtime.
See also https://github.com/dart-lang/reflectable/tree/use_build


问:
How do I enable http traffic for GCE instance templates?
When creating an instance template in Google Compute Engine, how do I enable http traffic for instances created from the template?

I was thinking that providing an http tag would work, but it doesn't seem to do so.

答:
One potential solution is to enable http traffic for all of your instances >in that project. To do so, from within GCE command line tools, run:

gcloud compute firewall-rules create FIREWALL_RULE --allow tcp:80

I try your command but it doesn't work because the command want the name of the instance:

```<code>google130505_student@qwiklabs-gcp-286ef104ac93631b:~$ gcloud compute firewall-rules create FIREWALL_RULE --allow tcp:80
Creating firewall...failed.
ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
 - Invalid value for field 'resource.name': 'FIREWALL_RULE'. Must be a match of regex '(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'
google130505_student@qwiklabs-gcp-286ef104ac93631b:~$ gcloud compute firewall-rules create gclab2 --allow tcp:80
Creating firewall.../Created [https://www.googleapis.com/compute/v1/projects/qwiklabs-gcp-286ef104ac93631b/global/firewalls/gclab2].
Creating firewall...done.
NAME    NETWORK  DIRECTION  PRIORITY  ALLOW   DENY
gclab2  default  INGRESS    1000      tcp:80
</code>```

so the correct command is:

```<code>gcloud compute firewall-rules create NAME_OF_YOUR_INSTANCE --allow tcp:80
</code>```

Body:
One potential solution is to enable http traffic for all of your instances >in that project. To do so, from within GCE command line tools, run:

gcloud compute firewall-rules create FIREWALL_RULE --allow tcp:80

I try your command but it doesn't work because the command want the name of the instance:

google130505_student@qwiklabs-gcp-286ef104ac93631b:~$ gcloud compute firewall-rules create FIREWALL_RULE --allow tcp:80
Creating firewall...failed.
ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
 - Invalid value for field 'resource.name': 'FIREWALL_RULE'. Must be a match of regex '(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'
google130505_student@qwiklabs-gcp-286ef104ac93631b:~$ gcloud compute firewall-rules create gclab2 --allow tcp:80
Creating firewall.../Created [https://www.googleapis.com/compute/v1/projects/qwiklabs-gcp-286ef104ac93631b/global/firewalls/gclab2].
Creating firewall...done.
NAME    NETWORK  DIRECTION  PRIORITY  ALLOW   DENY
gclab2  default  INGRESS    1000      tcp:80

so the correct command is:

gcloud compute firewall-rules create NAME_OF_YOUR_INSTANCE --allow tcp:80


问:
What is the best ORB for Java/C++ interoperation using CORBA?
I have a client-server application written in Java using CORBA for the communication. The ORB used is orbd, the one provided by the Java6 platform. I have to replace the Java server implementation with another one written in C++. So the question is, of the free source implementations of CORBA libraries, which one better interoperates with this ORB? Should I replace the Java ORB and also use the ORB provided by the C++ library?

The objective is to have an easy and smooth transition when replacing an already functioning server with the new C++ implementation. Is there anything else that I should take into account?

答:
C++

Have you looked at the ACE/TAO ORB.

https://www.dre.vanderbilt.edu/~schmidt/TAO.html

ACE is basically an OS abstraction Layer.

And TAO is a CORBA ORB build on-top of this abstraction so it is cross platform.

Java

The Java version of TAO is ZEN:

http://www.zen.uci.edu/

Though technically your ORBs do not need to be the same. As long as the conform to the CORBA protocol/specification they should be interoperable. So though you can use ZEN it is just as easy to use JacORB.

OwnerDisplayName: Martin York


问:
When is the best place to use Task.Result instead of awaiting Task
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

```<code>var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;
</code>```

Now becomes:

```<code>var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;
</code>```

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

答:
In your case, you can use:

```<code>user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);
</code>```

or perhaps more clearly:

```<code>var user = await _userRepo.GetByUsername(User.Identity.Name);
//Some work that doesn't rely on the user object
user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);
</code>```

The only time you should touch .Result is when you know the task has been completed. This can be useful in some scenarios where you are trying to avoid creating an async state machine and you think there's a good chance that the task has completed synchronously (perhaps using a local function for the async case), or if you're using callbacks rather than async/await, and you're inside the callback.

As an example of avoiding a state machine:

```<code>ValueTask<int> FetchAndProcess(SomeArgs args) {
    async ValueTask<int> Awaited(ValueTask<int> task) => SomeOtherProcessing(await task);
    var task = GetAsyncData(args);
    if (!task.IsCompletedSuccessfully) return Awaited(task);
    return new ValueTask<int>(SomeOtherProcessing(task.Result));
}
</code>```

The point here is that if GetAsyncData returns a synchronously completed result, we completely avoid all the async machinery.

Body:
Whilst I've been using async code in .NET for a while, I've only recently started to research it and understand what's going on.  I've just been going through my code and trying to alter it so if a task can be done in parallel to some work, then it is. So for example:

var user = await _userRepo.GetByUsername(User.Identity.Name);

//Some minor work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

return user;

Now becomes:

var userTask = _userRepo.GetByUsername(User.Identity.Name);

//Some work that doesn't rely on the user object

user = await _userRepo.UpdateLastAccessed(userTask.Result, DateTime.Now);

return user;

My understand is that the user object is now being fetched from the database WHILST some unrelated work is going on. However, things I've seen posted imply that result should be used rarely and await is preferred but I don't understand why I'd want to wait for my user object to be fetched if I can be performing some other independant logic at the same time?

Body:
In your case, you can use:

user = await _userRepo.UpdateLastAccessed(await userTask, DateTime.Now);

or perhaps more clearly:

var user = await _userRepo.GetByUsername(User.Identity.Name);
//Some work that doesn't rely on the user object
user = await _userRepo.UpdateLastAccessed(user, DateTime.Now);

The only time you should touch .Result is when you know the task has been completed. This can be useful in some scenarios where you are trying to avoid creating an async state machine and you think there's a good chance that the task has completed synchronously (perhaps using a local function for the async case), or if you're using callbacks rather than async/await, and you're inside the callback.

As an example of avoiding a state machine:

ValueTask<int> FetchAndProcess(SomeArgs args) {
    async ValueTask<int> Awaited(ValueTask<int> task) => SomeOtherProcessing(await task);
    var task = GetAsyncData(args);
    if (!task.IsCompletedSuccessfully) return Awaited(task);
    return new ValueTask<int>(SomeOtherProcessing(task.Result));
}

The point here is that if GetAsyncData returns a synchronously completed result, we completely avoid all the async machinery.


问:
UIButton causing unrecognized selector sent to instance
I'm trying to create multiple buttons with a for loop, but I'm having problems using the (sender:) function.

I have the following code

```<code>func setUpButtons(){
    for i in 1...3 {

    let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 75, height: 100))
        btn.center = CGPoint(x: 20 + 100.0 * CGFloat(i), y: 200)
        btn.backgroundColor = UIColor.green
        btn.setTitle("Click Me", for: UIControlState.normal)
        btn.addTarget(self, action: Selector(("buttonAction:")), for: UIControlEvents.touchUpInside)
        btn.tag = i
        self.view.addSubview(btn)
    }
}
func buttonAction(sender: UIButton!) {
    let btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {
        print("Button 1")
    } else if btnsendtag.tag == 2 {
        print("Button 2")
    } else if btnsendtag.tag == 3 {
        print("Button 3")
    }
}
</code>```

When I press a button it shows the following error:

```<code>    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Learn_ABCs.ViewController buttonAction:]: unrecognized selector sent to instance 0x7f9789d0bc50'
    *** First throw call stack:
(
0   CoreFoundation                      0x00000001095ac34b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x00000001061fd21e objc_exception_throw + 48
2   CoreFoundation                      0x000000010961bf34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   CoreFoundation                      0x0000000109531c15 ___forwarding___ + 1013
4   CoreFoundation                      0x0000000109531798 _CF_forwarding_prep_0 + 120
5   UIKit                               0x0000000106ddeb88 -[UIApplication sendAction:to:from:forEvent:] + 83
6   UIKit                               0x0000000106f642b2 -[UIControl sendAction:to:forEvent:] + 67
7   UIKit                               0x0000000106f645cb -[UIControl _sendActionsForEvents:withEvent:] + 444
8   UIKit                               0x0000000106f634c7 -[UIControl touchesEnded:withEvent:] + 668
9   UIKit                               0x0000000106e4c0d5 -[UIWindow _sendTouchesForEvent:] + 2747
10  UIKit                               0x0000000106e4d7c3 -[UIWindow sendEvent:] + 4011
11  UIKit                               0x0000000106dfaa33 -[UIApplication sendEvent:] + 371
12  UIKit                               0x00000001075ecb6d __dispatchPreprocessedEventFromEventQueue + 3248
13  UIKit                               0x00000001075e5817 __handleEventQueue + 4879
14  CoreFoundation                      0x0000000109551311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15  CoreFoundation                      0x000000010953659c __CFRunLoopDoSources0 + 556
16  CoreFoundation                      0x0000000109535a86 __CFRunLoopRun + 918
17  CoreFoundation                      0x0000000109535494 CFRunLoopRunSpecific + 420
18  GraphicsServices                    0x000000010c383a6f GSEventRunModal + 161
19  UIKit                               0x0000000106ddcf34 UIApplicationMain + 159
20  Learn ABCs                          0x0000000105c1fa7f main + 111
21  libdyld.dylib                       0x000000010a4d668d start + 1)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

I feel like I have the : correct, so I'm not sure what else to look for. I'm using swift 3.0.

答:
for Swift 4 - </p>

```<code>    override func awakeFromNib() {
        button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    }

    @objc func buttonClicked(sender:UIButton) {
        ...
    }
</code>```

Body:
I'm trying to create multiple buttons with a for loop, but I'm having problems using the (sender:) function.

I have the following code

func setUpButtons(){
    for i in 1...3 {

    let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 75, height: 100))
        btn.center = CGPoint(x: 20 + 100.0 * CGFloat(i), y: 200)
        btn.backgroundColor = UIColor.green
        btn.setTitle("Click Me", for: UIControlState.normal)
        btn.addTarget(self, action: Selector(("buttonAction:")), for: UIControlEvents.touchUpInside)
        btn.tag = i
        self.view.addSubview(btn)
    }
}
func buttonAction(sender: UIButton!) {
    let btnsendtag: UIButton = sender
    if btnsendtag.tag == 1 {
        print("Button 1")
    } else if btnsendtag.tag == 2 {
        print("Button 2")
    } else if btnsendtag.tag == 3 {
        print("Button 3")
    }
}

When I press a button it shows the following error:

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Learn_ABCs.ViewController buttonAction:]: unrecognized selector sent to instance 0x7f9789d0bc50'
    *** First throw call stack:
(
0   CoreFoundation                      0x00000001095ac34b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x00000001061fd21e objc_exception_throw + 48
2   CoreFoundation                      0x000000010961bf34 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
3   CoreFoundation                      0x0000000109531c15 ___forwarding___ + 1013
4   CoreFoundation                      0x0000000109531798 _CF_forwarding_prep_0 + 120
5   UIKit                               0x0000000106ddeb88 -[UIApplication sendAction:to:from:forEvent:] + 83
6   UIKit                               0x0000000106f642b2 -[UIControl sendAction:to:forEvent:] + 67
7   UIKit                               0x0000000106f645cb -[UIControl _sendActionsForEvents:withEvent:] + 444
8   UIKit                               0x0000000106f634c7 -[UIControl touchesEnded:withEvent:] + 668
9   UIKit                               0x0000000106e4c0d5 -[UIWindow _sendTouchesForEvent:] + 2747
10  UIKit                               0x0000000106e4d7c3 -[UIWindow sendEvent:] + 4011
11  UIKit                               0x0000000106dfaa33 -[UIApplication sendEvent:] + 371
12  UIKit                               0x00000001075ecb6d __dispatchPreprocessedEventFromEventQueue + 3248
13  UIKit                               0x00000001075e5817 __handleEventQueue + 4879
14  CoreFoundation                      0x0000000109551311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15  CoreFoundation                      0x000000010953659c __CFRunLoopDoSources0 + 556
16  CoreFoundation                      0x0000000109535a86 __CFRunLoopRun + 918
17  CoreFoundation                      0x0000000109535494 CFRunLoopRunSpecific + 420
18  GraphicsServices                    0x000000010c383a6f GSEventRunModal + 161
19  UIKit                               0x0000000106ddcf34 UIApplicationMain + 159
20  Learn ABCs                          0x0000000105c1fa7f main + 111
21  libdyld.dylib                       0x000000010a4d668d start + 1)
libc++abi.dylib: terminating with uncaught exception of type NSException

I feel like I have the : correct, so I'm not sure what else to look for. I'm using swift 3.0.

Body:
for Swift 4 -

    override func awakeFromNib() {
        button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    }

    @objc func buttonClicked(sender:UIButton) {
        ...
    }


问:
How to create a vertical slider in octave/matlab

Setup

The following command create a horizontal slider in octave/matlab filling the current window:

```<code>h= uicontrol ('style', 'slider', 'units','normalized', 'position',[0,0,1,1])
</code>```

Background Information

With the function call get(h) you can display all properties of the slider. Some more relevant properties are listed here:

```<code>type = uicontrol
style = slider
max = 1
min = 0
value =  0.50000
sliderstep =[0.010000  0.100000]
position =[0  0  1  1]
units = normalized
horizontalalignment = center
verticalalignment = middle
</code>```

Question

Is there any property to control the orientation of the slider? Or is there another way of creating a vertical slider?

答:
Solution

I found the solution myself: The slider orientation is defined implicitly from the aspect ratio of the uicontrol. If it is initially wider than high it becomes a horizontal slider, if it is higher than wide it becomes a vertical slider.

To control the aspect ratio set the 'position' property of the uicontrol to [xpos ypos width height].

Example

The following command creates a vertical slider:

```<code>uicontrol('style','slider','units','normalized','position',[0,0,0.2,1.0]);
</code>```

Notes

If you change the aspect ratio after creation, the slider orientation
stays as it is.

The designers of matlab have not made a good choice by anticipating which slider orientation the user may want. A separate property for the orientation would be more flexible.

Body:
Setup

The following command create a horizontal slider in octave/matlab filling the current window:

h= uicontrol ('style', 'slider', 'units','normalized', 'position',[0,0,1,1])

Background Information

With the function call get(h) you can display all properties of the slider. Some more relevant properties are listed here:

type = uicontrol
style = slider
max = 1
min = 0
value =  0.50000
sliderstep =[0.010000  0.100000]
position =[0  0  1  1]
units = normalized
horizontalalignment = center
verticalalignment = middle

Question

Is there any property to control the orientation of the slider? Or is there another way of creating a vertical slider?

Body:
Solution

I found the solution myself: The slider orientation is defined implicitly from the aspect ratio of the uicontrol. If it is initially wider than high it becomes a horizontal slider, if it is higher than wide it becomes a vertical slider.

To control the aspect ratio set the 'position' property of the uicontrol to [xpos ypos width height].

Example

The following command creates a vertical slider:

uicontrol('style','slider','units','normalized','position',[0,0,0.2,1.0]);

Notes

If you change the aspect ratio after creation, the slider orientation
stays as it is.

The designers of matlab have not made a good choice by anticipating which slider orientation the user may want. A separate property for the orientation would be more flexible.


问:
Loading basic HTML in Node.js
I'm trying to find out how to load and render a basic HTML file so I don't have to write code like:</p>

```<code>response.write('...<p>blahblahblah</p>...');
</code>```

答:
You can echo files manually using the fs object, but I'd recommend using the ExpressJS framework to make your life much easier. </p>

<p>...But if you insist on doing it the hard way:</p>

```<code>var http = require('http');
var fs = require('fs');

http.createServer(function(req, res){
    fs.readFile('test.html',function (err, data){
        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
        res.write(data);
        res.end();
    });
}).listen(8000);
</code>```

Title: Loading basic HTML in Node.js

Body:
I'm trying to find out how to load and render a basic HTML file so I don't have to write code like:

response.write('...
blahblahblah
...');

Body:
You can echo files manually using the fs object, but I'd recommend using the ExpressJS framework to make your life much easier.

...But if you insist on doing it the hard way:

var http = require('http');
var fs = require('fs');

http.createServer(function(req, res){
    fs.readFile('test.html',function (err, data){
        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
        res.write(data);
        res.end();
    });
}).listen(8000);


问:
SMTP email not working in Xampp locally hosted wordpress website
I am working locally on xampp and using Gmail SMTP plugin to get my contact form 7 to work. When I try sending a test email it fails, and i get this error message:

```<code>Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [C:\xampp1\htdocs\WP\wp-content\plugins\gmail-smtp\PHPMailer\class.smtp.php line 369]
SMTP Error: Could not connect to SMTP host.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

I changed the mail function settings in php.ini and sendmail configuration accordingly. Can you help me with what the problem might be here?

答:
You are getting this error most likely because internally, PHPMailer is trying to establish a secure connection (SSL/HTTPS) and the SSL certificate verification is failing because it is most like a self-signed certificate (inside xampp just for development).

Try allowing insecure connections (without SSL encryption - at least during development) by using the suggested piece of code

```<code>$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);
</code>```

As the document itself recommends against making these configurations globally in the php.ini file, you may want to revert them. And use the Run-time options instead (the code above).

Body:
I am working locally on xampp and using Gmail SMTP plugin to get my contact form 7 to work. When I try sending a test email it fails, and i get this error message:

Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed [C:\xampp1\htdocs\WP\wp-content\plugins\gmail-smtp\PHPMailer\class.smtp.php line 369]
SMTP Error: Could not connect to SMTP host.
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I changed the mail function settings in php.ini and sendmail configuration accordingly. Can you help me with what the problem might be here?

Body:
You are getting this error most likely because internally, PHPMailer is trying to establish a secure connection (SSL/HTTPS) and the SSL certificate verification is failing because it is most like a self-signed certificate (inside xampp just for development).

Try allowing insecure connections (without SSL encryption - at least during development) by using the suggested piece of code

$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);

As the document itself recommends against making these configurations globally in the php.ini file, you may want to revert them. And use the Run-time options instead (the code above).


问:
Apache Camel: File component moveFailed redelivery strategy
When a certain endpoint is not available (500 for instance) my queue file is moved to .error directory. I am using the parameter: moveFailed for this.

```<code><from uri="file:inbox?autoCreate=true&readLockTimeout=2000&charset=utf-8&preMove=.processing&delete=true&moveFailed=.error&maxMessagesPerPoll=50&delay=1000"/>
</code>```

According to: http://camel.apache.org/file2.html

When moving the files to the “fail” location Camel will handle the
  error and will not pick up the file again.

What is the best approach to implement a redelivery policy/strategy so that the files get picked up again when failed?

答:
Setup a retry by redelivering to that certain endpoint component, not to the whole route.

You can do this by specifying number of retries, a delay between retries, and a backoff multiplier if you so wish using an error handler.

```<code>onException(RestException.class)
            .maximumRedeliveries(3)
            .redeliveryDelay(100L)
            .backOffMultiplier(1.5)
</code>```

Or setting this in your camel context:

```<code><errorHandler id="errorhandler" redeliveryPolicyRef="redeliveryPolicy"/>
<redeliveryPolicyProfile id="redeliveryPolicy" maximumRedeliveries="3" redeliveryDelay="100" backOffMultiplier="1.5" retryAttemptedLogLevel="WARN"/>
</code>```

This way, the file is only delivered to the error folder once it has run out of redelivery attempts.

You could also look at using the dead letter handler, and putting the file into a queue to be processed later.

Body:
When a certain endpoint is not available (500 for instance) my queue file is moved to .error directory. I am using the parameter: moveFailed for this.

<from uri="file:inbox?autoCreate=true&readLockTimeout=2000&charset=utf-8&preMove=.processing&delete=true&moveFailed=.error&maxMessagesPerPoll=50&delay=1000"/>

According to: http://camel.apache.org/file2.html

When moving the files to the “fail” location Camel will handle the
  error and will not pick up the file again.

What is the best approach to implement a redelivery policy/strategy so that the files get picked up again when failed?

Body:
Setup a retry by redelivering to that certain endpoint component, not to the whole route.

You can do this by specifying number of retries, a delay between retries, and a backoff multiplier if you so wish using an error handler.

onException(RestException.class)
            .maximumRedeliveries(3)
            .redeliveryDelay(100L)
            .backOffMultiplier(1.5)

Or setting this in your camel context:

<errorHandler id="errorhandler" redeliveryPolicyRef="redeliveryPolicy"/>
<redeliveryPolicyProfile id="redeliveryPolicy" maximumRedeliveries="3" redeliveryDelay="100" backOffMultiplier="1.5" retryAttemptedLogLevel="WARN"/>

This way, the file is only delivered to the error folder once it has run out of redelivery attempts.

You could also look at using the dead letter handler, and putting the file into a queue to be processed later.


问:
Attribute img not allowed on element img at this point
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

```<code><li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" img style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
</code>```

答:
You have another img inside the image tag...

this is the corrected code...

```<code><li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
</code>```

Body:
Hello I've got a problem.
I started coding yesterday and I got an error when I wanted to verify my website on W3Validator:

Error: Attribute img not allowed on element img at this point.

Here is the code which causes the problem:

 Follow moi grow !

Body:
You have another img inside the image tag...

this is the corrected code...

<li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>


问:
ipad - can I write plist to external storage?
I am trying to capture data and have that accessible to someone and other computers without networking. There is a camera connection kit that is basically an adapter to connect an SDCard to iPad. Does anyone know if I can use same to write a plist?</p>

答: To the best of my knowledge, you have no direct access to the SD card, and therefore cannot write anything out to it.</p>


问:
Editing AspNet.Identity after add
I start a project without use security. Then now I add by nugtpackeged AspNet.Identity and need to customize it. In internet I found a lot of tutorials about it.

But I don't find the IdentityUser.cs in Models folder and if I press F12 to go to definition I see a metadata only-read version of IdentityUser.cs.

How can I edit this to add some custom properties?

I see the other Answers here like this:
How to extend available properties of User.Identity

But where I find the public class ApplicationUser : IdentityUser?
I need create this?

Another question: I can't edit the class IdentityUser??? because for me it only appears as read only (see the image).

Image from my screen show only read class

My solution explore. See the model folder is empty

答: Actually you can not edit that class, only you can inherit that class and add your extra properties then use that inherited class then you can easily add value in your extra properties.

Title: Editing AspNet.Identity after add


问:
Is it possible to limit forecasts made by bsts to positive values only?
I am learning to use various forecasting packages available in R, and came across bsts(). The data I deal with is a time series of demands.

```<code>data=c(27, 2, 7, 7, 9, 4, 3, 3, 3, 9, 6, 2, 6, 2, 3, 8, 6, 1, 3, 8, 4, 5, 8, 5, 4, 4, 6, 1, 6, 5, 1, 3, 0, 2, 6, 7, 1, 2, 6, 2, 8, 6, 1, 1, 3, 2, 1, 3, 1, 6, 3, 4, 3, 7, 3, 4, 1, 7, 5, 6, 3, 4, 3, 9, 2, 1, 7, 2, 2, 9, 4, 5, 3, 4, 2, 4, 4, 8, 6, 3, 9, 2, 9, 4, 1, 3, 8, 1, 7, 7, 6, 0, 1, 4, 8, 9, 2, 5)
ts.main=ts(data, start=c(1910,1), frequency=12)
ss <- AddLocalLinearTrend(list(), y=ts.main)
ss <- AddSeasonal(ss, y=as.numeric(ts.temp), nseasons=12)
model <- bsts(as.numeric(ts.temp),
          state.specification = ss,
          niter = 1000)
pred <- predict(model, horizon = 12)
</code>```

Is there way I can restrict pred$mean from becoming negative?

答:
Since your data are a time series of counts, you need to take that into account rather than assume Gaussian errors; for some discussion on this and elaboration of some approaches, see for example Brandt et al 2000 and Brandt and Williams 2001. Luckily, the bsts package has a built-in functionality for this, the family option (see pages 24 to 26 of the documentation).

So, you can just do this

```<code>model <- bsts(as.numeric(ts.main),
              state.specification = ss,
              family = 'poisson',
              niter = 1000)
</code>```

so that the bsts() function correctly considers the data as counts, which will solve your issue, since the draws from the posterior predictive distribution will then be non-negative by definition.

Body:
I am learning to use various forecasting packages available in R, and came across bsts(). The data I deal with is a time series of demands.

data=c(27, 2, 7, 7, 9, 4, 3, 3, 3, 9, 6, 2, 6, 2, 3, 8, 6, 1, 3, 8, 4, 5, 8, 5, 4, 4, 6, 1, 6, 5, 1, 3, 0, 2, 6, 7, 1, 2, 6, 2, 8, 6, 1, 1, 3, 2, 1, 3, 1, 6, 3, 4, 3, 7, 3, 4, 1, 7, 5, 6, 3, 4, 3, 9, 2, 1, 7, 2, 2, 9, 4, 5, 3, 4, 2, 4, 4, 8, 6, 3, 9, 2, 9, 4, 1, 3, 8, 1, 7, 7, 6, 0, 1, 4, 8, 9, 2, 5)
ts.main=ts(data, start=c(1910,1), frequency=12)
ss <- AddLocalLinearTrend(list(), y=ts.main)
ss <- AddSeasonal(ss, y=as.numeric(ts.temp), nseasons=12)
model <- bsts(as.numeric(ts.temp),
          state.specification = ss,
          niter = 1000)
pred <- predict(model, horizon = 12)

Is there way I can restrict pred$mean from becoming negative?

Body:
Since your data are a time series of counts, you need to take that into account rather than assume Gaussian errors; for some discussion on this and elaboration of some approaches, see for example Brandt et al 2000 and Brandt and Williams 2001. Luckily, the bsts package has a built-in functionality for this, the family option (see pages 24 to 26 of the documentation).

So, you can just do this

model <- bsts(as.numeric(ts.main),
              state.specification = ss,
              family = 'poisson',
              niter = 1000)

so that the bsts() function correctly considers the data as counts, which will solve your issue, since the draws from the posterior predictive distribution will then be non-negative by definition.


问:
Replacing text within string that contains serialize arrays
Thanks for clicking on the question. I am trying to find and replace text within a string that contains serialize arrays. For example :

```<code>'fgm2wc_options', 'a:19:{s:15:"automatic_empty";N;s:3:"url";s:25:"http://example.com/store/";s:8:"hostname";s:9:"localhost";s:4:"port";s:4:"3306";s:8:"database";s:22:"apgadmin_store_magento";s:8:"username" ... }
</code>```

I want to change http://example.com/ to smth else I can do it with str_replace but it will not change the string length indicator ( e.g s:25 ).

This is a function i am using:

```<code>function recursive_unserialize_replace( $old_url = '', $new_url = '', $data = '', $serialised = false ) {
    $new_url = rtrim( $new_url, '/' );
    $data = explode( ', ', $data );

    try {
        if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) {
            $data = recursive_unserialize_replace( $old_url, $new_url, $unserialized, true );
        } elseif ( is_array( $data ) ) {
            $_tmp = array( );

            foreach ( $data as $key => $value ) {
                $_tmp[ $key ] = recursive_unserialize_replace( $old_url, $new_url, $value );
            }

            $data = $_tmp;
            unset( $_tmp );
        } else {
            if ( is_string( $data ) ) {
                $data = str_replace( $old_url, $new_url, $data );
            }
        }

        if ( $serialised ) {
            return serialize( $data );
        }
    } catch( Exception $error ) {

    }

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

Any ideas ?

答:
For anyone interested  this is the solution i came up with:

```<code>function unserialize_replace( $old_url = '', $new_url = '', $database_string = '' ) {
    if ( substr( $old_url, -1 ) !== '/' ) {
        $new_url = rtrim( $new_url, '/' );
    }

    $serialized_arrays = preg_match_all( "/a:\d+:.*\;\}+/", $database_string, $matches );

    if( !empty( $serialized_arrays ) && is_array( $matches ) ) {
        foreach ( $matches[ 0 ] as $match ) {
            $unserialized = @unserialize( $match );

            if ( $unserialized ) {
                $buffer = str_replace( $old_url, $new_url, $unserialized );
                $buffer = serialize( $buffer );

                $database_string = str_replace( $match, $buffer, $database_string );
            }
        }
    }

    if ( is_string( $database_string ) ) {
        $database_string = str_replace( $old_url, $new_url, $database_string );
    }

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

Thanks for the suggestions. Please let me know if you see anything wrong and anything i can improve

Body:
Thanks for clicking on the question. I am trying to find and replace text within a string that contains serialize arrays. For example :

'fgm2wc_options', 'a:19:{s:15:"automatic_empty";N;s:3:"url";s:25:"http://example.com/store/";s:8:"hostname";s:9:"localhost";s:4:"port";s:4:"3306";s:8:"database";s:22:"apgadmin_store_magento";s:8:"username" ... }

I want to change http://example.com/ to smth else I can do it with str_replace but it will not change the string length indicator ( e.g s:25 ).

This is a function i am using:

function recursive_unserialize_replace( $old_url = '', $new_url = '', $data = '', $serialised = false ) {
    $new_url = rtrim( $new_url, '/' );
    $data = explode( ', ', $data );

    try {
        if ( is_string( $data ) && ( $unserialized = @unserialize( $data ) ) !== false ) {
            $data = recursive_unserialize_replace( $old_url, $new_url, $unserialized, true );
        } elseif ( is_array( $data ) ) {
            $_tmp = array( );

            foreach ( $data as $key => $value ) {
                $_tmp[ $key ] = recursive_unserialize_replace( $old_url, $new_url, $value );
            }

            $data = $_tmp;
            unset( $_tmp );
        } else {
            if ( is_string( $data ) ) {
                $data = str_replace( $old_url, $new_url, $data );
            }
        }

        if ( $serialised ) {
            return serialize( $data );
        }
    } catch( Exception $error ) {

    }

    return $data;
}

Any ideas ?

Body:
For anyone interested  this is the solution i came up with:

function unserialize_replace( $old_url = '', $new_url = '', $database_string = '' ) {
    if ( substr( $old_url, -1 ) !== '/' ) {
        $new_url = rtrim( $new_url, '/' );
    }

    $serialized_arrays = preg_match_all( "/a:\d+:.*\;\}+/", $database_string, $matches );

    if( !empty( $serialized_arrays ) && is_array( $matches ) ) {
        foreach ( $matches[ 0 ] as $match ) {
            $unserialized = @unserialize( $match );

            if ( $unserialized ) {
                $buffer = str_replace( $old_url, $new_url, $unserialized );
                $buffer = serialize( $buffer );

                $database_string = str_replace( $match, $buffer, $database_string );
            }
        }
    }

    if ( is_string( $database_string ) ) {
        $database_string = str_replace( $old_url, $new_url, $database_string );
    }

    return $database_string;
}

Thanks for the suggestions. Please let me know if you see anything wrong and anything i can improve


问:
MediaPlayer android, playing a file that's is inside the project
i'm a new android dev. Actually i'm moving from iPhone to Android :-)

well, i'm modifying the source of one of the examples (MediaPlayerDemo_Video.java) here: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/media/index.html

well, the point is that i want to play a video that is inside the project.

my questions:

where should i place the video file?, i guess inside the assets folder.

how do i get the correct video file path?

thanks in advance

答:
Welcome! You made the best to choose android :)

Yes you can put any file in asset folder.

For the path: R.asset.name


问:
Failing to init Hyperledger Fabric CA, "Failed to get user"
I followed the below link to install the fabric:

https://www.mlgblockchain.com/setup-hyperledger-client.html

But getting an error

server side

```<code>root@amit-VirtualBox:/home/amit# fabric-ca-server init -b “admin:adminpw”
2017/09/15 10:40:20 [INFO] Home directory for default CA: /opt/Fabric-CA/server
2017/09/15 10:40:20 [INFO] Listening on http://0.0.0.0:7054
2017/09/15 10:41:07 [INFO] 127.0.0.1:59210 POST /enroll 401 23 "Failed to get user: User not found
</code>```

Both are running on the same server.

答:
Try removing the invereted commas in the commands.

Delete the server and client folder and follow the instructions from the blog avoiding the inverted commas.

1.Initialize the server

```<code>fabric-ca-server init -b admin:adminpw
</code>```

2.Start the server

```<code>fabric-ca-server start -b admin:adminpw
</code>```

3.Enroll the Admin

```<code>fabric-ca-client enroll -u http://admin:adminpw@localhost:7054
</code>```

4.Create new user and register it

```<code>fabric-ca-client register -u http://localhost:7054 --id.name test --id.secret testpw --id.type client --id.affiliation org1.department1
</code>```

Hopefully you wont face the error you received!

Assuming you have build fabric ca server and client successfully.

Body:
I followed the below link to install the fabric:

https://www.mlgblockchain.com/setup-hyperledger-client.html

But getting an error

server side

root@amit-VirtualBox:/home/amit# fabric-ca-server init -b “admin:adminpw”
2017/09/15 10:40:20 [INFO] Home directory for default CA: /opt/Fabric-CA/server
2017/09/15 10:40:20 [INFO] Listening on http://0.0.0.0:7054
2017/09/15 10:41:07 [INFO] 127.0.0.1:59210 POST /enroll 401 23 "Failed to get user: User not found

Both are running on the same server.

Body:
Try removing the invereted commas in the commands.

Delete the server and client folder and follow the instructions from the blog avoiding the inverted commas.

1.Initialize the server

fabric-ca-server init -b admin:adminpw

2.Start the server

fabric-ca-server start -b admin:adminpw

3.Enroll the Admin

fabric-ca-client enroll -u http://admin:adminpw@localhost:7054

4.Create new user and register it

fabric-ca-client register -u http://localhost:7054 --id.name test --id.secret testpw --id.type client --id.affiliation org1.department1

Hopefully you wont face the error you received!

Assuming you have build fabric ca server and client successfully.


答:
The img you have inside your  tag is an attribute:

```<code><li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" img style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
<!-- This one >>------------------------------------------------------------------------^^^                                       -->
</code>```

img elements don't have an img attribute. Just remove it.

Title: Attribute img not allowed on element img at this point

Body:
The img you have inside your <img ...> tag is an attribute:

<li><a href="https://twitter.com/Koeen_Yt?lang=fr"><img src="twitter.png" alt="Twitter" img style="vertical-align:middle" width="100" height="85" > Follow moi grow ! </a></li>
<!-- This one >>------------------------------------------------------------------------^^^                                       -->

img elements don't have an img attribute. Just remove it.


问:
How can I set a minimum threshold for my LUISDialog to go to None Intent in .NET?
I have a LuisDialog as such:

```<code>[LuisModel("...", "...", domain: "...")]
[Serializable]
public class MainLUISDialog : LuisDialog<object>
{

   [LuisIntent("None")]
   public async Task Default(IDialogContext context, LuisResult result)
   {
      await context.PostAsync("Não percebi, podes ser mais claro se faz favor?");
      context.Wait(MessageReceived);
   }

   [LuisIntent("Service.Cancel")]
   public async Task CancelService(IDialogContext context, LuisResult result)
   {
      await context.PostAsync("Queres cancelar um serviço.");
      await context.PostAsync("Entities:");
      foreach (var entity in result.Entities)
      {
         await context.PostAsync($"{entity.Type}: {entity.Entity}");
      }
      context.Wait(MessageReceived);
   }
...
</code>```

I wanted to know how I can set so that for example all utterances that have an intent score lower than 0.7 will go to the None intent, is there any way to programmatically in my code add this threshold? I can't seem to find any way to do this with the code I have.

答:
One way could be inheriting from LuisDialog and override one of these functions:

BestIntentFrom

BestResultFrom

DispatchToIntentHandler

In any of those functions, you should be able to do your logic to discard the intent detected and replace it with None.

If this is just for 1-2 intents, then it might not be worthy to do the overrides and instead, you can just check it in all the intent methods as:

```<code> if (result.TopScoringIntent.Score < threshold)
 {
     return Default(context, result);
 }
</code>```

Body:
I have a LuisDialog as such:

[LuisModel("...", "...", domain: "...")]
[Serializable]
public class MainLUISDialog : LuisDialog<object>
{

   [LuisIntent("None")]
   public async Task Default(IDialogContext context, LuisResult result)
   {
      await context.PostAsync("Não percebi, podes ser mais claro se faz favor?");
      context.Wait(MessageReceived);
   }

   [LuisIntent("Service.Cancel")]
   public async Task CancelService(IDialogContext context, LuisResult result)
   {
      await context.PostAsync("Queres cancelar um serviço.");
      await context.PostAsync("Entities:");
      foreach (var entity in result.Entities)
      {
         await context.PostAsync($"{entity.Type}: {entity.Entity}");
      }
      context.Wait(MessageReceived);
   }
...

I wanted to know how I can set so that for example all utterances that have an intent score lower than 0.7 will go to the None intent, is there any way to programmatically in my code add this threshold? I can't seem to find any way to do this with the code I have.

Body:
One way could be inheriting from LuisDialog and override one of these functions:

BestIntentFrom

BestResultFrom

DispatchToIntentHandler

In any of those functions, you should be able to do your logic to discard the intent detected and replace it with None.

If this is just for 1-2 intents, then it might not be worthy to do the overrides and instead, you can just check it in all the intent methods as:

 if (result.TopScoringIntent.Score < threshold)
 {
     return Default(context, result);
 }


问:
Redis sizing for Production
I have few queries regarding Redis Cluster setup:
1.Does redis support cross site replication ? When we start redis cluster,can we decide what will be the slave of each instance.
2.I need to store around 11  billion keys,with full persistance and fault tolerance,how many master -slaves should i start with? I have a high tps requirement of both read and writes.

Pls suggest.

答:
Data is important for you and you don't want to lose any data during failover/DR scenarios.

You need to create a Redis cluster.

Redis cluster needs at least 3 master nodes which shares 16384 slots between each other.

You need to create slave nodes as much as you want to replicate data from master nodes.(Please consider right slave number by yourself.)

Title: Redis sizing for Production


问:
SQL Delete conditionally between rows
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

```<code>|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |
</code>```

I need to keep the last row.

```<code>|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |
</code>```

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

答:
Your output data doesn't correspond to sample data, so i assume that you want to keep one row having num = 'AM' and minimum date or just min date if num <> 'AM' for every id and delete all other rows, so one way could be.

```<code>WITH cte
AS (
    SELECT t.*
        ,row_number() OVER (
            PARTITION BY id
             ORDER BY (case when num = 'AM' then 1 else 2 end)
                ,DATE asc
            ) AS rn
    FROM table1 t
    )
DELETE
FROM table1 t1
WHERE EXISTS (
        SELECT 1
        FROM cte c
        WHERE t1.num = c.num
            AND t1.DATE = c.DATE
            AND t1.num = c.num
            AND c.rn <> 1
        );
</code>```

Result:

```<code>id  num    date
------------------------------
99  AM     18.02.2013 00:00:00
</code>```

DEMO

Title: SQL Delete conditionally between rows

Body:
I have a table with multiple rows for the same ID and I need to keep only one row with the following rules:

NUM = 'AM' prevail on other

If multiple NUM = 'AM' or none then the oldest date prevail

For example :

|_ID_|_NUM_|______DATE______|
| 99 | AM  |   2015-04-12   |
| 99 | QS  |   2012-05-31   |
| 99 | AM  |   2013-02-18   |

I need to keep the last row.

|_ID_|_NUM_|______DATE______|
| 99 | QS  |   2013-05-31   |
| 99 | QS  |   2016-02-18   |

I need to keep the first row.

I'm on a postgres database and I can't use Function or Procedure
Thank you for any help.

Body:
Your output data doesn't correspond to sample data, so i assume that you want to keep one row having num = 'AM' and minimum date or just min date if num <> 'AM' for every id and delete all other rows, so one way could be.

WITH cte
AS (
    SELECT t.*
        ,row_number() OVER (
            PARTITION BY id
             ORDER BY (case when num = 'AM' then 1 else 2 end)
                ,DATE asc
            ) AS rn
    FROM table1 t
    )
DELETE
FROM table1 t1
WHERE EXISTS (
        SELECT 1
        FROM cte c
        WHERE t1.num = c.num
            AND t1.DATE = c.DATE
            AND t1.num = c.num
            AND c.rn <> 1
        );

Result:

id  num    date
------------------------------
99  AM     18.02.2013 00:00:00

DEMO


问:
C# Reflection Programmatic Event Handlers with Custom Event Args
Here is my problem/scenario

```<code>public class TestEventArgs : EventArgs
{
   public int ID { get; set; }
   public string Name { get; set; }
}

public event EventHandler<TestEventArgs> TestClick
</code>```

How can I attach an EventHandler on TestClick by using reflection? (obj is instance, Activator.CreateInstance)

```<code>EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(eventClick.EventHandlerType, obj, ????);
eventClick.AddEventHandler(obj, handler);
</code>```

My problem being that TestEventArgs is declared in an external dll, but ???? methodinfo above requires the signature in its delegate?

答: Do you control the source of the target assembly? If so, simply add the InternalsVisibleTo assembly attribute to the target assembly.</p>

Body:
Here is my problem/scenario

public class TestEventArgs : EventArgs
{
   public int ID { get; set; }
   public string Name { get; set; }
}

public event EventHandler<TestEventArgs> TestClick

How can I attach an EventHandler on TestClick by using reflection? (obj is instance, Activator.CreateInstance)

EventInfo eventClick = obj.GetType().GetEvent("TestClick");
Delegate handler = Delegate.CreateDelegate(eventClick.EventHandlerType, obj, ????);
eventClick.AddEventHandler(obj, handler);

My problem being that TestEventArgs is declared in an external dll, but ???? methodinfo above requires the signature in its delegate?


问:
display a paperclip image using Foreign key association
I have two Models. I would like to use the foreign key(resource_id) in my resources_game model to display an image.

This is my Resource Model

```<code>class Resource < ActiveRecord::Base

has_many :resource_books
has_many :resource_games, :dependent => :destroy
belongs_to :resouce_type
has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"
accepts_nested_attributes_for :resource_books, :resource_games
</code>```

This is my ResourceGame Model

```<code>class ResourceGame < ActiveRecord::Base

belongs_to :resource, :class_name => ResourceGame, :foreign_key => :resource_id
attr_accessor :add_resources

has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"

accepts_nested_attributes_for :add_resource
</code>```

If the image was stored in the resources table I would retrieve and populate the table like this:

in my Resources Controller:

```<code>@latest_resources = Resource.paginate(:page => params[:page],:order => "id DESC", :per_page => 10)
</code>```

then in my view:

```<code><% @latest_resources.each do |project| %>

   <tr>
     <td><%= image_tag project.image.url(:small)  %></td>
     <td><%= project.resouce_type_name %></td>
     <td><%= project.name %></td>
     <td><%= project.url %></td>
   </tr>
<% end %>
</code>```

The image is being stored in the resources_game table, so what should I do to write in the image_tag in my view to retrieve it?

答:
I found a solution that worked for me by including the resource_games model to the array in the controller .

```<code>    @latest_resources = Resource.find(:all, :include => :resource_games)
</code>```

and calling in the View like this:

```<code><% @latest_resources.each do |project| %>
  <tr>
  <% project.resource_games.each do |resourcegames| %>

<td><%= image_tag resourcegames.image.url(:small)  %></td>
  <% end %>
<td><%= project.resouce_type_name %></td>
</code>```

This way I'm populating a table with data from multiples tables at the same time.

Body:
I have two Models. I would like to use the foreign key(resource_id) in my resources_game model to display an image.

This is my Resource Model

class Resource < ActiveRecord::Base

has_many :resource_books
has_many :resource_games, :dependent => :destroy
belongs_to :resouce_type
has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"
accepts_nested_attributes_for :resource_books, :resource_games

This is my ResourceGame Model

class ResourceGame < ActiveRecord::Base

belongs_to :resource, :class_name => ResourceGame, :foreign_key => :resource_id
attr_accessor :add_resources

has_attached_file :image, :styles => { :small => "100x120>"},
                  :url  => "/assets/games/images/:basename/:style/:basename.:extension",
                  :path =>":rails_root/public/assets/games/images/:basename/:style/:basename.:extension"

accepts_nested_attributes_for :add_resource

If the image was stored in the resources table I would retrieve and populate the table like this:

in my Resources Controller:

@latest_resources = Resource.paginate(:page => params[:page],:order => "id DESC", :per_page => 10)

then in my view:

<% @latest_resources.each do |project| %>

     <%= image_tag project.image.url(:small)  %>
     <%= project.resouce_type_name %>
     <%= project.name %>
     <%= project.url %>

<% end %>

The image is being stored in the resources_game table, so what should I do to write in the image_tag in my view to retrieve it?

Body:
I found a solution that worked for me by including the resource_games model to the array in the controller .

    @latest_resources = Resource.find(:all, :include => :resource_games)

and calling in the View like this:

<% @latest_resources.each do |project| %>
  <tr>
  <% project.resource_games.each do |resourcegames| %>

<td><%= image_tag resourcegames.image.url(:small)  %></td>
  <% end %>
<td><%= project.resouce_type_name %></td>

This way I'm populating a table with data from multiples tables at the same time.


问:
Autocomplete dropdown for Asp.net
I am working on ASP.net with javascript. I have a dropdown in a page and now it needs to be autocomplete(filter by text). I found some link for this issue but everything related to Jquery and it is not working for me.

Can any one suggest me a approach to handle my requirement. Even telerik is good for me.

Thanks in advance.
Answers appreciated.

Thanks,
Dhinesh

答:
Are you looking for a datalist?

Try this:

```<code><input list="optionsList" placeholder="-- Selecionar Marca --">
    <datalist id="optionsList" style="visibility:hidden">
        <option value="Option A">
        <option value="Option B">
        <option value="Option C">
    </datalist>
</div>
</code>```

Title: Autocomplete dropdown for Asp.net

Body:
Are you looking for a datalist?

Try this:

<input list="optionsList" placeholder="-- Selecionar Marca --">
    <datalist id="optionsList" style="visibility:hidden">
        <option value="Option A">
        <option value="Option B">
        <option value="Option C">
    </datalist>
</div>


问:
Rails Number to Indian currency format conversion helper
i have number like 100000

when i user number_to_currency(100000)

it give - 100,000.00

but how can i get format like 1,00,000.00

as $ 100,000 looks good but to show it in Rs i need separators (',') like this - 1,00,00,000.00

答: I would suggest writing your own function to perform this display formatting, rather than overwriting number_to_currency.  You could call it r_number_to_currency or something like that and place it in your application view helper.</p>


问:
How to handle charts directly in code
I started working with C# and Live Charts a few days ago.

Based on examples found in the internet, I made a very simple graph in order to understand the concepts behind it.

That is what I have (it is working perfectly fine):

```<code>public partial class Wdw_graph : Window
{
    public SeriesCollection SeriesCollection { get; set; }
    public string[] Labels { get; set; }

    public Wdw_graph(List<dated_value> serie)
    {
        InitializeComponent();

        SeriesCollection = new SeriesCollection();

        ColumnSeries col_serie = new ColumnSeries {
                Values = new ChartValues<double>(),
                DataLabels = true };

        Labels = new string[serie.Count];

        for(int i = 0; i < serie.Count; i++)
        {
            col_serie.Values.Add(serie[i].value);
            Labels[i] = serie[i].date;
        }

        SeriesCollection.Add(col_serie);

        DataContext = this;
    }
}
</code>```

<Grid>
    <lvc:CartesianChart Series="{Binding SeriesCollection}" >
          <lvc:CartesianChart.AxisX>
            <lvc:Axis Labels="{Binding Labels}" LabelsRotation="80">
              <lvc:Axis.Separator>
                <lvc:Separator IsEnabled="False" Step="1"></lvc:Separator>
              </lvc:Axis.Separator>
            </lvc:Axis>
          </lvc:CartesianChart.AxisX>
        <lvc:CartesianChart.AxisY>
            <lvc:Axis Title="Sold Apps"></lvc:Axis>
        </lvc:CartesianChart.AxisY>
    </lvc:CartesianChart>
</Grid>
```

<p>As you can see, I have 'SeriesCollection' and 'Labels' handled in the class code and them they are bound to the XAML.</p>

<p>I would like to know if it is possible to use the same approach to handle other graph elements, such as the 'AxisX'. If so, how can I do it?</p>

<p>In this post "Change the format of the axis tick labels in LiveCharts" there is a code that shows what I would like to do:</p>

```cartesianChart2.AxisX.Add(new Axis
{
    Name = "xAxis",
    Title = "DateTime",
    FontSize = 22,
    Foreground = System.Windows.Media.Brushes.Black,
    MinValue = 0,
    MaxValue = _amountValues,
});
```

But I could not reproduce that. I can't figure out where the 'cartesianChart2' comes from.

答:
Well, I learned how to refer to the XAML elements in the class code.

I added 'x:Name="something"' to the CartesianChart and removed everything else (not using 'Binding' anymore):

```<code><Grid>
    <lvc:CartesianChart x:Name="cartesian_chart">
    </lvc:CartesianChart>
</Grid>
</code>```

Then, in the class code I inserted the axis and serie:

```<code>public partial class Wdw_graph : Window
{
    public Wdw_graph(List<dated_value> serie)
    {
        InitializeComponent();

        cartesian_chart.AxisX.Add(new Axis
        {
            Name = "xAxis",
            Title = "Date and Time",
            FontSize = 20,
            Foreground = System.Windows.Media.Brushes.Black,
            MinValue = 0,
            MaxValue = serie.Count,
            Labels = new String[serie.Count],
        });
        cartesian_chart.AxisY.Add(new Axis
        {
            Name = "yAxis",
            Title = "Currency",
            FontSize = 20,
            Foreground = System.Windows.Media.Brushes.Black,
            MinValue = 0,
            MaxValue = 10,
        });

        cartesian_chart.AxisX[0].Separator.Step = 1;
        cartesian_chart.AxisX[0].LabelsRotation = 80;

        ColumnSeries col_serie = new ColumnSeries {
                Values = new ChartValues<double>(),
                DataLabels = true };

        for(int i = 0; i < serie.Count; i++)
        {
            col_serie.Values.Add(serie[i].value);
            cartesian_chart.AxisX[0].Labels[i] = serie[i].date;
        }

        cartesian_chart.Series.Add(col_serie);

        DataContext = this;
    }
}
</code>```

I really preferred to handle the graph directly from the code, instead of using the XAML.

Can you tell me what are the drawbacks of this approach?

Title: How to handle charts directly in code

Body:
I started working with C# and Live Charts a few days ago.

Based on examples found in the internet, I made a very simple graph in order to understand the concepts behind it.

That is what I have (it is working perfectly fine):

public partial class Wdw_graph : Window
{
    public SeriesCollection SeriesCollection { get; set; }
    public string[] Labels { get; set; }

    public Wdw_graph(List<dated_value> serie)
    {
        InitializeComponent();

        SeriesCollection = new SeriesCollection();

        ColumnSeries col_serie = new ColumnSeries {
                Values = new ChartValues<double>(),
                DataLabels = true };

        Labels = new string[serie.Count];

        for(int i = 0; i < serie.Count; i++)
        {
            col_serie.Values.Add(serie[i].value);
            Labels[i] = serie[i].date;
        }

        SeriesCollection.Add(col_serie);

        DataContext = this;
    }
}

<Grid>
    <lvc:CartesianChart Series="{Binding SeriesCollection}" >
          <lvc:CartesianChart.AxisX>
            <lvc:Axis Labels="{Binding Labels}" LabelsRotation="80">
              <lvc:Axis.Separator>
                <lvc:Separator IsEnabled="False" Step="1"></lvc:Separator>
              </lvc:Axis.Separator>
            </lvc:Axis>
          </lvc:CartesianChart.AxisX>
        <lvc:CartesianChart.AxisY>
            <lvc:Axis Title="Sold Apps"></lvc:Axis>
        </lvc:CartesianChart.AxisY>
    </lvc:CartesianChart>
</Grid>

As you can see, I have 'SeriesCollection' and 'Labels' handled in the class code and them they are bound to the XAML.

I would like to know if it is possible to use the same approach to handle other graph elements, such as the 'AxisX'. If so, how can I do it?

In this post "Change the format of the axis tick labels in LiveCharts" there is a code that shows what I would like to do:

cartesianChart2.AxisX.Add(new Axis
{
    Name = "xAxis",
    Title = "DateTime",
    FontSize = 22,
    Foreground = System.Windows.Media.Brushes.Black,
    MinValue = 0,
    MaxValue = _amountValues,
});

But I could not reproduce that. I can't figure out where the 'cartesianChart2' comes from.

Body:
Well, I learned how to refer to the XAML elements in the class code.

I added 'x:Name="something"' to the CartesianChart and removed everything else (not using 'Binding' anymore):

<Grid>
    <lvc:CartesianChart x:Name="cartesian_chart">
    </lvc:CartesianChart>
</Grid>

Then, in the class code I inserted the axis and serie:

public partial class Wdw_graph : Window
{
    public Wdw_graph(List<dated_value> serie)
    {
        InitializeComponent();

        cartesian_chart.AxisX.Add(new Axis
        {
            Name = "xAxis",
            Title = "Date and Time",
            FontSize = 20,
            Foreground = System.Windows.Media.Brushes.Black,
            MinValue = 0,
            MaxValue = serie.Count,
            Labels = new String[serie.Count],
        });
        cartesian_chart.AxisY.Add(new Axis
        {
            Name = "yAxis",
            Title = "Currency",
            FontSize = 20,
            Foreground = System.Windows.Media.Brushes.Black,
            MinValue = 0,
            MaxValue = 10,
        });

        cartesian_chart.AxisX[0].Separator.Step = 1;
        cartesian_chart.AxisX[0].LabelsRotation = 80;

        ColumnSeries col_serie = new ColumnSeries {
                Values = new ChartValues<double>(),
                DataLabels = true };

        for(int i = 0; i < serie.Count; i++)
        {
            col_serie.Values.Add(serie[i].value);
            cartesian_chart.AxisX[0].Labels[i] = serie[i].date;
        }

        cartesian_chart.Series.Add(col_serie);

        DataContext = this;
    }
}

I really preferred to handle the graph directly from the code, instead of using the XAML.

Can you tell me what are the drawbacks of this approach?


问:
UITextView with custom font not working when text set to "attributed"
I have a UITextView with some text that came from a .rtf (pasted directly onto Xcode)

The context contain only one custom font (Futura Book BT 11.0)

If I set the "text(attributed)" property to "plain"= The custom font appear properly from the storyboard and from the app

If I set the "text" property to "attributed"=. The custom font appear properly from the storyboard BUT not from the app.

As my goal was to have a text with multiple font working, how to have the attributed property to work with custom fonts? (Swift)

Thanks!

答:
I have faced the same problem when I used multiple custom fonts in attributed UILabel. Storyboard shows correct result but device does not!!

What I have find out that if the font size is different of text with different custom fonts. It works fine!!

So for now I use font size with minor difference. Like if one is 14 I used 14.01 for the other. Its not possible inside storyboard so I opened storyboard as source code and manually set font size like:

```<code><attributedString key="attributedTitle">
  <fragment content="Do not have account? ">
      <attributes>
        <color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
        <font key="NSFont" size="14" name="Roboto-Light"/>
        <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
      </attributes>
    </fragment>
    <fragment content="Login">
      <attributes>
        <color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
        <font key="NSFont" size="14.01" name="Roboto-Bold"/>
        <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
      </attributes>
    </fragment>
<attributedString key="attributedTitle">
</code>```

But still I am unable to find why it happens!

Body:
I have faced the same problem when I used multiple custom fonts in attributed UILabel. Storyboard shows correct result but device does not!!

What I have find out that if the font size is different of text with different custom fonts. It works fine!!

So for now I use font size with minor difference. Like if one is 14 I used 14.01 for the other. Its not possible inside storyboard so I opened storyboard as source code and manually set font size like:

<attributedString key="attributedTitle">
  <fragment content="Do not have account? ">
      <attributes>
        <color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
        <font key="NSFont" size="14" name="Roboto-Light"/>
        <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
      </attributes>
    </fragment>
    <fragment content="Login">
      <attributes>
        <color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="calibratedRGB"/>
        <font key="NSFont" size="14.01" name="Roboto-Bold"/>
        <paragraphStyle key="NSParagraphStyle" alignment="center" lineBreakMode="wordWrapping" baseWritingDirection="natural" tighteningFactorForTruncation="0.0"/>
      </attributes>
    </fragment>
<attributedString key="attributedTitle">

But still I am unable to find why it happens!


问:
Converting string format to datetime in mm/dd/yyyy
I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.

```<code>string strDate = DateTime.Now.ToString("MM/dd/yyyy");
</code>```

Please help.

答:
Solution

```<code>DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
</code>```

Body:
I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Please help.

Body:
Solution

DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)