问:
Streaming HTML from Java web application
How to achieve continuous HTML streaming in a Java web application?

Like, making the page keep on loading (indicates) and push data from server.

答: Depending on whether you're talking about doing content replacement (multipart/replace) or doing Comet-style push you can look at http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartResponse.html (for multipart replacement: some IP cameras use similar techniques to do crude video) or look at things like http://tomcat.apache.org/tomcat-6.0-doc/aio.html or http://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3 for Comet streaming.</p>


来源: stackexchange

问:
How to capture elements that display after button click - Python and Selenium used
On my local email-provider, i wanted to check if my desired email-name is free for registration or not with using a easy python script:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions  # as EC
import time

def checkmymail():
    s=Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=s)
    driver.get('https://meinkonto.telekom-dienste.de/telekom/email/registration/registration.xhtml')
    alias1 = driver.find_element(By.ID, 'j_idt58:j_idt98:j_idt100:j_idt101:j_idt108:emailAlias')
    alias1.send_keys("mywishmail25")
    sendb = driver.find_element(By.ID, 'j_idt58:j_idt98:j_idt100:j_idt148:checkEmailAlias')
    sendb.click()
    time.sleep(5)
    availability1 = driver.find_element(By.CLASS_NAME, 'form-input-plates')
    print(availability1)

checkmymail()
</code>```

On this emailprovider a message box with text displays after clicking the confirmation-button which either says (in german) "this email is free for registration" (green text) or "this email isnt free" (in red text)

i try to capture and print the text box that opens up after clicking the button, but neither with using the ID or the Class name i have success in getting the element output.

How to achieve to capture this special type of element?

答:
First
To manage to capture that message XPath , from your browser there is execution window next to network
Try to add stop point and take the full XPath

Second , try to find that element in the XPath helper
If you find it than you should be able to get element

If not and that is probably the case than you should check if there is any table or iframe  before the element than you should change your drive to the new frame

What you get ?

ContentLicense: CC BY-SA 4.0

Body:
On my local email-provider, i wanted to check if my desired email-name is free for registration or not with using a easy python script:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions  # as EC
import time

def checkmymail():
    s=Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=s)
    driver.get('https://meinkonto.telekom-dienste.de/telekom/email/registration/registration.xhtml')
    alias1 = driver.find_element(By.ID, 'j_idt58:j_idt98:j_idt100:j_idt101:j_idt108:emailAlias')
    alias1.send_keys("mywishmail25")
    sendb = driver.find_element(By.ID, 'j_idt58:j_idt98:j_idt100:j_idt148:checkEmailAlias')
    sendb.click()
    time.sleep(5)
    availability1 = driver.find_element(By.CLASS_NAME, 'form-input-plates')
    print(availability1)

checkmymail()

On this emailprovider a message box with text displays after clicking the confirmation-button which either says (in german) "this email is free for registration" (green text) or "this email isnt free" (in red text)

i try to capture and print the text box that opens up after clicking the button, but neither with using the ID or the Class name i have success in getting the element output.

How to achieve to capture this special type of element?


问:
Plotting piecewise functions using Matplotlib
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The above error is what I got for the below code intended to plot the piecewise function created. Can't figure it out.

```<code>import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000)
ylist = f(xlist)

plt.plot(ylist,xlist)
plt.show()
</code>```

答:
What I understood is , you are basically comparing an array with a number which should not be the case here, the code provided might help you with solution,</p>
```<code>import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000,endpoint=False)
ylist = np.array([f(num) for num in xlist])

plt.plot(xlist,ylist)
plt.show()
</code>```

Body:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The above error is what I got for the below code intended to plot the piecewise function created. Can't figure it out.

import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000)
ylist = f(xlist)

plt.plot(ylist,xlist)
plt.show()

Body:
What I understood is , you are basically comparing an array with a number which should not be the case here, the code provided might help you with solution,

import numpy as np
import matplotlib.pyplot as plt
def f(x):
    if x>=0 and x<=1:
        return x
    elif x>1 and x<=2:
        return 2-x
    else:
        return 0

xlist = np.linspace(0,1,num = 1000,endpoint=False)
ylist = np.array([f(num) for num in xlist])

plt.plot(xlist,ylist)
plt.show()


答:
As per comments, you need to vectorize your method f (and also fix some mistakes):

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

def f(x):
    y = np.empty_like(x)
    mask1 = (0 <= x) & (x <= 1)
    mask2 = (1 < x) & (x <= 2)
    mask3 = np.logical_not((0 <= x) & (x <= 2)) #or ~((0 <= x) & (x <= 2))
    y[mask1] = x[mask1]
    y[mask2] = 2 - x[mask2]
    y[mask3] = 0
    return y

xlist = np.linspace(-1, 3, num = 1000)
ylist = f(xlist)

plt.plot(xlist, ylist)
plt.show()
</code>```

You might also find that mask3 is not necessarry and vectorize a method f like this:

```<code>def f(x):
    y = np.full_like(x, fill_value=0) #or np.zeros_like(x)
    mask1 = (0 <= x) & (x <= 1)
    mask2 = (1 < x) & (x <= 2)
    y[mask1] = x[mask1]
    y[mask2] = 2 - x[mask2]
    return y
</code>```

Title: Plotting piecewise functions using Matplotlib

Body:
As per comments, you need to vectorize your method f (and also fix some mistakes):

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    y = np.empty_like(x)
    mask1 = (0 <= x) & (x <= 1)
    mask2 = (1 < x) & (x <= 2)
    mask3 = np.logical_not((0 <= x) & (x <= 2)) #or ~((0 <= x) & (x <= 2))
    y[mask1] = x[mask1]
    y[mask2] = 2 - x[mask2]
    y[mask3] = 0
    return y

xlist = np.linspace(-1, 3, num = 1000)
ylist = f(xlist)

plt.plot(xlist, ylist)
plt.show()

You might also find that mask3 is not necessarry and vectorize a method f like this:

def f(x):
    y = np.full_like(x, fill_value=0) #or np.zeros_like(x)
    mask1 = (0 <= x) & (x <= 1)
    mask2 = (1 < x) & (x <= 2)
    y[mask1] = x[mask1]
    y[mask2] = 2 - x[mask2]
    return y


问:
Flask / WTForms / Jinja2 - preserve form data from HTML url call
I am trying to preserve the information from a login form made in Flask when a resend verification button is pressed in HTML. The issue is that button redirects the page without preserving the login information already typed.

As such, is there a way to save / repopulate a form in in Jinja2 / HTML?
Apologies if this is badly phrased, I am very new to web development.

Here is the associated code -
auth.py (within function signup()):

```<code> if request.method == 'GET':
    verificationCode = str(random.randint(1000, 9999))
    print("Generating: {}".format(verificationCode))
    ret = oled.postPopup(popupRequest(priority=0, time=30, title="Signup Code", message=verificationCode))
    if "Error" in ret:
        flash("Error: Please try again later")
</code>```

signup.html:

```<code><span style="float:right;">
     <a href="{{ url_for('auth_bp.signup') }}">Resend Verification</a>
</span>
</code>```

My attempts so far have consisted of saving the information via SessionStorage and repopulating when the form is called again, and calling a new version of the verificationCode function within the Jinja2 HTML (currently working on this).

