问:
Timeout error using selenium in Python, although the code runs fine
I'm new here and new to Python too!
I have a huge movie archive on my disk,
I wrote a code to download movie posters, using movie names on my disk and put the poster inside each movie folder.

```<code>from os import listdir
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import requests

# Loading Film Names
film_names = [f for f in listdir("I:\\Movies")]

# Loading Image Names
image_names = [f for f in listdir("I:\\Movies")]

# Opening Chrome
driver = webdriver.Chrome()
driver.get('http://imdb.com')

counter = 0

for i in film_names[counter:]:
    # filtering movie names to become without director names and no release date
    parantez_num = i.find('(')
    film_names[counter] = i[0:parantez_num - 1]

    print(counter)

    # Typing Film Name in Search Box
    searchbox = driver.find_element_by_xpath('//*[@id="suggestion-search"]')
    searchbox.send_keys(film_names[counter])

    # Clicking Search Button
    searchbutton = driver.find_element_by_xpath('//*[@id="suggestion-search-button"]')
    searchbutton.click()

    # Clicking First Result
    firstsearch = WebDriverWait(driver, 5).until(
    expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [@id="main"]/div/div[2]/table/tbody/tr[1]/td[2]/a'))
    )
    firstsearch.click()

    # Maximizing Image
    wait = WebDriverWait(driver, 10)
    image_magnify = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [@id="title-overview-widget'''

    '"]/div[1]/div[3]/div[1]/a/img')))
    image_magnify.click()

    # Saving The Image
    image = WebDriverWait(driver, 5).until(
    expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="photo-
    container"]/div/div[3]/div/div[2]/div['
                                                           '1]/div[2]/div/img[2]'))
    )
    image_url = (image.get_attribute('src'))
    with open("I:\\Movies\\" + image_names[counter] + "\\" + image_names[counter] + ".jpg", "wb") as
    f:
    f.write(requests.get(image_url).content)

    # going back to the first page of IMDB
    driver.back()
    driver.back()
    driver.back()

    counter += 1
</code>```

It works fine. But after a random number of successful downloads, suddenly it stops and gives an error:

```<code>Traceback (most recent call last):
File "C:/Users/Kurdman/Desktop/Poster Downloader/Main/MainCode.py", line 42, in <module>
image_magnifier = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="title-
overview-widget'
File "C:\Users\Kurdman\Desktop\Poster Downloader\Main\venv\lib\site-
packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
</code>```

I wonder why I receive this error, because the "for loop" works fine for like 10 movies, then suddenly it stops. Even if I set the counter to something like 100, to start from the 100th movie, it works for some of them and then stops again and gives this error.

By the way, my movie names are in such format:
Ajami (2009) - Scandar Copti - Foreign Language Oscar Nominee
so I filter the names to remove the release date and director names and other things, by finding the index of the first parenthesis in the title.

答:
Yes there are chances of getting TimeOutError when the element takes more than expected time to load you can also handle this error by just slightly changing your for loop. try using the code given below
for i in film_names[counter:]:

```<code>try:
    parantez_num = i.find('(')
    film_names[counter] = i[0:parantez_num - 1]

    print(counter)

    # Typing Film Name in Search Box
    searchbox = driver.find_element_by_xpath('//*[@id="suggestion-search"]')
    searchbox.send_keys(film_names[counter])

    # Clicking Search Button
    searchbutton = driver.find_element_by_xpath('//*[@id="suggestion-search-button"]')
    searchbutton.click()

    # Clicking First Result
    firstsearch = WebDriverWait(driver, 5).until(
        expected_conditions.element_to_be_clickable((By.XPATH, '//*
        [ @ id="main"] / div / div[2] / table / tbody / tr[1] / td[2] / a'))
                                                     )
    firstsearch.click()

    # Maximizing Image
    wait = WebDriverWait(driver, 10)
    image_magnify = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [ @ id="title-overview-widget'''

                                                                            '"]/div[1]/div[3]/div[1]/a/img')))
    image_magnify.click()

    # Saving The Image
    image = WebDriverWait(driver, 5).until(
        expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="photo-
                                                     container"]/div/div[3]/div/div[2]/div['
                                                     '1]/div[2]/div/img[2]'))
    )
    image_url = (image.get_attribute('src'))
    with open("I:\\Movies\\" + image_names[counter] + "\\" + image_names[counter] + ".jpg", "wb") as
    f:
        f.write(requests.get(image_url).content)

    # going back to the first page of IMDB
    driver.back()
    driver.back()
    driver.back()

    counter += 1
except TimeoutError:
    counter += 0
</code>```

just try editing the for loop with this will handle that error if it appears again

Body:
I'm new here and new to Python too!
I have a huge movie archive on my disk,
I wrote a code to download movie posters, using movie names on my disk and put the poster inside each movie folder.

from os import listdir
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import requests

# Loading Film Names
film_names = [f for f in listdir("I:\\Movies")]

# Loading Image Names
image_names = [f for f in listdir("I:\\Movies")]

# Opening Chrome
driver = webdriver.Chrome()
driver.get('http://imdb.com')

counter = 0

for i in film_names[counter:]:
    # filtering movie names to become without director names and no release date
    parantez_num = i.find('(')
    film_names[counter] = i[0:parantez_num - 1]

    print(counter)

    # Typing Film Name in Search Box
    searchbox = driver.find_element_by_xpath('//*[@id="suggestion-search"]')
    searchbox.send_keys(film_names[counter])

    # Clicking Search Button
    searchbutton = driver.find_element_by_xpath('//*[@id="suggestion-search-button"]')
    searchbutton.click()

    # Clicking First Result
    firstsearch = WebDriverWait(driver, 5).until(
    expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [@id="main"]/div/div[2]/table/tbody/tr[1]/td[2]/a'))
    )
    firstsearch.click()

    # Maximizing Image
    wait = WebDriverWait(driver, 10)
    image_magnify = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [@id="title-overview-widget'''

    '"]/div[1]/div[3]/div[1]/a/img')))
    image_magnify.click()

    # Saving The Image
    image = WebDriverWait(driver, 5).until(
    expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="photo-
    container"]/div/div[3]/div/div[2]/div['
                                                           '1]/div[2]/div/img[2]'))
    )
    image_url = (image.get_attribute('src'))
    with open("I:\\Movies\\" + image_names[counter] + "\\" + image_names[counter] + ".jpg", "wb") as
    f:
    f.write(requests.get(image_url).content)

    # going back to the first page of IMDB
    driver.back()
    driver.back()
    driver.back()

    counter += 1

It works fine. But after a random number of successful downloads, suddenly it stops and gives an error:

Traceback (most recent call last):
File "C:/Users/Kurdman/Desktop/Poster Downloader/Main/MainCode.py", line 42, in <module>
image_magnifier = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="title-
overview-widget'
File "C:\Users\Kurdman\Desktop\Poster Downloader\Main\venv\lib\site-
packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

I wonder why I receive this error, because the "for loop" works fine for like 10 movies, then suddenly it stops. Even if I set the counter to something like 100, to start from the 100th movie, it works for some of them and then stops again and gives this error.

By the way, my movie names are in such format:
Ajami (2009) - Scandar Copti - Foreign Language Oscar Nominee
so I filter the names to remove the release date and director names and other things, by finding the index of the first parenthesis in the title.

Body:
Yes there are chances of getting TimeOutError when the element takes more than expected time to load you can also handle this error by just slightly changing your for loop. try using the code given below
for i in film_names[counter:]:

try:
    parantez_num = i.find('(')
    film_names[counter] = i[0:parantez_num - 1]

    print(counter)

    # Typing Film Name in Search Box
    searchbox = driver.find_element_by_xpath('//*[@id="suggestion-search"]')
    searchbox.send_keys(film_names[counter])

    # Clicking Search Button
    searchbutton = driver.find_element_by_xpath('//*[@id="suggestion-search-button"]')
    searchbutton.click()

    # Clicking First Result
    firstsearch = WebDriverWait(driver, 5).until(
        expected_conditions.element_to_be_clickable((By.XPATH, '//*
        [ @ id="main"] / div / div[2] / table / tbody / tr[1] / td[2] / a'))
                                                     )
    firstsearch.click()

    # Maximizing Image
    wait = WebDriverWait(driver, 10)
    image_magnify = wait.until(expected_conditions.element_to_be_clickable((By.XPATH, '//*
    [ @ id="title-overview-widget'''

                                                                            '"]/div[1]/div[3]/div[1]/a/img')))
    image_magnify.click()

    # Saving The Image
    image = WebDriverWait(driver, 5).until(
        expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="photo-
                                                     container"]/div/div[3]/div/div[2]/div['
                                                     '1]/div[2]/div/img[2]'))
    )
    image_url = (image.get_attribute('src'))
    with open("I:\\Movies\\" + image_names[counter] + "\\" + image_names[counter] + ".jpg", "wb") as
    f:
        f.write(requests.get(image_url).content)

    # going back to the first page of IMDB
    driver.back()
    driver.back()
    driver.back()

    counter += 1
except TimeoutError:
    counter += 0

just try editing the for loop with this will handle that error if it appears again


来源: stackexchange

问:
Socket Shutdown: when should I use SocketShutdown.Both
I believe the shutdown sequence is as follows (as described here):

The MSDN documentation (remarks section) reads:

When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed.

This seems to imply that if I use Shutdown(SocketShutdown.Both), any data that has not yet been received, may still be consumed. To test this:

I continuously send data to the client (via Send in a separate thread).

The client executed Shutdown(SocketShutdown.Both).

The BeginReceive callback on the server executes, however, EndReceive throws an exception: An existing connection was forcibly closed by the remote host. This means that I am unable to receive the 0 return value and in turn call Shutdown.

As requested, I've posted the Server side code below (it's wrapped in a Windows  Form and it was created just as an experiment). In my test scenario I did not see the CLOSE_WAIT state in TCPView as I normally did without sending the continuous data. So potentially I've done something wrong and I'm interrupting the consequences incorrectly. In another experiment:

