问:
Tasks in parallel using C#. Am I doing this right?
I've already search and read about, I just want to make sure if I am right. I have three methods that I want to run in parallel, and I want to make sure that all of them are done before continue. They are all async, and this code are inside an async method. I've done this:

```<code>public async ProcessBegin() {
   //... some code

   await SomeProcess();
   await AnotherMethod().
}

public async SomeProcess() {
   //.. some code

   var tasks = new Task[3];
   tasks[0] = method1();
   tasks[1] = method2();
   tasks[2] = method3();

   Task.WaitAll(tasks);
}

public async Method1(){...}
public async Method2(){...}
public async Method3(){...}
</code>```

Is this right?

答:
Task.WaitAll blocks synchronously so you might use Parallel.Invoke if this is intended:

```<code>Parallel.Invoke(() => method1(), () => method2(), () => method3());
</code>```

This works as long as the methodX methods themselves are not asynchronous. Parallel.ForEach doesn't work with async actions.

If you want to wait for the tasks to complete asynchronously, you should use Task.WhenAll:

```<code>var tasks = new Task[3];
tasks[0] = method1();
tasks[1] = method2();
tasks[2] = method3();

await Task.WhenAll(tasks);
</code>```

Body:
I've already search and read about, I just want to make sure if I am right. I have three methods that I want to run in parallel, and I want to make sure that all of them are done before continue. They are all async, and this code are inside an async method. I've done this:

public async ProcessBegin() {
   //... some code

   await SomeProcess();
   await AnotherMethod().
}

public async SomeProcess() {
   //.. some code

   var tasks = new Task[3];
   tasks[0] = method1();
   tasks[1] = method2();
   tasks[2] = method3();

   Task.WaitAll(tasks);
}

public async Method1(){...}
public async Method2(){...}
public async Method3(){...}

Is this right?

Body:
Task.WaitAll blocks synchronously so you might use Parallel.Invoke if this is intended:

Parallel.Invoke(() => method1(), () => method2(), () => method3());

This works as long as the methodX methods themselves are not asynchronous. Parallel.ForEach doesn't work with async actions.

If you want to wait for the tasks to complete asynchronously, you should use Task.WhenAll:

var tasks = new Task[3];
tasks[0] = method1();
tasks[1] = method2();
tasks[2] = method3();

await Task.WhenAll(tasks);


来源: stackexchange

问:
Passing WebElement as parameter to implicit wait method
I wrote the below method in my Page.class for reusing implicit wait.

```<code>public WebDriver waitForElementToLoad(WebElement element)
{
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
        return (driver);
}
</code>```

In my test.class I am using page factory elements, for example:

```<code>//Save button
@FindBy(xpath = "//*[@*='Save']")
private WebElement saveButton;
</code>```

Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.

"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
  cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
  org.openqa.selenium.By are in unnamed module of loader 'app')"

I also tried

```<code>WebElement saveButton = driver.findElement(By.xpath("//*[@*='Save']"));
waitForElementToLoad(saveButton);
</code>```

but no luck.

How can I make this work?

答:
If you need to use ExpectedConditions with some your "Page" class that contains asynchronously loaded elements I would recommend to use the following approach:

Extend AjaxElementLocator where override protected boolean isElementUsable(WebElement element) so that it uses ExpectedConditions to decide if the element is ready for use

Extend AjaxElementLocatorFactory where override public ElementLocator createLocator(Field field) method so that it now returns the instance of your extended class

Where you initialize elements use PageFactory.initElements(new MyAjaxElementLocatorFactory(driver, 10), this); where MyAjaxElementLocatorFactory is the class that you created on step 2

ContentLicense: CC BY-SA 4.0

Body:
I wrote the below method in my Page.class for reusing implicit wait.

public WebDriver waitForElementToLoad(WebElement element)
{
        WebDriverWait wait = new WebDriverWait(driver, 60);
        wait.until(ExpectedConditions.presenceOfElementLocated((By) element));
        return (driver);
}

In my test.class I am using page factory elements, for example:

//Save button
@FindBy(xpath = "//*[@*='Save']")
private WebElement saveButton;

Now I am trying to call:
waitForElementToLoad(saveButton);
from test.Class but I am getting below error.

"java.lang.ClassCastException: class com.sun.proxy.$Proxy12 cannot be
  cast to class org.openqa.selenium.By (com.sun.proxy.$Proxy12 and
  org.openqa.selenium.By are in unnamed module of loader 'app')"

I also tried

WebElement saveButton = driver.findElement(By.xpath("//*[@*='Save']"));
waitForElementToLoad(saveButton);

but no luck.

How can I make this work?


问:
What's a good way to organize projects with shared dependencies in Mercurial?
Currently, I'm moving from a legacy version control system and moving my group's project to mercurial.  As one example of the kinds of code I'm moving, I have a 25+ project Visual Studio solution, containing several separate application areas that all depend on common code.  Looking over Stack Overflow, the closest question I found was this one, but it merely mentioned version control.  I'm looking for a bit further advice, on specific implementation techniques of using Mercurial to manage these dependencies.

A simplified view of the dependencies look something like the following.  (This is for illustration and example only; the actual dependencies are significantly more complex but similar in nature.)

```<code>                     Common Lib 1
                    /      |      \
                ----       |       -----
               /           |        \   \
            App 1    Common Lib 2    \ App 2
                       /   |   \      \
                -------    |    ------ |
               /           |          \|
             App 3       App 4      App 5
</code>```

The Common Lib modules would be shared code - this would be a DLL or SO or some other library that would be used between all the apps simultaneously - both at compile and run time.  Applications would otherwise be able to run independently from each other.

I have a couple goals with setting up my mercurial repositories:

Give each significant application or component group its own repository.

Make each repository self contained.

Make the sum total of the project self contained.

Make it easy to build the entire codebase at once.  (eventually, all these programs and libraries end up in a single installer.)

Keep it simple.

One other point is that I have a server set up where I have separate repositories for each of these projects.

I see a couple ways of laying these projects out.

1. Create a "Shell" repository that contains everything.