Thank you, H.

答:
Found a solution: instead of creating a dict or storing the individual elements on the page I decided to call the Python function directly from within the HTML file. In the corresponding app.py (where the render template is defined), according to the Flask documentation, the resendVerification function (posted above) needs to be declared in a wrapper, like so:

```<code>@main_bp.context_processor
def utility_processor():
    def resendVerification():
        // function code
        pass
return dict(resendVerification=resendVerification)
</code>```

And called within the {% block content %} using:

```<code>{{ resendVerification() }}
</code>```

Body:
I am trying to preserve the information from a login form made in Flask when a resend verification button is pressed in HTML. The issue is that button redirects the page without preserving the login information already typed.

As such, is there a way to save / repopulate a form in in Jinja2 / HTML?
Apologies if this is badly phrased, I am very new to web development.

Here is the associated code -
auth.py (within function signup()):

 if request.method == 'GET':
    verificationCode = str(random.randint(1000, 9999))
    print("Generating: {}".format(verificationCode))
    ret = oled.postPopup(popupRequest(priority=0, time=30, title="Signup Code", message=verificationCode))
    if "Error" in ret:
        flash("Error: Please try again later")

signup.html:

     Resend Verification

My attempts so far have consisted of saving the information via SessionStorage and repopulating when the form is called again, and calling a new version of the verificationCode function within the Jinja2 HTML (currently working on this).

Thank you, H.

Body:
Found a solution: instead of creating a dict or storing the individual elements on the page I decided to call the Python function directly from within the HTML file. In the corresponding app.py (where the render template is defined), according to the Flask documentation, the resendVerification function (posted above) needs to be declared in a wrapper, like so:

@main_bp.context_processor
def utility_processor():
    def resendVerification():
        // function code
        pass
return dict(resendVerification=resendVerification)

And called within the {% block content %} using:

{{ resendVerification() }}


问:
Microsoft.Data.SQLite: Library e_sqlite3 not found
My ASP.NET MVC (.Net Framework 4.7.2) web app using Microsoft.Data.Sqlite 5.0.2 crashes (both in debug IIS Express, and app.publish on local IIS in Windows 10) at line:

```<code>SqliteConnection dbConn = new SqliteConnection("Data Source=test.db");
</code>```

The exception thrown :

```<code>System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
  Source=Microsoft.Data.Sqlite
  StackTrace:
   at Microsoft.Data.Sqlite.SqliteConnection..ctor(String connectionString)
   at sqliteTest.Controllers.ValuesController.Get() in C:\Users\FaqeerHussain\source\repos\sqliteTest\sqliteTest\Controllers\ValuesController.cs:line 16
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
TargetInvocationException: Exception has been thrown by the target of an invocation.

Inner Exception 2:
Exception: Library e_sqlite3 not found
</code>```

e_sqlite3.dll is already in bin\runtimes\win-x64\native and bin\runtimes\win-x86\native. Tried copying x86/x64 e_sqlite3.dll to root bin folder but error remains. What should I do to get Microsoft.Data.Sqlite working?

答:
I found that the e_sqlite3.dll is located at runtimes\win-x86\native\e_sqlite3.dll.
So I created those folders and added the e_sqlite3.dll in the native folder. After that it worked!

Body:
My ASP.NET MVC (.Net Framework 4.7.2) web app using Microsoft.Data.Sqlite 5.0.2 crashes (both in debug IIS Express, and app.publish on local IIS in Windows 10) at line:

SqliteConnection dbConn = new SqliteConnection("Data Source=test.db");

The exception thrown :

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
  Source=Microsoft.Data.Sqlite
  StackTrace:
   at Microsoft.Data.Sqlite.SqliteConnection..ctor(String connectionString)
   at sqliteTest.Controllers.ValuesController.Get() in C:\Users\FaqeerHussain\source\repos\sqliteTest\sqliteTest\Controllers\ValuesController.cs:line 16
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
TargetInvocationException: Exception has been thrown by the target of an invocation.

Inner Exception 2:
Exception: Library e_sqlite3 not found

e_sqlite3.dll is already in bin\runtimes\win-x64\native and bin\runtimes\win-x86\native. Tried copying x86/x64 e_sqlite3.dll to root bin folder but error remains. What should I do to get Microsoft.Data.Sqlite working?


问:
Picking and Instancing a Class using a parameter String with Typescript
It's my first time using TypeScript and using OOP.
I've created an interface for a common brokers methods. (Buy, Sell, sell limit, buy limit)

Then i implemented this interface with my brokers API.
GBM, Bitso, IB, AmeriTrade and so on i want to instance the correct class through a received string in my end point

example: "/api/broker/:brokername"
so i created the following code:

```<code>class BrokerIgniter {

    private instance: any;

    constructor(broker: string) {

        const brokerClass: any = this.pick(broker);
        if(brokerClass) {
            this.run(brokerClass);
        }
    }

    run(ctor: new () => IExecution | IGBMExecution) {
        this.instance = new ctor();
    }

    pick(className: string) {
        const magicWand: { [K: string]: any } = {
            GBM: GBMBroker,
         };
         if (magicWand[className]) {
            return magicWand[className];
        }
        return null;
    }

    get execute() {
        return this.instance;
    }

}
</code>```

the "magicWand variable in the pick method contains a list of classes that implements my common interface (in this case there's only one, at the moment..) in my express post method:

```<code>const BrokerName = req.params.broker;
if(BrokerName) {
    const Broker = new BrokerIgniter(BrokerName);
    const hash = Broker.execute.createOrderHash('SPXL *', 100, 1);

    super.sendSuccess(res, hash, 'fine');
}
</code>```

My question is:

Is this a good way to make what i want?
there's a name or a pattern for this?
can be improved?

If there's a name for this or a pattern can you name it so that i can learn more about it? i've been checking javascript patterns but nothing found related to this.

cheers.

答:
You seem to want to be able to pass in string as the broker key, since this is coming from an API input.

That means you can declare a list of supported classes and their keys outside the BrokerIgniter class, (though a static field would work, too).

```<code>// Sort of guessing at your types here since your example is incomplete.
const brokers: Record<
  string,
  typeof IExecution | typeof IGBMExecution | undefined
> = {
  GBM: GBMBroker
}
</code>```

brokers here is typed to to take any string as an index, and return an IExecution constructor, an IGBMExecution constructor, or undefined if they key has no value.

And now BrokerIgniter can become simply this:

```<code>class BrokerIgniter {
    private instance: IExecution | IGBMExecution | undefined;

    constructor(broker: string) {
        const brokerClass = this.pick(broker);
        if(brokerClass) {
            this.run(brokerClass);
        }
    }

    run(ctor: new () => IExecution | IGBMExecution) {
        this.instance = new ctor();
    }

    pick(className: string) {
        return brokers[className] ?? null
    }

    get execute() {
        return this.instance;
    }
}
</code>```

Playground

That said, this seems like overkill. This is basically the same code.

```<code>function igniteBroker(brokerKey: string) {
  const brokerClass = brokers[brokerKey]
  return brokerClass ? new brokerClass() : null
}
</code>```

And it's a lot simpler. Maybe you intend to expand on the BrokerIgniter class a great deal. But if not, then a simple functional approach will serve you far better.