Client connects to server.

Client executes Shutdown(SocketShutdown.Both).

Server receives shutdown acknowledgement and sends some data in response. Server also executes Shutdown.

Client receives data from server but the next BeginReceive is not allowed: A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call

In this scenario, I was still expecting a 0 return value from EndReceive to Close the socket. Does this mean that I should use Shutdown(SocketShutdown.Send) instead? If so, when should one use Shutdown(SocketShutdown.Both)?

Code from first experiment:

```<code>private TcpListener SocketListener { get; set; }
private Socket ConnectedClient { get; set; }
private bool serverShutdownRequested;
private object shutdownLock = new object();

private struct SocketState
{
  public Socket socket;
  public byte[] bytes;
}

private void ProcessIncoming(IAsyncResult ar)
{
  var state = (SocketState)ar.AsyncState;
  // Exception thrown here when client executes Shutdown:
  var dataRead = state.socket.EndReceive(ar);
  if (dataRead > 0)
  {
    state.socket.BeginReceive(state.bytes, 0, state.bytes.Length, SocketFlags.None, ProcessIncoming, state);
  }
  else
  {
    lock (shutdownLock)
    {
      serverShutdownRequested = true;
      state.socket.Shutdown(SocketShutdown.Both);
      state.socket.Close();
      state.socket.Dispose();
    }
  }
}

private void Spam()
{
  int i = 0;
  while (true)
  {
    lock (shutdownLock)
    {
      if (!serverShutdownRequested)
      {
        try { ConnectedClient.Send(Encoding.Default.GetBytes(i.ToString())); }
        catch { break; }
        ++i;
      }
      else { break; }
    }
  }
}

private void Listen()
{
  while (true)
  {
    ConnectedClient = SocketListener.AcceptSocket();
    var data = new SocketState();
    data.bytes = new byte[1024];
    data.socket = ConnectedClient;
    ConnectedClient.BeginReceive(data.bytes, 0, data.bytes.Length, SocketFlags.None, ProcessIncoming, data);
    serverShutdownRequested = false;
    new Thread(Spam).Start();
  }
}

public ServerForm()
{
  InitializeComponent();
  var hostEntry = Dns.GetHostEntry("localhost");
  var endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);
  SocketListener = new TcpListener(endPoint);
  SocketListener.Start();
  new Thread(Listen).Start();
}
</code>```

答: Shutdown(SocketShutdown.Both) should be used when you don't want to receive or send. You either want to abruptly close connection or you know that other party has shutdown using SocketShutdown.Receive. For example, you have a time server that sends current time to the client that connects it, server sends time and calls Shutdown(SocketShutdown.Received) as it is not expecting any more data from client. The client upon receiving time data should call Shutdown(SocketShutdown.Both) as it is not going to send or receive any further data.

ContentLicense: CC BY-SA 3.0

Body:
I believe the shutdown sequence is as follows (as described here):

The MSDN documentation (remarks section) reads:

When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed.

This seems to imply that if I use Shutdown(SocketShutdown.Both), any data that has not yet been received, may still be consumed. To test this:

I continuously send data to the client (via Send in a separate thread).

The client executed Shutdown(SocketShutdown.Both).

The BeginReceive callback on the server executes, however, EndReceive throws an exception: An existing connection was forcibly closed by the remote host. This means that I am unable to receive the 0 return value and in turn call Shutdown.

As requested, I've posted the Server side code below (it's wrapped in a Windows  Form and it was created just as an experiment). In my test scenario I did not see the CLOSE_WAIT state in TCPView as I normally did without sending the continuous data. So potentially I've done something wrong and I'm interrupting the consequences incorrectly. In another experiment:

Client connects to server.

Client executes Shutdown(SocketShutdown.Both).

Server receives shutdown acknowledgement and sends some data in response. Server also executes Shutdown.

Client receives data from server but the next BeginReceive is not allowed: A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call

In this scenario, I was still expecting a 0 return value from EndReceive to Close the socket. Does this mean that I should use Shutdown(SocketShutdown.Send) instead? If so, when should one use Shutdown(SocketShutdown.Both)?

Code from first experiment:

private TcpListener SocketListener { get; set; }
private Socket ConnectedClient { get; set; }
private bool serverShutdownRequested;
private object shutdownLock = new object();

private struct SocketState
{
  public Socket socket;
  public byte[] bytes;
}

private void ProcessIncoming(IAsyncResult ar)
{
  var state = (SocketState)ar.AsyncState;
  // Exception thrown here when client executes Shutdown:
  var dataRead = state.socket.EndReceive(ar);
  if (dataRead > 0)
  {
    state.socket.BeginReceive(state.bytes, 0, state.bytes.Length, SocketFlags.None, ProcessIncoming, state);
  }
  else
  {
    lock (shutdownLock)
    {
      serverShutdownRequested = true;
      state.socket.Shutdown(SocketShutdown.Both);
      state.socket.Close();
      state.socket.Dispose();
    }
  }
}

private void Spam()
{
  int i = 0;
  while (true)
  {
    lock (shutdownLock)
    {
      if (!serverShutdownRequested)
      {
        try { ConnectedClient.Send(Encoding.Default.GetBytes(i.ToString())); }
        catch { break; }
        ++i;
      }
      else { break; }
    }
  }
}

private void Listen()
{
  while (true)
  {
    ConnectedClient = SocketListener.AcceptSocket();
    var data = new SocketState();
    data.bytes = new byte[1024];
    data.socket = ConnectedClient;
    ConnectedClient.BeginReceive(data.bytes, 0, data.bytes.Length, SocketFlags.None, ProcessIncoming, data);
    serverShutdownRequested = false;
    new Thread(Spam).Start();
  }
}

public ServerForm()
{
  InitializeComponent();
  var hostEntry = Dns.GetHostEntry("localhost");
  var endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000);
  SocketListener = new TcpListener(endPoint);
  SocketListener.Start();
  new Thread(Listen).Start();
}

ContentLicense: CC BY-SA 4.0


问:
Why string str = new string("abc") doesn't pass compiler?
Given public String(char*) why we cannot use the following statement?

```<code>string str = new string("aaa");
</code>```

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

答:
have look to this may resolve your doubt C# New String Constructor</p>

```<code>unsafe public String(char*);
       public String(char[]);
unsafe public String(sbyte*);
       public String(char, int);
unsafe public String(char*, int, int);
       public String(char[], int, int);
unsafe public String(sbyte*, int, int);
unsafe public String(sbyte*, int, int, Encoding);
</code>```

Body:
Given public String(char*) why we cannot use the following statement?

string str = new string("aaa");

Error   1

The best overloaded method match for
  'string.String(char*)' has some
  invalid
  arguments C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  26  ConsoleApplication2

Error   2

Argument 1: cannot convert from
  'string' to
  'char*'   C:\temp\ConsoleApplication2\ConsoleApplication2\Program.cs  19  37  ConsoleApplication2

Body:
have look to this may resolve your doubt C# New String Constructor

unsafe public String(char*);
       public String(char[]);
unsafe public String(sbyte*);
       public String(char, int);
unsafe public String(char*, int, int);
       public String(char[], int, int);
unsafe public String(sbyte*, int, int);
unsafe public String(sbyte*, int, int, Encoding);


问:
How to make an API call in solidity?
I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.

```<code>"example-winner.com/winner"
</code>```

And it returns simple JSON with the address of the winner:

```<code>{"winner":"0xa7D0......."}
</code>```

However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.

Any thoughts? Below is my code:

```<code>pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }
    function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }
    function getWinner() public{
        assert(msg.sender == manager);
        // TODO
        // Get the winner from the API call
        result = 0; // the result of the API call
        players[result].transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        players = new address[](0);
        // this empties the dynamic array
    }
}
</code>```

答:
You didn't properly explain what you are trying to do. Are you having trouble with the solidity code? or rather with your server? Here is an edited version. See if it helps.

```<code>pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    //address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }

    struct Player {
        address playerAddress;
        uint score;
    }

    Player[] public players;

    // i prefer passing arguments this way
    function enter(uint value) public payable{
        assert(msg.value > MINIMUM);
        players.push(Player(msg.sender, value));
    }

    //call this to get the address of winner
    function winningPlayer() public view
            returns (address winner)
    {
        uint winningScore = 0;
        for (uint p = 0; p < players.length; p++) {
            if (players[p].score > winningScore) {
                winningScore = players[p].score;
                winner = players[p].playerAddress;
            }
        }
    }

    // call this to transfer fund
    function getWinner() public{
        require(msg.sender == manager, "Only a manager is allowed to perform this operation");
        // TODO

        address winner = winningPlayer();
        // Get the winner from the API call
        //uint result = 0; // the result of the API call
        winner.transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        delete players;
        // this empties the dynamic array
    }
}
</code>```

At least that is what I understand by your question.

Title: How to make an API call in solidity?

