问:
Moqing DI-ed DbContext in .net core
I started writing tests for a (webapi) application in .net core using ef core.
The repositories I want to test look like this:

```<code>   public class MyRepository : IMyRepository
   {
   private readonly IDbContext Db;
   public MyReporitory(IDbContext db)
      {
         Db = db;
      }
   /// Methods to access the Database
      public List<MyType> Get() {
         return Db.Set<Type>();
      }
</code>```

In my test I now try to mock the DBContext:

```<code> var dbContextMock = new Mock<IDBContext>();
 var classToBeTested = new MyRepository(dbContextMock)
 var result = classToBeTested.Get() (or any other method in my repository);
 Assert.That(result, Is.TypeOf<MyType>)
</code>```

When I run the test I get a null exception since the returned result is null (and I didnt tell the mock how to return data?)
How would I add data to the mocked DbContext so the Get() can get it?

答:
Use moq setup to return data. If I am correct you have created an Set method in your interface. Just mock that method

If your set method returns an DbSet type then you can mock it with this bit of code

```<code>        var mockDbSet = new Mock<DbSet<TestClass>>();
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Provider).Returns(data.Provider);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Expression).Returns(data.Expression);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator);
</code>```

data is of an type IQueryable

Title: Moqing DI-ed DbContext in .net core

Body:
I started writing tests for a (webapi) application in .net core using ef core.
The repositories I want to test look like this:

   public class MyRepository : IMyRepository
   {
   private readonly IDbContext Db;
   public MyReporitory(IDbContext db)
      {
         Db = db;
      }
   /// Methods to access the Database
      public List<MyType> Get() {
         return Db.Set<Type>();
      }

In my test I now try to mock the DBContext:

 var dbContextMock = new Mock<IDBContext>();
 var classToBeTested = new MyRepository(dbContextMock)
 var result = classToBeTested.Get() (or any other method in my repository);
 Assert.That(result, Is.TypeOf<MyType>)

When I run the test I get a null exception since the returned result is null (and I didnt tell the mock how to return data?)
How would I add data to the mocked DbContext so the Get() can get it?

Body:
Use moq setup to return data. If I am correct you have created an Set method in your interface. Just mock that method

If your set method returns an DbSet type then you can mock it with this bit of code

        var mockDbSet = new Mock<DbSet<TestClass>>();
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Provider).Returns(data.Provider);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.Expression).Returns(data.Expression);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockDbSet.As<IQueryable<TestClass>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator);

data is of an type IQueryable


来源: stackexchange

问:
Electron / node - Snipppets using require and readFile makes javascript fail
I use Electron which uses NodeJS. I started with a single very long HTML file. Now I want to split it up, similar to PHP require. I managed to do so with require and readFile.

However after using this approach my javascript stopped working. My guess is that my whole approach is wrong.

Inline script

const fs = require('fs');
require('./assets/js/snippets.js');
```

<h2>snippets.js</h2>

<pre class="lang-js prettyprint-override"><code>function snippet(name) {
  fs.readFile('snippets/' + name + '.html', function (err, data) {
    document.querySelector('[snippet-' + name + ']').innerHTML = data.toString();
  });
}

snippet('header');
snippet('post');
snippet('footer);
</code>```

What is the correct way to do this? Can I use the built in functions or do I need an exernal library?

答:
readFileSynccan be used instead of readFile.

https://stackoverflow.com/a/56110224/148496

ContentLicense: CC BY-SA 4.0

Body:
I use Electron which uses NodeJS. I started with a single very long HTML file. Now I want to split it up, similar to PHP require. I managed to do so with require and readFile.

However after using this approach my javascript stopped working. My guess is that my whole approach is wrong.

Inline script

const fs = require('fs');
require('./assets/js/snippets.js');

snippets.js

function snippet(name) {
  fs.readFile('snippets/' + name + '.html', function (err, data) {
    document.querySelector('[snippet-' + name + ']').innerHTML = data.toString();
  });
}

snippet('header');
snippet('post');
snippet('footer);

What is the correct way to do this? Can I use the built in functions or do I need an exernal library?


问:
Azure App Service deploy task option to remove files in container upon deployment
I am deploying a python web app using Web App on Linux service and using a DevOps release pipeline. The pipeline task that I am using is called AzureRmWebAppDeployment@4.

Between deployments, the files in the container are not being removed and this is causing issues.

I noticed if I am using a different type of app service (i.e. Web App on Windows) and if the deployment method is set to Web Deploy the option for Remove additional files at destination exists (see screenshot). However we are using a Zip Deploy method and prefer to be using a linux service. without that combination of app service and deployment method, this option is not available to me.

Can anybody suggest an alternate method for deleting the container contents upon deployment? Also, any insight as to why this option is not available through the pipeline task when using Zip Deploy and Linux?

Thanks in advance for any help provided.

答:
You can use kudu command api to clean the wwwroot folder on your webapp server. The kudu command rest api will execute the command in the specified directory on the server.

```<code>{
    command = "find . -mindepth 1 -delete"
    dir = "/home/site/wwwroot
}
</code>```

Add an Azure powershell task before Azure app service deploy task, and run below inline scripts.

```<code>$ResGroupName = ""
$WebAppName = ""

# Get publishing profile for web application
$WebApp = Get-AzWebApp -Name $WebAppName -ResourceGroupName $ResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $WebApp

# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

$bodyToPOST = @{
                  command = "find . -mindepth 1 -delete"
                  dir = "/home/site/wwwroot"
}
# Splat all parameters together in $param
$param = @{
            # command REST API url
            Uri = "https://$WebAppName.scm.azurewebsites.net/api/command"
            Headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
            Method = "POST"
            Body = (ConvertTo-Json $bodyToPOST)
            ContentType = "application/json"
}
# Invoke REST call
Invoke-RestMethod @param
</code>```

Above scripts will empty the folder /home/site/wwwroot before each deployment.

If you need to delete specific files on the app server, you can use kudu delete rest api:

```<code>DELETE /api/vfs/{path}
Delete the file at path.
</code>```

For more examples you can check here.

Body:
You can use kudu command api to clean the wwwroot folder on your webapp server. The kudu command rest api will execute the command in the specified directory on the server.

{
    command = "find . -mindepth 1 -delete"
    dir = "/home/site/wwwroot
}

Add an Azure powershell task before Azure app service deploy task, and run below inline scripts.

$ResGroupName = ""
$WebAppName = ""

# Get publishing profile for web application
$WebApp = Get-AzWebApp -Name $WebAppName -ResourceGroupName $ResGroupName
[xml]$publishingProfile = Get-AzWebAppPublishingProfile -WebApp $WebApp

# Create Base64 authorization header
$username = $publishingProfile.publishData.publishProfile[0].userName
$password = $publishingProfile.publishData.publishProfile[0].userPWD
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

$bodyToPOST = @{
                  command = "find . -mindepth 1 -delete"
                  dir = "/home/site/wwwroot"
}
# Splat all parameters together in $param
$param = @{
            # command REST API url
            Uri = "https://$WebAppName.scm.azurewebsites.net/api/command"
            Headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
            Method = "POST"
            Body = (ConvertTo-Json $bodyToPOST)
            ContentType = "application/json"
}
# Invoke REST call
Invoke-RestMethod @param

Above scripts will empty the folder /home/site/wwwroot before each deployment.

If you need to delete specific files on the app server, you can use kudu delete rest api:

DELETE /api/vfs/{path}
Delete the file at path.

For more examples you can check here.


问:
how to reset javascript variable declared by keyword var?
I have an 'init' function in which i have  few variables which i want to set as undefined/null on logout event.

```<code>var EmpCode;
function initChat(user, usertoken, ip){
  if(user!= null){
    EmpCode = user;
    var time_id = Date.now();
//some function calls.
}

function logout(){
//reset variable
}
</code>```

i want to reset 'EmpCode' variable value on on logout function.

delete EmpCode; does not seems to work because it is defined by keyword var.

答:
```<code>function logout(){
  //reset variable
  EmpCode = undefined; // or null
}
</code>```

Body:
I have an 'init' function in which i have  few variables which i want to set as undefined/null on logout event.

var EmpCode;
function initChat(user, usertoken, ip){
  if(user!= null){
    EmpCode = user;
    var time_id = Date.now();
//some function calls.
}

function logout(){
//reset variable
}

i want to reset 'EmpCode' variable value on on logout function.

delete EmpCode; does not seems to work because it is defined by keyword var.


问:
Problem with XslCompiledTransform and xslt in VB.NET
I am getting now where with this. I have an XML document that must be transformed using an xslt sheet. My code is as follows:

```<code>        Dim xStream As New IO.MemoryStream

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strLKxsl)

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strXSLfolder & "xslt_lookup.xslt")

        ' Create the XsltArgumentList.
        Dim xslArg As New XsltArgumentList()

        Using w As XmlWriter = XmlWriter.Create(xStream)
            ' Transform the file.
            xslt.Transform(xmldLookup, Nothing, w)
        End Using
</code>```

I get the following error at the xslt.Transform(xmldLookup, Nothing, w) line:

Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

This is the contents of the XMl file:

```<code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="includes/xslt_lookup.xslt"?>
<lookup xmlns="logis-online:lk"
title="<Document Title>"
nexturl="<URL>">

  <search visible="false">
    <field id="SUPPLIER_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="WEB_STORE_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="REST" hidden="true" size="40" value="" />
    <field id="LOOKUP_ACTION" hidden="true" size="1" value="<Value>" />
    <field id="WEB_ACTION" hidden="true" size="2" value="<Value>" />
  </search>
  <results>
    <header>
      <section>
        <item id="SUPPLIER_NO" title="Supplier No" value="<Value>"
        HelpID="10" />
        <item id="SUPPLIER_NAME_SHORT" title="Supplier Name"
        value="<Value>" HelpID="10" />
        <item id="LIABLE_STORE_NO" title="Liable Store No"
        value="<Value>" HelpID="98" />
      </section>
    </header>
    <list target="<lookup aspx page>" />
  </results>
</lookup>
</code>```

答:
This message is self-explanatory. It means that the result of the XSLT transformation is not a well-formed document and in order to force the XmlWriter to write such a thing, its ConformanceLevel setting must be set/specified as either ConformanceLevel.Fragment or ConformanceLevel.Auto. Read more about "Data conformance nad the XmlWriter" here.

If the XSLT transformation is not intended to produce an XML document, it is better not to specify an XmlWriter for producing the result. A better choice would be a to use a Transform() overload that accepts a TextWriter argument.

Otherwise, you could simply write directly to a stream (not specifying any XmlWriter).

Or, create an XmlWriter using the appropriate XmlWriterSettings (specify ConformanceLevel.Fragment or ConformanceLevel.Auto).

Or, if the XSLT transformation must produce an XML document -- debug and fix it.

ContentLicense: CC BY-SA 3.0

Body:
I am getting now where with this. I have an XML document that must be transformed using an xslt sheet. My code is as follows:

        Dim xStream As New IO.MemoryStream

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strLKxsl)

        ' Create the XslCompiledTransform and load the stylesheet.
        Dim xslt As New XslCompiledTransform()
        xslt.Load(strXSLfolder & "xslt_lookup.xslt")

        ' Create the XsltArgumentList.
        Dim xslArg As New XsltArgumentList()

        Using w As XmlWriter = XmlWriter.Create(xStream)
            ' Transform the file.
            xslt.Transform(xmldLookup, Nothing, w)
        End Using

I get the following error at the xslt.Transform(xmldLookup, Nothing, w) line:

Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.

This is the contents of the XMl file:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="includes/xslt_lookup.xslt"?>
<lookup xmlns="logis-online:lk"
title="<Document Title>"
nexturl="<URL>">

  <search visible="false">
    <field id="SUPPLIER_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="WEB_STORE_NO" hidden="true" size="10"
    value="<Value>" />
    <field id="REST" hidden="true" size="40" value="" />
    <field id="LOOKUP_ACTION" hidden="true" size="1" value="<Value>" />
    <field id="WEB_ACTION" hidden="true" size="2" value="<Value>" />
  </search>
  <results>

        <item id="SUPPLIER_NO" title="Supplier No" value="<Value>"
        HelpID="10" />
        <item id="SUPPLIER_NAME_SHORT" title="Supplier Name"
        value="<Value>" HelpID="10" />
        <item id="LIABLE_STORE_NO" title="Liable Store No"
        value="<Value>" HelpID="98" />

    <list target="<lookup aspx page>" />
  </results>
</lookup>


问:
Should I make the method virtual or abstract?
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

```<code>protected abstract bool ValidateFurther();
</code>```

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

```<code>protected virtual bool ValidateFurther() => true;
</code>```

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

答:
It's okay to make the method virtual and define a default implementation returning true.

```<code>protected virtual bool ValidateFurther() => true;
</code>```

The difference between abstract and virtual is that that abstract methods defines only the signature of a method and the implementation is left to be implemented by the derived classes(similar to an interface). All child classes are required to implement the logic of an abstract method. You can see the documentation for more details.

Virtual on the other hand requires you to implement the logic and if needed you can override that method to add/extend the logic. And because you have default logic your child/derived classes are not required to override it. You can see the documnetation for more details.

Basically it is okay to implement the method as virtual and return true; by default.

FYI: From C# 8 you can have default implementations in the interfaces link

Body:
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

protected abstract bool ValidateFurther();

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

protected virtual bool ValidateFurther() => true;

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

Body:
It's okay to make the method virtual and define a default implementation returning true.

protected virtual bool ValidateFurther() => true;

The difference between abstract and virtual is that that abstract methods defines only the signature of a method and the implementation is left to be implemented by the derived classes(similar to an interface). All child classes are required to implement the logic of an abstract method. You can see the documentation for more details.

Virtual on the other hand requires you to implement the logic and if needed you can override that method to add/extend the logic. And because you have default logic your child/derived classes are not required to override it. You can see the documnetation for more details.

Basically it is okay to implement the method as virtual and return true; by default.

FYI: From C# 8 you can have default implementations in the interfaces link


问:
Is it possible to display an output with a scanner above the output?
I have a program here that includes only scanners and outputs. What I wanted the program to show is that to display a scanner with the output below.

```<code>public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter anything: ");
     scan.nextLine();

    //while the scanner's text cursor shows, the bottom texts below also shows.

    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");

/*  what I wanted the output to show is this:

Enter anything: | << text cursor
bottom text
bottom text
bottom text
bottom text
bottom text
bottom text
bottom text

but the output shows like this instead:

Enter anything: |

*/

}//end of method

}
</code>```

Because it only shows the output below after the scanner has been used. Is it possible or is there any way to show the scanner and the bottom text at the same time? TIA :)