Playground

Body:
It's my first time using TypeScript and using OOP.
I've created an interface for a common brokers methods. (Buy, Sell, sell limit, buy limit)

Then i implemented this interface with my brokers API.
GBM, Bitso, IB, AmeriTrade and so on i want to instance the correct class through a received string in my end point

example: "/api/broker/:brokername"
so i created the following code:

class BrokerIgniter {

    private instance: any;

    constructor(broker: string) {

        const brokerClass: any = this.pick(broker);
        if(brokerClass) {
            this.run(brokerClass);
        }
    }

    run(ctor: new () => IExecution | IGBMExecution) {
        this.instance = new ctor();
    }

    pick(className: string) {
        const magicWand: { [K: string]: any } = {
            GBM: GBMBroker,
         };
         if (magicWand[className]) {
            return magicWand[className];
        }
        return null;
    }

    get execute() {
        return this.instance;
    }

}

the "magicWand variable in the pick method contains a list of classes that implements my common interface (in this case there's only one, at the moment..) in my express post method:

const BrokerName = req.params.broker;
if(BrokerName) {
    const Broker = new BrokerIgniter(BrokerName);
    const hash = Broker.execute.createOrderHash('SPXL *', 100, 1);

    super.sendSuccess(res, hash, 'fine');
}

My question is:

Is this a good way to make what i want?
there's a name or a pattern for this?
can be improved?

If there's a name for this or a pattern can you name it so that i can learn more about it? i've been checking javascript patterns but nothing found related to this.

cheers.

Body:
You seem to want to be able to pass in string as the broker key, since this is coming from an API input.

That means you can declare a list of supported classes and their keys outside the BrokerIgniter class, (though a static field would work, too).

// Sort of guessing at your types here since your example is incomplete.
const brokers: Record<
  string,
  typeof IExecution | typeof IGBMExecution | undefined
> = {
  GBM: GBMBroker
}

brokers here is typed to to take any string as an index, and return an IExecution constructor, an IGBMExecution constructor, or undefined if they key has no value.

And now BrokerIgniter can become simply this:

class BrokerIgniter {
    private instance: IExecution | IGBMExecution | undefined;

    constructor(broker: string) {
        const brokerClass = this.pick(broker);
        if(brokerClass) {
            this.run(brokerClass);
        }
    }

    run(ctor: new () => IExecution | IGBMExecution) {
        this.instance = new ctor();
    }

    pick(className: string) {
        return brokers[className] ?? null
    }

    get execute() {
        return this.instance;
    }
}

<a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAECSCiAPApsArgFwJYHsB20A3gFDRxKqa4EC80GATmssQL7HGiQywDiAQgFkK6bPiKk4A4SlHVodRszYcuUaNP4McAa2QNoyRBmR4AJjxFVxJMpu16Dipi3ad8EDNABGD-RAAuaAAlVBwGMwAeSU8GLDwAcwAaSQwATwAHZBwAM3JZawIAH3pM7Ly+ISsxYug0c2Qc+OQzYgA+BQk7ISD7XX0VTnB1LX6GWAS8LBMDWzJoDLiANzATaHjPMDxgZCCEAproEsqZSkOS+rNG5rMAbg556GAPJWAMcIAKXzGg2PiEgCUXUe82eeE8Pj8DAAwsMYIoABZYCAAOgyWGAOi+UIB9xB8ywOWxY1h3CBc3xjwwSNRTDwxMcpKguMk+PYjzcjzpHze4SCeGQAHdoB8gTQOvszvJjtJqtRyayQdTkSiNhgtjtOgLhbyGKK8fNOfN0ZieXCAHJgAC2u2gf0SCsp0AYyAwaAYBG+jggAG01BBLTaALrQAD8oegeDQIBAiqNZASrsMB2QouB+Jdbo99BpqvB6u2yANZHYbjBEJMngAglqhdBRo4JlMZh8AOTSVsAlFGM7IIA" rel="nofollow noreferrer">Playground

That said, this seems like overkill. This is basically the same code.

function igniteBroker(brokerKey: string) {
  const brokerClass = brokers[brokerKey]
  return brokerClass ? new brokerClass() : null
}

And it's a lot simpler. Maybe you intend to expand on the BrokerIgniter class a great deal. But if not, then a simple functional approach will serve you far better.

Playground


问:
What is the best way to access elements of parent control from a child control?
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

```<code>public enum ItemMode
{
    TRUE, FALSE, NONE
}
</code>```

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

```<code>e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);
</code>```

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

答:
There truly are many ways this could be done.  The easiest way, although some will shout "bad practice", would be to just pass a pointer to the main menu when the control is created.  Your control would have some code like this:

```<code>MenuStrip MainMenu;

internal void SetMainMenu(MenuStrip mainMenu)
{
    MainMenu = mainMenu;
}
</code>```

and when you create the control:

```<code>void CreateControl()
{
    MyUserControlType MyControl = new MyUserControlType();
    MyControl.SetMainMenu(mainMenuStrip); //or whatever you called your main menu
}
</code>```

This will give your child form unlimited access to the mainform's menu (which is why it's technically a bad practice).  From the child form you can access the submenus by name, eg:

```<code>if (MainMenu != null)
{
    ToolStripMenuItem fileMenu =
        (ToolStripMenuItem)MainMenu.Items["fileToolStripMenuItem"];
    fileMenu.DropDownItems["exportFileToolStripItem"].Visible = false;
}
</code>```

If you created the control in the designer, then you can add the SetMainMenu call into the .design file, or add it in the Form's load event.

ContentLicense: CC BY-SA 3.0

Body:
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

public enum ItemMode
{
    TRUE, FALSE, NONE
}

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

Body:
There truly are many ways this could be done.  The easiest way, although some will shout "bad practice", would be to just pass a pointer to the main menu when the control is created.  Your control would have some code like this:

MenuStrip MainMenu;

internal void SetMainMenu(MenuStrip mainMenu)
{
    MainMenu = mainMenu;
}

and when you create the control:

void CreateControl()
{
    MyUserControlType MyControl = new MyUserControlType();
    MyControl.SetMainMenu(mainMenuStrip); //or whatever you called your main menu
}

This will give your child form unlimited access to the mainform's menu (which is why it's technically a bad practice).  From the child form you can access the submenus by name, eg:

if (MainMenu != null)
{
    ToolStripMenuItem fileMenu =
        (ToolStripMenuItem)MainMenu.Items["fileToolStripMenuItem"];
    fileMenu.DropDownItems["exportFileToolStripItem"].Visible = false;
}

If you created the control in the designer, then you can add the SetMainMenu call into the .design file, or add it in the Form's load event.


问:
vue how to add attributes to vcalendar
I'm using the vcalendar for my vue-app. So far it works ok but when I try to add some attributes, they don't apply

here is my code:

<v-calendar :attributes="attributes" :available-dates="availableDates" @dayclick="dayClicked" />
```
<p>then I do this:</p>
```computed: {
  attributes() {
    return this.availableDates.map((date) => ({
       dot: {
         backgroundColor: '#FF0000',
       },
    }))
  },
}
```

but nothing happens and I don't know why. Can someone maybe help me out?

答:
I'm assuming you're trying to add a dot under all available dates in v-calendar.

attributes does not need to be computed. It should just be a data property that refers to availableDates (not mapped from it):

export default {
  data() {
    const availableDates = [ new Date() ]
    return {
      availableDates,
      attributes: [
        {
          dot: true,
          dates: availableDates,
        },
      ],
    }
  },
}
```

