问:
How to get folder path for ClickOnce application
I need to write a file in the same folder where a console ClickOnce .application (executable file) resides. The folder where it launches from.

I tried using Application.StartupPath & Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
but the path is pointing to a subfolder under c:\Documents & Settings. How do I get the path where the .application resides in?

答:
Here's what I found that worked for being able to get the deployed folder location of my clickonce application and that hasn't been mentioned anywhere I saw in my searches, for my similar, specific scenario:

The clickonce application is deployed to a company LAN network folder.

The clickonce application is set to be available online or offline.

My clickonce installation URL and Update URLs in my project properties have nothing specified. That is, there is no separate location for installation or updates.

In my publishing options, I am having a desktop shortcut created for the clickonce application.

The folder I want to get the path for at startup is one that I want to be accessed by the DEV, INT, and PROD versions of the application, without hardcoding the path.

Here is a visual of my use case:

The blue boxed folders are my directory locations for each
environment's application.

The red boxed folder is the directory I want to get the path for
(which requires first getting the app's deployed folder location
"MyClickOnceGreatApp_1_0_0_37" which is the same as the OP).

I did not find any of the suggestions in this question or their comments to work in returning the folder that the clickonce application was deployed to (that I would then move relative to this folder to find the folder of interest). No other internet searching or related SO questions turned up an answer either.

All of the suggested properties either were failing due to the object (e.g. ActivationUri) being null, or were pointing to the local PC's cached installed app folder. Yes, I could gracefully handle null objects by a check for IsNetworkDeployed - that's not a problem - but surprisingly IsNetworkDeployed returns false even though I do in fact have a network deployed folder location for the clickonce application. This is because the application is running from the local, cached bits.

The solution is to look at:

AppDomain.CurrentDomain.BaseDirectory when the application is being run within visual studio as I develop and

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation when it is executing normally.

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation correctly returns the network directory that my clickonce application is deployed to, in all cases. That is, when it is launched via:

setup.exe

MyClickOnceGreatApp.application

The desktop shortcut created upon first install and launch of the application.

Here's the code I use at application startup to get the path of the WorkAccounts folder. Getting the deployed application folder is simple by just not marching up to parent directories:

```<code>string directoryOfInterest = "";
if (System.Diagnostics.Debugger.IsAttached)
{
    directoryOfInterest = Directory.GetParent(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName).FullName;
}
else
{
    try
    {
        string path = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
        path = path.Replace("file:", "");
        path = path.Replace("/", "\\");
        directoryOfInterest = Directory.GetParent(Directory.GetParent(path).FullName).FullName;
    }
    catch (Exception ex)
    {
        directoryOfInterest = "Error getting update directory needed for relative base for finding WorkAccounts directory.\n" + ex.Message + "\n\nUpdate location directory is: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
    }
}
</code>```

Body:
Here's what I found that worked for being able to get the deployed folder location of my clickonce application and that hasn't been mentioned anywhere I saw in my searches, for my similar, specific scenario:

The clickonce application is deployed to a company LAN network folder.

The clickonce application is set to be available online or offline.

My clickonce installation URL and Update URLs in my project properties have nothing specified. That is, there is no separate location for installation or updates.

In my publishing options, I am having a desktop shortcut created for the clickonce application.

The folder I want to get the path for at startup is one that I want to be accessed by the DEV, INT, and PROD versions of the application, without hardcoding the path.

Here is a visual of my use case:

The blue boxed folders are my directory locations for each
environment's application.

The red boxed folder is the directory I want to get the path for
(which requires first getting the app's deployed folder location
"MyClickOnceGreatApp_1_0_0_37" which is the same as the OP).

I did not find any of the suggestions in this question or their comments to work in returning the folder that the clickonce application was deployed to (that I would then move relative to this folder to find the folder of interest). No other internet searching or related SO questions turned up an answer either.

All of the suggested properties either were failing due to the object (e.g. ActivationUri) being null, or were pointing to the local PC's cached installed app folder. Yes, I could gracefully handle null objects by a check for IsNetworkDeployed - that's not a problem - but surprisingly IsNetworkDeployed returns false even though I do in fact have a network deployed folder location for the clickonce application. This is because the application is running from the local, cached bits.

The solution is to look at:

AppDomain.CurrentDomain.BaseDirectory when the application is being run within visual studio as I develop and

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation when it is executing normally.

System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation correctly returns the network directory that my clickonce application is deployed to, in all cases. That is, when it is launched via:

setup.exe

MyClickOnceGreatApp.application

The desktop shortcut created upon first install and launch of the application.

Here's the code I use at application startup to get the path of the WorkAccounts folder. Getting the deployed application folder is simple by just not marching up to parent directories:

string directoryOfInterest = "";
if (System.Diagnostics.Debugger.IsAttached)
{
    directoryOfInterest = Directory.GetParent(Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName).FullName;
}
else
{
    try
    {
        string path = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
        path = path.Replace("file:", "");
        path = path.Replace("/", "\\");
        directoryOfInterest = Directory.GetParent(Directory.GetParent(path).FullName).FullName;
    }
    catch (Exception ex)
    {
        directoryOfInterest = "Error getting update directory needed for relative base for finding WorkAccounts directory.\n" + ex.Message + "\n\nUpdate location directory is: " + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();
    }
}


来源: stackexchange

问:
iOS app, is there a way to subscribe to an event when an app is updated through AppStore?
I need to cleanup some properties stored in NSUserDefaults for iOS app when it is updated to new version.

Is there a way to be notified when such an app update is going to happen or has happened?

Also is my assumption correct that when application is updated, NSUserDefaults are not automatically cleaned?

答:
The UserDefaults are not modified on an app-update. What you are essentially asking is how to implement versioning for your data. The most basic way to do this is by using a version value in your app and add it to your UserDefaults.

Sample flow on app start:

You have defined a version of "1.0" in your code and a "Version" key

On app start, UserDefaults is accessed and your "Version" key is checked to see if a value exists for it.

If a value exists and it is equal to the version defined above, that means the app has already been launched with this version previously so no work needs to be done.

If a value exists but it is not equal (this will happen for future versions) to the version defined above or no value exists at all, you can perform your cleanup since this is the first time you have launched this version.

Lastly, update the value in UserDefaults to the current version.

ContentLicense: CC BY-SA 3.0


问:
Resizing Div vertically when view port is resized
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body></code>```

答:
If I understood you correctly you are looking for something that behaves like this. You would have to

set height: 100% to html and body and your div

make your div overflow: auto.

Code snippet just simulates height resize. See fiddle for actual demo.

$('#button').click(function(){
  $('#b').append('First wrapper
');
});

$('#reset').click(function(){
  $('#b').empty();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height: 100%;
  background: green;
  padding: 0;
  margin: 0;
}
body {
  padding: 20px;
  box-sizing: border-box;
}

#a {
  height: 100%;
  background: red;
  overflow: auto;
  padding: 50px;
  box-sizing: border-box;
}</code>```

  <button id="button">add more content to simulate browser height</button>
  <button id="reset">reset</button>

    First wrapper

    First wrapper

```

Body:
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}

 System Dashboard

          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper

 Copyright here

Body:
If I understood you correctly you are looking for something that behaves like this. You would have to

set height: 100% to html and body and your div

make your div overflow: auto.

Code snippet just simulates height resize. See fiddle for actual demo.

$('#button').click(function(){
  $('#b').append('First wrapper<br />');
});

$('#reset').click(function(){
  $('#b').empty();
});

html, body {
  height: 100%;
  background: green;
  padding: 0;
  margin: 0;
}
body {
  padding: 20px;
  box-sizing: border-box;
}

#a {
  height: 100%;
  background: red;
  overflow: auto;
  padding: 50px;
  box-sizing: border-box;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="a">
  <button id="button">add more content to simulate browser height</button>
  <button id="reset">reset</button> <br>
  <div id='b'>
    First wrapper<br />
    First wrapper<br />
  </div>
</div>


问:
How can I group/sum values in LINQ to XML?
I've been trying to work thru this but I am having problems grouping the data.
I have an XML structure

```<code><FILE>
    <PLAN>
      <PLAN_ID>001</PLAN_ID>
      <PARTICIPANT>
        <PARTICIPANT_ID>9999</PARTICIPANT_ID>
        <INVESTMENTS>
          <INVESTMENT>
            <INVESTMENT_ID>ABC</INVESTMENT_ID>
            <BALANCE>1000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>XYZ</INVESTMENT_ID>
            <BALANCE>2000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>QWERTY</INVESTMENT_ID>
            <BALANCE>3000</BALANCE>
            <ELECTION>100.0</ELECTION>
          </INVESTMENT>
        </INVESTMENTS>
      </PARTICIPANT>
    </PLAN>
    <PLAN>
      <PLAN_ID>002</PLAN_ID>
      <PARTICIPANT>
        <PARTICIPANT_ID>9999</PARTICIPANT_ID>
        <INVESTMENTS>
          <INVESTMENT>
            <INVESTMENT_ID>ABC</INVESTMENT_ID>
            <BALANCE>2000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>XYZ</INVESTMENT_ID>
            <BALANCE>4000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>QWERTY</INVESTMENT_ID>
            <BALANCE>6000</BALANCE>
            <ELECTION>100.0</ELECTION>
          </INVESTMENT>
        </INVESTMENTS>
      </PARTICIPANT>
    </PLAN>
