问:
Sharepoint ItemStyle.xsl for CQWP using images from a content type
I'm building a custom Content Query Web Part to display rollup information from an employee content type.  This content type has a Publishing Image site column called EmpPhoto.  My CQWP is working great and all the site columns I need are available.

I am now creating a custom xsl template to render the information correctly but am stuck using the EmpPhoto image.

If I use the code:

```<code><xsl:value-of select="@EmpPhoto" disable-output-escaping="yes" />
</code>```

... I get a correctly rendered image which is great.  However I want to build an onmouseover event for this image and this approach will not work.

I thought to create an xsl variable to grab the actual image URL then build my own html img and write the onmouseover into that e.g.

```<code><xsl:variable name="EmpPhotoUrl">
    <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="@EmpPhoto"/>
    </xsl:call-template>
</xsl:variable>
</code>```

...

```<code><img src="{$EmpPhotoUrl}" onmouseover="" alt="test" />
</code>```

This doesn't get the URL from the EmpPhoto site column however.  I am new to xsl so I might well be missing an obvious solution!

Any help much appreciated,

Jonny

答:
Given the @EmpPhoto value is just a string representing an html image tag, you could "inject" the mouseover script into the value, e.g.</p>

```<code><xsl:variable name="EmpPhoto"><xsl:value-of select=sub-string(@EmpPhoto) />[and some other code to add the mouseover etc]</xsl:variable>

<xsl:value-of select="$EmpPhoto" />
</code>```

OwnerDisplayName: Jonny

ContentLicense: CC BY-SA 2.5

Body:
I'm building a custom Content Query Web Part to display rollup information from an employee content type.  This content type has a Publishing Image site column called EmpPhoto.  My CQWP is working great and all the site columns I need are available.

I am now creating a custom xsl template to render the information correctly but am stuck using the EmpPhoto image.

If I use the code:

<xsl:value-of select="@EmpPhoto" disable-output-escaping="yes" />

... I get a correctly rendered image which is great.  However I want to build an onmouseover event for this image and this approach will not work.

I thought to create an xsl variable to grab the actual image URL then build my own html img and write the onmouseover into that e.g.

<xsl:variable name="EmpPhotoUrl">
    <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
        <xsl:with-param name="UrlColumnName" select="@EmpPhoto"/>
    </xsl:call-template>
</xsl:variable>

...

This doesn't get the URL from the EmpPhoto site column however.  I am new to xsl so I might well be missing an obvious solution!

Any help much appreciated,

Jonny

Body:
Given the @EmpPhoto value is just a string representing an html image tag, you could "inject" the mouseover script into the value, e.g.

<xsl:variable name="EmpPhoto"><xsl:value-of select=sub-string(@EmpPhoto) />[and some other code to add the mouseover etc]</xsl:variable>

<xsl:value-of select="$EmpPhoto" />

OwnerDisplayName: Nat


来源: stackexchange

问:
How to "duplicate" the content of an array
If I have an array :

```<code>var array_1 = ['c','b','a'];
</code>```

What is the best way to transform array_1 into

```<code>['c','c','b','b','a','a'];
</code>```

or even

```<code>['c','c','c','b','b','b','a','a','a'];
</code>```

答:
```<code>var array_1 = ['a','b','c']
/* if array has numbers array_1 = [1,2,3] both case are handled and you can change duplicacy number for elements.*/

getResult = (array_1,elemDuplicacyNumber)=>{

    return  elemDuplicacyNumber <= 0 ? array_1 : array_1.reduce((curr, acc) =>{

                    let arr1 = Array(elemDuplicacyNumber).fill(curr);
                    let arr2 = Array(elemDuplicacyNumber).fill(acc);

                     arr1 = isNaN(curr) ? arr1   : arr1.map(Number);
                     arr2 = isNaN(acc) ?  arr2 : arr2.map(Number);

                    return (Array.isArray(curr)?curr : arr1 ).concat(arr2)
            })

}

console.log( getResult(array_1,5) )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I have an array :

var array_1 = ['c','b','a'];

What is the best way to transform array_1 into

['c','c','b','b','a','a'];

or even

['c','c','c','b','b','b','a','a','a'];


问:
How can I custom multidimensional array?
I have array like this :

```<code>$a  = array('value' =>
    array(
        'lesson_id' => array('1','6'),
        'knowledge_value' => array('2','7'),
        'knowledge_description' => array('3','8'),
        'skill_value' => array('4','9'),
        'skill_description' => array('5','10')
    )
);
</code>```

I want to change it to be like this :

```<code>$a = array('value' =>
    array(
        array(
            'lesson_id' => '1',
            'knowledge_value' => '2',
            'knowledge_description' => '3',
            'skill_value' => '4',
            'skill_description' => '5'
        ),
        array(
            'lesson_id' => '6',
            'knowledge_value' => '7',
            'knowledge_description' => '8',
            'skill_value' => '9',
            'skill_description' => '10'
        ),
    )
);
</code>```

How can I do it?

答:
Demo Link

Here is the snippet for you to work, please see inline doc for explanation

```<code>$temp = [];
$keys = array_keys($a['value']); // fetched all keys
for ($i = 0; $i < count($a['value']['lesson_id']); $i++) { // compared with first count of lession_id
    $temp['value'][] = array_combine($keys, array_column($a['value'], $i)); // combined key and values
}
</code>```

array_keys — Return all the keys or a subset of the keys of an array

array_combine — Creates an array by using one array for keys and another for its values

array_column — Return the values from a single column in the input array

Body:
I have array like this :

$a  = array('value' =>
    array(
        'lesson_id' => array('1','6'),
        'knowledge_value' => array('2','7'),
        'knowledge_description' => array('3','8'),
        'skill_value' => array('4','9'),
        'skill_description' => array('5','10')
    )
);

I want to change it to be like this :

$a = array('value' =>
    array(
        array(
            'lesson_id' => '1',
            'knowledge_value' => '2',
            'knowledge_description' => '3',
            'skill_value' => '4',
            'skill_description' => '5'
        ),
        array(
            'lesson_id' => '6',
            'knowledge_value' => '7',
            'knowledge_description' => '8',
            'skill_value' => '9',
            'skill_description' => '10'
        ),
    )
);

How can I do it?

Body:
Demo Link

Here is the snippet for you to work, please see inline doc for explanation

$temp = [];
$keys = array_keys($a['value']); // fetched all keys
for ($i = 0; $i < count($a['value']['lesson_id']); $i++) { // compared with first count of lession_id
    $temp['value'][] = array_combine($keys, array_column($a['value'], $i)); // combined key and values
}

array_keys — Return all the keys or a subset of the keys of an array

array_combine — Creates an array by using one array for keys and another for its values

array_column — Return the values from a single column in the input array


问:
Speed up reading/hashing millions of files/images
I have directories containing 100K - 1 million images. I'm going to create a hash for each image so that I can, in the future, find an exact match based on these hashes. My current approach is:

def hash_test(images):      # images is a list of image paths
    hashes = []
    for image in images:
        with open(folder + image, 'rb', buffering=0) as f:
           hashes.append(hashlib.sha256(f.read()).hexdigest())
           # hashes.append(CityHash128(f.read()))
    return hashes
```

```31%|███       | 102193/334887 [00:04<42:15, 112.02it/s]
```

Of what I can tell from my experiments, the file.read() operation is my bottleneck, which means that I am I/O bound. This is also confirmed by checking iotop . I am reading from a HDD. I have read about memory-mapped reading, but couldn't get my head around whether it was applicable in this situation or not.

My question is: is there a way to optimize this reading operation?

答:
You can try to parallelise your hash computation code like below. However, the performance depends upon how much parallel IO requests the disk can handle and also on how many cores does your CPU have. But, you can try.</p>

```<code>
from multiprocessing import Pool

# This function will return hashes as list
# Will wait for all parallel hash computation to complete

def parallel_hash(images):
    with Pool(5) as pool:
        return pool.map(hash_test, images)

def hash_test(image):      # images is a list of image paths
    with open(folder + image, 'rb', buffering=0) as f:
        return hashlib.sha256(f.read()).hexdigest()
        # hashes.append(CityHash128(f.read()))

parallel_hash(images)
</code>```

Body:
I have directories containing 100K - 1 million images. I'm going to create a hash for each image so that I can, in the future, find an exact match based on these hashes. My current approach is:

def hash_test(images):      # images is a list of image paths
    hashes = []
    for image in images:
        with open(folder + image, 'rb', buffering=0) as f:
           hashes.append(hashlib.sha256(f.read()).hexdigest())
           # hashes.append(CityHash128(f.read()))
    return hashes

31%|███       | 102193/334887 [00:04<42:15, 112.02it/s]

Of what I can tell from my experiments, the file.read() operation is my bottleneck, which means that I am I/O bound. This is also confirmed by checking iotop . I am reading from a HDD. I have read about memory-mapped reading, but couldn't get my head around whether it was applicable in this situation or not.

My question is: is there a way to optimize this reading operation?

Body:
You can try to parallelise your hash computation code like below. However, the performance depends upon how much parallel IO requests the disk can handle and also on how many cores does your CPU have. But, you can try.

from multiprocessing import Pool

# This function will return hashes as list
# Will wait for all parallel hash computation to complete

def parallel_hash(images):
    with Pool(5) as pool:
        return pool.map(hash_test, images)

def hash_test(image):      # images is a list of image paths
    with open(folder + image, 'rb', buffering=0) as f:
        return hashlib.sha256(f.read()).hexdigest()
        # hashes.append(CityHash128(f.read()))

parallel_hash(images)


问:
How to add a subdomain in cloudflare for my azure container which requires a port number to access it
I have a metabase docker image running on my Azure container. It can be accessed through azure's fqdn:port_number (port is 3000) or ip:port_number. I want to give a nice domain name for this application through cloudflare(. How can I do this?
Thanks in Advance!

PS: There were some topics on this in cloudflare community but I couldn't fine any answer relevant for me.

