问:
.NET Remoting with Reflection
I need to dynamically load an interface assembly that I use on client-side remoting. Something like this.

```<code>static void Main(string[] args)
{
  TcpClientChannel clientChannel = new TcpClientChannel();
  ChannelServices.RegisterChannel(clientChannel, false);

  Assembly interfaceAssembly = Assembly.LoadFile("RemotingInterface.dll");
  Type iTheInterface =
    interfaceAssembly.GetType("RemotingInterface.ITheService");

  RemotingConfiguration.RegisterWellKnownClientType(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
  object wellKnownObject = Activator.GetObject(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
}
</code>```

Only I can't seem to grasp how to call any methods as I can't cast the Activator.GetObject. How can I create a proxy of ITheService without knowing the interface at compile-time?

答:
First, inspect the available methods/interfaces of your object:

```<code>object wellKnownObject =
  Activator.GetObject(iTheInterface, "tcp://localhost:9090/Remotable.rem");

var objType = wellKnownObject.GetType();
var methods = objType.GetMethods();
var interfaces = objType.GetInterfaces();
</code>```

After you're sure about the method you want to invoke,

Consider using DLR and/or wrap the dynamic object in a DynamicObject container.

Use methods[i].Invoke on the object.

Here are some examples:

```<code>namespace ConsoleApplication1
{
  using System;

  class Program
  {

    static void Main()
    {
      //Using reflection:
      object obj = GetUnknownObject();
      var objType = obj.GetType();

      var knownInterface = objType.GetInterface("IA");
      var method = knownInterface.GetMethod("Print");
      method.Invoke(obj, new object[] { "Using reflection" });

      //Using DRL
      dynamic dObj = GetUnknownObject();
      dObj.Print("Using DLR");

      //Using a wrapper, so you the dirty dynamic code stays outside
      Marshal marshal = new Marshal(GetUnknownObject());
      marshal.Print("Using a wrapper");

    }

    static object GetUnknownObject()
    {
      return new A();
    }
  } //class Program

  class Marshal
  {
    readonly dynamic unknownObject;
    public Marshal(object unknownObject)
    {
      this.unknownObject = unknownObject;
    }

    public void Print(string text)
    {
      unknownObject.Print(text);
    }
  }

  #region Unknown Types
  interface IA
  {
    void Print(string text);
  }

  class A : IA
  {
    public void Print(string text)
    {
      Console.WriteLine(text);
      Console.ReadKey();
    }
  }
  #endregion Unknown Types
}
</code>```

Title: .NET Remoting with Reflection

Body:
I need to dynamically load an interface assembly that I use on client-side remoting. Something like this.

static void Main(string[] args)
{
  TcpClientChannel clientChannel = new TcpClientChannel();
  ChannelServices.RegisterChannel(clientChannel, false);

  Assembly interfaceAssembly = Assembly.LoadFile("RemotingInterface.dll");
  Type iTheInterface =
    interfaceAssembly.GetType("RemotingInterface.ITheService");

  RemotingConfiguration.RegisterWellKnownClientType(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
  object wellKnownObject = Activator.GetObject(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
}

Only I can't seem to grasp how to call any methods as I can't cast the Activator.GetObject. How can I create a proxy of ITheService without knowing the interface at compile-time?

Body:
First, inspect the available methods/interfaces of your object:

object wellKnownObject =
  Activator.GetObject(iTheInterface, "tcp://localhost:9090/Remotable.rem");

var objType = wellKnownObject.GetType();
var methods = objType.GetMethods();
var interfaces = objType.GetInterfaces();

After you're sure about the method you want to invoke,

Consider using DLR and/or wrap the dynamic object in a DynamicObject container.

Use methods[i].Invoke on the object.

Here are some examples:

namespace ConsoleApplication1
{
  using System;

  class Program
  {

    static void Main()
    {
      //Using reflection:
      object obj = GetUnknownObject();
      var objType = obj.GetType();

      var knownInterface = objType.GetInterface("IA");
      var method = knownInterface.GetMethod("Print");
      method.Invoke(obj, new object[] { "Using reflection" });

      //Using DRL
      dynamic dObj = GetUnknownObject();
      dObj.Print("Using DLR");

      //Using a wrapper, so you the dirty dynamic code stays outside
      Marshal marshal = new Marshal(GetUnknownObject());
      marshal.Print("Using a wrapper");

    }

    static object GetUnknownObject()
    {
      return new A();
    }
  } //class Program

  class Marshal
  {
    readonly dynamic unknownObject;
    public Marshal(object unknownObject)
    {
      this.unknownObject = unknownObject;
    }

    public void Print(string text)
    {
      unknownObject.Print(text);
    }
  }

  #region Unknown Types
  interface IA
  {
    void Print(string text);
  }

  class A : IA
  {
    public void Print(string text)
    {
      Console.WriteLine(text);
      Console.ReadKey();
    }
  }
  #endregion Unknown Types
}


来源: stackexchange

问:
Expiration of iOS build in the "Pending Developer Release" state
I'm planning on submitting a build, with the release being set to "Pending Developer Release". There are some outstanding dependencies that I'm waiting on before the build can go live in the App Store. That being said, once an app is approved and sitting in the "Pending Developer Release" state, is there any kind of expiration on that?

My concern is that I might be ready to make the build live on day 31 or 61 (for instance) from it being in "Pending Developer Release", but then unexpectedly the build is no longer valid and instead of going live, I'd have to make another new build and go through the approval process again.

答:
Binaries that are in "Pending Developer Release" wont expire, but you can expect an email from Apple if it stays in pending release for 30 days.

Just don't leave it so long that your certificate expires and should be fine.

ContentLicense: CC BY-SA 4.0


问:
How to complete or stall a save button operation using "Are you sure you want to proceed" modal with yes and no button in Rails?
I have a link in an HTML table which when clicked calls this Rails controller function :

Controller:

    def match
        render :partial => 'myview/match.js.erb'
    end
```

<p>The above controller calls this js partial:</p>

<h2>_match.js.erb</h2>

<pre class="lang-rb prettyprint-override"><code>    $('#match_' + <%=@debit.id%>).hide().after('<%= j render("match") %>');
</code>```

The above js partial calls the erb below:

_match.html.erb

  <%= form_for(@debit, remote: true, html: { id: 'match_form' }) do |f| %>
    <%= f.text_field :match_id, style: "width:82px" %>

    <%= button_tag 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
    <%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
  <% end %>
```

As shown the above partial displays a text field with 2 buttons Save and Cancel.

Now, when the user enters a value and clicks on Save, I would like to do some minor validation.

If the validation succeeds, I would like the Save operation to complete (which means the text field and the Save and Cancel buttons would disappear and the original HTML link would re-appear with the new value entered in the text field [now if this link with the new number is clicked, then the text field with Save and Cancel button would re-appear] i.e., the controller function def match should be allowed to complete)

If the validation fails, I would like to display a popup which gives a warning something like Are you sure you want to proceed with this value? along with 2 buttons Yes and No.

a) If the user clicks Yes, I would like the same thing to happen what happened in case 1 above
b) If the user clicks No, then the text field should stay unclosed along with the Save and Cancel buttons.

How can I achieve this please? What would be the simplest approach for this?

答:
The laziest way to do something similar would be to use the old client_side_validations gem.

You should be able to craft the behavior you want using the callbacks they provide:

```<code>// You will need to require 'jquery-ui' for this to work
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
  callback();
  if (element.data('valid') !== false) {
    element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500);
  }
}

window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
  // Take note how we're passing the callback to the hide()
  // method so it is run after the animation is complete.
  element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback);
}

.message {
  background-color: red;
  border-bottom-right-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  padding: 2px 5px;
}

div.field_with_errors div.ui-effects-wrapper {
  display: inline-block !important;
}
</code>```

Otherwise, you'll need to write a good amount of JavaScript to check all of the states of interest and draw the modal.

Body:
I have a link in an HTML table which when clicked calls this Rails controller function :

Controller:

    def match
        render :partial => 'myview/match.js.erb'
    end

The above controller calls this js partial:

_match.js.erb

    $('#match_' + <%=@debit.id%>).hide().after('<%= j render("match") %>');

The above js partial calls the erb below:

_match.html.erb

  <%= form_for(@debit, remote: true, html: { id: 'match_form' }) do |f| %>
    <%= f.text_field :match_id, style: "width:82px" %>

    <%= button_tag 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %>
    <%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
  <% end %>

As shown the above partial displays a text field with 2 buttons Save and Cancel.

Now, when the user enters a value and clicks on Save, I would like to do some minor validation.

If the validation succeeds, I would like the Save operation to complete (which means the text field and the Save and Cancel buttons would disappear and the original HTML link would re-appear with the new value entered in the text field [now if this link with the new number is clicked, then the text field with Save and Cancel button would re-appear] i.e., the controller function def match should be allowed to complete)

If the validation fails, I would like to display a popup which gives a warning something like Are you sure you want to proceed with this value? along with 2 buttons Yes and No.

a) If the user clicks Yes, I would like the same thing to happen what happened in case 1 above
b) If the user clicks No, then the text field should stay unclosed along with the Save and Cancel buttons.

How can I achieve this please? What would be the simplest approach for this?

Body:
The laziest way to do something similar would be to use the old client_side_validations gem.

You should be able to craft the behavior you want using the callbacks they provide:

// You will need to require 'jquery-ui' for this to work
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
  callback();
  if (element.data('valid') !== false) {
    element.parent().find('.message').hide().show('slide', {direction: "left", easing: "easeOutBounce"}, 500);
  }
}

window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
  // Take note how we're passing the callback to the hide()
  // method so it is run after the animation is complete.
  element.parent().find('.message').hide('slide', {direction: "left"}, 500, callback);
}

.message {
  background-color: red;
  border-bottom-right-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  padding: 2px 5px;
}

div.field_with_errors div.ui-effects-wrapper {
  display: inline-block !important;
}

Otherwise, you'll need to write a good amount of JavaScript to check all of the states of interest and draw the modal.


问:
TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds
I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.

Complete list of page response is :

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

My package.json is:

```<code>{
  "name": "webapplication10",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng run WebApplication10:server:dev",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "9.0.0",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "9.0.0",
    "@angular/compiler": "9.0.0",
    "@angular/core": "9.0.0",
    "@angular/forms": "9.0.0",
    "@angular/material": "~9.0.0",
    "@angular/platform-browser": "9.0.0",
    "@angular/platform-browser-dynamic": "9.0.0",
    "@angular/platform-server": "9.0.0",
    "@angular/router": "9.0.0",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "aspnet-prerendering": "^3.0.1",
    "bootstrap": "^4.4.1",
    "core-js": "^3.6.4",
    "jquery": "3.4.1",
    "oidc-client": "^1.10.1",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.900.1",
    "@angular/cli": "9.0.1",
    "@angular/compiler-cli": "9.0.0",
    "@angular/language-service": "9.0.0",
    "@types/jasmine": "^3.5.3",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "^12.12.27",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "typescript": "3.7.5"
  },
  "optionalDependencies": {
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "ts-node": "~8.4.1",
    "tslint": "~5.20.0"
  }
}
```
```