Body:
I have a smart contract that I’m trying to make, it pays out the winners of my League of Legends tournament. However I’m running into an issue. I need to make an API call to get the winner of the match, I have a simple URL that I’ve make.

"example-winner.com/winner"

And it returns simple JSON with the address of the winner:

{"winner":"0xa7D0......."}

However, I’m not sure how to make the API call to the outside function. I know I need to use some sort of oracle technology.

Any thoughts? Below is my code:

pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }
    function enter() public payable{
        assert(msg.value > MINIMUM);
        players.push(msg.sender);
    }
    function getWinner() public{
        assert(msg.sender == manager);
        // TODO
        // Get the winner from the API call
        result = 0; // the result of the API call
        players[result].transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        players = new address[](0);
        // this empties the dynamic array
    }
}

Body:
You didn't properly explain what you are trying to do. Are you having trouble with the solidity code? or rather with your server? Here is an edited version. See if it helps.

pragma solidity ^0.4.24;
contract LeagueWinners{
    address public manager;
    //address[] public players;
    uint256 MINIMUM = 1000000000000000;
    constructor() public{
        manager = msg.sender;
    }

    struct Player {
        address playerAddress;
        uint score;
    }

    Player[] public players;

    // i prefer passing arguments this way
    function enter(uint value) public payable{
        assert(msg.value > MINIMUM);
        players.push(Player(msg.sender, value));
    }

    //call this to get the address of winner
    function winningPlayer() public view
            returns (address winner)
    {
        uint winningScore = 0;
        for (uint p = 0; p < players.length; p++) {
            if (players[p].score > winningScore) {
                winningScore = players[p].score;
                winner = players[p].playerAddress;
            }
        }
    }

    // call this to transfer fund
    function getWinner() public{
        require(msg.sender == manager, "Only a manager is allowed to perform this operation");
        // TODO

        address winner = winningPlayer();
        // Get the winner from the API call
        //uint result = 0; // the result of the API call
        winner.transfer(address(this).balance);
        // returns an adress object
        // all units of transfer are in wei
        delete players;
        // this empties the dynamic array
    }
}

At least that is what I understand by your question.


问:
How to set focus on input field in Clarity modal
I am using Clarity 3 and Angular 9. I have Modal window with one input field. When modal is opened the input field should be in focused state.

Here is code for my modal window:

<clr-modal [(clrModalOpen)]="modal">

I have a nice title

This input should get the focus when modal is opened.

        <input class="clr-input" type="text" #input>

        <button type="button" class="btn btn-outline" (click)="close()">Close</button>

</clr-modal>
```

<p>The problem is Clarity does not provide callback when modal is opened. If I try to set focus in the method <code>open()</code>, then I couldn't do this because by this time the modal window had not yet opened due to animation.</p>

```@ViewChild('input', { static: false }) input: ElementRef;

open() {
    this.modal = true;
    this.input.nativeElement.focus(); // does not work
}
```

<p>If I set some delay with <code>setTimeout</code>, when it works, but I don't like such solution.</p>

```setTimeout(() => this.input.nativeElement.focus(), 10);
```

<p>I also tried to use directive <code>clrFocusOnViewInit</code>, but it also doesn't work.</p>

```<input class="clr-input" type="text" #input [clrFocusOnViewInit]="true">
```

Can someone suggest me a good solution? Why the directive clrFocusOnViewInit does not work?

https://stackblitz.com/edit/clarity-focus-on-view-init

Update

I created a feature request in Clarity project:
https://github.com/vmware/clarity/issues/4476

答: try using clrFocusTrap="1" starting from where you want it to be.</p>

Body:
I am using Clarity 3 and Angular 9. I have Modal window with one input field. When modal is opened the input field should be in focused state.

Here is code for my modal window:

<clr-modal [(clrModalOpen)]="modal">

I have a nice title

This input should get the focus when modal is opened.

        <input class="clr-input" type="text" #input>

        <button type="button" class="btn btn-outline" (click)="close()">Close</button>

</clr-modal>

The problem is Clarity does not provide callback when modal is opened. If I try to set focus in the method open(), then I couldn't do this because by this time the modal window had not yet opened due to animation.

@ViewChild('input', { static: false }) input: ElementRef;

open() {
    this.modal = true;
    this.input.nativeElement.focus(); // does not work
}

If I set some delay with setTimeout, when it works, but I don't like such solution.

setTimeout(() => this.input.nativeElement.focus(), 10);

I also tried to use directive clrFocusOnViewInit, but it also doesn't work.

<input class="clr-input" type="text" #input [clrFocusOnViewInit]="true">

Can someone suggest me a good solution? Why the directive clrFocusOnViewInit does not work?

https://stackblitz.com/edit/clarity-focus-on-view-init

Update

I created a feature request in Clarity project:
https://github.com/vmware/clarity/issues/4476


问:
How to generate a random number in solidity?
I have a couple of keccaks, which could be reduced to one if I would find a cheap way to get parts of the created uint.

```<code>pragma solidity ^0.4.19;

contract test {
  function test() {

  }

function sup() returns (uint test) {
    uint _test = uint(keccak256("wow"));
    return _test;
  }
}
</code>```

This returns me a sweet random number: 13483274892375982735325

Now the plan is that instead of calling keccak 5 times with different "seeds", I could take that number apart and get something like:
1348, 3274, 8923 etc.
which I then use for my random number e.g.: 1348 % 10

But solidity can't just do that. Is there anything cheap that could work?

答:
Solidity contracts are deterministic. Anyone who figures out how your contract produces randomness can anticipate its results and use this information to exploit your application.

One option is to produce randomness off-chain (where it cannot be predicted) and use it in your smart contract. Chainlink VRF is an easy-to-implement solution for using random data in smart contracts. Here's an example snippet to request & receive random data:

```<code>requestRandomness(keyHash, fee, seed);
</code>```

Your contract's request is fulfilled in a callback function:

```<code>function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
  // Do something with randomness
}
</code>```

An example of a full contract that implements a random number would be:

```<code>pragma solidity 0.6.2;

import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol";

contract Verifiable6SidedDiceRoll is VRFConsumerBase {
    using SafeMath for uint;

    bytes32 internal keyHash;
    uint256 internal fee;

    event RequestRandomness(
        bytes32 indexed requestId,
        bytes32 keyHash,
        uint256 seed
    );

    event RequestRandomnessFulfilled(
        bytes32 indexed requestId,
        uint256 randomness
    );

    /**
     * @notice Constructor inherits VRFConsumerBase
     * @dev Ropsten deployment params:
     * @dev   _vrfCoordinator: 0xf720CF1B963e0e7bE9F58fd471EFa67e7bF00cfb
     * @dev   _link:           0x20fE562d797A42Dcb3399062AE9546cd06f63280
     */
    constructor(address _vrfCoordinator, address _link)
        VRFConsumerBase(_vrfCoordinator, _link) public
    {
        vrfCoordinator = _vrfCoordinator;
        LINK = LinkTokenInterface(_link);
        keyHash = 0xced103054e349b8dfb51352f0f8fa9b5d20dde3d06f9f43cb2b85bc64b238205; // hard-coded for Ropsten
        fee = 10 ** 18; // 1 LINK hard-coded for Ropsten
    }

    /**
     * @notice Requests randomness from a user-provided seed
     * @dev The user-provided seed is hashed with the current blockhash as an additional precaution.
     * @dev   1. In case of block re-orgs, the revealed answers will not be re-used again.
     * @dev   2. In case of predictable user-provided seeds, the seed is mixed with the less predictable blockhash.
     * @dev This is only an example implementation and not necessarily suitable for mainnet.
     * @dev You must review your implementation details with extreme care.
     */
    function rollDice(uint256 userProvidedSeed) public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet");
        uint256 seed = uint256(keccak256(abi.encode(userProvidedSeed, blockhash(block.number)))); // Hash user seed and blockhash
        bytes32 _requestId = requestRandomness(keyHash, fee, seed);
        emit RequestRandomness(_requestId, keyHash, seed);
        return _requestId;
    }

    function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
        uint256 d6Result = randomness.mod(6).add(1);
        emit RequestRandomnessFulfilled(requestId, randomness);
    }

}
</code>```

Body:
I have a couple of keccaks, which could be reduced to one if I would find a cheap way to get parts of the created uint.

pragma solidity ^0.4.19;

contract test {
  function test() {

  }

function sup() returns (uint test) {
    uint _test = uint(keccak256("wow"));
    return _test;
  }
}

This returns me a sweet random number: 13483274892375982735325

Now the plan is that instead of calling keccak 5 times with different "seeds", I could take that number apart and get something like:
1348, 3274, 8923 etc.
which I then use for my random number e.g.: 1348 % 10

But solidity can't just do that. Is there anything cheap that could work?

Body:
Solidity contracts are deterministic. Anyone who figures out how your contract produces randomness can anticipate its results and use this information to exploit your application.

One option is to produce randomness off-chain (where it cannot be predicted) and use it in your smart contract. Chainlink VRF is an easy-to-implement solution for using random data in smart contracts. Here's an example snippet to request & receive random data:

requestRandomness(keyHash, fee, seed);

Your contract's request is fulfilled in a callback function:

function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
  // Do something with randomness
}

An example of a full contract that implements a random number would be:

pragma solidity 0.6.2;

import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol";

contract Verifiable6SidedDiceRoll is VRFConsumerBase {
    using SafeMath for uint;

    bytes32 internal keyHash;
    uint256 internal fee;

    event RequestRandomness(
        bytes32 indexed requestId,
        bytes32 keyHash,
        uint256 seed
    );

    event RequestRandomnessFulfilled(
        bytes32 indexed requestId,
        uint256 randomness
    );

    /**
     * @notice Constructor inherits VRFConsumerBase
     * @dev Ropsten deployment params:
     * @dev   _vrfCoordinator: 0xf720CF1B963e0e7bE9F58fd471EFa67e7bF00cfb
     * @dev   _link:           0x20fE562d797A42Dcb3399062AE9546cd06f63280
     */
    constructor(address _vrfCoordinator, address _link)
        VRFConsumerBase(_vrfCoordinator, _link) public
    {
        vrfCoordinator = _vrfCoordinator;
        LINK = LinkTokenInterface(_link);
        keyHash = 0xced103054e349b8dfb51352f0f8fa9b5d20dde3d06f9f43cb2b85bc64b238205; // hard-coded for Ropsten
        fee = 10 ** 18; // 1 LINK hard-coded for Ropsten
    }

    /**
     * @notice Requests randomness from a user-provided seed
     * @dev The user-provided seed is hashed with the current blockhash as an additional precaution.
     * @dev   1. In case of block re-orgs, the revealed answers will not be re-used again.
     * @dev   2. In case of predictable user-provided seeds, the seed is mixed with the less predictable blockhash.
     * @dev This is only an example implementation and not necessarily suitable for mainnet.
     * @dev You must review your implementation details with extreme care.
     */
    function rollDice(uint256 userProvidedSeed) public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) > fee, "Not enough LINK - fill contract with faucet");
        uint256 seed = uint256(keccak256(abi.encode(userProvidedSeed, blockhash(block.number)))); // Hash user seed and blockhash
        bytes32 _requestId = requestRandomness(keyHash, fee, seed);
        emit RequestRandomness(_requestId, keyHash, seed);
        return _requestId;
    }

    function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
        uint256 d6Result = randomness.mod(6).add(1);
        emit RequestRandomnessFulfilled(requestId, randomness);
    }

}


问:
Add image to button when pressed
```<code>button1_on_image = Gtk::manage(new Gtk::Image{"button1_on.png"});   // Load icon
button1_off_image = Gtk::manage(new Gtk::Image{"button1_off.png"}); //   images
button1 = Gtk::manage(new Gtk::ToolButton{*button1_off_image});  // Create button
button1->set_tooltip_markup("Select one stick");                //   with image
button1->signal_clicked().connect(sigc::mem_fun(*this,
    &Main_window::on_button1_click));