答:
You could add a CNAME record to point subdomain such as www.example.com to the FQDN value of your Azure container like containerdns.westus.azurecontainer.io.

Example of a CNAME record:

```<code>name: www
record type: CNAME
value:  FQDN value of your Azure container
TTL: 32600
</code>```

ref: https://www.cloudflare.com/learning/dns/dns-records/dns-cname-record/
https://support.cloudflare.com/hc/en-us/articles/360019093151-

Update

From your comment, you want to access myapp.com which actually points to fqdn:port. In this case, you could create and configure an application gateway to host web sites with custom ports using the Azure portal. If you have multiple sites, you could follow this tutorial.

You could follow the steps below:

Create a public-facing application gateway with a public IP address in the same region as your container instance.

Create a backend pool with target hostname of your container FQDN like containerdns.westus.azurecontainer.io

Create a basic listener and provide name, frontend port 80 and protocol HTTP.

Create a health probe, provide protocol HTTP, check the box Pick host name from backend http settings and the remaining setting is the default.

Add an HTTP-settings with custom port 3000 as your desired and check the box Pick host name from backend address and use custom probe and select custom probe.

Create a basic rule with the backend pool and HTTP setting.

In the end, you could create a CNAME record mapping the subdomain www.myapp.com to the FQDN of your application gateway.

I validate this on my website on Azure VM, hope this could help you.

Body:
You could add a CNAME record to point subdomain such as www.example.com to the FQDN value of your Azure container like containerdns.westus.azurecontainer.io.

Example of a CNAME record:

name: www
record type: CNAME
value:  FQDN value of your Azure container
TTL: 32600

ref: https://www.cloudflare.com/learning/dns/dns-records/dns-cname-record/
https://support.cloudflare.com/hc/en-us/articles/360019093151-

Update

From your comment, you want to access myapp.com which actually points to fqdn:port. In this case, you could create and configure an application gateway to host web sites with custom ports using the Azure portal. If you have multiple sites, you could follow this tutorial.

You could follow the steps below:

Create a public-facing application gateway with a public IP address in the same region as your container instance.

Create a backend pool with target hostname of your container FQDN like containerdns.westus.azurecontainer.io

Create a basic listener and provide name, frontend port 80 and protocol HTTP.

Create a health probe, provide protocol HTTP, check the box Pick host name from backend http settings and the remaining setting is the default.

Add an HTTP-settings with custom port 3000 as your desired and check the box Pick host name from backend address and use custom probe and select custom probe.

Create a basic rule with the backend pool and HTTP setting.

In the end, you could create a CNAME record mapping the subdomain www.myapp.com to the FQDN of your application gateway.

I validate this on my website on Azure VM, hope this could help you.


问:
Checkbox click function is not working angular 4
I have this data coming from another component
on the basis of active tag when row is clicked I am pushing Id to ngModel of checkbox input field.
Row click is working fine and checkbox is adding/removing data
but now when I click on checkbox itself it doesn't do anything like checkbox click function is not working
How can I solve that?

html component

```<code><ngb-panel [disabled]="true" *ngFor="let testPanel of otherTests; let i = index;" id="{{testPanel.Id}}" [title]="testPanel.Name">
  <ng-template ngbPanelTitle>
    <div class="action-items">
      <label class="custom-control custom-checkbox">
          <input
            type="checkbox"
            class="custom-control-input"
            [name]="testPanel.Id + '-' + testPanel.Moniker"
            [ngModel]="panelIds.indexOf(testPanel.Id) > -1"
            (ngModelChange)="onPanelCheckboxUpdate($event, testPanel)"
            [id]="testPanel.Id + '-' + testPanel.Moniker">
          <span class="custom-control-indicator"></span>
      </label>
    </div>
  </ng-template>
</ngb-panel>
</code>```

ts component

getting Id from service and push it on basis of row click

```<code>this.testOrderService.refreshRequestsObservable().subscribe(
  data => {

    this.panelActive = data.active;
    let testFilteredArray = lodash.filter(this.otherTests, item => item.Id === data.id);

    if (this.panelActive) {
      // is checked
      this.panelIds.push(data.id);
      if(testFilteredArray.length > 0){
        this.selectedPanels.push(testFilteredArray[0]);
      }
    }
    else {
      //is false
      this.panelIds = this.panelIds.filter(obj => obj !== data.id);
      this.selectedPanels = this.selectedPanels.filter(obj => obj.Id !== data.id);
    }

    // this.panelIds = lodash.uniq(this.panelIds);
    this.selectedPanels = lodash.uniqBy(this.selectedPanels, "Id");

    this.updateSession();

  }
)
</code>```

checkbox function

```<code>onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
let testPanelIds = panel.Tests.map(test => test.Id);
// Wipe any duplicates
this.panelIds = this.panelIds.filter(
  panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
);
this.selectedPanels = this.selectedPanels.filter(
  selectedPanel =>
    panel.Id !== selectedPanel.Id &&
    testPanelIds.indexOf(selectedPanel.Id) === -1
);

if ($event) {
  this.panelIds.push(panel.Id);
  this.selectedPanels.push(panel);
 }
 this.updateSession();
 }
</code>```

This checkbox function is not working and wont let me change the value of checkbox.

And also is there any way of adding click function in ngbPanel tag?
Any help?
Thanks

答:
If you want to achieve two way data binding , use below code.

In foo.html

```<code><input [(ngModel)]="checBxFlag" type="checkbox"/>
</code>```

In App.module.ts
    import { FormsModule } from '@angular/forms';

```<code>@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})
</code>```

If you want fire event click of check box ,use (onClick)="somemethod()" in your foo.html file and define method in foo.ts file.

Body:
I have this data coming from another component
on the basis of active tag when row is clicked I am pushing Id to ngModel of checkbox input field.
Row click is working fine and checkbox is adding/removing data
but now when I click on checkbox itself it doesn't do anything like checkbox click function is not working
How can I solve that?

html component

<ngb-panel [disabled]="true" *ngFor="let testPanel of otherTests; let i = index;" id="{{testPanel.Id}}" [title]="testPanel.Name">
  <ng-template ngbPanelTitle>

          <input
            type="checkbox"
            class="custom-control-input"
            [name]="testPanel.Id + '-' + testPanel.Moniker"
            [ngModel]="panelIds.indexOf(testPanel.Id) > -1"
            (ngModelChange)="onPanelCheckboxUpdate($event, testPanel)"
            [id]="testPanel.Id + '-' + testPanel.Moniker">

  </ng-template>
</ngb-panel>

ts component

getting Id from service and push it on basis of row click

this.testOrderService.refreshRequestsObservable().subscribe(
  data => {

    this.panelActive = data.active;
    let testFilteredArray = lodash.filter(this.otherTests, item => item.Id === data.id);

    if (this.panelActive) {
      // is checked
      this.panelIds.push(data.id);
      if(testFilteredArray.length > 0){
        this.selectedPanels.push(testFilteredArray[0]);
      }
    }
    else {
      //is false
      this.panelIds = this.panelIds.filter(obj => obj !== data.id);
      this.selectedPanels = this.selectedPanels.filter(obj => obj.Id !== data.id);
    }

    // this.panelIds = lodash.uniq(this.panelIds);
    this.selectedPanels = lodash.uniqBy(this.selectedPanels, "Id");

    this.updateSession();

  }
)

checkbox function

onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
let testPanelIds = panel.Tests.map(test => test.Id);
// Wipe any duplicates
this.panelIds = this.panelIds.filter(
  panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
);
this.selectedPanels = this.selectedPanels.filter(
  selectedPanel =>
    panel.Id !== selectedPanel.Id &&
    testPanelIds.indexOf(selectedPanel.Id) === -1
);

if ($event) {
  this.panelIds.push(panel.Id);
  this.selectedPanels.push(panel);
 }
 this.updateSession();
 }

This checkbox function is not working and wont let me change the value of checkbox.

And also is there any way of adding click function in ngbPanel tag?
Any help?
Thanks

Body:
If you want to achieve two way data binding , use below code.

In foo.html

<input [(ngModel)]="checBxFlag" type="checkbox"/>

In App.module.ts
    import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

If you want fire event click of check box ,use (onClick)="somemethod()" in your foo.html file and define method in foo.ts file.


问:
When players use reset board function on my Tic Tac Toe/ Connect Four game, the game counts every button click as win?
The code works perfectly until the player uses the 'reset board' function the game decides that the any button click afterwards is a winner and the only way to stop this is to close and re-build the application (using visual studio). This is using a WPF application.

I don't know exactly what is causing the issue, but i have a feeling it has something to do with the checkforwinner method and how it checks that all buttons in a row or column by matching all colours. When the board is reset, it changes the colour of all the buttons to color.lightgray which may interfere with the checkforwinner function.

If it is not too much trouble i would also like to add a 'dropping' mechanic like the real connect four and make a more efficient checkforwinner function so i can expand the board to 12 x 8 or so and not have double or triple the amount of checkforwinner if statements, cheers.

Code is below:

```<code>public partial class Form1 : Form
{
    bool turn = true; //if true it is red turn / if false it is yellow turn
    int turn_count = 0; //counts each turn for features such as draw function
    bool winner_found = false; // automatically sets winner found function to false to
    int win_method;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Random rnd = new Random();
        win_method = rnd.Next(1, 4);

        if (win_method == 1)
        {
            winMethod.Text = "Horizontal Wins Only";
        }
        else if (win_method == 2)
        {
            winMethod.Text = "Vertical Wins Only";
        }
        else if (win_method == 3)
        {
            winMethod.Text = "Diagonal Wins Only";
        }
    }

    // function to alternate turns between red and yellow players and count turns for potential draws (see below).
    // Also run checkForWinner function after every move (button click)
    private void button_click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (turn)
            b.BackColor = Color.Yellow;

        else
            b.BackColor = Color.Red;

        turn = !turn;
        b.Enabled = false;
        turn_count++;
        checkForWinner();
    }

    private void checkForWinner()
    {
        if (win_method == 1)

            //check for horizontal wins
            if ((A1.BackColor == A2.BackColor) && (A2.BackColor == A3.BackColor) && (A3.BackColor == A4.BackColor) && (A4.BackColor == A5.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((B1.BackColor == B2.BackColor) && (B2.BackColor == B3.BackColor) && (B3.BackColor == B4.BackColor) && (B4.BackColor == B5.BackColor) && (!B1.Enabled))
                winner_found = true;
            else if ((C1.BackColor == C2.BackColor) && (C2.BackColor == C3.BackColor) && (C3.BackColor == C4.BackColor) && (C4.BackColor == C5.BackColor) && (!C1.Enabled))
                winner_found = true;
            else if ((D1.BackColor == D2.BackColor) && (D2.BackColor == D3.BackColor) && (D3.BackColor == D4.BackColor) && (D4.BackColor == D5.BackColor) && (!D1.Enabled))
                winner_found = true;
            else if ((E1.BackColor == E2.BackColor) && (E2.BackColor == E3.BackColor) && (E3.BackColor == E4.BackColor) && (E4.BackColor == E5.BackColor) && (!E1.Enabled))
                winner_found = true;

        if (win_method == 2)

            //check for vertical wins
            if ((A1.BackColor == B1.BackColor) && (B1.BackColor == C1.BackColor) && (C1.BackColor == D1.BackColor) && (D1.BackColor == E1.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((A2.BackColor == B2.BackColor) && (B2.BackColor == C2.BackColor) && (C2.BackColor == D2.BackColor) && (D2.BackColor == E2.BackColor) && (!A2.Enabled))
                winner_found = true;
            else if ((A3.BackColor == B3.BackColor) && (B3.BackColor == C3.BackColor) && (C3.BackColor == D3.BackColor) && (D3.BackColor == E3.BackColor) && (!A3.Enabled))
                winner_found = true;
            else if ((A4.BackColor == B4.BackColor) && (B4.BackColor == C4.BackColor) && (C4.BackColor == D4.BackColor) && (D4.BackColor == E4.BackColor) && (!A4.Enabled))
                winner_found = true;
            else if ((A5.BackColor == B5.BackColor) && (B5.BackColor == C5.BackColor) && (C5.BackColor == D5.BackColor) && (D5.BackColor == E5.BackColor) && (!A5.Enabled))
                winner_found = true;

        if (win_method == 3)

            //check for diagonal wins
            if ((A1.BackColor == B2.BackColor) && (B2.BackColor == C3.BackColor) && (C3.BackColor == D4.BackColor) && (D4.BackColor == E5.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((A5.BackColor == B4.BackColor) && (B4.BackColor == C3.BackColor) && (C3.BackColor == D2.BackColor) && (D2.BackColor == E1.BackColor) && (!A5.Enabled))
                winner_found = true;

        // when winner string is detected to be true than find player who
        //won and give players a message box to show this.
            // also adds one point to the player who wins the round
        if (winner_found)
        {
            disableButtons();

            String winner = "";
            if (turn)
            {
                winner = Color.Red.ToString();
                red_win_count.Text = (Int32.Parse(red_win_count.Text) + 1).ToString();
            }
            else
            {
                winner = Color.Yellow.ToString();
                yellow_win_count.Text = (Int32.Parse(yellow_win_count.Text) + 1).ToString();
            }
        }
        else
        {  // if all squares are filled (25 moves) than signal draw as no more moves can be made
            if (turn_count == 25)
                MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
        }
    }

    // function to disable all buttons for when winner is detected
    private void disableButtons()
    {
        try
        {
            foreach (Control c in Controls)
            {
                Button b = (Button)c;
                b.Enabled = false;
            }
        }
        catch { }
    }

    // help -> how to play: instructions on how to play the game in brief terms
    private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
            "but there is a lot more spaces for you to play you pieces and you have to connect " +
            "five to win! The twist is, that you can only win a certain way, dependent on the " +
            "randomly generated direction on the right hand side of the screen. If the direction is " +
            "vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
            "horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
    }
    // help -> about: quick about menu of the game, creator and copyright year/ symbol
    private void aboutToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void fileToolStripMenuItem_click(object sender, EventArgs e)
    {

    }
    // file -> new game: resets complete game board to have a rematch
    private void newGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        turn = true;
        turn_count = 0;

        Random rnd = new Random();
        win_method = rnd.Next(1, 4);

        if (win_method == 1)
        {
            winMethod.Text = "Horizontal Wins Only";
        }
        else if (win_method == 2)
        {
            winMethod.Text = "Vertical Wins Only";
        }
        else if (win_method == 3)
        {
            winMethod.Text = "Diagonal Wins Only";
        }

        foreach (Control c in Controls)
        {
            try
            {
                Button b = (Button)c;
                b.Enabled = true;
                b.BackColor = Color.LightGray;
            }
            catch { }
        }
    }
    // file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
    private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void helpToolStrip_click(object sender, EventArgs e)
    {

    }

    private void button_enter(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            if (turn)
                b.BackColor = Color.Yellow;
            else
                b.BackColor = Color.Red;
        }
    }

    private void button_leave(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = Color.LightGray;
        }
    }

    private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
    {
        yellow_win_count.Text = "0";
        red_win_count.Text = "0";
    }
}
</code>```

答:
Have a play with this code:

```<code>public enum WinMethod
{
    Horizontal,
    Vertical,
    Diagonal,
}
public enum Player
{
    Yellow,
    Red,
}

public partial class Form1 : Form
{
    Player turn = Player.Red;
    int turn_count = 0; //counts each turn for features such as draw function
    bool winner_found = false; // automatically sets winner found function to false to
    private WinMethod win_method;

    private Dictionary<Player, int> _winnerCount = new Dictionary<Player, int>()
    {
        { Player.Yellow, 0 },
        { Player.Red, 0 },
    };

    public Form1()
    {
        InitializeComponent();
    }

    private static Random __rnd = new Random();

    private void Form1_Load(object sender, EventArgs e)
    {
        win_method =
            new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
                .OrderBy(_ => __rnd.Next())
                .First();
    }

    // function to alternate turns between red and yellow players and count turns for potential draws (see below).
    // Also run checkForWinner function after every move (button click)
    private void button_click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        b.BackColor = turn == Player.Red ? Color.Red : Color.Yellow;
        turn = turn == Player.Red ? Player.Yellow : Player.Red;
        b.Enabled = false;
        turn_count++;
        checkForWinner();
    }

    private void checkForWinner()
    {
        var grid = new[]
        {
            new { line = new [] { A1, A2, A3, A4, A5 }, method = WinMethod.Horizontal },
            new { line = new [] { B1, B2, B3, B4, B5 }, method = WinMethod.Horizontal },
            new { line = new [] { C1, C2, C3, C4, C5 }, method = WinMethod.Horizontal },
            new { line = new [] { D1, D2, D3, D4, D5 }, method = WinMethod.Horizontal },
            new { line = new [] { E1, E2, E3, E4, E5 }, method = WinMethod.Horizontal },
            new { line = new [] { A1, B1, C1, D1, E1 }, method = WinMethod.Vertical },
            new { line = new [] { A2, B2, C2, D2, E2 }, method = WinMethod.Vertical },
            new { line = new [] { A3, B3, C3, D3, E3 }, method = WinMethod.Vertical },
            new { line = new [] { A4, B4, C4, D4, E4 }, method = WinMethod.Vertical },
            new { line = new [] { A5, B5, C5, D5, E5 }, method = WinMethod.Vertical },
            new { line = new [] { A1, B2, C3, D4, E5 }, method = WinMethod.Diagonal },
            new { line = new [] { E1, D2, C3, B4, A5 }, method = WinMethod.Diagonal },
        };

        winner_found =
            grid.Any(g => g.method == win_method && g.line.Select(x => x.BackColor).Distinct().Count() == 1);

        if (winner_found)
        {
            disableButtons();

            _winnerCount[turn] += 1;
            (turn == Player.Red ? red_win_count : yellow_win_count).Text = _winnerCount[turn].ToString();
        }
        else
        {  // if all squares are filled (25 moves) than signal draw as no more moves can be made
            if (turn_count == 25)
                MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
        }
    }

    // function to disable all buttons for when winner is detected
    private void disableButtons()
    {
        foreach (Button b in Controls.OfType<Button>())
        {
            b.Enabled = false;
        }
    }

    // help -> how to play: instructions on how to play the game in brief terms
    private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
            "but there is a lot more spaces for you to play you pieces and you have to connect " +
            "five to win! The twist is, that you can only win a certain way, dependent on the " +
            "randomly generated direction on the right hand side of the screen. If the direction is " +
            "vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
            "horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
    }
    // help -> about: quick about menu of the game, creator and copyright year/ symbol
    private void aboutToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void fileToolStripMenuItem_click(object sender, EventArgs e)
    {

    }
    // file -> new game: resets complete game board to have a rematch
    private void newGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        turn = Player.Red;
        turn_count = 0;

        win_method =
            new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
                .OrderBy(_ => __rnd.Next())
                .First();

        foreach (Button b in Controls.OfType<Button>())
        {
            b.Enabled = true;
            b.BackColor = Color.LightGray;
        }
    }
    // file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
    private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void helpToolStrip_click(object sender, EventArgs e)
    {

    }

    private void button_enter(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = turn == Player.Yellow ? Color.Yellow : Color.Red;
        }
    }

    private void button_leave(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = Color.LightGray;
        }
    }

    private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
    {
        yellow_win_count.Text = "0";
        red_win_count.Text = "0";
    }
}
</code>```

It will definitively set winner_found so you should have the same problem as your existing code.

Body:
The code works perfectly until the player uses the 'reset board' function the game decides that the any button click afterwards is a winner and the only way to stop this is to close and re-build the application (using visual studio). This is using a WPF application.

I don't know exactly what is causing the issue, but i have a feeling it has something to do with the checkforwinner method and how it checks that all buttons in a row or column by matching all colours. When the board is reset, it changes the colour of all the buttons to color.lightgray which may interfere with the checkforwinner function.