This would use url-based subrepos (eg, in the .hgsub, I'd do something like App1 = https://my.server/repo/app1.)  Laid out, it would look like the following:

```<code>+---------------------------+
| Main Repository           |
| | +---------------------+ |
| +-| Build               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 1        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 2        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 1               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 2               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 3               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 4               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 5               | |
|   +---------------------+ |
+---------------------------+
</code>```

Each main folder in the shell repository would contain a subrepo, one for each project area.  Dependencies would be relative: Eg, since App 4 needs Common Lib 2, it would simply use relative paths to reference that common library.

Pros of this approach:

Each library is pulled down once and only once.

Mercurial's subreos will ensure that the same version of the library is used across all project automatically, since only one version of that subrepo exists in the project.

It's easy to find each resource.

Cons of this approach:

I can't work on an App independently.  Eg, if I work on App 2, and it needs a change to the common libraries, all of the other apps will have to take those changes right now.

If I pull an App repo by itself, I have to figure out (or know) what other dependent repos it requires by hand if I want to build it.

Dependencies are not strongly separated - it would be tempting to insert a new feature  anywhere since it was easy to get at all the features.

2. Have dependent subrepos be wholly contained.

In this approach, each application would have its own repository (as before) but this time also contain subrepositories: one for its own source, and one for each dependent subrepository.  An overall repository would then contain each of these project repositories, and know how to build the entire solution.  This would look like the following:

```<code>+-----------------------------------------------------------------------+
| Main Repository                                                       |
| +--------------------+ +--------------------+ +--------------------+  |
| | Build              | | Common Lib 1       | | Common Lib 2       |  |
| +--------------------+ | | +--------------+ | | | +--------------+ |  |
|                        | +-| Lib 1 Source | | | +-| Common Lib 1 | |  |
|                        |   +--------------+ | | | +--------------+ |  |
|                        |                    | | | +--------------+ |  |
|                        |                    | | +-| Lib 2 Source | |  |
|                        |                    | |   +--------------+ |  |
|                        +--------------------+ +--------------------+  |
| +--------------------+ +--------------------+ +---------------------+ |
| | App 1              | | App 2              | |  App 3              | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| Common Lib 1 | | | +-| Common Lib 1 | | |  +-| Common Lib 2 | | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| App 1 Source | | | +-| App 2 Source | | |  +-| App 3 Source | | |
| |   +--------------+ | |   +--------------+ | |    +--------------+ | |
| +--------------------+ +--------------------+ +---------------------+ |
| +--------------------+ +--------------------+                         |
| | App 4              | | App 5              |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| Common Lib 2 | | | +-| Common Lib 1 | |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| App 4 Source | | | +-| Common Lib 2 | |                         |
| |   +--------------+ | | | +--------------+ |                         |
| +--------------------+ + | +--------------+ |                         |
|                        | +-| App 5 Source | |                         |
|                        |   +--------------+ |                         |
|                        +--------------------+                         |
+-----------------------------------------------------------------------+
</code>```

Pros:

Each application can be built by itself, independent of each other.

Dependent versions of libraries can be tracked per-app, instead of globally.  It takes an explicit act of inserting a subrepo into the project to add a new dependency.

Cons:

When doing the final build, each app might be using a different version of a shared library.  (might need to write tools to sync the common lib subrepos.  Eww.)

If I want to build the entire source, I end up pulling down shared libraries multiple times.  In the case of Common Lib 1, I would have to pull it eight (!) times.

3.  Don't include dependencies at all as subrepos - bring them in as part of the build.

This approach would look much like approach 1, except the common libraries would only be pulled as part of the build.  Each app would know what repos it needed, and put them in the common location.

Pros:

Each app could build by itself.

Common libraries would only need to be pulled once.

Cons:

We'd have to keep track of versions of libraries currently used by each app.  This duplicates subrepo features.

We'd have to build an infrastructure to support this, which means more stuff going into build scripts.  Ugh.

4.  What else?

Is there another way of handling it?  A better way?  What ways have you tried and succeeded, what ways have you tried but hated?  I'm currently leaning towards 1, but the lack of application independence, when it should be able to, really bothers me.  Is there a way to get the nice separation of method 2 without the massive duplicate code pull and dependency maintenance nightmare, while not having to write scripts to handle it (like in option 3)?

答:
What you want to do is have each project in its own directory like in (1). Then you tag working versions of your dependencies and save the tag in some file for build like:

```
App1/.dependencies:
CommonLib1 tag-20100515
CommonLib2 tag-20100510

App2/.dependencies:
CommonLib1 tag-20100510
CommonLib2 tag-20100510
```

Then you use your build scripts to build the libraries based on the specific tag and include those built libraries as derived objects for your applications. If build time is an issue, you can have the tagged version that are in use for those libraries pre-built and saved somewhere.

Note (design principles are same if designing database schema, object model or product build):

Do not link to the code in other projects (breaks encapsulation)

Do not have multiple copies of the libraries in your repository (modularity)

ContentLicense: CC BY-SA 3.0

Body:
Currently, I'm moving from a legacy version control system and moving my group's project to mercurial.  As one example of the kinds of code I'm moving, I have a 25+ project Visual Studio solution, containing several separate application areas that all depend on common code.  Looking over Stack Overflow, the closest question I found was this one, but it merely mentioned version control.  I'm looking for a bit further advice, on specific implementation techniques of using Mercurial to manage these dependencies.

A simplified view of the dependencies look something like the following.  (This is for illustration and example only; the actual dependencies are significantly more complex but similar in nature.)

                     Common Lib 1
                    /      |      \
                ----       |       -----
               /           |        \   \
            App 1    Common Lib 2    \ App 2
                       /   |   \      \
                -------    |    ------ |
               /           |          \|
             App 3       App 4      App 5

The Common Lib modules would be shared code - this would be a DLL or SO or some other library that would be used between all the apps simultaneously - both at compile and run time.  Applications would otherwise be able to run independently from each other.

I have a couple goals with setting up my mercurial repositories:

Give each significant application or component group its own repository.

Make each repository self contained.

Make the sum total of the project self contained.

Make it easy to build the entire codebase at once.  (eventually, all these programs and libraries end up in a single installer.)

Keep it simple.

One other point is that I have a server set up where I have separate repositories for each of these projects.

I see a couple ways of laying these projects out.

1. Create a "Shell" repository that contains everything.

This would use url-based subrepos (eg, in the .hgsub, I'd do something like App1 = https://my.server/repo/app1.)  Laid out, it would look like the following:

+---------------------------+
| Main Repository           |
| | +---------------------+ |
| +-| Build               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 1        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| Common Lib 2        | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 1               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 2               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 3               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 4               | |
| | +---------------------+ |
| | +---------------------+ |
| +-| App 5               | |
|   +---------------------+ |
+---------------------------+

Each main folder in the shell repository would contain a subrepo, one for each project area.  Dependencies would be relative: Eg, since App 4 needs Common Lib 2, it would simply use relative paths to reference that common library.

Pros of this approach:

Each library is pulled down once and only once.

Mercurial's subreos will ensure that the same version of the library is used across all project automatically, since only one version of that subrepo exists in the project.

It's easy to find each resource.

Cons of this approach:

I can't work on an App independently.  Eg, if I work on App 2, and it needs a change to the common libraries, all of the other apps will have to take those changes right now.

If I pull an App repo by itself, I have to figure out (or know) what other dependent repos it requires by hand if I want to build it.

Dependencies are not strongly separated - it would be tempting to insert a new feature  anywhere since it was easy to get at all the features.

2. Have dependent subrepos be wholly contained.

In this approach, each application would have its own repository (as before) but this time also contain subrepositories: one for its own source, and one for each dependent subrepository.  An overall repository would then contain each of these project repositories, and know how to build the entire solution.  This would look like the following:

+-----------------------------------------------------------------------+
| Main Repository                                                       |
| +--------------------+ +--------------------+ +--------------------+  |
| | Build              | | Common Lib 1       | | Common Lib 2       |  |
| +--------------------+ | | +--------------+ | | | +--------------+ |  |
|                        | +-| Lib 1 Source | | | +-| Common Lib 1 | |  |
|                        |   +--------------+ | | | +--------------+ |  |
|                        |                    | | | +--------------+ |  |
|                        |                    | | +-| Lib 2 Source | |  |
|                        |                    | |   +--------------+ |  |
|                        +--------------------+ +--------------------+  |
| +--------------------+ +--------------------+ +---------------------+ |
| | App 1              | | App 2              | |  App 3              | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| Common Lib 1 | | | +-| Common Lib 1 | | |  +-| Common Lib 2 | | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | | +--------------+ | | | +--------------+ | |  | +--------------+ | |
| | +-| App 1 Source | | | +-| App 2 Source | | |  +-| App 3 Source | | |
| |   +--------------+ | |   +--------------+ | |    +--------------+ | |
| +--------------------+ +--------------------+ +---------------------+ |
| +--------------------+ +--------------------+                         |
| | App 4              | | App 5              |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| Common Lib 2 | | | +-| Common Lib 1 | |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | | +--------------+ | | | +--------------+ |                         |
| | +-| App 4 Source | | | +-| Common Lib 2 | |                         |
| |   +--------------+ | | | +--------------+ |                         |
| +--------------------+ + | +--------------+ |                         |
|                        | +-| App 5 Source | |                         |
|                        |   +--------------+ |                         |
|                        +--------------------+                         |
+-----------------------------------------------------------------------+

Pros:

Each application can be built by itself, independent of each other.

Dependent versions of libraries can be tracked per-app, instead of globally.  It takes an explicit act of inserting a subrepo into the project to add a new dependency.

Cons:

When doing the final build, each app might be using a different version of a shared library.  (might need to write tools to sync the common lib subrepos.  Eww.)

If I want to build the entire source, I end up pulling down shared libraries multiple times.  In the case of Common Lib 1, I would have to pull it eight (!) times.

3.  Don't include dependencies at all as subrepos - bring them in as part of the build.

This approach would look much like approach 1, except the common libraries would only be pulled as part of the build.  Each app would know what repos it needed, and put them in the common location.

Pros:

Each app could build by itself.

Common libraries would only need to be pulled once.

Cons:

We'd have to keep track of versions of libraries currently used by each app.  This duplicates subrepo features.

We'd have to build an infrastructure to support this, which means more stuff going into build scripts.  Ugh.

4.  What else?

Is there another way of handling it?  A better way?  What ways have you tried and succeeded, what ways have you tried but hated?  I'm currently leaning towards 1, but the lack of application independence, when it should be able to, really bothers me.  Is there a way to get the nice separation of method 2 without the massive duplicate code pull and dependency maintenance nightmare, while not having to write scripts to handle it (like in option 3)?

Body:
What you want to do is have each project in its own directory like in (1). Then you tag working versions of your dependencies and save the tag in some file for build like:

App1/.dependencies:
CommonLib1 tag-20100515
CommonLib2 tag-20100510

App2/.dependencies:
CommonLib1 tag-20100510
CommonLib2 tag-20100510

Then you use your build scripts to build the libraries based on the specific tag and include those built libraries as derived objects for your applications. If build time is an issue, you can have the tagged version that are in use for those libraries pre-built and saved somewhere.

Note (design principles are same if designing database schema, object model or product build):

Do not link to the code in other projects (breaks encapsulation)

Do not have multiple copies of the libraries in your repository (modularity)


问:
Optimal solution for looping and inserting/updating
I am interested to know if there is a better / more optimal solution than what I have so far as it uses a cursor, which I know is not too good performance wise.

Basically my requirement is too check if a number of settings exists for an ID and then update or insert them accordingly.

To do this I have:

```<code>DECLARE @UserId UNIQUEIDENTIFIER = '{PUT-GUID-HERE}'
</code>```

I then declare a table variable which I add the setting names and values to, there are approx 15 of these in total.

```<code>DECLARE @SettingsToCheck TABLE (SettingName varchar(100), SettingValue varchar(100)
INSERT INTO @SettingsToCheck ('Setting1', 'Setting1 Value') --Repeat...

DECLARE @CurrentSettingName varchar(100)
DECLARE @CurrentSettingValue varchar(100)
DECLARE Settings_Cursor CURSOR FOR SELECT SettingName, SettingValue FROM @SettingsToCheck
OPEN Settings_Cursor

FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
WHILE @@FETCH_STATUS = 0
BEGIN
    IF EXISTS (SELECT * FROM MyActualTable WHERE UserID = @UserId AND SettingName = @CurrentSettingName)
    BEGIN
        UPDATE MyActualTable SET SettingValue = @CurrentSettingValue WHERE UserID = @UserId AND SettingName = @CurrentSettingName
    END
    ELSE
    BEGIN
        INSERT INTO MyActualTableVALUES (NEWID(), @UserId, GETDATE(), @CurrentSettingName, @CurrentSettingValue)
    END

    FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
END

CLOSE Settings_Cursor
DEALLOCATE Settings_Cursor
</code>```

I know this question is subject to opinion, but I am unaware of any alternatives.

EDIT:

There could be a scenario where some/none or all of the settings already exist. But here's an example.

BEFORE:

```<code>SettingName  |  SettingValue
____________________________
Setting1     |  Setting1Value
</code>```

AFTER:

```<code>SettingName  |  SettingValue
____________________________
Setting1     |  Setting1ValueUPDATED

Setting2     |  NewSetting
</code>```

答:
You can use Merge as below</p>

```<code>DECLARE @SettingsToCheck TABLE
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

DECLARE @ActualTable TABLE
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

INSERT INTO @SettingsToCheck
VALUES
('Setting1', 'Setting1 Value') --Repeat...
,('Setting2', 'Setting2 Value')
,('Setting3', 'Setting3 Value')
,('Setting4', 'Setting45 Value')
,('Setting5', 'Setting5 Value')
,('Setting6', 'Setting6 Value')
,('Setting7', 'Setting7 Value')

INSERT INTO @ActualTable
VALUES
 ('Setting4', 'Setting4 Value')

MERGE INTO @ActualTable  AS target
USING @SettingsToCheck AS source
    ON target.SettingName = source.SettingName
WHEN MATCHED THEN
    UPDATE SET target.SettingValue = source.SettingValue
WHEN NOT MATCHED BY TARGET THEN
    INSERT (SettingName, SettingValue)
    VALUES (source.SettingName, source.SettingValue);

Select * from @ActualTable
</code>```

Body:
I am interested to know if there is a better / more optimal solution than what I have so far as it uses a cursor, which I know is not too good performance wise.

Basically my requirement is too check if a number of settings exists for an ID and then update or insert them accordingly.

To do this I have:

DECLARE @UserId UNIQUEIDENTIFIER = '{PUT-GUID-HERE}'

I then declare a table variable which I add the setting names and values to, there are approx 15 of these in total.

DECLARE @SettingsToCheck TABLE (SettingName varchar(100), SettingValue varchar(100)
INSERT INTO @SettingsToCheck ('Setting1', 'Setting1 Value') --Repeat...

DECLARE @CurrentSettingName varchar(100)
DECLARE @CurrentSettingValue varchar(100)
DECLARE Settings_Cursor CURSOR FOR SELECT SettingName, SettingValue FROM @SettingsToCheck
OPEN Settings_Cursor

FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
WHILE @@FETCH_STATUS = 0
BEGIN
    IF EXISTS (SELECT * FROM MyActualTable WHERE UserID = @UserId AND SettingName = @CurrentSettingName)
    BEGIN
        UPDATE MyActualTable SET SettingValue = @CurrentSettingValue WHERE UserID = @UserId AND SettingName = @CurrentSettingName
    END
    ELSE
    BEGIN
        INSERT INTO MyActualTableVALUES (NEWID(), @UserId, GETDATE(), @CurrentSettingName, @CurrentSettingValue)
    END

    FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
END

CLOSE Settings_Cursor
DEALLOCATE Settings_Cursor

I know this question is subject to opinion, but I am unaware of any alternatives.

EDIT:

There could be a scenario where some/none or all of the settings already exist. But here's an example.

BEFORE:

SettingName  |  SettingValue
____________________________
Setting1     |  Setting1Value

AFTER:

SettingName  |  SettingValue
____________________________
Setting1     |  Setting1ValueUPDATED

Setting2     |  NewSetting

Body:
You can use Merge as below

DECLARE @SettingsToCheck TABLE
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

DECLARE @ActualTable TABLE
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

INSERT INTO @SettingsToCheck
VALUES
('Setting1', 'Setting1 Value') --Repeat...
,('Setting2', 'Setting2 Value')
,('Setting3', 'Setting3 Value')
,('Setting4', 'Setting45 Value')
,('Setting5', 'Setting5 Value')
,('Setting6', 'Setting6 Value')
,('Setting7', 'Setting7 Value')

INSERT INTO @ActualTable
VALUES
 ('Setting4', 'Setting4 Value')

MERGE INTO @ActualTable  AS target
USING @SettingsToCheck AS source
    ON target.SettingName = source.SettingName
WHEN MATCHED THEN
    UPDATE SET target.SettingValue = source.SettingValue
WHEN NOT MATCHED BY TARGET THEN
    INSERT (SettingName, SettingValue)
    VALUES (source.SettingName, source.SettingValue);

Select * from @ActualTable


问:
Dart SDK is not configured
I installed Flutter and set up Android Studio. Then I cloned an example of flutter on GitHub (https://github.com/flutter/flutter) and launched it in Android Studio, but it warns me "Dart SDK is not configured", this happened to my co-worker as well. But if I create a new project in Android Studio, no problem at all.

What I have done:

Installed Flutter

Installed Android Studio, along with Flutter plugin including Dart plugin

Flutter run in command line works fine, all five tests passed. (See below)

[✓] Flutter (on Mac OS X 10.13.3 17D47, locale en-US, channel dev)
• Flutter version 0.0.22 at /Users/katelyn/flutter
• Framework revision 3001b3307d (7 days ago), 2018-01-30 11:37:15 -0800
• Engine revision 8f2d72b183
• Tools Dart version 2.0.0-dev.16.0
• Engine Dart version 2.0.0-edge.7af4db0ea091dddca6b2da851e6dda8d7f9467e8

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
• Android SDK at /Users/katelyn/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-27, build-tools 27.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] iOS toolchain - develop for iOS devices (Xcode 9.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 9.2, Build version 9C40b
• ios-deploy 1.9.2
• CocoaPods version 1.4.0

[✓] Android Studio (version 3.0)
• Android Studio at /Applications/Android Studio.app/Contents
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] Connected devices
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Last week, I can run their example thru command line (in that dir),

```<code>flutter run
</code>```

but now I it shows some errors with Gradle.

Launching lib/main.dart on Android SDK built for x86 in debug
mode...
Initializing gradle...                                0.7s
Resolving dependencies...

Error running Gradle:
Exit code 1 from: /Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/gradlew app:properties:

FAILURE: Build failed with an exception.

Where:
Build file '/Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/app/build.gradle' line: 20

What went wrong:
A problem occurred evaluating project ':app'.
3

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 0s

Please review your Gradle project setup in the android/ folder.

答:
I recently faced this issue on my MAC device when I was running flutter project on Android Studio

Steps to fix this.

install dart on MAC os using brew (https://dart.dev/get-dart)

brew tap dart-lang/dart

brew install dart

run

brew info dart

It will give you output something like this

Please note the path to the Dart SDK:/usr/local/opt/dart/libexec

paste the Dart SDK path in Android Studio Settings

Title: Dart SDK is not configured

Body:
I installed Flutter and set up Android Studio. Then I cloned an example of flutter on GitHub (https://github.com/flutter/flutter) and launched it in Android Studio, but it warns me "Dart SDK is not configured", this happened to my co-worker as well. But if I create a new project in Android Studio, no problem at all.

What I have done:

Installed Flutter

Installed Android Studio, along with Flutter plugin including Dart plugin

Flutter run in command line works fine, all five tests passed. (See below)

[✓] Flutter (on Mac OS X 10.13.3 17D47, locale en-US, channel dev)
• Flutter version 0.0.22 at /Users/katelyn/flutter
• Framework revision 3001b3307d (7 days ago), 2018-01-30 11:37:15 -0800
• Engine revision 8f2d72b183
• Tools Dart version 2.0.0-dev.16.0
• Engine Dart version 2.0.0-edge.7af4db0ea091dddca6b2da851e6dda8d7f9467e8

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
• Android SDK at /Users/katelyn/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-27, build-tools 27.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] iOS toolchain - develop for iOS devices (Xcode 9.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 9.2, Build version 9C40b
• ios-deploy 1.9.2
• CocoaPods version 1.4.0

[✓] Android Studio (version 3.0)
• Android Studio at /Applications/Android Studio.app/Contents
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] Connected devices
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Last week, I can run their example thru command line (in that dir),

flutter run

but now I it shows some errors with Gradle.

Launching lib/main.dart on Android SDK built for x86 in debug
mode...
Initializing gradle...                                0.7s
Resolving dependencies...

Error running Gradle:
Exit code 1 from: /Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/gradlew app:properties:

FAILURE: Build failed with an exception.

Where:
Build file '/Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/app/build.gradle' line: 20

What went wrong:
A problem occurred evaluating project ':app'.
3

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Get more help at https://help.gradle.org

BUILD FAILED in 0s

Please review your Gradle project setup in the android/ folder.


问:
Troubleshooting "TypeError: ord() expected string of length 1, but int found"
```<code>ERROR : TypeError: ord() expected string of length 1, but int found
</code>```

I am getting this error while compiling the program.

```<code> File "C:\Users\Administrator\Desktop\tracer1.py", line 129, in <module>
    get_route("www.google.com")
  File "C:\Users\Administrator\Desktop\tracer1.py", line 85, in get_route
    d = build_packet()
  File "C:\Users\Administrator\Desktop\tracer1.py", line 62, in build_packet
    myChecksum = checksum(header + data)
  File "C:\Users\Administrator\Desktop\tracer1.py", line 28, in checksum
    thisVal = ord(str[count+1]) * 256 + ord(str[count])
**TypeError: ord() expected string of length 1, but int found**
</code>```

the program is to find the traceroute using ICMP

```<code>from socket import *
import socket
import os
import sys
import struct
import time
import select
import binascii
import ctypes
ICMP_ECHO_REQUEST = 8
MAX_HOPS = 30
TIMEOUT = 2.0
TRIES = 2

# The packet that we shall send to each router along the path is the ICMP echo
# request packet, which is exactly what we had used in the ICMP ping exercise.
# We shall use the same packet that we built in the Ping exercise

ctypes.windll.shell32.IsUserAnAdmin()
print (ctypes.windll.shell32.IsUserAnAdmin())

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2
    count = 0

    while count < countTo:
        thisVal = ord(str[count+1]) * 256 + ord(str[count])
        csum = csum + thisVal
        csum = csum & 0xffffffff
        count = count + 2

    if countTo < len(str):
        csum = csum + ord(str[len(str) - 1])
        csum = csum & 0xffffffff

    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer

def build_packet():
    # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our
    # packet to be sent was made, secondly the checksum was appended to the header and
    # then finally the complete packet was sent to the destination.

    # Make the header in a similar way to the ping exercise.
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    myChecksum = 0
    pid = os.getpid() & 0xFFFF

    # Make a dummy header with a 0 checksum.
    # struct -- Interpret strings as packed binary data
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
    #header = struct.pack("!HHHHH", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
    data = struct.pack("d", time.time())

    # Calculate the checksum on the data and the dummy header.
    # Append checksum to the header.
    myChecksum = checksum(header + data)
    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
        #Convert 16-bit integers from host to network byte order.
    else:
        myChecksum = htons(myChecksum)

    packet = header + data
    return packet

def get_route(hostname):
    timeLeft = TIMEOUT
    for ttl in range(1,MAX_HOPS):
        for tries in range(TRIES):
            destAddr = socket.gethostbyname(hostname)
            #Fill in start
            # Make a raw socket named mySocket
            mySocket = socket.socket(AF_INET, SOCK_RAW, getprotobyname("icmp"))
            mySocket.bind(("", 12000));
            #Fill in end
            mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
            mySocket.settimeout(TIMEOUT)
            try:
                d = build_packet()
                mySocket.sendto(d, (hostname, 0))
                t = time.time()
                startedSelect = time.time()
                whatReady = select.select([mySocket], [], [], timeLeft)
                howLongInSelect = (time.time() - startedSelect)
                if whatReady[0] == []: # Timeout
                    print ("*    *    * Request timed out.")

                recvPacket, addr = mySocket.recvfrom(1024)
                print ("addr")
                timeReceived = time.time()
                timeLeft = timeLeft - howLongInSelect
                if timeLeft <= 0:
                    print ("*    *    * Request timed out.")
            except socket.timeout:
                continue
            else:
                #Fill in start
                # Fetch the icmp type from the IP packet
                print( struct.calcsize("bbHHhd"))
                request_code, request_type, checksum, packet_id, \
                    sequence, timeSent, data = struct.unpack("bbHHhd", recvPacket,0)
                #Fill in end

                if request_type == 11:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
                elif request_type == 3:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
                elif request_type == 0:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -timeSent)*1000, addr[0]))
                    return
                else:
                    print ("error")
                    break
            finally:
                mySocket.close()

get_route("www.google.com")
</code>```

答:
I encountered today a similar type of error. I added this answer here to highlight certain observations. The main API to focus here is triple_des. If the input is qqq, then it will cause the error. If the input is sMAC, then there is no error. Interestingly, qqq == sMAC is true. Furthermore, both variable's print via binascii shows similar value. Variable qqq came from bytearray.fromhex('7A414086D86A4BF5554AE6FBC4AC0465') and variable sMAC came from "7A414086D86A4BF5554AE6FBC4AC0465",decode('hex').

```<code>>>> qqq[0]
122
>>> sMAC[0]
'z'
>>> qqq == sMAC
True
>>> binascii.hexlify(sMAC)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> binascii.hexlify(qqq)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> qqq == sMAC
True
>>> repr(qqq)
"bytearray(b'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e')"
>>> repr(sMAC)
"'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e'"
>>> cipher1 = triple_des(qqq,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 710, in __init__
    self.setKey(key)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 727, in setKey
    self._padding, self._padmode)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 409, in __init__
    self.setKey(key)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 414, in setKey
    self.__create_sub_keys()
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 462, in __create_sub_keys
    key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 421, in __String_to_BitList
    data = [ord(c) for c in data]
TypeError: ord() expected string of length 1, but int found
>>> cipher1 = triple_des(sMAC,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
>>>
</code>```

Hope this additional detail helps.

Body:
ERROR : TypeError: ord() expected string of length 1, but int found

I am getting this error while compiling the program.

 File "C:\Users\Administrator\Desktop\tracer1.py", line 129, in <module>
    get_route("www.google.com")
  File "C:\Users\Administrator\Desktop\tracer1.py", line 85, in get_route
    d = build_packet()
  File "C:\Users\Administrator\Desktop\tracer1.py", line 62, in build_packet
    myChecksum = checksum(header + data)
  File "C:\Users\Administrator\Desktop\tracer1.py", line 28, in checksum
    thisVal = ord(str[count+1]) * 256 + ord(str[count])
**TypeError: ord() expected string of length 1, but int found**

the program is to find the traceroute using ICMP

from socket import *
import socket
import os
import sys
import struct
import time
import select
import binascii
import ctypes
ICMP_ECHO_REQUEST = 8
MAX_HOPS = 30
TIMEOUT = 2.0
TRIES = 2

# The packet that we shall send to each router along the path is the ICMP echo
# request packet, which is exactly what we had used in the ICMP ping exercise.
# We shall use the same packet that we built in the Ping exercise

ctypes.windll.shell32.IsUserAnAdmin()
print (ctypes.windll.shell32.IsUserAnAdmin())

def checksum(str):
    csum = 0
    countTo = (len(str) / 2) * 2
    count = 0

    while count < countTo:
        thisVal = ord(str[count+1]) * 256 + ord(str[count])
        csum = csum + thisVal
        csum = csum & 0xffffffff
        count = count + 2

    if countTo < len(str):
        csum = csum + ord(str[len(str) - 1])
        csum = csum & 0xffffffff

    csum = (csum >> 16) + (csum & 0xffff)
    csum = csum + (csum >> 16)
    answer = ~csum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer

def build_packet():
    # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our
    # packet to be sent was made, secondly the checksum was appended to the header and
    # then finally the complete packet was sent to the destination.

    # Make the header in a similar way to the ping exercise.
    # Header is type (8), code (8), checksum (16), id (16), sequence (16)
    myChecksum = 0
    pid = os.getpid() & 0xFFFF

    # Make a dummy header with a 0 checksum.
    # struct -- Interpret strings as packed binary data
    header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
    #header = struct.pack("!HHHHH", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
    data = struct.pack("d", time.time())

    # Calculate the checksum on the data and the dummy header.
    # Append checksum to the header.
    myChecksum = checksum(header + data)
    if sys.platform == 'darwin':
        myChecksum = socket.htons(myChecksum) & 0xffff
        #Convert 16-bit integers from host to network byte order.
    else:
        myChecksum = htons(myChecksum)

    packet = header + data
    return packet

def get_route(hostname):
    timeLeft = TIMEOUT
    for ttl in range(1,MAX_HOPS):
        for tries in range(TRIES):
            destAddr = socket.gethostbyname(hostname)
            #Fill in start
            # Make a raw socket named mySocket
            mySocket = socket.socket(AF_INET, SOCK_RAW, getprotobyname("icmp"))
            mySocket.bind(("", 12000));
            #Fill in end
            mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
            mySocket.settimeout(TIMEOUT)
            try:
                d = build_packet()
                mySocket.sendto(d, (hostname, 0))
                t = time.time()
                startedSelect = time.time()
                whatReady = select.select([mySocket], [], [], timeLeft)
                howLongInSelect = (time.time() - startedSelect)
                if whatReady[0] == []: # Timeout
                    print ("*    *    * Request timed out.")

                recvPacket, addr = mySocket.recvfrom(1024)
                print ("addr")
                timeReceived = time.time()
                timeLeft = timeLeft - howLongInSelect
                if timeLeft <= 0:
                    print ("*    *    * Request timed out.")
            except socket.timeout:
                continue
            else:
                #Fill in start
                # Fetch the icmp type from the IP packet
                print( struct.calcsize("bbHHhd"))
                request_code, request_type, checksum, packet_id, \
                    sequence, timeSent, data = struct.unpack("bbHHhd", recvPacket,0)
                #Fill in end

                if request_type == 11:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
                elif request_type == 3:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -t)*1000, addr[0]))
                elif request_type == 0:
                    bytes = struct.calcsize("d")
                    timeSent = struct.unpack("d", recvPacket[28:28 + bytes])[0]
                    print (" %d   rtt=%.0f ms %s" % (ttl,(timeReceived -timeSent)*1000, addr[0]))
                    return
                else:
                    print ("error")
                    break
            finally:
                mySocket.close()

get_route("www.google.com")

Body:
I encountered today a similar type of error. I added this answer here to highlight certain observations. The main API to focus here is triple_des. If the input is qqq, then it will cause the error. If the input is sMAC, then there is no error. Interestingly, qqq == sMAC is true. Furthermore, both variable's print via binascii shows similar value. Variable qqq came from bytearray.fromhex('7A414086D86A4BF5554AE6FBC4AC0465') and variable sMAC came from "7A414086D86A4BF5554AE6FBC4AC0465",decode('hex').

>>> qqq[0]
122
>>> sMAC[0]
'z'
>>> qqq == sMAC
True
>>> binascii.hexlify(sMAC)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> binascii.hexlify(qqq)
'7a414086d86a4bf5554ae6fbc4ac0465'
>>> qqq == sMAC
True
>>> repr(qqq)
"bytearray(b'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e')"
>>> repr(sMAC)
"'zA@\\x86\\xd8jK\\xf5UJ\\xe6\\xfb\\xc4\\xac\\x04e'"
>>> cipher1 = triple_des(qqq,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 710, in __init__
    self.setKey(key)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 727, in setKey
    self._padding, self._padmode)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 409, in __init__
    self.setKey(key)
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 414, in setKey
    self.__create_sub_keys()
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 462, in __create_sub_keys
    key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey()))
  File "/home/john/.local/lib/python2.7/site-packages/pyDes.py", line 421, in __String_to_BitList
    data = [ord(c) for c in data]