</FILE>
</code>```

I started with just trying to get the SUM of all of the BALANCE elements

```<code>var doc = XDocument.Load("test.xml");

var sum = (from nd in doc.Descendants("BALANCE")
           select Int32.Parse(nd.Value)).Sum();

Console.WriteLine(sum);
</code>```

and that worked, giving me 18000.  Then I wanted to group the data by the PLAN_ID but I cannot get it to give me other than 0.

```<code>var doc = XDocument.Load("test.xml");
var q = from x in doc.Descendants("PLAN")
        group x by x.Element("PLAN_ID").Value into gr
        select new
        {
             key = gr.Key,
             tot = (from tx in gr.Elements("BALANCE")
                    select (int)tx).Sum()
        };
</code>```

When I run that I get:

[0] { key = "001", tot = 0 }

[1] { key = "002", tot = 0 }

Where did I go wrong?

答:
The problem is that you're using Elements() when the element you're looking for is deeper into the XML tree than a single level.  If you switch to Descendants() within your inner query, then you should get the results you're expecting.

```<code>var doc = XDocument.Load("test.xml");
var q = from x in doc.Descendants("PLAN")
        group x by x.Element("PLAN_ID").Value into gr
        select new
        {
             key = gr.Key,
             tot = (from tx in gr.Descendants("BALANCE")
                    select (int)tx).Sum()
        };
</code>```

The BALANCE nodes are 3 nodes deeper than the inner nodes of each PLAN node, so this should do the trick.

Personally, I like using the lambda version because it's a bit cleaner, so just for completeness here's the associated solution using the lambda syntax:

```<code>var q = doc.Descedants("PLAN")
         .GroupBy(x => x.Element("PLAN_ID").Value))
         .Select(gr => new
         {
             key = gr.Key,
             tot = gr.Sum(tx => (int)tx.Descendants("BALANCE"))
         });
</code>```

Body:
I've been trying to work thru this but I am having problems grouping the data.
I have an XML structure

<FILE>
    <PLAN>
      <PLAN_ID>001</PLAN_ID>
      <PARTICIPANT>
        <PARTICIPANT_ID>9999</PARTICIPANT_ID>
        <INVESTMENTS>
          <INVESTMENT>
            <INVESTMENT_ID>ABC</INVESTMENT_ID>
            <BALANCE>1000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>XYZ</INVESTMENT_ID>
            <BALANCE>2000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>QWERTY</INVESTMENT_ID>
            <BALANCE>3000</BALANCE>
            <ELECTION>100.0</ELECTION>
          </INVESTMENT>
        </INVESTMENTS>
      </PARTICIPANT>
    </PLAN>
    <PLAN>
      <PLAN_ID>002</PLAN_ID>
      <PARTICIPANT>
        <PARTICIPANT_ID>9999</PARTICIPANT_ID>
        <INVESTMENTS>
          <INVESTMENT>
            <INVESTMENT_ID>ABC</INVESTMENT_ID>
            <BALANCE>2000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>XYZ</INVESTMENT_ID>
            <BALANCE>4000</BALANCE>
            <ELECTION>0.00</ELECTION>
          </INVESTMENT>
          <INVESTMENT>
            <INVESTMENT_ID>QWERTY</INVESTMENT_ID>
            <BALANCE>6000</BALANCE>
            <ELECTION>100.0</ELECTION>
          </INVESTMENT>
        </INVESTMENTS>
      </PARTICIPANT>
    </PLAN>
</FILE>

I started with just trying to get the SUM of all of the BALANCE elements

var doc = XDocument.Load("test.xml");

var sum = (from nd in doc.Descendants("BALANCE")
           select Int32.Parse(nd.Value)).Sum();

Console.WriteLine(sum);

and that worked, giving me 18000.  Then I wanted to group the data by the PLAN_ID but I cannot get it to give me other than 0.

var doc = XDocument.Load("test.xml");
var q = from x in doc.Descendants("PLAN")
        group x by x.Element("PLAN_ID").Value into gr
        select new
        {
             key = gr.Key,
             tot = (from tx in gr.Elements("BALANCE")
                    select (int)tx).Sum()
        };

When I run that I get:

[0] { key = "001", tot = 0 }

[1] { key = "002", tot = 0 }

Where did I go wrong?

Body:
The problem is that you're using Elements() when the element you're looking for is deeper into the XML tree than a single level.  If you switch to Descendants() within your inner query, then you should get the results you're expecting.

var doc = XDocument.Load("test.xml");
var q = from x in doc.Descendants("PLAN")
        group x by x.Element("PLAN_ID").Value into gr
        select new
        {
             key = gr.Key,
             tot = (from tx in gr.Descendants("BALANCE")
                    select (int)tx).Sum()
        };

The BALANCE nodes are 3 nodes deeper than the inner nodes of each PLAN node, so this should do the trick.

Personally, I like using the lambda version because it's a bit cleaner, so just for completeness here's the associated solution using the lambda syntax:

var q = doc.Descedants("PLAN")
         .GroupBy(x => x.Element("PLAN_ID").Value))
         .Select(gr => new
         {
             key = gr.Key,
             tot = gr.Sum(tx => (int)tx.Descendants("BALANCE"))
         });


问:
Selecting all rows with only one value in column with another common value
my table:

```<code>drop table if exists new_table;
create table if not exists new_table(
    obj_type int(4),
    user_id varchar(30),
    payer_id varchar(30)
);

insert into new_table (obj_type, user_id, payer_id) values
    (1, 'user1', 'payer1'),
    (1, 'user2', 'payer1'),
    (2, 'user3', 'payer1'),
    (1, 'user1', 'payer2'),
    (1, 'user2', 'payer2'),
    (2, 'user3', 'payer2'),
    (3, 'user1', 'payer3'),
    (3, 'user2', 'payer3');
</code>```

I am trying to select all the payer id's whose obj_type is only one value and not any other values. In other words, even though each payer has multiple users, I only want the payers who are only using one obj_type.

I have tried using a query like this:

```<code>select * from new_table
    where obj_type = 1
    group by payer_id;
</code>```

But this returns rows whose payers also have other user's with other obj_types. I am trying to get a result that looks like:

```<code>obj | user  |  payer
----|-------|--------
3   | user1 |  payer3
3   | user2 |  payer3
</code>```

Thanks in advance.

答:
If you want to return all rows without grouping them you can use analytic functions:

```<code>SELECT * FROM (
  SELECT obj_type,user_id,
         payer_id,
        COUNT(DISTINCT obj_type) OVER (PARTITION BY payer_id) AS distinct_obj_type
  FROM new_table)
WHERE distinct_obj_type = 1
</code>```

Or you can use exist with the query above:

```<code>SELECT *
FROM new_table
WHERE payer_id IN (SELECT payer_id
                   FROM new_table
                   GROUP BY payer_id
                   HAVING COUNT(DISTINCT obj_type) = 1)
</code>```

Body:
my table:

drop table if exists new_table;
create table if not exists new_table(
    obj_type int(4),
    user_id varchar(30),
    payer_id varchar(30)
);

insert into new_table (obj_type, user_id, payer_id) values
    (1, 'user1', 'payer1'),
    (1, 'user2', 'payer1'),
    (2, 'user3', 'payer1'),
    (1, 'user1', 'payer2'),
    (1, 'user2', 'payer2'),
    (2, 'user3', 'payer2'),
    (3, 'user1', 'payer3'),
    (3, 'user2', 'payer3');

I am trying to select all the payer id's whose obj_type is only one value and not any other values. In other words, even though each payer has multiple users, I only want the payers who are only using one obj_type.

I have tried using a query like this:

select * from new_table
    where obj_type = 1
    group by payer_id;

But this returns rows whose payers also have other user's with other obj_types. I am trying to get a result that looks like:

obj | user  |  payer
----|-------|--------
3   | user1 |  payer3
3   | user2 |  payer3

Thanks in advance.

Body:
If you want to return all rows without grouping them you can use analytic functions:

SELECT * FROM (
  SELECT obj_type,user_id,
         payer_id,
        COUNT(DISTINCT obj_type) OVER (PARTITION BY payer_id) AS distinct_obj_type
  FROM new_table)
WHERE distinct_obj_type = 1

Or you can use exist with the query above:

SELECT *
FROM new_table
WHERE payer_id IN (SELECT payer_id
                   FROM new_table
                   GROUP BY payer_id
                   HAVING COUNT(DISTINCT obj_type) = 1)


问:
Call method after view (DOM) is updated (in Angular 2)
Assume that I have the following directive:

```<code>import {Directive, Input, OnChanges } from '@angular/core'

@Directive({
  selector: 'select[my-select]'
})
export class NbSelect implements OnChanges {

  @Input() ngModel;

  constructor() {
  }

  ngOnChanges(changes) {
    doSomeStuffAfterViewIsUpdated();
  }