答:
I tried this...

CompletableFuture will spin off a new thread using runAsync( () -> { return null; } ) you can also use supplyAsync(() -> { returns anObject }) if you want to get a result from the thread. You can then chain additional threads which can be consumers/suppliers or a bit of both.

```<code>public static void main(String[] args) {
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(100); // delay start by 1/10 of a second.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
            System.out.println("bottom text");
            System.out.println("bottom text");
            System.out.println("bottom text");
            System.out.println("bottom text");
        });

        System.out.println("Enter anything: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.println("You entered: " + input);
    }
</code>```

Unfortunately when I put my cursor at the end of Enter anything: and the cursor went straight to the bottom so the output isn't quite what you're after...

```<code>Enter anything:

bottom text
bottom text
bottom text
bottom text
something            <<<<<< My input here
You entered: something

Process finished with exit code 0
</code>```

It I'm not 100% certain what you're trying to do is possible with such a simple set of commands. I'd imagine you'd need something more comprehensive to achieve what you're wanting.

Perhaps someone can improve on this?

Body:
I have a program here that includes only scanners and outputs. What I wanted the program to show is that to display a scanner with the output below.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter anything: ");
     scan.nextLine();

    //while the scanner's text cursor shows, the bottom texts below also shows.

    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");
    System.out.println("bottom text");

/*  what I wanted the output to show is this:

Enter anything: | << text cursor
bottom text
bottom text
bottom text
bottom text
bottom text
bottom text
bottom text

but the output shows like this instead:

Enter anything: |

*/

}//end of method

}

Because it only shows the output below after the scanner has been used. Is it possible or is there any way to show the scanner and the bottom text at the same time? TIA :)

Body:
I tried this...

CompletableFuture will spin off a new thread using runAsync( () -> { return null; } ) you can also use supplyAsync(() -> { returns anObject }) if you want to get a result from the thread. You can then chain additional threads which can be consumers/suppliers or a bit of both.

public static void main(String[] args) {
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(100); // delay start by 1/10 of a second.
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println();
            System.out.println("bottom text");
            System.out.println("bottom text");
            System.out.println("bottom text");
            System.out.println("bottom text");
        });

        System.out.println("Enter anything: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        System.out.println("You entered: " + input);
    }

Unfortunately when I put my cursor at the end of Enter anything: and the cursor went straight to the bottom so the output isn't quite what you're after...

Enter anything:

bottom text
bottom text
bottom text
bottom text
something            <<<<<< My input here
You entered: something

Process finished with exit code 0

It I'm not 100% certain what you're trying to do is possible with such a simple set of commands. I'd imagine you'd need something more comprehensive to achieve what you're wanting.

Perhaps someone can improve on this?


问:
C/C++ Variadic Macro Function Overloading
I am trying to build a simple c++ logger for learning purposes, but I seem to be stuck at the following issue. Let's say that I have a namespace that contains two functions as follows:

namespace l {
    void _p(const char* file, const int line, int vl, const char* fmt, ...) {
        printf("%d:%s:%d: ", vl, file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
    void _p(const char* file, const int line, const char* fmt, ...) {
        printf("%s:%d: ", file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
}
```

<p>and the main function is as follows:</p>

<pre class="lang-cpp prettyprint-override"><code>int main(int argc, char** argv)
{
    l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!");
    l::_p(__FILE__, __LINE__, "%s", "Hello World!");
    return 0;
}
</code>```

what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time. Similarly when the user types l::p("%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, "%s", "Hello World!"); at compile time

答:
Use a logging macro</p>

```<code>#define LOG(...) l::_p(__FILE__, __LINE__, __VA_ARGS__)

void f(int i) {
    LOG(12, "%d", i);
    LOG("%d", i);
}
</code>```

Body:
I am trying to build a simple c++ logger for learning purposes, but I seem to be stuck at the following issue. Let's say that I have a namespace that contains two functions as follows:

namespace l {
    void _p(const char* file, const int line, int vl, const char* fmt, ...) {
        printf("%d:%s:%d: ", vl, file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
    void _p(const char* file, const int line, const char* fmt, ...) {
        printf("%s:%d: ", file, line);
        va_list __args;
        va_start(__args, fmt);
        vfprintf(stdout, fmt, __args);
        printf("\n");
        va_end(__args);
    }
}

and the main function is as follows:

int main(int argc, char** argv)
{
    l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!");
    l::_p(__FILE__, __LINE__, "%s", "Hello World!");
    return 0;
}

what I would like to have is a macro such that when the user types: l::p(12, "%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, 12, "%s", "Hello World!"); at compile time. Similarly when the user types l::p("%s", "Hello World!"); it would be replaced by l::_p(__FILE__, __LINE__, "%s", "Hello World!"); at compile time

Body:
Use a logging macro

#define LOG(...) l::_p(__FILE__, __LINE__, __VA_ARGS__)

void f(int i) {
    LOG(12, "%d", i);
    LOG("%d", i);
}


问:
Studying VRML or openGL?
I will have to follow 1 course at my accademy. One is about openGL the other about VRML.

What would you choose? (course name: virtual reality)

答:
OpenGL is the practical answer.  It's wildly used today, so your investment of time will not be wasted.

Now, doing 3D isn't the easiest thing in the world to pick.  A good background is mathematics (linear algebra especially) is quite helpful.  The barrier to entry can be pretty high.  This is where VRML really shines.  It's extremely easy to pick up and understand.  Knowledge of advanced mathematics is not required, as VRML has abstracted that all away.

If you're a Java developer, another 3D API to look into is Java3D

OwnerDisplayName: anon

Title: Studying VRML or openGL?


问:
group by clause in sql oracle
so i have to write this query where i need to calculate the average amount of paid and withdraw operation for each account so it must look like this :

my table --> operation (Naccount,date_operation,average,nature_operation(withdraw/paid))

i wrote this query , and the problem is that its calculating and selecting only the account which has both paid and withdraw operation leaving the ones that only has paid or withdraw.

select x.naccount
       avg (x.amount) as paid
       avg (y.amount) as withdraw
from operation x, operation y
where
      x.nature_op = 'paid'
      and
      y.nature_op = 'withdraw'
      and
      x.naccount = y.naccount
group by x.naccount;

答:
Use case expressions to do conditional aggregation:

```<code>select o.naccount,
       avg(case when o.nature_op = 'paid' then o.amount end) as paid,
       avg(case when o.nature_op = 'withdraw' then o.amount end) as withdraw
from operation o
group by o.naccount;
</code>```

Edit: To get 0 instead of null if paid or withdraw doesn't exist, use coalesce():

```<code>select o.naccount,
       coalesce(avg(case when o.nature_op = 'paid' then o.amount end), 0) as paid,
       coalesce(avg(case when o.nature_op = 'withdraw' then o.amount end), 0) as withdraw
from operation o
group by o.naccount;
</code>```

Title: group by clause in sql oracle

Body:
Use case expressions to do conditional aggregation:

select o.naccount,
       avg(case when o.nature_op = 'paid' then o.amount end) as paid,
       avg(case when o.nature_op = 'withdraw' then o.amount end) as withdraw
from operation o
group by o.naccount;

Edit: To get 0 instead of null if paid or withdraw doesn't exist, use coalesce():

select o.naccount,
       coalesce(avg(case when o.nature_op = 'paid' then o.amount end), 0) as paid,
       coalesce(avg(case when o.nature_op = 'withdraw' then o.amount end), 0) as withdraw
from operation o
group by o.naccount;


问:
Plot time signals in Modelica.Electrical.Quasistationary
I am trying to model a balanced 3 phase star connection (see foto 1)
foto 1 and I want to get this simulation results (see foto 2 )foto 2 : R1.V,R2.V,R3.V. Here are some of the basic equations used foto 3.

I tried many times without success, can someone check and fix my model, so that I can get the same simulation results like foto 2?

```<code>model Unnamed
 parameter Integer m=3 "Number of phases";
     Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Star starS annotation (
     Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=180,
        origin={-22,70})));
  Modelica.Electrical.QuasiStationary.SinglePhase.Basic.Ground groundS
    annotation (Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=0,
        origin={-56,18})));
 Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Resistor resistor(R_ref=
        fill(1000, 3))
    annotation (Placement(transformation(extent={{42,60},{62,80}})));
  Modelica.Electrical.QuasiStationary.MultiPhase.Sources.VoltageSource
    voltageSource1(m=m,
    f=50,
    V=fill(230,m),
    phi=-Modelica.Electrical.MultiPhase.Functions.symmetricOrientation(3))
    "{(-(j - 1))*2*Modelica.Constants.pi/(m) for j in 1/m}"
    annotation (Placement(transformation(extent={{28,60},{8,80}})));
     Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Star starS1
                                                                     annotation (
     Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=0,
        origin={82,70})));
equation
  connect(groundS.pin, starS.pin_n)
    annotation (Line(points={{-56,28},{-36,28},{-36,70},{-32,70}},
                                                 color={85,170,255}));
  connect(starS.plug_p, voltageSource1.plug_n)
    annotation (Line(points={{-12,70},{8,70}}, color={85,170,255}));
  connect(voltageSource1.plug_p, resistor.plug_p)
    annotation (Line(points={{28,70},{42,70}}, color={85,170,255}));
  connect(resistor.plug_n, starS1.plug_p)
    annotation (Line(points={{62,70},{72,70}}, color={85,170,255}));
  connect(starS1.pin_n, groundS.pin) annotation (Line(points={{92,70},{92,26},{-56,
          26},{-56,28}}, color={85,170,255}));
  annotation (uses(Modelica(version="3.2.2")));
end Unnamed;
</code>```

Thank you

答:
The Modelica.Electrical.QuasiStationary package is phasor-based and therefore it seems to be a bit difficult to plot the sinusoidal signals - at least I didn't find a straight-forward way...

Therefore: Is there any specific reason to use the QuasiStationary package? The more obvious way would be to use Modelica.Electrical.MultiPhase in my opinion. This could e.g. result in the flowing code, which is copied and modified from Modelica.Electrical.MultiPhase.Examples.TransformerYY:

```<code>model ResistorThreephase "Test example with multiphase components"
  extends Modelica.Icons.Example;
  parameter Integer m=3 "Number of phases";
  parameter Modelica.SIunits.Voltage V=230 "Amplitude of Star-Voltage";
  parameter Modelica.SIunits.Frequency f=50 "Frequency";
  parameter Modelica.SIunits.Resistance RL=1e3 "Load Resistance";

  Modelica.Electrical.MultiPhase.Sources.SineVoltage sineVoltage(
    V=fill(V, m),
    freqHz=fill(f, m),
    m=m) annotation (Placement(transformation(
        origin={-30,20},
        extent={{-10,-10},{10,10}},
        rotation=180)));
  Modelica.Electrical.MultiPhase.Basic.Star starS(m=m)
    annotation (Placement(transformation(
        origin={-70,20},
        extent={{-10,-10},{10,10}},
        rotation=180)));
  Modelica.Electrical.Analog.Basic.Ground groundS annotation (Placement(
        transformation(extent={{-100,-40},{-80,-20}})));
  Modelica.Electrical.MultiPhase.Basic.Resistor loadR(m=m, R=fill(RL, m))
    annotation (Placement(transformation(extent={{20,10},{40,30}})));
  Modelica.Electrical.MultiPhase.Basic.Star starL(m=m)
    annotation (Placement(transformation(
        origin={70,20},
        extent={{-10,-10},{10,10}},
        rotation=0)));

equation
  connect(starS.pin_n, groundS.p)
    annotation (Line(points={{-80,20},{-90,20},{-90,-20}}, color={0,0,255}));
  connect(starS.plug_p, sineVoltage.plug_n)
    annotation (Line(points={{-60,20},{-40,20}}, color={0,0,255}));
  connect(loadR.plug_n, starL.plug_p)
    annotation (Line(points={{40,20},{60,20}}, color={0,0,255}));
  connect(sineVoltage.plug_p, loadR.plug_p) annotation (Line(points={{-20,20},{20,20}}, color={0,0,255}));
  connect(starL.pin_n, groundS.p) annotation (Line(points={{80,20},{90,20},{90,-20},{-90,-20}}, color={0,0,255}));

  annotation (
    experiment(StopTime=0.03, __Dymola_Algorithm="Dassl"),
    uses(Modelica(version="3.2.3")));
end ResistorThreephase;
</code>```

Body:
I am trying to model a balanced 3 phase star connection (see foto 1)
foto 1 and I want to get this simulation results (see foto 2 )foto 2 : R1.V,R2.V,R3.V. Here are some of the basic equations used foto 3.

I tried many times without success, can someone check and fix my model, so that I can get the same simulation results like foto 2?

model Unnamed
 parameter Integer m=3 "Number of phases";
     Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Star starS annotation (
     Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=180,
        origin={-22,70})));
  Modelica.Electrical.QuasiStationary.SinglePhase.Basic.Ground groundS
    annotation (Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=0,
        origin={-56,18})));
 Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Resistor resistor(R_ref=
        fill(1000, 3))
    annotation (Placement(transformation(extent={{42,60},{62,80}})));
  Modelica.Electrical.QuasiStationary.MultiPhase.Sources.VoltageSource
    voltageSource1(m=m,
    f=50,
    V=fill(230,m),
    phi=-Modelica.Electrical.MultiPhase.Functions.symmetricOrientation(3))
    "{(-(j - 1))*2*Modelica.Constants.pi/(m) for j in 1/m}"
    annotation (Placement(transformation(extent={{28,60},{8,80}})));
     Modelica.Electrical.QuasiStationary.MultiPhase.Basic.Star starS1
                                                                     annotation (
     Placement(transformation(
        extent={{-10,-10},{10,10}},
        rotation=0,
        origin={82,70})));
equation
  connect(groundS.pin, starS.pin_n)
    annotation (Line(points={{-56,28},{-36,28},{-36,70},{-32,70}},
                                                 color={85,170,255}));
  connect(starS.plug_p, voltageSource1.plug_n)
    annotation (Line(points={{-12,70},{8,70}}, color={85,170,255}));
  connect(voltageSource1.plug_p, resistor.plug_p)
    annotation (Line(points={{28,70},{42,70}}, color={85,170,255}));
  connect(resistor.plug_n, starS1.plug_p)
    annotation (Line(points={{62,70},{72,70}}, color={85,170,255}));
  connect(starS1.pin_n, groundS.pin) annotation (Line(points={{92,70},{92,26},{-56,
          26},{-56,28}}, color={85,170,255}));
  annotation (uses(Modelica(version="3.2.2")));
end Unnamed;

Thank you

Body:
The Modelica.Electrical.QuasiStationary package is phasor-based and therefore it seems to be a bit difficult to plot the sinusoidal signals - at least I didn't find a straight-forward way...

Therefore: Is there any specific reason to use the QuasiStationary package? The more obvious way would be to use Modelica.Electrical.MultiPhase in my opinion. This could e.g. result in the flowing code, which is copied and modified from Modelica.Electrical.MultiPhase.Examples.TransformerYY:

model ResistorThreephase "Test example with multiphase components"
  extends Modelica.Icons.Example;
  parameter Integer m=3 "Number of phases";
  parameter Modelica.SIunits.Voltage V=230 "Amplitude of Star-Voltage";
  parameter Modelica.SIunits.Frequency f=50 "Frequency";
  parameter Modelica.SIunits.Resistance RL=1e3 "Load Resistance";

  Modelica.Electrical.MultiPhase.Sources.SineVoltage sineVoltage(
    V=fill(V, m),
    freqHz=fill(f, m),
    m=m) annotation (Placement(transformation(
        origin={-30,20},
        extent={{-10,-10},{10,10}},
        rotation=180)));
  Modelica.Electrical.MultiPhase.Basic.Star starS(m=m)
    annotation (Placement(transformation(
        origin={-70,20},
        extent={{-10,-10},{10,10}},
        rotation=180)));
  Modelica.Electrical.Analog.Basic.Ground groundS annotation (Placement(
        transformation(extent={{-100,-40},{-80,-20}})));
  Modelica.Electrical.MultiPhase.Basic.Resistor loadR(m=m, R=fill(RL, m))
    annotation (Placement(transformation(extent={{20,10},{40,30}})));
  Modelica.Electrical.MultiPhase.Basic.Star starL(m=m)
    annotation (Placement(transformation(
        origin={70,20},
        extent={{-10,-10},{10,10}},
        rotation=0)));

equation
  connect(starS.pin_n, groundS.p)
    annotation (Line(points={{-80,20},{-90,20},{-90,-20}}, color={0,0,255}));
  connect(starS.plug_p, sineVoltage.plug_n)
    annotation (Line(points={{-60,20},{-40,20}}, color={0,0,255}));
  connect(loadR.plug_n, starL.plug_p)
    annotation (Line(points={{40,20},{60,20}}, color={0,0,255}));
  connect(sineVoltage.plug_p, loadR.plug_p) annotation (Line(points={{-20,20},{20,20}}, color={0,0,255}));
  connect(starL.pin_n, groundS.p) annotation (Line(points={{80,20},{90,20},{90,-20},{-90,-20}}, color={0,0,255}));

  annotation (
    experiment(StopTime=0.03, __Dymola_Algorithm="Dassl"),
    uses(Modelica(version="3.2.3")));
end ResistorThreephase;


问:
How to pass textbox value to java script on button click event

Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

```<code><asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>
</code>```

PassValue is JavaScript method.

Thanks in Advance.

答:
Or for cleaner mark-up, bind the event in code-behind at PageLoad like this

```<code>if (!IsPostBack)
{
    string script = String.Format("GetTextBoxValue('{0}')", rowID.ClientID);
    Click.Attributes.Add("onclick", script);
}
</code>```

Now your mark-up can be like this.

```<code><asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
<asp:Button ID="Click" runat="server" />
</code>```

Body:
Possible Duplicate:

  How to pass text in a textbox to javascript function?

I need to pass the text box value as parameter of javascript method which will be fired on button click.

<asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
        <asp:Button runat="server" ID="Click" OnClientClick="PassValue(Textboxvaluehere)"/>

PassValue is JavaScript method.

Thanks in Advance.

Body:
Or for cleaner mark-up, bind the event in code-behind at PageLoad like this

if (!IsPostBack)
{
    string script = String.Format("GetTextBoxValue('{0}')", rowID.ClientID);
    Click.Attributes.Add("onclick", script);
}

Now your mark-up can be like this.

<asp:TextBox ID="rowID" runat="server"> </asp:TextBox>
<asp:Button ID="Click" runat="server" />


问:
Yii1 - the config file is not loading
The main reason for not loading a config file in the server which worked well in localhost:

Code Snippet from public_html/admin.php

```<code>$yii = dirname(__FILE__) . '../framework/yii.php';
$config = dirname(__FILE__) . '/admin/config/main.php';

print_r($config);
</code>```

Result in localhost:

```<code>C:\xampp\htdocs\*****/admin/config/main.php
</code>```

Result in sever:

```<code>/home/folder_name/domains/*****/public_html/admin/config/main.php
</code>```

Sever Result from public_html/index.php:

```<code>/home/folder_name/domains/******/public_html/protected/config/main.php
</code>```

I am writing this because I had spent hours to trace the point.Its working in FrontEnd but not working in BackEnd. What was the main reason?

答:
Finally, I got the answer:

```<code>$yii = dirname(__FILE__) . '../framework/yii.php';
</code>```

This code is used during multiple domain on single hosting. But the code needs correction:

```<code>$yii = dirname(__FILE__) . '/framework/yii.php';
</code>```

I have uploaded framework folder within public_html.

Title: Yii1 - the config file is not loading

Body:
The main reason for not loading a config file in the server which worked well in localhost:

Code Snippet from public_html/admin.php

$yii = dirname(__FILE__) . '../framework/yii.php';
$config = dirname(__FILE__) . '/admin/config/main.php';

print_r($config);

Result in localhost:

C:\xampp\htdocs\*****/admin/config/main.php

Result in sever:

/home/folder_name/domains/*****/public_html/admin/config/main.php

Sever Result from public_html/index.php:

/home/folder_name/domains/******/public_html/protected/config/main.php

I am writing this because I had spent hours to trace the point.Its working in FrontEnd but not working in BackEnd. What was the main reason?

Body:
Finally, I got the answer:

$yii = dirname(__FILE__) . '../framework/yii.php';

This code is used during multiple domain on single hosting. But the code needs correction:

$yii = dirname(__FILE__) . '/framework/yii.php';

I have uploaded framework folder within public_html.


问:
C++ Implementing class function with nested struct outside
So, I want to make the code a bit more pretty in that I want the class def to contain just function declarations. Here is my code:

```<code>template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node* x)
     {
         return NULL;
     }

     node* error();
};

node* splay_tree<T>::error()
{
    return NULL;
}
</code>```

My question then is how to move the grandp implementation below the splay tree definition. Note that its return type is node*, so gcc is giving me a hard time with this. Is it possible?

答:
You've already gotten an answer but I'll put Evg's idea to use a trailing return type to bring splay_tree<T>::node into scope to show that alternative too:

```<code>template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node*);
     node* error();
};

template<typename T>
auto splay_tree<T>::grandp(node* x) -> node* // trailing return type
{
    return nullptr;
}

template <class T>
auto splay_tree<T>::error() -> node*         // trailing return type
{
    return nullptr;
}
</code>```

Body:
So, I want to make the code a bit more pretty in that I want the class def to contain just function declarations. Here is my code:

template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node* x)
     {
         return NULL;
     }

     node* error();
};

node* splay_tree<T>::error()
{
    return NULL;
}

My question then is how to move the grandp implementation below the splay tree definition. Note that its return type is node*, so gcc is giving me a hard time with this. Is it possible?

Body:
You've already gotten an answer but I'll put Evg's idea to use a trailing return type to bring splay_tree<T>::node into scope to show that alternative too:

template <typename T>
class splay_tree
{
    struct node
    {
        T data;
        node* parent;
        node* left;
        node* right;
     };

     node* grandp(node*);
     node* error();
};

template<typename T>
auto splay_tree<T>::grandp(node* x) -> node* // trailing return type
{
    return nullptr;
}

template <class T>
auto splay_tree<T>::error() -> node*         // trailing return type
{
    return nullptr;
}


问:
What is the difference between SBT and IDEA when creating a Scala project in intelliJ?
When creting a project in IntelliJ, I am given options for sbt, Lightbend Project Starter, IDEA, Play 2.x, Dotty(experimental). What do these options mean, and how could I learn more about them?</p>

答:
IDEA project, is just IDE configuration that let's you work with Scala... but it doesn't come with build system that you can easily configure, commit to git repo, etc - you basically would have to configure everything in IntelliJ yourself which is a pain.

Other options are sbt templates where sbt is a build tool for Scala:

sbt - creates empty build configuration and imports it to IDE

Lightbend Project Starter - a collection of templates with configurations seeded. In general sbt new template-name can generate a project using template name (github repository name of a template) and Lightbend  prepared and maintains some of them

Play - sbt configurations for Play Framework

Dotty - sbt configuration for Dotty (experimiental Scala 3)

With them you have a build config that you can configure and import and check into git, that is used by IntelliJ to generate IDE configuration.


问:
ElasticSearch: Weird problem in inserting documents to ElasticSearch indices when a template is present
I am trying to do some testing in ElasticSearch. I am able to populate everything as required but whenever I try to put our project's default template and then insert, the data is not ingested in the index (http calls are successful though).

Upon inspection, I realised that I can't insert even a simple document even after using elasticSearch's default template.
For example inserting the template from ES's documentation:

```<code>PUT _template/template_1
{
  "index_patterns": ["te*", "bar*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_source": {
      "enabled": false
    },
    "properties": {
      "host_name": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date",
        "format": "EEE MMM dd HH:mm:ss Z yyyy"
      }
    }
  }
}
</code>```

And then inserting a doc in index = "bark" by

```<code>PUT http://localhost:9200/bark/_doc/11232 HTTP/1.1
User-Agent: Fiddler
Host: localhost:9200
Content-Length: 21
Content-Type: application/json

{"host_name": "generic_name"}
</code>```

adds a doc in the index but without the data about the host_name.
Simply changing the index name to something for which this template does not apply (like index = dark) will add a doc with the data about host_name.
Showing index data for replication:

(when index=bark)

```<code>{"took":2,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"bark","_type":"_doc","_id":"11232","_score":1.0}]}}
</code>```

(when index=dark)

```<code>{"took":6,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"dark","_type":"_doc","_id":"11232","_score":1.0,"_source":{"host_name":"generic_name"}}]}}
</code>```

Notice the _source":{"host_name":"generic_name"} field is absent in the former?

What could be done for this? If someone has faced this issue or knows a fix, please help.

答:
You need to remove this from your mapping

```<code>"_source": {
  "enabled": false
},
</code>```

The effect of this setting is that the source document is not stored in the _source field. That's probably not what you want.

Body:
I am trying to do some testing in ElasticSearch. I am able to populate everything as required but whenever I try to put our project's default template and then insert, the data is not ingested in the index (http calls are successful though).

Upon inspection, I realised that I can't insert even a simple document even after using elasticSearch's default template.
For example inserting the template from ES's documentation:

PUT _template/template_1
{
  "index_patterns": ["te*", "bar*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "_source": {
      "enabled": false
    },
    "properties": {
      "host_name": {
        "type": "keyword"
      },
      "created_at": {
        "type": "date",
        "format": "EEE MMM dd HH:mm:ss Z yyyy"
      }
    }
  }
}

And then inserting a doc in index = "bark" by

PUT http://localhost:9200/bark/_doc/11232 HTTP/1.1
User-Agent: Fiddler
Host: localhost:9200
Content-Length: 21
Content-Type: application/json

{"host_name": "generic_name"}

adds a doc in the index but without the data about the host_name.
Simply changing the index name to something for which this template does not apply (like index = dark) will add a doc with the data about host_name.
Showing index data for replication:

(when index=bark)

{"took":2,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"bark","_type":"_doc","_id":"11232","_score":1.0}]}}