toolbar->append(*button1);
</code>```

This is a snippet of code showing how I successfully make the button. The problem is that, when it is clicked I want "button1_on.png" to be shown instead of "button1_off.png", but I don't know how to do that.

答:
Here is a code snippet that does what you want:

When the window is initially created, the button is "Off".

When the button is clicked, the button changes state to "On".

Note that this is a minimal example, so clicking again on the button will not change its state back to "On", but I will leave this part to you, if it is a requirement for you.

```<code>#include <gtkmm.h>

int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "buttons.on.off");

    // Load images:
    Gtk::Image button1_on_image{"button1_on.png"};
    Gtk::Image button1_off_image{"button1_off.png"};

    // Create button:
    Gtk::ToolButton button1{button1_off_image};
    button1.set_tooltip_markup("Select one stick");

    // Create handler (as a lambda):
    const auto handler = [&button1, &button1_on_image, &button1_off_image]()
                         {
                             // We change to "on" here (when clicked):
                             button1.set_icon_widget(button1_on_image);

                             // We make it visible:
                             button1.show_all();
                         };

    button1.signal_clicked().connect(handler);

    // Add the button to the window.
    Gtk::Window window;
    window.add(button1);

    // Make the window visible:
    window.show_all();

    return app->run(window);
}
</code>```

I made some simplifications to your snippet:

List item

I put everything on the stack (no new).

The handler is a lambda.

In my opinion, it makes the syntax clearer.

Title: Add image to button when pressed

Body:
button1_on_image = Gtk::manage(new Gtk::Image{"button1_on.png"});   // Load icon
button1_off_image = Gtk::manage(new Gtk::Image{"button1_off.png"}); //   images
button1 = Gtk::manage(new Gtk::ToolButton{*button1_off_image});  // Create button
button1->set_tooltip_markup("Select one stick");                //   with image
button1->signal_clicked().connect(sigc::mem_fun(*this,
    &Main_window::on_button1_click));
toolbar->append(*button1);

This is a snippet of code showing how I successfully make the button. The problem is that, when it is clicked I want "button1_on.png" to be shown instead of "button1_off.png", but I don't know how to do that.

Body:
Here is a code snippet that does what you want:

When the window is initially created, the button is "Off".

When the button is clicked, the button changes state to "On".

Note that this is a minimal example, so clicking again on the button will not change its state back to "On", but I will leave this part to you, if it is a requirement for you.

#include <gtkmm.h>

int main(int argc, char *argv[])
{
    auto app = Gtk::Application::create(argc, argv, "buttons.on.off");

    // Load images:
    Gtk::Image button1_on_image{"button1_on.png"};
    Gtk::Image button1_off_image{"button1_off.png"};

    // Create button:
    Gtk::ToolButton button1{button1_off_image};
    button1.set_tooltip_markup("Select one stick");

    // Create handler (as a lambda):
    const auto handler = [&button1, &button1_on_image, &button1_off_image]()
                         {
                             // We change to "on" here (when clicked):
                             button1.set_icon_widget(button1_on_image);

                             // We make it visible:
                             button1.show_all();
                         };

    button1.signal_clicked().connect(handler);

    // Add the button to the window.
    Gtk::Window window;
    window.add(button1);

    // Make the window visible:
    window.show_all();

    return app->run(window);
}

I made some simplifications to your snippet:

List item

I put everything on the stack (no new).

The handler is a lambda.

In my opinion, it makes the syntax clearer.


问:
I'm not sure what this java row does
I should probably know that but I'm not sure what this line of code is doing:</p>

```<code>int iEnd=i==grid.length - 1 ? 0:1;
</code>```

答:
it will set iEnd to 0 if i equals grind.length -1 otherwise it will set iEnd to 1

the operator is called Ternary Operator and is a short hand for a Conditional Operator
and you can read more about it here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Title: I'm not sure what this java row does

Body:
I should probably know that but I'm not sure what this line of code is doing:

int iEnd=i==grid.length - 1 ? 0:1;


问:
Convert sysdate to BST(British Summer Time)
I have a Java api which gets the data from oracle database which is in ET timezone. I want to query that table using sysdate on 2 columns but the sysdate should be picked as current BST date value not as ET date value.

```<code>select * from customers where sysdate between mem_registered_date and mem_deregistered_date;
</code>```

How this can be done? please help

答:
The simplest way to convert between time zones is to use a data type that understands time zones, a TIMESTAMP. Then when you've converted to the time zone you want then CAST it back to a DATE data type:

SELECT *
FROM   customers
WHERE  CAST( SYSTIMESTAMP AT TIME ZONE 'Europe/London' AS DATE )
         BETWEEN mem_registered_date AND mem_deregistered_date;
```

<p>I'm assuming that you want the current time in the United Kingdom (BST in summer and GMT in winter), if you want the time zone UTC+1 then use:</p>

```CAST( SYSTIMESTAMP AT TIME ZONE '+01:00' AS DATE )
```

Body:
I have a Java api which gets the data from oracle database which is in ET timezone. I want to query that table using sysdate on 2 columns but the sysdate should be picked as current BST date value not as ET date value.

select * from customers where sysdate between mem_registered_date and mem_deregistered_date;

How this can be done? please help

Body:
The simplest way to convert between time zones is to use a data type that understands time zones, a TIMESTAMP. Then when you've converted to the time zone you want then CAST it back to a DATE data type:

SELECT *
FROM   customers
WHERE  CAST( SYSTIMESTAMP AT TIME ZONE 'Europe/London' AS DATE )
         BETWEEN mem_registered_date AND mem_deregistered_date;

I'm assuming that you want the current time in the United Kingdom (BST in summer and GMT in winter), if you want the time zone UTC+1 then use:

CAST( SYSTIMESTAMP AT TIME ZONE '+01:00' AS DATE )


答:
You cannot. The vm does not have any I/O outside of the blockchain itself. Instead you will need to tell your smart contract who the winner is and then the smart contract can just read the value of that variable.

This design pattern is also known as the "oracle". Google "Ethereum oracle" for more info.

Basically your web server can call your smart contract. Your smart contract cannot call your web server. If you need your smart contract to access a 3rd party service then your web server will need to make the request then forward the result to solidity by calling a function in your smart contract.

Title: How to make an API call in solidity?


问:
Kotlin Cinterops native library name
I'm using cinterops to link a dynamic library in a mingw binary executable. Everything is working fine, except that the .dll name that the executable asks is different from the one declared at the .def file.
I don't know where this different name is coming from!
This is from my gradle.build.kts:

```<code>mingwX86("mingw"){
    compilations["main"].cinterops{
        val scape2 by creating {
            val cafmSrc = "C:/Software/SCAP E2/CAFM_src"
            val scapSrc = "C:/Software/SCAP E2/TO/ETME2"
            val modifiedSrc = "C:/Software/SCAP E2/Modified CAFM files"
            includeDirs.headerFilterOnly(cafmSrc, scapSrc, modifiedSrc)
            extraOpts.add("-verbose")
        }
    }
    binaries {
        executable()
    }
}
</code>```