TypeError: ord() expected string of length 1, but int found
>>> cipher1 = triple_des(sMAC,CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=PAD_PKCS5)
>>>

Hope this additional detail helps.


问:
Could not load file or assembly 'App_Code' or one of its dependencies.
Problem: I want to deploy modified code into web server. web server is having IIS version set to V2.0. and now I have developed and published code on my local machine with version 4.0. (there is App_code.dll as part of all dll files).

Now whenever I am deploying all files along with App_code.dll I am getting following error:"
Could not load file or assembly 'App_Code' or one of its dependencies.
This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

1) My question is how do I build App_code.dll in older version.
2) I tried changing target framework to V2.0 while publishing but then its not working because AJAX functions from other dll are not compiling..

can anyone please suggest what to do to run the site..

Help is appreciated.

Thanks

答:
Late answer but, I'm writing this for future viewers.
I had same error after publish the application to the Server.
I figure it out doing like this.

While publish there is configuration in Setting.

In publish section there is option called

Precompile during publishing

you have to check the checkbox and save then Publish. This will takes your code files .vb/.cs and converts them into a compiled DLL files.
In my case it was unchecked.


问:
SVG in Vuejs vfor loop for categories from WP REST API
I've been trying to add svg's from a sprite.svg file into a loop that get the categories from the wordpress rest api but I'm stuggling to find a way of adding them using the category name where I stated "INSERT-HERE". In the sprite.svg they correspond with the category name. This is one of my first projects that Im doing so any help would be appreciated.