If it is not too much trouble i would also like to add a 'dropping' mechanic like the real connect four and make a more efficient checkforwinner function so i can expand the board to 12 x 8 or so and not have double or triple the amount of checkforwinner if statements, cheers.

Code is below:

public partial class Form1 : Form
{
    bool turn = true; //if true it is red turn / if false it is yellow turn
    int turn_count = 0; //counts each turn for features such as draw function
    bool winner_found = false; // automatically sets winner found function to false to
    int win_method;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Random rnd = new Random();
        win_method = rnd.Next(1, 4);

        if (win_method == 1)
        {
            winMethod.Text = "Horizontal Wins Only";
        }
        else if (win_method == 2)
        {
            winMethod.Text = "Vertical Wins Only";
        }
        else if (win_method == 3)
        {
            winMethod.Text = "Diagonal Wins Only";
        }
    }

    // function to alternate turns between red and yellow players and count turns for potential draws (see below).
    // Also run checkForWinner function after every move (button click)
    private void button_click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (turn)
            b.BackColor = Color.Yellow;

        else
            b.BackColor = Color.Red;

        turn = !turn;
        b.Enabled = false;
        turn_count++;
        checkForWinner();
    }

    private void checkForWinner()
    {
        if (win_method == 1)

            //check for horizontal wins
            if ((A1.BackColor == A2.BackColor) && (A2.BackColor == A3.BackColor) && (A3.BackColor == A4.BackColor) && (A4.BackColor == A5.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((B1.BackColor == B2.BackColor) && (B2.BackColor == B3.BackColor) && (B3.BackColor == B4.BackColor) && (B4.BackColor == B5.BackColor) && (!B1.Enabled))
                winner_found = true;
            else if ((C1.BackColor == C2.BackColor) && (C2.BackColor == C3.BackColor) && (C3.BackColor == C4.BackColor) && (C4.BackColor == C5.BackColor) && (!C1.Enabled))
                winner_found = true;
            else if ((D1.BackColor == D2.BackColor) && (D2.BackColor == D3.BackColor) && (D3.BackColor == D4.BackColor) && (D4.BackColor == D5.BackColor) && (!D1.Enabled))
                winner_found = true;
            else if ((E1.BackColor == E2.BackColor) && (E2.BackColor == E3.BackColor) && (E3.BackColor == E4.BackColor) && (E4.BackColor == E5.BackColor) && (!E1.Enabled))
                winner_found = true;

        if (win_method == 2)

            //check for vertical wins
            if ((A1.BackColor == B1.BackColor) && (B1.BackColor == C1.BackColor) && (C1.BackColor == D1.BackColor) && (D1.BackColor == E1.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((A2.BackColor == B2.BackColor) && (B2.BackColor == C2.BackColor) && (C2.BackColor == D2.BackColor) && (D2.BackColor == E2.BackColor) && (!A2.Enabled))
                winner_found = true;
            else if ((A3.BackColor == B3.BackColor) && (B3.BackColor == C3.BackColor) && (C3.BackColor == D3.BackColor) && (D3.BackColor == E3.BackColor) && (!A3.Enabled))
                winner_found = true;
            else if ((A4.BackColor == B4.BackColor) && (B4.BackColor == C4.BackColor) && (C4.BackColor == D4.BackColor) && (D4.BackColor == E4.BackColor) && (!A4.Enabled))
                winner_found = true;
            else if ((A5.BackColor == B5.BackColor) && (B5.BackColor == C5.BackColor) && (C5.BackColor == D5.BackColor) && (D5.BackColor == E5.BackColor) && (!A5.Enabled))
                winner_found = true;

        if (win_method == 3)

            //check for diagonal wins
            if ((A1.BackColor == B2.BackColor) && (B2.BackColor == C3.BackColor) && (C3.BackColor == D4.BackColor) && (D4.BackColor == E5.BackColor) && (!A1.Enabled))
                winner_found = true;
            else if ((A5.BackColor == B4.BackColor) && (B4.BackColor == C3.BackColor) && (C3.BackColor == D2.BackColor) && (D2.BackColor == E1.BackColor) && (!A5.Enabled))
                winner_found = true;

        // when winner string is detected to be true than find player who
        //won and give players a message box to show this.
            // also adds one point to the player who wins the round
        if (winner_found)
        {
            disableButtons();

            String winner = "";
            if (turn)
            {
                winner = Color.Red.ToString();
                red_win_count.Text = (Int32.Parse(red_win_count.Text) + 1).ToString();
            }
            else
            {
                winner = Color.Yellow.ToString();
                yellow_win_count.Text = (Int32.Parse(yellow_win_count.Text) + 1).ToString();
            }
        }
        else
        {  // if all squares are filled (25 moves) than signal draw as no more moves can be made
            if (turn_count == 25)
                MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
        }
    }

    // function to disable all buttons for when winner is detected
    private void disableButtons()
    {
        try
        {
            foreach (Control c in Controls)
            {
                Button b = (Button)c;
                b.Enabled = false;
            }
        }
        catch { }
    }

    // help -> how to play: instructions on how to play the game in brief terms
    private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
            "but there is a lot more spaces for you to play you pieces and you have to connect " +
            "five to win! The twist is, that you can only win a certain way, dependent on the " +
            "randomly generated direction on the right hand side of the screen. If the direction is " +
            "vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
            "horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
    }
    // help -> about: quick about menu of the game, creator and copyright year/ symbol
    private void aboutToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void fileToolStripMenuItem_click(object sender, EventArgs e)
    {

    }
    // file -> new game: resets complete game board to have a rematch
    private void newGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        turn = true;
        turn_count = 0;

        Random rnd = new Random();
        win_method = rnd.Next(1, 4);

        if (win_method == 1)
        {
            winMethod.Text = "Horizontal Wins Only";
        }
        else if (win_method == 2)
        {
            winMethod.Text = "Vertical Wins Only";
        }
        else if (win_method == 3)
        {
            winMethod.Text = "Diagonal Wins Only";
        }

        foreach (Control c in Controls)
        {
            try
            {
                Button b = (Button)c;
                b.Enabled = true;
                b.BackColor = Color.LightGray;
            }
            catch { }
        }
    }
    // file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
    private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void helpToolStrip_click(object sender, EventArgs e)
    {

    }

    private void button_enter(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            if (turn)
                b.BackColor = Color.Yellow;
            else
                b.BackColor = Color.Red;
        }
    }

    private void button_leave(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = Color.LightGray;
        }
    }

    private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
    {
        yellow_win_count.Text = "0";
        red_win_count.Text = "0";
    }
}

Body:
Have a play with this code:

public enum WinMethod
{
    Horizontal,
    Vertical,
    Diagonal,
}
public enum Player
{
    Yellow,
    Red,
}

public partial class Form1 : Form
{
    Player turn = Player.Red;
    int turn_count = 0; //counts each turn for features such as draw function
    bool winner_found = false; // automatically sets winner found function to false to
    private WinMethod win_method;

    private Dictionary<Player, int> _winnerCount = new Dictionary<Player, int>()
    {
        { Player.Yellow, 0 },
        { Player.Red, 0 },
    };

    public Form1()
    {
        InitializeComponent();
    }

    private static Random __rnd = new Random();

    private void Form1_Load(object sender, EventArgs e)
    {
        win_method =
            new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
                .OrderBy(_ => __rnd.Next())
                .First();
    }

    // function to alternate turns between red and yellow players and count turns for potential draws (see below).
    // Also run checkForWinner function after every move (button click)
    private void button_click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        b.BackColor = turn == Player.Red ? Color.Red : Color.Yellow;
        turn = turn == Player.Red ? Player.Yellow : Player.Red;
        b.Enabled = false;
        turn_count++;
        checkForWinner();
    }

    private void checkForWinner()
    {
        var grid = new[]
        {
            new { line = new [] { A1, A2, A3, A4, A5 }, method = WinMethod.Horizontal },
            new { line = new [] { B1, B2, B3, B4, B5 }, method = WinMethod.Horizontal },
            new { line = new [] { C1, C2, C3, C4, C5 }, method = WinMethod.Horizontal },
            new { line = new [] { D1, D2, D3, D4, D5 }, method = WinMethod.Horizontal },
            new { line = new [] { E1, E2, E3, E4, E5 }, method = WinMethod.Horizontal },
            new { line = new [] { A1, B1, C1, D1, E1 }, method = WinMethod.Vertical },
            new { line = new [] { A2, B2, C2, D2, E2 }, method = WinMethod.Vertical },
            new { line = new [] { A3, B3, C3, D3, E3 }, method = WinMethod.Vertical },
            new { line = new [] { A4, B4, C4, D4, E4 }, method = WinMethod.Vertical },
            new { line = new [] { A5, B5, C5, D5, E5 }, method = WinMethod.Vertical },
            new { line = new [] { A1, B2, C3, D4, E5 }, method = WinMethod.Diagonal },
            new { line = new [] { E1, D2, C3, B4, A5 }, method = WinMethod.Diagonal },
        };

        winner_found =
            grid.Any(g => g.method == win_method && g.line.Select(x => x.BackColor).Distinct().Count() == 1);

        if (winner_found)
        {
            disableButtons();

            _winnerCount[turn] += 1;
            (turn == Player.Red ? red_win_count : yellow_win_count).Text = _winnerCount[turn].ToString();
        }
        else
        {  // if all squares are filled (25 moves) than signal draw as no more moves can be made
            if (turn_count == 25)
                MessageBox.Show("Draw! Wanna rematch?", "Rematch!");
        }
    }

    // function to disable all buttons for when winner is detected
    private void disableButtons()
    {
        foreach (Button b in Controls.OfType<Button>())
        {
            b.Enabled = false;
        }
    }

    // help -> how to play: instructions on how to play the game in brief terms
    private void howToPlayToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Connect Five is quite similar to the good old-fashioned Connect Four, " +
            "but there is a lot more spaces for you to play you pieces and you have to connect " +
            "five to win! The twist is, that you can only win a certain way, dependent on the " +
            "randomly generated direction on the right hand side of the screen. If the direction is " +
            "vertical, then you can only win with 5 coloured squares in a vertical line. Same with " +
            "horizontal and diagonal directions! Have Fun!", "Connect Five: How To Play");
    }
    // help -> about: quick about menu of the game, creator and copyright year/ symbol
    private void aboutToolStripMenuItem_click(object sender, EventArgs e)
    {
        MessageBox.Show("Made by Brendan Ellis © 2019", "Connect Five About");
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void fileToolStripMenuItem_click(object sender, EventArgs e)
    {

    }
    // file -> new game: resets complete game board to have a rematch
    private void newGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        turn = Player.Red;
        turn_count = 0;

        win_method =
            new[] { WinMethod.Horizontal, WinMethod.Vertical, WinMethod.Diagonal }
                .OrderBy(_ => __rnd.Next())
                .First();

        foreach (Button b in Controls.OfType<Button>())
        {
            b.Enabled = true;
            b.BackColor = Color.LightGray;
        }
    }
    // file -> exit game: just exits the game because clicking the cross is obviously sooooo last year
    private void exitGameToolStripMenuItem_click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    // visual studio has a hissy fit if i dont put this in because it recognises this as a menu strip.
    // This and the button_click function clash and i haven't been able to find a fix.
    private void helpToolStrip_click(object sender, EventArgs e)
    {

    }

    private void button_enter(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = turn == Player.Yellow ? Color.Yellow : Color.Red;
        }
    }

    private void button_leave(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        if (b.Enabled)
        {
            b.BackColor = Color.LightGray;
        }
    }

    private void resetWinCountersToolStripMenuItem_Click(object sender, EventArgs e)
    {
        yellow_win_count.Text = "0";
        red_win_count.Text = "0";
    }
}