(when index=dark)

{"took":6,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"dark","_type":"_doc","_id":"11232","_score":1.0,"_source":{"host_name":"generic_name"}}]}}

Notice the _source":{"host_name":"generic_name"} field is absent in the former?

What could be done for this? If someone has faced this issue or knows a fix, please help.

Body:
You need to remove this from your mapping

"_source": {
  "enabled": false
},

The effect of this setting is that the source document is not stored in the _source field. That's probably not what you want.


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答:
It would be helpful to have the C# Language from Microsoft (not ECMA) specification with you to guide you with the syntax changes between C++ & C#. </p>

<p>download C# Version 3.0 Specification (.doc) here </p>

ContentLicense: CC BY-SA 2.5

Title: from C++ to C#

Body:
It would be helpful to have the C# Language from Microsoft (not ECMA) specification with you to guide you with the syntax changes between C++ & C#.

download C# Version 3.0 Specification (.doc) here

OwnerDisplayName: AB Kolan


问:
C: how to convert foreach_point(t->board) to for loop?
I need to separate values with a comma in each case but the last.
Various posts suggest to use for instead of foreach,
but as this is a patch, and I don't use C, how can I convert
foreach_point(t->board)  to a for loop?

答:
It's basically the same syntax as a for-loop in C#:

```<code>for (int i = 0; i < NUM_ELEMENTS; i++)
{
    t->board[i] ...
}
</code>```

