问:
Simple clock that counts down from 30 seconds and executes a function afterward
I have a game that gives a time limit and I need to display a countdown clock for the users and stop the game once the time is up such as 30 seconds. How can I do this in javascript?</p>

答:
Use setInterval to set up a timer. Within this timer, you can update some text in your page and when the time is up, you can call whatever function you want:

var timeLeft = 30;
    var elem = document.getElementById('some_div');

    var timerId = setInterval(countdown, 1000);

    function countdown() {
      if (timeLeft == -1) {
        clearTimeout(timerId);
        doSomething();
      } else {
        elem.innerHTML = timeLeft + ' seconds remaining';
        timeLeft--;
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="some_div">
</div></code>```

Body:
Use setInterval to set up a timer. Within this timer, you can update some text in your page and when the time is up, you can call whatever function you want:

var timeLeft = 30;
    var elem = document.getElementById('some_div');

    var timerId = setInterval(countdown, 1000);

    function countdown() {
      if (timeLeft == -1) {
        clearTimeout(timerId);
        doSomething();
      } else {
        elem.innerHTML = timeLeft + ' seconds remaining';
        timeLeft--;
      }
    }

<div id="some_div">
</div>


来源: stackexchange

问:
how to avoid karaf load the default resolve bundle
I use the karaf to run an OSGI bundle which use a built-in commons-lang3.5.jar.

The problem is when I run this bundle, the karaf will auto load another commons-lang3.1.jar. I am not sure when it be load. But it take my bundle crash.

Are there any ways to uninstall the karaf default built-in bundle?

答:
As Achim says, do not uninstall the default bundle, but do specify the your required version range.  However, I would recommend that you not use the normal OSGI version range, and instead specify [3.5.0,3.5.0].

At the moment, it is safest to only import COMMONS bundles using a point version, or using a version range starting with the lowest version that you have determined to be compatible with your code using bnd baseline or similar, and ending in the full version number of the version you're building against.

For example, ignoring all minor releases:
 between release 3.0 and 3.1 of commons-lang, the only baseline reported api changes were minors in two packages:
 org.apache.commons.lang3 and org.apache.commons.lang3.exception.

However, all packages were bumped to 3.1.0.

Between from 3.1 to 3.2, there were minor changes to several packages: a second minor level change to org.apache.commons.lang3, and initial minor changes to
  org.apache.commons.lang3.reflect, org.apache.commons.lang3.text, org.apache.commons.lang3.text.translate, and org.apache.commons.lang3.tuple.

However, there was  major change to org.apache.commons.lang3.time.

Again, all package versions were just set to 3.2.0 , except now instead of the package versions being overly restrictive , there is a now a concealed breaking change.

In other words: comparing the declared export package versions to more "accurate" package versions based on baseline-detected changes, we have the following.

Note that for packages with minor changes only, the "accurate" package version numbers reflects the number of releases with minor changes to that package, and not a package number of any particular release.

```
  Package                                | "Accurate" | Declared
------------------------------------------------------------------
= org.apache.commons.lang3               | 3.2.0      | 3.2.0
+ org.apache.commons.lang3.builder       | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.concurrent    | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.event         | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.exception     | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.math          | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.mutable       | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.reflect       | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.text          | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.text.translate| 3.1.0      | 3.2.0
* org.apache.commons.lang3.time          | 4.0.0      | 3.2.0
+ org.apache.commons.lang3.tuple         | 3.1.0      | 3.2.0
```

The package number is "correct" for 1 package, too conservative for 10 packages, and wrong for 1.
This remains unchanged if we follow the pattern all the way to 3.5 (with a second concealed MAJOR change to the time package between 3.4 and 3.5:

```
Package                                  | "Accurate" | Declared
------------------------------------------------------------------
= org.apache.commons.lang3               | 3.5.0      | 3.5.0
+ org.apache.commons.lang3.builder       | 3.3.0      | 3.5.0
+ org.apache.commons.lang3.concurrent    | 3.1.0      | 3.5.0
+ org.apache.commons.lang3.event         | 3.1.0      | 3.5.0
+ org.apache.commons.lang3.exception     | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.math          | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.mutable       | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.reflect       | 3.4.0      | 3.5.0
+ org.apache.commons.lang3.text          | 3.3.0      | 3.5.0
+ org.apache.commons.lang3.text.translate| 3.2.0      | 3.5.0
* org.apache.commons.lang3.time          | 5.0.0      | 3.5.0
+ org.apache.commons.lang3.tuple         | 3.1.0      | 3.5.0
```

[ I'm in a discussion with some of the COMMONS project people about package versions, after I opened an issue for commons-compress about OSGI version issues.  For this project, every version of every package is identical to the release number (extended to three digits), and all are in the range [1,2).

The folks commons super-project are hung up about packageinfo files being in the source directory; possibly because I added a  manual copy of the packageinfo files from the src tree, which apparently is not required anymore. They also would prefer that package versions should be generated automatically.

I haven't yet explained properly why the maven-bundle-plugin default of using the release version for every package is dangerous, and that changing a package version should be done by the person changing the source in way that changes the version (to avoid accidental breaking changes), with the baseline verify serving as a kind of unit test.

Ironically I submitted the changes as part of getting ready to merge in some substantive contributions to compress, which were made to help store every declared bundle from maven central, in order to analyze how reliable package version numbers are, and to see how much can be done to automatically fix them when using a database backed repository (and to see if there are any features of bundle series that are predictors of reliability).
]

ContentLicense: CC BY-SA 3.0

Body:
As Achim says, do not uninstall the default bundle, but do specify the your required version range.  However, I would recommend that you not use the normal OSGI version range, and instead specify [3.5.0,3.5.0].

At the moment, it is safest to only import COMMONS bundles using a point version, or using a version range starting with the lowest version that you have determined to be compatible with your code using bnd baseline or similar, and ending in the full version number of the version you're building against.

For example, ignoring all minor releases:
 between release 3.0 and 3.1 of commons-lang, the only baseline reported api changes were minors in two packages:
 org.apache.commons.lang3 and org.apache.commons.lang3.exception.

However, all packages were bumped to 3.1.0.

Between from 3.1 to 3.2, there were minor changes to several packages: a second minor level change to org.apache.commons.lang3, and initial minor changes to
  org.apache.commons.lang3.reflect, org.apache.commons.lang3.text, org.apache.commons.lang3.text.translate, and org.apache.commons.lang3.tuple.

However, there was  major change to org.apache.commons.lang3.time.

Again, all package versions were just set to 3.2.0 , except now instead of the package versions being overly restrictive , there is a now a concealed breaking change.

In other words: comparing the declared export package versions to more "accurate" package versions based on baseline-detected changes, we have the following.

Note that for packages with minor changes only, the "accurate" package version numbers reflects the number of releases with minor changes to that package, and not a package number of any particular release.

  Package                                | "Accurate" | Declared
------------------------------------------------------------------
= org.apache.commons.lang3               | 3.2.0      | 3.2.0
+ org.apache.commons.lang3.builder       | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.concurrent    | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.event         | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.exception     | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.math          | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.mutable       | 3.0.0      | 3.2.0
+ org.apache.commons.lang3.reflect       | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.text          | 3.1.0      | 3.2.0
+ org.apache.commons.lang3.text.translate| 3.1.0      | 3.2.0
* org.apache.commons.lang3.time          | 4.0.0      | 3.2.0
+ org.apache.commons.lang3.tuple         | 3.1.0      | 3.2.0

The package number is "correct" for 1 package, too conservative for 10 packages, and wrong for 1.
This remains unchanged if we follow the pattern all the way to 3.5 (with a second concealed MAJOR change to the time package between 3.4 and 3.5:

Package                                  | "Accurate" | Declared
------------------------------------------------------------------
= org.apache.commons.lang3               | 3.5.0      | 3.5.0
+ org.apache.commons.lang3.builder       | 3.3.0      | 3.5.0
+ org.apache.commons.lang3.concurrent    | 3.1.0      | 3.5.0
+ org.apache.commons.lang3.event         | 3.1.0      | 3.5.0
+ org.apache.commons.lang3.exception     | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.math          | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.mutable       | 3.2.0      | 3.5.0
+ org.apache.commons.lang3.reflect       | 3.4.0      | 3.5.0
+ org.apache.commons.lang3.text          | 3.3.0      | 3.5.0
+ org.apache.commons.lang3.text.translate| 3.2.0      | 3.5.0
* org.apache.commons.lang3.time          | 5.0.0      | 3.5.0
+ org.apache.commons.lang3.tuple         | 3.1.0      | 3.5.0

[ I'm in a discussion with some of the COMMONS project people about package versions, after I opened an issue for commons-compress about OSGI version issues.  For this project, every version of every package is identical to the release number (extended to three digits), and all are in the range [1,2).

The folks commons super-project are hung up about packageinfo files being in the source directory; possibly because I added a  manual copy of the packageinfo files from the src tree, which apparently is not required anymore. They also would prefer that package versions should be generated automatically.

I haven't yet explained properly why the maven-bundle-plugin default of using the release version for every package is dangerous, and that changing a package version should be done by the person changing the source in way that changes the version (to avoid accidental breaking changes), with the baseline verify serving as a kind of unit test.

Ironically I submitted the changes as part of getting ready to merge in some substantive contributions to compress, which were made to help store every declared bundle from maven central, in order to analyze how reliable package version numbers are, and to see how much can be done to automatically fix them when using a database backed repository (and to see if there are any features of bundle series that are predictors of reliability).
]


问:
CSS and modifying div's width if radio button checked
JavaScript not accepted this time.

So, I have this CSS code. This code should change to width if radio button is checked. Nothing happens. How could I modify the code?

```<code>input[type="radio"]#someID-1:checked #extra { width: 4000px; }
</code>```

I also have this HTML code:

```<code><div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
  <div style="display: inline-block">
    <div style="DISPLAY:INLINE-BLOCK">
      <input id="someID-1" name="nappi" type="radio">
      <div class="listaus-sisalto" style="float:left;width:0">
        <div id="navi3">
          <div style="z-index:100;position:fixed;right:0;top:300px">
            <span><label for="someID-1">1</label></span>
          </div>
        </div>
      </div>
      <div class="kierros" style="display: inline-block;width:350px">
        R1
      </div>
    </div>
    <div style="DISPLAY:INLINE-BLOCK">
      <input id="someID-5" name="nappi" type="radio">
      <div class="listaus-sisalto" style="float:right;width:0">
        <div id="navi5"></div>
      </div>
      <div class="kierros" id="extra" style="display: inline-block;width:70px">
        extra
      </div>
    </div>
    <input id="someID-100" name="nappi" type="radio">
    <div class="listaus-sisalto" style="float:right;width:0">
      <div id="navi100"></div>
    </div>
    <div style="z-index:99;width:70px;position:fixed;left:0;top:100px;margin:auto;background-color:red">
      <br>
    </div>
    <div style="z-index:99;width:70px;position:fixed;right:0;top:100px;margin:auto;background-color:red">
      <br>
    </div>
  </div>
</div>
</code>```

答:
There is no child #extra of that input. Just remove that from the selector.

input[type="radio"]#someID-1:checked {
  width: 4000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
  <div style="display: inline-block">
    <!--
-->
    <DIV STYLE="DISPLAY:INLINE-BLOCK"><input name="nappi" type="radio" id="someID-1" />
      <div class="listaus-sisalto" style="float:left;width:0">
        <div id="navi3">
          <div style="z-index:100;position:fixed;right:0;top:300px"><span><label for="someID-1">1</label></span></div>
        </div>
      </div>
      <div class="kierros" style="display: inline-block;vertical-align:top;width:350px">R1
      </div>
    </DIV>
    <!--
-->
    <DIV STYLE="DISPLAY:INLINE-BLOCK"><input name="nappi" type="radio" id="someID-5" />
      <div class="listaus-sisalto" style="float:right;width:0">
        <div id="navi5">
        </div>
      </div>
      <div class="kierros" style="display: inline-block;vertical-align:top;width:70px" id="extra">extra
      </div>
    </DIV>
    <!--
--><input name="nappi" type="radio" id="someID-100" />
    <div class="listaus-sisalto" style="float:right;width:0">
      <div id="navi100">
      </div>
    </div>
    <!--

-->
    <div style="z-index:99;width:70px;position:fixed;left:0;top:100px;margin:auto;background-color:red"><br />
    </div>

    <div style="z-index:99;width:70px;position:fixed;right:0;top:100px;margin:auto;background-color:red"><br />
    </div>
  </div>
</div></code>```

Body:
JavaScript not accepted this time.

So, I have this CSS code. This code should change to width if radio button is checked. Nothing happens. How could I modify the code?

input[type="radio"]#someID-1:checked #extra { width: 4000px; }

I also have this HTML code:

      <input id="someID-1" name="nappi" type="radio">

            1

        R1

      <input id="someID-5" name="nappi" type="radio">

        extra

    <input id="someID-100" name="nappi" type="radio">

Body:
There is no child #extra of that input. Just remove that from the selector.

input[type="radio"]#someID-1:checked {
  width: 4000px;
}

<div id="kaaviotaulukko" style="white-space: nowrap; position: relative; text-align: center;">
  <div style="display: inline-block">
    <!--
-->
    <DIV STYLE="DISPLAY:INLINE-BLOCK"><input name="nappi" type="radio" id="someID-1" />
      <div class="listaus-sisalto" style="float:left;width:0">
        <div id="navi3">
          <div style="z-index:100;position:fixed;right:0;top:300px"><span><label for="someID-1">1</label></span></div>
        </div>
      </div>
      <div class="kierros" style="display: inline-block;vertical-align:top;width:350px">R1
      </div>
    </DIV>
    <!--
-->
    <DIV STYLE="DISPLAY:INLINE-BLOCK"><input name="nappi" type="radio" id="someID-5" />
      <div class="listaus-sisalto" style="float:right;width:0">
        <div id="navi5">
        </div>
      </div>
      <div class="kierros" style="display: inline-block;vertical-align:top;width:70px" id="extra">extra
      </div>
    </DIV>
    <!--
--><input name="nappi" type="radio" id="someID-100" />
    <div class="listaus-sisalto" style="float:right;width:0">
      <div id="navi100">
      </div>
    </div>
    <!--

-->
    <div style="z-index:99;width:70px;position:fixed;left:0;top:100px;margin:auto;background-color:red"><br />
    </div>

    <div style="z-index:99;width:70px;position:fixed;right:0;top:100px;margin:auto;background-color:red"><br />
    </div>
  </div>
</div>


问:
How do you put a restriction on a variable?
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

```<code><button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">

<script>
var i = 0;
    function add() {
        if(i >= 0) {
            i++;
            document.getElementById('inc').value = i;
        } else {
            i = 0;
            document.getElementById('inc').value = i;
        }

    }
        function remove() {
        i--;
        document.getElementById('inc').value = i;
    }
        </script>
</code>```

答:
try this

var i = 0;
    function add() {
        if(i >= 0) {
            i++;
            document.getElementById('inc').value = i;
        } else {
            i = 0;
            document.getElementById('inc').value = i;
        }

    };
        function remove() {
        i--;
        if(i >= 0){
        document.getElementById('inc').value = i;
        }
        else{
        return false;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc"></code>```

Body:
I am trying to make an add and remove button that has an input that has a text type and it show numbers. The add and remove button work and it will show positive numbers and negative also. I don't want it to show negative numbers. How do I make it so it can't go lower than 0? Also I do not want the input to have a number type.

Here is my code:

<button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">

Body:
try this

var i = 0;
    function add() {
        if(i >= 0) {
            i++;
            document.getElementById('inc').value = i;
        } else {
            i = 0;
            document.getElementById('inc').value = i;
        }

    };
        function remove() {
        i--;
        if(i >= 0){
        document.getElementById('inc').value = i;
        }
        else{
        return false;
        }
    }

<button onclick="add();">ADD</button>
<button onclick="remove();">REMOVE</button>
<input type="text" id="inc">


问:
Iterating an array of items with ngFor to create a NativeScript GridLayout
I'm trying to follow this tutorial:

http://www.blog.bdauria.com/?p=820

And having problem with this section:

```<code><GridLayout #boardGrid
[columns]="boardSideSpecification"
[rows]="boardSideSpecification">
<template ngFor let-item [ngForOf]="board.squares">
  <StackLayout
    [col]="item.yPosition"
    [row]="item.xPosition"
    [class]="classOf(item)">
  </StackLayout>
</template>
</code>```

The problem is that the ngFor spits out the first item but will NOT iterate any further down the array. So I end up with:

Image for: ngFor only provides first item

And the actual code to generate that with label:

```<code><GridLayout #boardGrid
            [columns]="boardSideSpecification"
            [rows]="boardSideSpecification">
    <template ngFor let-item [ngForOf]="board.squares">
        <StackLayout
                [col]="item.yPosition"
                [row]="item.xPosition"
                [class]="classOf(item)">
            <Label text="{{item.xPosition}}, {{item.yPosition}}"></Label>
        </StackLayout>
    </template>
</GridLayout>
</code>```

I've been beating my head against the wall for two days on this trying to find a reasonable fix.  Have looked at , even programmatically creating the GridLayout but everything comes with it's own special set of problems.

If anybody has any information on how to make this work I'd be ETERNALLY grateful.

Thanks!

P.S.  I guess I should mention that I have checked the validity of the rest of the code.  I AM getting the items I expect, etc.  It's all working except for that iterator.

答:
And for those poor souls that follow me down this path, here's what I came up with that worked:

```<code><GridLayout #boardGrid
            [columns]="boardSideSpecification"
            [rows]="boardSideSpecification">

    <StackLayout
            *ngFor="let item of board.squares"
            [col]="item.yPosition"
            [row]="item.xPosition"
            [class]="classOf(item)"
            (tap)="mark(item)">
        <Image
                class="state"
                [src]="item.state | squareStateImage"></Image>
    </StackLayout>

</GridLayout>
</code>```

Just Moved the ngFor from a <template> (or <ng-template>) to the StackLayout.

Still have no clue why I couldn't get a <template ngFor> to iterate and would REALLY like to know if anybody could possibly enlighten me.  But this seems to work just as well.

Body:
I'm trying to follow this tutorial:

http://www.blog.bdauria.com/?p=820

And having problem with this section:

<GridLayout #boardGrid
[columns]="boardSideSpecification"
[rows]="boardSideSpecification">
<template ngFor let-item [ngForOf]="board.squares">
  <StackLayout
    [col]="item.yPosition"
    [row]="item.xPosition"
    [class]="classOf(item)">
  </StackLayout>
</template>

The problem is that the ngFor spits out the first item but will NOT iterate any further down the array. So I end up with:

Image for: ngFor only provides first item

And the actual code to generate that with label:

<GridLayout #boardGrid
            [columns]="boardSideSpecification"
            [rows]="boardSideSpecification">
    <template ngFor let-item [ngForOf]="board.squares">
        <StackLayout
                [col]="item.yPosition"
                [row]="item.xPosition"
                [class]="classOf(item)">

        </StackLayout>
    </template>
</GridLayout>

I've been beating my head against the wall for two days on this trying to find a reasonable fix.  Have looked at , even programmatically creating the GridLayout but everything comes with it's own special set of problems.

If anybody has any information on how to make this work I'd be ETERNALLY grateful.

Thanks!

P.S.  I guess I should mention that I have checked the validity of the rest of the code.  I AM getting the items I expect, etc.  It's all working except for that iterator.

Body:
And for those poor souls that follow me down this path, here's what I came up with that worked:

<GridLayout #boardGrid
            [columns]="boardSideSpecification"
            [rows]="boardSideSpecification">

    <StackLayout
            *ngFor="let item of board.squares"
            [col]="item.yPosition"
            [row]="item.xPosition"
            [class]="classOf(item)"
            (tap)="mark(item)">
        <Image
                class="state"
                [src]="item.state | squareStateImage"></Image>
    </StackLayout>

</GridLayout>

Just Moved the ngFor from a <template> (or <ng-template>) to the StackLayout.

Still have no clue why I couldn't get a <template ngFor> to iterate and would REALLY like to know if anybody could possibly enlighten me.  But this seems to work just as well.


问:
Why is there no RAII in .NET?
Being primarily a C++ developer the absence of RAII (Resource Acquisition Is Initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of try finally or .NET's using construct) seems to be markedly inferior.

I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (struct) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.

My random searches found one argument that if a value-type is boxed it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic.
I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).

To cut a long story short my question is: are there any other reasons value types can not be used in order to introduce RAII to .NET?  (or do you think my argument about RAII's obvious advantages are flawed?)

Edit: I must have not phrased the question clearly since the first four answers have missed the point. I know about Finalize and its non-deterministic characteristics, I know about the using construct and I feel these two options are inferior to RAII. using is one more thing the consumer of a class must remember (how many people forgot to put a StreamReader in a using block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?

For instance with a generic deterministically destructible value-type I can make the using and lock keywords redundant (achievable by library classes):

```<code>    public struct Disposer<T> where T : IDisposable
    {
        T val;
        public Disposer(T t) { val = t; }
        public T Value { get { return val; } }
        ~Disposer()  // Currently illegal
        {
            if (val != default(T))
                val.Dispose();
        }
    }
</code>```

I can't help but end with a apropos quotation which I once saw but can't currently find its origin.

You can take my deterministic destruction when my cold dead hand goes out of scope.  --Anon

答:
IMHO, the big things that VB.net and C# need are:

a "using" declaration for fields, which would cause the compiler to generate code to dispose of all fields thus tagged.  The default behavior should be for the compiler to make a class implement IDisposable if it does not, or insert disposal logic before the start of the main disposal routine for any of a number of common IDisposal implementation patterns, or else use an attribute to specify that the disposal stuff should go in a routine with a particular name.

a means of deterministically disposing of objects whose constructors and/or field initializers throw an exception, either by a default behavior (calling the default disposal method) or a custom behavior (calling a method with a particular name).

For vb.net, an auto-generated method to null out all WithEvent fields.

All of those can be kludged pretty well in vb.net, and somewhat less well in C#, but first-class support for them would improve both languages.

OwnerDisplayName: Motti

ContentLicense: CC BY-SA 2.5

Title: Why is there no RAII in .NET?

Body:
Being primarily a C++ developer the absence of RAII (Resource Acquisition Is Initialization) in Java and .NET has always bothered me. The fact that the onus of cleaning up is moved from the class writer to its consumer (by means of try finally or .NET's using construct) seems to be markedly inferior.

I see why in Java there is no support for RAII since all objects are located on the heap and the garbage collector inherently doesn't support deterministic destruction, but in .NET with the introduction of value-types (struct) we have the (seemingly) perfect candidate for RAII. A value type that's created on the stack has a well defined scope and C++ destructor semantics can be used. However the CLR does not permit a value-type to have a destructor.

My random searches found one argument that if a value-type is boxed it falls under the jurisdiction of the garbage collector and therefore its destruction becomes non-deterministic.
I feel that this argument isn't strong enough, the benefits of RAII are big enough to say that a value-type with a destructor cannot be boxed (or used as a class member).

To cut a long story short my question is: are there any other reasons value types can not be used in order to introduce RAII to .NET?  (or do you think my argument about RAII's obvious advantages are flawed?)

Edit: I must have not phrased the question clearly since the first four answers have missed the point. I know about Finalize and its non-deterministic characteristics, I know about the using construct and I feel these two options are inferior to RAII. using is one more thing the consumer of a class must remember (how many people forgot to put a StreamReader in a using block?). My question is a philosophical one about the language design, why is it the way it is and can it be improved?

For instance with a generic deterministically destructible value-type I can make the using and lock keywords redundant (achievable by library classes):

    public struct Disposer<T> where T : IDisposable
    {
        T val;
        public Disposer(T t) { val = t; }
        public T Value { get { return val; } }
        ~Disposer()  // Currently illegal
        {
            if (val != default(T))
                val.Dispose();
        }
    }

I can't help but end with a apropos quotation which I once saw but can't currently find its origin.

You can take my deterministic destruction when my cold dead hand goes out of scope.  --Anon

LastEditorDisplayName: Motti


问:
Getting div width and height from jquery if that div used percentage itself
I need to get the div size in px while itself it set to 100% as width & height.

But CDT output gives:
Width = 437px and Height=439
But when I try to inspect that div tag CDT display width = 420 and height = 422px (as seen in image)

Why is that happen when I used

```<code>var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();
</code>```

  function getImageDimensions(path, callback) {
    var img = new Image();
    img.onload = function() {
      callback({
        width: img.width,
        height: img.height
      });
    }
    img.src = path;
  }
  var imgWidth;
  var imgHeight;

  function DoReset(_width, _height) {
    imgWidth = _width;
    imgHeight = _height;
    console.log("IMG Width:" + imgWidth);
    console.log("IMG Height:" + imgHeight);
    //get div
    var divWidth = $('.divhandler').width();
    var divHeight = $('.divhandler').height();
    console.log("DIV Width:" + divWidth);
    console.log("DIV Height:" + divHeight);
    var ratioCalc;
    var newImageHeight;
    var newImageWidth;
    if (imgWidth > imgHeight) {
      if (divWidth > imgWidth) {
        ratioCalc = imgWidth / imgHeight;
        newImageHeight = divHeight * ratioCalc;
        newImageWidth = (imgWidth / imgHeight) * newImageHeight;
        $('.imghandler').css('width', newImageHeight + 'px');
        console.log("1");
      } else {
        ratioCalc = imgHeight / imgWidth;
        newImageHeight = divWidth * ratioCalc;
        $('.imghandler').css('height', newImageHeight + 'px');
        console.log("2");
      }
    } else {
      console.log("2");
    }
  }
  getImageDimensions("http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg", function(data) {
    imgWidth = data.width;
    imgHeight = data.height;
    DoReset(data.width, data.height);
  });
  $(window).resize(function() {
    getImageDimensions("cgihandle.jpg", function(data) {
      imgWidth = data.width;
      imgHeight = data.height;
      DoReset(imgWidth, imgHeight);
    });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divhandler" style="width:100%;height:100%;background:#ccc"> <img src="http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg" class="imghandler" /> </div></code>```

答:
.height() and .width() Don't include borders, paddings and margins. If you want those included in width calc, use .outerHeight() and .outerWidth()

http://api.jquery.com/outerheight/

http://api.jquery.com/outerwidth/

Body:
I need to get the div size in px while itself it set to 100% as width & height.

But CDT output gives:
Width = 437px and Height=439
But when I try to inspect that div tag CDT display width = 420 and height = 422px (as seen in image)

Why is that happen when I used

var divWidth = $('.divhandler').width();
var divHeight = $('.divhandler').height();

  function getImageDimensions(path, callback) {
    var img = new Image();
    img.onload = function() {
      callback({
        width: img.width,
        height: img.height
      });
    }
    img.src = path;
  }
  var imgWidth;
  var imgHeight;

  function DoReset(_width, _height) {
    imgWidth = _width;
    imgHeight = _height;
    console.log("IMG Width:" + imgWidth);
    console.log("IMG Height:" + imgHeight);
    //get div
    var divWidth = $('.divhandler').width();
    var divHeight = $('.divhandler').height();
    console.log("DIV Width:" + divWidth);
    console.log("DIV Height:" + divHeight);
    var ratioCalc;
    var newImageHeight;
    var newImageWidth;
    if (imgWidth > imgHeight) {
      if (divWidth > imgWidth) {
        ratioCalc = imgWidth / imgHeight;
        newImageHeight = divHeight * ratioCalc;
        newImageWidth = (imgWidth / imgHeight) * newImageHeight;
        $('.imghandler').css('width', newImageHeight + 'px');
        console.log("1");
      } else {
        ratioCalc = imgHeight / imgWidth;
        newImageHeight = divWidth * ratioCalc;
        $('.imghandler').css('height', newImageHeight + 'px');
        console.log("2");
      }
    } else {
      console.log("2");
    }
  }
  getImageDimensions("http://www.dailymobile.net/wp-content/uploads/wallpapers/landscape-wallpapers-320x240/landscape-wallpapers-320x240-03.jpg", function(data) {
    imgWidth = data.width;
    imgHeight = data.height;
    DoReset(data.width, data.height);
  });
  $(window).resize(function() {
    getImageDimensions("cgihandle.jpg", function(data) {
      imgWidth = data.width;
      imgHeight = data.height;
      DoReset(imgWidth, imgHeight);
    });
  });


问:
How to get the value for Days in this code?
I am trying to show the average temperature for 4 days, the highest and lowest. The code works perfectly to show the average and highest/lowest value of the 4 days. The problem is trying to show in which day it occurred.

I know that I don't need to use arrays for it, I thought it was easy if I used it. So, here's the code. How can I improve it, to get the day of the highest/lowest value insert by the user?

```<code>int high[NUMS], low[NUMS];

int maximum = 40;
int minimum = -40;

int i, day;

float total, average;

printf("---=== IPC Temperature Analyzer ===---\n");

for (i = 0; i < NUMS; ++i) {

    do{
        printf("Enter the high value for day %d: \n", i+1);
        scanf("%d", &high[i]);
        printf("Enter the low value for day %d: \n", i+1);
        scanf("%d", &low[i]);

       if ((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i])){
                printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
        }

    } while((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i]));

    if((high[0] < high[i]))
       high[0] = high[i];

    if ((low[0] > low[i]))
       low[0] = low[i];

    total = total + (high[i] + low[i]);

}

 average = (total / (NUMS * 2));

printf("The average (mean) temperature was: %.2f\n", average);
printf("The highest temperature was %d, on day %d\n", high[0], day);
printf("The lowest temperature was %d, on day %d\n", low[0], day);

return 0;
</code>```

答:
Thanks everyone for the help. I had to add to variable and initiate as 0 as mentioned.

But was still wrong. Day one was showing as "Day 0". To fix it I add +1.

```<code>if((high[0] < high[i])){
       high[0] = high[i];
       highestDay = i + 1;
    }

    if ((low[0] > low[i])){
       low[0] = low[i];
       lowestDay = i + 1;
    }
</code>```

Body:
I am trying to show the average temperature for 4 days, the highest and lowest. The code works perfectly to show the average and highest/lowest value of the 4 days. The problem is trying to show in which day it occurred.

I know that I don't need to use arrays for it, I thought it was easy if I used it. So, here's the code. How can I improve it, to get the day of the highest/lowest value insert by the user?

int high[NUMS], low[NUMS];

int maximum = 40;
int minimum = -40;

int i, day;

float total, average;

printf("---=== IPC Temperature Analyzer ===---\n");

for (i = 0; i < NUMS; ++i) {

    do{
        printf("Enter the high value for day %d: \n", i+1);
        scanf("%d", &high[i]);
        printf("Enter the low value for day %d: \n", i+1);
        scanf("%d", &low[i]);

       if ((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i])){
                printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
        }

    } while((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i]));

    if((high[0] < high[i]))
       high[0] = high[i];

    if ((low[0] > low[i]))
       low[0] = low[i];

    total = total + (high[i] + low[i]);

}

 average = (total / (NUMS * 2));

printf("The average (mean) temperature was: %.2f\n", average);
printf("The highest temperature was %d, on day %d\n", high[0], day);
printf("The lowest temperature was %d, on day %d\n", low[0], day);

return 0;

Body:
Thanks everyone for the help. I had to add to variable and initiate as 0 as mentioned.

But was still wrong. Day one was showing as "Day 0". To fix it I add +1.

if((high[0] < high[i])){
       high[0] = high[i];
       highestDay = i + 1;
    }

    if ((low[0] > low[i])){
       low[0] = low[i];
       lowestDay = i + 1;
    }


问:
How to install vlc on centos7 from terminal?
I want to install vlc on centos7. I following some steps mentioned on internet. When I try to run
1.yum update then
2.yum install vlc, it is giving following error.
I am getting something following suggestion

You could try using --skip-broken to work around the problem

    You could try running: rpm -Va --nofiles --nodigest

```<code>    Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libnotify.so.1()(64bit)
           Available: libnotify-0.5.0-1.el6.x86_64 (tejas-barot-vlc)
               libnotify.so.1()(64bit)
           Installed: libnotify-0.7.5-7.el7.x86_64 (@base/$releasever)
              ~libnotify.so.4()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libgnutls.so.26()(64bit)
           Available: gnutls-2.8.5-14.el6_5.x86_64 (tejas-barot-vlc)
               libgnutls.so.26()(64bit)
           Installed: gnutls-3.3.8-12.el7.x86_64 (@base)
              ~libgnutls.so.28()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)
           Available: gnutls-2.8.5-14.el6_5.x86_64 (tejas-barot-vlc)
               libgnutls.so.26(GNUTLS_1_4)(64bit)
           Installed: gnutls-3.3.8-12.el7.x86_64 (@base)
              ~libgnutls.so.28(GNUTLS_1_4)(64bit)
              ~libgnutls.so.28(GNUTLS_2_10)(64bit)
              ~libgnutls.so.28(GNUTLS_2_12)(64bit)
              ~libgnutls.so.28(GNUTLS_2_8)(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libudev.so.0()(64bit)
           Available: libudev-147-2.57.el6.x86_64 (tejas-barot-vlc)
               libudev.so.0()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libproxy.so.0()(64bit)
           Available: libproxy-0.3.0-10.el6.x86_64 (tejas-barot-vlc)
               libproxy.so.0()(64bit)
           Installed: libproxy-0.4.11-6.el7.x86_64 (@base/$releasever)
              ~libproxy.so.1()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libmtp.so.8()(64bit)
           Available: libmtp-0.3.7-1.el5.rf.x86_64 (rpmforge)
               libmtp.so.8()(64bit)
           Available: libmtp-1.0.1-2.el6.x86_64 (tejas-barot-vlc)
               libmtp.so.8()(64bit)
           Installed: libmtp-1.1.6-3.el7.x86_64 (@base/$releasever)
              ~libmtp.so.9()(64bit)
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
</code>```

I just run yum repolist

```<code>repo id               repo name                                           status
adobe-linux-x86_64    Adobe Systems Incorporated                               2
atrpms/7/x86_64       Fedora Core 7 - x86_64 - ATrpms                        827
base/7/x86_64         CentOS-7 - Base                                      8,652
epel/x86_64           Extra Packages for Enterprise Linux 7 - x86_64       7,602
extras/7/x86_64       CentOS-7 - Extras                                       84
google-chrome         google-chrome                                            3
linuxtech-release     LinuxTECH.NET el6 main repo                          1,161
nodesource/x86_64     Node.js Packages for Enterprise Linux 7 - x86_64        29
openstack-juno        OpenStack Juno Repository                              953
rpmforge              RHEL 7 - RPMforge.net - dag                         11,403
tejas-barot-vlc       CentOS Repository for VLC Installation               6,518
updates/7/x86_64      CentOS-7 - Updates                                     300
repolist: 37,534
</code>```

We can see that EPEL list is enabled.
I followed from this link
http://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/

I ju

答:
There are several ways to install any software on Centos. We will be using YUM to install vlc. Before installing it you should check the version of Centos you are using by below command.

cat /etc/centos-release

Now according to version of centos follow the instructions:-

For Centos 7

Step 1: Install  EPEL

yum install epel-release

If you face any difficulty to install EPEL then follow the link.

rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-1.el7.nux.noarch.rpm

For Centos 6

Step 1: Run below commands

rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

rpm -Uvh
http://li.nux.ro/download/nux/dextop/el6/x86_64/nux-dextop-release-0-2.el6.nux.noarch.rpm

Step 2: Update Yum

yum update

Step 3: Install VLC

yum install vlc

Step 4: Open VLC

vlc -v

Congratulations!!! You have VLC installed.

Body:
I want to install vlc on centos7. I following some steps mentioned on internet. When I try to run
1.yum update then
2.yum install vlc, it is giving following error.
I am getting something following suggestion

You could try using --skip-broken to work around the problem

    You could try running: rpm -Va --nofiles --nodigest

    Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libnotify.so.1()(64bit)
           Available: libnotify-0.5.0-1.el6.x86_64 (tejas-barot-vlc)
               libnotify.so.1()(64bit)
           Installed: libnotify-0.7.5-7.el7.x86_64 (@base/$releasever)
              ~libnotify.so.4()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libgnutls.so.26()(64bit)
           Available: gnutls-2.8.5-14.el6_5.x86_64 (tejas-barot-vlc)
               libgnutls.so.26()(64bit)
           Installed: gnutls-3.3.8-12.el7.x86_64 (@base)
              ~libgnutls.so.28()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libgnutls.so.26(GNUTLS_1_4)(64bit)
           Available: gnutls-2.8.5-14.el6_5.x86_64 (tejas-barot-vlc)
               libgnutls.so.26(GNUTLS_1_4)(64bit)
           Installed: gnutls-3.3.8-12.el7.x86_64 (@base)
              ~libgnutls.so.28(GNUTLS_1_4)(64bit)
              ~libgnutls.so.28(GNUTLS_2_10)(64bit)
              ~libgnutls.so.28(GNUTLS_2_12)(64bit)
              ~libgnutls.so.28(GNUTLS_2_8)(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libudev.so.0()(64bit)
           Available: libudev-147-2.57.el6.x86_64 (tejas-barot-vlc)
               libudev.so.0()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libproxy.so.0()(64bit)
           Available: libproxy-0.3.0-10.el6.x86_64 (tejas-barot-vlc)
               libproxy.so.0()(64bit)
           Installed: libproxy-0.4.11-6.el7.x86_64 (@base/$releasever)
              ~libproxy.so.1()(64bit)
Error: Package: vlc-2.0.7-10.el6.x86_64 (linuxtech-release)
           Requires: libmtp.so.8()(64bit)
           Available: libmtp-0.3.7-1.el5.rf.x86_64 (rpmforge)
               libmtp.so.8()(64bit)
           Available: libmtp-1.0.1-2.el6.x86_64 (tejas-barot-vlc)
               libmtp.so.8()(64bit)
           Installed: libmtp-1.1.6-3.el7.x86_64 (@base/$releasever)
              ~libmtp.so.9()(64bit)
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I just run yum repolist

repo id               repo name                                           status
adobe-linux-x86_64    Adobe Systems Incorporated                               2
atrpms/7/x86_64       Fedora Core 7 - x86_64 - ATrpms                        827
base/7/x86_64         CentOS-7 - Base                                      8,652
epel/x86_64           Extra Packages for Enterprise Linux 7 - x86_64       7,602
extras/7/x86_64       CentOS-7 - Extras                                       84
google-chrome         google-chrome                                            3
linuxtech-release     LinuxTECH.NET el6 main repo                          1,161
nodesource/x86_64     Node.js Packages for Enterprise Linux 7 - x86_64        29
openstack-juno        OpenStack Juno Repository                              953
rpmforge              RHEL 7 - RPMforge.net - dag                         11,403
tejas-barot-vlc       CentOS Repository for VLC Installation               6,518
updates/7/x86_64      CentOS-7 - Updates                                     300
repolist: 37,534

We can see that EPEL list is enabled.
I followed from this link
http://www.tecmint.com/how-to-enable-epel-repository-for-rhel-centos-6-5/

I ju


问:
How To define arguments in ironpython for the Microsoft.SqlServer.SMO.Scripter.Script Class
I want to script my database objects using the ironpython code below:

```<code>import sys
import clr

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # TypeError: expected Array[Urn], got Table
        scripter.Script(table)
</code>```

When executing this code, I get the following error:

```<code>File "SMOtest2.py", line 18, in <module>
TypeError: expected Array[Urn], got Table
</code>```

The SMO.Scripter.doc gives me the following information:

```<code>Script(self: Scripter, urns: Array[Urn]) -> StringCollection
Script(self: Scripter, list: UrnCollection) -> StringCollection
Script(self: Scripter, objects: Array[SqlSmoObject]) -> StringCollection
</code>```

I tried creating an Array[Urn] or an Array[SqlSmoObject] but without any succes.

Does anyone have an idea how I can create the right argument for the SMO.Scripter.Script Class?

I want to write the VB code below in python.
Taken from: http://msdn.microsoft.com/en-us/library/ms162160(v=SQL.90).aspx

```<code>'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Scripter object and set the required scripting options.
Dim scrp As Scripter
scrp = New Scripter(srv)
scrp.Options.ScriptDrops = False
scrp.Options.WithDependencies = True
'Iterate through the tables in database and script each one. Display the script.
'Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Dim tb As Table
Dim smoObjects(1) As Urn
For Each tb In db.Tables
    smoObjects = New Urn(0) {}
    smoObjects(0) = tb.Urn
    If tb.IsSystemObject = False Then
        Dim sc As StringCollection
        sc = scrp.Script(smoObjects)
        Dim st As String
        For Each st In sc
            Console.WriteLine(st)
        Next
    End If
Next
</code>```

答:
Never used IronPython or SMO, but it looks like it expects a collection of some sort. Have you tried:

```<code>scripter.Script(database.Tables)
</code>```

instead of scripting one table at a time?

Body:
I want to script my database objects using the ironpython code below:

import sys
import clr

database_name  = r'localhost\SQLEXPRESS'
dir_assemblies = r'D:\programfiles\Microsoft SQL Server\100\SDK\Assemblies'

# Import SMO Namespace
sys.path.append(dir_assemblies)
clr.AddReferenceToFile('Microsoft.SqlServer.Smo.dll')
import Microsoft.SqlServer.Management.Smo as SMO

db       = SMO.Server(database_name)
scripter = SMO.Scripter(db)

for database in db.Databases:
    for table in database.Tables:
        # TypeError: expected Array[Urn], got Table
        scripter.Script(table)

When executing this code, I get the following error:

File "SMOtest2.py", line 18, in <module>
TypeError: expected Array[Urn], got Table

The SMO.Scripter.doc gives me the following information:

Script(self: Scripter, urns: Array[Urn]) -> StringCollection
Script(self: Scripter, list: UrnCollection) -> StringCollection
Script(self: Scripter, objects: Array[SqlSmoObject]) -> StringCollection

I tried creating an Array[Urn] or an Array[SqlSmoObject] but without any succes.

Does anyone have an idea how I can create the right argument for the SMO.Scripter.Script Class?

I want to write the VB code below in python.
Taken from: http://msdn.microsoft.com/en-us/library/ms162160(v=SQL.90).aspx

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Scripter object and set the required scripting options.
Dim scrp As Scripter
scrp = New Scripter(srv)
scrp.Options.ScriptDrops = False
scrp.Options.WithDependencies = True
'Iterate through the tables in database and script each one. Display the script.
'Note that the StringCollection type needs the System.Collections.Specialized namespace to be included.
Dim tb As Table
Dim smoObjects(1) As Urn
For Each tb In db.Tables
    smoObjects = New Urn(0) {}
    smoObjects(0) = tb.Urn
    If tb.IsSystemObject = False Then
        Dim sc As StringCollection
        sc = scrp.Script(smoObjects)
        Dim st As String
        For Each st In sc
            Console.WriteLine(st)
        Next
    End If
Next

Body:
Never used IronPython or SMO, but it looks like it expects a collection of some sort. Have you tried:

scripter.Script(database.Tables)

instead of scripting one table at a time?


问:
Test React on Chrome browser
How can I see what I´m building on my Chrome browser?
I know how to see PHP through local server, see HTML website through normal ways and with Gulp but can´t seem to understand this.</p>

答:
I would suggest you look into create-react-app, it comes handy with a few things that are already prebuilt https://github.com/facebookincubator/create-react-app

Here's a tutorial on it: https://medium.com/@diamondgfx/learning-react-with-create-react-app-part-1-a12e1833fdc

You can load the build from your project on 'create-react-app' into your PHP project.

Title: Test React on Chrome browser


问:
sizeof(void*) != sizeof(uintptr_t) in practice?
While the C99 standard theoretically allows for sizeof(void*) != sizeof(uintptr_t) (at least as I understand it), are there any modern systems where the widths are different? i.e., as a practical matter, would it be reasonable to rely on the assumption that these types have the same width?

答:
the C99 standard theoretically allows for sizeof(void*) != sizeof(uintptr_t) are there any modern systems where the widths are different?

I know no such system today (but perhaps you might find some weird VLIW embedded microcontroller). 1990 era Cray was an exception (but it was C89, not C99).

i.e., as a practical matter, would it be reasonable to rely on the assumption that these types have the same width?

Certainly yes in practice. BTW, very often your source code would practically have other dependencies (e.g. typically uses some non- C99-standard function, but commonly available ones, like e.g. POSIX).

(in practice, strictly conforming C99 useful programs not depending upon external libraries are very rare)


问:
How to build subsections in an NSFetchedResultsController
I'm building an expense tracker where an Expense can belong to only one Category but can have multiple Tags. This is my object graph:

In the screen where I list all the expenses in a table view, I want the expenses to be grouped by date (the sectionDate), and then by Category (or, using a segmented control, by Tag). This is the intended UI:

I can already make an NSFetchedResultsController query all expenses, section them by date, then by category, but I can't get the (1) total for the category and (2) the list of expenses in it. How might I proceed to do that? This is my current code:

```<code>let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Expense")
    fetchRequest.resultType = .dictionaryResultType

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(Expense.sectionDate), ascending: false)
    ]

    fetchRequest.propertiesToFetch = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]
    fetchRequest.propertiesToGroupBy = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                              managedObjectContext: Global.coreDataStack.viewContext,
                                                              sectionNameKeyPath: #keyPath(Expense.sectionDate),
                                                              cacheName: nil)
    return fetchedResultsController
}()
</code>```

答:
A should forewarn that I've never done this, but personally I would set about it as follows:

Don't use propertiesToGroupBy: it forces you to use the .dictionaryResultType which means you can only access the underlying managed objects by executing a separate fetch.

Instead, add another computed property to the relevant NSManagedObject subclass, combining the sectionDate and the category.name.  This property will be used as the sectionNameKeyPath for the FRC, so that the FRC will establish a section in the tableView for each unique combination of sectionDate and category name.

Add category.name as another sort descriptor for the fetch underlying the FRC.  This will ensure that the Expense objects fetched by the FRC are in the correct order (ie. all Expense objects with the same sectionDate and category name are together).

Add a section header view for each section.  The name property for the section (from the FRC) will include both the sectionDate and the category name.  In most cases, you can strip out and ignore the sectionDate, displaying only the category name and corresponding total (see below).  But for the very first section, and indeed the first section for any given sectionDate, add an additional view (to the section header view) showing the sectionDate and overall total for that sectionDate.

Working out whether a given section is the first section for the sectionDate is a little tricky.  You could retrieve the name for the previous section and compare the sectionDates.

To collapse/expand the sections, maintain an array holding the collapsed/expanded state of each section.  If the section is collapsed, return 0 in the tableView numberOfRowsInSection datasource method; if expanded use the figure provided by the FRC.

For the category totals, iterate through the objects array for the relevant section (or use a suitable .reduce to achieve the same).

For the sectionDate totals, filter the fetchedObjects for the FRC to include only the Expense objects for the relevant sectionDate, and then iterate or .reduce the filtered array.

I am happy to add or amend if any of that needs clarification.

Body:
I'm building an expense tracker where an Expense can belong to only one Category but can have multiple Tags. This is my object graph:

In the screen where I list all the expenses in a table view, I want the expenses to be grouped by date (the sectionDate), and then by Category (or, using a segmented control, by Tag). This is the intended UI:

I can already make an NSFetchedResultsController query all expenses, section them by date, then by category, but I can't get the (1) total for the category and (2) the list of expenses in it. How might I proceed to do that? This is my current code:

let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Expense")
    fetchRequest.resultType = .dictionaryResultType

    fetchRequest.sortDescriptors = [
        NSSortDescriptor(key: #keyPath(Expense.sectionDate), ascending: false)
    ]

    fetchRequest.propertiesToFetch = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]
    fetchRequest.propertiesToGroupBy = [
        #keyPath(Expense.sectionDate),
        #keyPath(Expense.category)
    ]

    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                              managedObjectContext: Global.coreDataStack.viewContext,
                                                              sectionNameKeyPath: #keyPath(Expense.sectionDate),
                                                              cacheName: nil)
    return fetchedResultsController
}()


问:
Unchecked cast warnings with parameterized types
I am reading about restrictions on generics from the Java Tutorials, specifically casting with parameterized types. I understand the examples that are presented. However, I am unsure about the following example:

```<code>List<? extends Number> l1 = new ArrayList<Integer>();
// unchecked cast warning
ArrayList<Number> l2 = (ArrayList<Number>) l1;
// no unchecked cast warning
ArrayList<? extends Number> l3 = (ArrayList<? extends Number>) l1;
</code>```

I understand why there is a warning in the first case. Why is there no warning in the second case? Is it because the only operations that I can perform on l3 are safe (e.g., I cannot add (say) a Float to the list)?

UPDATE: Below is an excerpt from section 5.5.2 of the JLS that addresses similar questions.

A cast from a type S to a parameterized type (§4.5) T is unchecked
  unless at least one of the following is true:

S <: T

All of the type arguments (§4.5.1) of T are unbounded wildcards

T <: S and S has no subtype X other than T where the type arguments of X are not contained in the type arguments of T.

答: There's no warning because the cast doesn't change the generic part of the type. List<? extends Number> and ArrayList<? extends Number> have the same type argument. Instead, the cast is a checked cast from List to ArrayList.

Body:
I am reading about restrictions on generics from the Java Tutorials, specifically casting with parameterized types. I understand the examples that are presented. However, I am unsure about the following example:

List<? extends Number> l1 = new ArrayList<Integer>();
// unchecked cast warning
ArrayList<Number> l2 = (ArrayList<Number>) l1;
// no unchecked cast warning
ArrayList<? extends Number> l3 = (ArrayList<? extends Number>) l1;

I understand why there is a warning in the first case. Why is there no warning in the second case? Is it because the only operations that I can perform on l3 are safe (e.g., I cannot add (say) a Float to the list)?

UPDATE: Below is an excerpt from section 5.5.2 of the JLS that addresses similar questions.

A cast from a type S to a parameterized type (§4.5) T is unchecked
  unless at least one of the following is true:

S <: T

All of the type arguments (§4.5.1) of T are unbounded wildcards

T <: S and S has no subtype X other than T where the type arguments of X are not contained in the type arguments of T.


问:
Many-to-Many Misunderstanding in Django
I am new to web development so this question might not be straightforward but please bear with me. Im working on a social network in which a user could follow another user in two different ways...anwyways...i created two models to define the relationships. A many-to-many relationship as follows.

How do i make this models totally independent of each other? so lets say a user could have 500Followers and 200Guests??

i used th javascript code below to toggle the follow button but its increases both. This might not be a great overview of the problem but thats because i am new to this. but please try. I am using django by the way.

```<code>class Follower(models.Model):
    user_from = models.ForeignKey(User, related_name='rel_from_set')
    user_to = models.ForeignKey(User, related_name='rel_to_set')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

class Meta:
    ordering = ('-created',)

def __str__(self):
    return "{} is now a following".format(self.user_from, self.user_to)

class Guests(models.Model):
    user_fromt = models.ForeignKey(User, related_name='yel_from_set')
    user_tot = models.ForeignKey(User, related_name='yel_to_set')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

class Meta:
    ordering = ('-created',)

def __str__(self):
    return '{} follows {}'.format(self.user_from, self.user_to)

User.add_to_class('follows', models.ManyToManyField('self',
through=Guests, related_name='guest', symmetrical=False))

User.add_to_class('follows', models.ManyToManyField('self',
through=Follwer, related_name='guest', symmetrical=False))
</code>```

View

```<code>def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = User.objects.get(id=user_id)
            if action == 'follow':
                Contact.objects.get_or_create(user_from=request.user,
                 user_to=user)
                create_action(request.user, 'is now a fan of', user)
            else:
                Contact.objects.filter(user_from=request.user,
            user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except User.DoesNotExist:
            return JsonResponse({'status':'ko'})
        return JsonResponse({'status':'ko'})
</code>```

答: Rather than having two separate through models, have a single model with a type field.

Title: Many-to-Many Misunderstanding in Django

Body:
I am new to web development so this question might not be straightforward but please bear with me. Im working on a social network in which a user could follow another user in two different ways...anwyways...i created two models to define the relationships. A many-to-many relationship as follows.

How do i make this models totally independent of each other? so lets say a user could have 500Followers and 200Guests??

i used th javascript code below to toggle the follow button but its increases both. This might not be a great overview of the problem but thats because i am new to this. but please try. I am using django by the way.

class Follower(models.Model):
    user_from = models.ForeignKey(User, related_name='rel_from_set')
    user_to = models.ForeignKey(User, related_name='rel_to_set')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

class Meta:
    ordering = ('-created',)

def __str__(self):
    return "{} is now a following".format(self.user_from, self.user_to)

class Guests(models.Model):
    user_fromt = models.ForeignKey(User, related_name='yel_from_set')
    user_tot = models.ForeignKey(User, related_name='yel_to_set')
    created = models.DateTimeField(auto_now_add=True, db_index=True)

class Meta:
    ordering = ('-created',)

def __str__(self):
    return '{} follows {}'.format(self.user_from, self.user_to)

User.add_to_class('follows', models.ManyToManyField('self',
through=Guests, related_name='guest', symmetrical=False))

User.add_to_class('follows', models.ManyToManyField('self',
through=Follwer, related_name='guest', symmetrical=False))

View

def user_follow(request):
    user_id = request.POST.get('id')
    action = request.POST.get('action')
    if user_id and action:
        try:
            user = User.objects.get(id=user_id)
            if action == 'follow':
                Contact.objects.get_or_create(user_from=request.user,
                 user_to=user)
                create_action(request.user, 'is now a fan of', user)
            else:
                Contact.objects.filter(user_from=request.user,
            user_to=user).delete()
            return JsonResponse({'status':'ok'})
        except User.DoesNotExist:
            return JsonResponse({'status':'ko'})
        return JsonResponse({'status':'ko'})


问:
CMake - Include third party files
I'm pretty new to working with third party stuff and also new to working on Windows with C.

I'm currently trying to simply use and include this third party library.

I've downloaded it and put all the files in include/subhook/ next to my main file.

My main.c looks like the example on the github page, except it includes include/subhook/subhook.h:

```<code>#include <stdio.h>
#include "include/subhook/subhook.h"

subhook_t foo_hook;

void foo(int x) {
    printf("real foo just got called with %d\n", x);
}

void my_foo(int x) {
    subhook_remove(foo_hook);

    printf("foo(%d) called\n", x);
    foo(x);

    subhook_install(foo_hook);
}

int main() {
    foo_hook = subhook_new((void *)foo, (void *)my_foo, 0);

    subhook_install(foo_hook);
    foo(123);

    subhook_remove(foo_hook);
    subhook_free(foo_hook);
}
</code>```

and this is my CMakeLists.txt file. I've also tried including all the other .c files but it won't work:

```<code>cmake_minimum_required(VERSION 3.7)
project(NexusHookSubhook)
set(CMAKE_C_STANDARD 11)

include_directories(include/subhook)

set(SOURCE_FILES main.c include/subhook/subhook.h include/subhook/subhook.c)
add_executable(NexusHookSubhook ${SOURCE_FILES})
</code>```

When I try to compile I get a whole load of these errors (which is, I assume, from linking/including the library wrong). Can anyone explain what I'm doing wrong here?

```<code>C:\Users\Nakroma\.CLion2017.1\system\cygwin_cmake\bin\cmake.exe --build C:\Users\Nakroma\CLionProjects\NexusHookSubhook\cmake-build-debug --target NexusHookSubhook -- -j 4
[ 33%] Linking C executable NexusHookSubhook.exe
CMakeFiles/NexusHookSubhook.dir/main.c.o: In function `my_foo':
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:12: undefined reference to `__imp_subhook_remove'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:12:(.text+0x3c): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `__imp_subhook_remove'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:17: undefined reference to `__imp_subhook_install'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:17:(.text+0x69): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `__imp_subhook_install'
CMakeFiles/NexusHookSubhook.dir/main.c.o: In function `main':
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:21: undefined reference to `__imp_subhook_new'
....
</code>```

Additional notes: I'm on Windows 10 with Cygwin 2.8.0 and CMake 3.7.2 (using the make and gcc package and GDB 7.11.1)

答:
I would recommend the following things:

Replace

```<code>#include "include/subhook/subhook.h"
</code>```

with

```<code>#include "subhook.h"
</code>```

as first part of the path is already included over here:

```<code>include_directories(include/subhook)
</code>```

Only include the .c files as SOURCE_FILES:

```<code>set(SOURCE_FILES main.c include/subhook/subhook.c)
</code>```

Title: CMake - Include third party files

Body:
I'm pretty new to working with third party stuff and also new to working on Windows with C.

I'm currently trying to simply use and include this third party library.

I've downloaded it and put all the files in include/subhook/ next to my main file.

My main.c looks like the example on the github page, except it includes include/subhook/subhook.h:

#include <stdio.h>
#include "include/subhook/subhook.h"

subhook_t foo_hook;

void foo(int x) {
    printf("real foo just got called with %d\n", x);
}

void my_foo(int x) {
    subhook_remove(foo_hook);

    printf("foo(%d) called\n", x);
    foo(x);

    subhook_install(foo_hook);
}

int main() {
    foo_hook = subhook_new((void *)foo, (void *)my_foo, 0);

    subhook_install(foo_hook);
    foo(123);

    subhook_remove(foo_hook);
    subhook_free(foo_hook);
}

and this is my CMakeLists.txt file. I've also tried including all the other .c files but it won't work:

cmake_minimum_required(VERSION 3.7)
project(NexusHookSubhook)
set(CMAKE_C_STANDARD 11)

include_directories(include/subhook)

set(SOURCE_FILES main.c include/subhook/subhook.h include/subhook/subhook.c)
add_executable(NexusHookSubhook ${SOURCE_FILES})

When I try to compile I get a whole load of these errors (which is, I assume, from linking/including the library wrong). Can anyone explain what I'm doing wrong here?

C:\Users\Nakroma\.CLion2017.1\system\cygwin_cmake\bin\cmake.exe --build C:\Users\Nakroma\CLionProjects\NexusHookSubhook\cmake-build-debug --target NexusHookSubhook -- -j 4
[ 33%] Linking C executable NexusHookSubhook.exe
CMakeFiles/NexusHookSubhook.dir/main.c.o: In function `my_foo':
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:12: undefined reference to `__imp_subhook_remove'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:12:(.text+0x3c): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `__imp_subhook_remove'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:17: undefined reference to `__imp_subhook_install'
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:17:(.text+0x69): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `__imp_subhook_install'
CMakeFiles/NexusHookSubhook.dir/main.c.o: In function `main':
/cygdrive/c/Users/Nakroma/CLionProjects/NexusHookSubhook/main.c:21: undefined reference to `__imp_subhook_new'
....

Additional notes: I'm on Windows 10 with Cygwin 2.8.0 and CMake 3.7.2 (using the make and gcc package and GDB 7.11.1)

Body:
I would recommend the following things:

Replace

#include "include/subhook/subhook.h"

with

#include "subhook.h"

as first part of the path is already included over here:

include_directories(include/subhook)

Only include the .c files as SOURCE_FILES:

set(SOURCE_FILES main.c include/subhook/subhook.c)


答:
The selector input[type="radio"]#someID-1:checked #extra selects an element with the id extra that is a child element of your radio button. Since radio buttons rarely have children, you'll need to change the selector to match your HTML structure.

I suggest placing the radio button inside the same parent element as #extra. That way you can use the selector input[type="radio"]#someID-1:checked ~ #extra which will target the #extra element if it is preceded by the radio button in selected state.

Title: CSS and modifying div's width if radio button checked

Body:
JavaScript not accepted this time.

So, I have this CSS code. This code should change to width if radio button is checked. Nothing happens. How could I modify the code?

input[type="radio"]#someID-1:checked #extra { width: 4000px; }

I also have this HTML code:

      <input id="someID-1" name="nappi" type="radio">

            1

        R1

      <input id="someID-5" name="nappi" type="radio">

        extra

    <input id="someID-100" name="nappi" type="radio">


问:
efficient breadth first search using sql joins
I'm dealing with a binary tree.

So I have a database table in my database where each node is a parent to up to 2 other nodes. I have a plan to efficiently find the top most node (under a given node) that is a parent to less than 2 other nodes. I'm looking for the top most open position to place a new node in other words. So I have this implemented as a breadth-first search. But the way I'm calling the database for each and every node is inefficient. I'm basically going down the tree, producing a running list of nodes on each level and checking each one if it is a parent to two other nodes.

Here's a diagram:

And here's the code if you'd like to see it:

```<code>  # breadth-first search
  def build_and_return_parent_id(breadth_list) do
        [ {node_id} | tail ] = breadth_list

        child_list = fetch_children_id(node_id)

        bc_list = tail ++ child_list

        case length(child_list) do
          x when x > 2 ->

            # recursion
            build_and_return_parent_id(bc_list)

          2 ->

            # recursion
            build_and_return_parent_id(bc_list)

          _ -> node_id
        end
  end

  def fetch_children_id(id) do
    Repo.all( from n in Node,
              where: n.parent_id == ^id,
              order_by: [asc: n.inserted_at],
              select: {n.id})
  end
end
</code>```

So instead of doing that so inefficiently - one db call per node - I was thinking, how about I produce a list of all the nodes that have less than two parents, then travel down the tree, for each level use one db call to get a list of all the nodes on that level, then simply compare the two lists. if there are matching IDs in both the lists I've found a node that has an available spot under it.

Here's a diagram:

The problem is I know almost nothing about sql queries. my guess is that this can be done with some kind of self join on the table.

```<code>node_id   |  parent_id
----------------------
1         |  nil
2         |  1
3         |  1
4         |  2
5         |  2
6         |  3
7         |  4
8         |  5
9         |  6
10        |  3
</code>```

So anyway I'm sure if this method works someone has done it before but I can't seem to find any information on the kinds of sql queries that would be used to generate the open list or the level list.

Now I suppose the 2nd query is pretty simple. since we have an open list we can just use a where-in-[list] clause. Byt the first one I think is the one I'm struggling with.

If you have anything you can point me to or help you can offer I'd really appreciate it.

答:
You can add columns depth and child_count and create an index:

```<code>create index nodes_depth_1child_idx on nodes(depth) where child_count=1;
</code>```

Then searching should be basically instant with:

```<code>select node_id from nodes where child_count=1 order by depth limit 1;
</code>```

You should also create triggers that would maintain these values. This would slow down insert operations slightly, as the insert would have to read the parent node depth and update the parent node child_count.

Body:
I'm dealing with a binary tree.

So I have a database table in my database where each node is a parent to up to 2 other nodes. I have a plan to efficiently find the top most node (under a given node) that is a parent to less than 2 other nodes. I'm looking for the top most open position to place a new node in other words. So I have this implemented as a breadth-first search. But the way I'm calling the database for each and every node is inefficient. I'm basically going down the tree, producing a running list of nodes on each level and checking each one if it is a parent to two other nodes.

Here's a diagram:

And here's the code if you'd like to see it:

  # breadth-first search
  def build_and_return_parent_id(breadth_list) do
        [ {node_id} | tail ] = breadth_list

        child_list = fetch_children_id(node_id)

        bc_list = tail ++ child_list

        case length(child_list) do
          x when x > 2 ->

            # recursion
            build_and_return_parent_id(bc_list)

          2 ->

            # recursion
            build_and_return_parent_id(bc_list)

          _ -> node_id
        end
  end

  def fetch_children_id(id) do
    Repo.all( from n in Node,
              where: n.parent_id == ^id,
              order_by: [asc: n.inserted_at],
              select: {n.id})
  end
end

So instead of doing that so inefficiently - one db call per node - I was thinking, how about I produce a list of all the nodes that have less than two parents, then travel down the tree, for each level use one db call to get a list of all the nodes on that level, then simply compare the two lists. if there are matching IDs in both the lists I've found a node that has an available spot under it.

Here's a diagram:

The problem is I know almost nothing about sql queries. my guess is that this can be done with some kind of self join on the table.

node_id   |  parent_id
----------------------
1         |  nil
2         |  1
3         |  1
4         |  2
5         |  2
6         |  3
7         |  4
8         |  5
9         |  6
10        |  3

So anyway I'm sure if this method works someone has done it before but I can't seem to find any information on the kinds of sql queries that would be used to generate the open list or the level list.

Now I suppose the 2nd query is pretty simple. since we have an open list we can just use a where-in-[list] clause. Byt the first one I think is the one I'm struggling with.

If you have anything you can point me to or help you can offer I'd really appreciate it.

Body:
You can add columns depth and child_count and create an index:

create index nodes_depth_1child_idx on nodes(depth) where child_count=1;

Then searching should be basically instant with:

select node_id from nodes where child_count=1 order by depth limit 1;

You should also create triggers that would maintain these values. This would slow down insert operations slightly, as the insert would have to read the parent node depth and update the parent node child_count.


问:
How to Edit Empty Spaces of Left, Right UIBarButtonItem in UINavigationBar [iOS 7]
I was using iOS 6.1 earlier, but now I have moved to iOS 7. Along with other problems, I have observed that in my navigation bar, the left space of left bar button item and right empty space of the right button bar item are quite more in IOS 7 than in iOS 6.

I need to know is there a way I can reduce empty spaces of left, right bar button items in navigation bar??

答:
Swift 3.1

To give left bar button item negative space:

```<code>    let backButton = UIButton.init(type: .custom)
    backButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
    // negative space
    backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -44.0, bottom: 0, right: 0)
    backButton.setImage(Ionicons.iosArrowBack.image(30, color: UIColor(hex: 0xFD6250)), for: .normal)
    backButton.addTarget(self, action: #selector(InviteVC.goBack), for: .touchUpInside)
    // set back button
    self.navigationItem.leftBarButtonIteUIBarButtonItem.init(customView: backButton)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Swift 3.1

To give left bar button item negative space:

    let backButton = UIButton.init(type: .custom)
    backButton.frame = CGRect.init(x: 0, y: 0, width: 40, height: 40)
    // negative space
    backButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: -44.0, bottom: 0, right: 0)
    backButton.setImage(Ionicons.iosArrowBack.image(30, color: UIColor(hex: 0xFD6250)), for: .normal)
    backButton.addTarget(self, action: #selector(InviteVC.goBack), for: .touchUpInside)
    // set back button
    self.navigationItem.leftBarButtonIteUIBarButtonItem.init(customView: backButton)


答:
you totally miss the linking part in your CMakeFiles

```<code>target_link_libraries(
    NexusHookSubhook
    ${subhookLib}
    m
)
</code>```

Where subhookLib is the library of subhook.

Title: CMake - Include third party files

Body:
you totally miss the linking part in your CMakeFiles

target_link_libraries(
    NexusHookSubhook
    ${subhookLib}
    m
)

Where subhookLib is the library of subhook.


问:
NHibernate InvalidProxyTypeException
I get this NHhiberante when verifying my Fluent Mappings

FluentNHibernate.Cfg.FluentConfigurationException
  : An invalid or incomplete
  configuration was used while creating
  a SessionFactory. Check
  PotentialReasons collection, and
  InnerException for more detail.

---->
  NHibernate.InvalidProxyTypeException :
  The following types may not be used as
  proxies: Domain.Address: method
  Equals should be 'public/protected
  virtual' or 'protected internal
  virtual' Domain.Person: method
  Equals should be 'public/protected
  virtual' or 'protected internal
  virtual' TearDown :
  System.NullReferenceException : Object
  reference not set to an instance of an
  object.

I Tried making my Equals method virtual however I just end up getting this error

System.ApplicationException : For
  property 'AddressPerson' expected
  'Domain.Person' of type
  'Domain.Person' but got
  'PersonProxy5ce0cdda11ac4829a4f038c9f7944213'
  of type 'Domain.Person'

I am confused does anyone know what exactly is going on here?

Edit: It looks like you cant override : Equals(Person person) for IEquatable Not sure why this confuses NHibernate however?

答: As you mentioned in your edit, yes you can't implement IEqualityComparer<T> for an NHibernate entity class. Just override the simple public override bool Equals(object obj) and public override int GetHashCode().

Title: NHibernate InvalidProxyTypeException


问:
Test run cron entry
I added a cron job recently, but made a mistake in the path while giving the command and hence, the job never succeeded. Is there some way to test the cron changes we have done?

Please note that I had indeed copied and pasted the command from my command line and it was just an stray keypress that caused this.

答:
Joshua's answer does not work for me. Two problems:

Variables in cron-env file are not exported (set -a needed).

Script is still tied to current tty (setsid needed).

The script run-as-cron should be

```<code>#!/bin/sh

. "$1"
exec setsid /usr/bin/env -i "$SHELL" -c "set -a; . $1; $2" </dev/null
</code>```

Not enough rep' to fix his answer or add a comment...

Title: Test run cron entry

Body:
Joshua's answer does not work for me. Two problems:

Variables in cron-env file are not exported (set -a needed).

Script is still tied to current tty (setsid needed).

The script run-as-cron should be

#!/bin/sh

. "$1"
exec setsid /usr/bin/env -i "$SHELL" -c "set -a; . $1; $2" </dev/null

Not enough rep' to fix his answer or add a comment...


问:
How add item to TableView from file with loop
I use this class to add items to tableview javafx but it just add the last line of file to tableview.

 I use ObservableList in this class

  how can I solve this problem?

```<code>public class MyTicket {
String name;
@FXML
private Button back;
@FXML
private TableView<ShowTicket> table;
@FXML
private TableColumn<ShowTicket, String> origin;
@FXML
private TableColumn<ShowTicket, String> goal;
@FXML
private TableColumn<ShowTicket, String> date;
public void addName(String userName){
    name= userName;
}
public void adddata(){
    String originFile= name + "\\" +name + "origin" + ".txt";
    String goalFile= name + "\\" +name + "goal" + ".txt";
    String dateFile= name + "\\" +name + "date" + ".txt";
        try {
            BufferedReader inputOrigin= new BufferedReader(new FileReader(originFile));
            BufferedReader inputGoal= new BufferedReader(new FileReader(goalFile));
            BufferedReader inputDate= new BufferedReader(new FileReader(dateFile));
            String line1= inputOrigin.readLine();
            String line2= inputGoal.readLine();
            String line3= inputDate.readLine();
            ArrayList<String> or= new ArrayList<>();
            ArrayList<String> go= new ArrayList<>();
            ArrayList<String> da= new ArrayList<>();
            while(line1 != null){
                or.add(line1);
                go.add(line2);
                da.add(line3);
                line1= inputOrigin.readLine();
                line2= inputGoal.readLine();
                line3= inputDate.readLine();
            }
            int i= or.size();
            for(int j=0; j<i; j++){
                ObservableList<ShowTicket> contactList= FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
                table.setItems(contactList);
                origin.setCellValueFactory(new PropertyValueFactory<>("firstName"));
                goal.setCellValueFactory(new PropertyValueFactory<>("lastName"));
                date.setCellValueFactory(new PropertyValueFactory<>("cellPhone"));
            }
                inputOrigin.close();
                inputGoal.close();
                inputDate.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
}//adddata
</code>```

my ShowTicket class:

http://textuploader.com/d0a3e

答:
I use this class to add items to tableview javafx but it just add the
  last line of file to tableview.

It is expected as you overwrite the value of the property items of the TableView object at each iteration :

```<code>for(int j=0; j<i; j++){
    ...
   ObservableList<ShowTicket> contactList= FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
   table.setItems(contactList);
   ...
}
</code>```

You should rather create an contactList object that contains the ShowTicket of all the lines.

```<code>ObservableList<ShowTicket> contactList = FXCollections.observableArrayList();
for(int j=0; j<i; j++){                         ...
   contactList.addAll(FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
}
</code>```

Then you could invoke table.setItems(contactList);.

Body:
I use this class to add items to tableview javafx but it just add the last line of file to tableview.

 I use ObservableList in this class

  how can I solve this problem?

public class MyTicket {
String name;
@FXML
private Button back;
@FXML
private TableView<ShowTicket> table;
@FXML
private TableColumn<ShowTicket, String> origin;
@FXML
private TableColumn<ShowTicket, String> goal;
@FXML
private TableColumn<ShowTicket, String> date;
public void addName(String userName){
    name= userName;
}
public void adddata(){
    String originFile= name + "\\" +name + "origin" + ".txt";
    String goalFile= name + "\\" +name + "goal" + ".txt";
    String dateFile= name + "\\" +name + "date" + ".txt";
        try {
            BufferedReader inputOrigin= new BufferedReader(new FileReader(originFile));
            BufferedReader inputGoal= new BufferedReader(new FileReader(goalFile));
            BufferedReader inputDate= new BufferedReader(new FileReader(dateFile));
            String line1= inputOrigin.readLine();
            String line2= inputGoal.readLine();
            String line3= inputDate.readLine();
            ArrayList<String> or= new ArrayList<>();
            ArrayList<String> go= new ArrayList<>();
            ArrayList<String> da= new ArrayList<>();
            while(line1 != null){
                or.add(line1);
                go.add(line2);
                da.add(line3);
                line1= inputOrigin.readLine();
                line2= inputGoal.readLine();
                line3= inputDate.readLine();
            }
            int i= or.size();
            for(int j=0; j<i; j++){
                ObservableList<ShowTicket> contactList= FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
                table.setItems(contactList);
                origin.setCellValueFactory(new PropertyValueFactory<>("firstName"));
                goal.setCellValueFactory(new PropertyValueFactory<>("lastName"));
                date.setCellValueFactory(new PropertyValueFactory<>("cellPhone"));
            }
                inputOrigin.close();
                inputGoal.close();
                inputDate.close();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
}//adddata

my ShowTicket class:

http://textuploader.com/d0a3e

Body:
I use this class to add items to tableview javafx but it just add the
  last line of file to tableview.

It is expected as you overwrite the value of the property items of the TableView object at each iteration :

for(int j=0; j<i; j++){
    ...
   ObservableList<ShowTicket> contactList= FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
   table.setItems(contactList);
   ...
}

You should rather create an contactList object that contains the ShowTicket of all the lines.

ObservableList<ShowTicket> contactList = FXCollections.observableArrayList();
for(int j=0; j<i; j++){                         ...
   contactList.addAll(FXCollections.observableArrayList(
                        new ShowTicket(or.get(j), go.get(j), da.get(j)));
}

Then you could invoke table.setItems(contactList);.


问:
Json / PHP - Get status and replace the return
so I'm trying to get the status of a server, and the field that the status is in returns 'true/false' however, when I place it in PHP, to show the status of the server, it's simply saying "1" or "0," is there a way to check the response, so I can say something similar to
"If 0, return "Offline", if 1 return "Online", if 3 return "Unknown Status"?

```<code>function status($server) {
    $constructor = 'https://url.com/query/'.$server.'/info';
    $json = json_decode(file_get_contents($constructor), true);
    return $json['status'];
}
</code>```

The code that's responsing 0 or 1 is;
    Status:

I'm very confused why it's returning 0 or 1 instead of true or false, but I'd also like to understand how I can replace the numbers with "Online" or "Offline"

答:
Use this code:

```<code>function status($server) {
    $constructor = 'https://url.com/query/'.$server.'/info';
    $json = json_decode(file_get_contents($constructor), true);
    return $json['status'] ? 'online' : 'offline';
}
</code>```

I used the Ternary operator: PHP Ternary Operator

In PHP the following is true:

```<code>var_dump("0" == FALSE); // bool(true)
var_dump("1" == TRUE); // bool(true)
</code>```

That's why "1" == TRUE

Body:
so I'm trying to get the status of a server, and the field that the status is in returns 'true/false' however, when I place it in PHP, to show the status of the server, it's simply saying "1" or "0," is there a way to check the response, so I can say something similar to
"If 0, return "Offline", if 1 return "Online", if 3 return "Unknown Status"?

function status($server) {
    $constructor = 'https://url.com/query/'.$server.'/info';
    $json = json_decode(file_get_contents($constructor), true);
    return $json['status'];
}

The code that's responsing 0 or 1 is;
    Status:

I'm very confused why it's returning 0 or 1 instead of true or false, but I'd also like to understand how I can replace the numbers with "Online" or "Offline"

Body:
Use this code:

function status($server) {
    $constructor = 'https://url.com/query/'.$server.'/info';
    $json = json_decode(file_get_contents($constructor), true);
    return $json['status'] ? 'online' : 'offline';
}

I used the Ternary operator: PHP Ternary Operator

In PHP the following is true:

var_dump("0" == FALSE); // bool(true)
var_dump("1" == TRUE); // bool(true)

That's why "1" == TRUE