问:
How to get all classname from previous element's NodeList?
I want to add some event listener to every button which placed after some block of element. This button intended to return all element classes from previous block of element if clicked.

I found the script to get classes from NodeList here, https://gist.github.com/cssence/41c8279810b1db71670d.js

```<code>for (var k = 0; k < trigger.length; k++) {
  trigger[k].addEventListener('click', function(e) {
    nav.classList.toggle('hidden');
    (function listAllUsedClassNames() {
      var classNames = {};
      Array.prototype.forEach.call(this.previousElementSibling.querySelectorAll("*"), function(element) {
        if (typeof element.className === "string") {
          element.className.split(" ").forEach(function(className) {
            if (className) {
              classNames[className] = true;
            }
          });
        };
      });
      return Object.keys(classNames);
    }());
  }, false);
}
</code>```

I want some array contains all classes of previous block returned after the button clicked. It would be better if the result is unique and doesn't have any duplicated item.

答:
To get the previous Element, use previousElementSibling. Iterate over the childNodes to get the classes of element using classList.

let classes = [];
document.querySelectorAll('button')
  .forEach(button => {
    button.addEventListener('click', function() {
      classes = [];
      const prev = this.previousElementSibling;
      classes.push(...prev.classList);
      prev.childNodes.forEach(child => {
        if(child.nodeType == 3) return; // Ignore text node
        classes.push(...child.classList);
      })
      console.log(classes);
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">
  <p class="childOfFirst">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Repudiandae totam dicta libero vero dolore aperiam consectetur. Non veritatis quo praesentium!</p>
</div>
<button>Button1</button>
<div class="second">
  <p class="childOfSecond">Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur, hic.</p>
</div>
<button>Button2</button></code>```

For multiple nesting, use recursion

let classes = [];

document.querySelectorAll('button')
    .forEach(button => {
        button.addEventListener('click', function() {
            classes = [];
            const prev = this.previousElementSibling;
            if(prev.children.length > 0) {
                const output = getNestedClasses([...prev.children]);
                classes.push(...prev.classList, ...output);
                console.log('With Duplicates', classes);
                const uniqueClassList = removeDuplicateClasses(classes)
                console.log('Without Duplicates', uniqueClassList);
            }
        });
    });

function getNestedClasses(childrens) {
    return childrens.reduce((accu, ele) => {
        if(ele.children.length > 0) {
            accu.push(...ele.classList);
            return accu.concat(getNestedClasses([...ele.children]));
        } else {
            return accu.concat([...ele.classList]);
        }
    }, []);
}

function removeDuplicateClasses(classArr) {
    return Object.keys(classArr.reduce((accu, name) => {
        accu[name] += (accu[name] || 0);
        return accu;
    }, {}));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">
    <p class="firstChild">First Child
        <span class="firstGrandChild">First Grand Child</span>
        <span class="secondGrandChild">Second Grand Child</span>
    </p>
    <p class="secondChild duplicate">Second Child</p>
    <p class="duplicate"></p>
    <p class="thirdChild">Third Child</p>
</div>
<button>Button1</button></code>```

Body:
I want to add some event listener to every button which placed after some block of element. This button intended to return all element classes from previous block of element if clicked.

I found the script to get classes from NodeList here, https://gist.github.com/cssence/41c8279810b1db71670d.js

for (var k = 0; k < trigger.length; k++) {
  trigger[k].addEventListener('click', function(e) {
    nav.classList.toggle('hidden');
    (function listAllUsedClassNames() {
      var classNames = {};
      Array.prototype.forEach.call(this.previousElementSibling.querySelectorAll("*"), function(element) {
        if (typeof element.className === "string") {
          element.className.split(" ").forEach(function(className) {
            if (className) {
              classNames[className] = true;
            }
          });
        };
      });
      return Object.keys(classNames);
    }());
  }, false);
}

I want some array contains all classes of previous block returned after the button clicked. It would be better if the result is unique and doesn't have any duplicated item.

Body:
To get the previous Element, use previousElementSibling. Iterate over the childNodes to get the classes of element using classList.

let classes = [];
document.querySelectorAll('button')
  .forEach(button => {
    button.addEventListener('click', function() {
      classes = [];
      const prev = this.previousElementSibling;
      classes.push(...prev.classList);
      prev.childNodes.forEach(child => {
        if(child.nodeType == 3) return; // Ignore text node
        classes.push(...child.classList);
      })
      console.log(classes);
    });
  });

<div class="first">
  <p class="childOfFirst">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Repudiandae totam dicta libero vero dolore aperiam consectetur. Non veritatis quo praesentium!</p>
</div>
<button>Button1</button>
<div class="second">
  <p class="childOfSecond">Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur, hic.</p>
</div>
<button>Button2</button>

For multiple nesting, use recursion

let classes = [];

document.querySelectorAll('button')
    .forEach(button => {
        button.addEventListener('click', function() {
            classes = [];
            const prev = this.previousElementSibling;
            if(prev.children.length > 0) {
                const output = getNestedClasses([...prev.children]);
                classes.push(...prev.classList, ...output);
                console.log('With Duplicates', classes);
                const uniqueClassList = removeDuplicateClasses(classes)
                console.log('Without Duplicates', uniqueClassList);
            }
        });
    });

function getNestedClasses(childrens) {
    return childrens.reduce((accu, ele) => {
        if(ele.children.length > 0) {
            accu.push(...ele.classList);
            return accu.concat(getNestedClasses([...ele.children]));
        } else {
            return accu.concat([...ele.classList]);
        }
    }, []);
}

function removeDuplicateClasses(classArr) {
    return Object.keys(classArr.reduce((accu, name) => {
        accu[name] += (accu[name] || 0);
        return accu;
    }, {}));
}

<div class="first">
    <p class="firstChild">First Child
        <span class="firstGrandChild">First Grand Child</span>
        <span class="secondGrandChild">Second Grand Child</span>
    </p>
    <p class="secondChild duplicate">Second Child</p>
    <p class="duplicate"></p>
    <p class="thirdChild">Third Child</p>
</div>
<button>Button1</button>


来源: stackexchange

问:
Self-Hosted Wcf Service with Certificate client authentication
I have a self-hosted wcf service which uses wsHttpBinding with Transport security. I want the service to authenticate a client using a certificate.

When the client communicates with the service using clientCredentialsType set to 'None' everything works fine.
The certificate was created with OpenSSL (self-signed) and registered with netsh on a specific port. The name of the certificate is DomainName (machine name in my case).

Update

I have created certificates for both client and server and placed them in each others Trusted Root stores (server certificate in client's store and vice-versa).

I've gone over a lot of articles and other questions at SOF but even the ones that look relevant couldn't help me resolve the issue.

Current Configuration

Service

```<code><system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" httpsHelpPageEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="httpsBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="01:00:00">
          <security mode="Transport" >
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="serviceBehavior" name="Service">
        <endpoint binding="wsHttpBinding" bindingConfiguration="httpsBinding" contract="SomeNamespace.IService"/>
        <host>
          <baseAddresses>
            <add baseAddress="https://domain:port/Something/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</code>```

Client

```<code><system.serviceModel>
    <client>
      <endpoint address="https://domain:port/Something/"
                behaviorConfiguration="endpointCredentialBehavior"
                binding="wsHttpBinding"
                bindingConfiguration="Binding"
                contract="SomeNamespace.IService"/>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="endpointCredentialBehavior">
          <clientCredentials>
            <clientCertificate findValue="DomainName"
                               storeLocation="LocalMachine"
                               storeName="My"
                               x509FindType="FindBySubjectName" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding">
          <security mode="Transport">
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>
</code>```

I get the following exception:

System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
     at System.Net.HttpWebRequest.GetResponse()
     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

答:
There is one more thing we need to do. We should make their certificate trusted by each other. the server’s certificate must be trusted by the client and the client’s certificate must be trusted by the server.

Specifically, the server certificate is installed in the client Trusted Root Certification Authorities, the client certificate is installed in the server Trusted Root Certificate Authorities. It is best to use a local machine certificate store. We could check the certificate by using Certlm.msc command.

Please refer to the official document with regards to this issue.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/transport-security-with-certificate-authentication

For some special certificates created by other special tools, such as PowerShell, we had better make the target framework of the project (server and client) above 4.6.2.

https://github.com/dotnet/docs/issues/12000

Feel free to let me know if there is anything I can help with.

ContentLicense: CC BY-SA 4.0

Body:
I have a self-hosted wcf service which uses wsHttpBinding with Transport security. I want the service to authenticate a client using a certificate.

When the client communicates with the service using clientCredentialsType set to 'None' everything works fine.
The certificate was created with OpenSSL (self-signed) and registered with netsh on a specific port. The name of the certificate is DomainName (machine name in my case).

Update

I have created certificates for both client and server and placed them in each others Trusted Root stores (server certificate in client's store and vice-versa).

I've gone over a lot of articles and other questions at SOF but even the ones that look relevant couldn't help me resolve the issue.

Current Configuration

Service

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceMetadata httpsGetEnabled="true" httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="true" httpsHelpPageEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="httpsBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="01:00:00">
          <security mode="Transport" >
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="serviceBehavior" name="Service">
        <endpoint binding="wsHttpBinding" bindingConfiguration="httpsBinding" contract="SomeNamespace.IService"/>
        <host>
          <baseAddresses>
            <add baseAddress="https://domain:port/Something/"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

Client

<system.serviceModel>
    <client>
      <endpoint address="https://domain:port/Something/"
                behaviorConfiguration="endpointCredentialBehavior"
                binding="wsHttpBinding"
                bindingConfiguration="Binding"
                contract="SomeNamespace.IService"/>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="endpointCredentialBehavior">
          <clientCredentials>
            <clientCertificate findValue="DomainName"
                               storeLocation="LocalMachine"
                               storeName="My"
                               x509FindType="FindBySubjectName" />
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding">
          <security mode="Transport">
            <transport clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>

I get the following exception:

System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
     at System.Net.HttpWebRequest.GetResponse()
     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)


问:
How to create a shape with a hole in QML?
I want to create a kind of masking layer which consists of a black area with holes in it. Through the holes it should be possible to see the background. In the simplest version I it's just an rectangle covering the whole screen with an opening in the middle. As shown in the sample picture below.

My first approach was to use QML's Context2D feature: https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).

```<code>Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
        ctx.fill();
    }
</code>```

答:
I found the solution myself by rereading the Qt docs. There is a function to create transparent rectangles inside a given canvas which is called "clearRect(...)": https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clearRect-method

```<code>Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, 1000, 600);
        ctx.fill();

        ctx.clearRect(10, 10, 600, 100)

    }
</code>```

For more advanced shapes OpacityMask suggested by Frank Osterfeld is definitely the way to solve this. But for rectangle I think my solution is more straight forward.

Body:
I want to create a kind of masking layer which consists of a black area with holes in it. Through the holes it should be possible to see the background. In the simplest version I it's just an rectangle covering the whole screen with an opening in the middle. As shown in the sample picture below.

My first approach was to use QML's Context2D feature: https://doc.qt.io/qt-5/qml-qtquick-context2d.html. Maybe it's totally wrong to do it this way, but maybe it's a good starting point. I tried to create an rectangle (which works) and a clipping area (which doesn't work). Besides the fact my implementation of the clipping doesn't work I would have the problem that the clip() command erases the area outside its path but not inside (at least that's what I understood from the docs: https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clip-method).

Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, Sizes.rootWindow.width, Sizes.rootWindow.height);
        ctx.fill();
    }

Body:
I found the solution myself by rereading the Qt docs. There is a function to create transparent rectangles inside a given canvas which is called "clearRect(...)": https://doc.qt.io/qt-5/qml-qtquick-context2d.html#clearRect-method

Canvas {

    anchors.fill: parent

    onPaint: {
        var ctx = getContext("2d");
        ctx.fillStyle = "black"

        ctx.beginPath();
        ctx.fillRect(0, 0, 1000, 600);
        ctx.fill();

        ctx.clearRect(10, 10, 600, 100)

    }

For more advanced shapes OpacityMask suggested by Frank Osterfeld is definitely the way to solve this. But for rectangle I think my solution is more straight forward.


问:
How to prevent wix custom bootstrapper Uninstallation UI from showing in the upgrade process
I have a custom bootstrapper application installer which has been worked well with the normal features such as install, uninstall and so on. But now I need to add a upgrade feature for the installer exactly for the bundle, but it always shows the installation UI or uninstallation UI during the installation process of newer bundle installer. I know the old version should be removed during this process but I expect the previous version is removed before the newer version installed and the uninstallation process should be in silence mode.

I am new be with Wix, but I have read lots of articles in StackOverflow, and tried most of the related solutions. Such as the following links:

How do I detect the currently installed features during a MajorUpgrade using WiX Burn MBA Bundles?

How to perform Wix Upgrade with custom bootstrapper

Wix doesn't remove previous version of burn exe during major upgrade

WiX burn Upgrade shows uninstall UI at the end

Unfortunately None of them work for me. I don't know the call stacks of the burn engine well, so I post my code to here!

In my code, I have tried the following solutions:

```<code>private void DetectComplete(object sender, DetectCompleteEventArgs e)
{
    if (LaunchAction.Uninstall == WixBA.Model.Command.Action)
    {
    WixBA.Model.Engine.Log(LogLevel.Verbose, "Invoking automatic plan for uninstall");
    WixBA.Plan(LaunchAction.Uninstall);
    }
}

private void BootstrapperApplication_ApplyComplete(object sender, ApplyCompleteEventArgs e)
{
    if (this.model.BootstrapperApplication.Command.Action == LaunchAction.Uninstall && isRelatedBundlePresent) // this will be called in case of Upgrade of the bundle
    {
            CustomBootstrapperApplication.Dispatcher.InvokeShutdown();
    }
}
</code>```

If anyone could help me to review my code, that would be appreciate. When you have downloaded my code, please change the MsiVersion parameter with a version number and change the ProjectRootDir paramter to be your local path of solution file in the "ccnetcall-build-language-package.bat" file in "Build" folder, and then create the different versions of the installers by launching the bat file.

Thanks in advance!

答:
The BootstrapperApplication.Command struct contains the display field that your BA should respect when deciding to display UI (or not).

During the upgrade of the old version the value should be Display.Embedded or Display.None (I forget which off the top of my head).

Body:
I have a custom bootstrapper application installer which has been worked well with the normal features such as install, uninstall and so on. But now I need to add a upgrade feature for the installer exactly for the bundle, but it always shows the installation UI or uninstallation UI during the installation process of newer bundle installer. I know the old version should be removed during this process but I expect the previous version is removed before the newer version installed and the uninstallation process should be in silence mode.

I am new be with Wix, but I have read lots of articles in StackOverflow, and tried most of the related solutions. Such as the following links:

How do I detect the currently installed features during a MajorUpgrade using WiX Burn MBA Bundles?

How to perform Wix Upgrade with custom bootstrapper

Wix doesn't remove previous version of burn exe during major upgrade

WiX burn Upgrade shows uninstall UI at the end

Unfortunately None of them work for me. I don't know the call stacks of the burn engine well, so I post my code to here!

In my code, I have tried the following solutions:

private void DetectComplete(object sender, DetectCompleteEventArgs e)
{
    if (LaunchAction.Uninstall == WixBA.Model.Command.Action)
    {
    WixBA.Model.Engine.Log(LogLevel.Verbose, "Invoking automatic plan for uninstall");
    WixBA.Plan(LaunchAction.Uninstall);
    }
}

private void BootstrapperApplication_ApplyComplete(object sender, ApplyCompleteEventArgs e)
{
    if (this.model.BootstrapperApplication.Command.Action == LaunchAction.Uninstall && isRelatedBundlePresent) // this will be called in case of Upgrade of the bundle
    {
            CustomBootstrapperApplication.Dispatcher.InvokeShutdown();
    }
}

If anyone could help me to review my code, that would be appreciate. When you have downloaded my code, please change the MsiVersion parameter with a version number and change the ProjectRootDir paramter to be your local path of solution file in the "ccnetcall-build-language-package.bat" file in "Build" folder, and then create the different versions of the installers by launching the bat file.

Thanks in advance!


问:
Angular Renderer2 can't add class
addClass method of Renderer doesn't work in case element has class with binding

Some HTML

```

<p>Inside <code>addClassDir</code></p>

<pre class="lang-js prettyprint-override"><code>ngOnInit() {
    this.renderer.addClass(this.elementRef.nativeElement, 'new-class');
}
</code>```

I know that class="my-class-{{smth}}" is a not Angular way, but I don't know how people use my directive. It should work anyway, but it doesn't. What is the most correct way to do it?

答:
There are few correct ways to do that. It depends on what you want achieve.

HostBinding directive
https://angular.io/api/core/HostBinding

```<code>export class MyComponent {
  @HostBinding('class.valid') get valid() { return this.control.valid; }
  @HostBinding('class.my-class') myClass = true;
  @HostBinding('class') class = 'box';
}
</code>```

NgClass https://angular.io/api/common/NgClass

```<code><some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
</code>```

Attribute binding

```<code><div [class.active]="isActive">
  ...
</div>
</code>```

Title: Angular Renderer2 can't add class

Body:
addClass method of Renderer doesn't work in case element has class with binding

Some HTML

Inside addClassDir

ngOnInit() {
    this.renderer.addClass(this.elementRef.nativeElement, 'new-class');
}

I know that class="my-class-{{smth}}" is a not Angular way, but I don't know how people use my directive. It should work anyway, but it doesn't. What is the most correct way to do it?

Body:
There are few correct ways to do that. It depends on what you want achieve.

HostBinding directive
https://angular.io/api/core/HostBinding

export class MyComponent {
  @HostBinding('class.valid') get valid() { return this.control.valid; }
  @HostBinding('class.my-class') myClass = true;
  @HostBinding('class') class = 'box';
}

NgClass https://angular.io/api/common/NgClass

<some-element [ngClass]="'first second'">...</some-element>

<some-element [ngClass]="['first', 'second']">...</some-element>

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

Attribute binding

<div [class.active]="isActive">
  ...
</div>


问:
Can Azure Cognitive Services work with local model?
I want to use Cognitive Services to translate some text, and we can train our custom models, I want to know is there any possible to host models on local server?</p>

答:
It sounds like you want to deploy your custom trained model of Azure Cognitive Service on an on-promise datacenter. As I known, Azure Stack supports Azure capabilities available on-premises, but its features do not include Azure Cognitive Services by now, as refer to Azure Stack key capabilities. Meanwhile, the model of Custom Translator is not public, just used on cloud, and can not be exported as a general format like ONNX. So may you need to contact with Azure offical sales to ask for your needs and how to buy.

Hope it helps.


问:
How to determine a server WebSocket url when the address is unknown at build time?
Although I'm relatively new to web sockets, my development environment's Angular-7 client and node/express development server are communicating using WebSockets quite successfully.

The problem is that, in deployment, the actual server will be running on a portable instrument which itself can reside at any Manual IP address on any customer's network.

There are numerous examples of using Angular with WebSockets. All of them use known IP addresses. The techniques I'm folowing are quite simple. The basic WebSocket creation code is shown below:

websocket.service.ts

```<code> constructor() {
    this.socket$ = new WebSocketSubject(environment.wsUrl);
    this.subscription$ = this.socket$
      .subscribe(
      (message) => this.processWebSocketMessage(message),
      (err) => console.error(err),
      () => console.warn('Connection closed')
    );
  }
</code>```

environment.ts

export const environment = {
  production: false,
  wsUrl: 'ws://localhost:8999'
};
```

My problem is that I have found no examples of what the wsUrl property value should be for a production build (environment.prod.ts) for a server whose IP address is unknown at build time.

I strongly suspect I'm missing something very simple here. Should I be determining the server IP address dynamically? All suggestions welcome.

答:
Following deeper research and testing against multiple browsers. I have settled on the following solution. The browser already "knows" the address of the server. The only additional part is to supply the correct port based on the current environment.

websocket.service.ts

   this.socket$ = new WebSocketSubject(
     'ws://' + window.location.hostname + ':' + environment.wsPort
   );
```

<p><strong>environment.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export const environment = {
  production: false,
  wsPort: 8999
};
</code>```

environment.prod.ts

export const environment = {
  production: true,
  wsPort: 8080
};
```

Body:
Although I'm relatively new to web sockets, my development environment's Angular-7 client and node/express development server are communicating using WebSockets quite successfully.

The problem is that, in deployment, the actual server will be running on a portable instrument which itself can reside at any Manual IP address on any customer's network.

There are numerous examples of using Angular with WebSockets. All of them use known IP addresses. The techniques I'm folowing are quite simple. The basic WebSocket creation code is shown below:

websocket.service.ts

 constructor() {
    this.socket$ = new WebSocketSubject(environment.wsUrl);
    this.subscription$ = this.socket$
      .subscribe(
      (message) => this.processWebSocketMessage(message),
      (err) => console.error(err),
      () => console.warn('Connection closed')
    );
  }

environment.ts

export const environment = {
  production: false,
  wsUrl: 'ws://localhost:8999'
};

My problem is that I have found no examples of what the wsUrl property value should be for a production build (environment.prod.ts) for a server whose IP address is unknown at build time.

I strongly suspect I'm missing something very simple here. Should I be determining the server IP address dynamically? All suggestions welcome.

Body:
Following deeper research and testing against multiple browsers. I have settled on the following solution. The browser already "knows" the address of the server. The only additional part is to supply the correct port based on the current environment.

websocket.service.ts

   this.socket$ = new WebSocketSubject(
     'ws://' + window.location.hostname + ':' + environment.wsPort
   );

environment.ts

export const environment = {
  production: false,
  wsPort: 8999
};

environment.prod.ts

export const environment = {
  production: true,
  wsPort: 8080
};


问:
JointJS Dependency Management Issue
I'm using JointJS as a NPM package and it's working fine.  My issue is with managing its dependencies.  Right now, it created its own jquery folder inside its own node_modules folder.  It's using that jQuery but I have jQuery as a "top level" folder next to JointJS inside my top level node_modules folder.
How do I make JointJS use the top level jQuery so I can delete the jquery folder inside JointJS?</p>

```<code>ProjectFolder
    node_modules
        jointjs
            node_modules
                jquery (want to delete)
        jquery
</code>```

答:
The short version is to run npm dedupe after you've done your npm install

This will scan your dependency tree and lift/point the nested dependencies to dependencies that sit at the top level your dependency tree where it can.

I say "where it can" because being able to do this will require that the version of jQuery defined in your package.json meets the restrictions of the jQuery version defined in JointJS's package.json. As an example, the v2.2.1 of JointJS requires jQuery 3.3.1 . If your version of jQuery deviates from this at all, npm dedupe will not remove the nested jQuery dependency.

Also remember that other packages you have in your application may have their own versions of jQuery which may also interact with what jQuery ends up in your top level.

In some cases, the jQuery in JointJS will remain nested because it has to remain nested to fulfil all the dependencies and restrictions of your application.

This blog post was immensely useful in helping me understand how npm's dependency resolution works, and why dedupe is needed.

Title: JointJS Dependency Management Issue

Body:
I'm using JointJS as a NPM package and it's working fine.  My issue is with managing its dependencies.  Right now, it created its own jquery folder inside its own node_modules folder.  It's using that jQuery but I have jQuery as a "top level" folder next to JointJS inside my top level node_modules folder.
How do I make JointJS use the top level jQuery so I can delete the jquery folder inside JointJS?

ProjectFolder
    node_modules
        jointjs
            node_modules
                jquery (want to delete)
        jquery


Title: Plotting a histogram using a range of values and their frequency as a dictionary

Body:
Assume that I have the following dictionary:

scenario_summary = {'Day1': {'22459-22585': 0.0, '22585-22711': 0.0, '22711-22837': 0.0, '22837-22963': 0.0, '22963-23089': 0.0, '23089-23215': 0.0, '23215-23341': 0.0, '23341-23467': 0.0, '23467-23593': 0.0, '23593-23719': 0.0, '23719-23845': 0.0, '23845-23971': 0.0, '23971-24097': 0.0, '24097-24223': 0.0, '24223-24349': 0.0, '24349-24475': 0.0, '24475-24601': 0.0, '24601-24727': 0.0, '24727-24853': 0.0, '24853-24979': 0.0, '24979-25105': 0.0, '25105-25231': 0.0, '25231-25357': 0.0, '25357-25483': 0.0, '25483-25609': 0.0, '25609-25735': 0.0, '25735-25861': 0.0, '25861-25987': 0.0, '25987-26113': 1.0, '26113-26239': 1.0, '26239-26365': 0.0, '26365-26491': 2.0, '26491-26617': 5.0, '26617-26743': 5.0, '26743-26869': 5.0, '26869-26995': 12.0, '26995-27121': 19.0, '27121-27247': 7.000000000000001, '27247-27373': 11.0, '27373-27499': 15.0, '27499-27625': 7.000000000000001, '27625-27751': 4.0, '27751-27877': 4.0, '27877-28003': 2.0, '28003-28129': 0.0, '28129-28255': 0.0, '28255-28381': 0.0, '28381-28507': 0.0, '28507-28633': 0.0, '28633-28759': 0.0, '28759-28885': 0.0, '28885-29011': 0.0, '29011-29137': 0.0, '29137-29263': 0.0, '29263-29389': 0.0, '29389-29515': 0.0, '29515-29641': 0.0, '29641-29767': 0.0, '29767-29893': 0.0, '29893-30019': 0.0, '30019-30145': 0.0, '30145-30271': 0.0, '30271-30397': 0.0, '30397-30523': 0.0, '30523-30649': 0.0, '30649-30775': 0.0, '30775-30901': 0.0, '30901-31027': 0.0, '31027-31153': 0.0, '31153-31279': 0.0, '31279-31405': 0.0, '31405-31531': 0.0, '31531-31657': 0.0, '31657-31783': 0.0, '31783-31909': 0.0, '31909-32035': 0.0, '32035-32161': 0.0, '32161-32287': 0.0, '32287-32413': 0.0, '32413-32539': 0.0, '32539-32665': 0.0, '32665-32791': 0.0, '32791-32917': 0.0, '32917-33043': 0.0, '33043-33169': 0.0, '33169-33295': 0.0, '33295-33421': 0.0, '33421-33547': 0.0, '33547-33673': 0.0, '33673-33799': 0.0, '33799-33925': 0.0, '33925-34051': 0.0, '34051-34177': 0.0, '34177-34303': 0.0, '34303-34429': 0.0, '34429-34555': 0.0, '34555-34681': 0.0, '34681-34807': 0.0}}

As you can see, the dictionary consists of a range of values in string and their frequency. I would like to plot this as a histogram, but I don't know how I would be able to transform the string into a form that pandas or plotly would understand. What would your approach be? Or is there an easier way to do it, instead of hardcoding things? Or, would another module be easier option in doing so?

Thanks!

Body:
You can use pandas module to convert dictionary data into data frame:

import pandas as pd
import matplotlib.pyplot as plt

scenario_summary = {'Day1': {'22459-22585': 0.0, '22585-22711': 0.0, '22711-22837': 0.0,
                         '22837-22963': 0.0, '22963-23089': 0.0, '23089-23215': 0.0,
                         '23215-23341': 0.0, '23341-23467': 0.0, '23467-23593': 0.0,
                         '23593-23719': 0.0, '23719-23845': 0.0, '23845-23971': 0.0,
                         '23971-24097': 0.0, '24097-24223': 0.0, '24223-24349': 0.0,
                         '24349-24475': 0.0, '24475-24601': 0.0, '24601-24727': 0.0,
                         '24727-24853': 0.0, '24853-24979': 0.0, '24979-25105': 0.0,
                         '25105-25231': 0.0, '25231-25357': 0.0, '25357-25483': 0.0,
                         '25483-25609': 0.0, '25609-25735': 0.0, '25735-25861': 0.0,
                         '25861-25987': 0.0, '25987-26113': 1.0, '26113-26239': 1.0,
                         '26239-26365': 0.0, '26365-26491': 2.0, '26491-26617': 5.0,
                         '26617-26743': 5.0, '26743-26869': 5.0, '26869-26995': 12.0,
                         '26995-27121': 19.0, '27121-27247': 7.000000000000001, '27247-27373': 11.0,
                         '27373-27499': 15.0, '27499-27625': 7.000000000000001, '27625-27751': 4.0,
                         '27751-27877': 4.0, '27877-28003': 2.0, '28003-28129': 0.0,
                         '28129-28255': 0.0, '28255-28381': 0.0, '28381-28507': 0.0,
                         '28507-28633': 0.0, '28633-28759': 0.0, '28759-28885': 0.0,
                         '28885-29011': 0.0, '29011-29137': 0.0, '29137-29263': 0.0,
                         '29263-29389': 0.0, '29389-29515': 0.0, '29515-29641': 0.0,
                         '29641-29767': 0.0, '29767-29893': 0.0, '29893-30019': 0.0,
                         '30019-30145': 0.0, '30145-30271': 0.0, '30271-30397': 0.0,
                         '30397-30523': 0.0, '30523-30649': 0.0, '30649-30775': 0.0,
                         '30775-30901': 0.0, '30901-31027': 0.0, '31027-31153': 0.0,
                         '31153-31279': 0.0, '31279-31405': 0.0, '31405-31531': 0.0,
                         '31531-31657': 0.0, '31657-31783': 0.0, '31783-31909': 0.0,
                         '31909-32035': 0.0, '32035-32161': 0.0, '32161-32287': 0.0,
                         '32287-32413': 0.0, '32413-32539': 0.0, '32539-32665': 0.0,
                         '32665-32791': 0.0, '32791-32917': 0.0, '32917-33043': 0.0,
                         '33043-33169': 0.0, '33169-33295': 0.0, '33295-33421': 0.0,
                         '33421-33547': 0.0, '33547-33673': 0.0, '33673-33799': 0.0,
                         '33799-33925': 0.0, '33925-34051': 0.0, '34051-34177': 0.0,
                         '34177-34303': 0.0, '34303-34429': 0.0, '34429-34555': 0.0,
                         '34555-34681': 0.0, '34681-34807': 0.0}}

# convert to data frame
data_frame = pd.DataFrame.from_dict(scenario_summary)

# plot data
plt.hist(data_frame['Day1'], density=1, bins=20)
plt.show()


问:
How to sum columns without using Loop in VBA
I am trying to reformat a report so it can feed into my system like below:

```<code>wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value
</code>```

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

```<code>wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value
</code>```

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?

答:
You already have two good answers, just want to add my 2 cents here...

If you have lots of data, you should consider using arrays, and one way of doing what you are trying to achieve can be the below, please see comments for further details:

Dim wsOutput As Worksheet: Set wsOutput = wbOutput.Sheets(1) 'allocate the output worksheet to a variable
Dim wsSource As Worksheet: Set wsSource = wbSource.Sheets(1) 'allocate the source worksheet to a variable

Dim arrSource As Variant
Dim arrOutput() As Variant 'Could change this to match your expected data type output
Dim R As Long, C As Long
arrSource = wsSource.Range("N1:O" & lRow) 'Get the source data into an array
ReDim arrOutput(1 To UBound(arrSource), 1 To 1) 'set the size of the output
For R = 1 To UBound(arrSource)
    For C = 1 To UBound(arrSource, 2)
        arrOutput(R, 1) = arrSource(R, 1) + arrSource(R, 2) 'make your calculations here
    Next C
Next R

wsOutput.Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow) = arrOutput 'spit it back to the sheet once is done
```

Body:
I am trying to reformat a report so it can feed into my system like below:

wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?


问:
How to update user data in MongoDB using node.js
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

```<code>    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});
</code>```

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

```<code>router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});
</code>```

答:
Use this simple case is better.</p>

```<code>data=user.find({ id: req.session.passport.user})
user.update({id:data.id},{name: req.body.name,email: req.body.email,password: req.body.password},
(err,user)=>{
//handle error
});
</code>```

Body:
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});

Body:
Use this simple case is better.

data=user.find({ id: req.session.passport.user})
user.update({id:data.id},{name: req.body.name,email: req.body.email,password: req.body.password},
(err,user)=>{
//handle error
});


问:
find similar rows in a text file in unix system
I have a file named tt.txt and the contents of this file is as follows:

```<code>fdgs
jhds
fdgs
</code>```

I am trying to get the similar row as the output in a text file.

my expected output is:

```<code>fdgs
fdgs
</code>```

to do so, I used this command:

```<code>uniq -u tt.txt > output.txt
</code>```

but it returns:

```<code>fdgs
jhds
fdgs
</code>```

do you know how to fix it?

答:
One in awk:</p>

```<code>$ awk '++seen[$0]==2;seen[$0]>1' file
fdgs
fdgs
</code>```

Body:
I have a file named tt.txt and the contents of this file is as follows:

fdgs
jhds
fdgs

I am trying to get the similar row as the output in a text file.

my expected output is:

fdgs
fdgs

to do so, I used this command:

uniq -u tt.txt > output.txt

but it returns:

fdgs
jhds
fdgs

do you know how to fix it?

Body:
One in awk:

$ awk '++seen[$0]==2;seen[$0]>1' file
fdgs
fdgs


问:
JQuery Datatable Buttons not working/ not displayed
I have created a view for a datatable (Which is called upon a modal from a link in a datatable in another view), and I intend to put buttons to export the data to Excel, PDF, Print...etc.
I have added the script, but the buttons are not displayed in the final output.

What are the library files that I want to load in order to make the code working with the results that I expect from it?

Note: I have used JQuery 3.1.1

I have tried various methods, also by changing the script library references to no avail. I even tried the download builder from datatables.net, but any of it seemed not working too.

```<code>*The html code*
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h2 class="modal-title">Item</h2>
            <h4>TRANSFER HISTORY</h4>
        </div>
        <div>
            <table id="example" class="display" style="width:100%">
                <tr style="background-color:#b5bbc8">
                    <th>
                        From
                    </th>
                    <th>
                        To
                    </th>
                    <th>
                        Date
                    </th>
                    <th>
                        Cause
                    </th>
                    <th>
                        Updated By
                    </th>
                </tr>

                @foreach (var item in Model)
            {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.Center.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Center1.Name)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.TransferDate)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.TransferCause)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.User.FirstName) @Html.DisplayFor(modelItem => item.User.LastName)
                        </td>
                    </tr>
                }
            </table>
        </div>
    </div>