You will need to know NUM_ELEMENTS, obviously!

Body:
It's basically the same syntax as a for-loop in C#:

for (int i = 0; i < NUM_ELEMENTS; i++)
{
    t->board[i] ...
}

You will need to know NUM_ELEMENTS, obviously!


问:
How do I get the key's value after I release the key
I understand by using for example,

```<code>Space & a::b
</code>```

I can have b by holding Space then press a. However this disable the Space's output. How do I get a Space character, for example by releasing Space key or press Space key twice.

答:
You have to bind Space to send itself:

```<code>Space & a::b
Space::Send {Space}
</code>```

I would advise against using a common key as a prefix, however: a prefix key will lose any "on press" and repeat capabilities.  So with this script, Space won't write many spaces, only one, and only on release (and you'll wonder for a while why can't you bunny hop in your fav game anymore, every time!).

Just typing text feels awkward right now, the slight delay after every space causing mistakes.

I'd recommend at least using a whitelist to restrict the hotkey to the programs where you need it:

```<code>SetTitleMatchMode RegEx
#IfWinActive "i)notepad|word|thunderbird"
Space & a::b
Space::Send {Space}
</code>```

Or some such.

Body:
I understand by using for example,

Space & a::b

I can have b by holding Space then press a. However this disable the Space's output. How do I get a Space character, for example by releasing Space key or press Space key twice.

Body:
You have to bind Space to send itself:

Space & a::b
Space::Send {Space}

I would advise against using a common key as a prefix, however: a prefix key will lose any "on press" and repeat capabilities.  So with this script, Space won't write many spaces, only one, and only on release (and you'll wonder for a while why can't you bunny hop in your fav game anymore, every time!).

Just typing text feels awkward right now, the slight delay after every space causing mistakes.

I'd recommend at least using a whitelist to restrict the hotkey to the programs where you need it:

SetTitleMatchMode RegEx
#IfWinActive "i)notepad|word|thunderbird"
Space & a::b
Space::Send {Space}

Or some such.


问:
eclipse.ini file not present on Mac
I am trying to alter my eclipse configuration, but the eclipse.ini file is not present in my eclipse installation directory.

I am on Mac os x with eclipse 4.2.1 Juno.

Did the eclipse.ini file get replaced with the config.ini in eclipse/configuration?

答:
On Mac Catalina

move mat.app into mac ~/Application, then use it directly

Title: eclipse.ini file not present on Mac


问:
Colored background with png image
I want to create a square white box with png image in it. I want png to follow background while the colour of box doesn't affect it.

Here is the sample of the output that I want:

As for now, the white background color couldn't work after I added background colour on div for image. I want the transparent space of png follow body background color.

jsfiddle

I've attached snippet too. Can someone help me to look into it? Thanks in advance!

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  border: 1px solid black;
  background-color:white;
}