答:
TL;DR

Sadly the issue seems related to some changes in the way Angular CLI starts up the angular part of the application. As per this issue:

https://github.com/dotnet/aspnetcore/issues/17277

proposed solutions are to set progress: true in angular.json or  perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).

Full answer

I dug the asp.net core code base (https://github.com/dotnet/aspnetcore), looking how the Angular template starts up the Angular application.

The core engine that starts up the angular server is represented by two classes: AngularCliMiddleware (https://git.io/JvlaL) and NodeScriptRunner (https://git.io/Jvlaq).

In AngularCliMiddleware we find this code (I removed the original comments and added some of my own to explain a couple of things):

```<code>public static void Attach(ISpaBuilder spaBuilder, string npmScriptName)
{
    var sourcePath = spaBuilder.Options.SourcePath;
    if (string.IsNullOrEmpty(sourcePath))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
    }

    if (string.IsNullOrEmpty(npmScriptName))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName));
    }

    // Start Angular CLI and attach to middleware pipeline
    var appBuilder = spaBuilder.ApplicationBuilder;
    var logger = LoggerFinder.GetOrCreateLogger(appBuilder, LogCategoryName);
    var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger);

    var targetUriTask = angularCliServerInfoTask.ContinueWith(
        task => new UriBuilder("http", "localhost", task.Result.Port).Uri);

    SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, () =>
    {
        var timeout = spaBuilder.Options.StartupTimeout;
        return targetUriTask.WithTimeout(timeout,
            $"The Angular CLI process did not start listening for requests " +

            // === NOTE THIS LINE, THAT CARRIES THE "0 seconds" BUG!!!
            $"within the timeout period of {timeout.Seconds} seconds. " +

            $"Check the log output for error information.");
    });
}

private static async Task<AngularCliServerInfo> StartAngularCliServerAsync(
    string sourcePath, string npmScriptName, ILogger logger)
{
    var portNumber = TcpPortFinder.FindAvailablePort();
    logger.LogInformation($"Starting @angular/cli on port {portNumber}...");

    var npmScriptRunner = new NpmScriptRunner(
        sourcePath, npmScriptName, $"--port {portNumber}", null);
    npmScriptRunner.AttachToLogger(logger);

    Match openBrowserLine;
    using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr))
    {
        try
        {
            // THIS LINE: awaits for the angular server to output
            // the 'open your browser...' string to stdout stream
            openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch(
                new Regex("open your browser on (http\\S+)", RegexOptions.None, RegexMatchTimeout));
        }
        catch (EndOfStreamException ex)
        {
            throw new InvalidOperationException(
                $"The NPM script '{npmScriptName}' exited without indicating that the " +
                $"Angular CLI was listening for requests. The error output was: " +
                $"{stdErrReader.ReadAsString()}", ex);
        }
    }

    var uri = new Uri(openBrowserLine.Groups[1].Value);
    var serverInfo = new AngularCliServerInfo { Port = uri.Port };

    await WaitForAngularCliServerToAcceptRequests(uri);

    return serverInfo;
}
</code>```

As you can see, the StartAngularCliServerAsync method creates a new NpmScriptRunner object, that is a wrapper around a Process.Start method call, basically, attaches the logger and then waits for the StdOut of the process to emit something that matches "open your browser on httpSOMETHING...".

Fun thing is this should work!

If you run ng serve (or npm run start) in ClientApp folder, once the server starts it still emit the output "open your browser on http...".

If you dotnet run the application, the node server actually starts, just enable all the logs in Debug mode, find the "Starting @angular/cli on port ..." line and try visiting localhost on that port, you'll see that your angular application IS running.

Problem is that for some reason the StdOut is not getting the "open your browser on" line anymore, nor it is written by the logger... it seems that in some way that particular output line from ng serve is held back, like it's no longer sent in the Stardard Output stream. The WaitForMatch method hits his timeout after 5 seconds and is catched from the code of the WithTimeout extension method, that outputs the (bugged) "... 0 seconds ..." message.

For what I could see, once you dotnet run your application, a series of processes is spawn in sequence, but i couldn't notice any difference in the command lines from Angular 8 to Angular 9.

My theory is that something has been changed in Angular CLI that prevents that line to be sent in stdout, so the .net proxy doesn't catch it and can't detect when the angular server is started.

As per this issue:

https://github.com/dotnet/aspnetcore/issues/17277

proposed solutions are to set progress: true in angular.json or  perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).

Body:
I'm getting this error after upgrading to angular 9. I'm using visual studio 2019, ASP .NET core with angular. Even if I create new project and update angular to 9 version, It stops working.

Complete list of page response is :

TimeoutException: The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Check the log output for error information. Microsoft.AspNetCore.SpaServices.Extensions.Util.TaskTimeoutExtensions.WithTimeout(Task task, TimeSpan timeoutDelay, string message) Microsoft.AspNetCore.SpaServices.Extensions.Proxy.SpaProxy.PerformProxyRequest(HttpContext context, HttpClient httpClient, Task baseUriTask, CancellationToken applicationStoppingToken, bool proxy404s) Microsoft.AspNetCore.Builder.SpaProxyingExtensions+<>c__DisplayClass2_0+<b__0>d.MoveNext() Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

My package.json is:

{
  "name": "webapplication10",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "build:ssr": "ng run WebApplication10:server:dev",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "9.0.0",
    "@angular/cdk": "~9.0.0",
    "@angular/common": "9.0.0",
    "@angular/compiler": "9.0.0",
    "@angular/core": "9.0.0",
    "@angular/forms": "9.0.0",
    "@angular/material": "~9.0.0",
    "@angular/platform-browser": "9.0.0",
    "@angular/platform-browser-dynamic": "9.0.0",
    "@angular/platform-server": "9.0.0",
    "@angular/router": "9.0.0",
    "@nguniversal/module-map-ngfactory-loader": "8.1.1",
    "aspnet-prerendering": "^3.0.1",
    "bootstrap": "^4.4.1",
    "core-js": "^3.6.4",
    "jquery": "3.4.1",
    "oidc-client": "^1.10.1",
    "popper.js": "^1.16.1",
    "rxjs": "^6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.900.1",
    "@angular/cli": "9.0.1",
    "@angular/compiler-cli": "9.0.0",
    "@angular/language-service": "9.0.0",
    "@types/jasmine": "^3.5.3",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "^12.12.27",
    "codelyzer": "^5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "typescript": "3.7.5"
  },
  "optionalDependencies": {
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "ts-node": "~8.4.1",
    "tslint": "~5.20.0"
  }
}
```

Body:
TL;DR

Sadly the issue seems related to some changes in the way Angular CLI starts up the angular part of the application. As per this issue:

https://github.com/dotnet/aspnetcore/issues/17277

proposed solutions are to set progress: true in angular.json or  perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).

Full answer

I dug the asp.net core code base (https://github.com/dotnet/aspnetcore), looking how the Angular template starts up the Angular application.

The core engine that starts up the angular server is represented by two classes: AngularCliMiddleware (https://git.io/JvlaL) and NodeScriptRunner (https://git.io/Jvlaq).

In AngularCliMiddleware we find this code (I removed the original comments and added some of my own to explain a couple of things):

public static void Attach(ISpaBuilder spaBuilder, string npmScriptName)
{
    var sourcePath = spaBuilder.Options.SourcePath;
    if (string.IsNullOrEmpty(sourcePath))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(sourcePath));
    }

    if (string.IsNullOrEmpty(npmScriptName))
    {
        throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName));
    }

    // Start Angular CLI and attach to middleware pipeline
    var appBuilder = spaBuilder.ApplicationBuilder;
    var logger = LoggerFinder.GetOrCreateLogger(appBuilder, LogCategoryName);
    var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger);

    var targetUriTask = angularCliServerInfoTask.ContinueWith(
        task => new UriBuilder("http", "localhost", task.Result.Port).Uri);

    SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, () =>
    {
        var timeout = spaBuilder.Options.StartupTimeout;
        return targetUriTask.WithTimeout(timeout,
            $"The Angular CLI process did not start listening for requests " +

            // === NOTE THIS LINE, THAT CARRIES THE "0 seconds" BUG!!!
            $"within the timeout period of {timeout.Seconds} seconds. " +

            $"Check the log output for error information.");
    });
}

private static async Task<AngularCliServerInfo> StartAngularCliServerAsync(
    string sourcePath, string npmScriptName, ILogger logger)
{
    var portNumber = TcpPortFinder.FindAvailablePort();
    logger.LogInformation($"Starting @angular/cli on port {portNumber}...");

    var npmScriptRunner = new NpmScriptRunner(
        sourcePath, npmScriptName, $"--port {portNumber}", null);
    npmScriptRunner.AttachToLogger(logger);

    Match openBrowserLine;
    using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr))
    {
        try
        {
            // THIS LINE: awaits for the angular server to output
            // the 'open your browser...' string to stdout stream
            openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch(
                new Regex("open your browser on (http\\S+)", RegexOptions.None, RegexMatchTimeout));
        }
        catch (EndOfStreamException ex)
        {
            throw new InvalidOperationException(
                $"The NPM script '{npmScriptName}' exited without indicating that the " +
                $"Angular CLI was listening for requests. The error output was: " +
                $"{stdErrReader.ReadAsString()}", ex);
        }
    }

    var uri = new Uri(openBrowserLine.Groups[1].Value);
    var serverInfo = new AngularCliServerInfo { Port = uri.Port };

    await WaitForAngularCliServerToAcceptRequests(uri);

    return serverInfo;
}

As you can see, the StartAngularCliServerAsync method creates a new NpmScriptRunner object, that is a wrapper around a Process.Start method call, basically, attaches the logger and then waits for the StdOut of the process to emit something that matches "open your browser on httpSOMETHING...".

Fun thing is this should work!

If you run ng serve (or npm run start) in ClientApp folder, once the server starts it still emit the output "open your browser on http...".

If you dotnet run the application, the node server actually starts, just enable all the logs in Debug mode, find the "Starting @angular/cli on port ..." line and try visiting localhost on that port, you'll see that your angular application IS running.

Problem is that for some reason the StdOut is not getting the "open your browser on" line anymore, nor it is written by the logger... it seems that in some way that particular output line from ng serve is held back, like it's no longer sent in the Stardard Output stream. The WaitForMatch method hits his timeout after 5 seconds and is catched from the code of the WithTimeout extension method, that outputs the (bugged) "... 0 seconds ..." message.

For what I could see, once you dotnet run your application, a series of processes is spawn in sequence, but i couldn't notice any difference in the command lines from Angular 8 to Angular 9.

My theory is that something has been changed in Angular CLI that prevents that line to be sent in stdout, so the .net proxy doesn't catch it and can't detect when the angular server is started.

As per this issue:

https://github.com/dotnet/aspnetcore/issues/17277

proposed solutions are to set progress: true in angular.json or  perform a simple echo prior to ng serve (https://github.com/dotnet/aspnetcore/issues/17277#issuecomment-562433864).


问:
Add fds in the GLIB mainloop
I need to attach file descriptors to the GLIB mainloop. My issue is that the list of file descriptors is not fixed during execution.

According to GLIB documentation, I can:

create a GIOChannel for each FD using g_io_channel_unix_new and attach it to the context with g_io_add_watch

Use a Gsource created with g_io_create_watch and set a callback g_source_set_callback

My question is : is it possible to modify dynamically a source or a context. And how can I do it ? I find the GSourceFuncs ability, but that doesn't fit my issue.

Thanks for your help.

答:
Seems, I found a diminutive hook. Try this:

```<code>struct source {
    GSource gsrc;
    GPollFD *gpfd;
};