  doSomeStuffAfterViewIsUpdated() {
    console.log(jQuery('select[my-select]').val()); // this should write the new value
  }
}
</code>```

I'm using it in somewhere in a template: ...<select my-select [(ngModel)]="someReference">...

At some point I change the value of someReference in a component: someReference = "newValue"

What is happening now: The doSomeStuffAfterViewIsUpdated function is called before the DOM is updated. Which means the console shows the old value of the select.

What I want: The doSomeStuffAfterViewIsUpdated function should be called after the DOM is updated by angular, so the console shows the "newValue".

What should I use instead of ngOnChanges to make it work like I want?

Please note that the important thing here is that the code should run after the DOM update. The question is not about how can I access the new value of the element.

Thx!

答:
I'm a bit late to the party, but since I had a similar problem and a probable solution, I thought I'd share:

What you're looking for is MutationObservers (CanIUse);
I solved a very similar issue with a directive similar to this (simplified for... simplicity? :P):

```<code>ngOnChanges() {
    this.observer = new MutationObserver(() => { this.methodToCall() });
    this.observer.observe(this.elRef.nativeElement, this.observerOptions); // See linked MDN doc for options
}

private methodToCall(): void {
    this.observer.disconnect();
}

ngOnDestroy() {
    if(this.observer) {
        this.observer.disconnect();
        this.observer = undefined;
    }
}
</code>```

The MutationObserver callback will be triggered when either an attribute, children, etc is modified in the DOM (or added, deleted, etc)

It is possible you won't need the ngOnChanges at all depending on your use case and it would make the code a bit cleaner too.

Body:
Assume that I have the following directive:

import {Directive, Input, OnChanges } from '@angular/core'

@Directive({
  selector: 'select[my-select]'
})
export class NbSelect implements OnChanges {

  @Input() ngModel;

  constructor() {
  }

  ngOnChanges(changes) {
    doSomeStuffAfterViewIsUpdated();
  }

  doSomeStuffAfterViewIsUpdated() {
    console.log(jQuery('select[my-select]').val()); // this should write the new value
  }
}

I'm using it in somewhere in a template: ...<select my-select [(ngModel)]="someReference">...

At some point I change the value of someReference in a component: someReference = "newValue"

What is happening now: The doSomeStuffAfterViewIsUpdated function is called before the DOM is updated. Which means the console shows the old value of the select.

What I want: The doSomeStuffAfterViewIsUpdated function should be called after the DOM is updated by angular, so the console shows the "newValue".

What should I use instead of ngOnChanges to make it work like I want?

Please note that the important thing here is that the code should run after the DOM update. The question is not about how can I access the new value of the element.

Thx!

Body:
I'm a bit late to the party, but since I had a similar problem and a probable solution, I thought I'd share:

What you're looking for is MutationObservers (CanIUse);
I solved a very similar issue with a directive similar to this (simplified for... simplicity? :P):

ngOnChanges() {
    this.observer = new MutationObserver(() => { this.methodToCall() });
    this.observer.observe(this.elRef.nativeElement, this.observerOptions); // See linked MDN doc for options
}

private methodToCall(): void {
    this.observer.disconnect();
}

ngOnDestroy() {
    if(this.observer) {
        this.observer.disconnect();
        this.observer = undefined;
    }
}

The MutationObserver callback will be triggered when either an attribute, children, etc is modified in the DOM (or added, deleted, etc)

It is possible you won't need the ngOnChanges at all depending on your use case and it would make the code a bit cleaner too.


问:
Calling another objectStream.Write text macro within my macro isn't workiing
So I'm creating a macro to output an UTF-8 encoded XML since the source text will sometimes involve Japanese or Chinese characters. I'm trying to break each section of the XML into different chunks so it's easier for me to edit but my call line isn't working. Since I'm not trained in programming and my knowledge is based on looking up VBA macro codes and tweaking them until I get the desired result, I'm stumped as to how to get my objStream macro to not error when calling another objStream line.

Thanks!

Here it is:

```<code>Sub Export_iTunes_XML()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

If Dir(Output, vbNormal) <> "" Then
    Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
End If
If Answer = vbCancel Then Exit Sub

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

If Sheets("RawMetadata").Range("P4") <> 0 Then Call LocaleTest2

objStream.WriteText "      <production_company>" & Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
___________________________________________________________________________
Sub LocaleTest2()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText Sheets("RawMetadata").Range("P4")
objStream.CopyTo Output

End Sub
</code>```

答:
CopyTo expects another stream object, not a string/file path. If you want LocaleTest2 to write content to the same stream as is already open in Export_iTunes_XML, then you should pass the stream as a parameter when you call LocaleTest2.

Having made that change though, I'm not sure you get any benefit from breaking that out into a separate Sub.

```<code>Sub Export_iTunes_XML()

    Dim FilePath As String
    FilePath = ActiveWorkbook.Path & "\"

    Dim FileName As String
    FileName = "metadata.xml"

    Dim Output As String
    Output = FilePath & FileName

    If Dir(Output, vbNormal) <> "" Then
        Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
    End If
    If Answer = vbCancel Then Exit Sub

    Set objStream = CreateObject("ADODB.Stream") 'Create the stream
    objStream.Open 'Initialize the stream
    objStream.Position = 0 'Rest the position
    objStream.Charset = "UTF-8" 'indicate the character encoding

    objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
    objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

    If Sheets("RawMetadata").Range("P4") <> 0
        LocaleTest2 objStream '<<< pass the stream object
    End If

    objStream.WriteText "      <production_company>" &
    Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
    '....
End Sub

Sub LocaleTest2(objStream as Object)

    'write to the provided stream
    objStream.WriteText Sheets("RawMetadata").Range("P4")

End Sub
</code>```

Body:
So I'm creating a macro to output an UTF-8 encoded XML since the source text will sometimes involve Japanese or Chinese characters. I'm trying to break each section of the XML into different chunks so it's easier for me to edit but my call line isn't working. Since I'm not trained in programming and my knowledge is based on looking up VBA macro codes and tweaking them until I get the desired result, I'm stumped as to how to get my objStream macro to not error when calling another objStream line.

Thanks!

Here it is:

Sub Export_iTunes_XML()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

If Dir(Output, vbNormal) <> "" Then
    Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
End If
If Answer = vbCancel Then Exit Sub

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

If Sheets("RawMetadata").Range("P4") <> 0 Then Call LocaleTest2

objStream.WriteText "      <production_company>" & Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
___________________________________________________________________________
Sub LocaleTest2()

Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"

Dim FileName As String
FileName = "metadata.xml"

Dim Output As String
Output = FilePath & FileName

Set objStream = CreateObject("ADODB.Stream") 'Create the stream
objStream.Open 'Initialize the stream
objStream.Position = 0 'Rest the position
objStream.Charset = "UTF-8" 'indicate the character encoding

objStream.WriteText Sheets("RawMetadata").Range("P4")
objStream.CopyTo Output

End Sub

Body:
CopyTo expects another stream object, not a string/file path. If you want LocaleTest2 to write content to the same stream as is already open in Export_iTunes_XML, then you should pass the stream as a parameter when you call LocaleTest2.

Having made that change though, I'm not sure you get any benefit from breaking that out into a separate Sub.

Sub Export_iTunes_XML()

    Dim FilePath As String
    FilePath = ActiveWorkbook.Path & "\"

    Dim FileName As String
    FileName = "metadata.xml"

    Dim Output As String
    Output = FilePath & FileName

    If Dir(Output, vbNormal) <> "" Then
        Answer = MsgBox("Do you want to overwrite?", vbOKCancel, "File Exists")
    End If
    If Answer = vbCancel Then Exit Sub

    Set objStream = CreateObject("ADODB.Stream") 'Create the stream
    objStream.Open 'Initialize the stream
    objStream.Position = 0 'Rest the position
    objStream.Charset = "UTF-8" 'indicate the character encoding

    objStream.WriteText "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCr
    objStream.WriteText "      <title>" & Sheets("RawMetadata").Range("A3") & "</title>" & vbCr

    If Sheets("RawMetadata").Range("P4") <> 0
        LocaleTest2 objStream '<<< pass the stream object
    End If

    objStream.WriteText "      <production_company>" &
    Sheets("RawMetadata").Range("H3") & "</production_company>" & vbCr
    '....
End Sub

Sub LocaleTest2(objStream as Object)

    'write to the provided stream
    objStream.WriteText Sheets("RawMetadata").Range("P4")

End Sub


问:
Xpath deepest node whose string content is longer than a given length
How does one use XPath to find the deepest node that matches a string content length constraint.

Given a chunk of XHTML (or XML) that looks like this:

```<code><html>
    <body>
        <div id="page">
             <div id="desc">
                  This wool sweater has the following features:
                  <ul>
                       <li>4 buttons</li>
                       <li>Merino Wool</li>
                  </ul>
             </div>
        </div>
        ...
     </body>
</html>
</code>```

An an XPath expression like

```<code>//*[string-length() > 50]
</code>```

Would match the , ,
 and
.  How can one make XPath pick the deepest matching node (ie: <div id="desc">)?

Bonus points, how does one apply the constraint to space normalized content length?

答:
This cannot be expressed as a single XPath 1.0 expression (not using variables)

A single XPath 2.0 expression:

```<code>//*[string-length(.) > 50]
      [count(ancestor::*) >= //*[string-length(.) > 50]/count(ancestor::*)]
</code>```

An XPath 1.0 expression using a variable:

```<code>//*[string-length() > 50]
         [not(//*[string-length() > 50
        and count(ancestor::*) > $vNumAncestrors])
         ]