.title {
  margin-top: auto;
  width: auto;
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  animation: gradient 15s ease infinite;
  -webkit-text-fill-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
 <div class="title">
    <img src="https://img.icons8.com/material/24/000000/print--v1.png"/>
  </div>
</div></code>```

答:
You need to consider mask here:

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  min-height:100vh;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  border: 1px solid black;
}

.title {
  margin-top: auto;
  -webkit-mask:
    url(https://i.ibb.co/Zcvccd9/print-v1.png) center/contain no-repeat,
    linear-gradient(#fff,#fff);
  -webkit-mask-composite:destination-out;
          mask:
    url(https://i.ibb.co/Zcvccd9/print-v1.png) center/contain no-repeat,
    linear-gradient(#fff,#fff);
          mask-composite:exclude;
  background: #fff;
}
.title img {
  visibility:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
 <div class="title">
    <img src="https://i.ibb.co/Zcvccd9/print-v1.png" >
  </div>
</div></code>```

Title: Colored background with png image

Body:
You need to consider mask here:

body {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  min-height:100vh;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.wrapper {
  text-align: center;
  border: 1px solid black;
}

.title {
  margin-top: auto;
  -webkit-mask:
    url(https://i.ibb.co/Zcvccd9/print-v1.png) center/contain no-repeat,
    linear-gradient(#fff,#fff);
  -webkit-mask-composite:destination-out;
          mask:
    url(https://i.ibb.co/Zcvccd9/print-v1.png) center/contain no-repeat,
    linear-gradient(#fff,#fff);
          mask-composite:exclude;
  background: #fff;
}
.title img {
  visibility:hidden;
}

<div class="wrapper">
 <div class="title">
    <img src="https://i.ibb.co/Zcvccd9/print-v1.png" >
  </div>
</div>


问:
How can I add a message and add a reaction to that message in Discord.py
I want to send a message and reactions with discord.py (trying to create a poll, with my own BOT) like this:

This is as far a could go:

With $poll, just call the function.
Parameters: "question" "option1" "option2" ... to 10 options. If the user send more than 10 just ignore them.

I can add the bold text, quote some text (the options part), and insert an emoji inside the text

BUT! I can add a reaction to the message itself to let the users set their opinions.

```<code>import os
from discord.utils import get
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='$')

@bot.command(name='poll', help='Create a Poll!')
async def poll(ctx, q : str, *opt):
    bar = ":bar_chart: "
    qu = "> "
    e = "\n"
    c = 0
    opts = ""
    l = [":regional_indicator_a:",
         ":regional_indicator_b:",
         ":regional_indicator_c:",
         ":regional_indicator_d:",
         ":regional_indicator_e:",
         ":regional_indicator_f:",
         ":regional_indicator_g:",
         ":regional_indicator_h:",
         ":regional_indicator_i:",
         ":regional_indicator_j:",
         ":regional_indicator_k:"]
    new_l = [] #This is just to store the name from :name: to name
    question = bar + '**' + q + '**' + e
    for i in opt:
        opts = opts + qu + l[c] + ' ' + i + (e if c <= 9 else "")
        p = str(l[c])
        new_l.append(p[1:-1]) #Here from :name: to name
        c = c + 1
        if c == 10: break
    response = question + opts
    m = await ctx.send(response)

    # Here is where the error comes... When the user adds the options,
    #I need to add that emoji as a reaction
    #(:regional_indicator_a:, and so on, to 10) to
    #led the user make the vote.
    #BUT! As you can see, i can not add the reaction!
    for j in new_l:
        emoji = get(ctx.guild.emojis, name=j)
        await m.add_reaction(emoji)

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
bot.run(TOKEN)
</code>```

This is part of the error:

```<code>Command raised an exception: InvalidArgument: emoji argument must be str, Emoji, or Reaction not NoneType.
</code>```

答:
When adding emojis, you'll want to use the actual emoji, for example , which you can get from doing \:emoji_name: in discord and sending the message:

Turns into:

Which you can then copy directly into your IDE.

Alternatively, if your IDE doesn't support emojis, you can use the unicode, which you can find from this site. As an example, the unicode for bar chart would be \u1f4ca, as the format in python follows the formatting of \u as the prefix, followed by its unicode.

This means your list of emojis would look like ["", "", "", .... or ["\u1f1e6", "\u1f1e7", "\u1f1e8", ....

Body:
I want to send a message and reactions with discord.py (trying to create a poll, with my own BOT) like this:

This is as far a could go:

With $poll, just call the function.
Parameters: "question" "option1" "option2" ... to 10 options. If the user send more than 10 just ignore them.

I can add the bold text, quote some text (the options part), and insert an emoji inside the text

BUT! I can add a reaction to the message itself to let the users set their opinions.

import os
from discord.utils import get
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='$')

@bot.command(name='poll', help='Create a Poll!')
async def poll(ctx, q : str, *opt):
    bar = ":bar_chart: "
    qu = "> "
    e = "\n"
    c = 0
    opts = ""
    l = [":regional_indicator_a:",
         ":regional_indicator_b:",
         ":regional_indicator_c:",
         ":regional_indicator_d:",
         ":regional_indicator_e:",
         ":regional_indicator_f:",
         ":regional_indicator_g:",
         ":regional_indicator_h:",
         ":regional_indicator_i:",
         ":regional_indicator_j:",
         ":regional_indicator_k:"]
    new_l = [] #This is just to store the name from :name: to name
    question = bar + '**' + q + '**' + e
    for i in opt:
        opts = opts + qu + l[c] + ' ' + i + (e if c <= 9 else "")
        p = str(l[c])
        new_l.append(p[1:-1]) #Here from :name: to name
        c = c + 1
        if c == 10: break
    response = question + opts
    m = await ctx.send(response)

    # Here is where the error comes... When the user adds the options,
    #I need to add that emoji as a reaction
    #(:regional_indicator_a:, and so on, to 10) to
    #led the user make the vote.
    #BUT! As you can see, i can not add the reaction!
    for j in new_l:
        emoji = get(ctx.guild.emojis, name=j)
        await m.add_reaction(emoji)

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
bot.run(TOKEN)

This is part of the error:

Command raised an exception: InvalidArgument: emoji argument must be str, Emoji, or Reaction not NoneType.


问:
Should i include /public in Vue.js gitignore?
I have a laravel/Vue.js project, and whenever i commit there are 3 files that get committed too:
-public/main.js
-public/manifest.js
-public/vendor.js

so, Should i include /public in Vue.js gitignore?

答:
It depends on your workflow and project setup:

if you are working alone you can build assets locally and upload on
production. It will save you space from node_modules on your server

if you are working with someone else it is good to be ignored to skip
the conflicts on merging (not big deal, but annoying)

there is some
setups for zero-downtime deploy where each release is in new
directory. In this case you don't want node_modules in each release
and wait to be build. Then you shouldn't ignore them.

the same case
will be if you are using some continues integration tool to test
frontend


问:
How to simulate ionBlur in tests
Maybe I'll start with what I want to achieve: I have a form with a required field. By default it should not display any error. The error should be displayed if a user touches the field. So my field looks more or less like this:

```<code><ion-input .... (ionBlur)="updateDispayedErrors()"></ion-input>
</code>```

But I don't know how to test it because:

Running fixture.debugElement.nativeElement.blur() does not triggers ionBlur handler (the same with ....dispatchEvent(new Event('blur')))

Plain angular (blur) does not work (i.e. if I change the code to (blur)="updateDisplayErrors()" then it does not work)

It seems that calling blur() method on native <input .../> element that is created in the browser would work but... the problem is that when I run the tests fixture.debugElement.nativeElement.childNodes is empty... So the native <input .../> is not created

Please let me know if you would like to see a full example to illustrate it.

答:
If you add a selector to ion-input like:

<ion-input .... (ionBlur)="updateDisplayedErrors()" id="specialInput"></ion-input>
```

<p>Then you can use <code>fixture.debugElement.triggerEventHandler</code>:</p>

<pre class="lang-ts prettyprint-override"><code>import { By } from '@angular/platform-browser';

...

it('should emit ionBlur', () => {
    const ionDe = fixture.debugElement.query(By.css('#specialInput'));
    const ionBlurResult = spyOn(component, 'updateDisplayedErrors');
    ionDe.triggerEventHandler('ionBlur', {});
    expect(ionBlurResult).toHaveBeenCalled();
});
</code>```

Title: How to simulate ionBlur in tests

Body:
Maybe I'll start with what I want to achieve: I have a form with a required field. By default it should not display any error. The error should be displayed if a user touches the field. So my field looks more or less like this:

<ion-input .... (ionBlur)="updateDispayedErrors()"></ion-input>

But I don't know how to test it because:

Running fixture.debugElement.nativeElement.blur() does not triggers ionBlur handler (the same with ....dispatchEvent(new Event('blur')))

Plain angular (blur) does not work (i.e. if I change the code to (blur)="updateDisplayErrors()" then it does not work)

It seems that calling blur() method on native <input .../> element that is created in the browser would work but... the problem is that when I run the tests fixture.debugElement.nativeElement.childNodes is empty... So the native <input .../> is not created

Please let me know if you would like to see a full example to illustrate it.

Body:
If you add a selector to ion-input like:

<ion-input .... (ionBlur)="updateDisplayedErrors()" id="specialInput"></ion-input>

Then you can use fixture.debugElement.triggerEventHandler:

import { By } from '@angular/platform-browser';

...

it('should emit ionBlur', () => {
    const ionDe = fixture.debugElement.query(By.css('#specialInput'));
    const ionBlurResult = spyOn(component, 'updateDisplayedErrors');
    ionDe.triggerEventHandler('ionBlur', {});
    expect(ionBlurResult).toHaveBeenCalled();
});


问:
Rewrite URL for static website hosted in Azure Storage
I have deployed Angular 7 app to Azure Storage Static Website.

Angular app makes calls to .NET Core API which is deployed to Azure App Service.

Is it possible to configure URL rewrite (reverse proxy) to route Angular app requests to .NET Core API without having to enable CORS? Similar way like using Angular proxy configuration for local development?

I have read that it is possible to use URL rewrite rules in Azure CDN, but I am not quite sure how to do it.
https://learn.microsoft.com/en-us/azure/cdn/cdn-rules-engine-reference-features#url-rewrite

As far as I understand it is possible to specify only relative path in URL rewrite rule.

Any help is appreciated.

答:
You can use azure function proxy where your site is deployed. I am assuming for frontend you will have every url starting with /api.

```<code>{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "root": {
            "matchCondition": {
                "route": "/api/{*route}",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://my-dot-net-server/{*route}": {
                //If you want to override any headers
            }
        }
   }
}
</code>```

The above proxy will redirect your request to dotnet url and send the response.

Body:
You can use azure function proxy where your site is deployed. I am assuming for frontend you will have every url starting with /api.

{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
        "root": {
            "matchCondition": {
                "route": "/api/{*route}",
                "methods": [
                    "GET",
                    "HEAD"
                ]
            },
            "backendUri": "https://my-dot-net-server/{*route}": {
                //If you want to override any headers
            }
        }
   }
}

The above proxy will redirect your request to dotnet url and send the response.


问:
How to make countdown timer print result on single line in C?
I have code here which works as a countdown timer but it prints results on a new line
like this:

```<code>10
9
8
7
6
5
4
3
2
1
</code>```

here is my code:

```<code>int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}
</code>```

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense

答: Try changing printf("Time: \t%d \n", count); to printf("Time: \t%d \t", count);

Body:
I have code here which works as a countdown timer but it prints results on a new line
like this:

10
9
8
7
6
5
4
3
2
1

here is my code:

int timer()
{
        int count;
        count = 10;

        while(count != 0)
        {
                printf("Time: \t%d \n", count);
                count--;
                sleep(1);
        }

        printf("\nCount down timer has expired\n");
        return 0;
}

what I've tried so far is to change \n to \r to print on a single line but it did not work. I'm trying to make it clear the line and print the next number in the line then clear that and print the next one if that makes sense


问:
Postgres Full Text Search using TSVECTOR and special UTF8 characters
I have a database of instagram posts which needs to be searchable. Current implementation uses TSVECTOR column and @@ operator to search against it:

CREATE TABLE ig_posts (
 /* ... */
 caption_tsv TSVECTOR
);
```

<p>Posts insert SQL:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO ig_posts(caption_tsv)
VALUES (to_tsvector('simple', ?)) /* simple, because post can be in any language */
</code>```

Search SQL:

SELECT *
FROM ig_posts
WHERE ig_posts.caption_tsv @@ to_tsquery('simple', ?)
```

<p>Everything works great, except some posts might contain utf8 encoded bold/italic text, for example:</p>

```'rosegold':26 'sunshine':23 '':1 '':4 '':2 '':3 '':21 '':17 '':15
```

This causes the @@ operator to fail, since the "Always" and "" are considered different words. Is it possible to covert bold/italic UTF8 text back to normal within Postgres?

Edit: the accepted answer works perfectly, here is the rules file that I used: https://gist.github.com/dsenkus/9250134b338b9862585963dfdf450e13

And the script that was used to generate it: https://gist.github.com/dsenkus/17ddbd29d53bd6dd2cf4051bd05ad44d (generated results requires some cleanup, since some special letters do not exist in UTF8, and 3rd h letter is not recognized, ℎ should be used as value)

答:
You need the unaccent contrib module:

```<code>CREATE EXTENSION unaccent;
</code>```

Then you need to create a file my_unaccent.rules in the tsearch_data subdirectory of the PostgreSQL share directory that contains the character-wise mapping you need. This is something you have to build yourself.

Then you can create a dictionary using it:

```<code>CREATE TEXT SEARCH DICTIONARY my_unaccent (TEMPLATE = unaccent, RULES = 'my_unaccent');
</code>```

Then you can create a new text search configuration based on simple that uses that dictionary:

```<code>CREATE TEXT SEARCH CONFIGURATION my_unaccent (COPY = simple);
ALTER TEXT SEARCH CONFIGURATION my_unaccent
   ALTER MAPPING FOR asciihword, asciiword, hword, hword_asciipart, hword_part, word
      WITH my_unaccent, simple;
</code>```

This full text search configuration should so what you need.

Body:
I have a database of instagram posts which needs to be searchable. Current implementation uses TSVECTOR column and @@ operator to search against it:

CREATE TABLE ig_posts (
 /* ... */
 caption_tsv TSVECTOR
);

Posts insert SQL:

INSERT INTO ig_posts(caption_tsv)
VALUES (to_tsvector('simple', ?)) /* simple, because post can be in any language */

Search SQL:

SELECT *
FROM ig_posts
WHERE ig_posts.caption_tsv @@ to_tsquery('simple', ?)

Everything works great, except some posts might contain utf8 encoded bold/italic text, for example:

'rosegold':26 'sunshine':23 '':1 '':4 '':2 '':3 '':21 '':17 '':15

This causes the @@ operator to fail, since the "Always" and "" are considered different words. Is it possible to covert bold/italic UTF8 text back to normal within Postgres?

Edit: the accepted answer works perfectly, here is the rules file that I used: https://gist.github.com/dsenkus/9250134b338b9862585963dfdf450e13

And the script that was used to generate it: https://gist.github.com/dsenkus/17ddbd29d53bd6dd2cf4051bd05ad44d (generated results requires some cleanup, since some special letters do not exist in UTF8, and 3rd h letter is not recognized, ℎ should be used as value)

Body:
You need the unaccent contrib module:

CREATE EXTENSION unaccent;

Then you need to create a file my_unaccent.rules in the tsearch_data subdirectory of the PostgreSQL share directory that contains the character-wise mapping you need. This is something you have to build yourself.

Then you can create a dictionary using it:

CREATE TEXT SEARCH DICTIONARY my_unaccent (TEMPLATE = unaccent, RULES = 'my_unaccent');

Then you can create a new text search configuration based on simple that uses that dictionary:

CREATE TEXT SEARCH CONFIGURATION my_unaccent (COPY = simple);
ALTER TEXT SEARCH CONFIGURATION my_unaccent
   ALTER MAPPING FOR asciihword, asciiword, hword, hword_asciipart, hword_part, word
      WITH my_unaccent, simple;

This full text search configuration should so what you need.


问:
OpenID Connect: How to add custom claims data in the client credential flow
I'm setting up a client credential flow with my identity server to get an access token from a client. I'm able to get the access token with the following code,

Identity server configuration:

```<code> public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var corsPolicyService = new DefaultCorsPolicyService()
        {
            AllowAll = true
        };

        var idServerServiceFactory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get())
        .UseInMemoryUsers(Users.Get());

        var options = new IdentityServerOptions
        {
            Factory = idServerServiceFactory,
            SiteName = "Demo",
            IssuerUri = IdentityConstants.IssuerUri,
            PublicOrigin = IdentityConstants.STSOrigin,
            SigningCertificate = LoadCertificate()
        };

        idsrvApp.UseIdentityServer(options);
    });
}
</code>```

Identity Server - Client configuration:

```<code>public static class Clients
{
    public static IEnumerable<Client> Get()
    {
    return new[]
     {
        new Client
        {
             ClientId = "ClientSDK",
             ClientName = "Client SDK (Client Credentials)",
             Flow = Flows.ClientCredentials,
             AllowAccessToAllScopes = true,

            ClientSecrets = new List<Secret>()
            {
                new Secret(IdentityConstants.ClientSecret.Sha256())
            }
        }
     };
}
</code>```

}

MVC Client:

```<code>  var oAuth2Client = new TokenClient(
              IdentityConstants.STSTokenEndpoint,
              "ClientSDK",
                IdentityConstants.ClientSecret);

    var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("MyScope").Result;

    return tokenResponse.AccessToken;
</code>```

I'm able to get the access token(i.e. JWT). Can one please tell me how to add a unique key like (UserId) from my database, when the JWT is created with its claims data when the token is created.

答:
You should implement custom user store for validating user and adding claims from database. Change startup code like below, Userrepository class represents database communication to authenticate user and get claims from database:

```<code>var idServerServiceFactory = new IdentityServerServiceFactory()
   .UseInMemoryClients(Clients.Get())
   .UseInMemoryScopes(Scopes.Get())
   .AddCustomUserStore();
</code>```

Add below classes and change according to your requirement:

```<code>public static class CustomIdentityServerBuilderExtensions
{
    public static IIdentityServerBuilder AddCustomUserStore(this IIdentityServerBuilder builder)
    {
        builder.AddProfileService<UserProfileService>();
        builder.AddResourceOwnerValidator<UserResourceOwnerPasswordValidator>();
        return builder;
    }
}

public class UserProfileService : IProfileService
{
    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
            UserRepository userRepository=new UserRepository();
            var user = userRepository.GetUserById(int.Parse(context.Subject.GetSubjectId()));
            if (user != null)
            {
                var userTokenModel = _mapper.Map<UserTokenModel>(user);
                var claims = new List<Claim>();
                claims.Add(new Claim("UserId", user.UserId));
                // Add another claims here
                context.IssuedClaims.AddRange(claims);
    }
    public async Task IsActiveAsync(IsActiveContext context)
    {
    }
}

public class UserResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
            UserRepository userRepository=new UserRepository();
            var userLoginStatus = userRepository.GetUserById(context.UserName, context.Password);

            if (userLoginStatus != null)
            {

                    context.Result = new GrantValidationResult(userLoginStatus.UserId.ToString(),
                         OidcConstants.AuthenticationMethods.Password);
            }
            else
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient,
                        "Wrong Credentials");
            }
    }
}
</code>```

Body:
I'm setting up a client credential flow with my identity server to get an access token from a client. I'm able to get the access token with the following code,

Identity server configuration:

 public void Configuration(IAppBuilder app)
{
    app.Map("/identity", idsrvApp =>
    {
        var corsPolicyService = new DefaultCorsPolicyService()
        {
            AllowAll = true
        };

        var idServerServiceFactory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get())
        .UseInMemoryUsers(Users.Get());

        var options = new IdentityServerOptions
        {
            Factory = idServerServiceFactory,
            SiteName = "Demo",
            IssuerUri = IdentityConstants.IssuerUri,
            PublicOrigin = IdentityConstants.STSOrigin,
            SigningCertificate = LoadCertificate()
        };

        idsrvApp.UseIdentityServer(options);
    });
}

Identity Server - Client configuration:

public static class Clients
{
    public static IEnumerable<Client> Get()
    {
    return new[]
     {
        new Client
        {
             ClientId = "ClientSDK",
             ClientName = "Client SDK (Client Credentials)",
             Flow = Flows.ClientCredentials,
             AllowAccessToAllScopes = true,

            ClientSecrets = new List<Secret>()
            {
                new Secret(IdentityConstants.ClientSecret.Sha256())
            }
        }
     };
}

}

MVC Client:

  var oAuth2Client = new TokenClient(
              IdentityConstants.STSTokenEndpoint,
              "ClientSDK",
                IdentityConstants.ClientSecret);

    var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("MyScope").Result;

    return tokenResponse.AccessToken;

I'm able to get the access token(i.e. JWT). Can one please tell me how to add a unique key like (UserId) from my database, when the JWT is created with its claims data when the token is created.

Body:
You should implement custom user store for validating user and adding claims from database. Change startup code like below, Userrepository class represents database communication to authenticate user and get claims from database:

var idServerServiceFactory = new IdentityServerServiceFactory()
   .UseInMemoryClients(Clients.Get())
   .UseInMemoryScopes(Scopes.Get())
   .AddCustomUserStore();

Add below classes and change according to your requirement:

public static class CustomIdentityServerBuilderExtensions
{
    public static IIdentityServerBuilder AddCustomUserStore(this IIdentityServerBuilder builder)
    {
        builder.AddProfileService<UserProfileService>();
        builder.AddResourceOwnerValidator<UserResourceOwnerPasswordValidator>();
        return builder;
    }
}

public class UserProfileService : IProfileService
{
    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
            UserRepository userRepository=new UserRepository();
            var user = userRepository.GetUserById(int.Parse(context.Subject.GetSubjectId()));
            if (user != null)
            {
                var userTokenModel = _mapper.Map<UserTokenModel>(user);
                var claims = new List<Claim>();
                claims.Add(new Claim("UserId", user.UserId));
                // Add another claims here
                context.IssuedClaims.AddRange(claims);
    }
    public async Task IsActiveAsync(IsActiveContext context)
    {
    }
}

public class UserResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
{
    public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    {
            UserRepository userRepository=new UserRepository();
            var userLoginStatus = userRepository.GetUserById(context.UserName, context.Password);

            if (userLoginStatus != null)
            {

                    context.Result = new GrantValidationResult(userLoginStatus.UserId.ToString(),
                         OidcConstants.AuthenticationMethods.Password);
            }
            else
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidClient,
                        "Wrong Credentials");
            }
    }
}


问:
Drupal JSON API: how to filter using "different than"?
I'm trying to write a very simple JSON API query on Drupal 8: return all users except uid 0 and 1.
Sounds trivial enough but I haven't been able to figure it out and to find any example.

Something like this?

```<code>jsonapi/user/user?filter[drupal_internal__uid]!=0
</code>```

Any ideas would be most welcome!

答:
Something like this should work as you want:

```<code>/jsonapi/user/user?filter[user-uid][condition][path]=uid&filter[user-uid][condition][operator]=NOT IN&filter[user-uid][condition][value][]=0&filter[user-uid][condition][value][]=1
</code>```

For more informations: https://www.drupal.org/node/2943641

Edit: If you use cURL, brackets will throw an error, add "--globoff" to your request.

Example:

curl --globoff --location --request GET "{{localhost}}/jsonapi/node/article?sort=nid&page[limit]=10&filter[article-title][path]=title&filter[article-title][value]=headless&filter[article-title][operator]=NOT%20IN".

Reference: https://stackoverflow.com/a/8333999/5052969

Body:
I'm trying to write a very simple JSON API query on Drupal 8: return all users except uid 0 and 1.
Sounds trivial enough but I haven't been able to figure it out and to find any example.

Something like this?

jsonapi/user/user?filter[drupal_internal__uid]!=0

Any ideas would be most welcome!

Body:
Something like this should work as you want:

/jsonapi/user/user?filter[user-uid][condition][path]=uid&filter[user-uid][condition][operator]=NOT IN&filter[user-uid][condition][value][]=0&filter[user-uid][condition][value][]=1

For more informations: https://www.drupal.org/node/2943641

Edit: If you use cURL, brackets will throw an error, add "--globoff" to your request.

Example:

curl --globoff --location --request GET "{{localhost}}/jsonapi/node/article?sort=nid&page[limit]=10&filter[article-title][path]=title&filter[article-title][value]=headless&filter[article-title][operator]=NOT%20IN".

Reference: https://stackoverflow.com/a/8333999/5052969


问:
nginx configs to haproxy
I want equivalent of nginx config in haproxy. Went through lot of links but none of them mentioned anything related to below configs.</p>

```<code>proxy_http_version 1.1;
proxy_set_header Connection "";
</code>```

答:
You can set the preferred alpn protocol on the server line and the header with http-request set-header

```<code># I would prefer to set this option instead of the header
option http-server-close