This is my scape2.def file:

```<code>headers = scape2.h
headerFilter = scape2.h \ GEO_API_SCAPTO.h
linkerOpts.mingw = -LC:/Users/lscarmin/git/calculation-module4 -lscape2
</code>```

I was expecting that the dll name to be scape2.dll.
But when I run the executable, it asks for ETME2.dll!
If I rename scape2.dll to ETME2.dll, the code works. (editado)

答:
Well, it seems that the file name used is the one defined inside the dll. I have renamed the dll file, but the name used will be the original one.
I didn't know that this info was kept inside the dll</p>

Title: Kotlin Cinterops native library name

Body:
I'm using cinterops to link a dynamic library in a mingw binary executable. Everything is working fine, except that the .dll name that the executable asks is different from the one declared at the .def file.
I don't know where this different name is coming from!
This is from my gradle.build.kts:

mingwX86("mingw"){
    compilations["main"].cinterops{
        val scape2 by creating {
            val cafmSrc = "C:/Software/SCAP E2/CAFM_src"
            val scapSrc = "C:/Software/SCAP E2/TO/ETME2"
            val modifiedSrc = "C:/Software/SCAP E2/Modified CAFM files"
            includeDirs.headerFilterOnly(cafmSrc, scapSrc, modifiedSrc)
            extraOpts.add("-verbose")
        }
    }
    binaries {
        executable()
    }
}

This is my scape2.def file:

headers = scape2.h
headerFilter = scape2.h \ GEO_API_SCAPTO.h
linkerOpts.mingw = -LC:/Users/lscarmin/git/calculation-module4 -lscape2

I was expecting that the dll name to be scape2.dll.
But when I run the executable, it asks for ETME2.dll!
If I rename scape2.dll to ETME2.dll, the code works. (editado)


问:
My Python set-up is too complicated, and I don't understand it. Currently my Python is unusable. Advice would be welcome
Here is a sequence of my commands, and my system's response. This shows that I do not know how to access numpy with my current (very confusing) Python setup. It was recently working, but then I changed something, but can't remember what.

I run MacOs 10.14.6 on a Macbook Pro.

dbae$ which $SHELL
/bin/bash

dbae$ bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin18)
Copyright (C) 2007 Free Software Foundation, Inc.

dbae$ echo $PATH
/Users/dbae/bin:/opt/local/bin:/opt/local/sbin:/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/bin:/usr/local/texlive/2018/bin/universal-darwin:/usr/local/texlive/2018/bin/x86_64-darwin:/Library/TeX/texbin:/opt/X11/bin:/Users/dbae/Library/Python/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:

dbae$ python run.py
Traceback (most recent call last):
  File "run.py", line 9, in <module>
    import numpy
ModuleNotFoundError: No module named 'numpy'

dbae$ which python
/opt/local/bin/python

dbae$ /opt/local/bin/python --version
Python 3.8.3

dbae$ which pip
/opt/local/bin/pip

dbae$ /opt/local/bin/pip --version
pip 19.3.1 from /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pip (python 3.6)

dbae$ pip install --upgrade pip
Collecting pip
  Using cached https://files.pythonhosted.org/packages/43/84/23ed6a1796480a6f1a2d38f2802901d078266bda38388954d01d3f2e821d/pip-20.1.1-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 19.3.1
    Uninstalling pip-19.3.1:
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/opt/local/Library/Frameworks/Python.framework/Versions/3.6/bin/pip'
Consider using the `--user` option or check the permissions.

dbae$ pip install numpy
Requirement already satisfied: numpy in /opt/local/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (1.17.4)
```

答:
Actually, you kind of screwed your pip setup. Start with the beginning :

```<code>$ python -m pip list
</code>```

What is returned by this command ?

I would suggest you start using virtual environment (venv). It is much easier to handle module dependency issues in the future.

```<code>$ python -m venv /path/to/env
$ source /path/to/env/bin/activate # Activates your environment
$ python -m pip install numpy
$ python run.py
</code>```

Doing so will gather all your dependencies in /path/to/env without messing up with your global setup.

Body:
Actually, you kind of screwed your pip setup. Start with the beginning :

$ python -m pip list

What is returned by this command ?

I would suggest you start using virtual environment (venv). It is much easier to handle module dependency issues in the future.

$ python -m venv /path/to/env
$ source /path/to/env/bin/activate # Activates your environment
$ python -m pip install numpy
$ python run.py

Doing so will gather all your dependencies in /path/to/env without messing up with your global setup.


问:
ABP vs Asp.net Boilerplate - Current State for Production
I am about to embark on a few multi-tenant applications projects and are seriously looking at both ABP and ASP.NET Boilerplate as a starting point. Since I have that rare chance to start anew, I would like to obviously go with the latest and greatest (ABP) but it seems that ABP is missing LOTS of documentation - event system, emailing, how to seed data, etc - everywhere I go I see TO DO in the documentation and that makes me question how many people are developing new projects with it.
Are people (that previously had not developed a ASP.NET Boilerplate solution) actually using ABP?
How are you resolving all the documentation holes?
With such a better foundation in place, what are the real downsides of going with ASP.NET Boilerplate?

Thanks, Dave

答:
I had the oportunity to use ASP.NET BOILERPLATE with net framework last year january, and then (10 months ago) in a net core project.
Then a new net core project came 5 months ago and we were eskeptical about ABP madurity, but instead we jumped to it because it was recommended for net core, despite most of the documentation was empty.
It was a good decision, if you have used ASP.NET BOILERPLATE before, or you're starting a net core project, I highly recommend to start with APB framework (they're optimizing a lot for net core). Each week they release new documentation, version's releases very quickly and their github issues page has a lot of documentation from other users' questions (community is rapidly increasing).</p>


问:
What pattern of datetimeformat is needed for DateTimeFormatter to parse JAN01/2020?
I'm being passed a date in ths format - "JAN01/2020" but I can't seem to find the DateTimeFormatter pattern for it. I tried these (as well as several others) but they're resulting in DateTimeParseException -

```<code> DateTimeFormatter.ofPattern("MMMd/YYYY").parse("JAN01/2020")
 DateTimeFormatter.ofPattern("MMMdd/YYYY").parse("JAN01/2020")
</code>```

I also considered this post's solution and the three lines below also result in DateTimeParseException. It does not appear to be a case-sensitivity issue
Java 8 DateTimeFormatter for month in all CAPS not working

```<code>DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMMdd/yyyy");
LocalDateTime dateTime = LocalDateTime.parse("JAN14/2020", formatter);
System.out.println(dateTime.getYear());
</code>```

I appreciate any suggestions!

答:
Case-sensitive

The main problem with your format is, you are using YYYY instead of yyyy. Do it as follows:

```<code>import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

class Main {
    public static void main(String args[]) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                            .parseCaseInsensitive()
                                            .appendPattern("MMMd/yyyy")
                                            .toFormatter();
        System.out.println(LocalDate.parse("JAN01/2020", formatter));
    }
}
</code>```

Output:

```<code>2020-01-01
</code>```

Demo of using DateTimeFormatter::parse with it:

```<code>import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

class Main {
    public static void main(String args[]) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("MMMd/yyyy")
                .toFormatter();
        System.out.println(formatter.parse("JAN01/2020"));
    }
}
</code>```

Output:

```<code>{},ISO resolved to 2020-01-01
</code>```

Body:
I'm being passed a date in ths format - "JAN01/2020" but I can't seem to find the DateTimeFormatter pattern for it. I tried these (as well as several others) but they're resulting in DateTimeParseException -

 DateTimeFormatter.ofPattern("MMMd/YYYY").parse("JAN01/2020")
 DateTimeFormatter.ofPattern("MMMdd/YYYY").parse("JAN01/2020")

I also considered this post's solution and the three lines below also result in DateTimeParseException. It does not appear to be a case-sensitivity issue
Java 8 DateTimeFormatter for month in all CAPS not working

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("MMMdd/yyyy");
LocalDateTime dateTime = LocalDateTime.parse("JAN14/2020", formatter);
System.out.println(dateTime.getYear());

I appreciate any suggestions!

Body:
Case-sensitive

The main problem with your format is, you are using YYYY instead of yyyy. Do it as follows:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

class Main {
    public static void main(String args[]) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                            .parseCaseInsensitive()
                                            .appendPattern("MMMd/yyyy")
                                            .toFormatter();
        System.out.println(LocalDate.parse("JAN01/2020", formatter));
    }
}

Output:

2020-01-01

Demo of using DateTimeFormatter::parse with it:

import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

class Main {
    public static void main(String args[]) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("MMMd/yyyy")
                .toFormatter();
        System.out.println(formatter.parse("JAN01/2020"));
    }
}

Output:

{},ISO resolved to 2020-01-01


问:
How to feed extra data along with image to CNN?
Note: I am using TensorFlow to create my neural network.

Info: I have an image with some extra data which I would like to feed into my neural network (first couple layers of the network are conv layers).

The Problem: The extra data is just a couple of integers that describe the image, not an image, so I wouldn't be able to feed the integers into the network without repeating them until they match the height of the image and append an array of the repeated integers to the side of the image. Doing this would provide a lot of unnecessary data since it is being repeated and is very unelegant.

My Question: Is there a way to add data to the neural network after the conv layer that way the extra data could skip past the conv layers and go directly to the dense layer with the image after the image has already been processed and flatten? If this is not possible would there be a better method of passing extra data alongside an image into a neural network with conv layers?

答:
Tensorflow supports deep networks with multiple inputs. Here's a toy example of a network with image and vector input:</p>

```<code>from tensorflow.keras.layers import Input, Conv2D, Dense, Activation, Flatten, concatenate
from tensorflow.keras.models import Model