</code>```

where the variable vNumAncestrors holds the value of count(ancestor::*) for the context node.

The latter expression can be implemented in a hosting language, such as XSLT 1.0 or DOM.

Here is one XSLT 1.0 implementation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:variable name="vLongTextElements"
   select="//*[string-length()>50]"/>

  <xsl:for-each select="$vLongTextElements">
   <xsl:variable name="vNumAncestrors"
        select="count(ancestor::*)"/>

    <xsl:copy-of select=
    "(.)[not(//*[string-length() > 50
            and count(ancestor::*) > $vNumAncestrors])
         ]
    "/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>
</code>```

when this transformation is applied on the provided XML document:

```<code><html>
    <body>
        <div id="page">
            <div id="desc">                                This wool sweater has the following features:
                <ul>
                    <li>4 buttons</li>
                    <li>Merino Wool</li>
                </ul>
            </div>
        </div>                      ...
    </body>
</html>
</code>```

the wanted, correct result is produced:

```<code><div id="desc">                                This wool sweater has the following features:
                <ul>

      <li>4 buttons</li>

      <li>Merino Wool</li>

   </ul>

</div>
</code>```

Bonus points, how does one apply the
  constraint to space normalized content
  length?

Very simple to implement atop of the last solution:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:variable name="vLongTextElements"
   select="//*[string-length(normalize-space())>50]"/>

  <xsl:for-each select="$vLongTextElements">
   <xsl:variable name="vNumAncestrors"
        select="count(ancestor::*)"/>

    <xsl:copy-of select=
    "(.)[not(//*[string-length(normalize-space()) > 50
            and count(ancestor::*) > $vNumAncestrors])
         ]
    "/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>
</code>```

And the initial XPath 2.0 expression is now modified to this one:

```<code>//*[string-length(normalize-space(.)) > 50]
      [count(ancestor::*)
     >=
      //*[string-length(normalize-space(.)) > 50]/count(ancestor::*)
      ]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How does one use XPath to find the deepest node that matches a string content length constraint.

Given a chunk of XHTML (or XML) that looks like this:

                  This wool sweater has the following features:

4 buttons

Merino Wool

        ...

An an XPath expression like

//*[string-length() > 50]

Would match the , ,
 and
.  How can one make XPath pick the deepest matching node (ie: <div id="desc">)?

Bonus points, how does one apply the constraint to space normalized content length?

Body:
This cannot be expressed as a single XPath 1.0 expression (not using variables)

A single XPath 2.0 expression:

//*[string-length(.) > 50]
      [count(ancestor::*) >= //*[string-length(.) > 50]/count(ancestor::*)]

An XPath 1.0 expression using a variable:

//*[string-length() > 50]
         [not(//*[string-length() > 50
        and count(ancestor::*) > $vNumAncestrors])
         ]

where the variable vNumAncestrors holds the value of count(ancestor::*) for the context node.

The latter expression can be implemented in a hosting language, such as XSLT 1.0 or DOM.

Here is one XSLT 1.0 implementation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:variable name="vLongTextElements"
   select="//*[string-length()>50]"/>

  <xsl:for-each select="$vLongTextElements">
   <xsl:variable name="vNumAncestrors"
        select="count(ancestor::*)"/>

    <xsl:copy-of select=
    "(.)[not(//*[string-length() > 50
            and count(ancestor::*) > $vNumAncestrors])
         ]
    "/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on the provided XML document:

<html>
    <body>
        <div id="page">
            <div id="desc">                                This wool sweater has the following features:
                <ul>
                    <li>4 buttons</li>
                    <li>Merino Wool</li>
                </ul>
            </div>
        </div>                      ...
    </body>
</html>

the wanted, correct result is produced:

<div id="desc">                                This wool sweater has the following features:
                <ul>

      <li>4 buttons</li>

      <li>Merino Wool</li>

   </ul>

</div>

Bonus points, how does one apply the
  constraint to space normalized content
  length?