struct data {
    /* A something data. */
};

static gboolean gsrc_dispatch(GSource *gsrc, GSourceFunc cb, gpointer data);
static struct data * data_alloc(void);

static GSourceFuncs gsf = {
    .prepare = NULL,
    .check = NULL,
    .dispatch = gsrc_dispatch,
    .finalize = NULL
};

int main(void)
{
    struct source *src;
    int fd;
    struct data *data = data_alloc();

    /* Something other. */

    /* For example, we are want to capture video from a camera. */
    fd = open("/dev/video0", O_RDWR);
    if (fd < 0) {
        perror("open()");

        return -1;
    }

    src = (struct source *) g_source_new(&gsf, sizeof(struct source));
    src->gpfd = g_source_add_unix_fd((GSource *) src, fd, G_IO_IN);

    g_source_set_callback((GSource *) src, NULL, data, NULL);
    g_source_attach((GSource *) src, NULL);

    /* Something other and free. */

    return 0;
}

static gboolean
gsrc_dispatch(GSource *gsrc, GSourceFunc cb, gpointer data)
{
    struct source *src = (struct source *) gsrc;
    struct data *d = data;

    if (src->gpfd != NULL) {
        if (src->gpfd->revents & G_IO_IN) {
            /* Capture a frame. */
        }
    }

    g_main_context_iteration(NULL, TRUE);

    return G_SOURCE_CONTINUE;
}

static struct data *
data_alloc(void)
{
    /* Allocate a data. */
}
</code>```

Yes, you can use the double gpfd pointer.

ContentLicense: CC BY-SA 3.0

Title: Add fds in the GLIB mainloop

Body:
Seems, I found a diminutive hook. Try this:

struct source {
    GSource gsrc;
    GPollFD *gpfd;
};

struct data {
    /* A something data. */
};

static gboolean gsrc_dispatch(GSource *gsrc, GSourceFunc cb, gpointer data);
static struct data * data_alloc(void);

static GSourceFuncs gsf = {
    .prepare = NULL,
    .check = NULL,
    .dispatch = gsrc_dispatch,
    .finalize = NULL
};

int main(void)
{
    struct source *src;
    int fd;
    struct data *data = data_alloc();

    /* Something other. */

    /* For example, we are want to capture video from a camera. */
    fd = open("/dev/video0", O_RDWR);
    if (fd < 0) {
        perror("open()");

        return -1;
    }

    src = (struct source *) g_source_new(&gsf, sizeof(struct source));
    src->gpfd = g_source_add_unix_fd((GSource *) src, fd, G_IO_IN);

    g_source_set_callback((GSource *) src, NULL, data, NULL);
    g_source_attach((GSource *) src, NULL);

    /* Something other and free. */

    return 0;
}

static gboolean
gsrc_dispatch(GSource *gsrc, GSourceFunc cb, gpointer data)
{
    struct source *src = (struct source *) gsrc;
    struct data *d = data;

    if (src->gpfd != NULL) {
        if (src->gpfd->revents & G_IO_IN) {
            /* Capture a frame. */
        }
    }

    g_main_context_iteration(NULL, TRUE);

    return G_SOURCE_CONTINUE;
}

static struct data *
data_alloc(void)
{
    /* Allocate a data. */
}

Yes, you can use the double gpfd pointer.


问:
Combine arrays of identical length into array of objects
I have 10 arrays of data that look like this:

```<code>var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
</code>```

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

```<code>overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
</code>```

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

答:
You can get from this:

```<code>[  [1, 2, 3]
,  [4, 5, 6]
,  [7, 8, 9]
]
</code>```

to this:

```<code>[  [1, 4, 7]
,  [2, 5, 8]
,  [3, 6, 9]
]
</code>```

with this function:

```<code>const combine =
  (...arrs) =>
    [ arrs.map(xs => xs[0])
    , ... (  arrs.every(xs => xs.length === 1)
              ? []
              : combine(...arrs.map(xs => xs.slice(1)))
          )
    ];

combine
  (  [1, 2, 3]
  ,  [4, 5, 6]
  ,  [7, 8, 9]
  );
</code>```

Then from this:

```<code>[  [1, 4, 7]
,  [2, 5, 8]
,  [3, 6, 9]
]
</code>```

to this:

```<code>[ {arr1: 1, arr2: 4, arr3: 7}
, {arr1: 2, arr2: 5, arr3: 8}
, {arr1: 3, arr2: 6, arr3: 9}
]
</code>```

with this function:

```<code>const to_obj =
  (...arrs) =>
    arrs.map(arr =>
      Object.fromEntries(
        arr.map((x, i) => [`arr${i+1}`, x])));

to_obj
  ( [1, 4, 7]
  , [2, 5, 8]
  , [3, 6, 9]
  )