Since attributes.dates refers to availableDates, any changes to availableDates is automatically reflected in the attributes binding.

demo

Title: vue how to add attributes to vcalendar

Body:
I'm using the vcalendar for my vue-app. So far it works ok but when I try to add some attributes, they don't apply

here is my code:

<v-calendar :attributes="attributes" :available-dates="availableDates" @dayclick="dayClicked" />

then I do this:

computed: {
  attributes() {
    return this.availableDates.map((date) => ({
       dot: {
         backgroundColor: '#FF0000',
       },
    }))
  },
}

but nothing happens and I don't know why. Can someone maybe help me out?

Body:
I'm assuming you're trying to add a dot under all available dates in v-calendar.

attributes does not need to be computed. It should just be a data property that refers to availableDates (not mapped from it):

export default {
  data() {
    const availableDates = [ new Date() ]
    return {
      availableDates,
      attributes: [
        {
          dot: true,
          dates: availableDates,
        },
      ],
    }
  },
}

Since attributes.dates refers to availableDates, any changes to availableDates is automatically reflected in the attributes binding.

demo


问:
FE: Unit testing window.location.href changing on button click (test fails)
I am trying to test when the window.location.href changes after a button is clicked using react-testing-library. I have seen examples online where you manually update window.location.href inside of a test case as so window.location.href = 'www.randomurl.com' and then follow it with expect(window.location.href).toEqual(www.randomurl.com). While this indeed will pass, I want to avoid this as I'd rather simulate the user actions instead of injecting the new value into the test. If I do that, even if I remove my button click (which is what will actually trigger the function call) the expect will still pass because I have anyway manually updated the window.location.href in my test

What I've opted for is having goToThisPage func (which will redirect the user) to be placed outside of my functional component. I then mock goToThisPage in my test file and in my test case check whether it has been called. I do know that the goToThisPage is being triggered  because I included a console.log and when I run my tests I see it in my terminal. Nonetheless, the test still fails. I have been playing around with both spyOn and jest.doMock/mock with no luck

component.js

```<code>import React from 'react'
import { ChildComponent } from './childcomponent';
export const goToThisPage = () => {
  const url = '/url'
  window.location.href = url;
  console.log('reached');
};

export const Component = () => {
 return (<ChildComponent goToThisPage={ goToThisPage }/>)
}

export default Component;
</code>```

Test file:

```<code>  import * as Component from './component'
  import userEvent from '@testing-library/user-event';

  jest.doMock('./component', () => ({
   goToThisPage: jest.fn(),
  }));

  describe('goToThisPage', () => {
    test('should call goToThisPage when button is clicked', async () => {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
        const { container, getByTestId } = render(<Component.Component />);

        userEvent.click(screen.getByTestId('goToThisPage')); // this is successfully triggered (test id exists in child component)
        expect(goToThisPageSpy).toHaveBeenCalled();
        // expect(Component.goToThisPage()).toHaveBeenCalled(); this will fail and say that the value must be a spy or mock so I opted for using spy above
    });
});
</code>```

Note: when I try to just do jest.mock I got this error Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
When testing out with jest.doMock the error disappeared but the actual test fails.

I am open to hear more refined ideas of solving my issue if someone believes this solution could be improved. Thanks in advance

Edit:
This is another approach I have tried out

```<code>  import { Component, goToThisPage } from './component'
  import userEvent from '@testing-library/user-event';

  describe('goToThisPage', () => {
    test('should call goToThisPage when button is clicked', async () => {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
// I am not certain what I'd put as the first value in the spy. Because `goToThisPage` is an external func of <Component/> & not part of the component
        const { container, getByTestId } = render(<Component />);

        userEvent.click(screen.getByTestId('goToThisPage'));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});
</code>```

答:
Save yourself the headache and split the goToThisPage function into its own file. You seem to be mocking the goToThisPage function fine but when the Component is rendered with react testing library it doesn't seem render with the mocked function but defaults to what the function would normally do. This easiest way would be just to mock the function from its own file. If you truly want to keep the function in the same file you will need to make some adjustments, see (example #2) but I do not recommend this path.

See below for examples

Example 1: (Recommended) Split function into it's own file

Component.spec.jsx

```<code>import React from "react";
import Component from "./Component";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import * as goToThisPage from "./goToThisPage";

jest.mock('./goToThisPage');

describe("goToThisPage", () => {
    test("should call goToThisPage when button is clicked", async () => {
        const goToThisPageSpy = jest.spyOn(goToThisPage, 'default').mockImplementation(() => console.log('hi'));
        render(<Component />);
        userEvent.click(screen.getByTestId("goToThisPage"));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});
</code>```

goToThisPage.js

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

export default goToThisPage;
```
<h2>Component.jsx</h2>
```import React from "react";
import ChildComponent from "./ChildComponent";
import goToThisPage from "./goToThisPage";

export const Component = () => {
    return <ChildComponent goToThisPage={goToThisPage} />
};

export default Component;
```
<h1>Example 2: (Not Recommend for React components!)</h1>
<p>We can also get it working by calling the goToThisPage function via exports. This ensures the component is rendered with our spyOn and mockImplementation. To get this working for both browser and jest you need to ensure we run the original function if it's on browser. We can do this by creating a proxy function that determines which function to return based on a ENV that jest defines when it runs.</p>
<h2>Component.jsx</h2>
```import React from "react";
import ChildComponent from "./ChildComponent";

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

// jest worker id, if defined means that jest is running
const isRunningJest = !!process.env.JEST_WORKER_ID;

// proxies the function, if jest is running we return the function
// via exports, else return original function. This is because
// you cannot invoke exports functions in browser!
const proxyFunctionCaller = (fn) => isRunningJest ? exports[fn.name] : fn;

export const Component = () => {
    return <ChildComponent goToThisPage={proxyFunctionCaller(goToThisPage)} />
};