</div>

*The Buttons script*
<script type="text/javascript">
    $(document).ready(function () {
        $('#example').DataTable({
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'excel', 'pdf', 'print'
            ]
        });
    });
</script>
</code>```

Update - I just found out what was missing. Actually, it was a reference in the parent view, from which this view is loaded. I fixed it, now everything works fine. Thank you all for your answers and feedback.

答:
You can implement the datatable in grid.you can add defer in JS

```<code><script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"
 type="text/javascript" defer></script>
<script
src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"
type="text/javascript"> </script>
<script
src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"
type="text/javascript"></script>

<link
href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"
rel="stylesheet"/>
<link href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css"rel="stylesheet" />
</code>```

It's working for me, I hope its help you
Please Add Alll JS and CSS in your view page

Body:
I have created a view for a datatable (Which is called upon a modal from a link in a datatable in another view), and I intend to put buttons to export the data to Excel, PDF, Print...etc.
I have added the script, but the buttons are not displayed in the final output.

What are the library files that I want to load in order to make the code working with the results that I expect from it?

Note: I have used JQuery 3.1.1

I have tried various methods, also by changing the script library references to no avail. I even tried the download builder from datatables.net, but any of it seemed not working too.

*The html code*

            <button type="button" class="btn btn-default" data-dismiss="modal">Back</button>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Item

TRANSFER HISTORY

                        From

                        To

                        Date

                        Cause

                        Updated By

                @foreach (var item in Model)
            {

                            @Html.DisplayFor(modelItem => item.Center.Name)

                            @Html.DisplayFor(modelItem => item.Center1.Name)

                            @Html.DisplayFor(modelItem => item.TransferDate)

                            @Html.DisplayFor(modelItem => item.TransferCause)

                            @Html.DisplayFor(modelItem => item.User.FirstName) @Html.DisplayFor(modelItem => item.User.LastName)

                }

*The Buttons script*

Update - I just found out what was missing. Actually, it was a reference in the parent view, from which this view is loaded. I fixed it, now everything works fine. Thank you all for your answers and feedback.

Body:
You can implement the datatable in grid.you can add defer in JS

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"
 type="text/javascript" defer></script>
<script
src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"
type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"
type="text/javascript"> </script>
<script
src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"
type="text/javascript"></script>

<link
href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"
rel="stylesheet"/>
<link href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.dataTables.min.css"rel="stylesheet" />

It's working for me, I hope its help you
Please Add Alll JS and CSS in your view page


问:
Rails puts and logger.info not working deep inside do loops
```<code>def poster
    mechanize = Mechanize.new
    Spider.start_at('http://www.cnn.com/') do |s|
      s.add_url_check do |a_url|
        a_url =~ %r{^http://www.cnn.com/*}
      end
      s.on :success do |a_url, resp|
        agent = mechanize.get("#{a_url}")
        cnnbody = resp.body
        parsedcnnbody = Nokogiri::HTML.parse(cnnbody)
        tags = parsedcnnbody.xpath("//a")
        imgs = parsedcnnbody.xpath("//img")
        headers = parsedcnnbody.css("h1")
        containers = parsedcnnbody.css(".zn__containers")
        containers.each do |container|
          container.xpath("//a").each do |link|
            Spider.start_at(link['href']) do |d|
              d.on :success do |b_url, res|
                # @org = Organization.where(title: "CNN").first_or_create!
                @parsedbody = Nokogiri::HTML.parse(res.body)
                @authorusername = @parsedbody.css(".metadata__byline__author")
                puts @authorusername
                # @author = User.where(username: @authorusername, organization_id: @org.id).first_or_create!
                @parsedtext = @parsedbody.css(".l-container").css(".l-container")
                puts @parsedtext
                # @post = Post.where(title: parsedbody.css(".pg-headline"), content: parsedtext)
</code>```

I'd like to test the output of this spider with a puts argument before I uncomment the remaining work.

But when @org is uncommented it just loops through that without displaying from puts.

答:
I usually use Rails.logger.debug '' to show the message or debug on server.

As I just checked, I can still use this to show message in a loop.

Hope this helps

Body:
def poster
    mechanize = Mechanize.new
    Spider.start_at('http://www.cnn.com/') do |s|
      s.add_url_check do |a_url|
        a_url =~ %r{^http://www.cnn.com/*}
      end
      s.on :success do |a_url, resp|
        agent = mechanize.get("#{a_url}")
        cnnbody = resp.body
        parsedcnnbody = Nokogiri::HTML.parse(cnnbody)
        tags = parsedcnnbody.xpath("//a")
        imgs = parsedcnnbody.xpath("//img")
        headers = parsedcnnbody.css("h1")
        containers = parsedcnnbody.css(".zn__containers")
        containers.each do |container|
          container.xpath("//a").each do |link|
            Spider.start_at(link['href']) do |d|
              d.on :success do |b_url, res|
                # @org = Organization.where(title: "CNN").first_or_create!
                @parsedbody = Nokogiri::HTML.parse(res.body)
                @authorusername = @parsedbody.css(".metadata__byline__author")
                puts @authorusername
                # @author = User.where(username: @authorusername, organization_id: @org.id).first_or_create!
                @parsedtext = @parsedbody.css(".l-container").css(".l-container")
                puts @parsedtext
                # @post = Post.where(title: parsedbody.css(".pg-headline"), content: parsedtext)

I'd like to test the output of this spider with a puts argument before I uncomment the remaining work.

But when @org is uncommented it just loops through that without displaying from puts.


问:
Leaflet maps not appearing in tabbed HTML document output from Rmarkdown
I've used R Markdown to create a HTML document with tabbed sections and each tab should include one Leaflet map. When I run the code, the Leaflet maps only appear in the first two tabs of the HTML document and do not appear in any of the subsequent tabs. Here's a quick summary of what I've tried:

I have tried viewing the HTML document in RStudio Viewer, Chrome, and Firefox, but all have the same results (i.e. no maps starting on the third tab). When I open the browser console, there is an error that reads, "Error: Set map center and zoom first." However, I have set map center and zoom using setView() in Leaflet.

When I run the code chunks independently in the Markdown file or in the R console, they work perfectly in generating the desired maps.

When I remove the tabbed sections from the Markdown file, all the Leaflet maps appear under their respective headings.

The order of the tabs does not matter, maps always appear on the first two tabs and do not appear on subsequent tabs (i.e. In the example, if you move east_map chunk to the beginning, there will be no map for cent_state).

I have intentionally added the full set of code to each code chunk and renamed each filtered iteration to try to ensure I wasn't missing pulling something from the global environment.

I have also tried using leafletOutput() and renderLeaflet(), but to no avail. But I don't think this is relevant as it applies more to Shiny integration.

I updated R (3.6.0), RStudio (1.2.1335), pandoc (2.7.2), and all relevant packages.

I have scoured StackOverview, but am absolutely out of ideas and would appreciate any thoughts or guidance.

In my document, I have 10 tabs, but for brevity, I have created an example below with just 3 tabs that reproduces my problem. (Also, I have cut away a lot of code from my full Markdown file to make this as straight-forward as possible, so apologies if there are some lingering packages, etc. that aren't immediately relevant.)

```<code>---
title: "REPRODUCIBLE EXAMPLE <br> April 2019"
always_allow_html: yes
output:
  html_document:
    df_print: paged
---

# {.tabset .tabset-fade}

## TAB 1

### HEADING 1

```{r natl_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

#Create factor layers by facility_type
abc_data <- dat %>%
  filter(org == "abc")

cbs_data <- dat %>%
  filter(org == "cbs")

fox_data <- dat %>%
  filter(org == "fox")

ssd_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 30.2189853, lat = 7.1751893, zoom = 7) %>%
  setMaxBounds(
    lng1 = 22.625227,
    lat1 = 1.422041,
    lng2 = 36.978083,
    lat2 = 13.528717
  )

natl_map <- ssd_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

natl_map

```

## TAB 2

### HEADING 2.1

```{r cent_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

cent_dat <- dat %>%
  filter(state == "cent")

#Create factor layers by facility_type
cent_abc_data <- cent_dat %>%
  filter(org == "abc")

cent_cbs_data <- cent_dat %>%
  filter(org == "cbs")

cent_fox_data <- cent_dat %>%
  filter(org == "fox")

cent_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 31.3222933, lat = 4.734494, zoom = 8) %>%
  setMaxBounds(
    lng1 = 32.149583,
    lat1 = 6.259701,
    lng2 = 29.753375,
    lat2 = 3.501536
  )

cent_map <- cent_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   cent_abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   cent_cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   cent_fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

cent_map

```

## TAB 3

### HEADING 3

```{r east_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

east_dat <- dat %>%
  filter(state == "east")

#Create factor layers by facility_type
east_abc_data <- east_dat %>%
  filter(org == "abc")

east_cbs_data <- east_dat %>%
  filter(org == "cbs")

east_fox_data <- east_dat %>%
  filter(org == "fox")

east_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 33.731222, lat = 5.084033, zoom = 8) %>%
  setMaxBounds(
    lng1 = 35.964000,
    lat1 = 3.556817,
    lng2 = 31.597152,
    lat2 = 5.906979
  )

east_map <- east_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   east_abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   east_cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   east_fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

east_map

```
</code>```

The expected output is an HTML document with three tabs that have one Leaflet map on each tab.

答: Thanks to some support on other forums a solution was shared here: https://github.com/rstudio/leaflet/issues/623</p>

Body:
I've used R Markdown to create a HTML document with tabbed sections and each tab should include one Leaflet map. When I run the code, the Leaflet maps only appear in the first two tabs of the HTML document and do not appear in any of the subsequent tabs. Here's a quick summary of what I've tried:

I have tried viewing the HTML document in RStudio Viewer, Chrome, and Firefox, but all have the same results (i.e. no maps starting on the third tab). When I open the browser console, there is an error that reads, "Error: Set map center and zoom first." However, I have set map center and zoom using setView() in Leaflet.

When I run the code chunks independently in the Markdown file or in the R console, they work perfectly in generating the desired maps.

When I remove the tabbed sections from the Markdown file, all the Leaflet maps appear under their respective headings.

The order of the tabs does not matter, maps always appear on the first two tabs and do not appear on subsequent tabs (i.e. In the example, if you move east_map chunk to the beginning, there will be no map for cent_state).

I have intentionally added the full set of code to each code chunk and renamed each filtered iteration to try to ensure I wasn't missing pulling something from the global environment.

I have also tried using leafletOutput() and renderLeaflet(), but to no avail. But I don't think this is relevant as it applies more to Shiny integration.

I updated R (3.6.0), RStudio (1.2.1335), pandoc (2.7.2), and all relevant packages.

I have scoured StackOverview, but am absolutely out of ideas and would appreciate any thoughts or guidance.

In my document, I have 10 tabs, but for brevity, I have created an example below with just 3 tabs that reproduces my problem. (Also, I have cut away a lot of code from my full Markdown file to make this as straight-forward as possible, so apologies if there are some lingering packages, etc. that aren't immediately relevant.)

---
title: "REPRODUCIBLE EXAMPLE
 April 2019"
always_allow_html: yes
output:
  html_document:
    df_print: paged
---

# {.tabset .tabset-fade}

## TAB 1

### HEADING 1

```{r natl_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

#Create factor layers by facility_type
abc_data <- dat %>%
  filter(org == "abc")

cbs_data <- dat %>%
  filter(org == "cbs")

fox_data <- dat %>%
  filter(org == "fox")

ssd_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 30.2189853, lat = 7.1751893, zoom = 7) %>%
  setMaxBounds(
    lng1 = 22.625227,
    lat1 = 1.422041,
    lng2 = 36.978083,
    lat2 = 13.528717
  )

natl_map <- ssd_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

natl_map

```

## TAB 2

### HEADING 2.1

```{r cent_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

cent_dat <- dat %>%
  filter(state == "cent")

#Create factor layers by facility_type
cent_abc_data <- cent_dat %>%
  filter(org == "abc")

cent_cbs_data <- cent_dat %>%
  filter(org == "cbs")

cent_fox_data <- cent_dat %>%
  filter(org == "fox")

cent_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 31.3222933, lat = 4.734494, zoom = 8) %>%
  setMaxBounds(
    lng1 = 32.149583,
    lat1 = 6.259701,
    lng2 = 29.753375,
    lat2 = 3.501536
  )

cent_map <- cent_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   cent_abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   cent_cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   cent_fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

cent_map

```

## TAB 3

### HEADING 3

```{r east_map, echo = FALSE, message=FALSE, warning=FALSE, comment=NA, out.width='100%'}
setwd()
library(tidyverse)
library(leaflet)
library(leaflet.extras)
library(htmltools)
library(htmlwidgets)
library(shiny)
library(rgdal)

dat <- tibble(
  state = c("lak", "cent", "east", "east"),
  org = c("abc", "cbs", "fox", "abc"),
  item = c("pump 1", "pump 2", "pump 3", "pump 4"),
  status = c("terrible", "poor", "good", "excellent"),
  lat = c(6.87239, 4.01313, 5.00959, 4.77239),
  lon = c(29.57524, 30.56462, 32.39547,     33.59156)
)

dat$status <- factor(dat$status, levels = c("terrible", "poor", "good", "excellent"))

#Set color pallette for by status
pal <- colorFactor(palette = c("#FF0000", "yellow", "#2cb42c", "blue"),
                   levels = levels(dat$status))

east_dat <- dat %>%
  filter(state == "east")

#Create factor layers by facility_type
east_abc_data <- east_dat %>%
  filter(org == "abc")

east_cbs_data <- east_dat %>%
  filter(org == "cbs")

east_fox_data <- east_dat %>%
  filter(org == "fox")

east_map <- leaflet() %>%
  addProviderTiles("OpenStreetMap.BlackAndWhite") %>%
  setView(lng = 33.731222, lat = 5.084033, zoom = 8) %>%
  setMaxBounds(
    lng1 = 35.964000,
    lat1 = 3.556817,
    lng2 = 31.597152,
    lat2 = 5.906979
  )

east_map <- east_map %>%
  clearMarkers() %>%
  addCircleMarkers(data =   east_abc_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "abc") %>%
  addCircleMarkers(data =   east_cbs_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "cbs") %>%
  addCircleMarkers(data =   east_fox_data,
                   color = ~pal(status),
                   radius   =   2,
                   group = "fox") %>%
  addLayersControl(overlayGroups = c("abc",
                                     "cbs",
                                     "fox")) %>%
  addLegend(position = "topright",
            pal = pal,
            title = "Status",
            values = dat$status) %>%
  addResetMapButton()

east_map

```

The expected output is an HTML document with three tabs that have one Leaflet map on each tab.


问:
HttpSession, session.getAttribute(), problem
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

```<code>Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);
</code>```

Thanks.

答: Because Register attribute may be set from some other  place (like. from jsp(in bad case),Servlet or Filter . . )

ContentLicense: CC BY-SA 3.0

Body:
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);

Thanks.


问:
If Else in Djnago Views
I'm making a LMS.
Where a User applies for a leave and the admin accepts or rejects it.
Right now I am stuck in a problem where I want the user to apply for a leave through the Django form by selecting a leave type (casual, sick, half pay etc), if the admin accepts it then the default values in the database changes or gets deducted from the Employee model and when the counter reaches 0 an error is generated that you don't have any leaves,contact the admin.

I'm unable to understand how to make the logic for it.

I tried Applying if else statement in the views and even in the models.

views.py

The function name is "Reject" as I am trying to make changes to the accept function.

def reject_leave(request, id):
    # employee_item = Employee.objects.get(id=id)
    all_item = Leave.objects.get(id=id)
    all = Employee.objects.get(id=id)
    context = {'all': all,'all_item': all_item}

'''
if the leave_type (choice field of the leaves from the django form) equals to a leave type like Annual leave

The the program deducts 1 or the amount entered from the total value of Annual leave from the Model Employee
'''

*Sorry for the poor writing I'm not experienced in Django*

***This code is saying that in an illogical way.***

 if leave_type.id is "Annual_leave":
                Annual_leave - 1
    else:
                subject = "Leave Rejected"  # email subject
                email_from = "settings.EMAIL_HOST_USER"  # email from
                to_email = ['someemail@something.com']  # email to

                with open(...) as f:
                    msgbody = f.read()
                    msg = EmailMultiAlternatives(
                    subject=subject, body=msgbody, from_email=email_from, to=to_email)
                    html_template = get_template(...).render()
                    msg.attach_alternative(html_template, "text/html")
                    msg.send()

    return render(request, 'projectfiles/rejectemail.html',context)

```