<template>

                <router-link :to="{path: `/blog/${category.name}`}" active-class="active" class="flex items-center" exact>
                    <svg :class="`group-hover:fill-${category.id}`" class="w-1/5 h-12 pr-3 fill-default">
                        <use href="../assets/svg/sprite.svg#INSERT-HERE"></use>
                    </svg>
                    <h3 :class="`group-hover:text-${category.id}`" class="text-xl font-semibold">{{ category.name }}

                </router-link>

        <router-view></router-view>

</template>```

Thanks

答:
You may try this:

```<code><use :href=`../assets/svg/sprite.svg#${category.name}`></use>
</code>```

Or this:

```<code><use :href="'../assets/svg/sprite.svg#' + category.name + '"></use>
</code>```

Body:
I've been trying to add svg's from a sprite.svg file into a loop that get the categories from the wordpress rest api but I'm stuggling to find a way of adding them using the category name where I stated "INSERT-HERE". In the sprite.svg they correspond with the category name. This is one of my first projects that Im doing so any help would be appreciated.

<template>

                <router-link :to="{path: `/blog/${category.name}`}" active-class="active" class="flex items-center" exact>
                    <svg :class="`group-hover:fill-${category.id}`" class="w-1/5 h-12 pr-3 fill-default">
                        <use href="../assets/svg/sprite.svg#INSERT-HERE"></use>
                    </svg>
                    <h3 :class="`group-hover:text-${category.id}`" class="text-xl font-semibold">{{ category.name }}

                </router-link>

        <router-view></router-view>

</template>

Thanks

Body:
You may try this:

<use :href=`../assets/svg/sprite.svg#${category.name}`></use>