</code>```

Hopefully connecting the two functions together is straightforward.

A note about performance

With exactly 10 arrays of 10 elements each, it is unlikely that you can tell whether a particular solution performs better than another. You should probably go for the solution that feels right in terms of readability or maintenance.

By these criteria you  should probably exclude mine; just wanted to share a different approach.

Body:
I have 10 arrays of data that look like this:

var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays

Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:

overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]

I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.

Body:
You can get from this:

[  [1, 2, 3]
,  [4, 5, 6]
,  [7, 8, 9]
]

to this:

[  [1, 4, 7]
,  [2, 5, 8]
,  [3, 6, 9]
]

with this function:

const combine =
  (...arrs) =>
    [ arrs.map(xs => xs[0])
    , ... (  arrs.every(xs => xs.length === 1)
              ? []
              : combine(...arrs.map(xs => xs.slice(1)))
          )
    ];

combine
  (  [1, 2, 3]
  ,  [4, 5, 6]
  ,  [7, 8, 9]
  );

Then from this:

[  [1, 4, 7]
,  [2, 5, 8]
,  [3, 6, 9]
]

to this:

[ {arr1: 1, arr2: 4, arr3: 7}
, {arr1: 2, arr2: 5, arr3: 8}
, {arr1: 3, arr2: 6, arr3: 9}
]

with this function:

const to_obj =
  (...arrs) =>
    arrs.map(arr =>
      Object.fromEntries(
        arr.map((x, i) => [`arr${i+1}`, x])));

to_obj
  ( [1, 4, 7]
  , [2, 5, 8]
  , [3, 6, 9]
  )

Hopefully connecting the two functions together is straightforward.

A note about performance

With exactly 10 arrays of 10 elements each, it is unlikely that you can tell whether a particular solution performs better than another. You should probably go for the solution that feels right in terms of readability or maintenance.

By these criteria you  should probably exclude mine; just wanted to share a different approach.


问:
in nested for loop in JAVA, why is the faster big loop in small loop than small loop in big loop?
When the number of iterations is the same, I wonder if the smaller iterations of the outer 'for loop' are faster.

This is my java code.

total loops iterations is 100 billion.

```<code>public class Test {

    public static long run1() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<1000000000; i++) {
            for(int j = 0 ; j<100 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run1 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static long run2() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<100; i++) {
            for(int j = 0 ; j<1000000000 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run2 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static void main(String[] args) {

        for(int i = 0 ; i < 10 ; i++) {
            long test1 = run1();
            long test2 = run2();
            System.out.println("Time diff : "+(test1-test2)*1e-9+" sec\n");
        }
    }
}
</code>```

and this is result

```<code>run1 : 4.5772473950000006 sec
run2 : 1.7155700900000002 sec
Time diff : -2.861677305 sec

run1 : 4.4107229420000005 sec
run2 : 1.6532413140000002 sec
Time diff : -2.7574816280000003 sec

run1 : 3.815836296 sec
run2 : 1.761153921 sec
Time diff : -2.054682375 sec

run1 : 3.913543021 sec
run2 : 1.752971717 sec
Time diff : -2.1605713040000003 sec

run1 : 3.851766485 sec
run2 : 1.7262416440000001 sec
Time diff : -2.1255248410000003 sec

run1 : 3.95305219 sec
run2 : 1.7323067330000002 sec
Time diff : -2.220745457 sec

run1 : 3.924869236 sec
run2 : 1.6953032440000002 sec
Time diff : -2.229565992 sec

run1 : 3.839871705 sec
run2 : 1.692300162 sec
Time diff : -2.147571543 sec

run1 : 3.93864626 sec
run2 : 1.704322469 sec
Time diff : -2.234323791 sec

run1 : 3.863758493 sec
run2 : 1.700392962 sec
Time diff : -2.163365531 sec
</code>```

like this,

I wonder why these results are coming.

and, edited by Triple nested loops, Similar results are obtained.

答:
The short answer is: JIT and your math is wrong.

Let's start with your run methods, which end with this print line and a return

```<code>System.out.println("run1 : "+(end-start)*1e-9+" sec");
return start - end;
</code>```

The problem here is you're printing end-start, and returning start-end. Instead of doing the math in the run methods, I shifted it around so that each run is only responsible for the run and the timing:

```<code>public class loops
{

  public static long run1()
  {
    final long start = System.nanoTime();
    long cnt = 0;
    for (int i = 0; i < 1000000000; i++)
    {
      for (int j = 0; j < 100; j++)
      {
        cnt++;
      }
    }
    final long end = System.nanoTime();
    return end - start;
  }

  public static long run2()
  {
    final long start = System.nanoTime();
    long cnt = 0;
    for (int i = 0; i < 100; i++)
    {
      for (int j = 0; j < 1000000000; j++)
      {
        cnt++;
      }
    }
    final long end = System.nanoTime();
    return end - start;
  }

  public static void main(String[] args)
  {

    for (int i = 0; i < 10; i++)
    {
      long test1 = run1();
      long test2 = run2();
      System.out.println("run1 : " + test1 + " ns");
      System.out.println("run2 : " + test2 + " ns");
      System.out.println("Time diff : " + (test1 - test2) + " ns\n");
    }
  }
}
</code>```

I also took out the math because.. well, why bother? what's wrong with looking at the values as nanoseconds? That's what the actually are...

Running this you can see initial large values that decrease and approach zero. In some runs they do even reach zero for both versions.

Zero nanoseconds? Yes, instant computing. Let Quantum computing suck on that!
Okay, it's not really instant. Not when you check the nanoTime description:

This method provides nanosecond precision, but not necessarily
  nanosecond resolution (that is, how frequently the value changes)

It's just faster than is feasibly measurable becauser the JIT has probably ultimately figured out that the method doesn't actually do anything. Now why one or the other decreases faster than the other would require a deeper dive into the JIT and how it decides to optimize one method vs the another - which is more than I know.

Utilmately, there is virtually no difference. After the intial run of both methods, the largest time difference is only a few milliseconds at most. I don't believe this is anything significant to say that one version is truly faster than the other.

Interesting side notes:
JDK-11 didn't seem to perform as well...

GraalVM didn't seem to perform as well... although, there's probably some flag that would improve it...

Body:
When the number of iterations is the same, I wonder if the smaller iterations of the outer 'for loop' are faster.

This is my java code.

total loops iterations is 100 billion.

public class Test {

    public static long run1() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<1000000000; i++) {
            for(int j = 0 ; j<100 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run1 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static long run2() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<100; i++) {
            for(int j = 0 ; j<1000000000 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run2 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static void main(String[] args) {

        for(int i = 0 ; i < 10 ; i++) {
            long test1 = run1();
            long test2 = run2();
            System.out.println("Time diff : "+(test1-test2)*1e-9+" sec\n");
        }
    }
}

and this is result

run1 : 4.5772473950000006 sec
run2 : 1.7155700900000002 sec
Time diff : -2.861677305 sec

run1 : 4.4107229420000005 sec
run2 : 1.6532413140000002 sec
Time diff : -2.7574816280000003 sec

run1 : 3.815836296 sec
run2 : 1.761153921 sec
Time diff : -2.054682375 sec

run1 : 3.913543021 sec
run2 : 1.752971717 sec
Time diff : -2.1605713040000003 sec

run1 : 3.851766485 sec
run2 : 1.7262416440000001 sec
Time diff : -2.1255248410000003 sec

run1 : 3.95305219 sec
run2 : 1.7323067330000002 sec
Time diff : -2.220745457 sec

run1 : 3.924869236 sec
run2 : 1.6953032440000002 sec
Time diff : -2.229565992 sec

run1 : 3.839871705 sec
run2 : 1.692300162 sec
Time diff : -2.147571543 sec

run1 : 3.93864626 sec
run2 : 1.704322469 sec
Time diff : -2.234323791 sec

run1 : 3.863758493 sec
run2 : 1.700392962 sec
Time diff : -2.163365531 sec

like this,

I wonder why these results are coming.

and, edited by Triple nested loops, Similar results are obtained.

Body:
The short answer is: JIT and your math is wrong.

Let's start with your run methods, which end with this print line and a return

System.out.println("run1 : "+(end-start)*1e-9+" sec");
return start - end;

The problem here is you're printing end-start, and returning start-end. Instead of doing the math in the run methods, I shifted it around so that each run is only responsible for the run and the timing:

public class loops
{

  public static long run1()
  {
    final long start = System.nanoTime();
    long cnt = 0;
    for (int i = 0; i < 1000000000; i++)
    {
      for (int j = 0; j < 100; j++)
      {
        cnt++;
      }
    }
    final long end = System.nanoTime();
    return end - start;
  }

  public static long run2()
  {
    final long start = System.nanoTime();
    long cnt = 0;
    for (int i = 0; i < 100; i++)
    {
      for (int j = 0; j < 1000000000; j++)
      {
        cnt++;
      }
    }
    final long end = System.nanoTime();
    return end - start;
  }

  public static void main(String[] args)
  {

    for (int i = 0; i < 10; i++)
    {
      long test1 = run1();
      long test2 = run2();
      System.out.println("run1 : " + test1 + " ns");
      System.out.println("run2 : " + test2 + " ns");
      System.out.println("Time diff : " + (test1 - test2) + " ns\n");
    }
  }
}

I also took out the math because.. well, why bother? what's wrong with looking at the values as nanoseconds? That's what the actually are...

Running this you can see initial large values that decrease and approach zero. In some runs they do even reach zero for both versions.

Zero nanoseconds? Yes, instant computing. Let Quantum computing suck on that!
Okay, it's not really instant. Not when you check the nanoTime description:

This method provides nanosecond precision, but not necessarily
  nanosecond resolution (that is, how frequently the value changes)

It's just faster than is feasibly measurable becauser the JIT has probably ultimately figured out that the method doesn't actually do anything. Now why one or the other decreases faster than the other would require a deeper dive into the JIT and how it decides to optimize one method vs the another - which is more than I know.

Utilmately, there is virtually no difference. After the intial run of both methods, the largest time difference is only a few milliseconds at most. I don't believe this is anything significant to say that one version is truly faster than the other.

Interesting side notes:
JDK-11 didn't seem to perform as well...

GraalVM didn't seem to perform as well... although, there's probably some flag that would improve it...


问:
including a .c file in another .c file
This is part of a homework assignment. What we have to do is write a makefile to compile previous homework solutions. The solutions were provided by the professor, and they're what will be used to test our makefiles. One of the files has an #include "quicksort.c".

I know the usage of something like that is discouraged, but that doesn't really help me :)

What would be the best approach to getting the two files to compile (the file quicksortTest.c, which includes quicksort.c, and quicksort.c itself)?

What I currently have as part of my makefile is the following:

```<code>    quicksort: quicksort.c quicksortTest.c
               $(CC) quicksortTest.c quicksort.c -o quicksortTest
</code>```

Where quicksortTest.c has the #include "quicksort.c".

When I try it, I get several gcc compiler errors... ideas?

答:
Do it like this

```<code>quicksort: quicksort.c quicksortTest.c
           $(CC) quicksortTest.c -o quicksortTest
</code>```

Consider giving your teacher a C book.

Title: including a .c file in another .c file

Body:
This is part of a homework assignment. What we have to do is write a makefile to compile previous homework solutions. The solutions were provided by the professor, and they're what will be used to test our makefiles. One of the files has an #include "quicksort.c".

I know the usage of something like that is discouraged, but that doesn't really help me :)

What would be the best approach to getting the two files to compile (the file quicksortTest.c, which includes quicksort.c, and quicksort.c itself)?

What I currently have as part of my makefile is the following:

    quicksort: quicksort.c quicksortTest.c
               $(CC) quicksortTest.c quicksort.c -o quicksortTest

Where quicksortTest.c has the #include "quicksort.c".

When I try it, I get several gcc compiler errors... ideas?

Body:
Do it like this

quicksort: quicksort.c quicksortTest.c
           $(CC) quicksortTest.c -o quicksortTest

Consider giving your teacher a C book.


问:
Function for adjusted Rsquare on test data?
w.r.t  R/Rstudio  I know there is RMSE and R2 function which i can leverage to calculate RMSE and Rsquare on test data.  Is there a similar function for adjusted R square on test data?</p>

答:
A number of base functions in R will output an adjusted R2. It just depends on what the objective or context is. For example, if the goal is to calculate the fit of a linear model with the lm() function,

```<code>x <- rnorm( 10 )
y <- rnorm( 10 )
linear_model <- lm( y~x )
summary( linear_model )
</code>```

The output would include the adjusted R-square for fitting that linear model:

```<code>Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max
-1.5876 -0.5203  0.1511  0.4593  1.1989

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.2018     0.2777  -0.727    0.488
x            -0.4355     0.3696  -1.178    0.272

Residual standard error: 0.8748 on 8 degrees of freedom
Multiple R-squared:  0.1479,    Adjusted R-squared:  0.0414
F-statistic: 1.389 on 1 and 8 DF,  p-value: 0.2725
</code>```

But again, this value is ONLY in reference for fitting a linear model to the data, and is simply an illustration that R may report it with certain functions.

Body:
A number of base functions in R will output an adjusted R2. It just depends on what the objective or context is. For example, if the goal is to calculate the fit of a linear model with the lm() function,

x <- rnorm( 10 )
y <- rnorm( 10 )
linear_model <- lm( y~x )
summary( linear_model )

The output would include the adjusted R-square for fitting that linear model:

Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max
-1.5876 -0.5203  0.1511  0.4593  1.1989

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -0.2018     0.2777  -0.727    0.488
x            -0.4355     0.3696  -1.178    0.272

Residual standard error: 0.8748 on 8 degrees of freedom
Multiple R-squared:  0.1479,    Adjusted R-squared:  0.0414
F-statistic: 1.389 on 1 and 8 DF,  p-value: 0.2725

But again, this value is ONLY in reference for fitting a linear model to the data, and is simply an illustration that R may report it with certain functions.


问:
Using a .R file as a resource and create a batch directly in C#
I have a number of shiny applications with the file structure global.R, ui.R, server.R and something I call batchTrigger.R. The contents of the latter is simply the following-

```<code>.libPath(*Path to my R Package Repository*)
require('shiny')
runApp(*Path to the folder with the aforementioned files*)
</code>```

I created a batch file called application.cmd with the following code-

```<code>cls
@pushd ""
:::::::::::::::::::
@echo off
ECHO Loading...Please, wait. The Application will open automatically.
ECHO ---
ECHO Do not close this console window for the whole duration of your session
ECHO in the application.
ECHO ---
@echo off

"C:\Program Files\R\bin\Rscript.exe" ".../**batchTrigger.R**"

:::::::::::::::::::
@popd
cmd /k
</code>```

This batch file is working just fine. Then I went one step further, and decided to create a windows form with multiple R Applications. I have two buttons in the form, each of which goes something like this-

```<code> private void application1_click(object sender, EventArgs e)
    {
        System.Diagnostics.Process cmd = new Process();
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.FileName = "...\\**application1.cmd**";
        cmd.StartInfo.Arguments = "/K";
        cmd.StartInfo.CreateNoWindow = false;
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.Start();
    }
</code>```

So far, so good. Both the buttons work exactly as they were supposed to. I want to go one more step ahead, but since I am very new at C#, I need help. What I am hoping to get is a dynamic location for the R files and the cmd files within the thus deployed application, within the solution. In other words, I should be able to write the contents of the batch file within the C# code, and the path of the batchTrigger.R should be something which changes with the location of the windows form application (which will be a self contained deployed executable file). The idea is that the R package repository and R installation may remain static and can be pointed at by the batchTrigger.R and application.cmd respectively, but the location of batchTrigger.R itself along with other R files move with the application. I think that resource.resx can do something about this, but how exactly can I go about doing it, I don't seem to get. Any suggestion would be highly appreciated.

答:
Make a general method:

```<code>private void StartSilentR(string rScriptFilePath)
{
    System.Diagnostics.Process cmd = new Process();
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.FileName = @"C:\Program Files\R\bin\Rscript.exe";
    cmd.StartInfo.Arguments = rScriptFilePath;
    cmd.StartInfo.CreateNoWindow = false;
    //avoid this unless you must control the app via stdin
    //cmd.StartInfo.RedirectStandardInput = true;
    cmd.Start();
}
</code>```

Then write something that calls it after working out where the script is. For example if you have your directory structure as:

```<code>RLauncherCSharpApp.exe
rscripts\ui.R
rscripts\global.R
rscripts\batchTrigger.R
</code>```

Then in c# you can:

```<code>//take exe Path, remove exe name and add rscripts folder and batchtrigger.R file name
var rbt = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "rscripts", "batchTrigger.R");

StartSilentR(rbt);
</code>```

Or, say you want to search all the subfolders of the app's folder looking for all files called batchTrigger.R:

```<code>var exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string[] paths = Directory.GetFiles(exeFolder, "batchTrigger.R", SearchOption.AllDirectories);

//maybe add them to a list view and the user can click one to launch ..
</code>```

Body:
I have a number of shiny applications with the file structure global.R, ui.R, server.R and something I call batchTrigger.R. The contents of the latter is simply the following-

.libPath(*Path to my R Package Repository*)
require('shiny')
runApp(*Path to the folder with the aforementioned files*)

I created a batch file called application.cmd with the following code-

cls
@pushd ""
:::::::::::::::::::
@echo off
ECHO Loading...Please, wait. The Application will open automatically.
ECHO ---
ECHO Do not close this console window for the whole duration of your session
ECHO in the application.
ECHO ---
@echo off

"C:\Program Files\R\bin\Rscript.exe" ".../**batchTrigger.R**"

:::::::::::::::::::
@popd
cmd /k

This batch file is working just fine. Then I went one step further, and decided to create a windows form with multiple R Applications. I have two buttons in the form, each of which goes something like this-

 private void application1_click(object sender, EventArgs e)
    {
        System.Diagnostics.Process cmd = new Process();
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.FileName = "...\\**application1.cmd**";
        cmd.StartInfo.Arguments = "/K";
        cmd.StartInfo.CreateNoWindow = false;
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.Start();
    }

So far, so good. Both the buttons work exactly as they were supposed to. I want to go one more step ahead, but since I am very new at C#, I need help. What I am hoping to get is a dynamic location for the R files and the cmd files within the thus deployed application, within the solution. In other words, I should be able to write the contents of the batch file within the C# code, and the path of the batchTrigger.R should be something which changes with the location of the windows form application (which will be a self contained deployed executable file). The idea is that the R package repository and R installation may remain static and can be pointed at by the batchTrigger.R and application.cmd respectively, but the location of batchTrigger.R itself along with other R files move with the application. I think that resource.resx can do something about this, but how exactly can I go about doing it, I don't seem to get. Any suggestion would be highly appreciated.

Body:
Make a general method:

private void StartSilentR(string rScriptFilePath)
{
    System.Diagnostics.Process cmd = new Process();
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.FileName = @"C:\Program Files\R\bin\Rscript.exe";
    cmd.StartInfo.Arguments = rScriptFilePath;
    cmd.StartInfo.CreateNoWindow = false;
    //avoid this unless you must control the app via stdin
    //cmd.StartInfo.RedirectStandardInput = true;
    cmd.Start();
}

Then write something that calls it after working out where the script is. For example if you have your directory structure as:

RLauncherCSharpApp.exe
rscripts\ui.R
rscripts\global.R
rscripts\batchTrigger.R

Then in c# you can:

//take exe Path, remove exe name and add rscripts folder and batchtrigger.R file name
var rbt = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "rscripts", "batchTrigger.R");

StartSilentR(rbt);

Or, say you want to search all the subfolders of the app's folder looking for all files called batchTrigger.R:

var exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string[] paths = Directory.GetFiles(exeFolder, "batchTrigger.R", SearchOption.AllDirectories);

//maybe add them to a list view and the user can click one to launch ..


问:
Using postgres triggers to update tag counts efficiently
I have a schema where users have tags associated with them:

```<code>user_id: int4    tags: text[]
-------------    ------------
1                [ 'apple', 'carrot', 'jelly' ]
2                [ 'jelly', 'zebra' ]
</code>```

I am looking to create query that returns the list of all tags along with their associated counts. Example:

```<code>tag: text      count: int4
---------      -----------
'apple'        1
'carrot'       1
'jelly'        2
'zebra'        1
</code>```

Triggers seem to be the ideal way to do this, since the application is read-heavy and write-light.

However, I am having difficulty implementing this. The trigger itself seems simple enough I think:

```<code>CREATE TRIGGER tags_count_update
AFTER UPDATE OF tags ON person
FOR EACH ROW
EXECUTE PROCEDURE trigger_update_tags_count();
</code>```

The trigger_update_tags_count is the part I'm having trouble with, because it seems to be a highly complex operation. For example, if  the tag doesn't already exist in the tags table then it should be inserted with a count of 1.

Also, I believe you need to do some sort of diff operation, because if someone's tags are updated from [ 'apple', 'carrot', 'jelly' ] to [ 'apple', 'dogs' ] then apple's count doesn't change, carrot and jelly is decremented by 1, and dogs is created with its count set to 1. This is compounded with the fact that tags are arrays. I currently have something like this:

```<code>CREATE OR REPLACE FUNCTION public.trigger_update_tags_count()
  RETURNS trigger
  LANGUAGE plpgsql
AS $function$
BEGIN
   INSERT INTO tags (tag, count) VALUES (new.tag, 1)
   ON CONFLICT (tag) DO UPDATE
   SET count = CASE WHEN (tag.new AND NOT tag.old) THEN count + 1
                    WHEN (tag.old AND NOT tag.new) THEN count - 1
                    ELSE count
               END
   RETURN NEW;
END;
$function$;
</code>```

Which is slightly pseudocode because I'm not sure how to integrate the fact that I'm dealing with text arrays, nor how to handle the diffing case.

答:
I am unsure that you do need a trigger a complex logic for that. You can get the output that you want with a simple query that leverages Postgres' array function unnest():

```<code>select x.tag, count(*)
from mytable t
cross join lateral unnest(t.tags) x(tag)
group by x.tag
</code>```

Note that if you find yourself repeatedly running such query, it is an indication that your design does not really fit your use case; you might be better off storing each user_id/tag tuple in a separate table row, separated from the tables where users are stored.

Body:
I have a schema where users have tags associated with them:

user_id: int4    tags: text[]
-------------    ------------
1                [ 'apple', 'carrot', 'jelly' ]
2                [ 'jelly', 'zebra' ]

I am looking to create query that returns the list of all tags along with their associated counts. Example:

tag: text      count: int4
---------      -----------
'apple'        1
'carrot'       1
'jelly'        2
'zebra'        1

Triggers seem to be the ideal way to do this, since the application is read-heavy and write-light.

However, I am having difficulty implementing this. The trigger itself seems simple enough I think:

CREATE TRIGGER tags_count_update
AFTER UPDATE OF tags ON person
FOR EACH ROW
EXECUTE PROCEDURE trigger_update_tags_count();

The trigger_update_tags_count is the part I'm having trouble with, because it seems to be a highly complex operation. For example, if  the tag doesn't already exist in the tags table then it should be inserted with a count of 1.

Also, I believe you need to do some sort of diff operation, because if someone's tags are updated from [ 'apple', 'carrot', 'jelly' ] to [ 'apple', 'dogs' ] then apple's count doesn't change, carrot and jelly is decremented by 1, and dogs is created with its count set to 1. This is compounded with the fact that tags are arrays. I currently have something like this:

CREATE OR REPLACE FUNCTION public.trigger_update_tags_count()
  RETURNS trigger
  LANGUAGE plpgsql
AS $function$
BEGIN
   INSERT INTO tags (tag, count) VALUES (new.tag, 1)
   ON CONFLICT (tag) DO UPDATE
   SET count = CASE WHEN (tag.new AND NOT tag.old) THEN count + 1
                    WHEN (tag.old AND NOT tag.new) THEN count - 1
                    ELSE count
               END
   RETURN NEW;
END;
$function$;

Which is slightly pseudocode because I'm not sure how to integrate the fact that I'm dealing with text arrays, nor how to handle the diffing case.

Body:
I am unsure that you do need a trigger a complex logic for that. You can get the output that you want with a simple query that leverages Postgres' array function unnest():

select x.tag, count(*)
from mytable t
cross join lateral unnest(t.tags) x(tag)
group by x.tag

Note that if you find yourself repeatedly running such query, it is an indication that your design does not really fit your use case; you might be better off storing each user_id/tag tuple in a separate table row, separated from the tables where users are stored.


问:
Asymptotic Notation: Proving Big Omega, O, and Theta
I have a few asymptotic notation problems I do not entirely grasp.

So when proving asymptotic complexity, I understand the operations of finding a constant and the n0 term of which the notation will be true for. So, for example:

```<code>Prove 7n+4 = Ω(n)
</code>```

In such a case we would pick a constant c, such that it is lower than 7 since this regarding Big Omega. Picking 6 would result in

```<code>7n+4 >= 6n

n+4 >= 0

n = -4
</code>```

But since n0 cannot be a negative term, we pick a positive integer, so n0 = 1.

But what about a problem like this:

```<code>Prove that n^3 − 91n^2 − 7n − 14 = Ω(n^3).
</code>```

I picked 1/2 as the constant, reaching

1/2n^3 - 91n^2 - 7n -14 >= 0.

But I am unsure how to continue. Also, a problem like this, I think regarding theta:

```<code>Let g(n) = 27n^2 + 18n and let f(n) = 0.5n^2 − 100. Find positive constants n0, c1 and c2 such
that c1f(n) ≤ g(n) ≤ c2f(n) for all n ≥ n0.
</code>```

In such a case am I performing two separate operations here, one big O comparison and one Big Omega comparison, so that there is a theta relationship, or tight bound? If so, how would I go about that?

答:
To show n3 − 91n2 − 7n − 14 is in Ω(n3), we need to exhibit some numbers n0 and c such that, for all n ≥ n0:

n3 − 91n2 − 7n − 14 ≥ cn3

You've chosen c = 0.5, so let's go with that. Rearranging gives:

n3 − 0.5n3 ≥ 91n2 + 7n + 14

Multiplying both sides by 2 and simplifying:

182n2 + 14n + 28 ≤ n3

For all n ≥ 1, we have:

182n2 + 14n + 28 ≤ 182n2 + 14n2 + 28n2 = 224n2

And when n ≥ 224, we have 224n2 ≤ n3. Therefore, the choice of n0 = 224 and c = 0.5 demonstrates that the original function is in Ω(n3).

Body:
I have a few asymptotic notation problems I do not entirely grasp.

So when proving asymptotic complexity, I understand the operations of finding a constant and the n0 term of which the notation will be true for. So, for example:

Prove 7n+4 = Ω(n)

In such a case we would pick a constant c, such that it is lower than 7 since this regarding Big Omega. Picking 6 would result in

7n+4 >= 6n

n+4 >= 0

n = -4

But since n0 cannot be a negative term, we pick a positive integer, so n0 = 1.

But what about a problem like this:

Prove that n^3 − 91n^2 − 7n − 14 = Ω(n^3).

I picked 1/2 as the constant, reaching

1/2n^3 - 91n^2 - 7n -14 >= 0.

But I am unsure how to continue. Also, a problem like this, I think regarding theta:

Let g(n) = 27n^2 + 18n and let f(n) = 0.5n^2 − 100. Find positive constants n0, c1 and c2 such
that c1f(n) ≤ g(n) ≤ c2f(n) for all n ≥ n0.

In such a case am I performing two separate operations here, one big O comparison and one Big Omega comparison, so that there is a theta relationship, or tight bound? If so, how would I go about that?


问:
Python quick question about comprehensions vs list comprehensions
Just wanted to ask why this(list comprehension, if I'm not mistaken):

```<code>def s(number):
    return sum([n for n in range(number) if n%3==0 or n%5==0])
s(100)
</code>```

is twice as fast(108 steps on visualize python) as this(202 steps):

```<code>def s(number):
    return sum(n for n in range(number) if n%3==0 or n%5==0)
s(100)
</code>```

?

And also, although the first code is faster, does the second code have any advantages in any cases? Maybe, uses less memory? Just spitballing, don''t really have any idea what I'm talking about. Any clarification would be greatly appreciated.

答:
Performance of both of your snippets is quite similar, apparently not every step is equal. For small values of number first code (list) is slightly faster, but for larger number second code (generator) wins.

Other thing is memory usage - creating a list requires amount of memory proportional to its size, so larger number consumes more RAM. Moreover, as list grows it requires memory reallocations, which eventually triggers garbage collector (timeit() by default disables gc, mangling results).
On the other hand, generator version uses the same (minimal) amount of memory for any number.

The conclusion is that you should use generator expressions whenever possible. It's especially important when you care of memory footprint and/or you operate on large numbers. Also, this way your code is slightly shorter and cleaner (arguable).

This subject is explained in PEP 289, introducing generator expressions.

Body:
Just wanted to ask why this(list comprehension, if I'm not mistaken):

def s(number):
    return sum([n for n in range(number) if n%3==0 or n%5==0])
s(100)

is twice as fast(108 steps on visualize python) as this(202 steps):

def s(number):
    return sum(n for n in range(number) if n%3==0 or n%5==0)
s(100)

?

And also, although the first code is faster, does the second code have any advantages in any cases? Maybe, uses less memory? Just spitballing, don''t really have any idea what I'm talking about. Any clarification would be greatly appreciated.


问:
Turning numbers into one piece of string vector in R
When I use as.character(1:5), my current output is: "1" "2" "3" "4" "5". Is it possible to instead get the following desired output when we input any numeric vector such as 1:5?

Desired output:

"1 2 3 4 5"

答:
We can use paste with collapse argument.  It will coerce numeric to character and gives a single string as output

```<code>paste(1:5, collapse=' ')
#[1] "1 2 3 4 5"
</code>```

Body:
We can use paste with collapse argument.  It will coerce numeric to character and gives a single string as output

paste(1:5, collapse=' ')
#[1] "1 2 3 4 5"


问:
Checking which object called the other's object method
Let's say I have two classes:

```<code>class TV
{
   ...
   void TV_chnl_change(int channel_number);
   ...
};

class Remote
{
   ...

   void remote_chnl_change(int channel_number, TV *T)
   {
      T->TV_chnl_change(channel_number);
   }

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

Both showed methods are public, what I want to do is to implement TV_chnl_change method such that it can check whether it was called by object from Remote class. Is there any way in cpp to obtain the pointer to the calling object or at least check its class without passing any additional parameters?
I don't want any object other than Remote and let's say some arbitrary Viewer object to be able to use TV_chnl_change method. What I want to do is to omit using friend mechanism.

答: Why do you have a public method which you need to restrict access to? You should assign it as private and write an interface for it.</p>

Body:
Let's say I have two classes:

class TV
{
   ...
   void TV_chnl_change(int channel_number);
   ...
};

class Remote
{
   ...

   void remote_chnl_change(int channel_number, TV *T)
   {
      T->TV_chnl_change(channel_number);
   }

   ...
};

Both showed methods are public, what I want to do is to implement TV_chnl_change method such that it can check whether it was called by object from Remote class. Is there any way in cpp to obtain the pointer to the calling object or at least check its class without passing any additional parameters?
I don't want any object other than Remote and let's say some arbitrary Viewer object to be able to use TV_chnl_change method. What I want to do is to omit using friend mechanism.


问:
Code Runner using MSVC create a too long string
I use CodeRunner for VSCode on Windows, so I need to change g++ to MSVC (Visual C++ Compiler).
So I configure settings.json for coderunner:

```<code>{
    "window.zoomLevel": 0,
    "code-runner.runInTerminal": true,
    "terminal.integrated.shell.windows": "cmd.exe",
    "code-runner.executorMap": {
        "cpp": "vcvars64.bat && cl.exe $fileName && del $fileNameWithoutExt.obj && cls && $fileNameWithoutExt.exe",
    },
    "files.autoSave": "afterDelay"
}
</code>```

As you can see, I add path of vcvars64.bat to system PATH.
It works, but after several runs I get next error:

Input line is too long.

I search for it and found that it is because CodeRunner run vcvars64.bat every time! So after several runs total path become too long:

"Input line is too long" error in BAT File

Restarting console clear it, but after several runs falls again.

Looks like I need to find some way to use vcvars64.bat only once but I don't know how!

答:
This is my setting.json

```<code>"code-runner.executorMap": {
    "cpp": "cd $dir && cl /EHsc $fileName && cls && $dir$fileNameWithoutExt.exe && del
  $dir$fileNameWithoutExt.obj $dir$fileNameWithoutExt.exe",
},
</code>```

And it's working as expected.

Body:
I use CodeRunner for VSCode on Windows, so I need to change g++ to MSVC (Visual C++ Compiler).
So I configure settings.json for coderunner:

{
    "window.zoomLevel": 0,
    "code-runner.runInTerminal": true,
    "terminal.integrated.shell.windows": "cmd.exe",
    "code-runner.executorMap": {
        "cpp": "vcvars64.bat && cl.exe $fileName && del $fileNameWithoutExt.obj && cls && $fileNameWithoutExt.exe",
    },
    "files.autoSave": "afterDelay"
}

As you can see, I add path of vcvars64.bat to system PATH.
It works, but after several runs I get next error:

Input line is too long.

I search for it and found that it is because CodeRunner run vcvars64.bat every time! So after several runs total path become too long:

"Input line is too long" error in BAT File

Restarting console clear it, but after several runs falls again.

Looks like I need to find some way to use vcvars64.bat only once but I don't know how!

Body:
This is my setting.json

"code-runner.executorMap": {
    "cpp": "cd $dir && cl /EHsc $fileName && cls && $dir$fileNameWithoutExt.exe && del
  $dir$fileNameWithoutExt.obj $dir$fileNameWithoutExt.exe",
},

And it's working as expected.


问:
syntax error when using forward slash to define positional only arguments
I'm following the python tutorial here.

I'm trying to define a function with positional only arguments and I get a invalid syntax error

I've tried both the command line interpreter and putting the definition into a file

My definition looks like this

def pos_only(x,/):
    return x**2
```

<p>I get the usual syntax error</p>

```  File "bas.py", line 1
    def pos_ony(x,/):
                  ^
SyntaxError: invalid syntax
```

Using * to define a keyword argument only function works just fine.

答:
Please read the documentation of Python3.7 https://docs.python.org/3.7/tutorial/controlflow.html

What you said is for new release from Python3.8.

Body:
I'm following the python tutorial here.

I'm trying to define a function with positional only arguments and I get a invalid syntax error

I've tried both the command line interpreter and putting the definition into a file

My definition looks like this

def pos_only(x,/):
    return x**2

I get the usual syntax error

  File "bas.py", line 1
    def pos_ony(x,/):
                  ^
SyntaxError: invalid syntax

Using * to define a keyword argument only function works just fine.


问:
Kotlin map with function reference of a member function
Given the following two classes:

```<code>class Parent {
    val child : Child = Child()
}

class Child {
    fun doSomethingWithParent(parent : Parent) = Foo()
}

class Foo
</code>```

And a list of Parents:

```<code>val list = List<Parent>(10){_ -> Parent()}
</code>```

Instead of mapping with

```<code>list.map { it.child.doSomethingWithParent(it) } // works
</code>```

to use a function reference to doSomethingWithParent like

```<code>// does not work
list.map(Child::doSomethingWithParent)
list.map(Parent::child::doSomethingWithParent)
</code>```

答:
You can't do this

map requires transform: (T) -> R (≈ KFunction1<T,R>) function

Child::doSomethingWithParent is KFunction2<Child, Parent, Foo> (≈ f: (Child, Parent) -> Foo). It's method reference therefore it requires an object on which the function will be invoked (Child parameter)

You can do something like this:

```<code>class Parent {
    val child: Child = Child()

    fun foo() = child.doSomethingWithParent(this)
}

val l1 = list.map(Parent::foo)
</code>```

Body:
Given the following two classes:

class Parent {
    val child : Child = Child()
}

class Child {
    fun doSomethingWithParent(parent : Parent) = Foo()
}

class Foo

And a list of Parents:

val list = List<Parent>(10){_ -> Parent()}

Instead of mapping with

list.map { it.child.doSomethingWithParent(it) } // works

to use a function reference to doSomethingWithParent like

// does not work
list.map(Child::doSomethingWithParent)
list.map(Parent::child::doSomethingWithParent)

Body:
You can't do this

map requires transform: (T) -> R (≈ KFunction1<T,R>) function

Child::doSomethingWithParent is KFunction2<Child, Parent, Foo> (≈ f: (Child, Parent) -> Foo). It's method reference therefore it requires an object on which the function will be invoked (Child parameter)

You can do something like this:

class Parent {
    val child: Child = Child()

    fun foo() = child.doSomethingWithParent(this)
}

val l1 = list.map(Parent::foo)


问:
using sinonjs to test a function that calls new on a dependency
I'm terribly confused and would love some help.

I don't think this code is poorly designed, but correct me if you see a flaw.

I can't seem to figure out how to test a function that calls new on a dependency.  Here are my boiled down classes....with irrelevant business logic stripped.

MyWrapper.js

```<code>const SomeLib = require('SomeLib');

module.exports.MyWrapper = class MyWrapper {
    constructor(username, password) {
        this._someLib = new SomeLib(username, password);
    }

    async getFoo(id) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.findById(id)
    }

    async saveFoo(object) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.save(object)
    }
}
</code>```

MyApp.js

```<code>const MyWrapper = require('MyWrapper');