image_input = Input((64,64,3))
x = Conv2D(32, kernel_size=8, strides=4)(image_input)
x = Flatten()(x)
x = Dense(64)(x)

vector_input = Input((10,))
y = Dense(64)(vector_input)

z = concatenate([x, y])
z = Dense(64)(z)
z = Activation('softmax')(z)

model = Model([image_input, vector_input], [z])
</code>```

Body:
Tensorflow supports deep networks with multiple inputs. Here's a toy example of a network with image and vector input:

from tensorflow.keras.layers import Input, Conv2D, Dense, Activation, Flatten, concatenate
from tensorflow.keras.models import Model

image_input = Input((64,64,3))
x = Conv2D(32, kernel_size=8, strides=4)(image_input)
x = Flatten()(x)
x = Dense(64)(x)

vector_input = Input((10,))
y = Dense(64)(vector_input)

z = concatenate([x, y])
z = Dense(64)(z)
z = Activation('softmax')(z)

model = Model([image_input, vector_input], [z])


问:
How to place multiple invisible links over one picture in html?
I am making a website using flask and want an image where clicking different parts of this will take you to different links. Is this possible? Even somewhere I could start figuring out something like this would be great thanks!</p>

答: What you're looking for is the area tag in HTML: https://www.w3schools.com/tags/tag_area.asp


问:
SQL subtract two columns giving error- Invalid operator for data type. Operator equals subtract, type equals nvarchar
I am trying to subtract 2 columns in a database table and call the column calc, and its giving me an error:

Invalid operator for data type. Operator equals subtract, type equals nvarchar.

Anyone shed some light on this? Thanks.

```<code>
SELECT
      ,[old]
      ,[new]
       , (new - old) as calc
    FROM database
</code>```

database:

what i want to show with calc column:

答:
Try:</p>

```<code>SELECT
  ,[old]
  ,[new]
   , (numeric(new) - numeric(old)) as calc
FROM database
</code>```

Body:
I am trying to subtract 2 columns in a database table and call the column calc, and its giving me an error:

Invalid operator for data type. Operator equals subtract, type equals nvarchar.

Anyone shed some light on this? Thanks.

SELECT
      ,[old]
      ,[new]
       , (new - old) as calc
    FROM database

database:

what i want to show with calc column:

Body:
Try:

SELECT
  ,[old]
  ,[new]
   , (numeric(new) - numeric(old)) as calc
FROM database


问:
Plotting lines connecting points
I know there is another very similar question, but I could not extract the information I need from it.

plotting lines in pairs

I have 4 points in the (x,y) plane: x=[x1,x2,x3,x4] and y=[y1,y2,y3,y4]

```<code>x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]
</code>```

Now, I can plot the four points by doing:

```<code>import matplotlib.pyplot as plt

plt.plot(x,y, 'ro')
plt.axis('equal')
plt.show()
</code>```

But, apart from the four points, I would like to have 2 lines:

1) one connecting (x1,y1) with (x2,y2) and
2) the second one connecting (x3,y3) with (x4,y4).

This is a simple toy example. In the real case I have 2N points in the plane.

How can I get the desired output: for points with two connecting lines ?

Thank you.

答:
I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')
```

<p>Have a long list of x's and y's, and want to connect adjacent pairs?</p>

<pre class="lang-py prettyprint-override"><code>xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])
</code>```

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')
```

Title: Plotting lines connecting points

Body:
I know there is another very similar question, but I could not extract the information I need from it.

plotting lines in pairs

I have 4 points in the (x,y) plane: x=[x1,x2,x3,x4] and y=[y1,y2,y3,y4]

x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]

Now, I can plot the four points by doing:

import matplotlib.pyplot as plt

plt.plot(x,y, 'ro')
plt.axis('equal')
plt.show()

But, apart from the four points, I would like to have 2 lines:

1) one connecting (x1,y1) with (x2,y2) and
2) the second one connecting (x3,y3) with (x4,y4).

This is a simple toy example. In the real case I have 2N points in the plane.

How can I get the desired output: for points with two connecting lines ?

Thank you.

Body:
I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')


答:
You may

handle the case with use of DateTimeFormatterBuilder

.parseCaseInsensitive() for the case of the month, MMM is for Jan and you have JAN

.appendPattern("MMMdd/yyyy") for the pattern

parse into a LocalDate as there is no time composant

```<code>DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("MMMdd/yyyy");
DateTimeFormatter dateFormat = builder.toFormatter();

LocalDate dateTime = LocalDate.parse("JAN14/2020", dateFormat);
System.out.println(dateTime); // 2020-01-14
</code>```

CODE DEMO

Title: What pattern of datetimeformat is needed for DateTimeFormatter to parse JAN01/2020?

Body:
You may

handle the case with use of DateTimeFormatterBuilder

.parseCaseInsensitive() for the case of the month, MMM is for Jan and you have JAN

.appendPattern("MMMdd/yyyy") for the pattern

parse into a LocalDate as there is no time composant

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("MMMdd/yyyy");
DateTimeFormatter dateFormat = builder.toFormatter();

LocalDate dateTime = LocalDate.parse("JAN14/2020", dateFormat);
System.out.println(dateTime); // 2020-01-14

CODE DEMO


问:
Looking for syntax to traverse all the nested tags in ElementTree.findall() in python
Plz bear with me I am struggling with xml and ElementTree from python. I have posted a question: How to use Element.findall() to search for a tag and print its value and provided solution worked fine however later I realized that namespace was registered on <parent> tag. I had no idea how that piece of data would change the game plan.

```<code><parent xmlns="http://xmlns.test.com/parent" version="1">
</code>```

Having namespace, this findall('./*/c/d') no longer finds nested tag (i.e. c/d). Reading more threads in here I realized that I have to prepend with namespace like this.

```<code>def search(root, wordToSearch):
  tags = root.findall('{http://xmlns.test.com/parent}first')
  print tags
</code>```