http-request set-header Connection "''"
server 127.0.0.1:443 ssl crt pub.pem alpn http/1.1
</code>```

You can also use option http-server-close

Title: nginx configs to haproxy

Body:
I want equivalent of nginx config in haproxy. Went through lot of links but none of them mentioned anything related to below configs.

proxy_http_version 1.1;
proxy_set_header Connection "";

Body:
You can set the preferred alpn protocol on the server line and the header with http-request set-header

# I would prefer to set this option instead of the header
option http-server-close

http-request set-header Connection "''"
server 127.0.0.1:443 ssl crt pub.pem alpn http/1.1

You can also use option http-server-close


问:
How to insert table between 2 server in Azure data warehouse?
I want to insert table from different factory / server in Azure data warehouse. Is it possible to insert by query?

Because it takes a lot of time if I make dataset and pipeline for each table in Azure data factory.

答:
Just from your screenshot, according the icon of the Azure SQL, you're using Azure SQL database, not Azure Data Warehouse.

You could use Elastic Query to do a cross database query in Azure.

Ref the tutorial: Get started with cross-database queries (vertical partitioning) (preview)

Elastic database query (preview) for Azure SQL Database allows you to run T-SQL queries that span multiple databases using a single connection point. This article applies to vertically partitioned databases.

When completed, you will: learn how to configure and use an Azure SQL Database to perform queries that span multiple related databases.

Then you can inset data from external table to current database table.

Note: Azure SQL database already has the master key, you don't need create it again.

Hope this helps.


问:
Do I need to restructure my Backbone models/collections? Unsure how to save all at once
My application revolves around people. I have a Person model where you can set the name, age, and other traits. On the same page I have a Collection of Interest models that can be added for the person.

I need to pass a JSON representation of the Person and their Interests to the server. But I do  not know how to bring these pieces together (the Person and Collection of Interests are separate).

Do I need to restructure my application? Should the Interests be a property of the People model? Should it still be a collection or should I change it to an array of native Javascript objects?

答:
First, it sounds like Person should have a collection of Interest models.  You should be able to see an example of this on the backbone.js documentation page -- see the Mailbox example.  Link here: http://documentcloud.github.com/backbone/#FAQ-nested

However, if you are trying to have one single call to update your Person and Interests, you'll more than likely have to overload the save method to save the model and the collection too.  To do that, it seems like you might have to temporarily add Interest data to the attributes of the Person model.  Then when you do a save, these nested attributes go to the server.  This is a hack, though.


问:
CodeBlocks C++ program not running
Few days back I downloaded CodeBlocks for C++.
I tried to run a HelloWorld program but it does not runs.
When I click on Build and Run nothing happens.
My compiler location is right i think (C:\Program Files\CodeBlocks\MinGW)

Below the inteface is see this error message:-
No such file or directory.
Please Help!

enter image description here
[enter code here][1]

答:
It looks like you have something wrong in your compiler settings. Maybe look at this question: CodeBlocks : [highlight: No such directory found

All I did was go to "Compiler Settings" ("Settings" -> "Compiler" -> Global compiler settings), and selected "Reset Defaults".

Does that work for you?

Title: CodeBlocks C++ program not running


问:
R Pagedown resume/cv lowercase letters for title
I am working on creating a resume in R using Pagedown. Currently, the default is to have your name in all capital letters at the top of the first page (e.g. JANE DOE). However, this doesn't look great with my name and I am wondering if there is a way to edit just the title line to have mixed case (Jane Doe). Thanks!</p>

答:
It is possible to remove the uppercase text transformation with CSS like that:</p>

```<code>---
title: "Lijia Yu's resume"
author: Lijia Yu
date: "`r Sys.Date()`"
output:
  pagedown::html_resume:
    # set it to true for a self-contained HTML page but it'll take longer to render
    self_contained: false