const process = async (message) => {
    const wrapper = new MyWrapper(process.env.username, process.env.password)
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }
</code>```

MyApp.spec.js

```<code>const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        it('should call save when data is found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return some JSON
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was called
        });
    });
});
</code>```

答:
from looking at your code with the way it is currently structured, you won't be able to not call new MyWrapper because that call is made inside the function that you are calling. What you likely would want to do is use dependency injection to pass in an instance of MyWrapper. Using DI would also allow you to pass in a mocked version of your Wrapper class for more control over testing. This would look something like this:

```<code>// MyApp.js

const MyWrapper = require('MyWrapper');

const wrapper = new MyWrapper(process.env.username, process.env.password);

const process = async (message, wrapper) => {
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }
</code>```

You may want to instantiate the wrapper somewhere else that makes sense for your application, but based on the code you have presented this would now allow you to pass in your own test version of the Wrapper class when testing, like so:

```<code>// MyApp.spec.js

const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             const wrapper = new MyWrapper();
             await sut.process(msg, wrapper);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        ...
});
</code>```

the second part of your question involves creating a stub of a class using sinon. The documentation for sinon, found here, is probably going to give you the best example of how to make a stub and return your own value from the stubbed class.

Hope this helps!

Body:
I'm terribly confused and would love some help.

I don't think this code is poorly designed, but correct me if you see a flaw.

I can't seem to figure out how to test a function that calls new on a dependency.  Here are my boiled down classes....with irrelevant business logic stripped.

MyWrapper.js

const SomeLib = require('SomeLib');

module.exports.MyWrapper = class MyWrapper {
    constructor(username, password) {
        this._someLib = new SomeLib(username, password);
    }

    async getFoo(id) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.findById(id)
    }

    async saveFoo(object) {
        // other business logic omitted
        // which was tested in the MyWrapper.spec.js
        return this._someLib.save(object)
    }
}

MyApp.js

const MyWrapper = require('MyWrapper');

const process = async (message) => {
    const wrapper = new MyWrapper(process.env.username, process.env.password)
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }

MyApp.spec.js

const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        it('should call save when data is found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return some JSON
             const msg = {......};
             await sut.process(msg);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was called
        });
    });
});

Body:
from looking at your code with the way it is currently structured, you won't be able to not call new MyWrapper because that call is made inside the function that you are calling. What you likely would want to do is use dependency injection to pass in an instance of MyWrapper. Using DI would also allow you to pass in a mocked version of your Wrapper class for more control over testing. This would look something like this:

// MyApp.js

const MyWrapper = require('MyWrapper');

const wrapper = new MyWrapper(process.env.username, process.env.password);

const process = async (message, wrapper) => {
    // some business logic around the message...omitted
    const data = wrapper.getFoo(message.id);
    if(data) {
       // do stuff with the data
       wrapper.saveFoo(data);
    } else {
       console.log('no data found for message', message);
    }
}
module.exports = { process }

You may want to instantiate the wrapper somewhere else that makes sense for your application, but based on the code you have presented this would now allow you to pass in your own test version of the Wrapper class when testing, like so:

// MyApp.spec.js

const sut = require('MyApp');

describe('MyApp', function(){
    describe('process', function(){
        it('should not call save when no data found', async function(){
             // how do I prevent 'new MyWrapper(process.env.username, process.env.password)' from being called???
             // how do I stub "wrapper.getFoo(message.id)" so I can return "undefined"
             const msg = {......};
             const wrapper = new MyWrapper();
             await sut.process(msg, wrapper);
             // now assert wrapper.getFoo was called
             // now assert wrapper.saveFoo was *NOT* called
        });

        ...
});

the second part of your question involves creating a stub of a class using sinon. The documentation for sinon, found here, is probably going to give you the best example of how to make a stub and return your own value from the stubbed class.

Hope this helps!


问:
How to assign new coordinates into a multiindex in xarray
I am trying to assign new coordinates to a xarray DataArray's multiIndex.

I have a dataArray which contains 2 main dimensions ('longitude', 'latitude), and a single multiindex ('states').

Here is the DataArray structe:

```<code>print(dataArray)