Above code will find <first> tag for sure however I am hoping to have catch all path something like (./*/c/d) that would traverse <first> then <second> tag.

My concern is xml could have third or even more tag under <parent> in the future. Is there way I can pull this off without using lxml library? Btw - I have both python 2.6.6 and 2.7.18 in rhel server I am running the script.

[update]

Fortunately I was able to find a solution with ElementTree 1.3.

```<code>def search(root, wordToSearch):
   for child in root: # child represents first and second tag
     el = child.tag.split('}', 1)[1] # Remove namespace
     el_path = 'xmlns:{0}/xmlns:c/xmlns:d'.format(el)
     target_tags = root.findall(el_path, namespaces={'xmlns': 'http://...'})
</code>```

答:
Does this work for you?

from bs4 import BeautifulSoup

def get_texts(root, tag_name):
    return [tag.get_text() for tag in root.find_all(tag_name)]

soup = BeautifulSoup(open('test.xml').read(), features="lxml")
print(get_texts(soup, 'd'))
print(get_texts(soup, 'f'))
```

<p>Output:</p>

```['987', '345']
['xxx', 'yyy', 'zzz', 'ttt', 'hhh', 'www']
```

Here's the package: https://pypi.org/project/beautifulsoup4/

Body:
Plz bear with me I am struggling with xml and ElementTree from python. I have posted a question: How to use Element.findall() to search for a tag and print its value and provided solution worked fine however later I realized that namespace was registered on <parent> tag. I had no idea how that piece of data would change the game plan.

<parent xmlns="http://xmlns.test.com/parent" version="1">

Having namespace, this findall('./*/c/d') no longer finds nested tag (i.e. c/d). Reading more threads in here I realized that I have to prepend with namespace like this.

def search(root, wordToSearch):
  tags = root.findall('{http://xmlns.test.com/parent}first')
  print tags

Above code will find <first> tag for sure however I am hoping to have catch all path something like (./*/c/d) that would traverse <first> then <second> tag.

My concern is xml could have third or even more tag under <parent> in the future. Is there way I can pull this off without using lxml library? Btw - I have both python 2.6.6 and 2.7.18 in rhel server I am running the script.

[update]

Fortunately I was able to find a solution with ElementTree 1.3.

def search(root, wordToSearch):
   for child in root: # child represents first and second tag
     el = child.tag.split('}', 1)[1] # Remove namespace
     el_path = 'xmlns:{0}/xmlns:c/xmlns:d'.format(el)
     target_tags = root.findall(el_path, namespaces={'xmlns': 'http://...'})

Body:
Does this work for you?

from bs4 import BeautifulSoup

def get_texts(root, tag_name):
    return [tag.get_text() for tag in root.find_all(tag_name)]

soup = BeautifulSoup(open('test.xml').read(), features="lxml")
print(get_texts(soup, 'd'))
print(get_texts(soup, 'f'))

Output:

['987', '345']
['xxx', 'yyy', 'zzz', 'ttt', 'hhh', 'www']

Here's the package: https://pypi.org/project/beautifulsoup4/


问:
How do I reference libraries in NetBeans?
I have a Java Web Services project that was created in an older version of NetBeans, and I haven't accessed it in many months, so my paths and installed libraries are different.

When I try to open the project, I get a "Resolve Reference Problems" dialog, and two Reference Problems are listed:

```<code>"metro" library could not be found
"JAX-WS-ENDORSED" library could not be found
</code>```

I have a fresh installation of JDK 6 Update 25 with NetBeans 7.0, and am running Windows 7.

What steps can I take to solve this? I don't even know where to start, as every approach I've taken so far hasn't gotten me anywhere.

Note: JAX-WS-ENDORSED does not appear in my Libraries listing, so I can't remove it. Something hidden is referencing it.  How would I find this?

答:
Netbeans maintains a set of libraries, which are simply a convenient way to manage groups of related jar files. Start by clicking Tools > Libraries. You will see the library manager window.

You will see the options to add your own libraries if you have jar files downloaded. If you do not see the library that you are looking for you can download them and add them your self. Once the library exist in Netbeans you can go to the Project Explorer window and right click on the Libraries tab of your project. Select Add Library and you will have the chance to add the library that you added in the library manager.

Body:
I have a Java Web Services project that was created in an older version of NetBeans, and I haven't accessed it in many months, so my paths and installed libraries are different.

When I try to open the project, I get a "Resolve Reference Problems" dialog, and two Reference Problems are listed:

"metro" library could not be found
"JAX-WS-ENDORSED" library could not be found

I have a fresh installation of JDK 6 Update 25 with NetBeans 7.0, and am running Windows 7.

What steps can I take to solve this? I don't even know where to start, as every approach I've taken so far hasn't gotten me anywhere.

Note: JAX-WS-ENDORSED does not appear in my Libraries listing, so I can't remove it. Something hidden is referencing it.  How would I find this?


问:
how to copy only one row within cells of multiple rows in LIbreoffice calc?
I have large number of cells with multiples rows in each cells. Is there any command or regex or formula to copy only 1st or 2nd rows within cells from a large no of cells?  </p>

答:
Use Conditional Formatting, C2: L2 Duplicate, then copy this area to the other C3:Cn line, and paste format only.

Duplicates per line will be identified, by the chosen color, delete the discarded one.

Note: Identifies only identical values, if not spelled differently.
TestFile


问:
PHP disable caching for specific header?
I'm wanting to send a response header with PHP, but I don't want that specific header to be cached by browsers.

Is there any way to specific a header and disable caching it, but still cache everything else as usual?

答: You can instruct the browser in terms of caching behaviour using Cache-Control header, see here docs. But, that beeing said, you cannot instruct it on specific headers. That is the kind of logic that a CDN or a caching server like Varnish would implement and is not something you will do in PHP.


问:
Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel)
This is my default Serilog configuration

```<code>SeriLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.ControlledBy(SeriLogLevelSwitch)
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
    .Enrich.FromLogContext()
     ....
</code>```

How can i change the loglevel to Debug for a specific namespace at runtime when the default is Information?

答:
Each of your MinimumLevel.Override can have its own LoggingLevelSwitch, which allows you to control the log level for each particular override at run-time.

Create individual LoggingLevelSwitch for each override that you intend to modify whilst the app is running, and store these instances in a place that you can access from other parts of your application, which will allow you to change the MinimumLevel of these LoggingLevelSwitch(es).

e.g.

```<code>public class LoggingLevelSwitches
{
    // Logging level switch that will be used for the "Microsoft" namespace
    public static readonly LoggingLevelSwitch MicrosoftLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Warning);

    // Logging level switch that will be used for the "Microsoft.Hosting.Lifetime" namespace
    public static readonly LoggingLevelSwitch MicrosoftHostingLifetimeLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Information);
}
</code>```

Configure your Serilog logging pipeline to use these LoggingLevelSwitch instances:

```<code>static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LoggingLevelSwitches.MicrosoftLevelSwitch)
        .MinimumLevel.Override("Microsoft.Hosting.Lifetime",
            LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch)
        .Enrich.FromLogContext()
        .CreateLogger();

    // ...
}
</code>```

Then somewhere in your application, for example, in the code that handles your application configuration that can be changed at run-time, update the LoggingLevelSwitch instance(s) to the new LogEventLevel that you want:

```<code>public class AppSettings
{
    void ChangeLoggingEventLevel()
    {
        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Error;

        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Warning;

        // ...
    }
}
</code>```

As you can see, the LogEventLevel is controlled by the LoggingLevelSwitch instances, so it's up to you to decide where in your application (and how) these instances will be modified, to affect the logging pipeline.

The example above I'm assuming you have a screen (or API) in your application that a user would be able to configure the logging levels.

If you don't have that, then another approach is to have a background thread that periodically checks a configuration file, an environment variable, or query a database, etc. to determine what these logging levels should be.

If you're using a .NET Core Host, you can use the Options pattern which can handle the refresh of the configuration for you, and allow you to execute code when the configuration changes (where you'd change the MinimumLevel of your LoggingLevelSwitch(es) you have.

Body:
This is my default Serilog configuration

SeriLogLevelSwitch.MinimumLevel = LogEventLevel.Information;
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.ControlledBy(SeriLogLevelSwitch)
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
    .Enrich.FromLogContext()
     ....

How can i change the loglevel to Debug for a specific namespace at runtime when the default is Information?

Body:
Each of your MinimumLevel.Override can have its own LoggingLevelSwitch, which allows you to control the log level for each particular override at run-time.

Create individual LoggingLevelSwitch for each override that you intend to modify whilst the app is running, and store these instances in a place that you can access from other parts of your application, which will allow you to change the MinimumLevel of these LoggingLevelSwitch(es).

e.g.

public class LoggingLevelSwitches
{
    // Logging level switch that will be used for the "Microsoft" namespace
    public static readonly LoggingLevelSwitch MicrosoftLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Warning);

    // Logging level switch that will be used for the "Microsoft.Hosting.Lifetime" namespace
    public static readonly LoggingLevelSwitch MicrosoftHostingLifetimeLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Information);
}

Configure your Serilog logging pipeline to use these LoggingLevelSwitch instances:

static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LoggingLevelSwitches.MicrosoftLevelSwitch)
        .MinimumLevel.Override("Microsoft.Hosting.Lifetime",
            LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch)
        .Enrich.FromLogContext()
        .CreateLogger();

    // ...
}

Then somewhere in your application, for example, in the code that handles your application configuration that can be changed at run-time, update the LoggingLevelSwitch instance(s) to the new LogEventLevel that you want:

public class AppSettings
{
    void ChangeLoggingEventLevel()
    {
        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Error;

        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Warning;

        // ...
    }
}

As you can see, the LogEventLevel is controlled by the LoggingLevelSwitch instances, so it's up to you to decide where in your application (and how) these instances will be modified, to affect the logging pipeline.

The example above I'm assuming you have a screen (or API) in your application that a user would be able to configure the logging levels.

If you don't have that, then another approach is to have a background thread that periodically checks a configuration file, an environment variable, or query a database, etc. to determine what these logging levels should be.

If you're using a .NET Core Host, you can use the Options pattern which can handle the refresh of the configuration for you, and allow you to execute code when the configuration changes (where you'd change the MinimumLevel of your LoggingLevelSwitch(es) you have.


问:
Is there a way change an array to a string, split the values at a comma, and join each value via a new line?
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

```<code>const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));
</code>```

Array:

EDITED (5/28 2:52 pm): From object to array.

```<code>const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];
</code>```

Current console log:

```<code>[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]
</code>```

答:
Try JSON.stringify(results).split(",").join("\n").

JSON.stringify() will return a string of the array as you showed in the request.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

But, as others in the comment said, if in your function you end up returning the string representation, .map() breaks because it is not an array.

It's better if you make another function to display the data, and keep the recursive function as is.

As @Omri Attiya said, to get a string from the array you can just use results.join('\n').

```<code>function getArrayAsString(array){
return array.join('\n');
}
</code>```

Body:
I am writing a recursive function that prints an org chart. When logging, this function displays the hierarchy of the chart by adding spaces to the beginning of "subKeys".

Problem:
I am having trouble logging the array as a string and splitting the array and joining it with "\n".

Question:
Is there a way to implement .toString().split(",").join("\n") to results?

I've tried return results.toString().split(",").join("\n") under // Base case and have been receiving a TypeError, TypeError: subKeys.map is not a function.

const displayOrgChart = (orgChart) => {

  let results = [];

  // General case
  for (let member in orgChart) {
    if (typeof orgChart[member] === "object") {
      let subKeys = displayOrgChart(orgChart[member]);
      results = results.concat(subKeys.map(subKey => {
        return "  " + subKey;
      }))
    } else {
      results.push(orgChart[member]);
    }
  }

  // Base case
  return results
};

console.log(displayOrgChart(orgChart));

Array:

EDITED (5/28 2:52 pm): From object to array.

const orgChart = [
  {
    0: {
      name: "Zuckerberg",
      children: {
        0: {
          name: "Schroepfer",
          children: {
            0: {
              name: "Bosworth",
              children: {
                0: {
                  name: "Steve",
                },
                1: {
                  name: "Kyle",
                },
                2: {
                  name: "Andra",
                },
              },
            },
            1: {
              name: "Zhao",
              children: {
                0: {
                  name: "Richie",
                },
                1: {
                  name: "Sofia",
                },
                2: {
                  name: "Jen",
                },
              },
            },
          },
        },
        1: {
          name: "Schrage",
          children: {
            0: {
              name: "VanDyck",
              children: {
                0: {
                  name: "Sabrina",
                },
                1: {
                  name: "Michelle",
                },
                2: {
                  name: "Josh",
                },
              },
            },
            1: {
              name: "Swain",
              children: {
                0: {
                  name: "Blanch",
                },
                1: {
                  name: "Tom",
                },
                2: {
                  name: "Joe",
                },
              },
            },
          },
        },
        2: {
          name: "Sandberg",
          children: {
            0: {
              name: "Goler",
              children: {
                0: {
                  name: "Eddie",
                },
                1: {
                  name: "Julie",
                },
                2: {
                  name: "Annie",
                },
              },
            },
            1: {
              name: "Hernandez",
              children: {
                0: {
                  name: "Rowi",
                },
                1: {
                  name: "Inga",
                },
                2: {
                  name: "Morgan",
                },
              },
            },
            2: {
              name: "Moissinac",
              children: {
                0: {
                  name: "Amy",
                },
                1: {
                  name: "Chuck",
                },
                2: {
                  name: "Vinni",
                },
              },
            },
            3: {
              name: "Kelley",
              children: {
                0: {
                  name: "Eric",
                },
                1: {
                  name: "Ana",
                },
                2: {
                  name: "Wes",
                },
              },
            },
          },
        },
      },
    },
  },
];

Current console log:

[
  '    Zuckerberg',
  '        Schroepfer',
  '            Bosworth',
  '                Steve',
  '                Kyle',
  '                Andra',
  '            Zhao',
  '                Richie',
  '                Sofia',
  '                Jen',
  '        Schrage',
  '            VanDyck',
  '                Sabrina',
  '                Michelle',
  '                Josh',
  '            Swain',
  '                Blanch',
  '                Tom',
  '                Joe',
  '        Sandberg',
  '            Goler',
  '                Eddie',
  '                Julie',
  '                Annie',
  '            Hernandez',
  '                Rowi',
  '                Inga',
  '                Morgan',
  '            Moissinac',
  '                Amy',
  '                Chuck',
  '                Vinni',
  '            Kelley',
  '                Eric',
  '                Ana',
  '                Wes'
]

Body:
Try JSON.stringify(results).split(",").join("\n").

JSON.stringify() will return a string of the array as you showed in the request.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

But, as others in the comment said, if in your function you end up returning the string representation, .map() breaks because it is not an array.

It's better if you make another function to display the data, and keep the recursive function as is.

As @Omri Attiya said, to get a string from the array you can just use results.join('\n').

function getArrayAsString(array){
return array.join('\n');
}


问:
ActionDispatch::ClosedError when testing Rails 3.1 model creation (RSpec/Cucumber)
I am creating a web application with Ruby on Rails 3.1 (RC1). I am using Factory Girl, RSpec and Cucumber (with Capybara) for testing, but I am experiencing unexpected raised ActionDispatch::ClosedErrors some of the times (not every time) when I am creating new users (through the User model's create action). Below is the error message that I get:

```<code>Cannot modify cookies because it was closed. This means it was already streamed
back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)
</code>```

The error is raised when using these ways of creating users:

Creation using Factory Girl

Factory.create( :user )

Factory.build( :user ).save

Basic creation

User.create( { ... } )

User.new( { ... } ).save

What is funny is that they do work during some test, but not in others, and it does not seem random, although I cannot figure out the reason. Below is an excerpt from my code:

users_controller_spec.rb

    require 'spec_helper'

```<code>def user
  @user ||= Factory.create( :user )
end

def valid_attributes
  Factory.attributes_for :user
end

describe UsersController do

  describe 'GET index' do
    it 'assigns all users as @users' do
      users = [ user ] # The call to user() raises the error here
      get :index
      assigns[ :users ].should == users
    end
  end

  describe 'GET show' do
    it 'assigns the requested user as @user' do
      get :show, id: user.id # The call to user() raises the error here
      assigns[ :user ].should == user
    end
  end
</code>```

However, the error is not raised in the following code block:

    describe 'GET edit' do
      it 'assigns the requested user as @user' do
        get :edit, id: user.id # This raises no error
        assigns[ :user ].should == user
      end
    end

Any other method below this does not raise the error, even though I am creating users in the exact same way.

Any suggestions to what I might be doing wrong would be greatly appreciated!

答:
This is due to the way rails 3 streams the response now. They posted a fix in edge for the same issue in flash but not in cookies yet. For now I have turned off my request specs. I am going to look at the problem this weekend if no one gets to it before then.

https://github.com/rails/rails/issues/1452

Body:
I am creating a web application with Ruby on Rails 3.1 (RC1). I am using Factory Girl, RSpec and Cucumber (with Capybara) for testing, but I am experiencing unexpected raised ActionDispatch::ClosedErrors some of the times (not every time) when I am creating new users (through the User model's create action). Below is the error message that I get:

Cannot modify cookies because it was closed. This means it was already streamed
back to the client or converted to HTTP headers. (ActionDispatch::ClosedError)

The error is raised when using these ways of creating users:

Creation using Factory Girl

Factory.create( :user )

Factory.build( :user ).save

Basic creation

User.create( { ... } )

User.new( { ... } ).save

What is funny is that they do work during some test, but not in others, and it does not seem random, although I cannot figure out the reason. Below is an excerpt from my code:

users_controller_spec.rb

    require 'spec_helper'

def user
  @user ||= Factory.create( :user )
end

def valid_attributes
  Factory.attributes_for :user
end

describe UsersController do

  describe 'GET index' do
    it 'assigns all users as @users' do
      users = [ user ] # The call to user() raises the error here
      get :index
      assigns[ :users ].should == users
    end
  end

  describe 'GET show' do
    it 'assigns the requested user as @user' do
      get :show, id: user.id # The call to user() raises the error here
      assigns[ :user ].should == user
    end
  end

However, the error is not raised in the following code block:

    describe 'GET edit' do
      it 'assigns the requested user as @user' do
        get :edit, id: user.id # This raises no error
        assigns[ :user ].should == user
      end
    end

Any other method below this does not raise the error, even though I am creating users in the exact same way.

Any suggestions to what I might be doing wrong would be greatly appreciated!


问:
How can I store dynamically a vector in a For iterator Simulink Subsystem?
I have this simple system:

The code in the function is:

```<code>function a = fcn(iteration,a)
a(1,iteration) = iteration;
end
</code>```

The outside Simulink layer is the following (a is initialized as a = zeros(1,5)):

The loop is:

```<code>for i = 1:5
</code>```

and I want to store the iterator in an array (i.e. [1 2 3 4 5]), but for some reason Simulink initializes the array at every iterator step for a single time step, so I can only see the last value.
I have tried many different combinations, but I cannot make it work the way I want. How to do it?

答:
With every iteration the MATLAB Function starts from the initial array, the input port. To prevent this, just add a loop with a delay.
The output of the MATLAB Function should feed the delay as well as the output port. This ensures the result of the last iteration is also available.
You can use the resettable delay with an external initial condition to start with the input value and update that during every iteration.

Body:
I have this simple system:

The code in the function is:

function a = fcn(iteration,a)
a(1,iteration) = iteration;
end

The outside Simulink layer is the following (a is initialized as a = zeros(1,5)):

The loop is:

for i = 1:5

and I want to store the iterator in an array (i.e. [1 2 3 4 5]), but for some reason Simulink initializes the array at every iterator step for a single time step, so I can only see the last value.
I have tried many different combinations, but I cannot make it work the way I want. How to do it?


问:
Jenkins pipelines trigger one after another
Can we execute one pipeline from Jenkins and trigger another pipeline with inputdata from previous pipeline? If Yes, will you please provide me how?</p>

答:
Yes, you can do that. Let’s say there are two pipeline i.e. jobA and jobB.
Let us assume jobA is the upstream pipeline for jobB i.e. jobB will be called or build by jobA with parameters (or input parameters from jobA).

Follow the steps below:

1) create both upstream pipeline jobA and downstream piepeline jobB (which will be called by jobA)

2) In jobB, Check the box “This project is parameterized” in configure page.

3) Click on Add Parameter drop-down and select String Parameter.

4) Fill in the name, default value and description.

5) Click on Apply and Save.

6) Go to the pipeline jobA. Create a stage similar to the stage given below in your Jenkinsfile or Pipeline as a code section.

```<code>pipeline {
     agent any
     stages {

     stage ('Build JobB')
     {
        steps {
            build job: 'jobB', parameters: [string(name: ‘Environment', value: "production")]
        }
    }
 }
}
</code>```

In this way, you can trigger Jenkins pipeline one after another.

Note: I have use declarative pipeline as code for the example. If you have, scripted pipeline or freestyle project, follow the steps upto step 5 and change the step 6 according to your pipeline.

Body:
Yes, you can do that. Let’s say there are two pipeline i.e. jobA and jobB.
Let us assume jobA is the upstream pipeline for jobB i.e. jobB will be called or build by jobA with parameters (or input parameters from jobA).

Follow the steps below:

1) create both upstream pipeline jobA and downstream piepeline jobB (which will be called by jobA)

2) In jobB, Check the box “This project is parameterized” in configure page.

3) Click on Add Parameter drop-down and select String Parameter.

4) Fill in the name, default value and description.

5) Click on Apply and Save.

6) Go to the pipeline jobA. Create a stage similar to the stage given below in your Jenkinsfile or Pipeline as a code section.

pipeline {
     agent any
     stages {

     stage ('Build JobB')
     {
        steps {
            build job: 'jobB', parameters: [string(name: ‘Environment', value: "production")]
        }
    }
 }
}

In this way, you can trigger Jenkins pipeline one after another.

Note: I have use declarative pipeline as code for the example. If you have, scripted pipeline or freestyle project, follow the steps upto step 5 and change the step 6 according to your pipeline.