Very simple to implement atop of the last solution:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/*">
  <xsl:variable name="vLongTextElements"
   select="//*[string-length(normalize-space())>50]"/>

  <xsl:for-each select="$vLongTextElements">
   <xsl:variable name="vNumAncestrors"
        select="count(ancestor::*)"/>

    <xsl:copy-of select=
    "(.)[not(//*[string-length(normalize-space()) > 50
            and count(ancestor::*) > $vNumAncestrors])
         ]
    "/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

And the initial XPath 2.0 expression is now modified to this one:

//*[string-length(normalize-space(.)) > 50]
      [count(ancestor::*)
     >=
      //*[string-length(normalize-space(.)) > 50]/count(ancestor::*)
      ]


答:
Looks like a job for Flexbox:

```<code> body {
   height: 100vh;
   padding: 0;
   margin: 0;
 }

 .container {
   height: 100%;
   border: 1px solid #bbb;
 }

 .page-header {
   display: block;
 }

 .content {
   display: flex;
   flex-direction: column;
   height: 100%;
 }

 .wrapper {
   width: 100%;
   height: 100%;
   overflow: auto;
 }

 .override {
   border: 1px solid blue;
   height: 100%;
   overflow: auto;
 }

 .footer {
   text-align: center;
   height: 25px;
 }
</code>```

JSFiddle demo:https://jsfiddle.net/9yhsnaLk/2/

Title: Resizing Div vertically when view port is resized

Body:
Looks like a job for Flexbox:

 body {
   height: 100vh;
   padding: 0;
   margin: 0;
 }

 .container {
   height: 100%;
   border: 1px solid #bbb;
 }

 .page-header {
   display: block;
 }

 .content {
   display: flex;
   flex-direction: column;
   height: 100%;
 }

 .wrapper {
   width: 100%;
   height: 100%;
   overflow: auto;
 }

 .override {
   border: 1px solid blue;
   height: 100%;
   overflow: auto;
 }

 .footer {
   text-align: center;
   height: 25px;
 }

JSFiddle demo:https://jsfiddle.net/9yhsnaLk/2/


问:
Scala Collections Optional Tuple flatMap
Just practicing/playing with scala collections and using partials. Though I can't seem to figure out how to type match for flatMap when map will map correctly to a list. I'm aware there are other ways(skip to ending) just curious how this would work.

```<code>val fours = Map( 1 -> 4, 2 -> 8, 3 -> 12)
def greaterTuple( k:Int, v:Int):Option[(Int, Int)] = if(v > 4) Some(k,v) else None

fours.flatMap { case (k,v) => greaterTuple(k,v) }  //works
fours.flatMap( x => greaterTuple(x._1, x._2))      //works
fours.map( (greaterTuple _).tupled)                //works

fours.flatMap( (greaterTuple _).tupled)

 Error:(27, 56) type mismatch;
 found   : ((Int, Int)) => Option[(Int, Int)]
 required: ((Int, Int)) => scala.collection.GenTraversableOnce[?]
</code>```

So other than changing the function signature to something like

```<code>def greaterTuple( t: (Int,Int)):Option[(Int,Int)] = if(t._2 > 4) Some(t) else None
</code>```

Making everything as easy

```<code>fours.flatMap(greaterTuple)
fours.map(greaterTuple)
</code>```

or before someone suggests: inline the whole thing just not my point

```<code>fours.filter(t => t._2 > 4)
</code>```

So how do you type cast it as optional?

Maybe you don't worry and just except the aforementioned

```<code>fours.flatMap { case (k,v) => greaterTuple(k,v) }
</code>```

** Aside why is there so much complaint on t._1/2/etc.. if you are ever at most working with a single tuple to pass to a function. I feel like it's a part of the language we should use it were it makes sense and idiomatic otherwise; end rant.

答:
Scala Option is not a traversable, so flatMap doesn't work. You can't cast an Option into a traversable. The map operation returns an Iterable[Option[(Int, Int)]]. 2.12 has an operation flatten that you can use on the result of the map. It'll filter out the empty Options and convert the non-empty ones into (Int, Int).

I'm not clear what you're trying to achieve using the flatMap. Do you want an Iterable[(Int, Int)]?

Edit:

I overlooked implicit Option.option2Iterable: Option[A] => Iterable[A], and @JustDave's syntax was wrong.

```<code>scala> fours.flatMap((greaterTuple _).tupled(_))
res0: scala.collection.immutable.Map[Int,Int] = Map(2 -> 8, 3 -> 12)
</code>```

Also see this.

Body:
Just practicing/playing with scala collections and using partials. Though I can't seem to figure out how to type match for flatMap when map will map correctly to a list. I'm aware there are other ways(skip to ending) just curious how this would work.

val fours = Map( 1 -> 4, 2 -> 8, 3 -> 12)
def greaterTuple( k:Int, v:Int):Option[(Int, Int)] = if(v > 4) Some(k,v) else None

fours.flatMap { case (k,v) => greaterTuple(k,v) }  //works
fours.flatMap( x => greaterTuple(x._1, x._2))      //works
fours.map( (greaterTuple _).tupled)                //works

fours.flatMap( (greaterTuple _).tupled)

 Error:(27, 56) type mismatch;
 found   : ((Int, Int)) => Option[(Int, Int)]
 required: ((Int, Int)) => scala.collection.GenTraversableOnce[?]

So other than changing the function signature to something like

def greaterTuple( t: (Int,Int)):Option[(Int,Int)] = if(t._2 > 4) Some(t) else None

Making everything as easy

fours.flatMap(greaterTuple)
fours.map(greaterTuple)

or before someone suggests: inline the whole thing just not my point

fours.filter(t => t._2 > 4)

So how do you type cast it as optional?

Maybe you don't worry and just except the aforementioned

fours.flatMap { case (k,v) => greaterTuple(k,v) }

** Aside why is there so much complaint on t._1/2/etc.. if you are ever at most working with a single tuple to pass to a function. I feel like it's a part of the language we should use it were it makes sense and idiomatic otherwise; end rant.

Body:
Scala Option is not a traversable, so flatMap doesn't work. You can't cast an Option into a traversable. The map operation returns an Iterable[Option[(Int, Int)]]. 2.12 has an operation flatten that you can use on the result of the map. It'll filter out the empty Options and convert the non-empty ones into (Int, Int).

I'm not clear what you're trying to achieve using the flatMap. Do you want an Iterable[(Int, Int)]?

Edit:

I overlooked implicit Option.option2Iterable: Option[A] => Iterable[A], and @JustDave's syntax was wrong.

scala> fours.flatMap((greaterTuple _).tupled(_))
res0: scala.collection.immutable.Map[Int,Int] = Map(2 -> 8, 3 -> 12)

Also see this.


问:
Servlet multipart config can't upload larger files
I am using @MultipartConfig for uploading files into a database but it works only for small files, smaller than 5 MB. How to improve my code to work with larger files?

```<code>@WebServlet(name = "Upload", urlPatterns = {"/upload"})
@MultipartConfig(maxFileSize = 16177215)
public class Upload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        InputStream in = null;

        Part filePart = request.getPart("pdffile");

        if (filePart != null) {
            in = filePart.getInputStream();
        }
        Connection con = (Connection) getServletContext().getAttribute("Connection");
        String sql = "INSERT INTO storepdf (pdffile) VALUES (?)";
        try (PreparedStatement stat = con.prepareStatement(sql)) {
            if (in != null) {
                stat.setBlob(1, in);
            }
            int i = stat.executeUpdate();
            request.setAttribute("res", i);

        } catch (SQLException e) {

        }
        request.getRequestDispatcher("finish.jsp").forward(request, response);
    }
}
</code>```

答:
Make sure the server allows you to let the users upload more than this. For instance tomcat has configs to limit the upload size (maxPostSizein server.xml), and by default it's limited to 2MB.

Not just that, the read/write timeout also could close the connection if the upload gets long!(for example low-bandwidth)

You may print the exception you catch to find out if there was any issue you could get it in server.

(p.s the way you SQL, is so scary, datasource pool?)

Body:
I am using @MultipartConfig for uploading files into a database but it works only for small files, smaller than 5 MB. How to improve my code to work with larger files?

@WebServlet(name = "Upload", urlPatterns = {"/upload"})
@MultipartConfig(maxFileSize = 16177215)
public class Upload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        InputStream in = null;

        Part filePart = request.getPart("pdffile");

        if (filePart != null) {
            in = filePart.getInputStream();
        }
        Connection con = (Connection) getServletContext().getAttribute("Connection");
        String sql = "INSERT INTO storepdf (pdffile) VALUES (?)";
        try (PreparedStatement stat = con.prepareStatement(sql)) {
            if (in != null) {
                stat.setBlob(1, in);
            }
            int i = stat.executeUpdate();
            request.setAttribute("res", i);

        } catch (SQLException e) {

        }
        request.getRequestDispatcher("finish.jsp").forward(request, response);
    }
}


问:
2D linear interpolation: data and interpolated points
Consider this y(x) function:

where we can generate these scattered points in a file: dataset_1D.dat:

```<code># x   y
0   0
1   1
2   0
3   -9
4   -32
</code>```

The following is a 1D interpolation code for these points:

Load this scattered points

Create a x_mesh

Perform a 1D interpolation

Code:

```<code>import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt

# Load the data:
x, y  = np.loadtxt('./dataset_1D.dat', skiprows = 1).T

# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)

# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh

# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated

# plot:

plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left',  prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()
</code>```

This plots the following:

Now, consider this z(x,y) function:

where we can generate these scattered points in a file: dataset_2D.dat :

```<code># x    y    z
0   0   0
1   1   0
2   2   -4
3   3   -18
4   4   -48
</code>```

In this case we would have to perform a 2D interpolation:

```<code>import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt('./dataset_2D.dat', skiprows = 1).T

# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)

# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh

# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape

# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

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

This plots the following:

where the scattered data is shown again in red dots, to be consistent with the 2D plot.

I do not know how to interpret the  Z_interpolated result:

According to the printing lines for the above code,
Z_interpolated is a n-dimensional numpy array, of shape (10,10). In other words, a 2D matrix with 10 rows and 10 columns.

I would have expected an interpolated z[i] value for each value of x_mesh[i] and y_mesh[i] Why I do not receive this ?

How could I plot also in the 3D plot the interpolated data (just like the black crosses in the 2D plot)?

答:
You would need two steps of interpolation. The first interpolates between y data. And the second interpolates between z data. You then plot the x_mesh with the two interpolated arrays.

```<code>x_mesh = np.linspace(0, 4, num=16)

yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)

ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')
</code>```

In the complete example below I added some variation in y direction as well to make the solution more general.

```<code>u = u"""# x    y    z
0   0   0
1   3   0
2   9   -4
3   16   -18
4   32   -48"""

import io
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)

x_mesh = np.linspace(0, 4, num=16)

yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

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

For using scipy.interpolate.interp1d the solution is essentially the same:

```<code>u = u"""# x    y    z
0   0   0
1   3   0
2   9   -4
3   16   -18
4   32   -48"""

import io
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)

x_mesh = np.linspace(0, 4, num=16)

fy = interp1d(x, y, kind='cubic')
fz = interp1d(x, z, kind='cubic')

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, fy(x_mesh), fz(x_mesh), c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

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

Body:
Consider this y(x) function:

where we can generate these scattered points in a file: dataset_1D.dat:

# x   y
0   0
1   1
2   0
3   -9
4   -32

The following is a 1D interpolation code for these points:

Load this scattered points

Create a x_mesh

Perform a 1D interpolation

Code:

import numpy as np
from scipy.interpolate import interp2d, interp1d, interpnd
import matplotlib.pyplot as plt

# Load the data:
x, y  = np.loadtxt('./dataset_1D.dat', skiprows = 1).T

# Create the function Y_inter for interpolation:
Y_inter = interp1d(x,y)

# Create the x_mesh:
x_mesh = np.linspace(0, 4, num=10)
print x_mesh

# We calculate the y-interpolated of this x_mesh :
Y_interpolated = Y_inter(x_mesh)
print Y_interpolated

# plot:

plt.plot(x_mesh, Y_interpolated, "k+")
plt.plot(x, y, 'ro')
plt.legend(['Linear 1D interpolation', 'data'], loc='lower left',  prop={'size':12})
plt.xlim(-0.1, 4.2)
plt.grid()
plt.ylabel('y')
plt.xlabel('x')
plt.show()

This plots the following:

Now, consider this z(x,y) function:

where we can generate these scattered points in a file: dataset_2D.dat :

# x    y    z
0   0   0
1   1   0
2   2   -4
3   3   -18
4   4   -48

In this case we would have to perform a 2D interpolation:

import numpy as np
from scipy.interpolate import interp1d, interp2d, interpnd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt('./dataset_2D.dat', skiprows = 1).T

# Create the function Z_inter for interpolation:
Z_inter = interp2d(x, y, z)

# Create the x_mesh and y_mesh :
x_mesh = np.linspace(1.0, 4, num=10)
y_mesh = np.linspace(1.0, 4, num=10)
print x_mesh
print y_mesh

# We calculate the z-interpolated of this x_mesh and y_mesh :
Z_interpolated = Z_inter(x_mesh, y_mesh)
print Z_interpolated
print type(Z_interpolated)
print Z_interpolated.shape

# plot:
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

This plots the following:

where the scattered data is shown again in red dots, to be consistent with the 2D plot.

I do not know how to interpret the  Z_interpolated result:

According to the printing lines for the above code,
Z_interpolated is a n-dimensional numpy array, of shape (10,10). In other words, a 2D matrix with 10 rows and 10 columns.

I would have expected an interpolated z[i] value for each value of x_mesh[i] and y_mesh[i] Why I do not receive this ?

How could I plot also in the 3D plot the interpolated data (just like the black crosses in the 2D plot)?

Body:
You would need two steps of interpolation. The first interpolates between y data. And the second interpolates between z data. You then plot the x_mesh with the two interpolated arrays.

x_mesh = np.linspace(0, 4, num=16)

yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)

ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')

In the complete example below I added some variation in y direction as well to make the solution more general.

u = u"""# x    y    z
0   0   0
1   3   0
2   9   -4
3   16   -18
4   32   -48"""

import io
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)

x_mesh = np.linspace(0, 4, num=16)

yinterp = np.interp(x_mesh, x, y)
zinterp = np.interp(x_mesh, x, z)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, yinterp, zinterp, c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

For using scipy.interpolate.interp1d the solution is essentially the same:

u = u"""# x    y    z
0   0   0
1   3   0
2   9   -4
3   16   -18
4   32   -48"""

import io
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Load the data:
x, y, z  = np.loadtxt(io.StringIO(u), skiprows = 1, unpack=True)

x_mesh = np.linspace(0, 4, num=16)

fy = interp1d(x, y, kind='cubic')
fz = interp1d(x, z, kind='cubic')

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_mesh, fy(x_mesh), fz(x_mesh), c='k', marker='s')
ax.scatter(x, y, z, c='r', marker='o')
plt.legend(['data'], loc='lower left',  prop={'size':12})
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()


问:
Sum and product in given range
Given four positive integers , ,  and , is there a way to quickly find any two integers  and  such that:

, and

?

When  and , there is a closed-form  solution to this using quadratic equations. We simply have to find the roots of  and it will give us a suitable .

When , I know how to solve it in  by noticing that the curve  is convex and so we can just binary search for a suitable .

When , it can be solved in  by factoring  and looking for a pair of factors that sum to a value within the range.

When both of them are ranges, however, I can't think of any algorithm that can solve this efficiently. There are some possible heuristics, like fixing one of the two (iterating through the smaller range, etc.), or immediately reporting that no pair exists when the largest possible product that can be made with two integers summing to  is smaller than , etc.

Unfortunately, I haven't been able to come up with anything that would work in the general case that is faster than iterating through everything in either  or  (possibly with some extra smaller factors). Is there a nice algorithm, or some fancy mathematics, that gives a faster solution?

Alternatively, is there a way to prove that iterating terminates quickly? (After handling some corner cases, etc.) I'm not interested in the number of valid pairs; finding any pair will do. It seems that iterating over the product and trying to find a corresponding sum tends to quickly find a solution if the range of allowable sums is sufficiently large. Could there be some sort of proof of this?

I would greatly appreciate any help!

答:
You can solve it in O(sqrt(P2)) time.

Find these sums: small_sum = i + ceiling(P1/i) and big_sum = i + floor(P2/i) for i between 1 and sqrt(P2).

If small_sum > big_sum or big_sum < s1 or small_sum > s2 then i isn't partn of a solution. Move on.

Otherwise, max(small_sum, s1) min(big_sum, s2), and all values between "good sums." For any of these, let j = good_sum - i. Then i + j is a value between s1 and s2, and i * j is between p1 and p2.

We're checking at most sqrt(P2) values of i, and for each of these values we're doing constant work.

Edit -- Ruby implementation

```<code>def solve(s1, s2, p1, p2)
  max_i = (p2**0.5).floor
  1.upto(max_i) do |i|
    small_sum = i + (p1/i.to_f).ceil
    big_sum = i + (p2/i.to_f).floor
    next if big_sum < s1 || small_sum > s2 || big_sum < small_sum
    good_sum = [small_sum, s1].max
    puts "sum: #{i} + #{good_sum - i} = #{good_sum}, #{s1} <= #{good_sum} <= #{s2}"
    puts "product: #{i} * #{good_sum-i} = #{i*(good_sum-i)}, #{p1} <= #{i*(good_sum-i)} <= #{p2}"
    return
  end
  puts "no solution"
end
</code>```

Title: Sum and product in given range

Body:
You can solve it in O(sqrt(P2)) time.

Find these sums: small_sum = i + ceiling(P1/i) and big_sum = i + floor(P2/i) for i between 1 and sqrt(P2).

If small_sum > big_sum or big_sum < s1 or small_sum > s2 then i isn't partn of a solution. Move on.

Otherwise, max(small_sum, s1) min(big_sum, s2), and all values between "good sums." For any of these, let j = good_sum - i. Then i + j is a value between s1 and s2, and i * j is between p1 and p2.

We're checking at most sqrt(P2) values of i, and for each of these values we're doing constant work.

Edit -- Ruby implementation

def solve(s1, s2, p1, p2)
  max_i = (p2**0.5).floor
  1.upto(max_i) do |i|
    small_sum = i + (p1/i.to_f).ceil
    big_sum = i + (p2/i.to_f).floor
    next if big_sum < s1 || small_sum > s2 || big_sum < small_sum
    good_sum = [small_sum, s1].max
    puts "sum: #{i} + #{good_sum - i} = #{good_sum}, #{s1} <= #{good_sum} <= #{s2}"
    puts "product: #{i} * #{good_sum-i} = #{i*(good_sum-i)}, #{p1} <= #{i*(good_sum-i)} <= #{p2}"
    return
  end
  puts "no solution"
end


问:
Selenium clicks not working with GWT
I run GWT OBF (thus this isn't the problem), but when I use Selenium (tried both IDE and RC) my clicks don't get recorded. The component I'm trying to click is a
, but nothing happens.

For instance, in IDE I am sometimes (very seldom, like one in 50 clicks) able to register a click on different tabs (contained in
), but never able to replay the test with any resulting click. Help!?!

答: Another thing to try in this situation is selenium.fireEvent(locater, 'click').  It seems to work in some situations where selenium.click doesn't, depending on how your dhtml works.</p>

Title: Selenium clicks not working with GWT


问:
Android Branch Deeplinks not working from within Facebook
I have Branch.io deeplinking implemented in my App. Everything used to work fine, but recently (not sure how long ago, just noticed), when links are clicked from within the FB App, the returned branchUniversalObject is always null. The following code snippet is implemented and if the same link is clicked from any other App (messenger, slack, browser, etc...) the branchUniversalObject is valid and everything works as expected. I even copied the link from the FB post and pasted it into the browser and the branchUniversalObject was non-null then.

```<code>branch.initSession(new Branch.BranchUniversalReferralInitListener() {
        @Override
        public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
            Log.d(TAG, "setupBranch: onInitiFinished: branchUniversalObject: " + branchUniversalObject);
            if (error == null && branchUniversalObject != null) {
                HashMap<String,String> branchMetadata = branchUniversalObject.getMetadata();
                    Bundle bundle = new Bundle();
                    if (Session.isGuestMode()) {
                        bundle.put(.....)
                        jumpToLogin(bundle);
                    } else {
                        bundle.put(.....);
                        BranchUtils.startBranchSubscribe(bundle);

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

Did FB change something in their App how they are handling link clicks? And if so, is there something that needs to be done on the Android App side?

Seems to work fine in the iOS version of the App.

答:
Alex from Branch.io: this is not expected behavior. We just tried this with our own testbed apps and everything is working as expected, so it sounds like some sort of configuration issue unique to your app.

Would you mind writing a ticket for our Integrations team so we can get to the bottom of this?

Body:
I have Branch.io deeplinking implemented in my App. Everything used to work fine, but recently (not sure how long ago, just noticed), when links are clicked from within the FB App, the returned branchUniversalObject is always null. The following code snippet is implemented and if the same link is clicked from any other App (messenger, slack, browser, etc...) the branchUniversalObject is valid and everything works as expected. I even copied the link from the FB post and pasted it into the browser and the branchUniversalObject was non-null then.

branch.initSession(new Branch.BranchUniversalReferralInitListener() {
        @Override
        public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
            Log.d(TAG, "setupBranch: onInitiFinished: branchUniversalObject: " + branchUniversalObject);
            if (error == null && branchUniversalObject != null) {
                HashMap<String,String> branchMetadata = branchUniversalObject.getMetadata();
                    Bundle bundle = new Bundle();
                    if (Session.isGuestMode()) {
                        bundle.put(.....)
                        jumpToLogin(bundle);
                    } else {
                        bundle.put(.....);
                        BranchUtils.startBranchSubscribe(bundle);

                    }
                }
            }
        }
    });

Did FB change something in their App how they are handling link clicks? And if so, is there something that needs to be done on the Android App side?

Seems to work fine in the iOS version of the App.


问:
Kubernetes on aws displays hex code on the external ip address
After following the link https://kubernetes.io/docs/tasks/access-application-cluster/load-balance-access-application-cluster/ to create a service and expose the replica set.

The output shows the internal IP address as Hex code.

```<code>$ kubectl get services example-service
NAME              CLUSTER-IP     EXTERNAL-IP        PORT(S)          AGE
example-service   100.66.5.159   a75af4afc61af...   8080:32114/TCP   1h
</code>```

Here is my Kubernetes environment.

The Kubernetes cluster is running on AWS was deployed with kops version 1.6.0 and kubelet version 1.6.4. Everything is working fine with the internal cluster including DNS.

答: That is the address of the ELB that was created for the service. If you go into the AWS console you should see an ELB that begins with that string. This will make your service externally accessible from outside your cluster.</p>

Body:
After following the link https://kubernetes.io/docs/tasks/access-application-cluster/load-balance-access-application-cluster/ to create a service and expose the replica set.

The output shows the internal IP address as Hex code.

$ kubectl get services example-service
NAME              CLUSTER-IP     EXTERNAL-IP        PORT(S)          AGE
example-service   100.66.5.159   a75af4afc61af...   8080:32114/TCP   1h

Here is my Kubernetes environment.

The Kubernetes cluster is running on AWS was deployed with kops version 1.6.0 and kubelet version 1.6.4. Everything is working fine with the internal cluster including DNS.


问:
jQuery disable/re-enable validators on a page
When I need to disable/re-enable validator I usually use jQuery code like so:

```<code>      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], false);
</code>```

and to re-enable it back:

```<code>      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            var validator = $('[id*=DueDateRequiredValidator]')[0];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);
</code>```

And it works. But now I need to disable/re-enable a large number of validators, but only a subset of validators, not entire set on a page. There's too many of them to refer each validator by "id".

I tried something like this but it didn't work, don't know why:

```<code>      $.each(Page_Validators, function(index, validator) {
                if ( validator.CssClass == "noinjuries" )

                { ValidatorEnable(validator, false); }

      });
</code>```

What's the best way to do this, if any?

答:
Yeah, try this first

if ($(validator).hasClass('noinjuries')) { /* disable validator */ }