It will definitively set winner_found so you should have the same problem as your existing code.


问:
R loop doesn't work while single command works
I am trying to covert many time series xts objects to tibbles, and the for loop I wrote does not work properly, I don't know why.

This does not only happen to this particular task, but other task I perform, I have a list called "code", which contains a list of names for all the xts objects I want to convert from.

code <- c('ABT','BA','CL','ROK')

for (i in code)
  {
  i <- tk_tbl(i, preserve_index = TRUE, rename_index = "index",
       timetk_idx = FALSE, silent = FALSE)
}
```

<p>What is strange is that, if I use a single one without loop, it works beautifully and convert the xts "ABT" to a tibble "ABT"</p>

<pre class="lang-r prettyprint-override"><code>ABT <- tk_tbl(ABT, preserve_index = TRUE, rename_index = "index",
       timetk_idx = FALSE, silent = FALSE)
</code>```

The error message for the first code is

Warning: No index to preserve. Object otherwise converted to tibble
  successfully.

38: In tk_tbl.data.frame(as.data.frame(data), preserve_index,  ... :

Edit:

tk_tabl is a function from the package timetk, and it "Coerce time-series objects to tibble."

And code is a vector containing names.

```<code>library(timetk)
code <- c('ABT','BA','CL','ROK')

> dput(head(ROK))
structure(c(8.14062, 8.15625, 8.03125, 7.78125, 7.6875, 7.71875,
8.25, 8.15625, 8.125, 7.90625, 7.71875, 7.75, 8.03125, 8.125,
7.90625, 7.65625, 7.625, 7.65625, 8.1875, 8.125, 7.90625, 7.71875,
7.65625, 7.6875, 109600, 80800, 138400, 151600, 96800, 258800,
0.684505, 0.67928, 0.660992, 0.645316, 0.640091, 0.642704),
class=c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC", src = "yahoo",
updated = structure(1558826745.23035, class = c("POSIXct","POSIXt")),
index = structure(c(378604800, 378950400, 379036800,
379123200, 379209600, 379296000), tzone = "UTC", tclass = "Date"),
.Dim = c(6L, 6L), .Dimnames = list(NULL, c("ROK.Open", "ROK.High",
"ROK.Low", "ROK.Close", "ROK.Volume", "ROK.Adjusted")))
</code>```

答:
For me it looks like that you expect <- to do what assign is doing.

I think you get your expected result when you change your loop to:

```<code>for (i in code) {
  assign(i, tk_tbl(i, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE))
}
</code>```

Body:
I am trying to covert many time series xts objects to tibbles, and the for loop I wrote does not work properly, I don't know why.

This does not only happen to this particular task, but other task I perform, I have a list called "code", which contains a list of names for all the xts objects I want to convert from.

code <- c('ABT','BA','CL','ROK')

for (i in code)
  {
  i <- tk_tbl(i, preserve_index = TRUE, rename_index = "index",
       timetk_idx = FALSE, silent = FALSE)
}

What is strange is that, if I use a single one without loop, it works beautifully and convert the xts "ABT" to a tibble "ABT"

ABT <- tk_tbl(ABT, preserve_index = TRUE, rename_index = "index",
       timetk_idx = FALSE, silent = FALSE)

The error message for the first code is

Warning: No index to preserve. Object otherwise converted to tibble
  successfully.

38: In tk_tbl.data.frame(as.data.frame(data), preserve_index,  ... :

Edit:

tk_tabl is a function from the package timetk, and it "Coerce time-series objects to tibble."

And code is a vector containing names.

library(timetk)
code <- c('ABT','BA','CL','ROK')

> dput(head(ROK))
structure(c(8.14062, 8.15625, 8.03125, 7.78125, 7.6875, 7.71875,
8.25, 8.15625, 8.125, 7.90625, 7.71875, 7.75, 8.03125, 8.125,
7.90625, 7.65625, 7.625, 7.65625, 8.1875, 8.125, 7.90625, 7.71875,
7.65625, 7.6875, 109600, 80800, 138400, 151600, 96800, 258800,
0.684505, 0.67928, 0.660992, 0.645316, 0.640091, 0.642704),
class=c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC", src = "yahoo",
updated = structure(1558826745.23035, class = c("POSIXct","POSIXt")),
index = structure(c(378604800, 378950400, 379036800,
379123200, 379209600, 379296000), tzone = "UTC", tclass = "Date"),
.Dim = c(6L, 6L), .Dimnames = list(NULL, c("ROK.Open", "ROK.High",
"ROK.Low", "ROK.Close", "ROK.Volume", "ROK.Adjusted")))

Body:
For me it looks like that you expect <- to do what assign is doing.

I think you get your expected result when you change your loop to:

for (i in code) {
  assign(i, tk_tbl(i, preserve_index = TRUE, rename_index = "index", timetk_idx = FALSE, silent = FALSE))
}


问:
Oracle SQL Developer Database Copy Error
I am trying to utilise the database copy in Oracle SQL Developer, specifically the Objects Copy to copy data from a table in one database to the same table in another database.
I am trying to copy data from one table on a database, to the exact same format table on another database. See below for log output.

When doing this I come up with the following error:

```<code>Copy Option: Objects
Copy Source Connection: DATABASEA
Destination Connection: DATABASEB
DDL Objects: Views Tables Materialized Views
Data Objects: Tables Table X
Object Where: PROCESS_DATE = '2017-12-31'
Copy DDL: No
Copy Data: Yes
Append Existing Objects
--- START
--------------------------------------------------------------------
Skipping Table X
--- END --------------------------------------------------------------------–
</code>```

I am following the steps outlined here: http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/sqldev/r31/DatabaseCopy/DatabaseCopy.html

I was able to perform a data copy before I got a new laptop, using the exact same software.

I would be grateful for any advice on how to fix this issue.

答:
In my case, the root cause of this issue was a previous attempt to copy this table which failed and SQL Developer failed to roll back the changed - even though I selected the "Cancel and rollback" option. As a result, the table was deleted and the second attempt to copy the table data without DDL was simply skipped - without any error message or explanation. IMHO, the database or SQL Developer should rather output an error message.

Eventually, I was able to resolve the issue by copying the DDL, too.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to utilise the database copy in Oracle SQL Developer, specifically the Objects Copy to copy data from a table in one database to the same table in another database.
I am trying to copy data from one table on a database, to the exact same format table on another database. See below for log output.

When doing this I come up with the following error:

Copy Option: Objects
Copy Source Connection: DATABASEA
Destination Connection: DATABASEB
DDL Objects: Views Tables Materialized Views
Data Objects: Tables Table X
Object Where: PROCESS_DATE = '2017-12-31'
Copy DDL: No
Copy Data: Yes
Append Existing Objects
--- START
--------------------------------------------------------------------
Skipping Table X
--- END --------------------------------------------------------------------–

I am following the steps outlined here: http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/sqldev/r31/DatabaseCopy/DatabaseCopy.html

I was able to perform a data copy before I got a new laptop, using the exact same software.

I would be grateful for any advice on how to fix this issue.


问:
Can't connect to Hive server with spark JDBC in kerberised cluster
I try to read data from one Hive (hive n°1) and write result into another Hive (hive n°2) ( they are from 2 different cluster ). I can't use a single spark session to connect to both Hive, so i will use jdbc to read data and the spark hive context to write data.

Both cluster use kerberos, knox, ranger.

ths batch spark will run on hive n°2

this is my main error :

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)

What i have already tried :

I can connect to hive server using beeline commande, with zookeeper discovery mode and also in direct http.

```<code>beeline -u "jdbc:hive2://<hiveServer2Host>:<Port>/<db>;transportMode=http;httpPath=cliservice;ssl=true;sslTrustStore=truststore.jks;trustStorePassword=<psw>;principal=<hive server 2 principal>;"
</code>```

my code :

```<code>String url = "jdbc:hive2://<hiveServer2Host>:<Port>/<db>;transportMode=http;httpPath=cliservice;ssl=true;sslTrustStore=truststore.jks;trustStorePassword=<psw>;principal=<hive server 2 principal>";
String table = "test";
Properties connectionProperties = new Properties();
Dataset<Row> testDS= spark.read().jdbc(url, table, connectionProperties);
testDS.show();
</code>```

i try to add some manual keberos connection before JDBC :

```<code>org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
conf.set("hadoop.security.authentication", "kerberos");
conf.set("hadoop.rpc.protection", "privacy");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(args[0], args[1]);
System.out.println("login with: " + UserGroupInformation.getLoginUser());
System.out.println("Current User:" + UserGroupInformation.getCurrentUser());
</code>```

i am well identified ( in spark log ) :

login with: A@XXX.LOCAL (auth:KERBEROS)

Current User: A (auth:SIMPLE)

i also do a kinit before spark submit :

```<code>kinit -kt <A_keytabs> <A principal>
</code>```

klist is fine

i try to add --keytab and -- principal in spark-submit but that change nothing.

only the connection to JDBC get problem, otherwhise i am well identified to acces HDFS ressources, kafka topic ...

i also try to connect to JDBC with zookeeper discovery in java mode but that dont work too.

java.sql.SQLException: Could not open client transport for any of the Server URI's in ZooKeeper: Unable to read HiveServer2 configs from ZooKeeper

i use HDP 2.6.4 , Java 8 , Spark 2.2.1

UPDATED :
after Samson reply :

I add jass and KBR property to system :

```<code>System.setProperty("java.security.auth.login.config", spark_jaas.conf);
System.setProperty("sun.security.jgss.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
System.setProperty("java.security.krb5.realm", <realm from krb5.conf>);
System.setProperty("java.security.krb5.kdc", <kdc from krb5.conf>);
</code>```

my app dont crash but I get this error.

GSSException: No valid credentials provided (Mechanism level: Attempt to obtain new INITIATE credentials failed! (null))

Search Subject for Kerberos V5 INIT cred (<>, sun.security.jgss.krb5.Krb5InitCredential)

答:
Try using this.
I am assuming you are passing principal and the keytab in spark submit

```<code>val principal: String = sparkSession.sparkContext.getConf.get("spark.yarn.principal")
val keytab: String = sparkSession.sparkContext.getConf.get("spark.yarn.keytab")
UserGroupInformation.loginUserFromKeytab(principal, keytab);
</code>```

Let me know if it works.

Body:
I try to read data from one Hive (hive n°1) and write result into another Hive (hive n°2) ( they are from 2 different cluster ). I can't use a single spark session to connect to both Hive, so i will use jdbc to read data and the spark hive context to write data.

Both cluster use kerberos, knox, ranger.

ths batch spark will run on hive n°2

this is my main error :

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)