export default Component;
```
<h2>Component.spec.jsx</h2>
```import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("goToThisPage", () => {
    test("should call goToThisPage when button is clicked", async () => {
        const Component = require('./Component');
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage').mockImplementation(() => console.log('hi'));

        render(<Component.default />);

        userEvent.click(screen.getByTestId("goToThisPage"));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});
```
<p>You can move the function proxy to it's own file but you need to pass exports into the proxy function as exports is scoped to it's own file.</p>
<h3>Example code</h3>
```// component.js
import React from "react";
import ChildComponent from "./ChildComponent";
import proxyFunctionCaller from "./utils/proxy-function-caller";

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

export const Component = () => {
    return <ChildComponent goToThisPage={proxyFunctionCaller(typeof exports !== 'undefined' ? exports : undefined, goToThisPage)} />
};

export default Component;

// utils/proxy-function-caller.js

// jest worker id, if defined means that jest is running
const isRunningJest = !!process.env.JEST_WORKER_ID;

// proxies the function, if jest is running we return the function
// via exports, else return original function. This is because
// you cannot invoke exports functions in browser!
const proxyFunctionCaller = (exports, fn) => isRunningJest ? exports[fn.name] : fn;

export default proxyFunctionCaller;
```
<p>There are other ways to do this but I would follow the first solution as you should be splitting utility functions into it's own files anyway. Goodluck.</p>
<h2>Example 3 for @VinceN</h2>
<p>You can mock a function that lives in the same file using the below example files.</p>
<h3>SomeComponent.tsx</h3>
```import * as React from 'react';

const someFunction = () => 'hello world';

const SomeComponent = () => {
  return (

      {someFunction()}

  )
}

export default SomeComponent;

```
<h3>SomeComponent.spec.tsx</h3>
```import SomeComponent from './SomeComponent';
import { render, screen } from "@testing-library/react";

jest.mock('./SomeComponent', () => ({
  __esModule: true,
  ...jest.requireActual('./SomeComponent'),
  someFunction: jest.fn().mockReturnValue('mocked!')
}));

describe('<SomeComponent />', () => {
  it('renders', () => {
      render(<SomeComponent />);
      const el = screen.getByTestId('innards');

      expect(el.textContent).toEqual('mocked!');
  });
});
```

Body:
I am trying to test when the window.location.href changes after a button is clicked using react-testing-library. I have seen examples online where you manually update window.location.href inside of a test case as so window.location.href = 'www.randomurl.com' and then follow it with expect(window.location.href).toEqual(www.randomurl.com). While this indeed will pass, I want to avoid this as I'd rather simulate the user actions instead of injecting the new value into the test. If I do that, even if I remove my button click (which is what will actually trigger the function call) the expect will still pass because I have anyway manually updated the window.location.href in my test

What I've opted for is having goToThisPage func (which will redirect the user) to be placed outside of my functional component. I then mock goToThisPage in my test file and in my test case check whether it has been called. I do know that the goToThisPage is being triggered  because I included a console.log and when I run my tests I see it in my terminal. Nonetheless, the test still fails. I have been playing around with both spyOn and jest.doMock/mock with no luck

component.js

import React from 'react'
import { ChildComponent } from './childcomponent';
export const goToThisPage = () => {
  const url = '/url'
  window.location.href = url;
  console.log('reached');
};

export const Component = () => {
 return (<ChildComponent goToThisPage={ goToThisPage }/>)
}

export default Component;

Test file:

  import * as Component from './component'
  import userEvent from '@testing-library/user-event';

  jest.doMock('./component', () => ({
   goToThisPage: jest.fn(),
  }));

  describe('goToThisPage', () => {
    test('should call goToThisPage when button is clicked', async () => {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
        const { container, getByTestId } = render(<Component.Component />);

        userEvent.click(screen.getByTestId('goToThisPage')); // this is successfully triggered (test id exists in child component)
        expect(goToThisPageSpy).toHaveBeenCalled();
        // expect(Component.goToThisPage()).toHaveBeenCalled(); this will fail and say that the value must be a spy or mock so I opted for using spy above
    });
});

Note: when I try to just do jest.mock I got this error Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
When testing out with jest.doMock the error disappeared but the actual test fails.

I am open to hear more refined ideas of solving my issue if someone believes this solution could be improved. Thanks in advance

Edit:
This is another approach I have tried out

  import { Component, goToThisPage } from './component'
  import userEvent from '@testing-library/user-event';

  describe('goToThisPage', () => {
    test('should call goToThisPage when button is clicked', async () => {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
// I am not certain what I'd put as the first value in the spy. Because `goToThisPage` is an external func of <Component/> & not part of the component
        const { container, getByTestId } = render(<Component />);

        userEvent.click(screen.getByTestId('goToThisPage'));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});

Body:
Save yourself the headache and split the goToThisPage function into its own file. You seem to be mocking the goToThisPage function fine but when the Component is rendered with react testing library it doesn't seem render with the mocked function but defaults to what the function would normally do. This easiest way would be just to mock the function from its own file. If you truly want to keep the function in the same file you will need to make some adjustments, see (example #2) but I do not recommend this path.

See below for examples

Example 1: (Recommended) Split function into it's own file

Component.spec.jsx

import React from "react";
import Component from "./Component";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import * as goToThisPage from "./goToThisPage";

jest.mock('./goToThisPage');

describe("goToThisPage", () => {
    test("should call goToThisPage when button is clicked", async () => {
        const goToThisPageSpy = jest.spyOn(goToThisPage, 'default').mockImplementation(() => console.log('hi'));
        render(<Component />);
        userEvent.click(screen.getByTestId("goToThisPage"));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});

goToThisPage.js

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

export default goToThisPage;

Component.jsx

import React from "react";
import ChildComponent from "./ChildComponent";
import goToThisPage from "./goToThisPage";

export const Component = () => {
    return <ChildComponent goToThisPage={goToThisPage} />
};

export default Component;

Example 2: (Not Recommend for React components!)

We can also get it working by calling the goToThisPage function via exports. This ensures the component is rendered with our spyOn and mockImplementation. To get this working for both browser and jest you need to ensure we run the original function if it's on browser. We can do this by creating a proxy function that determines which function to return based on a ENV that jest defines when it runs.

Component.jsx

import React from "react";
import ChildComponent from "./ChildComponent";

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

// jest worker id, if defined means that jest is running
const isRunningJest = !!process.env.JEST_WORKER_ID;

// proxies the function, if jest is running we return the function
// via exports, else return original function. This is because
// you cannot invoke exports functions in browser!
const proxyFunctionCaller = (fn) => isRunningJest ? exports[fn.name] : fn;

export const Component = () => {
    return <ChildComponent goToThisPage={proxyFunctionCaller(goToThisPage)} />
};

export default Component;

Component.spec.jsx

import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

describe("goToThisPage", () => {
    test("should call goToThisPage when button is clicked", async () => {
        const Component = require('./Component');
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage').mockImplementation(() => console.log('hi'));

        render(<Component.default />);

        userEvent.click(screen.getByTestId("goToThisPage"));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});

You can move the function proxy to it's own file but you need to pass exports into the proxy function as exports is scoped to it's own file.

Example code

// component.js
import React from "react";
import ChildComponent from "./ChildComponent";
import proxyFunctionCaller from "./utils/proxy-function-caller";

export const goToThisPage = () => {
    const url = "/url";
    window.location.href = url;
};

export const Component = () => {
    return <ChildComponent goToThisPage={proxyFunctionCaller(typeof exports !== 'undefined' ? exports : undefined, goToThisPage)} />
};

export default Component;

// utils/proxy-function-caller.js

// jest worker id, if defined means that jest is running
const isRunningJest = !!process.env.JEST_WORKER_ID;

// proxies the function, if jest is running we return the function
// via exports, else return original function. This is because
// you cannot invoke exports functions in browser!
const proxyFunctionCaller = (exports, fn) => isRunningJest ? exports[fn.name] : fn;

export default proxyFunctionCaller;

There are other ways to do this but I would follow the first solution as you should be splitting utility functions into it's own files anyway. Goodluck.

Example 3 for @VinceN

You can mock a function that lives in the same file using the below example files.

SomeComponent.tsx

import * as React from 'react';

const someFunction = () => 'hello world';

const SomeComponent = () => {
  return (
    <div data-testid="innards">
      {someFunction()}
    </div>
  )
}

export default SomeComponent;

SomeComponent.spec.tsx

import SomeComponent from './SomeComponent';
import { render, screen } from "@testing-library/react";

jest.mock('./SomeComponent', () => ({
  __esModule: true,
  ...jest.requireActual('./SomeComponent'),
  someFunction: jest.fn().mockReturnValue('mocked!')
}));

describe('<SomeComponent />', () => {
  it('renders', () => {
      render(<SomeComponent />);
      const el = screen.getByTestId('innards');

      expect(el.textContent).toEqual('mocked!');
  });
});


问:
Categories library for Agda?
Are there any "recommended" libraries that provide a easy-to-use formalisation of basic category theory in Agda? The Agda standard library seems to provide very little in this regard.

I'm looking for something with a low barrier to entry, similar to how one uses the algebraic structures such as Semigroup defined in the standard library.

For example, there are several notions of morphism in my current project, and overloading syntax for composition and identity gets awkward. The natural thing to do would be to introduce a suitable record type and use Agda's "instance arguments" mechanism to emulate a Morphism type class. But no doubt this must be a wheel that has been invented many times. (Ok, there is a structure called Morphism in the standard library which perhaps could be adapted to this purpose, so this isn't necessarily the best example, but you get the idea.)

I'm aware of this library, which looks comprehensive, but doesn't seem to be particularly active.

答: This is an old question, but it still gets hits on google and other searches, so: the de facto library is now agda-categories.</p>

Title: Categories library for Agda?


问:
Using pyaudio to build a Metronome; wrong timing
So I wanted to build a metronome and decided to use pyaudio. I know there are other ways but I want to make something else later with that.

Thats my Code so far:

```<code>
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def play_audio(filename):
    wf=wave.open(filename,"rb")
    p=pyaudio.PyAudio()
    stream_play=p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)
    data = wf.readframes(CHUNK)
    while True:
        if data != '':
            stream_play.write(data)
            data = wf.readframes(CHUNK)
        if data == b"":
            break
    stream_play.stop_stream()
    stream_play.close()
    p.terminate()

def metronom(bpm):
    while True:
        play_callback(beep)
        time.sleep(60/bpm)

beep="beep-07a.wav"

</code>```

I thought it worked out, but unfortunately the timing is completely off. I also tried it with a callback function, but had the same wrong timing.

THE SOLUTION NOW LOOKS LIKE THIS

```<code>def metronom(bpm):
    while True:
        startTime = time.time()
        play_callback(beep)
        endTime=time.time()-startTime
        time.sleep(60/bpm-endTime)
</code>```

答:
You want the play_audio function to be called every 60/bpm seconds, but the function call itself takes time: you need to read the file, open the stream, play the file (who knows how long it is) and close the stream. So that adds to the time from one click to the next.

To fix this problem, you could try subtracting the time it takes to run the play_audio function from the time you sleep. You could also experiment with running play_audio on a separate thread.

Body:
So I wanted to build a metronome and decided to use pyaudio. I know there are other ways but I want to make something else later with that.

Thats my Code so far:

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
def play_audio(filename):
    wf=wave.open(filename,"rb")
    p=pyaudio.PyAudio()
    stream_play=p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)
    data = wf.readframes(CHUNK)
    while True:
        if data != '':
            stream_play.write(data)
            data = wf.readframes(CHUNK)
        if data == b"":
            break
    stream_play.stop_stream()
    stream_play.close()
    p.terminate()

def metronom(bpm):
    while True:
        play_callback(beep)
        time.sleep(60/bpm)

beep="beep-07a.wav"

I thought it worked out, but unfortunately the timing is completely off. I also tried it with a callback function, but had the same wrong timing.

THE SOLUTION NOW LOOKS LIKE THIS

def metronom(bpm):
    while True:
        startTime = time.time()
        play_callback(beep)
        endTime=time.time()-startTime
        time.sleep(60/bpm-endTime)


问:
conditional statment in prompt
I'm working on providing a user with two different pictures depending on the right username/password. I'm having a prompt popup for the user to give the username/password and after providing the right credentials the login picture should appear and if the credentials are wrong the logout picture should appear. I am using the getElementById to change accordingly. At this moment the prompt shows up, but there is no picture showing.

```

答:
You have to apply a function to your document.getElementById("user_in_id") selector,which somehow makes the selected element visible.

One way would be to remove the hidden attribute from it with document.getElementById("user_in_id").removeAttribute("hidden");

You also forgot to wrap your else statement around curly brackets in order to work properly.

```

Title: conditional statment in prompt

Body:
You have to apply a function to your document.getElementById("user_in_id") selector,which somehow makes the selected element visible.

One way would be to remove the hidden attribute from it with document.getElementById("user_in_id").removeAttribute("hidden");

You also forgot to wrap your else statement around curly brackets in order to work properly.

<img src="https://styles.redditmedia.com/t5_3obin/styles/communityIcon_5v6pv5kqz5241.PNG" id="user_in_id" hidden>
<img src="https://public.blenderkit.com/thumbnails/assets/0992088bfb844c69bb6e426272970c8b/files/thumbnail_c858218a-4afc-4e94-b6b9-080f5e6c7066.jpg.256x256_q85_crop-%2C.jpg" id="user_out_id" hidden>

<script>
    var person = prompt("Please enter your name", "");
    var password = prompt("Please enter your password", "");
     if (person === "admin" && password === "admin") {
        alert("Welcome, You are now Logged in");
        document.getElementById("user_in_id").removeAttribute("hidden");

      }else{
       alert("wrong username or password");
       document.getElementById("user_out_id").removeAttribute("hidden");
      }

</script>


问:
How to turn these C# foreach loops into LINQ to Objects and return a bool?
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

```<code>private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }
</code>```

答:
```<code>return videoTracks.Any(t => t.Events.Any(te => te.Start == currentEvent.Start));
</code>```

Body:
I'm writing a .Net 3.5 C# script for Sony Vegas Pro. I've created this method which returns true if it finds a video event with the same timecode as a given audio event.

This works but I'm wondering if I could get rid of the foreach loops using LINQ. I'm just learning LINQ and I'm finding it quite hard so if you could explain your thought steps in getting to the solution, that'd be great.

private bool videoExistsWithSameStart(TrackEvent currentEvent)
    {
        //Look through each video track - we don't want audio tracks.
        var videoTracks = from t in myVegas.Project.Tracks
                          where t.IsVideo()
                          select t;

        foreach (Track t in videoTracks)
        {
            foreach (TrackEvent te in t.Events)
            {
                if (te.Start == currentEvent.Start)
                    return true;
            }
        }
        return false;
    }


问:
Rest Call to Azure
I am trying to login to Azure with my c# code and was able to find something like this on the net.

Not sure what to pass in the scope array here and once I get the access token, how can I make the rest call ?

```<code>public static string getAccessToken(string[] scopes)
{
   var interactiveCredential = new InteractiveBrowserCredential();
   return interactiveCredential.GetToken(new Azure.Core.TokenRequestContext(scopes, null)).Token;
}
</code>```

答:
First create a Azure AD Application:

Follow this link

Then get the Tenant ID , Client ID , Client Secret from the AD Application and use this class to query your azure subscription recourses.

```<code>class CustomLoginCredentials : ServiceClientCredentials
{
    //Variables
    private static string tenantId = "<Tenant ID goes here>";
    private static string clientId = "<Client ID goes here>";
    private static string clientSecret = "<Client Secret goes here>";
    private static string windowsURL = "https://login.windows.net/";
    private static string azureManagementURL = "https://management.azure.com/";

    private string AuthenticationToken { get; set; }

    public override void InitializeServiceClient<T>(ServiceClient<T> client)
    {
        var authenticationContext =
            new AuthenticationContext(windowsURL + tenantId);
        var credential = new ClientCredential(clientId, clientSecret);

        var result = authenticationContext.AcquireTokenAsync(azureManagementURL,
            clientCredential: credential).Result;

        AuthenticationToken = result.AccessToken;
    }
    public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
        await base.ProcessHttpRequestAsync(request, cancellationToken);
    }
}