<p><strong><em>forms.py</em></strong></p>

<pre class="lang-py prettyprint-override"><code>
class Leave_Form(forms.ModelForm):
    to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    class Meta:
        model = Leave
        fields = ['leave_Type', 'description',
                  'from_date', 'to_date', 'leave_qty']
        exclude = ['employee_leaves', 'submit_date']
        leave_type_choice = (

            ("Annual_leave", "Annual leave"),
            ("Sick_leave", "Sick leave"),
            ("Casual_leave", "Casual leave"),
            ("Emergency_leave", "Emergency leave"),
            ("Half_pay","Half Pay")
    )

        widgets = {

            'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
            'description': forms.Textarea(
                attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}

</code>```

models.py

class Employee(models.Model):

    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 20)
    employee_department = models.CharField(max_length = 35)
    Annual_leave = models.PositiveSmallIntegerField(default=10)
    Sick_leave = models.PositiveSmallIntegerField(default=3)
    Casual_leave = models.PositiveSmallIntegerField(default=3)
    Half_pay = models.PositiveSmallIntegerField(default=4)
    Emergency_leave = models.PositiveSmallIntegerField(default=3)
    allowed = models.BooleanField(default=False)

    def __str__(self):
                return self.employee_name.username

    class Meta:
        verbose_name_plural = "Employee"

class Leave(models.Model):

    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)

    class Meta:
        verbose_name_plural = "Leave"

    def __str__(self):
        return self.leave_Type + "  by  " + str(self.employee_leaves)

```

When the Admin accepts (or in this case rejects) a leave.
e.g.
Sick leave I want 1 or entered amount of leaves to be deducted from the total of the allocated sick leaves.

答:
```<code>def reject_leave(request, id):  # overwriting built-in id is not a good idea
    all_item = Leave.objects.get(id=id)  # This is a single item, not all items
    all = Employee.objects.get(id=id)  # this again is a single item, not all items
    context = {'all': all, 'all_item': all_item}

    if leave_type.id is "Annual_leave":
    # What is leave_type?
        Annual_leave - 1
        # What is Annual_leave? What does -1 supposed to do?
    # Maybe you meant
    # employee = Employee.objects.get(id=id)
    # leave = employee.employee_leaves_set.last()
    # if leave.leave_Type == 'Annual_leave':
    #     employee.Annual_leave -= 1
    #     employee.save()
    else:
        subject = "Leave Rejected"
        email_from = "settings.EMAIL_HOST_USER"
        to_email = ['talhamurtaza@clickmail.info']

        with open('...') as f:
            msgbody = f.read()
            msg = EmailMultiAlternatives(
                subject=subject, body=msgbody, from_email=email_from, to=to_email)
            html_template = get_template(
                "...").render()
            msg.attach_alternative(html_template, "text/html")
            msg.send()

    return render(request, 'projectfiles/rejectemail.html', context)
</code>```

<p>There is so many things wrong with this that I can confidently say you haven't taken a python tutorial, read pep-8 nor taken a django tutorial. So please start from the first one and work your way up. </p>

Title: If Else in Djnago Views

Body:
I'm making a LMS.
Where a User applies for a leave and the admin accepts or rejects it.
Right now I am stuck in a problem where I want the user to apply for a leave through the Django form by selecting a leave type (casual, sick, half pay etc), if the admin accepts it then the default values in the database changes or gets deducted from the Employee model and when the counter reaches 0 an error is generated that you don't have any leaves,contact the admin.

I'm unable to understand how to make the logic for it.

I tried Applying if else statement in the views and even in the models.

views.py

The function name is "Reject" as I am trying to make changes to the accept function.

def reject_leave(request, id):
    # employee_item = Employee.objects.get(id=id)
    all_item = Leave.objects.get(id=id)
    all = Employee.objects.get(id=id)
    context = {'all': all,'all_item': all_item}

'''
if the leave_type (choice field of the leaves from the django form) equals to a leave type like Annual leave

The the program deducts 1 or the amount entered from the total value of Annual leave from the Model Employee
'''

*Sorry for the poor writing I'm not experienced in Django*

***This code is saying that in an illogical way.***

 if leave_type.id is "Annual_leave":
                Annual_leave - 1
    else:
                subject = "Leave Rejected"  # email subject
                email_from = "settings.EMAIL_HOST_USER"  # email from
                to_email = ['someemail@something.com']  # email to

                with open(...) as f:
                    msgbody = f.read()
                    msg = EmailMultiAlternatives(
                    subject=subject, body=msgbody, from_email=email_from, to=to_email)
                    html_template = get_template(...).render()
                    msg.attach_alternative(html_template, "text/html")
                    msg.send()

    return render(request, 'projectfiles/rejectemail.html',context)

forms.py

class Leave_Form(forms.ModelForm):
    to_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                                      'placeholder': ' Month/Date/Year'}))

    from_date = forms.DateField(
        widget=forms.DateInput(format=('%m/%d/%y'),
                               attrs={'class': 'form-control',
                               'placeholder':' Month/Date/Year'}))

    class Meta:
        model = Leave
        fields = ['leave_Type', 'description',
                  'from_date', 'to_date', 'leave_qty']
        exclude = ['employee_leaves', 'submit_date']
        leave_type_choice = (

            ("Annual_leave", "Annual leave"),
            ("Sick_leave", "Sick leave"),
            ("Casual_leave", "Casual leave"),
            ("Emergency_leave", "Emergency leave"),
            ("Half_pay","Half Pay")
    )

        widgets = {

            'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
            'description': forms.Textarea(
                attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}

models.py

class Employee(models.Model):

    employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
    employee_designation = models.CharField(max_length = 20)
    employee_department = models.CharField(max_length = 35)
    Annual_leave = models.PositiveSmallIntegerField(default=10)
    Sick_leave = models.PositiveSmallIntegerField(default=3)
    Casual_leave = models.PositiveSmallIntegerField(default=3)
    Half_pay = models.PositiveSmallIntegerField(default=4)
    Emergency_leave = models.PositiveSmallIntegerField(default=3)
    allowed = models.BooleanField(default=False)

    def __str__(self):
                return self.employee_name.username

    class Meta:
        verbose_name_plural = "Employee"

class Leave(models.Model):

    employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
    leave_Type = models.CharField(max_length=25)
    leave_qty = models.PositiveSmallIntegerField(default=0)
    description = models.CharField(max_length=75, blank=True, null=True)
    submit_date = models.DateTimeField(auto_now_add=True)
    from_date = models.DateField(auto_now=False, auto_now_add=False)
    to_date = models.DateField(auto_now=False, auto_now_add=False)

    class Meta:
        verbose_name_plural = "Leave"

    def __str__(self):
        return self.leave_Type + "  by  " + str(self.employee_leaves)

When the Admin accepts (or in this case rejects) a leave.
e.g.
Sick leave I want 1 or entered amount of leaves to be deducted from the total of the allocated sick leaves.

Body:
def reject_leave(request, id):  # overwriting built-in id is not a good idea
    all_item = Leave.objects.get(id=id)  # This is a single item, not all items
    all = Employee.objects.get(id=id)  # this again is a single item, not all items
    context = {'all': all, 'all_item': all_item}

    if leave_type.id is "Annual_leave":
    # What is leave_type?
        Annual_leave - 1
        # What is Annual_leave? What does -1 supposed to do?
    # Maybe you meant
    # employee = Employee.objects.get(id=id)
    # leave = employee.employee_leaves_set.last()
    # if leave.leave_Type == 'Annual_leave':
    #     employee.Annual_leave -= 1
    #     employee.save()
    else:
        subject = "Leave Rejected"
        email_from = "settings.EMAIL_HOST_USER"
        to_email = ['talhamurtaza@clickmail.info']

        with open('...') as f:
            msgbody = f.read()
            msg = EmailMultiAlternatives(
                subject=subject, body=msgbody, from_email=email_from, to=to_email)
            html_template = get_template(
                "...").render()
            msg.attach_alternative(html_template, "text/html")
            msg.send()

    return render(request, 'projectfiles/rejectemail.html', context)

There is so many things wrong with this that I can confidently say you haven't taken a python tutorial, read pep-8 nor taken a django tutorial. So please start from the first one and work your way up.


问:
System.Data.Common, System.Net.Http Framework vs Nuget assembly in ASP.NET Web API project
I am really confused about these two libraries that are included in the .NET Framework but are also available on Nuget. My instinct is to use the Nuget one as I would be getting more frequent updates etc. However Visual Studio even though I have referenced the one from nuget the msbuild uses one from .NET framework located at:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib
</code>```

One workaround I found on github was to remove those libraries from the msbuild folder. But anytime I update VS Studio it brings them back there. Also the nuget package introduced some binding redirects. I can't count how many times the build goes fine and then Xth build gives an error that just makes no sense in regards to those assemblies.

Do you recommend removing the nuget packages and use the ones contained in the framework?

答:
I got an answer from Jose Perez Rodriguez on Visual Studio Forum which explains it quite nicely:

Hello Jakub, and thanks for posting your question. Sorry it took us so
  long to respond. First of all, I do agree with you that this space in
  general is a bit confusing, but here is a TL;DR explanation of the
  issue. System.Net.Http and System.Data.Common packages to get updated
  more frequently, but only for the .NET Core implementation, not for
  .NET Framework which is what you are targetting. .NET Framework
  actually already has a version of these two assemblies installed in
  the GAC, but it is not the newest version (at least that is the case
  for frameworks < 4.7.2), and if your application has any dependency
  that is targeting .NET Standard 1.4+, then you will most likely need
  the very latest version of these assemblies in order for your app to
  work correctly at runtime. The latest version for .NET Framework is
  not the one in the GAC nor the one in the packages as I've said
  before, but instead the one found in the MSBuild Extensions folder
  that you found. Those versions are really the latest versions for .NET
  Framework, so when our build detects that you will need them, we
  inject them into your bin folder and we reference those in order to be
  able to not hit any runtime issues.

So all in all, the conclusion is that whichever workaround you found
  saying to delete those files from that directory is incorrect, and
  should never really be done as that may cause your app to have runtime
  issues. In order to let your app work properly, remove the binding
  redirects that were added automatically by NuGet when you installed
  the System.Net.Http and the Data.Common packages, and make sure you
  turn on AutoGenerateBindingRedirects. After taking those steps (and
  making sure that you restore that msbuild extensions folder since you
  said you deleted some files from it) your app in the end should have a
  copy of these assemblies in the bin folder with the latest version of
  them, and it should also have an app config with the right binding
  redirects generated at build time.

We will do a better job of explaining this behavior in github, since a
  lot of people are confused by this behavior. I hope this answers your
  question, but if not, please feel free to ask any follow up questions
  you may have.

Body:
I am really confused about these two libraries that are included in the .NET Framework but are also available on Nuget. My instinct is to use the Nuget one as I would be getting more frequent updates etc. However Visual Studio even though I have referenced the one from nuget the msbuild uses one from .NET framework located at:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib

One workaround I found on github was to remove those libraries from the msbuild folder. But anytime I update VS Studio it brings them back there. Also the nuget package introduced some binding redirects. I can't count how many times the build goes fine and then Xth build gives an error that just makes no sense in regards to those assemblies.

Do you recommend removing the nuget packages and use the ones contained in the framework?


问:
Backbone.View "el" confusion
How should a view's el be handled?
It has to be set, otherwise events don't fire (see here).

But should it be an element that is already on the page?
In my app, I render a (jQuery Templates) template into a Fancybox. What should the el be in that case?

答: You want your 'el' to reference an element that contains a child element that has any event that triggers a change in your view.  Could be as wide as a "body" tag.</p>

Title: Backbone.View "el" confusion


问:
Is there a way to dynamically set variables values for the post request with jmeter beanshell preprocessor
I need to dynamically build the following post request JSON body with jmeter beanshell preprocessor. I am referring to the following question which has a solution for my problem with looped strings. I would need to do this with json-property(variables) an array of JSON objects with different name and values. Thanks a lot. </p>

```<code>{
  "processDefinitionId":"optaplannerkey:1:dbc4af8f-7e04-11e9-afa3-1ecac26bb5e0",
  "businessKey":"optaplannerkey",
  "returnVariables":true,
  "variables": [
    {
      "name": "TaskDescription",
      "value": "Fixing the issue with sink"
    },
    {
      "name": "TaskCategory",
      "value": "plumbing"
    },
    {
      "name": "Priority",
      "value": "Medium"
    },
    {
      "name": "Status",
      "value": "New"
    },
    {
      "name": "SkillsRequired",
      "value": "Plumbing Skills"
    },
    {
      "name": "DueDate",
      "value": "2019-05-24T11:23:08.030+05:30"
    }
  ]
}
</code>```

答:
Use dummy sampler with the parameterized json request and CSV Data Set Config for the dynamic input. Below, I have paremeterized only two for demo.

Then, Use JSR223 Post processor with the following code:-

```<code>vars.put("responseVar",prev.getResponseDataAsString());
</code>```

This will put response body in "responseVar" variable. Fetch it using ${responseVar}

Hope this helps.

Body:
I need to dynamically build the following post request JSON body with jmeter beanshell preprocessor. I am referring to the following question which has a solution for my problem with looped strings. I would need to do this with json-property(variables) an array of JSON objects with different name and values. Thanks a lot.

{
  "processDefinitionId":"optaplannerkey:1:dbc4af8f-7e04-11e9-afa3-1ecac26bb5e0",
  "businessKey":"optaplannerkey",
  "returnVariables":true,
  "variables": [
    {
      "name": "TaskDescription",
      "value": "Fixing the issue with sink"
    },
    {
      "name": "TaskCategory",
      "value": "plumbing"
    },
    {
      "name": "Priority",
      "value": "Medium"
    },
    {
      "name": "Status",
      "value": "New"
    },
    {
      "name": "SkillsRequired",
      "value": "Plumbing Skills"
    },
    {
      "name": "DueDate",
      "value": "2019-05-24T11:23:08.030+05:30"
    }
  ]
}

Body:
Use dummy sampler with the parameterized json request and CSV Data Set Config for the dynamic input. Below, I have paremeterized only two for demo.

Then, Use JSR223 Post processor with the following code:-

vars.put("responseVar",prev.getResponseDataAsString());

This will put response body in "responseVar" variable. Fetch it using ${responseVar}

Hope this helps.