What i have already tried :

I can connect to hive server using beeline commande, with zookeeper discovery mode and also in direct http.

beeline -u "jdbc:hive2://<hiveServer2Host>:<Port>/<db>;transportMode=http;httpPath=cliservice;ssl=true;sslTrustStore=truststore.jks;trustStorePassword=<psw>;principal=<hive server 2 principal>;"

my code :

String url = "jdbc:hive2://<hiveServer2Host>:<Port>/<db>;transportMode=http;httpPath=cliservice;ssl=true;sslTrustStore=truststore.jks;trustStorePassword=<psw>;principal=<hive server 2 principal>";
String table = "test";
Properties connectionProperties = new Properties();
Dataset<Row> testDS= spark.read().jdbc(url, table, connectionProperties);
testDS.show();

i try to add some manual keberos connection before JDBC :

org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
conf.set("hadoop.security.authentication", "kerberos");
conf.set("hadoop.rpc.protection", "privacy");
UserGroupInformation.setConfiguration(conf);
UserGroupInformation.loginUserFromKeytab(args[0], args[1]);
System.out.println("login with: " + UserGroupInformation.getLoginUser());
System.out.println("Current User:" + UserGroupInformation.getCurrentUser());

i am well identified ( in spark log ) :

login with: A@XXX.LOCAL (auth:KERBEROS)

Current User: A (auth:SIMPLE)

i also do a kinit before spark submit :

kinit -kt <A_keytabs>

klist is fine

i try to add --keytab and -- principal in spark-submit but that change nothing.

only the connection to JDBC get problem, otherwhise i am well identified to acces HDFS ressources, kafka topic ...

i also try to connect to JDBC with zookeeper discovery in java mode but that dont work too.

java.sql.SQLException: Could not open client transport for any of the Server URI's in ZooKeeper: Unable to read HiveServer2 configs from ZooKeeper

i use HDP 2.6.4 , Java 8 , Spark 2.2.1

UPDATED :
after Samson reply :

I add jass and KBR property to system :

System.setProperty("java.security.auth.login.config", spark_jaas.conf);
System.setProperty("sun.security.jgss.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
System.setProperty("java.security.krb5.realm", <realm from krb5.conf>);
System.setProperty("java.security.krb5.kdc", <kdc from krb5.conf>);

my app dont crash but I get this error.

GSSException: No valid credentials provided (Mechanism level: Attempt to obtain new INITIATE credentials failed! (null))

Search Subject for Kerberos V5 INIT cred (<>, sun.security.jgss.krb5.Krb5InitCredential)

Body:
Try using this.
I am assuming you are passing principal and the keytab in spark submit

val principal: String = sparkSession.sparkContext.getConf.get("spark.yarn.principal")
val keytab: String = sparkSession.sparkContext.getConf.get("spark.yarn.keytab")
UserGroupInformation.loginUserFromKeytab(principal, keytab);

Let me know if it works.


问:
How to pass raw complex object to MVC action?
Problem: Can't parse File object to JSON string, when doing that only null values are gotten, while trying to send complex type to MVC controller.

I tried adding it into FormData object and passing it to controller, however, passing List of them was not successful, because it would either return an empty array or just plain null

model:

public class UploadedDocument
    {

        public HttpPostedFile File { get; set;}
        public string DocumentId { get; set;}
        public string DocumentType { get; set; }

    }
```

<p>controller:</p>

<pre class="lang-cs prettyprint-override"><code>        [HttpPost]
        [ActionName("UploadFile")]
        public ActionResult Upload(IEnumerable<UploadedDocument> documents)
        {
            return View();
        }
</code>```

upload function:

```<code>var _documents = [];

                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: {"documents":_documents}
                    });
            }
        });
</code>```

答:
Try this.
   var _documents = [];</p>

```<code>                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

var formData = new FormData();
formData.append("documents", documents);

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                });
            }
        });
</code>```

Body:
Problem: Can't parse File object to JSON string, when doing that only null values are gotten, while trying to send complex type to MVC controller.

I tried adding it into FormData object and passing it to controller, however, passing List of them was not successful, because it would either return an empty array or just plain null

model:

public class UploadedDocument
    {

        public HttpPostedFile File { get; set;}
        public string DocumentId { get; set;}
        public string DocumentType { get; set; }

    }

controller:

        [HttpPost]
        [ActionName("UploadFile")]
        public ActionResult Upload(IEnumerable<UploadedDocument> documents)
        {
            return View();
        }

upload function:

var _documents = [];

                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: {"documents":_documents}
                    });
            }
        });

Body:
Try this.
   var _documents = [];

                for (var i = 0; i < arrayOfFiles.length; i++) {

                    var document = {
                        "File": arrayOfFiles[i].file,
                        "DocumentId": arrayOfFiles[i].documentId,
                        "DocumentType": arrayOfFiles[i].documentName
                    };

                    _documents.push(document);
                }

var formData = new FormData();
formData.append("documents", documents);

                $.ajax({
                    url: "@Url.Action("UploadFile", "Home")",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                });
            }
        });


问:
How to fix in <module> Error for my neural network?
I get the following error File "C:/Users/xx/Desktop/xxx/ost.py", line 213, in
    main(), while trying to initiate training of neural network

This is for a final lab assignment about pictures classification

if __name__ == '__main__':
     main()
```

<p>and the main function is</p>

```def main():
    with open('train.pkl', 'rb') as f:
        data = pickle.load(f)

    x = data[0]
    y = data[1]

    # x=feature_extraction_hog(x)

    D = x.shape[1]

    hidden_size = 55
    output_size = 36

    w1 = np.random.uniform(low=-0.1, high=0.1, size=(hidden_size, (D + 1)))
    w2 = np.random.uniform(low=-0.1, high=0.1, size=(output_size, (hidden_size + 1)))

    w1, w2 = fit(x, y, True, output_size, hidden_size, w1, w2, 0.2, 0.2)

    np.savetxt('weights1.txt', w1)
    np.savetxt('weights2.txt', w2)

    y_train_pred = predict(x, w1, w2)

    print(classification_error(y_train_pred, y))

```

答: I managed to fix it, the problem was with a line that received too many indexes! Thanks anyways</p>

Body:
I get the following error File "C:/Users/xx/Desktop/xxx/ost.py", line 213, in
    main(), while trying to initiate training of neural network

This is for a final lab assignment about pictures classification

if __name__ == '__main__':
     main()

and the main function is

def main():
    with open('train.pkl', 'rb') as f:
        data = pickle.load(f)

    x = data[0]
    y = data[1]

    # x=feature_extraction_hog(x)

    D = x.shape[1]

    hidden_size = 55
    output_size = 36

    w1 = np.random.uniform(low=-0.1, high=0.1, size=(hidden_size, (D + 1)))
    w2 = np.random.uniform(low=-0.1, high=0.1, size=(output_size, (hidden_size + 1)))

    w1, w2 = fit(x, y, True, output_size, hidden_size, w1, w2, 0.2, 0.2)

    np.savetxt('weights1.txt', w1)
    np.savetxt('weights2.txt', w2)

    y_train_pred = predict(x, w1, w2)

    print(classification_error(y_train_pred, y))


问:
React synthetic events not working in Web Component
I followed React's documentation on how to use React inside of a Web Component (https://reactjs.org/docs/web-components.html) but found that the synthetic event system just does not work for the React tree inside of that React component.

Here is a JS Fiddle where you can try:

A React component embedded naturally without Web Components

The same React component embedded inside of a Web Component (events won't fire)

Another React component that attaches event listeners manually, inside a Web Component

```<code>class CounterWithSyntheticEvents extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        };
    }

    handleClick() {
        this.setState(prevState => ({ counter: prevState.counter + 1 }));
    }

    render() {
        return (
            <div>
                Count {this.state.counter} <button onClick={this.handleClick.bind(this)}>+</button>
            </div>
        );
    }
}
class CounterWithDOMEvents extends React.Component {
    constructor(props) {
        super(props);
        this.buttonRef = React.createRef();
        this.state = {
            counter: 0,
        };
    }