Body:
When I need to disable/re-enable validator I usually use jQuery code like so:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], false);

and to re-enable it back:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            var validator = $('[id*=DueDateRequiredValidator]')[0];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);

And it works. But now I need to disable/re-enable a large number of validators, but only a subset of validators, not entire set on a page. There's too many of them to refer each validator by "id".

I tried something like this but it didn't work, don't know why:

      $.each(Page_Validators, function(index, validator) {
                if ( validator.CssClass == "noinjuries" )

                { ValidatorEnable(validator, false); }

      });

What's the best way to do this, if any?


问:
Dynamic SUMPRODUCT to Auto Update with New Row
I am trying to figure out a way to have a dynamic SUMPRODUCT that automatically update when a new row (expense) is inserted with a different unit price. I'm currently using =SUM(INDIRECT("D23 :"&ADDRESS(ROW()-2,COLUMN())) for the sum version to get the total number of units, but I need to do a SUMPRODUCT in order to total different cost per units with the number of units resulting in the total cost for that particular service. The columns are the different services being provided. The SUMPRODUCT isn't working with the INDIRECT and ADDRESS nested to make the arrays. Due to needing more than one total at the bottom for error checking, I cannot use a table. Any help would be greatly appreciated!

答:
You can use a mix of absolute and relative referencing instead of Indirect. Consider this screenshot:

The range is referred to with $F$7:F12 If more row are inserted above the total row, the formula in the total will change to =SUM($F$7:F13), i.e. the range always starts in F7 and will extend to one cell above the current cell.

The formula in F14 calculates the average and uses =AVERAGE($F$7:F12). When another row is inserted above the total row, the formula will change to =AVERAGE($F$7:F13), i.e. start at cell F7 and extend the range to two cells above the current cell.

This concept can be used without issues in all formulas that use ranges.


问:
Generating custom PDF server or client side using Angular4 and PHP
I am building an Angular 4 app with PHP API. Within the app users are able generate some sort of "magazine". This allows them to sort pages, edit content and add images but not in a WYSIWYG way, rather in a step by step "this option I selected is what I want" way.

So I end up with a lot of data stored in a MySQL database kind of "describing" how the final PDF should look like.

The problem is I have absolutely no idea how to generate a PDF. I know there are things like pdfmake or jsPDF as client side solutions or tcpdf (which seems to be in version transition for ever?!) as server side solution. But all of these are limited.

I think the best solution would be to generate some LaTeX code and generating some PDF out of it, due to the ability to use the variety of LaTeX commands instead of the limited commands for jsPDF or pdfmake.

Is there any kind of standard or best way to manage compiling LaTeX code using angular?

Which way to go? Server side or client side? The LaTeX and PDFs which are going to be created contain lots of images, and about 100-200 pages ...

答:
For everyone else searching

CLSI seems to be a way of managing it. There is an still being maintained open source api to compile LaTeX files: CLSI ShareLaTeX

Thanks to mike42
Another very interesting example of compiling LaTeX with PHP ... which actually is the way to go in my case ... is to generate a .tex file which is a valid LaTeX file and a valid PHP file at once so the code ends up something like this:

```<code>% This file is a valid PHP file and also a valid LaTeX file
% When processed with LaTeX, it will generate a blank template
% Loading with PHP will fill it with details

\documentclass{article}
% Required for proper escaping
\usepackage{textcomp} % Symbols
\usepackage[T1]{fontenc} % Input format

% Because Unicode etc.
\usepackage{fontspec} % For loading fonts
\setmainfont{Liberation Serif} % Has a lot more symbols than Computer Modern

% Make placeholders visible
\newcommand{\placeholder}[1]{\textbf{$<$ #1 $>$}}

% Defaults for each variable
\newcommand{\test}{\placeholder{Data here}}

% Fill in
% <?php echo "\n" . "\\renewcommand{\\test}{" . LatexTemplate::escape($data['test']) . "}\n"; ?>

\begin{document}
    \section{Data From PHP}
    \test{}
\end{document}
</code>```

If PHP safe mode is disabled and the server has xelatex / pdflatex installed execute the command on a file directly ...

First the filled-in LaTeX code needs to be stored in a temporary file by doing something like this:

```<code>/**
 * Generate a PDF file using xelatex and pass it to the user
 */
public static function download($data, $template_file, $outp_file) {
    // Pre-flight checks
    if(!file_exists($template_file)) {
        throw new Exception("Could not open template");
    }
    if(($f = tempnam(sys_get_temp_dir(), 'tex-')) === false) {
        throw new Exception("Failed to create temporary file");
    }

    $tex_f = $f . ".tex";
    $aux_f = $f . ".aux";
    $log_f = $f . ".log";
    $pdf_f = $f . ".pdf";

    // Perform substitution of variables
    ob_start();
    include($template_file);
    file_put_contents($tex_f, ob_get_clean());
}
</code>```

After that the engine of choice should be executed to generate the output files:

```<code>// Run xelatex (Used because of native unicode and TTF font support)
$cmd = sprintf("xelatex -interaction nonstopmode -halt-on-error %s",
        escapeshellarg($tex_f));
chdir(sys_get_temp_dir());
exec($cmd, $foo, $ret);

// No need for these files anymore
@unlink($tex_f);
@unlink($aux_f);
@unlink($log_f);

// Test here
if(!file_exists($pdf_f)) {
    @unlink($f);
    throw new Exception("Output was not generated and latex returned: $ret.");
}
</code>```

Body:
For everyone else searching

CLSI seems to be a way of managing it. There is an still being maintained open source api to compile LaTeX files: CLSI ShareLaTeX

Thanks to mike42
Another very interesting example of compiling LaTeX with PHP ... which actually is the way to go in my case ... is to generate a .tex file which is a valid LaTeX file and a valid PHP file at once so the code ends up something like this:

% This file is a valid PHP file and also a valid LaTeX file
% When processed with LaTeX, it will generate a blank template
% Loading with PHP will fill it with details

\documentclass{article}
% Required for proper escaping
\usepackage{textcomp} % Symbols
\usepackage[T1]{fontenc} % Input format

% Because Unicode etc.
\usepackage{fontspec} % For loading fonts
\setmainfont{Liberation Serif} % Has a lot more symbols than Computer Modern