<xarray.DataArray (longitude: 5000, latitude: 3000)>
array([[nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
  * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
  * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
    states     (latitude, longitude) float64 nan nan nan nan ... nan nan nan nan
</code>```

The 'states' multiindex contains solely interger values, and I would like to convert them, or add a second multiIndex with "named coordinates" (i.e.: USA, Italy, Germany, Brazil...).

Once with a named "states" multiindex, one could easily select a given state by its proper name - from the available index.

Below is a reproducible script. It has been taken from here :

```<code>import pandas as pd
pd.set_option('display.width', 50000)
pd.set_option('display.max_rows', 50000)
pd.set_option('display.max_columns', 5000)
import geopandas
from rasterio import features
from affine import Affine
import numpy as np
import xarray as xr
from cartopy.io import shapereader

def transform_from_latlon(lat, lon):
    lat = np.asarray(lat)
    lon = np.asarray(lon)
    trans = Affine.translation(lon[0], lat[0])
    scale = Affine.scale(lon[1] - lon[0], lat[1] - lat[0])
    return trans * scale

def rasterize(shapes, coords, fill=np.nan, **kwargs):
    """Rasterize a list of (geometry, fill_value) tuples onto the given
    xray coordinates. This only works for 1d latitude and longitude
    arrays.
    """
    transform = transform_from_latlon(coords['latitude'], coords['longitude'])
    out_shape = (len(coords['latitude']), len(coords['longitude']))
    raster = features.rasterize(shapes, out_shape=out_shape,
                                fill=fill, transform=transform,
                                dtype=float, **kwargs)
    return xr.DataArray(raster, coords=coords, dims=('latitude', 'longitude'))

if '__main__' == __name__:

    # this shapefile is from natural earth data
    # http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-1-states-provinces/

    resolution = '10m'
    category = 'cultural'
    name = 'admin_0_countries'

    shpfilename = shapereader.natural_earth(resolution, category, name)

    # read the shapefile using geopandas
    states = geopandas.read_file(shpfilename)

    South_America = states[states['SUBREGION'] == 'South America'].reset_index(drop=True)

    state_ids = {k: i for i, k in enumerate(South_America['NAME_LONG'])}
    shapes = [(shape, n) for n, shape in enumerate(South_America.geometry)]

    LONGITUDE = np.linspace(-145, -15, num=5000)
    LATITUDE = np.linspace(-85, 25, num=3000)

    ds = xr.DataArray(coords=(LONGITUDE, LATITUDE), dims=['longitude', 'latitude'])

    ds['states'] = rasterize(shapes, ds.coords)

    # trying to assign new coordinates to the dimension:

    try:
        ds = ds.assign_coords(states = South_America['NAME_LONG'])
    except ValueError:
        print("message error", "cannot add coordinates with new dimensions to a DataArray")

    # ds = ds.expand_dims({'names':South_America['NAME_LONG']})  # --> this does not work

    Array = np.random.randn(LATITUDE.size, LONGITUDE.size)

    dArray_Brazil = xr.DataArray(Array, coords=(LATITUDE, LONGITUDE), dims=['latitude', 'longitude'])

    import matplotlib.pyplot as plt
    quadmash = dArray_Brazil.plot()
    ax = ds.states.where(ds.states != 'Brazil').plot(ax=quadmash.axes)

    plt.show()
</code>```

ideally, I would like to have a DataArray structure as one of the two options below:

option 1)

```<code><xarray.DataArray (longitude: 5000, latitude: 3000)>
array([[nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
  * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
  * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
    states     (latitude, longitude) string Brazil, USA Germany ...
</code>```

option 2)

```<code> <xarray.DataArray (longitude: 5000, latitude: 3000)>
    array([[nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           ...,
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan]])
    Coordinates:
      * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
      * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
        states     (latitude, longitude) float64 nan nan nan nan ... nan nan nan nan
        Named_states     (latitude, longitude) string Brazil, USA Germany ...
</code>```

答:
Here's one way to replace coordinate values:

```<code>temp = 15 + 8 * np.random.randn(2, 2, 3)
precip = 10 * np.random.rand(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]
states = [[1,2],[3,2]]

ds = xr.Dataset({'temperature': (['x', 'y', 'time'],  temp),
        'precipitation': (['x', 'y', 'time'], precip)},
        coords={'lon': (['x', 'y'], lon),
        'lat': (['x', 'y'], lat),
        'time': pd.date_range('2014-09-06', periods=3),
        'states': (['x','y'], states)})

ds
</code>```

```<code><xarray.Dataset>
Dimensions:        (time: 3, x: 2, y: 2)
Coordinates:
    lon            (x, y) float64 -99.83 -99.32 -99.79 -99.23
    lat            (x, y) float64 42.25 42.21 42.63 42.59
  * time           (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
    states         (x, y) int64 1 2 3 2
Dimensions without coordinates: x, y
Data variables:
    temperature    (x, y, time) float64 1.096 19.28 16.27 ... 19.25 20.38 4.981
    precipitation  (x, y, time) float64 9.09 7.486 2.288 ... 3.639 0.6625 8.19
</code>```

```<code>transdict = {'1':'Brazil', '2':'Germany', '3':'USA'} # need dictionary for all mappings
ds.states.values = ds.states.astype(str)

for key, value in transdict.items():
    ds.states.values = np.where(ds.states.values == key, value, ds.states.values)
    ds
</code>```

```<code><xarray.Dataset>
Dimensions:        (time: 3, x: 2, y: 2)
Coordinates:
    lon            (x, y) float64 -99.83 -99.32 -99.79 -99.23
    lat            (x, y) float64 42.25 42.21 42.63 42.59
  * time           (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
    states         (x, y) <U21 'Brazil' 'Germany' 'USA' 'Germany'
Dimensions without coordinates: x, y
Data variables:
    temperature    (x, y, time) float64 1.096 19.28 16.27 ... 19.25 20.38 4.981
    precipitation  (x, y, time) float64 9.09 7.486 2.288 ... 3.639 0.6625 8.19
</code>```

Body:
I am trying to assign new coordinates to a xarray DataArray's multiIndex.

I have a dataArray which contains 2 main dimensions ('longitude', 'latitude), and a single multiindex ('states').

Here is the DataArray structe:

print(dataArray)

<xarray.DataArray (longitude: 5000, latitude: 3000)>
array([[nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
  * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
  * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
    states     (latitude, longitude) float64 nan nan nan nan ... nan nan nan nan

The 'states' multiindex contains solely interger values, and I would like to convert them, or add a second multiIndex with "named coordinates" (i.e.: USA, Italy, Germany, Brazil...).

Once with a named "states" multiindex, one could easily select a given state by its proper name - from the available index.

Below is a reproducible script. It has been taken from here :

import pandas as pd
pd.set_option('display.width', 50000)
pd.set_option('display.max_rows', 50000)
pd.set_option('display.max_columns', 5000)
import geopandas
from rasterio import features
from affine import Affine
import numpy as np
import xarray as xr
from cartopy.io import shapereader

def transform_from_latlon(lat, lon):
    lat = np.asarray(lat)
    lon = np.asarray(lon)
    trans = Affine.translation(lon[0], lat[0])
    scale = Affine.scale(lon[1] - lon[0], lat[1] - lat[0])
    return trans * scale

def rasterize(shapes, coords, fill=np.nan, **kwargs):
    """Rasterize a list of (geometry, fill_value) tuples onto the given
    xray coordinates. This only works for 1d latitude and longitude
    arrays.
    """
    transform = transform_from_latlon(coords['latitude'], coords['longitude'])
    out_shape = (len(coords['latitude']), len(coords['longitude']))
    raster = features.rasterize(shapes, out_shape=out_shape,
                                fill=fill, transform=transform,
                                dtype=float, **kwargs)
    return xr.DataArray(raster, coords=coords, dims=('latitude', 'longitude'))

if '__main__' == __name__:

    # this shapefile is from natural earth data
    # http://www.naturalearthdata.com/downloads/10m-cultural-vectors/10m-admin-1-states-provinces/

    resolution = '10m'
    category = 'cultural'
    name = 'admin_0_countries'

    shpfilename = shapereader.natural_earth(resolution, category, name)

    # read the shapefile using geopandas
    states = geopandas.read_file(shpfilename)

    South_America = states[states['SUBREGION'] == 'South America'].reset_index(drop=True)

    state_ids = {k: i for i, k in enumerate(South_America['NAME_LONG'])}
    shapes = [(shape, n) for n, shape in enumerate(South_America.geometry)]

    LONGITUDE = np.linspace(-145, -15, num=5000)
    LATITUDE = np.linspace(-85, 25, num=3000)

    ds = xr.DataArray(coords=(LONGITUDE, LATITUDE), dims=['longitude', 'latitude'])

    ds['states'] = rasterize(shapes, ds.coords)

    # trying to assign new coordinates to the dimension:

    try:
        ds = ds.assign_coords(states = South_America['NAME_LONG'])
    except ValueError:
        print("message error", "cannot add coordinates with new dimensions to a DataArray")

    # ds = ds.expand_dims({'names':South_America['NAME_LONG']})  # --> this does not work

    Array = np.random.randn(LATITUDE.size, LONGITUDE.size)

    dArray_Brazil = xr.DataArray(Array, coords=(LATITUDE, LONGITUDE), dims=['latitude', 'longitude'])

    import matplotlib.pyplot as plt
    quadmash = dArray_Brazil.plot()
    ax = ds.states.where(ds.states != 'Brazil').plot(ax=quadmash.axes)

    plt.show()

ideally, I would like to have a DataArray structure as one of the two options below:

option 1)

<xarray.DataArray (longitude: 5000, latitude: 3000)>
array([[nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       ...,
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan],
       [nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
  * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
  * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
    states     (latitude, longitude) string Brazil, USA Germany ...

option 2)

 <xarray.DataArray (longitude: 5000, latitude: 3000)>
    array([[nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           ...,
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan],
           [nan, nan, nan, ..., nan, nan, nan]])
    Coordinates:
      * longitude  (longitude) float64 -145.0 -145.0 -144.9 ... -15.05 -15.03 -15.0
      * latitude   (latitude) float64 -85.0 -84.96 -84.93 ... 24.93 24.96 25.0
        states     (latitude, longitude) float64 nan nan nan nan ... nan nan nan nan
        Named_states     (latitude, longitude) string Brazil, USA Germany ...

Body:
Here's one way to replace coordinate values:

temp = 15 + 8 * np.random.randn(2, 2, 3)
precip = 10 * np.random.rand(2, 2, 3)
lon = [[-99.83, -99.32], [-99.79, -99.23]]
lat = [[42.25, 42.21], [42.63, 42.59]]
states = [[1,2],[3,2]]

ds = xr.Dataset({'temperature': (['x', 'y', 'time'],  temp),
        'precipitation': (['x', 'y', 'time'], precip)},
        coords={'lon': (['x', 'y'], lon),
        'lat': (['x', 'y'], lat),
        'time': pd.date_range('2014-09-06', periods=3),
        'states': (['x','y'], states)})

ds

<xarray.Dataset>
Dimensions:        (time: 3, x: 2, y: 2)
Coordinates:
    lon            (x, y) float64 -99.83 -99.32 -99.79 -99.23
    lat            (x, y) float64 42.25 42.21 42.63 42.59
  * time           (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
    states         (x, y) int64 1 2 3 2
Dimensions without coordinates: x, y
Data variables:
    temperature    (x, y, time) float64 1.096 19.28 16.27 ... 19.25 20.38 4.981
    precipitation  (x, y, time) float64 9.09 7.486 2.288 ... 3.639 0.6625 8.19

transdict = {'1':'Brazil', '2':'Germany', '3':'USA'} # need dictionary for all mappings
ds.states.values = ds.states.astype(str)

for key, value in transdict.items():
    ds.states.values = np.where(ds.states.values == key, value, ds.states.values)
    ds

<xarray.Dataset>
Dimensions:        (time: 3, x: 2, y: 2)
Coordinates:
    lon            (x, y) float64 -99.83 -99.32 -99.79 -99.23
    lat            (x, y) float64 42.25 42.21 42.63 42.59
  * time           (time) datetime64[ns] 2014-09-06 2014-09-07 2014-09-08
    states         (x, y) <U21 'Brazil' 'Germany' 'USA' 'Germany'
Dimensions without coordinates: x, y
Data variables:
    temperature    (x, y, time) float64 1.096 19.28 16.27 ... 19.25 20.38 4.981
    precipitation  (x, y, time) float64 9.09 7.486 2.288 ... 3.639 0.6625 8.19


答:
You have nothing called tag in the data; it is tags.  So you need to UNNEST() and to handle both old and new tags.  I'm thinking something like:

```<code>INSERT INTO tags (tag, count)
   SELECT COALESCE(ntag, otag),
          (ntag IS NOT NULL)::int - (otag IS NOT NULL)::int
   FROM UNNEST(new.tags) ntag FULL JOIN
        UNNEST(old.tags) otag
        ON ntag = otag
ON CONFLICT (tag) DO UPDATE
   SET count = count + (excluded.ntag IS NOT NULL)::int - (excluded.otag IS NOT NULL)::int
</code>```

Title: Using postgres triggers to update tag counts efficiently

Body:
You have nothing called tag in the data; it is tags.  So you need to UNNEST() and to handle both old and new tags.  I'm thinking something like:

INSERT INTO tags (tag, count)
   SELECT COALESCE(ntag, otag),
          (ntag IS NOT NULL)::int - (otag IS NOT NULL)::int
   FROM UNNEST(new.tags) ntag FULL JOIN
        UNNEST(old.tags) otag
        ON ntag = otag
ON CONFLICT (tag) DO UPDATE
   SET count = count + (excluded.ntag IS NOT NULL)::int - (excluded.otag IS NOT NULL)::int