</code>```

Example:

```<code>private async void GetAzureResourcesConsumption()
        {
            var credentials = new CustomLoginCredentials();
            ConsumptionManagementClient client = new ConsumptionManagementClient(credentials);
            client.SubscriptionId = subscriptionId;

            var resources = await client.UsageDetails.ListAsync(null, null, null, top: NumberOfItems);
            var results = resources.ToList<UsageDetail>();
        }

</code>```

Do you mean to get access token?

```<code>private static string GetAuthorizationToken()
    {
        ClientCredential cc = new ClientCredential(ClientId, ServicePrincipalPassword);
        var context = new AuthenticationContext("https://login.windows.net/" + AzureTenantId);
        var result = context.AcquireTokenAsync("https://management.azure.com/", cc);
        if (result == null)
        {
            throw new InvalidOperationException("Failed to obtain the JWT token");
        }

        return result.Result.AccessToken;
    }
</code>```

Title: Rest Call to Azure

Body:
I am trying to login to Azure with my c# code and was able to find something like this on the net.

Not sure what to pass in the scope array here and once I get the access token, how can I make the rest call ?

public static string getAccessToken(string[] scopes)
{
   var interactiveCredential = new InteractiveBrowserCredential();
   return interactiveCredential.GetToken(new Azure.Core.TokenRequestContext(scopes, null)).Token;
}

Body:
First create a Azure AD Application:

Follow this link

Then get the Tenant ID , Client ID , Client Secret from the AD Application and use this class to query your azure subscription recourses.

class CustomLoginCredentials : ServiceClientCredentials
{
    //Variables
    private static string tenantId = "<Tenant ID goes here>";
    private static string clientId = "<Client ID goes here>";
    private static string clientSecret = "<Client Secret goes here>";
    private static string windowsURL = "https://login.windows.net/";
    private static string azureManagementURL = "https://management.azure.com/";

    private string AuthenticationToken { get; set; }

    public override void InitializeServiceClient<T>(ServiceClient<T> client)
    {
        var authenticationContext =
            new AuthenticationContext(windowsURL + tenantId);
        var credential = new ClientCredential(clientId, clientSecret);

        var result = authenticationContext.AcquireTokenAsync(azureManagementURL,
            clientCredential: credential).Result;

        AuthenticationToken = result.AccessToken;
    }
    public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
        await base.ProcessHttpRequestAsync(request, cancellationToken);
    }
}

Example:

private async void GetAzureResourcesConsumption()
        {
            var credentials = new CustomLoginCredentials();
            ConsumptionManagementClient client = new ConsumptionManagementClient(credentials);
            client.SubscriptionId = subscriptionId;

            var resources = await client.UsageDetails.ListAsync(null, null, null, top: NumberOfItems);
            var results = resources.ToList<UsageDetail>();
        }

Do you mean to get access token?

private static string GetAuthorizationToken()
    {
        ClientCredential cc = new ClientCredential(ClientId, ServicePrincipalPassword);
        var context = new AuthenticationContext("https://login.windows.net/" + AzureTenantId);
        var result = context.AcquireTokenAsync("https://management.azure.com/", cc);
        if (result == null)
        {
            throw new InvalidOperationException("Failed to obtain the JWT token");
        }

        return result.Result.AccessToken;
    }


问:
Use Column Header Name Within Index-Match Function VBA Macro
I'd like to modify my Index-Match function to use the column header names defined in row 1, rather than the column letters.

The function resides in a sheet named AssetName Sheet and references a sheet named AMP Sheet

Here is my code for the Index-Match:

```<code>=IFERROR(INDEX('AMP Sheet'!$L:$L,MATCH("*"&B2&"*", 'AMP Sheet'!$B:$B,0)), "")
</code>```

'AMP Sheet' !$L:$L - This is referring to column L in the AMP Sheet tab. I want to replace using column letter L in the formula with its column name ID

'AMP Sheet' !$B:$B - This is referring to column B in the AMP Sheet tab. I want to replace using column letter B in the formula with its column name Name

"&B2&" - This part of the function does not need to change! The function is within a sheet tab named AssetName Sheet which columns will not change. This will stay as-is.

Thank you!

答:
From the comments, both Tragamor and VBasic2008 came up with a working solution. Here it is:</p>
```<code>=IFERROR(INDEX(OFFSET('AMP Sheet'!$A:$A,,MATCH("ID",'AMP Sheet'!$1:$1,0)-1),MATCH("*"&B1&"*",OFFSET('AMP Sheet'!$A:$A,,MATCH("Name",'AMP Sheet'!$1:$1,0)-1),0)),"")
</code>```

Body:
I'd like to modify my Index-Match function to use the column header names defined in row 1, rather than the column letters.

The function resides in a sheet named AssetName Sheet and references a sheet named AMP Sheet

Here is my code for the Index-Match:

=IFERROR(INDEX('AMP Sheet'!$L:$L,MATCH("*"&B2&"*", 'AMP Sheet'!$B:$B,0)), "")

'AMP Sheet' !$L:$L - This is referring to column L in the AMP Sheet tab. I want to replace using column letter L in the formula with its column name ID

'AMP Sheet' !$B:$B - This is referring to column B in the AMP Sheet tab. I want to replace using column letter B in the formula with its column name Name

"&B2&" - This part of the function does not need to change! The function is within a sheet tab named AssetName Sheet which columns will not change. This will stay as-is.

Thank you!

Body:
From the comments, both Tragamor and VBasic2008 came up with a working solution. Here it is:

=IFERROR(INDEX(OFFSET('AMP Sheet'!$A:$A,,MATCH("ID",'AMP Sheet'!$1:$1,0)-1),MATCH("*"&B1&"*",OFFSET('AMP Sheet'!$A:$A,,MATCH("Name",'AMP Sheet'!$1:$1,0)-1),0)),"")


问:
Fetching from firestore and Firebase functions timeout
I have a simple function that I am testing locally on the emulator.

```<code>    exports.sendNotification = functions.https.onRequest(() => {
  firebase
    .firestore()
    .collection("Users")
    .get()
    .then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.id, doc.data());
      });
    });
});
</code>```

When I execute the function, it works fine, but shortly after I get this message:

```<code>     functions: Your function timed out after ~60s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
>  C:\Users\myusername\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:618
>              throw new Error("Function timed out.");
>              ^
>
>  Error: Function timed out.
>      at Timeout._onTimeout (C:\Users\myusername\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:618:19)
>      at listOnTimeout (node:internal/timers:557:17)
>      at processTimers (node:internal/timers:500:7)
</code>```

my expectation was that the function would just end normally since its at the end of the function, is this message saying that I need to do something to indicate the function has finished? Do I need to change something especially when pushing to production?

答:
You must terminate a HTTP function by sending back a response otherwise it'll run until it times out. Try refactoring your code like this:</p>
```<code>exports.sendNotification = functions.https.onRequest((req, res) => {
  // add req, res in functions parameters             ^^^
  return firebase
    .firestore()
    .collection("Users")
    .get()
    .then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.id, doc.data());
      });
      // Return response
      return res.json({ data: snapshot.docs.map(d => d.data()) })
    });
});
</code>```

Body:
I have a simple function that I am testing locally on the emulator.

    exports.sendNotification = functions.https.onRequest(() => {
  firebase
    .firestore()
    .collection("Users")
    .get()
    .then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.id, doc.data());
      });
    });
});

When I execute the function, it works fine, but shortly after I get this message:

     functions: Your function timed out after ~60s. To configure this timeout, see
      https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation.
>  C:\Users\myusername\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:618
>              throw new Error("Function timed out.");
>              ^
>
>  Error: Function timed out.
>      at Timeout._onTimeout (C:\Users\myusername\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:618:19)
>      at listOnTimeout (node:internal/timers:557:17)
>      at processTimers (node:internal/timers:500:7)

my expectation was that the function would just end normally since its at the end of the function, is this message saying that I need to do something to indicate the function has finished? Do I need to change something especially when pushing to production?

Body:
You must terminate a HTTP function by sending back a response otherwise it'll run until it times out. Try refactoring your code like this:

exports.sendNotification = functions.https.onRequest((req, res) => {
  // add req, res in functions parameters             ^^^
  return firebase
    .firestore()
    .collection("Users")
    .get()
    .then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.id, doc.data());
      });
      // Return response
      return res.json({ data: snapshot.docs.map(d => d.data()) })
    });
});


问:
Add corner radius to view borders Swift
I have a UIView extension with a function that adds borders to specific edges (which I need). On that function, I am also trying to add cornerRadius if the borders are near each other.

Here is my function:

```<code>func addBorders(withEdges edges: [UIRectEdge],
                    withColor color: UIColor,
                    withThickness thickness: CGFloat) {
        let maskLayer = CAShapeLayer()
        maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft[![\]][1]][1], cornerRadii: CGSize(width: 10, height: 10)).cgPath

        layer.mask = maskLayer

        let border = CAShapeLayer()

        edges.forEach({ edge in

            border.backgroundColor = color.cgColor
            border.name = String(edge.rawValue)

            switch edge {
            case .left:
                border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)

                break

            case .right:
                border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)

                break

            case .top:
                border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)

                break

            case .bottom:
                border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)

                break

            default:
                break
            }

            layer.addSublayer(border)
        })

        border.path = maskLayer.path
    }