% Make placeholders visible
\newcommand{\placeholder}[1]{\textbf{$<$ #1 $>$}}

% Defaults for each variable
\newcommand{\test}{\placeholder{Data here}}

% Fill in
% <?php echo "\n" . "\\renewcommand{\\test}{" . LatexTemplate::escape($data['test']) . "}\n"; ?>

\begin{document}
    \section{Data From PHP}
    \test{}
\end{document}

If PHP safe mode is disabled and the server has xelatex / pdflatex installed execute the command on a file directly ...

First the filled-in LaTeX code needs to be stored in a temporary file by doing something like this:

/**
 * Generate a PDF file using xelatex and pass it to the user
 */
public static function download($data, $template_file, $outp_file) {
    // Pre-flight checks
    if(!file_exists($template_file)) {
        throw new Exception("Could not open template");
    }
    if(($f = tempnam(sys_get_temp_dir(), 'tex-')) === false) {
        throw new Exception("Failed to create temporary file");
    }

    $tex_f = $f . ".tex";
    $aux_f = $f . ".aux";
    $log_f = $f . ".log";
    $pdf_f = $f . ".pdf";

    // Perform substitution of variables
    ob_start();
    include($template_file);
    file_put_contents($tex_f, ob_get_clean());
}

After that the engine of choice should be executed to generate the output files:

// Run xelatex (Used because of native unicode and TTF font support)
$cmd = sprintf("xelatex -interaction nonstopmode -halt-on-error %s",
        escapeshellarg($tex_f));
chdir(sys_get_temp_dir());
exec($cmd, $foo, $ret);

// No need for these files anymore
@unlink($tex_f);
@unlink($aux_f);
@unlink($log_f);

// Test here
if(!file_exists($pdf_f)) {
    @unlink($f);
    throw new Exception("Output was not generated and latex returned: $ret.");
}


问:
How can I merge a branch without closing the issue in Gitlab?
I'm using Gitlab.

I created an issue and then used the "create branch" button in the issue view page.

I worked on the branch and completed and committed around 80% of work.

When I created a merge request from this branch to master and accepted it, the issue was closed automatically.

What was I supposed to do to accept the merge request without closing the issue?

Or maybe it's a git concept that you should merge a branch only when the issue is complete resolved?

答:
Gitlab analyses the commit messages of all commits on the default branch, which is most of the time the master branch.

If it detects an issue pattern, e.g. fixed #<issue number>, in a commit message, it will close this issue. Git handles also merges with commits, to be more specific by default it will create a merge commit.

Now to the merge request:

If you create a merge request in Gitlab from such kind of specific issue branch, it will automatically fill the commit message with a reference to the source issue.
To prevent this you have to delete the commit message before merging.

See the link on the right side which reads Modify Commit Message, there you will find the pattern.


问:
Should I use std::for_each?
I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness, etc).

So with that context in mind, is a good idea to use std::for_each for simple tasks like, say, printing out a vector:

```<code>for_each(v.begin(), v.end(), [](int n) { cout << n << endl; }
</code>```

(The [](int n) being a lambda function). Instead of:

```<code>for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }
</code>```

I hope this question doesn't seem pointless. I guess it almost asks a larger question... should an intermediate programmer use a language feature even though he doesn't really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it. Although this larger question has probably already been asked (e.g. here).

答:
Note that the "traditional" example is buggy:

```<code>for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }
</code>```

This assumes that int can always represent the index of every value in the vector.  There are actually two ways this can go wrong.

One is that int may be of lower rank than std::vector<T>::size_type.  On a 32-bit machine, ints are typically 32-bits wide but v.size() will almost certainly be 64 bits wide.  If you manage to stuff 2^32 elements into the vector, your index will never reach the end.

The second problem is that you're comparing a signed value (int) to an unsigned value (std::vector<T>::size_type).  So even if they were of the same rank, when the size exceeds the maximum integer value, then the index will overflow and trigger undefined behavior.

You may have prior knowledge that, for this vector, those error conditions will never be true.  But you'd either have to ignore or disable the compiler warnings.  And if you disable them, then you don't get the benefit of those warnings helping you find actual bugs elsewhere in your code.  (I've spent lots of time tracking down bugs that should have been detected by these compiler warnings, if the code had made it feasible to enable them.)

So, yes, for_each (or any appropriate <algorithm>) is better because it avoids this pernicious abuse of ints.  You could also use a range-based for loop or an iterator-based loop with auto.

An additional advantage to using <algorithm>s or iterators rather than indexes is that it gives you more flexibility to change container types in the future without refactoring all the code that uses it.

Title: Should I use std::for_each?

Body:
I'm always trying to learn more about the languages I use (different styles, frameworks, patterns, etc). I've noticed that I never use std::for_each so I thought that perhaps I should start. The goal in such cases is to expand my mind and not to improve the code in some measure (readability, expressiveness, compactness, etc).

So with that context in mind, is a good idea to use std::for_each for simple tasks like, say, printing out a vector:

for_each(v.begin(), v.end(), [](int n) { cout << n << endl; }

(The [](int n) being a lambda function). Instead of:

for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }

I hope this question doesn't seem pointless. I guess it almost asks a larger question... should an intermediate programmer use a language feature even though he doesn't really need to at this time but just so that he can understand the feature better for a time that may actually greatly benefit from it. Although this larger question has probably already been asked (e.g. here).

Body:
Note that the "traditional" example is buggy:

for(int i=0; i<v.size(); i++) { cout << v[i] << endl; }

This assumes that int can always represent the index of every value in the vector.  There are actually two ways this can go wrong.

One is that int may be of lower rank than std::vector<T>::size_type.  On a 32-bit machine, ints are typically 32-bits wide but v.size() will almost certainly be 64 bits wide.  If you manage to stuff 2^32 elements into the vector, your index will never reach the end.

The second problem is that you're comparing a signed value (int) to an unsigned value (std::vector<T>::size_type).  So even if they were of the same rank, when the size exceeds the maximum integer value, then the index will overflow and trigger undefined behavior.

You may have prior knowledge that, for this vector, those error conditions will never be true.  But you'd either have to ignore or disable the compiler warnings.  And if you disable them, then you don't get the benefit of those warnings helping you find actual bugs elsewhere in your code.  (I've spent lots of time tracking down bugs that should have been detected by these compiler warnings, if the code had made it feasible to enable them.)

So, yes, for_each (or any appropriate <algorithm>) is better because it avoids this pernicious abuse of ints.  You could also use a range-based for loop or an iterator-based loop with auto.

An additional advantage to using <algorithm>s or iterators rather than indexes is that it gives you more flexibility to change container types in the future without refactoring all the code that uses it.


问:
Resizing Div vertically when view port is resized
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body></code>```

答:
The calc function will work, but you need to remove the spaces around the minus sign. You can use vh units to get the viewport height: height: calc(100vh - 100px);.

* {
  box-sizing:border-box;
}

.container {
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.wrapper {
  height:calc(100vh - 100px);
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body></code>```

Body:
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}

 System Dashboard

          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper

 Copyright here

Body:
The calc function will work, but you need to remove the spaces around the minus sign. You can use vh units to get the viewport height: height: calc(100vh - 100px);.

* {
  box-sizing:border-box;
}

.container {
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.wrapper {
  height:calc(100vh - 100px);
  overflow:auto;
}

<body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body>


问:
Is there any way to check the whole page is dirty or not?
i am new at angularJS, i want to check my page is dirty or not. i know how to check dirty form but not whole page(like i am using directive in this form).is there any way to check directive part is dirty or not? like in my page i have directive for star rating. in that if i change rating then i want to check the page is dirty or not?

```<code><form name="reviewForm">
        <div class="row">
            <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div>
                    <table class="rwd-table table-responsive table-bordered table-striped" >
                        <tbody>
                            <tr data-ng-repeat="review in reviewModifyData.review.KeyAreaList" >
                                <td  class="mywidth">
                                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                        <strong class="reviewPadding">
                                            <span  data-ng-bind="review.Title"></span>
                                        </strong>
                                        <br>
                                    </div>
                                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                                        <small class="reviewPadding"><span data-ng-bind="review.HelpText | limitTo:150"></span><span tooltip-placement="auto" uib-tooltip="{{review.HelpText}}"  data-ng-show="review.HelpText.length > 150">...</span></small>
                                    </div>
                                </td>
                                <td >
                                        <span class="visible-sm visible-xs">             </span>
                                        <angular-star-rating min="reviewModifyData.minValue" max="reviewModifyData.review.RatingLevel"
                                                             value='review.Rate' hover='reviewModifyData.changeOnHover'
                                                             is-readonly='reviewModifyData.isReadonly'>
                                        </angular-star-rating>

                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <br>

                    <div class="row"  data-ng-if="reviewModifyData.section.length !== 0" data-ng-class="{'has-error': reviewForm.$submitted && reviewForm.Remark.$invalid,'has-feedback': reviewForm.$submitted && reviewForm.Remark.$valid}">
                        <div class="form-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <label class="control-label" > Remark</label> <span data-ng-if="reviewModifyData.review.IsRemarkMandetory" class="errortext">*</span>
                            <div class="has-feedback">
                                <textarea class="form-control noresize"  data-ng-if="!reviewModifyData.review.IsRemarkMandetory" rows="3"  name="Remark" placeholder="Enter Remark"  data-ng-model='reviewModifyData.review.Remark' ></textarea>
                                <textarea class="form-control noresize" required data-ng-if="reviewModifyData.review.IsRemarkMandetory" rows="3"  name="Remark" placeholder="Enter Remark"  data-ng-model='reviewModifyData.review.Remark' ></textarea>
                            </div>
                            <span class="text-danger" data-ng-show="reviewForm.$submitted && reviewForm.Remark.$error.required">Please Enter Remark <i class="fa fa-exclamation-circle"></i></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</form>
</code>```

now i have tried in my js like this.

```<code>if ($scope.reviewForm.$dirty) {
                toastr.error('The form is dirty, do you want to stay on the page?');
                return;
            }
</code>```

Thanks in advance,

答:
you can access formController in your directive (look at this answer)
than use $setDirty() method</p>

Body:
i am new at angularJS, i want to check my page is dirty or not. i know how to check dirty form but not whole page(like i am using directive in this form).is there any way to check directive part is dirty or not? like in my page i have directive for star rating. in that if i change rating then i want to check the page is dirty or not?

<form name="reviewForm">

                                         150">...

                                        <angular-star-rating min="reviewModifyData.minValue" max="reviewModifyData.review.RatingLevel"
                                                             value='review.Rate' hover='reviewModifyData.changeOnHover'
                                                             is-readonly='reviewModifyData.isReadonly'>
                                        </angular-star-rating>

                             Remark *

                                <textarea class="form-control noresize"  data-ng-if="!reviewModifyData.review.IsRemarkMandetory" rows="3"  name="Remark" placeholder="Enter Remark"  data-ng-model='reviewModifyData.review.Remark' ></textarea>
                                <textarea class="form-control noresize" required data-ng-if="reviewModifyData.review.IsRemarkMandetory" rows="3"  name="Remark" placeholder="Enter Remark"  data-ng-model='reviewModifyData.review.Remark' ></textarea>

                            Please Enter Remark

</form>

now i have tried in my js like this.

if ($scope.reviewForm.$dirty) {
                toastr.error('The form is dirty, do you want to stay on the page?');
                return;
            }

Thanks in advance,