问:
Microsoft Outlook on Windows Adds Padding to my H4
Take a look at the following image:

What you see there is a highlighted
 element (if there's any confusion, that grey is not a background colour, it is me highlighting the text). It has inline styles explicitly declaring padding-bottom: 0; and line-height: 18px; (the same as the font size - not sure if that even works in Outlook, but figured I'd give it a try). In addition, the HTML is completely minified (so its not caused by a whitespace or tab), and the code has been checked for hidden line break characters (there are none).

Nonetheless, Microsoft Outlook (on Windows only) happily ignores me and adds all that extra space underneath the element. I'm tapped out on ideas as to how to fix this issue.

How can I fix the height of this header element so it is only the height of the text?

答:
I find these rules helpful:

```<code> #outlook a{
        padding:0;
    }
    .ReadMsgBody{
        width:100%;
    }
    body{
        width:100% !important;
        min-width:100%;
        -webkit-text-size-adjust:100%;
        -ms-text-size-adjust:100%;
        -webkit-font-smoothing: antialiased;
    }
    v*{
        behavior:url(#default#VML);
        display:inline-block;
    }
    .ExternalClass{
        width:100%;
    }
    td{
        border-collapse: separate !important;
    }
    .ExternalClass,
    .ExternalClass p,
    .ExternalClass span,
    .ExternalClass font,
    .ExternalClass td,
    .ExternalClass div{
        line-height:100%;
    }
</code>```

You can also add a rule to reset the h4 line-height to 0:

```<code> h4{
    margin:0;
    padding:0;
    border:0;
    font-size:100%;
    line-height:100%;
 }
</code>```

Then add back in line height INLINE:

```<code> <h4 style: font-size: 24px; color: #000000; line-height: 1.8em;">This is an h4 headline</h4>
</code>```

Body:
I find these rules helpful:

 #outlook a{
        padding:0;
    }
    .ReadMsgBody{
        width:100%;
    }
    body{
        width:100% !important;
        min-width:100%;
        -webkit-text-size-adjust:100%;
        -ms-text-size-adjust:100%;
        -webkit-font-smoothing: antialiased;
    }
    v*{
        behavior:url(#default#VML);
        display:inline-block;
    }
    .ExternalClass{
        width:100%;
    }
    td{
        border-collapse: separate !important;
    }
    .ExternalClass,
    .ExternalClass p,
    .ExternalClass span,
    .ExternalClass font,
    .ExternalClass td,
    .ExternalClass div{
        line-height:100%;
    }

You can also add a rule to reset the h4 line-height to 0:

 h4{
    margin:0;
    padding:0;
    border:0;
    font-size:100%;
    line-height:100%;
 }

Then add back in line height INLINE:

 <h4 style: font-size: 24px; color: #000000; line-height: 1.8em;">This is an h4 headline</h4>


来源: stackexchange

问:
Need div to return to previous background color with JavaScript (no jquery)
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}</code>```

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

```

答:
You need to create another event listener attached to contBtn in order to change your background color:

```<code>document.getElementById('contBtn').addEventListener('click', removeAlert);

function removeAlert(event) {
    // remove alert
    document.getElementById('example').innerHTML = '';
    // update background color
    setBgColorById('e1','#fff');
    // remove event listener when there is no alert
    document.getElementById('contBtn').removeEventListener('click', removeAlert);
}
</code>```

Here is a working example

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';

  // attach event listener to contBtn
  document.getElementById('contBtn').addEventListener('click', removeAlert);

}

function removeAlert(event) {
    document.getElementById('example').innerHTML = '';
    setBgColorById('e1','#fff');

    // remove event listener
    document.getElementById('contBtn').removeEventListener('click', removeAlert);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}</code>```

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

```

ContentLicense: CC BY-SA 3.0

Body:
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

Body:
You need to create another event listener attached to contBtn in order to change your background color:

document.getElementById('contBtn').addEventListener('click', removeAlert);

function removeAlert(event) {
    // remove alert
    document.getElementById('example').innerHTML = '';
    // update background color
    setBgColorById('e1','#fff');
    // remove event listener when there is no alert
    document.getElementById('contBtn').removeEventListener('click', removeAlert);
}

Here is a working example

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '<div><span style="display:inline-block;width:28px;height:28px;"><svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg></span><p>For your security, this session is about to end due to inactivity.</p><button id="contBtn" type="button">Continue Session</button></div>';

  // attach event listener to contBtn
  document.getElementById('contBtn').addEventListener('click', removeAlert);

}