# uncomment this line to produce HTML and PDF in RStudio:
#knit: pagedown::chrome_print
---

```{css, echo=FALSE}
#title h1 {
  text-transform: unset;
}
```

Aside
================================================================================
...
</code>```

Body:
It is possible to remove the uppercase text transformation with CSS like that:

---
title: "Lijia Yu's resume"
author: Lijia Yu
date: "`r Sys.Date()`"
output:
  pagedown::html_resume:
    # set it to true for a self-contained HTML page but it'll take longer to render
    self_contained: false
# uncomment this line to produce HTML and PDF in RStudio:
#knit: pagedown::chrome_print
---

```{css, echo=FALSE}
#title h1 {
  text-transform: unset;
}
```

Aside
================================================================================
...


问:
How to pass a class to a function in Kotlin
I am trying to pass a class as an argument in Kotlin so that I can reuse a method, how would I convert this Java function to a Kotlin function?</p>

```<code> public void goToActivity(Activity activity, Class classs) {
    Intent intent = new Intent(activity, classs);
    context.startActivity(intent);
    activity.finish();
}
</code>```

答:
A class is passed in this format in Kotlin ClassName::class.java.

This seems to be the correct way to do it:

```<code>fun Context.goToActivity(activity: Activity, classs: Class<*>?) {
    val intent = Intent(activity, classs)
    startActivity(intent)
    activity.finish()
}
</code>```

And an example of how the method is called:

```<code>goToActivity(this, OneMainActivity::class.java)
</code>```

Body:
I am trying to pass a class as an argument in Kotlin so that I can reuse a method, how would I convert this Java function to a Kotlin function?

 public void goToActivity(Activity activity, Class classs) {
    Intent intent = new Intent(activity, classs);
    context.startActivity(intent);
    activity.finish();
}

Body:
A class is passed in this format in Kotlin ClassName::class.java.

This seems to be the correct way to do it:

fun Context.goToActivity(activity: Activity, classs: Class<*>?) {
    val intent = Intent(activity, classs)
    startActivity(intent)
    activity.finish()
}

And an example of how the method is called:

goToActivity(this, OneMainActivity::class.java)


问:
Java - class name in method declaration where the return type should be
I am working on some code where there is a method that looks like this:

```<code>    public static ProcessorClass getProcessor(String x, int y) {
     return(var);
    }
</code>```

From what I remember the way this is written the "ProcessorClass" is a return type but what does that mean. The "ProcessorClass" is the class that the method is currently in. I am confused in what this means.

答:
When a method uses a class name as its return type, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type.

Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated below.

```<code>                        Object
                          |
                        Number
                          |
                     ImaginaryNumber
</code>```

Now suppose that you have a method declared to return a Number:

```<code>public Number returnANumber() {
    ...
}
</code>```

The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

```<code>public ImaginaryNumber returnANumber() {
    ...
}
</code>```

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Body:
I am working on some code where there is a method that looks like this:

    public static ProcessorClass getProcessor(String x, int y) {
     return(var);
    }

From what I remember the way this is written the "ProcessorClass" is a return type but what does that mean. The "ProcessorClass" is the class that the method is currently in. I am confused in what this means.

Body:
When a method uses a class name as its return type, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type.

Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated below.

                        Object
                          |
                        Number
                          |
                     ImaginaryNumber

Now suppose that you have a method declared to return a Number:

public Number returnANumber() {
    ...
}

The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.

You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber() {
    ...
}

This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.


问:
How to search the name starting with special character in postgres
I have names which starts with special characters.I want to list those names. Some of the names are '%faf yf? -s_', '%faO{','%]fac?)f' and so on.

My query to list the name starting from '%' is like this:

```<code>Select * from table where name like '%fa%';
</code>```

This query is not working and it is also listing the names which starts from 'fa'. I only need the values which start from '%fa'.
I also tried the query like this

```<code>Select * from table where name like'[%]fa%'.
</code>```

答:
You need to escape the %:

Quote from the manual

To match a literal underscore or percent sign without matching other characters, the respective character in pattern must be preceded by the escape character. The default escape character is the backslash but a different one can be selected by using the ESCAPE clause. To match the escape character itself, write two escape characters

```<code>Select *
from the_table
where name like'\%fa%' escape '\'
</code>```

Body:
I have names which starts with special characters.I want to list those names. Some of the names are '%faf yf? -s_', '%faO{','%]fac?)f' and so on.

My query to list the name starting from '%' is like this:

Select * from table where name like '%fa%';

This query is not working and it is also listing the names which starts from 'fa'. I only need the values which start from '%fa'.
I also tried the query like this

Select * from table where name like'[%]fa%'.

Body:
You need to escape the %:

Quote from the manual

To match a literal underscore or percent sign without matching other characters, the respective character in pattern must be preceded by the escape character. The default escape character is the backslash but a different one can be selected by using the ESCAPE clause. To match the escape character itself, write two escape characters

Select *
from the_table
where name like'\%fa%' escape '\'


问:
What XCode version do I need for mcOS HighSierra Version 10.13.6
Hello I have a macbook air 2017 macOS High Sierra Version 10.13.6 and I tried installing from app store XCode and it says : Xcode can`t be installed on "Macintosh HD" because macOS version 10.15.2 or later is required. What can I do ? Please help</p>

答:
The current release of xcode is 11.5.1 (i think). Xcode 11.0 - 11.3 requires Mojave, Xcode 11.4.1 and above requires Catalina, so you would need to either update your OS or download Xcode 10 (probably Xcode 10.1).

There are a few potential issues with this...

There is a known issue that xcode 10 has trouble extracting/installing, if i remember rightly its to do with its signing certificate, you need to adjust the date on your system to unpack and install it

All new apps uploaded to the store must be built using Xcode 11

By installing and developing against an older version you will misss out on new features, such as SwiftUI which is usable since ios 13 / XC 11