Or this:

<use :href="'../assets/svg/sprite.svg#' + category.name + '"></use>


问:
Multiple Images Upload Field in Django
I am new to Django and i am using this tutorial to add a multiple image upload field to a model in my web application. So far i am stuck (I am unable to link the uploaded photos to Hotel model. The Photos get uploaded but are not associated with the hotel model) at how to associate my Photo Model to the Hotels Model on the HotelCreateView. My question is how do i associate this multiple image filed with my Hotel model so that on creating the hotel the images uploaded are linked to the created hotel. Kindly assist.

Thanks alot

Hotel Model

```<code>class Hotels(models.Model):
    """Stores all the information about the hotel and also used to query hotels"""

    name = models.CharField(max_length=255) #The name of the hotel
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    mobile_number = models.CharField(max_length=12)
    created_at = models.DateTimeField(default=timezone.now)
    last_modified = models.DateTimeField(auto_now=True)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
    star_rating = models.PositiveIntegerField()
    contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel

    class Meta:
        unique_together = ('name', 'slug')
        verbose_name_plural = 'Hotels'
</code>```

Photo Model

```<code>class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,)

    class Meta:
        verbose_name_plural = 'Photos'

    def __str__(self):
        """Prints the name of the Photo"""
        return f'{self.hotel} photos'
</code>```