function removeAlert(event) {
    document.getElementById('example').innerHTML = '';
    setBgColorById('e1','#fff');

    // remove event listener
    document.getElementById('contBtn').removeEventListener('click', removeAlert);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

<div id="example" role="alert"></div>
<div id="e1">
  <h1>Testing Banner Timeout</h1>
  <p>This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.</p>
  <p>If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.</p>
  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>
</div>


问:
Remove table rows based on condition in matlab
a=[1; 2 ; 3]; b=[ 4; 5; 6 ]; T=table(a,b).
I want to remove rows of table for which the value of b is less than or equal to 5 (b<=5).

答:
Another approach: </p>

```<code>   a = [1; 2; 3];

   b = [4; 5; 6];

   X = [a, b];

   n = 1; m = 1;

   while (n <= size(X, 1))

       if(X(n, 2)  > 5)

           X_new(m, :) = X(n, :);

           m = m + 1;

        end

        n = n + 1;

   end
</code>```

<p>'X_new' will be the required matrix.</p>

Body:
Another approach:

   a = [1; 2; 3];

   b = [4; 5; 6];

   X = [a, b];

   n = 1; m = 1;

   while (n <= size(X, 1))

       if(X(n, 2)  > 5)

           X_new(m, :) = X(n, :);

           m = m + 1;

        end

        n = n + 1;

   end

'X_new' will be the required matrix.


问:
*.vue files, Visual Studio 2017 & TypeScript
Is it possible to edit vuejs's *.vue component files in Visual Studio 2017 with highlighting and intellisense support for HTML, TypeScript AND SCSS?

At the moment, I'm separating the different sections to different files:

```<code><!-- my-component.vue opened in HTML editor -->
<template>
    <div> text </div>
</template>
<script src="./path/to/my-component.ts"></script>
<style src="./path/to/my-component.scss"></style>
</code>```

答: There is a Vue plugin for Visual Studio called VuePack that will provide a better dev experience for single page vue files "*.vue" located here: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.VuejsPack-18329 </p>

Body:
Is it possible to edit vuejs's *.vue component files in Visual Studio 2017 with highlighting and intellisense support for HTML, TypeScript AND SCSS?

At the moment, I'm separating the different sections to different files:

<template>

 text

</template>


问:
Get duplicates based on property using linq
I have a class say

```<code>public class Sample
{
    public string property;
    public List<string> someListProperty;
    public string someOtherPropery;
}
</code>```

Now I have a object which is List<Sample>, I need to iterate over this collection and find out items which are having same values for property and someListProperty fields.

I tried this:

```<code>var listSample = List<Sample>()
var result = listSample.GroupBy(x => new { x.property, x.someListProperty})
                       .Where(x => x.Count() > 1).ToList();
</code>```

But this doesn't seem to work, any pointer would be greatly appreciated.

答:
Update after comment below: As what you describe is that you want to group by someOtherProperty instead of someListProperty then just group by it:

```<code>listSample.GroupBy(x => new { x.property, x.someOtherProperty});
</code>```

Option 1 - You should use the SequenceEqual to check that the nested lists of two given samples are the same. To do that pass a custom IEqualityComparer

```<code>public class SampleComparer : IEqualityComparer<Sample>
{
    public bool Equals(Sample x, Sample y)
    {
        return x.property == y.property &&
            Enumerable.SequenceEqual(x.someListProperty, y.someListProperty);
    }
    public int GetHashCode(Sample obj)
    {
        // Implement
    }
}
</code>```

(for implementing the GetHashCode see: What is the best algorithm for an overridden System.Object.GetHashCode?)

and then:

```<code>var result = list.GroupBy(k => k, new SampleComparer());
</code>```

tested on the following data and it returns 3 groups:

```<code>List<Sample> a = new List<Sample>()
{
    new Sample { property = "a", someListProperty = new List<string> {"a"}, someOtherPropery = "1"},
    new Sample { property = "a", someListProperty = new List<string> {"a"}, someOtherPropery = "2"},
    new Sample { property = "a", someListProperty = new List<string> {"b"}, someOtherPropery = "3"},
    new Sample { property = "b", someListProperty = new List<string> {"a"}, someOtherPropery = "4"},
};
</code>```

Option 2 - Instead of creating a class implementing the interface is to use the ProjectionEqualityComparer as explained here: Can you create a simple 'EqualityComparer<T>' using a lambda expression

As a side note instead of using Count in the where use:

```<code>var result = list.GroupBy(k => k, new SampleComparer())
                 .Where(g => g.Skip(1).Any());
</code>```

As all you want is just to check there is more than one item in the group but not the actual amount this will just go through two items instead of counting them all in an O(n) operation.

Body:
I have a class say

public class Sample
{
    public string property;
    public List<string> someListProperty;
    public string someOtherPropery;
}

Now I have a object which is List<Sample>, I need to iterate over this collection and find out items which are having same values for property and someListProperty fields.

I tried this:

var listSample = List<Sample>()
var result = listSample.GroupBy(x => new { x.property, x.someListProperty})
                       .Where(x => x.Count() > 1).ToList();

But this doesn't seem to work, any pointer would be greatly appreciated.

Body:
Update after comment below: As what you describe is that you want to group by someOtherProperty instead of someListProperty then just group by it:

listSample.GroupBy(x => new { x.property, x.someOtherProperty});

Option 1 - You should use the SequenceEqual to check that the nested lists of two given samples are the same. To do that pass a custom IEqualityComparer

public class SampleComparer : IEqualityComparer<Sample>
{
    public bool Equals(Sample x, Sample y)
    {
        return x.property == y.property &&
            Enumerable.SequenceEqual(x.someListProperty, y.someListProperty);
    }
    public int GetHashCode(Sample obj)
    {
        // Implement
    }
}

(for implementing the GetHashCode see: What is the best algorithm for an overridden System.Object.GetHashCode?)

and then:

var result = list.GroupBy(k => k, new SampleComparer());

tested on the following data and it returns 3 groups:

List<Sample> a = new List<Sample>()
{
    new Sample { property = "a", someListProperty = new List<string> {"a"}, someOtherPropery = "1"},
    new Sample { property = "a", someListProperty = new List<string> {"a"}, someOtherPropery = "2"},
    new Sample { property = "a", someListProperty = new List<string> {"b"}, someOtherPropery = "3"},
    new Sample { property = "b", someListProperty = new List<string> {"a"}, someOtherPropery = "4"},
};

Option 2 - Instead of creating a class implementing the interface is to use the ProjectionEqualityComparer as explained here: Can you create a simple 'EqualityComparer<T>' using a lambda expression

As a side note instead of using Count in the where use:

var result = list.GroupBy(k => k, new SampleComparer())
                 .Where(g => g.Skip(1).Any());

As all you want is just to check there is more than one item in the group but not the actual amount this will just go through two items instead of counting them all in an O(n) operation.


问:
Difference between `type {}` and `Dictionary<T> { [key: string]: T; }`
The async library uses this declaration

```<code>export interface Dictionary<T> { [key: string]: T; }
</code>```

but I am confused, how is this different from

```<code>type {}
</code>```

?

Perhaps type {} allows for Symbol to be used for keys, and the Dictionary interface only allows for keys to be strings?

Here are the typings for async:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/async/index.d.ts#L9

答:
When using --noImplicitAny, the index-signature in the Dictionary<T> interface above will allow arbitrary string-based property access, while {} will not, because it does not have an index-signature:

```<code>interface Dictionary<T> { [key: string]: T; }

let a: Dictionary<string> = {};
let b: {} = {};

a["one"] = "two"; // OK
b["two"] = "three"; // Not OK
</code>```

This is not a problem when --noImplicitAny is not used, or --suppressImplicitAnyIndexErrors is used, because then every object type is treated as having an implicit "any-to-any" index-signature by default.

Body:
The async library uses this declaration

export interface Dictionary<T> { [key: string]: T; }

but I am confused, how is this different from

type {}

?

Perhaps type {} allows for Symbol to be used for keys, and the Dictionary interface only allows for keys to be strings?

Here are the typings for async:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/async/index.d.ts#L9

Body:
When using --noImplicitAny, the index-signature in the Dictionary<T> interface above will allow arbitrary string-based property access, while {} will not, because it does not have an index-signature:

interface Dictionary<T> { [key: string]: T; }

let a: Dictionary<string> = {};
let b: {} = {};

a["one"] = "two"; // OK
b["two"] = "three"; // Not OK

This is not a problem when --noImplicitAny is not used, or --suppressImplicitAnyIndexErrors is used, because then every object type is treated as having an implicit "any-to-any" index-signature by default.


问:
Filter based on a string and count number of rows
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work,</p>

```<code>ByrNbr = Watchlist.Range("B" & i).Value

LookFor = ByrNbr

Set Age_rng = Total.Sheets("Counts").Range("A:S")

If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then

 .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A"))

End If
</code>```

答:
```<code>Sub formulatest()

MsgBox Application.WorksheetFunction.CountIfs(Sheet1.Range("B13:B16"), Sheet1.Range("C12").Value, Sheet1.Range("G13:G16"), Sheet1.Range("D12").Value)
'~~Returns 2

End Sub
</code>```

Body:
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work,

ByrNbr = Watchlist.Range("B" & i).Value

LookFor = ByrNbr

Set Age_rng = Total.Sheets("Counts").Range("A:S")

If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then

 .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A"))

End If


问:
List assignment index out of range when deleting columns in a nested list
I have a nested list with a couple of things in each list. It looks something like this:

```<code>itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]
</code>```

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

```<code>minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)
</code>```

Next I have a bit of code that goes like this:

```<code>for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)
</code>```

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.

答:
Why not use a dictionary? You can even form a dictionary from your existing array and item names:

```<code>item_dict = {k: [l[j] for l in itemsOnShelf] for j, k in enumerate(food)}
</code>```

or using numpy (makes for easier array slicing):

```<code>import numpy as np  # for convenience
itemsOnShelf = np.array(itemsOnShelf)  # lets us use numpy slicing---not necessary, just easier
item_dict = {k: itemsOnShelf[:, j] for j, k in enumerate(food)}
</code>```

You can delete your items with something like:

```<code>def throw_away(key):
    if sum(item_dict[key]) >= max_allowed:
        item_dict.pop(key)  # remove the item from the dictionary
</code>```

Your last part:

```<code>max_allowed = # some threshold
for key in food:
    throw_away(key)
</code>```

Body:
I have a nested list with a couple of things in each list. It looks something like this:

itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)

Next I have a bit of code that goes like this:

for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.

Body:
Why not use a dictionary? You can even form a dictionary from your existing array and item names:

item_dict = {k: [l[j] for l in itemsOnShelf] for j, k in enumerate(food)}

or using numpy (makes for easier array slicing):

import numpy as np  # for convenience
itemsOnShelf = np.array(itemsOnShelf)  # lets us use numpy slicing---not necessary, just easier
item_dict = {k: itemsOnShelf[:, j] for j, k in enumerate(food)}

You can delete your items with something like:

def throw_away(key):
    if sum(item_dict[key]) >= max_allowed:
        item_dict.pop(key)  # remove the item from the dictionary

Your last part:

max_allowed = # some threshold
for key in food:
    throw_away(key)


问:
Model not saving to DB and rolling back
```<code>Rails 5.1
</code>```

fw_export.rb model:

```<code>class FwExport < ApplicationRecord
  include Shared

  has_one :location

end
</code>```

location.rb model:

```<code>class Location < ApplicationRecord
  include Shared

  belongs_to :fw_export

end
</code>```

locations_controller.rb:

```<code>class LocationsController < ApplicationController
  before_action :set_location, only: [:show, :edit, :update, :destroy]

  def new
    @location = Location.new
  end

  def create
    @location = Location.new(location_params)

    respond_to do |format|
      if @location.save
        format.html { redirect_to @location, notice: 'Location was successfully created.' }
        format.json { render :show, status: :created, location: @location }
      else
        format.html { render :new }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    def set_location
      @location = Location.find(params[:id])
    end

    def location_params
      params.require(:location).permit(:fw_exports_id, :city, :state, :country, :api_source)
    end
end
</code>```

location migration file:

```<code>class CreateLocations < ActiveRecord::Migration[5.1]
  def change
    create_table :locations, id: :string do |t|
      t.string :fw_exports_id
      t.string :city
      t.string :state
      t.string :country
      t.string :api_source
      t.timestamps
      t.index [:fw_exports_id], unique: true
    end
  end
end
</code>```