    componentDidMount() {
        const listenerFn = this.handleClick.bind(this);
        this.buttonRef.current.addEventListener("click", listenerFn);
      this.removeListener = () => this.buttonRef.current.removeEventListener('click', listenerFn);
    }

    componentWillUnmount() {
        this.removeListener();
    }

    handleClick() {
        this.setState(prevState => ({ counter: prevState.counter + 1 }));
    }

    render() {
        return (
            <div>
                Count {this.state.counter} <button ref={this.buttonRef}>+</button>
            </div>
        );
    }
}

ReactDOM.render(<CounterWithSyntheticEvents />, document.getElementById("container"));

class ReactSyntheticEvents extends HTMLElement {
    connectedCallback() {
        const mountPoint = document.createElement("div");

        const shadow = this.attachShadow({ mode: "open" });
        shadow.appendChild(mountPoint);
        ReactDOM.render(<CounterWithSyntheticEvents />, mountPoint);
    }
}
customElements.define("react-synthetic-events", ReactSyntheticEvents);

class ReactDOMEvents extends HTMLElement {
    connectedCallback() {
        const mountPoint = document.createElement("div");

        const shadow = this.attachShadow({ mode: "open" });
        shadow.appendChild(mountPoint);
        ReactDOM.render(<CounterWithDOMEvents />, mountPoint);
    }
}

customElements.define("react-dom-events", ReactDOMEvents);
</code>```

<react-synthetic-events ></react-synthetic-events>
<react-dom-events ></react-dom-events>
```

The approach with the manual listeners binding works, but I want to avoid rewriting every single react component that is to be integrated.

Does anyone know about a quick fix I could do in order to have events propagated to the components ? (to make the 2nd case of the fiddle work)

I have heard of Polymer-react but haven't given it a try yet. And I'd like to not introduce another layer if possible.

答:
I spent some time trying to find a fix or a workaround, and here is the result:

The bug is identified and a solution has been agreed upon: React should allow several listener roots, that should be the "containers" instead of the document only: https://github.com/facebook/react/issues/2043. There have been at least more than one attempt to fix this, but it seems like there has been no fix in the end, after more than two years : https://github.com/facebook/react/issues/2043#issuecomment-346039823. It looks like this won't be fixed unless we contribute, or Facebook starts looking into Web Components !

Some activity on StackOverflow (Click event not firing when React Component in a Shadow DOM) has led to the implementation of a workaround (https://www.npmjs.com/package/react-shadow-dom-retarget-events). The technical implementation can be summarized as a trial to replicate React's event handling system at the Web Component shadow-root-level, except that it is really simplified. When I tried it on a kind of form use-case, it worked for some UI components (checkbox, textfield), but not on some others (toggle). For the toggle (from Material UI), I was getting two events instead of one. In any-case, I find that trying to replicate React's even system with a couple lines of code is not a robust workaround.

Finally, I found a couple of libraries that claim to make the use of React easier with Web Components, but they are actually dealing with the "surface" of the Web Component instead of the inside of it, and therefore do not fix the issue. I tried https://github.com/skatejs/val and https://www.npmjs.com/package/web-react-components. I found the latter to be the most interesting (simple and to the point).

In the end, as a conclusion, we decided to use Web Components without the Shadow-DOM feature.

Body:
I followed React's documentation on how to use React inside of a Web Component (https://reactjs.org/docs/web-components.html) but found that the synthetic event system just does not work for the React tree inside of that React component.

Here is a JS Fiddle where you can try:

A React component embedded naturally without Web Components

The same React component embedded inside of a Web Component (events won't fire)

Another React component that attaches event listeners manually, inside a Web Component

class CounterWithSyntheticEvents extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            counter: 0,
        };
    }

    handleClick() {
        this.setState(prevState => ({ counter: prevState.counter + 1 }));
    }

    render() {
        return (

                Count {this.state.counter} <button onClick={this.handleClick.bind(this)}>+</button>

        );
    }
}
class CounterWithDOMEvents extends React.Component {
    constructor(props) {
        super(props);
        this.buttonRef = React.createRef();
        this.state = {
            counter: 0,
        };
    }

    componentDidMount() {
        const listenerFn = this.handleClick.bind(this);
        this.buttonRef.current.addEventListener("click", listenerFn);
      this.removeListener = () => this.buttonRef.current.removeEventListener('click', listenerFn);
    }

    componentWillUnmount() {
        this.removeListener();
    }

    handleClick() {
        this.setState(prevState => ({ counter: prevState.counter + 1 }));
    }

    render() {
        return (

                Count {this.state.counter} <button ref={this.buttonRef}>+</button>

        );
    }
}

ReactDOM.render(<CounterWithSyntheticEvents />, document.getElementById("container"));

class ReactSyntheticEvents extends HTMLElement {
    connectedCallback() {
        const mountPoint = document.createElement("div");

        const shadow = this.attachShadow({ mode: "open" });
        shadow.appendChild(mountPoint);
        ReactDOM.render(<CounterWithSyntheticEvents />, mountPoint);
    }
}
customElements.define("react-synthetic-events", ReactSyntheticEvents);

class ReactDOMEvents extends HTMLElement {
    connectedCallback() {
        const mountPoint = document.createElement("div");

        const shadow = this.attachShadow({ mode: "open" });
        shadow.appendChild(mountPoint);
        ReactDOM.render(<CounterWithDOMEvents />, mountPoint);
    }
}

customElements.define("react-dom-events", ReactDOMEvents);

<react-synthetic-events ></react-synthetic-events>
<react-dom-events ></react-dom-events>

The approach with the manual listeners binding works, but I want to avoid rewriting every single react component that is to be integrated.

Does anyone know about a quick fix I could do in order to have events propagated to the components ? (to make the 2nd case of the fiddle work)

I have heard of Polymer-react but haven't given it a try yet. And I'd like to not introduce another layer if possible.


问:
Awaiting some results before dispatching an event with flutter_bloc library
I am trying to create a BLOC which depends on two other time based bloc and a non-time based bloc. What i mean with time based is, for example they are connecting a remote server so it takes time. It's working just like this:

Login (It's of course taking some time)

If login is successful

Do another process (This is something takes time also. It returns a future.)

After login and another process finishes, let the page know it.

My BLOC depends on these three:

```<code>final UserBloc _userBloc;
final AnotherBloc _anotherBloc;
final FinishBloc _finishBloc;
</code>```

Inside the map event to state method I should dispatch relevant events. However i cannot await if they are finished.

```<code>_userBloc.dispatch(
  Login(),
);

_anotherBloc.dispatch(
  AnotherProcess(),
);

//LetThePageKnowIt should work after login and another process
_finishBloc.dispatch(
  LetThePageKnowIt(),
);
</code>```

Is there a clean way to await some others before dispatching something?

Right know I use a way that i don't like. In the main bloc's state which i connect other blocs in it, I have bools.

```<code>class CombinerState {
  bool isLoginFinished = false;
  bool isAnotherProcessFinished = false;
</code>```

I am listening the time dependent blocs' states in constructor of main bloc. When they yield "i am finished" I just mark the bools "true".

```<code>MainBloc(
  this._userBloc,
  this._anotherBloc,
  this._pageBloc,
); {
  _userBloc.state.listen(
    (state) {
      if (state.status == Status.finished) {
        dispatch(FinishLogin());
      }
    },
  );

  _anotherBloc.state.listen(
    (state) {
      if (state.status == AnotherStatus.finished) {
        dispatch(FinishAnotherProcess());
      }
    },
  );
}
</code>```

and I dispatch another event for main bloc to check if all the bools are true after setting a bool to true.

```<code>else if (event is FinishAnotherProcess) {
  newState.isAnotherProcessFinished = true;

  yield newState;

  dispatch(CheckIfReady());
}
</code>```

If the bools are true, i dispatch LetThePageKnowIt()

```<code>else if (event is CheckIfReady) {
  if (currentState.isAnotherProcessFinished == true &&
      currentState.isLoginFinished == true) {
    _pageBloc.dispatch(LetThePageKnowIt());
  }
}
</code>```

I am not satisfied with this code. I am looking a way to await other BLOCs send a state with "finished". After that I want to dispatch my LetThePageKnowIt()

答:
@pskink 's suggestion solved my problem.

I have created two methods which return a future. Inside of them, I just await for my streams. Here is the example of login stream.

In map event to state, after the dispatches, I await an async method.

```<code>_userBloc.dispatch(
  Login(),
);

_anotherBloc.dispatch(
  AnotherProcess(),
);

await loginProcess();
await otherProcess();

_finishBloc.dispatch(
  LetThePageKnowIt(),
);
</code>```

Inside the method I just await for userbloc to finish its job and yields about it. Then return.

```<code>Future loginProcess() async {
  await for (var result in _userBloc.state) {
    if (result.status == Status.finished) {
      return;
    }
  }
}
</code>```

Body:
I am trying to create a BLOC which depends on two other time based bloc and a non-time based bloc. What i mean with time based is, for example they are connecting a remote server so it takes time. It's working just like this:

Login (It's of course taking some time)

If login is successful

Do another process (This is something takes time also. It returns a future.)

After login and another process finishes, let the page know it.

My BLOC depends on these three:

final UserBloc _userBloc;
final AnotherBloc _anotherBloc;
final FinishBloc _finishBloc;

Inside the map event to state method I should dispatch relevant events. However i cannot await if they are finished.

_userBloc.dispatch(
  Login(),
);

_anotherBloc.dispatch(
  AnotherProcess(),
);

//LetThePageKnowIt should work after login and another process
_finishBloc.dispatch(
  LetThePageKnowIt(),
);

Is there a clean way to await some others before dispatching something?

Right know I use a way that i don't like. In the main bloc's state which i connect other blocs in it, I have bools.

class CombinerState {
  bool isLoginFinished = false;
  bool isAnotherProcessFinished = false;

I am listening the time dependent blocs' states in constructor of main bloc. When they yield "i am finished" I just mark the bools "true".

MainBloc(
  this._userBloc,
  this._anotherBloc,
  this._pageBloc,
); {
  _userBloc.state.listen(
    (state) {
      if (state.status == Status.finished) {
        dispatch(FinishLogin());
      }
    },
  );

  _anotherBloc.state.listen(
    (state) {
      if (state.status == AnotherStatus.finished) {
        dispatch(FinishAnotherProcess());
      }
    },
  );
}

and I dispatch another event for main bloc to check if all the bools are true after setting a bool to true.

else if (event is FinishAnotherProcess) {
  newState.isAnotherProcessFinished = true;

  yield newState;

  dispatch(CheckIfReady());
}

If the bools are true, i dispatch LetThePageKnowIt()

else if (event is CheckIfReady) {
  if (currentState.isAnotherProcessFinished == true &&
      currentState.isLoginFinished == true) {
    _pageBloc.dispatch(LetThePageKnowIt());
  }
}

I am not satisfied with this code. I am looking a way to await other BLOCs send a state with "finished". After that I want to dispatch my LetThePageKnowIt()

Body:
@pskink 's suggestion solved my problem.

I have created two methods which return a future. Inside of them, I just await for my streams. Here is the example of login stream.

In map event to state, after the dispatches, I await an async method.

_userBloc.dispatch(
  Login(),
);

_anotherBloc.dispatch(
  AnotherProcess(),
);

await loginProcess();
await otherProcess();

_finishBloc.dispatch(
  LetThePageKnowIt(),
);

Inside the method I just await for userbloc to finish its job and yields about it. Then return.

Future loginProcess() async {
  await for (var result in _userBloc.state) {
    if (result.status == Status.finished) {
      return;
    }
  }
}


问:
Changing Button Color using Listbox
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.</p>

```<code><StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>
</code>```

答:
Here is my solution using a Converter. The converter will take receive the string value and then return a colour, see below.

```<code>public class StringToColorConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var listItem = value as ListBoxItem;
        if (listItem != null)
        {
            var text = listItem.Content;
            switch (text)
            {
                case "Green":
                    return new SolidColorBrush(Colors.Green);
                case "Yellow":
                    return new SolidColorBrush(Colors.Yellow);
                case "Red":
                    return new SolidColorBrush(Colors.Red);
            }
        }
        return new SolidColorBrush(Colors.Transparent);
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

You made a mistake in your xaml because you cannot directly change the background of a togglebutton. Below is how to use the converter with your actual code. Please note it will only change the background of the textblock. to make the button look better Please see here

```<code><StackPanel>
    <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
        <Border Background="LightYellow">
            <ListBox x:Name="ColorPicker">
                <ListBoxItem>Green</ListBoxItem>
                <ListBoxItem>Yellow</ListBoxItem>
                <ListBoxItem>Red</ListBoxItem>
            </ListBox>
        </Border>
    </Popup>
    <ToggleButton Name="button"
                  Height="50"
                  >
        <TextBlock Text="Change!" Background="{Binding Source={x:Reference ColorPicker}, Path=SelectedValue, Converter={StaticResource StringToColorConverter}}"/>
    </ToggleButton>
</StackPanel>
</code>```

Title: Changing Button Color using Listbox

Body:
I need to change background color of Button using ListBox. I have 3 ListBoxItems for 3 colors ( green, yellow and red). I am not sure how to do this. Any help will be greatly appreciated.

<StackPanel Grid.Column="1" Grid.Row="3">
  <ToggleButton Height="50" Content="Change!" Name="button">
   </ToggleButton>
    <Popup  IsOpen="{Binding IsChecked, ElementName=button}"   StaysOpen="False">
     <Border Background="LightYellow">
       <ListBox>
        <ListBoxItem>Green</ListBoxItem>
         <ListBoxItem>Yellow</ListBoxItem>
        <ListBoxItem>Red</ListBoxItem>
      </ListBox>
    </Border>
  </Popup>
</StackPanel>

Body:
Here is my solution using a Converter. The converter will take receive the string value and then return a colour, see below.

public class StringToColorConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var listItem = value as ListBoxItem;
        if (listItem != null)
        {
            var text = listItem.Content;
            switch (text)
            {
                case "Green":
                    return new SolidColorBrush(Colors.Green);
                case "Yellow":
                    return new SolidColorBrush(Colors.Yellow);
                case "Red":
                    return new SolidColorBrush(Colors.Red);
            }
        }
        return new SolidColorBrush(Colors.Transparent);
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

You made a mistake in your xaml because you cannot directly change the background of a togglebutton. Below is how to use the converter with your actual code. Please note it will only change the background of the textblock. to make the button look better Please see here

<StackPanel>
    <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
        <Border Background="LightYellow">
            <ListBox x:Name="ColorPicker">
                <ListBoxItem>Green</ListBoxItem>
                <ListBoxItem>Yellow</ListBoxItem>
                <ListBoxItem>Red</ListBoxItem>
            </ListBox>
        </Border>
    </Popup>
    <ToggleButton Name="button"
                  Height="50"
                  >
        <TextBlock Text="Change!" Background="{Binding Source={x:Reference ColorPicker}, Path=SelectedValue, Converter={StaticResource StringToColorConverter}}"/>
    </ToggleButton>
</StackPanel>


问:
Best practices to keep strings in one place
I'm setting up a new iOS project and wondering if I should use a Localizable.strings file to keep my strings even without planning to add support for other languages.

I've tried using struct to keep my strings before but I am wondering if this is a good practice. Using Localizable.strings will also work well on the library R.swift, another reason why I am struggling to choose a strategy.

答:
There is no "best practice" in this case. There are practices and some may be a bit more appropriate for your case than others.

You are saying that you are not planning to add support for other languages but it seems like you want to be prepared for it if you change your mind. So first thing is to ask yourself what is the actual problem you are looking solution for. I would say the problem is the overhead you get once app is already out and you need to hunt all the strings you have used in your app and wrap them into NSLocalizedString. This usually includes endless testing and you will still in the end most likely forget to localize at least some strings.

You can from beginning start wrapping things into NSLocalizedString which will in the end help you extract all the strings using native tools from your code. The problem then are still Storyboards; not as much extracting strings from storyboard but removing those default texts you have no plan to translate (Like "Name" will actually be some name and should not be translated). So in my experience this is a half solution.

To solve the Storyboard issue there should be a tool (I can't remember which, maybe some other CocoaPod) which enables you to ignore views that should not be translated. So in this case you need to use 2 things; NSLocalizedString and ignoring untranslatable items in IB.

As you already put it nicely you can use R.Swift to get strings directly from your strings file. This is very neat but also extremely distracting as you develop. Doing so you are forcing developer to first enter a text in strings file before he can use it. Personally I hate that. Also this can be a problem with multiple developers being in conflict. Not to mention this hasn't nearly fixed your issue with Storyboards.

Creating a separate structure system to hold all the strings does work pretty nicely. You don't have to hunt down all of the strings in your code and you don't need to jump to strings file (going to another source is much more pleasant when developing since you can navigate to it very easily). You do also preserve a good structure, assuming you maintain it like label.text = Strings.Settings.User.firstNamePlaceholder which helps you to easily find strings you need or are deprecated. You can remove whole screens with great ease. But it still is an overhead for developer plus you still have an issue that now you need to drag all the outlets from storyboard to set the localized strings to them.

Doing this procedure you can in the end choose to use NSLocalizedString directly or to use R.Swift. In fact you can just use nothing and you will still not have much overtime switching to any of the two (again assuming that hunting down those strings in the code takes most of the time).

Personally I would go with nothing at all or go with creating a custom structure system which then uses nothing but just returns raw strings. But this all really depends on what size is your project of, what type of project, how many things are in Storyboards... It also depends on when you expect to have more resources so you either spend more time now and don't bother later or you simply do it simplest now prepare for a lot of work when localization is indeed needed (hopefully when that happens it is one of the "sweet" problems because it means you have tons of users).


问:
Rails 5.2 Can't open rails credentials with Sublime Text
I am using Windows Subsystem for Linux with Rails 5.2 and Sublime Text 3.
When i do

EDITOR="subl --wait" rails credentials:edit

It says "New credentials encrypted and saved." but does not open the file to be edited with Sublime Text 3.
Also when trying Visual Studio Code with

EDITOR="code --wait" rails credentials:edit

Visual Studio Code opens but it is empty.

I can only edit the file with VIM and the command
EDITOR="vim" rails credentials:edit

The thing is i do not want to edit the file with vim.
What is the problem so it does not open the file to be edited with Sublime or VS Code?

I am using Rails 5.2

Thanks a lot in advance

答:
I have succeeded my following this

```<code> SET EDITOR="full_path to sublime"
 rails credentials:edit
</code>```

after closing sublime only i am getting new credentials saved response.

Hope it helps

Body:
I have succeeded my following this

 SET EDITOR="full_path to sublime"
 rails credentials:edit

after closing sublime only i am getting new credentials saved response.

Hope it helps


问:
You can't specify target table 'A' for update in FROM clause
This is my request

```<code>> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )
</code>```

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause

答:
You want to delete all records from table A that don't have a matching id in table B?

How about this:

```<code>DELETE
FROM A
WHERE NOT EXISTS (select 1 from B where A.id = B.id);
</code>```

Body:
This is my request

> DELETE FROM A WHERE id in (    Select
> id From A    Left Join B on A.id=B.id
> Where B.id is null )

When I execute this I have this error

You can't specify target table 'A' for
  update in FROM clause

Body:
You want to delete all records from table A that don't have a matching id in table B?

How about this:

DELETE
FROM A
WHERE NOT EXISTS (select 1 from B where A.id = B.id);