Forms.py

```<code>class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ('hotel','file', )
</code>```

Views.py

```<code>class PhotoUploadView(LoginRequiredMixin,View):
    def get(self, request):
        photos_list = Photo.objects.all()
        return render(self.request, 'hotels/uploads.html', {'photos': photos_list})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES, self.request.user)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.hotel = self.request.hotel.contact_person
            photo.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)
</code>```

答:
There is nothing much wrong with models but you need to make some changes for Photo models

```<code>class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, related_name='photos')
</code>```

Now you should create hotels object first, then when you hit your views for adding images it should set hotel into it by passing hotel id to it or something like that. When in other cases you will be using hotel object you can directly access its photos by using related_name against it.

There also exist other ways to this problem if you can't create hotels beforehand or something like that but for current scenario this approach will work.

Title: Multiple Images Upload Field in Django

Body:
I am new to Django and i am using this tutorial to add a multiple image upload field to a model in my web application. So far i am stuck (I am unable to link the uploaded photos to Hotel model. The Photos get uploaded but are not associated with the hotel model) at how to associate my Photo Model to the Hotels Model on the HotelCreateView. My question is how do i associate this multiple image filed with my Hotel model so that on creating the hotel the images uploaded are linked to the created hotel. Kindly assist.

Thanks alot