From the console, if I try to do the following:

```<code>location_record = Location.new(
  :fw_exports_id => "fwexport.1510768198.5364478"
)
location_record.save
</code>```

It is failing and rolling back:

```<code>[9] pry(main)> location_record = Location.new(
[9] pry(main)*   :fw_exports_id => "fwexport.1510768198.5364478"
[9] pry(main)* )
=> #<Location:0x0000000003e68888 id: nil, fw_exports_id: "fwexport.1510768198.5364478", city: nil, state: nil, country: nil, api_source: nil, created_at: nil, updated_at: nil>
[10] pry(main)> location_record.save
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
=> false
</code>```

If I do:

```<code>Location.create!(fw_exports_id: "fwexport.1510768198.5364478")
</code>```

I get:

```<code>ActiveRecord::RecordInvalid: Validation failed: Fw export must exist
</code>```

Any idea what the problem might be?

Solution:

Location belongs to FwExport, so the foreign key needs to be singular as in fw_export_id, not fw_exports_id

It worked when I made that chanve

答:
Try to call location_record.errors.full_messages
right after:

```<code>location_record = Location.new(:fw_exports_id =>"fwexport.1510768198.5364478")
location_record.save
</code>```

Copy the output here

It might contains cause of the problem

Title: Model not saving to DB and rolling back

Body:
Rails 5.1

fw_export.rb model:

class FwExport < ApplicationRecord
  include Shared

  has_one :location

end

location.rb model:

class Location < ApplicationRecord
  include Shared

  belongs_to :fw_export

end

locations_controller.rb:

class LocationsController < ApplicationController
  before_action :set_location, only: [:show, :edit, :update, :destroy]

  def new
    @location = Location.new
  end

  def create
    @location = Location.new(location_params)

    respond_to do |format|
      if @location.save
        format.html { redirect_to @location, notice: 'Location was successfully created.' }
        format.json { render :show, status: :created, location: @location }
      else
        format.html { render :new }
        format.json { render json: @location.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    def set_location
      @location = Location.find(params[:id])
    end

    def location_params
      params.require(:location).permit(:fw_exports_id, :city, :state, :country, :api_source)
    end
end

location migration file:

class CreateLocations < ActiveRecord::Migration[5.1]
  def change
    create_table :locations, id: :string do |t|
      t.string :fw_exports_id
      t.string :city
      t.string :state
      t.string :country
      t.string :api_source
      t.timestamps
      t.index [:fw_exports_id], unique: true
    end
  end
end

From the console, if I try to do the following:

location_record = Location.new(
  :fw_exports_id => "fwexport.1510768198.5364478"
)
location_record.save

It is failing and rolling back:

[9] pry(main)> location_record = Location.new(
[9] pry(main)*   :fw_exports_id => "fwexport.1510768198.5364478"
[9] pry(main)* )
=> #<Location:0x0000000003e68888 id: nil, fw_exports_id: "fwexport.1510768198.5364478", city: nil, state: nil, country: nil, api_source: nil, created_at: nil, updated_at: nil>
[10] pry(main)> location_record.save
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
=> false

If I do:

Location.create!(fw_exports_id: "fwexport.1510768198.5364478")

I get:

ActiveRecord::RecordInvalid: Validation failed: Fw export must exist

Any idea what the problem might be?

Solution:

Location belongs to FwExport, so the foreign key needs to be singular as in fw_export_id, not fw_exports_id

It worked when I made that chanve

Body:
Try to call location_record.errors.full_messages
right after:

location_record = Location.new(:fw_exports_id =>"fwexport.1510768198.5364478")
location_record.save

Copy the output here

It might contains cause of the problem


问:
Using split method to split a string

The user is able to specify where the .txt file they want to import is located, via typing the location in via an onscreen prompt (this is stored within String 'importFile', which is being populated using a keyboard scanner).

Content of the file is then scanned using the scanner 'fileReader'.

```<code>String importFile = "";
File Fileobject = new File(importFile);
Scanner fileReader = new Scanner(Fileobject);

while(fileReader.hasNext())
{
  importFile = fileReader.next();
  String [] splitText = importFile.split("[-\\s]");
  System.out.println(splitText[0]);
}
</code>```

However, i am having some trouble then splitting the data within the text file properly...

Each line of text within the text file is formatted as follows:

```<code>abcd - efgh - 12.34 - ijkl - mnop
</code>```

the text should be formatted as such after being split:

```<code>abcd
efgh
12.34
ijkl
mnop
</code>```

i want the text to be stored within the array 'splitText' once it is split, so for example "abcd" will be located within splitText[0] etc. etc. though the whole string is being put into splitText[0] even after being split - screenshot follows (here

答:
Your problem is multifold:

By using Scanner.next(), you are reading the file one whitespace-delimited field at a time, whereas you want to read line by line.  Fix this by using Scanner.nextLine() instead.

As @YCF_L observed first, the delimiter regex you are using is unsuited to your particular task.  There are many variations you could use, but YCF_L's is clear and to the point: "\\s*-\\s*".

After splitting the input, you print only the first of the resulting fields.  Presumably you did this to offset issue (1).

Putting those together, a read loop that does the job you want might look more like this:

```<code>    while(fileReader.hasNext()) {
        String line = fileReader.nextLine();
        String[] splitText = line.split("\\s*-\\s*");

        for (String field : splitText) {
            System.out.println(field);
        }
    }
</code>```

Title: Using split method to split a string

Body:
The user is able to specify where the .txt file they want to import is located, via typing the location in via an onscreen prompt (this is stored within String 'importFile', which is being populated using a keyboard scanner).

Content of the file is then scanned using the scanner 'fileReader'.

String importFile = "";
File Fileobject = new File(importFile);
Scanner fileReader = new Scanner(Fileobject);

while(fileReader.hasNext())
{
  importFile = fileReader.next();
  String [] splitText = importFile.split("[-\\s]");
  System.out.println(splitText[0]);
}

However, i am having some trouble then splitting the data within the text file properly...

Each line of text within the text file is formatted as follows:

abcd - efgh - 12.34 - ijkl - mnop

the text should be formatted as such after being split:

abcd
efgh
12.34
ijkl
mnop

i want the text to be stored within the array 'splitText' once it is split, so for example "abcd" will be located within splitText[0] etc. etc. though the whole string is being put into splitText[0] even after being split - screenshot follows (here

Body:
Your problem is multifold:

By using Scanner.next(), you are reading the file one whitespace-delimited field at a time, whereas you want to read line by line.  Fix this by using Scanner.nextLine() instead.

As @YCF_L observed first, the delimiter regex you are using is unsuited to your particular task.  There are many variations you could use, but YCF_L's is clear and to the point: "\\s*-\\s*".

After splitting the input, you print only the first of the resulting fields.  Presumably you did this to offset issue (1).

Putting those together, a read loop that does the job you want might look more like this:

    while(fileReader.hasNext()) {
        String line = fileReader.nextLine();
        String[] splitText = line.split("\\s*-\\s*");

        for (String field : splitText) {
            System.out.println(field);
        }
    }


问:
Host an Ionic app into AWS S3 Bucket - Not working/rendering
I have created a simple app using ionic2 framework and is working well in local machine/behind a simple 'lite-server'

I wanted to deploy the same in AWS S3 - With "enable static web-hosting" and try it from mobile browsers

I ran - ionic build browser

This created a static web-page contents in \MyApp\platforms\browser\www.

I used a node tool 's3-website' - https://www.npmjs.com/package/s3-website

to publish my App content to S3

All went well, I enabled static web-hosting, had permission for everyone to view, but its not rendering.

Edited
Should the app module name "MyApp" and s3 bucket name match? curious?

In Chrome Console, I get these errors

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
/build/main.css Failed to load resource: the server responded with a status of 404 (Not Found)
device.js Failed to load resource: the server responded with a status of 404 (Not Found)
statusbar.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
StatusBarProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
SplashScreenProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
splashscreen.js Failed to load resource: the server responded with a status of 404 (Not Found)
DeviceProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
keyboard.js Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1297 Uncaught Error: Module cordova-plugin-device.device does not exist.
    at addEntry (cordova.js:1297)
    at Object.exports.clobbers (cordova.js:1307)
    at onScriptLoadingComplete (cordova.js:1551)
    at HTMLScriptElement.scriptLoadedCallback (cordova.js:1584)
addEntry @ cordova.js:1297
exports.clobbers @ cordova.js:1307
onScriptLoadingComplete @ cordova.js:1551
scriptLoadedCallback @ cordova.js:1584
cordova.js:1582 [Violation] 'error' handler took 177ms
main.css Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1051 deviceready has not fired after 5 seconds.
cordova.js:1044 Channel not fired: onPluginsReady
cordova.js:1044 Channel not fired: onCordovaReady
</code>```

答: Make sure all your files are copied there. If possible, install AWS CLI and clear your existing files in the bucket. Now, try aws s3 cp  s3:/// --recursive. Hope it helps you</p>

Body:
I have created a simple app using ionic2 framework and is working well in local machine/behind a simple 'lite-server'

I wanted to deploy the same in AWS S3 - With "enable static web-hosting" and try it from mobile browsers

I ran - ionic build browser

This created a static web-page contents in \MyApp\platforms\browser\www.

I used a node tool 's3-website' - https://www.npmjs.com/package/s3-website

to publish my App content to S3

All went well, I enabled static web-hosting, had permission for everyone to view, but its not rendering.

Edited
Should the app module name "MyApp" and s3 bucket name match? curious?

In Chrome Console, I get these errors

Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
/build/main.css Failed to load resource: the server responded with a status of 404 (Not Found)
device.js Failed to load resource: the server responded with a status of 404 (Not Found)
statusbar.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
StatusBarProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
SplashScreenProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
splashscreen.js Failed to load resource: the server responded with a status of 404 (Not Found)
DeviceProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
keyboard.js Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1297 Uncaught Error: Module cordova-plugin-device.device does not exist.
    at addEntry (cordova.js:1297)
    at Object.exports.clobbers (cordova.js:1307)
    at onScriptLoadingComplete (cordova.js:1551)
    at HTMLScriptElement.scriptLoadedCallback (cordova.js:1584)
addEntry @ cordova.js:1297
exports.clobbers @ cordova.js:1307
onScriptLoadingComplete @ cordova.js:1551
scriptLoadedCallback @ cordova.js:1584
cordova.js:1582 [Violation] 'error' handler took 177ms
main.css Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1051 deviceready has not fired after 5 seconds.
cordova.js:1044 Channel not fired: onPluginsReady
cordova.js:1044 Channel not fired: onCordovaReady


问:
What is the proper way of adding a custom field to Keystone (to be included in an admin UI form)?
I can see the nice explanation for fields, and what they are made of, here: https://github.com/keystonejs/keystone/tree/v4.0.0-beta.5/fields

How do you go about adding a custom field?

Is adding a custom field (versioned in my own project which depends on keystone, or perhaps done generic enough that could be pushed to npm) a matter of importing it during the keystone setup script and somehow mutating the keystone instance or whatever in order that it also loads my field along with the built-in ones?

EDIT:

The use case is in the context of the admin UI (e.g. you have a User keystone model, and you want the User form to have a new custom field whose UI is an arbitrary react component you implement)

答:
The framework does support storage fields like local file, s3, azure, cloudinary images and embedly fields. That might satisfy your file field needs.

Custom Fields

It appears that the keystone wiki has a short tutorial on the keystonejs wiki and at time of writing, custom types aren't supported in the admin UI.

The example code in the wiki includes a validation method for a credit card number, so this might be the type of functionality that you're looking for.

Here's a short example of what a custom type would look like. It's a field that only accepts Jeff or Alexander as a valid value. You would put it in its own myNameType.js file.

```<code>var keystone = require('keystone');
var util = require('util');

/*
    Custom FieldType Constructor
    @extends Field
    @api public
*/
function myName(list, path, options) {
    // add your options to this
    // call super_
    this._nativeType = Text;
    myName.super_.call(this, list, path, options);
}

/* inherit Field */
util.inherits(myName, keystone.Field);

/* override or add methods */
myName.prototype.validateInput = function(data) {
    console.log('validate my name');
    var isValid = false;

    if (data && (data.toLower() === 'jeff' || data.toLower() === 'alexander')) {
        isValid = true;
    }

    return isValid;
};
</code>```

Then register your type in the keystonejs startup file:

```<code>// Require keystone
var keystone = require('keystone');

 // add a new custom Field Type
Object.defineProperty(
    keystone.Field.Types,
    'MyName',
    {
        get: function() {
            // or whatever your path is
            return require('./myName.js');
        }
    }
);
</code>```

From there you can use it in a model (remember to set it to hidden because of the lack of admin UI support):

```<code>var keystone = require('keystone');
var Types = keystone.Field.Types;

var Person = new keystone.List('Post', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true },
    sortable: 'unshift',
    perPage: 5,
    track: true,
    autocreate: true
});

Person.add({
    name: { type: Types.MyName, label: 'My Name', hidden: true },
    heightInInches: { type: Types.Number, label: 'Height (inches)' },
});

Person.register();
</code>```

Body:
The framework does support storage fields like local file, s3, azure, cloudinary images and embedly fields. That might satisfy your file field needs.

Custom Fields

It appears that the keystone wiki has a short tutorial on the keystonejs wiki and at time of writing, custom types aren't supported in the admin UI.

The example code in the wiki includes a validation method for a credit card number, so this might be the type of functionality that you're looking for.

Here's a short example of what a custom type would look like. It's a field that only accepts Jeff or Alexander as a valid value. You would put it in its own myNameType.js file.

var keystone = require('keystone');
var util = require('util');

/*
    Custom FieldType Constructor
    @extends Field
    @api public
*/
function myName(list, path, options) {
    // add your options to this
    // call super_
    this._nativeType = Text;
    myName.super_.call(this, list, path, options);
}

/* inherit Field */
util.inherits(myName, keystone.Field);

/* override or add methods */
myName.prototype.validateInput = function(data) {
    console.log('validate my name');
    var isValid = false;

    if (data && (data.toLower() === 'jeff' || data.toLower() === 'alexander')) {
        isValid = true;
    }

    return isValid;
};

Then register your type in the keystonejs startup file:

// Require keystone
var keystone = require('keystone');

 // add a new custom Field Type
Object.defineProperty(
    keystone.Field.Types,
    'MyName',
    {
        get: function() {
            // or whatever your path is
            return require('./myName.js');
        }
    }
);

From there you can use it in a model (remember to set it to hidden because of the lack of admin UI support):

var keystone = require('keystone');
var Types = keystone.Field.Types;

var Person = new keystone.List('Post', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true },
    sortable: 'unshift',
    perPage: 5,
    track: true,
    autocreate: true
});

Person.add({
    name: { type: Types.MyName, label: 'My Name', hidden: true },
    heightInInches: { type: Types.Number, label: 'Height (inches)' },
});

Person.register();


问:
Razorpay ionic 3 callback issue
I will implement razorpay with ionic 3 app everything works find, i got successcallback with payment_id but after that nothing happenig like redirect to other page or route or any other activity or calling functions etc.

I am refer following link,

https://github.com/razorpay/razorpay-cordova-sample-app/tree/master/rzp-ionic2-example

Here is my code,

```<code>var options = {
      description: 'Credits towards consultation',
      image: 'https://i.imgur.com/3g7nmJC.png',
      currency: 'INR',
      key: 'rzp_test_1DP5mmOlF5G5ag',
      amount: '5000',
      name: 'foo',
      prefill: {
        email: 'pranav@razorpay.com',
        contact: '8879524924',
        name: 'Pranav Gupta'
      },
      theme: {
        color: '#F37254'
      },
      modal: {
        ondismiss: function() {
          alert('dismissed')
        }
      }
    };

    var successCallback = function(payment_id) {
      alert('payment_id: ' + payment_id);
      this.navCtrl.push("ThankyouPage",{
              status: this.status
          });
    };

    var cancelCallback = function(error) {
      alert(error.description + ' (Error ' + error.code + ')');
    };

    this.platform.ready().then(() => {
      RazorpayCheckout.open(options, successCallback, cancelCallback);
    })
</code>```

答:
Another solution to this problem can be assigning this variable to some other variable and using it in the callback like - </p>

```<code>let me = this;

var successCallback = function(payment_id) {
    alert('payment_id: ' + payment_id);
    me.navCtrl.push("ThankyouPage",{
        status: me.status
    });
};
</code>```

Title: Razorpay ionic 3 callback issue

Body:
I will implement razorpay with ionic 3 app everything works find, i got successcallback with payment_id but after that nothing happenig like redirect to other page or route or any other activity or calling functions etc.

I am refer following link,

https://github.com/razorpay/razorpay-cordova-sample-app/tree/master/rzp-ionic2-example

Here is my code,

var options = {
      description: 'Credits towards consultation',
      image: 'https://i.imgur.com/3g7nmJC.png',
      currency: 'INR',
      key: 'rzp_test_1DP5mmOlF5G5ag',
      amount: '5000',
      name: 'foo',
      prefill: {
        email: 'pranav@razorpay.com',
        contact: '8879524924',
        name: 'Pranav Gupta'
      },
      theme: {
        color: '#F37254'
      },
      modal: {
        ondismiss: function() {
          alert('dismissed')
        }
      }
    };

    var successCallback = function(payment_id) {
      alert('payment_id: ' + payment_id);
      this.navCtrl.push("ThankyouPage",{
              status: this.status
          });
    };

    var cancelCallback = function(error) {
      alert(error.description + ' (Error ' + error.code + ')');
    };

    this.platform.ready().then(() => {
      RazorpayCheckout.open(options, successCallback, cancelCallback);
    })

Body:
Another solution to this problem can be assigning this variable to some other variable and using it in the callback like -

let me = this;

var successCallback = function(payment_id) {
    alert('payment_id: ' + payment_id);
    me.navCtrl.push("ThankyouPage",{
        status: me.status
    });
};


问:
Disable validation in xsd:anyType element
Having following XML Schema with a element of type xs:anyType.

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="payloadAny" type="xs:anyType"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

Any example of an XML:

```<code><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <payloadAny>
        <anything>anyContent</anything>
    </payloadAny>
</root>
</code>```

We now discovered the problem when in the  element is the xsi:type attribute like this:

```<code><root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <payloadAny>
        <anything xsi:type="ForeignType">anyContent</anything>
    </payloadAny>
</root>
</code>```

This XML having the xsi:type attribute does not validate anymore against the XML Schema with the xs:anyType element.

E [Xerces] cvc-elt.4.2: Cannot resolve 'ForeignType' to a type definition for element 'anything'.

When using the <xs:any/> element instead of the <element type="xs:anyType"/>, the validation can be disabled using the processContents attribute.

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:complexType name="any">
        <xs:sequence>
            <xs:any processContents="skip"/>
        </xs:sequence>
    </xs:complexType>
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="payloadAny" type="any"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

The questions are now the following:

How to disable the xsi:type validation in a xs:anyType element (like processContents="skip)

Why is there such difference in a <xs:any/> vs. <element type="xs:anyType"/>

答:
How to disable the xsi:type validation in a xs:anyType element (like processContents="skip")

With the element and type structure you have defined in your schema, the validation of the xsi:type attribute by the schema processor cannot be disabled.  A declaration for xsi:type is built in to every conforming XSD schema validator, and whenever an element with an xsi:type attribute is validated either strictly or laxly, that declaration will be found and the xsi:type attribute will be validated against it.  A valid xsi:type attribute has a QName value which identifies a type definition in the schema.  If the QName value does not identify a type definition, the attribute is invalid.

From the error message you are reporting, it appears that your schema contains no type whose expanded name is {}ForeignType.

One way to work around it would be to declare the type you appear to really want for the payloadAny element, which is not xs:anyType but a different type with a skip wildcard.  Your second schema example shows the principle, although your {}any type differs from xs:anyType in allowing only one element child, instead of allowing many elements and also character data. (If you only want one element as child of payloadAny, then xs:anyType is too loose.)

Note that the error reported is not a claim that the anything element is invalid against the type ForeignType, but a report that the xsi:type attribute is itself invalid, because it violates clause 4.2 of the constraint Element Locally Valid.  That in turn makes payloadAny invalid.

Why is there such difference in a <xs:any/> vs. <element type="xs:anyType"/>

The built-in type xs:anyType behaves (roughly) as though declared with the following declaration shown in the XSD 1.0 schema for schema documents:

```<code><xs:complexType name="anyType" mixed="true">
  <xs:annotation>
    <xs:documentation>
      Not the real urType, but as close an approximation as we can
      get in the XML representation</xs:documentation>
  </xs:annotation>
  <xs:sequence>
    <xs:any minOccurs="0"
            maxOccurs="unbounded"
            processContents="lax"/>
  </xs:sequence>
  <xs:anyAttribute processContents="lax"/>
</code>```

There are no parameterization mechanisms for complex types analogous to the processContents and other attributes on xs:any.  Adding such mechanisms for xs:anyType would have required additional ad hoc mechanisms (is XSD not complicated enough for you?  you want more?) and would not have increased the expressive power of the language.

As design decisions go, that one looks pretty much like a no-brainer.   Even the XML Schema working group (never one to regard ad hoc machinery with much skepticism) thought such special-purpose machinery unnecessary.

In a schema language built on attribute grammars, where inherited attributes can serve to parameterize elements and/or types, such machinery would be a natural part of the language and having parameters for lax/strict/skip processing might make sense.  But neither XSD nor any other schema language in wide use is built on attribute grammars.

Body:
Having following XML Schema with a element of type xs:anyType.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="payloadAny" type="xs:anyType"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Any example of an XML:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <payloadAny>
        <anything>anyContent</anything>
    </payloadAny>
</root>

We now discovered the problem when in the  element is the xsi:type attribute like this:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <payloadAny>
        <anything xsi:type="ForeignType">anyContent</anything>
    </payloadAny>
</root>

This XML having the xsi:type attribute does not validate anymore against the XML Schema with the xs:anyType element.

E [Xerces] cvc-elt.4.2: Cannot resolve 'ForeignType' to a type definition for element 'anything'.

When using the <xs:any/> element instead of the <element type="xs:anyType"/>, the validation can be disabled using the processContents attribute.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:complexType name="any">
        <xs:sequence>
            <xs:any processContents="skip"/>
        </xs:sequence>
    </xs:complexType>
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="payloadAny" type="any"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

The questions are now the following:

How to disable the xsi:type validation in a xs:anyType element (like processContents="skip)

Why is there such difference in a <xs:any/> vs. <element type="xs:anyType"/>

Body:
How to disable the xsi:type validation in a xs:anyType element (like processContents="skip")

With the element and type structure you have defined in your schema, the validation of the xsi:type attribute by the schema processor cannot be disabled.  A declaration for xsi:type is built in to every conforming XSD schema validator, and whenever an element with an xsi:type attribute is validated either strictly or laxly, that declaration will be found and the xsi:type attribute will be validated against it.  A valid xsi:type attribute has a QName value which identifies a type definition in the schema.  If the QName value does not identify a type definition, the attribute is invalid.

From the error message you are reporting, it appears that your schema contains no type whose expanded name is {}ForeignType.

One way to work around it would be to declare the type you appear to really want for the payloadAny element, which is not xs:anyType but a different type with a skip wildcard.  Your second schema example shows the principle, although your {}any type differs from xs:anyType in allowing only one element child, instead of allowing many elements and also character data. (If you only want one element as child of payloadAny, then xs:anyType is too loose.)

Note that the error reported is not a claim that the anything element is invalid against the type ForeignType, but a report that the xsi:type attribute is itself invalid, because it violates clause 4.2 of the constraint Element Locally Valid.  That in turn makes payloadAny invalid.

Why is there such difference in a <xs:any/> vs. <element type="xs:anyType"/>

The built-in type xs:anyType behaves (roughly) as though declared with the following declaration shown in the XSD 1.0 schema for schema documents:

<xs:complexType name="anyType" mixed="true">
  <xs:annotation>
    <xs:documentation>
      Not the real urType, but as close an approximation as we can
      get in the XML representation</xs:documentation>
  </xs:annotation>
  <xs:sequence>
    <xs:any minOccurs="0"
            maxOccurs="unbounded"
            processContents="lax"/>
  </xs:sequence>
  <xs:anyAttribute processContents="lax"/>

There are no parameterization mechanisms for complex types analogous to the processContents and other attributes on xs:any.  Adding such mechanisms for xs:anyType would have required additional ad hoc mechanisms (is XSD not complicated enough for you?  you want more?) and would not have increased the expressive power of the language.

As design decisions go, that one looks pretty much like a no-brainer.   Even the XML Schema working group (never one to regard ad hoc machinery with much skepticism) thought such special-purpose machinery unnecessary.

In a schema language built on attribute grammars, where inherited attributes can serve to parameterize elements and/or types, such machinery would be a natural part of the language and having parameters for lax/strict/skip processing might make sense.  But neither XSD nor any other schema language in wide use is built on attribute grammars.


问:
How to avoid duplicate file upload but keep the uploader unaware of it?
First of all, I apologize if the question is not clear, I'm explaining it below.

For every file uploaded, I'm renaming the file and recording the hash values (using sha1_files function, please suggest if there are some better or faster hashing techniques for the file in php) in a separate DB table and checking the hash of every new file to avoid duplicate files.

In this manner, the one uploading a duplicate file will get an error msg and the file won't be uploaded.

My question is, is there any techniques or algorithm by which I can prevent duplicate file upload but the duplicate file uploader will be unaware of it and will find the file in his/her account with a different name than the one already present. However, users won't be able to upload banned files by any means.

答:
Yes, you should use xxhash which is much faster than sha1.

According to their benchmarks:

The benchmark uses SMHasher speed test, compiled with Visual 2010 on a
  Windows Seven 32-bits box. The reference system uses a Core 2 Duo
  @3GHz

SHA1-32 is 0.28 GB/s fast, and xxHash is 5.4 GB/s.

The PHP library is only getting a string as input, so you should use the binary library, and have something like this in your PHP:

```<code>list($hash) = explode(" ", shell_exec("/path/to/xxHash/xxhsum " . escapeshellarg($filePath)));
echo $hash;
</code>```

Installing xxhash:

```<code>$ wget https://codeload.github.com/Cyan4973/xxHash/tar.gz/v0.6.3 -O xx.tar.gz
$ tar xvzf xx.tar.gz
$ cd xxHash-0.6.3; make
</code>```

Body:
Yes, you should use xxhash which is much faster than sha1.

According to their benchmarks:

The benchmark uses SMHasher speed test, compiled with Visual 2010 on a
  Windows Seven 32-bits box. The reference system uses a Core 2 Duo
  @3GHz

SHA1-32 is 0.28 GB/s fast, and xxHash is 5.4 GB/s.

The PHP library is only getting a string as input, so you should use the binary library, and have something like this in your PHP:

list($hash) = explode(" ", shell_exec("/path/to/xxHash/xxhsum " . escapeshellarg($filePath)));
echo $hash;

Installing xxhash:

$ wget https://codeload.github.com/Cyan4973/xxHash/tar.gz/v0.6.3 -O xx.tar.gz
$ tar xvzf xx.tar.gz
$ cd xxHash-0.6.3; make


问:
How to Shadow DOM, if I want to perserve event from outside, but prevent custom event bubbling
I am trying to use Shadow DOM to encapsulate custom event bubbling but still get the styles from outside.

I have tried to use slot and found that preserve the outside styles, but cannot encapsulate events.

I have tried to directly append child to shadowroot, but then I lost all the outside styles.

So what I want to achieve is that ...

the outside styles can bleed in, in this case span will get color: red

the custom event 'span-clicked' is blocked by the boundary of the component

the standard events (such as click) will see the entire component as srcElement

Is there a way that I can achieve all three above? Thank you very much!

var outer = document.getElementById('outer');
var shadowroot = outer.attachShadow({mode: 'open'});

shadowroot.innerHTML = `
  <slot></slot>
`;

var spanInsideShadow = document.getElementById('span_inside_shadow');
shadowroot.appendChild(spanInsideShadow);

var spanInLightDom = document.getElementById('span_in_slot');

spanInsideShadow.addEventListener('click', function(e){
  spanInsideShadow.dispatchEvent(new Event('span-clicked', {bubbles: true}));
});

outer.addEventListener('span-clicked', function(e){
  console.log('outer received custom event. Do not want this!');
});

outer.addEventListener('click', function(e){
  console.log('click event received, source elem = ', e.srcElement);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  color: red;
}</code>```

     SPAN_IN_LIGHT_DOM_BUT_RENDERED_IN_SLOT

A_NORMAL_SPAN_OUTSIDE

SPAN_WILL_BE_APPENDED_TO_SHAODOW_ROOT

```

I hope I am explaining myself clear enough. Thank you very much for your help!

Body:
I am trying to use Shadow DOM to encapsulate custom event bubbling but still get the styles from outside.

I have tried to use slot and found that preserve the outside styles, but cannot encapsulate events.

I have tried to directly append child to shadowroot, but then I lost all the outside styles.

So what I want to achieve is that ...

the outside styles can bleed in, in this case span will get color: red

the custom event 'span-clicked' is blocked by the boundary of the component

the standard events (such as click) will see the entire component as srcElement

Is there a way that I can achieve all three above? Thank you very much!

var outer = document.getElementById('outer');
var shadowroot = outer.attachShadow({mode: 'open'});

shadowroot.innerHTML = `
  <slot></slot>
`;

var spanInsideShadow = document.getElementById('span_inside_shadow');
shadowroot.appendChild(spanInsideShadow);

var spanInLightDom = document.getElementById('span_in_slot');

spanInsideShadow.addEventListener('click', function(e){
  spanInsideShadow.dispatchEvent(new Event('span-clicked', {bubbles: true}));
});

outer.addEventListener('span-clicked', function(e){
  console.log('outer received custom event. Do not want this!');
});

outer.addEventListener('click', function(e){
  console.log('click event received, source elem = ', e.srcElement);
});

span {
  color: red;
}

     SPAN_IN_LIGHT_DOM_BUT_RENDERED_IN_SLOT

A_NORMAL_SPAN_OUTSIDE

SPAN_WILL_BE_APPENDED_TO_SHAODOW_ROOT

I hope I am explaining myself clear enough. Thank you very much for your help!

Body:
The only way to auto-convert your event target and to get outside styles into Shadow DOM is to include all of the DOM and the CSS in the Shadow DOM. And not by using <slot>.

If you are loading an external CSS file through the <link> tag then you can include that same <link> tag in your shadow DOM.

If you are including a <style> tag in your main page then you need to include a clone of that <style> tag inside your shadow DOM.

As I write this, the only other option you have is to use CSS variables that will allow the outside world to change values of the inner CSS. But then you have to write your CSS to use variables.

No matter which way you chose you can only affect the styling of elements within the Shadow DOM if you copy those styles in or affect them through CSS variables. If you don't include some new, unexpected, CSS then it will not be applied.

And since you want the Shadow DOM to convert the target of your events you must place the DOM inside the shadow and not by using <slot>.

There are other methods being worked on, but those won't be out for some time. Probably several years.

I hope this answers your question. Unfortunately I don't think this is what you wanted to find out.


问:
How to ensure Makefile variable is set as a prerequisite?
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

```<code>ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"
</code>```

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

```<code>deploy: make-sure-ENV-variable-is-set
</code>```

答:
This will cause a fatal error if ENV is undefined and something needs it (in GNUMake, anyway).

```
.PHONY: deploy check-env

deploy: check-env
	...

other-thing-that-needs-env: check-env
	...

check-env:
ifndef ENV
	$(error ENV is undefined)
endif
```

(Note that ifndef and endif are not indented - they control what make "sees", taking effect before the Makefile is run. "$(error" is indented with a tab so that it only runs in the context of the rule.)

ContentLicense: CC BY-SA 4.0

Body:
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

deploy: make-sure-ENV-variable-is-set

Body:
This will cause a fatal error if ENV is undefined and something needs it (in GNUMake, anyway).

.PHONY: deploy check-env

deploy: check-env
	...

other-thing-that-needs-env: check-env
	...

check-env:
ifndef ENV
	$(error ENV is undefined)
endif

(Note that ifndef and endif are not indented - they control what make "sees", taking effect before the Makefile is run. "$(error" is indented with a tab so that it only runs in the context of the rule.)


问:
Firebase Hosting: Connect with own AWS backend
Is it possible to connect my firebase hosted app with my backend hosted in an aws ec2 instance? Is it possible to use the ssl certificate from firebase? Or can I use the certificate from aws Certificate Manager?</p>

答:
You can call out to your own hosted backend via XHR (using CORS) or you can connect your Firebase Hosting site to a Cloud Function which would then be able to proxy to your ec2 instance. You cannot directly connect Firebase Hosting with AWS.

The certificate used for Firebase Hosting cannot be reused for other purposes, and you cannot upload your own certificate (from e.g. Certificate Manager) into Firebase Hosting.


问:
How to get hard drive unique serial number in C#
I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.

```<code>private string getHardDiskID()
{
     string hddID = null;
     ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
     ManagementObjectCollection moc = mc.GetInstances();
     foreach (ManagementObject strt in moc)
     {
         hddID += Convert.ToString(strt["VolumeSerialNumber"]);
     }
     return hddID.Trim().ToString();
}
</code>```

But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...?
Thanks in advance..

答:
```<code>ManagementObjectSearcher searcher;

searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
        string serial_number="";

        foreach (ManagementObject wmi_HD in searcher.Get())
        {

             serial_number = wmi_HD["SerialNumber"].ToString();

        }

        MessageBox.Show(serial_number);
</code>```

Body:
I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.

private string getHardDiskID()
{
     string hddID = null;
     ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
     ManagementObjectCollection moc = mc.GetInstances();
     foreach (ManagementObject strt in moc)
     {
         hddID += Convert.ToString(strt["VolumeSerialNumber"]);
     }
     return hddID.Trim().ToString();
}

But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...?
Thanks in advance..


问:
MVC Bundle not working with Release Configuration (Debug is False), CSS and JS not loading
When I release MVC.Net application using release mode, the below setting will be available in the web.config file.

```<code><compilation debug="false" targetFramework="4.5" />
</code>```

When we do the above, the site loaded with CSS and JavaScript and developer tools show the bunch of URL bundles returning 404 errors.

I have also tried the below code which also not loading the script and style sheets.

```<code>BundleTable.EnableOptimizations = true;
</code>```

Can someone help me fix this issue? Due to the above issues, my application is running into Caching issue with script and CSS file. Each of my new releases, I have to ask my customers to clear the browser cache to make sure that new functionalities are working fine.

答: Check that the files are included correctly in the solution to be deployed (right click on the file and select properties).</p>

Body:
When I release MVC.Net application using release mode, the below setting will be available in the web.config file.

<compilation debug="false" targetFramework="4.5" />

When we do the above, the site loaded with CSS and JavaScript and developer tools show the bunch of URL bundles returning 404 errors.

I have also tried the below code which also not loading the script and style sheets.

BundleTable.EnableOptimizations = true;

Can someone help me fix this issue? Due to the above issues, my application is running into Caching issue with script and CSS file. Each of my new releases, I have to ask my customers to clear the browser cache to make sure that new functionalities are working fine.


问:
Bash, cut word with dot character from string
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

```<code>echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5
</code>```

But I ended up with:

2017.11.13

How can I get the result I want?

答:
This solution is a bit more reusable than the previous ones offered:

```<code>awk '/^Log/{ split($3,x,"."); print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] };'
</code>```

This looks for all lines starting with Log, then grabs the 3rd column which contains squid.log.2017.11.13 and utilizes the the split built-in to break up the string in to array x using the . as the delimiter. Once we have our array x, we know that the last 3 values will always be the date, and this will work regardless of the rest of the string, (even if squid.log was something different) - we can use the length built-in to make sure we only get the last three elements.

Then we just print our reformatted string print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] - reinserting the .'s in the appropriate places since they were stripped by using them as the split delimiter.

Output:
Log for: 2017.11.13

Body:
I have a string:

Log for: squid.log.2017.11.13

I need to cut out squid.log. so that I see:

Log for: 2017.11.13

I tried to cut

echo "Log for: squid.log.2017.11.13" | cut -d'.' -f3-5

But I ended up with:

2017.11.13

How can I get the result I want?

Body:
This solution is a bit more reusable than the previous ones offered:

awk '/^Log/{ split($3,x,"."); print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] };'

This looks for all lines starting with Log, then grabs the 3rd column which contains squid.log.2017.11.13 and utilizes the the split built-in to break up the string in to array x using the . as the delimiter. Once we have our array x, we know that the last 3 values will always be the date, and this will work regardless of the rest of the string, (even if squid.log was something different) - we can use the length built-in to make sure we only get the last three elements.

Then we just print our reformatted string print $1" "$2" "x[length(x)-2]"."x[length(x)-1]"."x[length(x)] - reinserting the .'s in the appropriate places since they were stripped by using them as the split delimiter.

Output:
Log for: 2017.11.13


问:
How can I execute a .Net application during a VSTS build task?
I currently have a .Net console application that I use to perform build and release tasks. At the moment I run this application locally using PowerShell. The application effectively moves data between databases via web services.

I'm looking to automate build and release tasks using VSTS. It wasn't clear to me how I could run my console application in VSTS. I want to use my application in multiple projects.

This documentation suggests JavaScript build tasks can be created - but I don't really want to port my code.

Is there somewhere I can upload my console application into VSTS that I can then call using a PowerShell build task? Or can I create a bespoke build task that allows .Net code? Should I checkin my application as code?

How can I execute a .Net application during a VSTS build task?

答:
Couple of options. You could create a custom task and package the exe in the task.

Option two is commit the exe to source in a tools folder.

Option three. Store in blob storage and pull during your build.

Once it is on the machine you can use either the PowerShell or the Command Line task to run it.


问:
PHP oci timeout?
I would like to set a timeout on a query

```<code>$statement = oci_parse($conn, $query);
oci_execute($statement); // timeout if this takes over 5 minutes
</code>```

this is was asked before but all the way back in 11 with no solid answer

Run a sql query with a timeout in PHP or How in PHP, to stop a sql query once already begun?

I found this request too from last year
https://bugs.php.net/bug.php?id=73038

答:
The PHP OCI driver does not support query time outs (via PDO::ATTR_TIMEOUT) at the interface with the Oracle library. Thus, there is no direct user-land means to accomplish this.

The standard way to do this would be to execute a separate process that itself has a timeout. You might go about it like so:

```<code>// oci8-exec.php
set_time_limit(300); // 5 minutes
$conn = getDatabaseConnection();
$stmt = oci_parse($conn, $_SERVER['argv'][1]);
oci_execute($stmt);
oci_fetch_all($stmt, $rows);
var_export($rows);
</code>```

then in your code do:

```<code>$rows = shell_exec('oci8-exec.php "select * from foo"');
</code>```

Obviously you would need to have error handling, exit code checking, etc. to make this production ready.

Title: PHP oci timeout?

Body:
I would like to set a timeout on a query

$statement = oci_parse($conn, $query);
oci_execute($statement); // timeout if this takes over 5 minutes

this is was asked before but all the way back in 11 with no solid answer

Run a sql query with a timeout in PHP or How in PHP, to stop a sql query once already begun?

I found this request too from last year
https://bugs.php.net/bug.php?id=73038

Body:
The PHP OCI driver does not support query time outs (via PDO::ATTR_TIMEOUT) at the interface with the Oracle library. Thus, there is no direct user-land means to accomplish this.

The standard way to do this would be to execute a separate process that itself has a timeout. You might go about it like so:

// oci8-exec.php
set_time_limit(300); // 5 minutes
$conn = getDatabaseConnection();
$stmt = oci_parse($conn, $_SERVER['argv'][1]);
oci_execute($stmt);
oci_fetch_all($stmt, $rows);
var_export($rows);

then in your code do:

$rows = shell_exec('oci8-exec.php "select * from foo"');

Obviously you would need to have error handling, exit code checking, etc. to make this production ready.


问:
How to build a sequence in the method calls of a fluent interface
Hi I would like to build a fluent interface for creating am object some sort of factory or builder.

I understand that I have to "return this" in order to make the methods chainable.

```<code>public class CarBuilder
{

   public  CarBuilder()
   {
       car = new Car();
   }
    private Car car;

    public CarBuilder AddEngine(IEngineBuilder engine)
    {
        car.Engine = engine.Engine();
        return this;
    }

    public CarBuilder AddWheels(IWheelsBuilder wheels)
    {
        car.Wheels = wheels.Wheels();
        return this;
    }
    public CarBuilder AddFrame(IFrameBuilder frame)
    {
        car.Frame = frame.Frame();
        return this;
    }

    public Car BuildCar()
    {
        return car;
    }

}
</code>```

with this I could build a car like that:

```<code> Car c = builder.AddFrame(fBuilder).AddWheels(wBuilder).AddEngine(eBuilder).BuildCar();
</code>```

But what I need is a special sequence or workflow:
I can only build the wheels on top of the frame and when the wheels exist then I'll be able to build up the engine.
So instead of offering every method of the car builder I want to be able to add only the frame to the builder and then only the wheels to the frame and then the engine on top of that...

And how would it be or what would be a good implementation if the EngineBuilder itself has a fluent api like eBuilder.Cylinders(12).WithPistons()....

Would it be possible to have something like this

```<code>Car c = builder.AddFrame(fBuilder).AddWheels(wBuilder).AddEngine(x=>x.WithCylinders(12).WithPistons()).BuildCar();
</code>```

So in sum how to structure the flow of the fluent interface and how to nest fluent Interfaces?

答:
Instead of having a single CarBuilder class that exposes all the methods, you have multiple classes that each expose only the methods appropriate for the "state" of the car being built.

Given your example, CarBuilder would offer only AddFrame.  Instead of returning this, AddFrame returns an object of class CarBuilderWithFrame that offers only AddWheels, which returns an object of class CarBuilderWithFrameAndWheels that offers only AddEngine, which returns an object of class CarBuilderWithEverything that offers only Build.

This example is very serial, and you can argue over whether it makes sense to go through this much work for such a linear process.

An example I like is for printing.  A Printer object could return a PrintJob object that offers three methods:  Cancel, Print, or StartPage.  The StartPage method would return a Page object that gives you methods for all the drawing commands one one called EndPage that gives you the PrintJob object back.  This makes it easy to hardcode a simple print job.

```<code>Printer.StartPrintJob().StartPage().DrawText("Title").DrawIcon("logo.png").EndPage().Print();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi I would like to build a fluent interface for creating am object some sort of factory or builder.

I understand that I have to "return this" in order to make the methods chainable.

public class CarBuilder
{

   public  CarBuilder()
   {
       car = new Car();
   }
    private Car car;

    public CarBuilder AddEngine(IEngineBuilder engine)
    {
        car.Engine = engine.Engine();
        return this;
    }

    public CarBuilder AddWheels(IWheelsBuilder wheels)
    {
        car.Wheels = wheels.Wheels();
        return this;
    }
    public CarBuilder AddFrame(IFrameBuilder frame)
    {
        car.Frame = frame.Frame();
        return this;
    }

    public Car BuildCar()
    {
        return car;
    }

}

with this I could build a car like that:

 Car c = builder.AddFrame(fBuilder).AddWheels(wBuilder).AddEngine(eBuilder).BuildCar();

But what I need is a special sequence or workflow:
I can only build the wheels on top of the frame and when the wheels exist then I'll be able to build up the engine.
So instead of offering every method of the car builder I want to be able to add only the frame to the builder and then only the wheels to the frame and then the engine on top of that...

And how would it be or what would be a good implementation if the EngineBuilder itself has a fluent api like eBuilder.Cylinders(12).WithPistons()....

Would it be possible to have something like this

Car c = builder.AddFrame(fBuilder).AddWheels(wBuilder).AddEngine(x=>x.WithCylinders(12).WithPistons()).BuildCar();

So in sum how to structure the flow of the fluent interface and how to nest fluent Interfaces?

Body:
Instead of having a single CarBuilder class that exposes all the methods, you have multiple classes that each expose only the methods appropriate for the "state" of the car being built.

Given your example, CarBuilder would offer only AddFrame.  Instead of returning this, AddFrame returns an object of class CarBuilderWithFrame that offers only AddWheels, which returns an object of class CarBuilderWithFrameAndWheels that offers only AddEngine, which returns an object of class CarBuilderWithEverything that offers only Build.

This example is very serial, and you can argue over whether it makes sense to go through this much work for such a linear process.

An example I like is for printing.  A Printer object could return a PrintJob object that offers three methods:  Cancel, Print, or StartPage.  The StartPage method would return a Page object that gives you methods for all the drawing commands one one called EndPage that gives you the PrintJob object back.  This makes it easy to hardcode a simple print job.

Printer.StartPrintJob().StartPage().DrawText("Title").DrawIcon("logo.png").EndPage().Print();


问:
How to redirect users to a specific url after registration in django registration?
So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.

Here is what my main urls.py looks like:

```<code>from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',

    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^upload/', include('mysite.fileupload.urls')),
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

import os
urlpatterns += patterns('',
        (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)
</code>```

fileupload is the name of the other app I have in the project directory mysite.

This is what the backends.simple.urls looks like:

```<code>"""
URLconf for registration and activation, using django-registration's
one-step backend.

If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::

    (r'^accounts/', include('registration.backends.simple.urls')),

This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.

If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.

"""

from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView

from registration.backends.simple.views import RegistrationView

urlpatterns = patterns('',
                       url(r'^register/$',
                           RegistrationView.as_view(),
                           name='registration_register'),
                       url(r'^register/closed/$',
                           TemplateView.as_view(template_name='registration/registration_closed.html'),
                           name='registration_disallowed'),
                       (r'', include('registration.auth_urls')),
                       )
</code>```

And here is the backends.simple.views:

```<code>from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User

from registration import signals
from registration.views import RegistrationView as BaseRegistrationView

class RegistrationView(BaseRegistrationView):
    """
    A registration backend which implements the simplest possible
    workflow: a user supplies a username, email address and password
    (the bare minimum for a useful account), and is immediately signed
    up and logged in).

    """
    def register(self, request, **cleaned_data):
        username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
        User.objects.create_user(username, email, password)

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user

    def registration_allowed(self, request):
        """
        Indicate whether account registration is currently permitted,
        based on the value of the setting ``REGISTRATION_OPEN``. This
        is determined as follows:

        * If ``REGISTRATION_OPEN`` is not specified in settings, or is
          set to ``True``, registration is permitted.

        * If ``REGISTRATION_OPEN`` is both specified and set to
          ``False``, registration is not permitted.

        """
        return getattr(settings, 'REGISTRATION_OPEN', True)

    def get_success_url(self, request, user):
        return (user.get_absolute_url(), (), {})
</code>```

I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?

答:
If you wish, you can modify the following file /usr/local/lib/python2.7/dist-packages/registration/backends/simple/urls.py, changing the path, for example:

Before modifying:

```<code>success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'),
</code>```

After modifying:

```<code>success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/upload/new'),
</code>```

Regards.

Diego

Body:
So I am using django-registration app to implement a user registration page for my site. I used Django's backends.simple views which allows the users to immediately login after registration. My question is how do I redirect them to my other app's page located in the same directory as the project.

Here is what my main urls.py looks like:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',

    url(r'^accounts/', include('registration.backends.simple.urls')),
    url(r'^upload/', include('mysite.fileupload.urls')),
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

import os
urlpatterns += patterns('',
        (r'^media/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media')}),
)