</code>```

This functions adds the borders well, as I need them, and let's say I need all the borders and corners (based on the hardcoded byRoundingCorners value), but the result is at if follows:

The cornerRadius is there, but the borders now are somehow the whole UIView not the thickness I've sent.

Can somebody help me?

Thank you for your time!

**

UPDATE

**

So I have updated my function to this:

```<code> func addBorders(withEdges edges: [UIRectEdge],
                withColor color: UIColor,
                withThickness thickness: CGFloat) {
    edges.forEach({ edge in
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.name = String(edge.rawValue)

        switch edge {
        case .left:
            border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
            border.masksToBounds = true

            break

        case .right:
            border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
            border.masksToBounds = true

            break

        case .top:
            border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
            border.masksToBounds = true

            break

        case .bottom:
            border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
            border.masksToBounds = true

            break

        default:
            break
        }

        layer.addSublayer(border)
    })
</code>```

and now the output is like that:

How can I achieve some normal corners?

答:
if you look at the red lines that you’re drawing (closely, zoom on it with an app like “Zoom It”, you will see that the edges of that red border have been curved out, which i think that is not what you want).

here is what i came up with:

```<code>  func addBorders(withEdges edges: [UIRectEdge],
                  withColor color: UIColor,
                  withThickness thickness: CGFloat,
                  cornerRadius: CGFloat) {
    layer.borderColor = color.cgColor
    layer.borderWidth = thickness
    layer.cornerRadius = cornerRadius
    edges.forEach({ edge in

      switch edge {
        case .left:
          layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]

        case .right:
          layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]

        case .top:
          layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

        case .bottom:
          layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

        default:
          break
      }
    })
  }