Hotel Model

class Hotels(models.Model):
    """Stores all the information about the hotel and also used to query hotels"""

    name = models.CharField(max_length=255) #The name of the hotel
    address = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    country = models.CharField(max_length=255)
    mobile_number = models.CharField(max_length=12)
    created_at = models.DateTimeField(default=timezone.now)
    last_modified = models.DateTimeField(auto_now=True)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
    star_rating = models.PositiveIntegerField()
    contact_person = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True,) #Owner of the hotel or person who created the hotel

    class Meta:
        unique_together = ('name', 'slug')
        verbose_name_plural = 'Hotels'

Photo Model

class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, null=True, blank=True,)

    class Meta:
        verbose_name_plural = 'Photos'

    def __str__(self):
        """Prints the name of the Photo"""
        return f'{self.hotel} photos'

Forms.py

class PhotoForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ('hotel','file', )

Views.py

class PhotoUploadView(LoginRequiredMixin,View):
    def get(self, request):
        photos_list = Photo.objects.all()
        return render(self.request, 'hotels/uploads.html', {'photos': photos_list})

    def post(self, request):
        form = PhotoForm(self.request.POST, self.request.FILES, self.request.user)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.hotel = self.request.hotel.contact_person
            photo.save()
            data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url}
        else:
            data = {'is_valid': False}
        return JsonResponse(data)

Body:
There is nothing much wrong with models but you need to make some changes for Photo models

class Photo(models.Model):
    title = models.CharField(max_length=255, blank=True)
    file = models.ImageField(upload_to='hotel_photos')
    hotel = models.ForeignKey(Hotels,on_delete=models.SET_NULL, related_name='photos')

Now you should create hotels object first, then when you hit your views for adding images it should set hotel into it by passing hotel id to it or something like that. When in other cases you will be using hotel object you can directly access its photos by using related_name against it.

There also exist other ways to this problem if you can't create hotels beforehand or something like that but for current scenario this approach will work.


问:
how to create inline style with :before and :after
I generated a bubble chat thingy from http://www.ilikepixels.co.uk/drop/bubbler/

In my page I put a number inside of it

```<code>.bubble {
  position: relative;
  width: 20px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #FFF;
   display: block;
  width: 0;
  z-index: 1;
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}
</code>```

I want the background-color of the bubble to change according to the number inside of it via rgb

so if my div is

```<code><div class="bubble" style="background-color: rgb(100,255,255);"> 100 </div>
</code>```

I want the color to be rgb(100,255,255)

The thing is this doesn't affect the triangle.

How do I write the inline css so it will include the :before and :after?

答:
I resolved a similar problem by border-color: inherit

, see:

```<code><li style="border-color: <?php echo $hex ?>;">...</li>

li {
    border-width: 0;
}

li:before {
    content: '';
    display: inline-block;
    float: none;
    margin-right: 10px;
    border-width: 4px;
    border-style: solid;
    border-color: inherit;
}
</code>```

Body:
I generated a bubble chat thingy from http://www.ilikepixels.co.uk/drop/bubbler/

In my page I put a number inside of it

.bubble {
  position: relative;
  width: 20px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #FFF;
   display: block;
  width: 0;
  z-index: 1;
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}

I want the background-color of the bubble to change according to the number inside of it via rgb

so if my div is

 100

I want the color to be rgb(100,255,255)

The thing is this doesn't affect the triangle.

How do I write the inline css so it will include the :before and :after?

Body:
I resolved a similar problem by border-color: inherit

, see:

<li style="border-color: <?php echo $hex ?>;">...</li>

li {
    border-width: 0;
}

li:before {
    content: '';
    display: inline-block;
    float: none;
    margin-right: 10px;
    border-width: 4px;
    border-style: solid;
    border-color: inherit;
}


问:
Which are the best alternatives to Lucene?
It may run on Unix and it will be used for email searching (Dovecot, Postfix and maildir).

Lucene is not a problem, I'm just analyzing some alternatives.