fileupload is the name of the other app I have in the project directory mysite.

This is what the backends.simple.urls looks like:

"""
URLconf for registration and activation, using django-registration's
one-step backend.

If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::

    (r'^accounts/', include('registration.backends.simple.urls')),

This will also automatically set up the views in
``django.contrib.auth`` at sensible default locations.

If you'd like to customize registration behavior, feel free to set up
your own URL patterns for these views instead.

"""

from django.conf.urls import include
from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import TemplateView

from registration.backends.simple.views import RegistrationView

urlpatterns = patterns('',
                       url(r'^register/$',
                           RegistrationView.as_view(),
                           name='registration_register'),
                       url(r'^register/closed/$',
                           TemplateView.as_view(template_name='registration/registration_closed.html'),
                           name='registration_disallowed'),
                       (r'', include('registration.auth_urls')),
                       )

And here is the backends.simple.views:

from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth.models import User

from registration import signals
from registration.views import RegistrationView as BaseRegistrationView

class RegistrationView(BaseRegistrationView):
    """
    A registration backend which implements the simplest possible
    workflow: a user supplies a username, email address and password
    (the bare minimum for a useful account), and is immediately signed
    up and logged in).

    """
    def register(self, request, **cleaned_data):
        username, email, password = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1']
        User.objects.create_user(username, email, password)

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user

    def registration_allowed(self, request):
        """
        Indicate whether account registration is currently permitted,
        based on the value of the setting ``REGISTRATION_OPEN``. This
        is determined as follows:

        * If ``REGISTRATION_OPEN`` is not specified in settings, or is
          set to ``True``, registration is permitted.

        * If ``REGISTRATION_OPEN`` is both specified and set to
          ``False``, registration is not permitted.

        """
        return getattr(settings, 'REGISTRATION_OPEN', True)

    def get_success_url(self, request, user):
        return (user.get_absolute_url(), (), {})

I tried the changing the get_success_url function to just return the url I want which is /upload/new but it still redirected me to users/insert username page and gave an error. How do I redirect the user to the upload/new page where the other app resides after registration?

Body:
If you wish, you can modify the following file /usr/local/lib/python2.7/dist-packages/registration/backends/simple/urls.py, changing the path, for example:

Before modifying:

success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/'),

After modifying:

success_url = getattr (settings, 'SIMPLE_BACKEND_REDIRECT_URL', '/upload/new'),

Regards.

Diego