</code>```

Title: Add corner radius to view borders Swift

Body:
I have a UIView extension with a function that adds borders to specific edges (which I need). On that function, I am also trying to add cornerRadius if the borders are near each other.

Here is my function:

func addBorders(withEdges edges: [UIRectEdge],
                    withColor color: UIColor,
                    withThickness thickness: CGFloat) {
        let maskLayer = CAShapeLayer()
        maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft[![\]][1]][1], cornerRadii: CGSize(width: 10, height: 10)).cgPath

        layer.mask = maskLayer

        let border = CAShapeLayer()

        edges.forEach({ edge in

            border.backgroundColor = color.cgColor
            border.name = String(edge.rawValue)

            switch edge {
            case .left:
                border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)

                break

            case .right:
                border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)

                break

            case .top:
                border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)

                break

            case .bottom:
                border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)

                break

            default:
                break
            }

            layer.addSublayer(border)
        })

        border.path = maskLayer.path
    }

This functions adds the borders well, as I need them, and let's say I need all the borders and corners (based on the hardcoded byRoundingCorners value), but the result is at if follows:

The cornerRadius is there, but the borders now are somehow the whole UIView not the thickness I've sent.

Can somebody help me?

Thank you for your time!

**

UPDATE

**

So I have updated my function to this:

 func addBorders(withEdges edges: [UIRectEdge],
                withColor color: UIColor,
                withThickness thickness: CGFloat) {
    edges.forEach({ edge in
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.name = String(edge.rawValue)

        switch edge {
        case .left:
            border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
            border.masksToBounds = true

            break

        case .right:
            border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
            border.masksToBounds = true

            break

        case .top:
            border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
            border.masksToBounds = true

            break

        case .bottom:
            border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
            border.cornerRadius = 10
            border.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
            border.masksToBounds = true

            break

        default:
            break
        }

        layer.addSublayer(border)
    })

and now the output is like that:

How can I achieve some normal corners?

Body:
if you look at the red lines that you’re drawing (closely, zoom on it with an app like “Zoom It”, you will see that the edges of that red border have been curved out, which i think that is not what you want).

here is what i came up with:

  func addBorders(withEdges edges: [UIRectEdge],
                  withColor color: UIColor,
                  withThickness thickness: CGFloat,
                  cornerRadius: CGFloat) {
    layer.borderColor = color.cgColor
    layer.borderWidth = thickness
    layer.cornerRadius = cornerRadius
    edges.forEach({ edge in

      switch edge {
        case .left:
          layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]

        case .right:
          layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]

        case .top:
          layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

        case .bottom:
          layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

        default:
          break
      }
    })
  }