答:
The ones I can come up with now is native DBMS-full-text-indexing (MSSQL, MySQL both has implementations for it) aswell as Sphinx http://www.sphinxsearch.com/about.html

The advantage with Sphinx is easier integration with MySQL and PostgreSQL, however Lucene is more feature-rich.

OwnerDisplayName: Rui Carneiro

LastEditorDisplayName: Rui Carneiro

OwnerDisplayName: jishi

ContentLicense: CC BY-SA 2.5


问:
gperftools - profile file not dumped
I've configured and built gpreftools. however, I can't seem to find the generated profile file of my program to display it.

I took the following actions:

Adding the -lprofiler linker flag to my .pro, building the program and the flag is added correctly at the linking stage.
QMAKE_LFLAGS += -lprofiler

Running with:
$ CPUPROFILE=/tmp/prof.out /path/to/executable

Executing:
$ pprof --gv /path/to/MyExe /tmp/prof.out

Then I get the following:

Failed to get profile: curl -s --max-time 90 'http:///pprof/profile?seconds=30' > /home/eslam/pprof/.tmp.MyExe.1509005857.: No such file or directory.

Anyone has a resolve on this?

答:
LD_PRELOAD method without rebuild

Besides passing -Wl,--no-as-needed,-lprofiler,--as-needed at build time mentioned by Eslam, you can also get it to work without modifying the build by passing the LD_PRELOAD option at runtime as:

```<code>LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libprofiler.so CPUPROFILE=prof.out ./main.out
</code>```

You can find libprofiler.so easily with locate libprofiler.so.

See also: How can I profile C++ code running on Linux?

Tested in Ubuntu 18.04.

Title: gperftools - profile file not dumped

Body:
LD_PRELOAD method without rebuild

Besides passing -Wl,--no-as-needed,-lprofiler,--as-needed at build time mentioned by Eslam, you can also get it to work without modifying the build by passing the LD_PRELOAD option at runtime as:

LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libprofiler.so CPUPROFILE=prof.out ./main.out

You can find libprofiler.so easily with locate libprofiler.so.

See also: How can I profile C++ code running on Linux?

Tested in Ubuntu 18.04.


问:
PayPal transaction with a mix of one time and recurring payments using Smart Payment Buttons
My project runs on products with both the one time and recurring payments.

Right now I'm trying to integrate the paypal smart buttons, which would create one transaction consisting of one time and recurring payments.

For example: The user adds to the cart Product1 (5$ one time payment) and Product2 (15$ recurring payment), which makes it a 20$ transaction.

Is it possible to charge the user 20$ in the beginning and set a trial on the recurring product (Product2 in our case), which would charge the user from the next billing period?

Here's what I tried:

On the js side I have the following code

```<code>createPayPalButton = function() {

    // setting up the details for the transaction
    createOrder: function (data, actions) {
            return actions.order.create({
                purchase_units: [{
                    amount: {
                        value: '20.00'
                    }
                }]
            })
        },

     // setting up the details for subscription
     createSubscription: function (data, actions) {
            return actions.subscription.create({
                'plan_id': 'MY_PLAN_ID'
            });
     },
}

$(function() {
    createPayPalButton();
})
</code>```

But after running it I receive the following error:

Uncaught Error: Do not pass both createSubscription and createOrder

I tried to find a solution on the paypal side, but I didn't manage to.

Any guidance would be much appreciated. Thank you.

答:
You could create a new bespoke plan with a setup_fee that corresponds to the amount of the one-time order.

Otherwise you need a separate checkout and transaction.

Body:
My project runs on products with both the one time and recurring payments.

Right now I'm trying to integrate the paypal smart buttons, which would create one transaction consisting of one time and recurring payments.

For example: The user adds to the cart Product1 (5$ one time payment) and Product2 (15$ recurring payment), which makes it a 20$ transaction.

Is it possible to charge the user 20$ in the beginning and set a trial on the recurring product (Product2 in our case), which would charge the user from the next billing period?

Here's what I tried:

On the js side I have the following code

createPayPalButton = function() {

    // setting up the details for the transaction
    createOrder: function (data, actions) {
            return actions.order.create({
                purchase_units: [{
                    amount: {
                        value: '20.00'
                    }
                }]
            })
        },

     // setting up the details for subscription
     createSubscription: function (data, actions) {
            return actions.subscription.create({
                'plan_id': 'MY_PLAN_ID'
            });
     },
}

$(function() {
    createPayPalButton();
})

But after running it I receive the following error:

Uncaught Error: Do not pass both createSubscription and createOrder

I tried to find a solution on the paypal side, but I didn't manage to.

Any guidance would be much appreciated. Thank you.


问:
Getting data between certain dates for the entries which are not present before the time period mentioned
I have this date set table:

```<code>Product     Entry_Date
1-A         18-02-2020
2-A         19-02-2020
1-A         23-02-2020
3-C         25-02-2020
4-D         26-02-2020
2-A         27-02-2020
</code>```

I need those products which have Entry_Date between 23rd to 27th Feb BUT do not have entries before.
For eg. the output should be

```<code>Product
3-C
4-D
</code>```

I tried two approaches:
This works:

```<code>select Product
from table a join (select Product, min(Entry_date) as min_date from table) b on a.Product = b.Product
where Entry_date between '23-02-2020' and '27-02-2020'
and b.min_date >='23-02-2020'
</code>```

and this does not:

```<code>select Product
from table
where Entry_Date between '23-02-2020' and '27-02-2020'
group by 1
having min(Entry_Date)>='23-02-2020'
</code>```

Is there any elegant way of doing this. Why does the second method does not work?

答:
Use aggregation and min() in the having clause:

```<code>select product
from t
group by product
having min(Entry_Date) between '2020-02-23' and '2020-02-27';
</code>```

Here is a db<>fiddle.

Note that I also fixed your date constants so they are YYYY-MM-DD standard.

Body:
I have this date set table:

Product     Entry_Date
1-A         18-02-2020
2-A         19-02-2020
1-A         23-02-2020
3-C         25-02-2020
4-D         26-02-2020
2-A         27-02-2020

I need those products which have Entry_Date between 23rd to 27th Feb BUT do not have entries before.
For eg. the output should be

Product
3-C
4-D

I tried two approaches:
This works:

select Product
from table a join (select Product, min(Entry_date) as min_date from table) b on a.Product = b.Product
where Entry_date between '23-02-2020' and '27-02-2020'
and b.min_date >='23-02-2020'

and this does not:

select Product
from table
where Entry_Date between '23-02-2020' and '27-02-2020'
group by 1
having min(Entry_Date)>='23-02-2020'

Is there any elegant way of doing this. Why does the second method does not work?

Body:
Use aggregation and min() in the having clause:

select product
from t
group by product
having min(Entry_Date) between '2020-02-23' and '2020-02-27';

Here is a db<>fiddle.

Note that I also fixed your date constants so they are YYYY-MM-DD standard.