问:
C# Unity Puzzle Game
I want to create a game where all tiles must be rotated to the correct position. I have 15 tiles with a script attached which rotates them 90 degrees on each click. I can detect when each tile is in the correct position but what I am having trouble doing is detecting when ALL 15 are in the correct position.

Here is a screen shot of my stage

https://www.dropbox.com/s/9ag4ly2bil1mzf1/Untitled-1.jpg?dl=0

I was thinking I can create an empty game object and attach a new script with code to get the value from each tile and check if all are true (in the correct position).

Here is my basic code for the rotation script

```<code>using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

    public float rotationAnswer;
    // Use this for initialization
    void Start() {}

    // Update is called once per frame
    void Update() {}

    float rotationValue = 0;

    void OnMouseDown(){
        transform.Rotate(Vector3.up * 90);
        rotationValue = transform.rotation.eulerAngles.y;
        Debug.Log ( rotationValue );

        if ( rotationValue == rotationAnswer)
        {
            Debug.Log ( "Correct" );
            switch (this.name )
            {
            case "tile1":

            }

            Debug.Log ( GameObject.Find("GameComplete").GetComponent<TileGameComplete>().totalCorrectTiles ))

        } else {
        Debug.Log ( "Wrong" );
        }
    }
}
</code>```

Here is my basic code for the detection and complete game script

```<code>using UnityEngine;
using System.Collections;

public class TileGameComplete : MonoBehaviour {

    public int currentCorrectTiles = 0;
    public bool tile1 = false;
    public bool tile2 = false;
    public int totalCorrectTiles = 15;
    // Use this for initialization

    void Update()
    {
        GameObject.Find("Tile1").GetComponent<rotate>().done
        if (tile1 && tile2)
        {
            Debug.Log ("You've won");
        }
    }
}
</code>```

How would you go about solving this problem in C#. Thanks :)

答: @Agumander has a good answer, but personally I prefer to keep logic simple. I would recommend creating a GameController that has access to all 15 tiles, either via a public static list or GameObject.find(...) That way you won't have to check the list 15 times each time the game update for each tile. The tile just has to do their own job (Rotate) And the game controller will determine the logic to end/restart the game</p>

Title: C# Unity Puzzle Game

Body:
I want to create a game where all tiles must be rotated to the correct position. I have 15 tiles with a script attached which rotates them 90 degrees on each click. I can detect when each tile is in the correct position but what I am having trouble doing is detecting when ALL 15 are in the correct position.

Here is a screen shot of my stage

https://www.dropbox.com/s/9ag4ly2bil1mzf1/Untitled-1.jpg?dl=0

I was thinking I can create an empty game object and attach a new script with code to get the value from each tile and check if all are true (in the correct position).

Here is my basic code for the rotation script

using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

    public float rotationAnswer;
    // Use this for initialization
    void Start() {}

    // Update is called once per frame
    void Update() {}

    float rotationValue = 0;

    void OnMouseDown(){
        transform.Rotate(Vector3.up * 90);
        rotationValue = transform.rotation.eulerAngles.y;
        Debug.Log ( rotationValue );

        if ( rotationValue == rotationAnswer)
        {
            Debug.Log ( "Correct" );
            switch (this.name )
            {
            case "tile1":

            }

            Debug.Log ( GameObject.Find("GameComplete").GetComponent<TileGameComplete>().totalCorrectTiles ))

        } else {
        Debug.Log ( "Wrong" );
        }
    }
}

Here is my basic code for the detection and complete game script

using UnityEngine;
using System.Collections;

public class TileGameComplete : MonoBehaviour {

    public int currentCorrectTiles = 0;
    public bool tile1 = false;
    public bool tile2 = false;
    public int totalCorrectTiles = 15;
    // Use this for initialization

    void Update()
    {
        GameObject.Find("Tile1").GetComponent<rotate>().done
        if (tile1 && tile2)
        {
            Debug.Log ("You've won");
        }
    }
}

How would you go about solving this problem in C#. Thanks :)


来源: stackexchange

问:
Why getApplicationContext and Activity context inflate different style of the spinner?
I have a strange problem. I have 2 pre-defined spinner in the xml. However, the item and related dropdown item are rendering in runtime.

However, the following 2 statement provide different result of the layout. I have no idea why the result is like this. But the main difference is getApplicationContext() and this

```<code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_item, getSrvNumList());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
</code>```

```<code> ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
        android.R.layout.simple_spinner_item, getSrvNumList());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
</code>```

答:
As  @MikeM. commented, it is the issue about the context. Hope the following answer can help someone with this issue.

Use Activity context instead of Application context

```<code>ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyActivity.this,
        android.R.layout.simple_spinner_item, getSrvNumList());
</code>```

Otherwise, the application will get different theme to render the spinner.

ContentLicense: CC BY-SA 3.0

Body:
I have a strange problem. I have 2 pre-defined spinner in the xml. However, the item and related dropdown item are rendering in runtime.

However, the following 2 statement provide different result of the layout. I have no idea why the result is like this. But the main difference is getApplicationContext() and this

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_item, getSrvNumList());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
        android.R.layout.simple_spinner_item, getSrvNumList());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Body:
As  @MikeM. commented, it is the issue about the context. Hope the following answer can help someone with this issue.

Use Activity context instead of Application context

ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyActivity.this,
        android.R.layout.simple_spinner_item, getSrvNumList());

Otherwise, the application will get different theme to render the spinner.


问:
How to convert JSON string to Avro in Python?
Is there a way to convert a JSON string to an Avro without a schema definition in Python? Or is this something only Java can handle?</p>

答:
This should help:

```<code>b = BytesIO(b'some message')
reader = DataFileReader(b, DatumReader())
</code>```

For more information take a look at this Avro Python Guide.

ContentLicense: CC BY-SA 4.0

Body:
This should help:

b = BytesIO(b'some message')
reader = DataFileReader(b, DatumReader())

For more information take a look at this Avro Python Guide.


问:
Inserting breakpoints on Eclipse for an Android program
I'm using Eclipse 3.3 and Android 1.6. I installed DDMS on my Eclipse and tried to insert breakpoints as in tutorial https://www.ibm.com/developerworks/library/os-ecbug/ . However, as I run my project, the program won't stop when it reaches the breakpoint. Is there a bug in Eclipse or am I doing something wrong?</p>

答: My breakpoints haven't been working either.  In my debug configuration on the Android tab, I had the launch action set to "Do Nothing".  When I changed that to instead launch directly into an activity, my breakpoints started working. </p>

OwnerDisplayName: Jaska

ContentLicense: CC BY-SA 2.5


问:
Java calculate week number with February first week as no.1 week?
I am trying to calculate week numbers where the start of the week number must start with February first week. For example. Feb 2-feb 8 2015 the week number must be 1. Please help me as I am new to this environment and I am able to calculate the week numbers starting with January first week.

To add more context I am trying to implement a Broadcast calendar in java with week 1 starting from February.

答:
java.time

The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify your desired date as an anchor date, a date from which we count weeks. You want ordinal week numbers, so add one to avoid a week numbered zero.

The ChronoUnit enum offers the between method to calculate elapsed time.

```<code>LocalDate anchor = LocalDate.of( 2015 , Month.FEBRUARY , 2 );

LocalDate feb5 = LocalDate.of( 2015 , Month.FEBRUARY , 5 );
LocalDate feb8 = LocalDate.of( 2015 , Month.FEBRUARY , 8 );
LocalDate feb9 = LocalDate.of( 2015 , Month.FEBRUARY , 9 );

System.out.println( feb5 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb5 ) + 1 ) );
System.out.println( feb8 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb8 ) + 1 ) );
System.out.println( feb9 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb9 ) + 1 ) );
</code>```

See this code run live at IdeOne.com.

2015-02-05 is in week # 1

2015-02-08 is in week # 1

2015-02-09 is in week # 2

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
java.time

The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify your desired date as an anchor date, a date from which we count weeks. You want ordinal week numbers, so add one to avoid a week numbered zero.

The ChronoUnit enum offers the between method to calculate elapsed time.

LocalDate anchor = LocalDate.of( 2015 , Month.FEBRUARY , 2 );

LocalDate feb5 = LocalDate.of( 2015 , Month.FEBRUARY , 5 );
LocalDate feb8 = LocalDate.of( 2015 , Month.FEBRUARY , 8 );
LocalDate feb9 = LocalDate.of( 2015 , Month.FEBRUARY , 9 );

System.out.println( feb5 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb5 ) + 1 ) );
System.out.println( feb8 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb8 ) + 1 ) );
System.out.println( feb9 + " is in week # " + ( ChronoUnit.WEEKS.between( anchor , feb9 ) + 1 ) );

See this code run live at IdeOne.com.

2015-02-05 is in week # 1

2015-02-08 is in week # 1

2015-02-09 is in week # 2

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
.show() and .toggle() will not reveal final game screen in trivia game

I have gone over and over the code. I've tried to show the final game screen (result-screen) with JQuery and then again by defining global variables. I have called it as part of another function and within its own function. No combination I come up with is displaying my final result-screen.

```<code>var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               playerInteract.answerCheck()
               playerInteract.gameOverLoad()
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds);
</code>```

<----HTML---->

```<code><div id="welcome-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">
    <h1>Take a stab at it!</h1>
    <button id=start-button><h2>STAB!</h2></button>

</div>

<div id="game-screen" class="container">
    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h2>Take a stab at it!</h2>
    <h3>Time Remaining: <div id="countdown"></div></h3>

    <img id="penny" src="assets/images/penny.png" alt="Pennywise the clown.">

    <h4>What's the name of the killer clown in Stephen King's novel, <em>IT</em>?</h4>

        <div class="answer-boxes">
            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko
        </div>

    <img id="georgie" src="assets/images/georgie.png" alt="Georgie from 'It'">

    <h4>Which King protagonist went crazy and killed<br> most of her classmates and teachers during prom?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie
        </div>

    <h4>Stephen King regularly contributed to <em>Dave's Rag</em> in high school.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False
        </div>

    <h4>What year and model car was featured <br>in the movie <em>Christine</em> based on a Stephen King book?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury
        </div>

    <h4>Mike Hanlon made seven phone calls in Stephen King's novel, <em>IT</em>.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False
    </div>

    <h4>What's the name of Stephen King's western/fantasy saga?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q6"class="radio-button" id="correct6"> <em>The Dark Tower</em>
        <input type="radio" name="q6"class="radio-button" id="wrongL"> <em>The Darkest Hour</em>
        <input type="radio" name="q6"class="radio-button" id="wrongM"> <em>The Dark Knight</em>
        <input type="radio" name="q6"class="radio-button" id="wrongN"> <em>The Dark Travels</em>
    </div>

    <h4>Which of the below is a Stephen King pseudonym?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders
    </div>

    <h4>One of Stephen King's jobs prior to publication was as a high school teacher.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase
    </div>

<div id="result-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h1>All Done!</h1>
    <h4>Correct Answers: <div id="correct-answers"></div></h4>
    <h4>Incorrect Answers: <div id="incorrect-answers"></div></h4>
    <h4>Unanswered: <div id="unanswered"></div></h4>

</div>
</code>```

The only code I have eliminated from my JS is the answerCheck function.

After the setTimeout concludes, I want the game screen to hide and the result screen to show. Hide, show, toggle all work in the code up until the timeout finishes.

The game screen hides, leaving the background the only thing visible. The console.log to print gameover to the log runs. No errors in the console.

答:
**EDIT. Ok, I think the div "game-screen" is missing the closing div tag in the html. I updated it in the snippet below.

I also commented out playerInteract.answerCheck() as that function is not in the code like you mentioned, and it fires an error.

var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               //playerInteract.answerCheck();
               playerInteract.gameOverLoad();
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds); ```
<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 id="welcome-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">
    <h1>Take a stab at it!</h1>
    <button id=start-button><h2>STAB!</h2></button>

</div>

<div id="game-screen" class="container">
    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h2>Take a stab at it!</h2>
    <h3>Time Remaining: <div id="countdown"></div></h3>

    <img id="penny" src="assets/images/penny.png" alt="Pennywise the clown.">

    <h4>What's the name of the killer clown in Stephen King's novel, <em>IT</em>?</h4>

        <div class="answer-boxes">
            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko
        </div>

    <img id="georgie" src="assets/images/georgie.png" alt="Georgie from 'It'">

    <h4>Which King protagonist went crazy and killed<br> most of her classmates and teachers during prom?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie
        </div>

    <h4>Stephen King regularly contributed to <em>Dave's Rag</em> in high school.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False
        </div>

    <h4>What year and model car was featured <br>in the movie <em>Christine</em> based on a Stephen King book?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury
        </div>

    <h4>Mike Hanlon made seven phone calls in Stephen King's novel, <em>IT</em>.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False
    </div>

    <h4>Wha's the name of Stephen King's western/fantasy saga?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q6"class="radio-button" id="correct6"> <em>The Dark Tower</em>
        <input type="radio" name="q6"class="radio-button" id="wrongL"> <em>The Darkest Hour</em>
        <input type="radio" name="q6"class="radio-button" id="wrongM"> <em>The Dark Knight</em>
        <input type="radio" name="q6"class="radio-button" id="wrongN"> <em>The Dark Travels</em>
    </div>

    <h4>Which of the below is a Stephen King pseudonym?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders
    </div>

    <h4>One of Stephen King's jobs prior to publication was as a high school teacher.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase
    </div>

</div><!-- #game-screen -->

<div id="result-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h1>All Done!</h1>
    <h4>Correct Answers: <div id="correct-answers"></div></h4>
    <h4>Incorrect Answers: <div id="incorrect-answers"></div></h4>
    <h4>Unanswered: <div id="unanswered"></div></h4>

</div></code>```

Body:
I have gone over and over the code. I've tried to show the final game screen (result-screen) with JQuery and then again by defining global variables. I have called it as part of another function and within its own function. No combination I come up with is displaying my final result-screen.

var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               playerInteract.answerCheck()
               playerInteract.gameOverLoad()
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds);

<----HTML---->

Take a stab at it!

    <button id=start-button>
STAB!
</button>

Take a stab at it!

Time Remaining:

What's the name of the killer clown in Stephen King's novel, IT?

            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko

Which King protagonist went crazy and killed
 most of her classmates and teachers during prom?

        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie

Stephen King regularly contributed to Dave's Rag in high school.

        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False

What year and model car was featured
in the movie Christine based on a Stephen King book?

        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury

Mike Hanlon made seven phone calls in Stephen King's novel, IT.

        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False

What's the name of Stephen King's western/fantasy saga?

        <input type="radio" name="q6"class="radio-button" id="correct6"> The Dark Tower
        <input type="radio" name="q6"class="radio-button" id="wrongL"> The Darkest Hour
        <input type="radio" name="q6"class="radio-button" id="wrongM"> The Dark Knight
        <input type="radio" name="q6"class="radio-button" id="wrongN"> The Dark Travels

Which of the below is a Stephen King pseudonym?

        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders

One of Stephen King's jobs prior to publication was as a high school teacher.

        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase

All Done!

Correct Answers:

Incorrect Answers:

Unanswered:

The only code I have eliminated from my JS is the answerCheck function.

After the setTimeout concludes, I want the game screen to hide and the result screen to show. Hide, show, toggle all work in the code up until the timeout finishes.

The game screen hides, leaving the background the only thing visible. The console.log to print gameover to the log runs. No errors in the console.

Body:
**EDIT. Ok, I think the div "game-screen" is missing the closing div tag in the html. I updated it in the snippet below.

I also commented out playerInteract.answerCheck() as that function is not in the code like you mentioned, and it fires an error.

var welcome = $("#welcome-screen")
var gameOver = $("#result-screen")
var game = $("#game-screen")

var playerInteract = {
    correctAnswers: 0,
    incorrectAnswers: 0,
    unanswered: 8,
    seconds: 10,
    //done: false,

    welcome: function() {
        gameOver.toggle();
        game.hide();
    },

    initiate: function() {
        welcome.hide();
        game.show();
        playerInteract.timer();
    },

    timer: function() {
        var windowTimeout = setTimeout(function() {
            //playerInteract.gameOver()
            game.hide()
               //playerInteract.answerCheck();
               playerInteract.gameOverLoad();
            },  10000);
        var intervalVariable = setInterval(playerInteract.decrement, 1000);
        var seconds = playerInteract.seconds;

    },

    decrement: function () {
        if (playerInteract.seconds >= 2) {
                playerInteract.seconds--;
                console.log("seconds: " + playerInteract.seconds);
                $("#countdown").text(playerInteract.seconds);
            }
    },
   gameOverLoad: function() {
       gameOver.show();
       console.log("gameover");
   }

};

window.onload = playerInteract.welcome;

$("#start-button").on("click", function(event) {
    //event.preventDefault()
    playerInteract.initiate()
});

$("#countdown").text(playerInteract.seconds);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="welcome-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">
    <h1>Take a stab at it!</h1>
    <button id=start-button><h2>STAB!</h2></button>

</div>

<div id="game-screen" class="container">
    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h2>Take a stab at it!</h2>
    <h3>Time Remaining: <div id="countdown"></div></h3>

    <img id="penny" src="assets/images/penny.png" alt="Pennywise the clown.">

    <h4>What's the name of the killer clown in Stephen King's novel, <em>IT</em>?</h4>

        <div class="answer-boxes">
            <input type="radio" name="q1" class="radio-button" id="wrongA"> Torchy
            <input type="radio" name="q1" class="radio-button" id="wrongB"> Quarterdumb
            <input type="radio" name="q1" class="radio-button" id="correct1"> Pennywise
            <input type="radio" name="q1" class="radio-button" id="wrongC"> Boinko
        </div>

    <img id="georgie" src="assets/images/georgie.png" alt="Georgie from 'It'">

    <h4>Which King protagonist went crazy and killed<br> most of her classmates and teachers during prom?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q2" class="radio-button" id="wrongD"> Sandy
        <input type="radio" name="q2" class="radio-button" id="wrongE"> Dolores
        <input type="radio" name="q2" class="radio-button" id="wrongF"> Sherrie
        <input type="radio" name="q2" class="radio-button" id="correct2"> Carrie
        </div>

    <h4>Stephen King regularly contributed to <em>Dave's Rag</em> in high school.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q3" class="radio-button" id="correct3"> True
        <input type="radio" name="q3" class="radio-bitton" id="wrongG"> False
        </div>

    <h4>What year and model car was featured <br>in the movie <em>Christine</em> based on a Stephen King book?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q4" class="radio-button" id="wrongH"> 1962 Ford Mustang
        <input type="radio" name="q4" class="radio-button" id="wrongI"> 1957 Chevy Chevelle
        <input type="radio" name="q4" class="radio-button" id="wrongJ"> 1951 Jaquar XK 120
        <input type="radio" name="q4" class="radio-button" id="corrcet4"> 1958 Plymouth Fury
        </div>

    <h4>Mike Hanlon made seven phone calls in Stephen King's novel, <em>IT</em>.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q5" class="radio-button" id="wrongK"> True
        <input type="radio" name="q5" class="radio-button" id="correct5"> False
    </div>

    <h4>Wha's the name of Stephen King's western/fantasy saga?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q6"class="radio-button" id="correct6"> <em>The Dark Tower</em>
        <input type="radio" name="q6"class="radio-button" id="wrongL"> <em>The Darkest Hour</em>
        <input type="radio" name="q6"class="radio-button" id="wrongM"> <em>The Dark Knight</em>
        <input type="radio" name="q6"class="radio-button" id="wrongN"> <em>The Dark Travels</em>
    </div>

    <h4>Which of the below is a Stephen King pseudonym?</h4>

    <div class="answer-boxes">
        <input type="radio" name="q7" class="radio-button" id="wrongO"> Dick Hallorann
        <input type="radio" name="q7" class="radio-button" id="correct7"> Richard Bachman
        <input type="radio" name="q7" class="radio-button" id="wrongP"> Sam Paul
        <input type="radio" name="q7" class="radio-button" id="wrongQ"> Benjamin Sanders
    </div>

    <h4>One of Stephen King's jobs prior to publication was as a high school teacher.</h4>

    <div class="answer-boxes">
        <input type="radio" name="q8" class="radio-button" id="correct8"> True
        <input type="radio" name="q8" class="radio-button" id="wrongR"> Flase
    </div>

</div><!-- #game-screen -->

<div id="result-screen" class="container">

    <img id="header" src="assets/images/header-image.png" alt="Stephen King Killer Trivia">

    <h1>All Done!</h1>
    <h4>Correct Answers: <div id="correct-answers"></div></h4>
    <h4>Incorrect Answers: <div id="incorrect-answers"></div></h4>
    <h4>Unanswered: <div id="unanswered"></div></h4>

</div>


问:
Set div background color to inherit when checkbox is unchecked
I currently have checkboxes in groups; I want to be able to set color of unchecked checkboxes when a checkbox is checked.

var name = $("input:checkbox[name='fooby[2][]']:checked").prop('id')
var unique_id = $(this).parent().find('label[for="' + name + '"]').find('div.eachText').attr('id')
var2 = $("input:checkbox[name='fooby[2][]']:checked")
if ($(var2).is(":checked")) {
  $("input:checkbox[name='fooby[2][]']:checked").map(function() {
    document.getElementById(unique_id).style.backgroundColor = 'grey';
  })

} else {
  document.getElementById(unique_id).style.backgroundColor = 'inherit'
}```
<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>
<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />
<label for="group4">
    <div  id="test1" class="eachText ">
        dTLA
        <div class="l_desc ">
            555 West 5th street, 34th floor<br> 811 W 7th St
        </div>

    </div>
</label>
<input type="checkbox " class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />
<label for="group5 " class="eachText1">
<div id="test2" class="eachText">
  Long Beach
  <div class="l_desc">
    100 W Broadway
  </div>
</div>
</label></code>```

My goal is to be able to set checkbox to grey when checked and to inherit when unchecked.

答:
No need for JavaScript to set the color with that markup. Just use CSS checked and sibling selector

input[type="checkbox"]:checked + label > div {
   background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />
<label for="group4">
    <div  id="test1" class="eachText ">
        dTLA
        <div class="l_desc ">
            555 West 5th street, 34th floor<br> 811 W 7th St
        </div>

    </div>
</label>
<input type="checkbox" class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />
<label for="group5 " class="eachText1">
<div id="test2" class="eachText">
  Long Beach
  <div class="l_desc">
    100 W Broadway
  </div>
</div>
</label></code>```

Body:
I currently have checkboxes in groups; I want to be able to set color of unchecked checkboxes when a checkbox is checked.

var name = $("input:checkbox[name='fooby[2][]']:checked").prop('id')
var unique_id = $(this).parent().find('label[for="' + name + '"]').find('div.eachText').attr('id')
var2 = $("input:checkbox[name='fooby[2][]']:checked")
if ($(var2).is(":checked")) {
  $("input:checkbox[name='fooby[2][]']:checked").map(function() {
    document.getElementById(unique_id).style.backgroundColor = 'grey';
  })

} else {
  document.getElementById(unique_id).style.backgroundColor = 'inherit'
}

<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />

        dTLA

            555 West 5th street, 34th floor
 811 W 7th St

<input type="checkbox " class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />

  Long Beach

    100 W Broadway

My goal is to be able to set checkbox to grey when checked and to inherit when unchecked.

Body:
No need for JavaScript to set the color with that markup. Just use CSS checked and sibling selector

input[type="checkbox"]:checked + label > div {
   background-color: red;
}

<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />
<label for="group4">
    <div  id="test1" class="eachText ">
        dTLA
        <div class="l_desc ">
            555 West 5th street, 34th floor<br> 811 W 7th St
        </div>

    </div>
</label>
<input type="checkbox" class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />
<label for="group5 " class="eachText1">
<div id="test2" class="eachText">
  Long Beach
  <div class="l_desc">
    100 W Broadway
  </div>
</div>
</label>


问:
How to order by custom rule, e.g. how to order like 4,2,1,3
I am not sure that the title is saying it right, most probably it does not :)

So I have products table and I want to order them by the season they are made for.

If 'spring' is 1, 'summer' - 2 , 'autumn' - 3 and 'winter' - 4, how can I order them in such way so it shows the 'summer' first, then 'spring', then 'winter' and at the end 'autumn'. So like 2,1,4,3.

And to clarify it more, I want to be able to change the rule. It might be 2,1,4,3 or 4,2,1,3, etc. This is to show the season products on top.

Hope that explanation helps to get the problem. Any solutions are welcomed. Database is MySQL, language PHP.

答:
This should work for all major dbms:

```<code>order
   by case when season = 2 then 1
           when season = 1 then 2
           when season = 4 then 3
           when season = 3 then 4
       end;
</code>```

You could also add a column to your season table to indicate how they should be sorted:

```<code>table season(
   season_id int
  ,ordinal   int
);

select ...
  from tab t
  join seasons s on(t.season_id = s.season_id)
 order
    by s.ordinal;
</code>```

...or, if you feel like writing non-portable code you can use:

```<code>order by field(season_id, 2,1,4,3);
</code>```

Body:
This should work for all major dbms:

order
   by case when season = 2 then 1
           when season = 1 then 2
           when season = 4 then 3
           when season = 3 then 4
       end;

You could also add a column to your season table to indicate how they should be sorted:

table season(
   season_id int
  ,ordinal   int
);

select ...
  from tab t
  join seasons s on(t.season_id = s.season_id)
 order
    by s.ordinal;

...or, if you feel like writing non-portable code you can use:

order by field(season_id, 2,1,4,3);


问:
How to query average difference in ratings between a user and all other users
I have a Postgres table of book ratings with the following structure:

id serial primary key,
userid integer not null,
bookid integer not null,
rating integer not null

I want to extract the average difference between a given user's ratings and and every other user's ratings, each considered separately. Put another way, as a user, I want to know what the average difference between my ratings and some x user's ratings, for all x. Ultimately, I want to be able to put this average number in a new SQL table alongside ids for the given user and the user being compared.

I'm pretty unfamilar with SQL past simple queries, and I've implemented a solution that dances back and forth between Javascript loops and SQL queries. I'm looking for something as clean as possible if anyone is willing to help.

EDIT: Here's a short example of data and ideal output.

```<code>id,userid,bookid,rating

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

Here is the ideal output, structured as another sql table:

```<code>id serial primary key,
currentuser integer not null,
compareuser integer not null,
averagediff float not null

id,currentuser,compareuser,averagediff

1,1,2,0
2,1,3,2.33333
</code>```

答:
This can be done with a self join.</p>

```<code>select t1.userid as current_user,t2.userid as compare_user
,avg(abs(t1.rating-t2.rating)) as average_difference
from tbl t1
join tbl t2 on t1.userid<t2.userid and t1.bookid=t2.bookid
group by t1.userid,t2.userid
</code>```

Body:
I have a Postgres table of book ratings with the following structure:

id serial primary key,
userid integer not null,
bookid integer not null,
rating integer not null

I want to extract the average difference between a given user's ratings and and every other user's ratings, each considered separately. Put another way, as a user, I want to know what the average difference between my ratings and some x user's ratings, for all x. Ultimately, I want to be able to put this average number in a new SQL table alongside ids for the given user and the user being compared.

I'm pretty unfamilar with SQL past simple queries, and I've implemented a solution that dances back and forth between Javascript loops and SQL queries. I'm looking for something as clean as possible if anyone is willing to help.

EDIT: Here's a short example of data and ideal output.

id,userid,bookid,rating

1,1,1,5
2,1,2,2
3,1,3,3
4,1,4,3
5,1,5,1
6,2,1,5
7,2,2,2
8,3,1,1
9,3,2,5
10,3,3,3

Here is the ideal output, structured as another sql table:

id serial primary key,
currentuser integer not null,
compareuser integer not null,
averagediff float not null

id,currentuser,compareuser,averagediff

1,1,2,0
2,1,3,2.33333

Body:
This can be done with a self join.

select t1.userid as current_user,t2.userid as compare_user
,avg(abs(t1.rating-t2.rating)) as average_difference
from tbl t1
join tbl t2 on t1.userid<t2.userid and t1.bookid=t2.bookid
group by t1.userid,t2.userid


问:
docker + dotnet watch
I use Visual studio Code.

I create a new projet dotnet new webapi. I have referenced dotnet-watch in my .csproj :
    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
        <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
        <DotNetCliToolReference Include="Microsoft.Extensions.Caching.SqlConfig.Tools" Version="2.0.0" />
    </ItemGroup>

Then, I Build my DockerFile.

I notice strange behavior. The docker image detects the changes and rebuilds the solution. The binary files have been updated in bin and obj directory but when I call the api, it is as if there had never been any change.

```<code>FROM microsoft/aspnetcore-build:2.0

COPY . /app
WORKDIR /app

ENV ASPNETCORE_URLS=http://*:5000
EXPOSE 5000

ENV DOTNET_USE_POLLING_FILE_WATCHER=1
ENV ASPNETCORE_ENVIRONMENT=Development
</code>```

Docker command : docker run -i -p 5000:5000 -v $(pwd):/app -t docker-todoapi

finally in the container terminal : docker restore and docker Watch run

答:
This blog post describes the current issues, but also how to get around the issues:

http://www.natemcmaster.com/blog/2017/11/13/dotnet-watch-and-docker/

To summarize changes you need:

Use version 2.1.0-preview1-27567 of Microsoft.DotNet.Watcher.Tools.

To get this preview version you need to add a NuGet.config file to your project directory:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="aspnetcore-nightly" value="https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json" />
    <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>
</code>```

The bin and obj directories used in Docker must be separated from those used by Visual Studio Code, or you will have the problems you are currently seeing.

To do this the bin and obj directories must be placed in a rather odd place outside of the project directory, which can be accomplished by adding a file called Directory.Build.props to your project directory:

```<code><Project>
  <PropertyGroup>
    <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/../obj/</BaseIntermediateOutputPath>
    <BaseOutputPath>$(MSBuildProjectDirectory)/../bin/</BaseOutputPath>
  </PropertyGroup>
</Project>
</code>```

You must also delete the old bin and obj directories from your project directory.

Title: docker + dotnet watch

Body:
I use Visual studio Code.

I create a new projet dotnet new webapi. I have referenced dotnet-watch in my .csproj :
    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
        <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
        <DotNetCliToolReference Include="Microsoft.Extensions.Caching.SqlConfig.Tools" Version="2.0.0" />
    </ItemGroup>

Then, I Build my DockerFile.

I notice strange behavior. The docker image detects the changes and rebuilds the solution. The binary files have been updated in bin and obj directory but when I call the api, it is as if there had never been any change.

FROM microsoft/aspnetcore-build:2.0

COPY . /app
WORKDIR /app

ENV ASPNETCORE_URLS=http://*:5000
EXPOSE 5000

ENV DOTNET_USE_POLLING_FILE_WATCHER=1
ENV ASPNETCORE_ENVIRONMENT=Development

Docker command : docker run -i -p 5000:5000 -v $(pwd):/app -t docker-todoapi

finally in the container terminal : docker restore and docker Watch run

Body:
This blog post describes the current issues, but also how to get around the issues:

http://www.natemcmaster.com/blog/2017/11/13/dotnet-watch-and-docker/

To summarize changes you need:

Use version 2.1.0-preview1-27567 of Microsoft.DotNet.Watcher.Tools.

To get this preview version you need to add a NuGet.config file to your project directory:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="aspnetcore-nightly" value="https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json" />
    <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

The bin and obj directories used in Docker must be separated from those used by Visual Studio Code, or you will have the problems you are currently seeing.

To do this the bin and obj directories must be placed in a rather odd place outside of the project directory, which can be accomplished by adding a file called Directory.Build.props to your project directory:

<Project>
  <PropertyGroup>
    <BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/../obj/</BaseIntermediateOutputPath>
    <BaseOutputPath>$(MSBuildProjectDirectory)/../bin/</BaseOutputPath>
  </PropertyGroup>
</Project>

You must also delete the old bin and obj directories from your project directory.


问:
Node JS Mocha Test Cases Not running
I am trying to set up a test suite with test cases.  For some reason non of the hooks our firing, so I made the test cases as simple as possible.  Still none of the debug.log print out except the one before describe.  It is almost like the code does not see any of my mocha test.  I have mocha installed locally as a dev dependency.  It also returns a number of test cases passed even though I don't have that number of test cases in my code.  I have tried uninstalling and re-installing mocha.

The terminal returns
**/test/runner.js
Entered Org Runner
Config setup DB info: mongodb://xxxxx:xxxxxxxx@localhost/icpDB

657 tests. 0 failures. 268 ms

Process finished with exit code 0

```<code>    const mocha = require('mocha');
const chai = require('chai');
const debug = require('debug');

debug.log('Entered Org Runner');
describe('Org api test suite', function () {
  before(function (done) {
    debug.log('Entered Org Before');
    done();
  });
  after(function (done) {
    debug.log('Entered Org After');
    done();
  });

  it('should create a new org', function (done) {
    debug.log('Entered Create Org It');
    done();
  });

  describe('GET Orgs', function () {
    it('should respond with an array of orgs', function (done) {
      debug.log('Entered Get Orgs It');
      done();
    });
  });

  describe('GET Org', function () {
    it('should get a org by id', function (done) {
      debug.log('It: should get a org by id');
      done();
    });

    it('should throw an error for invalid id', function (done) {
      debug.log('It: should throw an error for invalid id');
      done();
    });
  });

  describe('Update Org', function () {
    it('should update an existing org', function (done) {
      debug.log('should update an existing org');
      done();
    });
  });

  describe('Delete Org', function () {
    it('should delete an existing org', function (done) {
      debug.log('should delete an existing org');
      done();
    });
  });
});
</code>```

答: It turns out the issue was using --recursive in my package.json.  One of the test cases was causing mocha to exit.  When I point it directly to the specific file above, it executes as expected.</p>

Title: Node JS Mocha Test Cases Not running

Body:
I am trying to set up a test suite with test cases.  For some reason non of the hooks our firing, so I made the test cases as simple as possible.  Still none of the debug.log print out except the one before describe.  It is almost like the code does not see any of my mocha test.  I have mocha installed locally as a dev dependency.  It also returns a number of test cases passed even though I don't have that number of test cases in my code.  I have tried uninstalling and re-installing mocha.

The terminal returns
**/test/runner.js
Entered Org Runner
Config setup DB info: mongodb://xxxxx:xxxxxxxx@localhost/icpDB

657 tests. 0 failures. 268 ms

Process finished with exit code 0

    const mocha = require('mocha');
const chai = require('chai');
const debug = require('debug');

debug.log('Entered Org Runner');
describe('Org api test suite', function () {
  before(function (done) {
    debug.log('Entered Org Before');
    done();
  });
  after(function (done) {
    debug.log('Entered Org After');
    done();
  });

  it('should create a new org', function (done) {
    debug.log('Entered Create Org It');
    done();
  });

  describe('GET Orgs', function () {
    it('should respond with an array of orgs', function (done) {
      debug.log('Entered Get Orgs It');
      done();
    });
  });

  describe('GET Org', function () {
    it('should get a org by id', function (done) {
      debug.log('It: should get a org by id');
      done();
    });

    it('should throw an error for invalid id', function (done) {
      debug.log('It: should throw an error for invalid id');
      done();
    });
  });

  describe('Update Org', function () {
    it('should update an existing org', function (done) {
      debug.log('should update an existing org');
      done();
    });
  });

  describe('Delete Org', function () {
    it('should delete an existing org', function (done) {
      debug.log('should delete an existing org');
      done();
    });
  });
});


问:
Does AWS ECS support per container dynamic scalability?
Amazon's EC2 Container Service allows you to run any amount of containers you want, it will choose an EC2 instance(s) to run the containers on automatically. Which are great features. However, we are really concerned about automatic scalability.

Scenario:

I launch a container via AWS ECS Console.

The HTTP requests are starting to come up.

The HTTP load increases significantly with time.

CPU (or RAM) usage of the container is getting closer to 100%.

Question 1: Will ECS run one more container automatically?

Question 2: Will ECS automatically shut one of the containers down when CPU (or RAM) load gets low?

答:
As of Dec 2017 Amazon announced the new service called Fargate. Quoting the link:

AWS Fargate makes it easy to scale your applications. You no longer have to worry about provisioning enough compute resources for your container applications. After you define your application requirements (e.g., CPU, memory, etc.), AWS Fargate manages all the scaling and infrastructure needed to run your containers in a highly-available manner. You no longer have to decide when to scale your clusters or pack them for optimal utilization.

I assume the bold text means that Fargate will scale up and down the resources for me. Not 100% sure though.


问:
Ionic 2 Project - Promise issue with authentication
I've been searching for a solution to this problem I'm having, but haven't found anything that works for my particular case. I am working on an Ionic 2 application and I am working on some authentication stuff for my login screen. The purpose of this file is to add backend functionality to the front end code I wrote (refer to my login.html file on the github link below). I was following the tutorial on this website:
https://devdactic.com/login-ionic-2/

The problem I am having is that for certain functions, which will be marked in my code, I am getting a "Promise returned from (function) is ignored" which stops the code from functioning entirely. It doesn't come up as a compile error, but instead it is a runtime error that is:

Runtime Error
Uncaught (in promise): Error: No provider for Http! Error at d

I am really not sure what this means, so any insight would be very helpful. If needed, I can provide a picture of the full error.

```<code>@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  loading: Loading;
  registerCredentials = { email: '', password: ''};

  constructor(public navCtrl: NavController, private auth: AuthService, public navParams: NavParams,
  private alertCtrl: AlertController, private loadingCtrl: LoadingController) {}

  public createAccount() {
    this.navCtrl.push('RegisterPage'); //Promise ignored error
  }

  public login() {
    this.showLoading();
    this.auth.login(this.registerCredentials).subscribe(allowed => {
        if (allowed) {
          this.navCtrl.setRoot('HomePage'); //Promise ignored error
        } else {
          this.showError("Access Denied");
        }
      },
      error => {
        this.showError(error);
      });
  }

  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: 'Please wait...',
      dismissOnPageChange: true
    });
    this.loading.present(); //Promise ignored error
  }

  showError(text) {
    this.loading.dismiss(); //Promise ignored error

    let alert = this.alertCtrl.create({
      title: 'Fail',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present(prompt); //Promise ignored error
  }
}
</code>```

Picture of the error:

I am just not sure what is causing this problem, and it is causing my code to crash entirely and won't even load my UI. If you need to look at some of the other files, the rest is on my github, this particular file is located in /src/pages/login.

The rest of the files:
https://github.com/jparr721/Badmeat/tree/master/BadMeat-Ionic/FirstBuild/src

IDE: JetBrains WebStorm

OS: MacOS Sierra

Ionic Version: 2.2.2

答:
You probably figured it out already but try changing the public to private in your code over here:

```<code>constructor(public navCtrl: NavController,
</code>```

try:

```<code>constructor(private navCtrl: NavController,
</code>```

Body:
I've been searching for a solution to this problem I'm having, but haven't found anything that works for my particular case. I am working on an Ionic 2 application and I am working on some authentication stuff for my login screen. The purpose of this file is to add backend functionality to the front end code I wrote (refer to my login.html file on the github link below). I was following the tutorial on this website:
https://devdactic.com/login-ionic-2/

The problem I am having is that for certain functions, which will be marked in my code, I am getting a "Promise returned from (function) is ignored" which stops the code from functioning entirely. It doesn't come up as a compile error, but instead it is a runtime error that is:

Runtime Error
Uncaught (in promise): Error: No provider for Http! Error at d

I am really not sure what this means, so any insight would be very helpful. If needed, I can provide a picture of the full error.

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  loading: Loading;
  registerCredentials = { email: '', password: ''};

  constructor(public navCtrl: NavController, private auth: AuthService, public navParams: NavParams,
  private alertCtrl: AlertController, private loadingCtrl: LoadingController) {}

  public createAccount() {
    this.navCtrl.push('RegisterPage'); //Promise ignored error
  }

  public login() {
    this.showLoading();
    this.auth.login(this.registerCredentials).subscribe(allowed => {
        if (allowed) {
          this.navCtrl.setRoot('HomePage'); //Promise ignored error
        } else {
          this.showError("Access Denied");
        }
      },
      error => {
        this.showError(error);
      });
  }

  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: 'Please wait...',
      dismissOnPageChange: true
    });
    this.loading.present(); //Promise ignored error
  }

  showError(text) {
    this.loading.dismiss(); //Promise ignored error

    let alert = this.alertCtrl.create({
      title: 'Fail',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present(prompt); //Promise ignored error
  }
}

Picture of the error:

I am just not sure what is causing this problem, and it is causing my code to crash entirely and won't even load my UI. If you need to look at some of the other files, the rest is on my github, this particular file is located in /src/pages/login.

The rest of the files:
https://github.com/jparr721/Badmeat/tree/master/BadMeat-Ionic/FirstBuild/src

IDE: JetBrains WebStorm

OS: MacOS Sierra

Ionic Version: 2.2.2

Body:
You probably figured it out already but try changing the public to private in your code over here:

constructor(public navCtrl: NavController,

try:

constructor(private navCtrl: NavController,


问:
Google Forms Onclick Submit
I have created a simple Google Form with two multiple choice answers (Yes and No). Image below.

The form works fine when I select an answer then click the submit button.

I'm wondering if it's possible to submit the form immediately when an option is selected? Then refresh the page.

I've been reading about triggers here but not sure where to start, or if it's even possible.

Google Forms is my only option at current, I know this is possible via other methods.

Any advice is appreciated.

答:
I'm wondering if it's possible to submit the form immediately when an option is selected? Then refresh the page.

No, it's not possible. The only trigger that works on the form respondent view is on form submit.

The workaround is to create your own form. If you want to work with Google Apps Script, you should use the HTML Service.

Title: Google Forms Onclick Submit


问:
How to get python to recognize "YYYY W##" as date time object and then fill add time objects less than a certain week
I have a dataframe consisting of columns Name (names), value (the week in 2016 that an event occurred), binary (an indication that the event occurred, "1"), for example:

```<code>df
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W17   1
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
</code>```

I am interested in adding rows to this dataframe so that each Name (apple, orange, etc.) has an item in the value column for the weeks before an event occurred. Again, the week that the event occurred is stated as the value column in df. The time period of interest is the weeks between 2016 W16 and 2016 W19, e.g.:

```<code>start_end_weeks
     week
     2016 W16
     2016 W17
     2016 W18
     2016 W19
</code>```

My problem is that I need to in-fill the rows with weeks between 2016 W16 and 2016 W19 that are not represented in df. Here's what I mean:

```<code>df_result
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W16   0
    orange    2016 W17   1
    melon     2016 W16   0
    melon     2016 W17   0
    melon     2016 W18   0
    melon     2016 W19   0
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
    ...
</code>```

But since value isn't a traditional date time object, I'm not sure how to get python to recognize that 2016 W16 occurs before 2016 W17, and then to only in-fill the values before the week stated in value in df.

I am having trouble with where to start, so if someone could help me convert value to a date time object that would be great, and I can go from there. Any other insight appreciated.

I found this stack overflow question which is all I have so far: Match rows in one Pandas dataframe to another based on three columns.

答:
If you need convert to date

```<code>import datetime
df.value.apply(lambda x : datetime.datetime.strptime(x + '-0', "%Y W%W-%w"))
Out[133]:
0   2016-04-24
1   2016-05-01
2   2016-05-22
3   2016-05-01
4   2016-05-15
Name: value, dtype: datetime64[ns]
</code>```

without change the date I am going to use reindex with groupby

```<code>df1=df.groupby('Name')['binary','value'].apply(lambda x : x.set_index('value').\
           reindex(['2016 W16','2016 W17','2016 W18','2016 W19','2016 W20']))

df1.loc[df1.groupby(level=0).binary.bfill().dropna().index].fillna(0).reset_index()
Out[65]:
      Name     value  binary
0    apple  2016 W16     1.0
1    berry  2016 W16     0.0
2    berry  2016 W17     1.0
3     lime  2016 W16     0.0
4     lime  2016 W17     0.0
5     lime  2016 W18     0.0
6     lime  2016 W19     1.0
7    melon  2016 W16     0.0
8    melon  2016 W17     0.0
9    melon  2016 W18     0.0
10   melon  2016 W19     0.0
11   melon  2016 W20     1.0
12  orange  2016 W16     0.0
13  orange  2016 W17     1.0
</code>```

Body:
I have a dataframe consisting of columns Name (names), value (the week in 2016 that an event occurred), binary (an indication that the event occurred, "1"), for example:

df
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W17   1
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1

I am interested in adding rows to this dataframe so that each Name (apple, orange, etc.) has an item in the value column for the weeks before an event occurred. Again, the week that the event occurred is stated as the value column in df. The time period of interest is the weeks between 2016 W16 and 2016 W19, e.g.:

start_end_weeks
     week
     2016 W16
     2016 W17
     2016 W18
     2016 W19

My problem is that I need to in-fill the rows with weeks between 2016 W16 and 2016 W19 that are not represented in df. Here's what I mean:

df_result
    Name      value      binary
    apple     2016 W16   1
    orange    2016 W16   0
    orange    2016 W17   1
    melon     2016 W16   0
    melon     2016 W17   0
    melon     2016 W18   0
    melon     2016 W19   0
    melon     2016 W20   1
    berry     2016 W17   1
    lime      2016 W19   1
    ...

But since value isn't a traditional date time object, I'm not sure how to get python to recognize that 2016 W16 occurs before 2016 W17, and then to only in-fill the values before the week stated in value in df.

I am having trouble with where to start, so if someone could help me convert value to a date time object that would be great, and I can go from there. Any other insight appreciated.

I found this stack overflow question which is all I have so far: Match rows in one Pandas dataframe to another based on three columns.

Body:
If you need convert to date

import datetime
df.value.apply(lambda x : datetime.datetime.strptime(x + '-0', "%Y W%W-%w"))
Out[133]:
0   2016-04-24
1   2016-05-01
2   2016-05-22
3   2016-05-01
4   2016-05-15
Name: value, dtype: datetime64[ns]

without change the date I am going to use reindex with groupby

df1=df.groupby('Name')['binary','value'].apply(lambda x : x.set_index('value').\
           reindex(['2016 W16','2016 W17','2016 W18','2016 W19','2016 W20']))

df1.loc[df1.groupby(level=0).binary.bfill().dropna().index].fillna(0).reset_index()
Out[65]:
      Name     value  binary
0    apple  2016 W16     1.0
1    berry  2016 W16     0.0
2    berry  2016 W17     1.0
3     lime  2016 W16     0.0
4     lime  2016 W17     0.0
5     lime  2016 W18     0.0
6     lime  2016 W19     1.0
7    melon  2016 W16     0.0
8    melon  2016 W17     0.0
9    melon  2016 W18     0.0
10   melon  2016 W19     0.0
11   melon  2016 W20     1.0
12  orange  2016 W16     0.0
13  orange  2016 W17     1.0


问:
IEnumerable' does not contain a definition for 'Type'
I am trying to use this @Html.DropDownListFor for filtering the results.

Controller:

```<code>[HttpGet]
public ActionResult Leading()
{
    ReportClassHandle ReportClassHandle = new ReportClassHandle();
    return View(ReportClassHandle.LeadingAll());
}
</code>```

And LeadingAll method is:

```<code>public List<Leading> LeadingAll(string Type)
{
    clsUtilities clsUtilities = new clsUtilities();
    DataSet ds;
    List<Leading> leading = new List<Leading>();
    string sSQL;

    SqlParameter[] prms = new SqlParameter[1];
    sSQL = "exec GetLeading @Type";
    prms[0] = new SqlParameter("@Type", SqlDbType.VarChar);
    prms[0].Value = Type;
    ds = clsUtilities.CreateCommandwithParams(sSQL, prms);
    DataTable dataTable = ds.Tables[0];
    foreach(DataRow dr in dataTable.Rows)
    {
        leading.Add(new Leading
        {
            RankId = Convert.ToInt32(dr["RankId"]),
            Name = Convert.ToString(dr["Name"]),
        });
    }
</code>```

My complete Leading View is:

```<code>@model IEnumerable<ReportProject.Models.Leading>
@using (Html.BeginForm("Leading", "Home", FormMethod.Post))
{
    @Html.DisplayFor(m => m.Type)
    @Html.DropDownListFor(m => m.Type, new List<SelectListItem> {
        new SelectListItem{ Text="General", Value="1" },
        new SelectListItem{Text="Advance", Value="2"}}, "Please select")
    @Html.ValidationMessageFor(m => m.Type, "", new { @class = "error" })
}
<table class="table table-striped">
    <tr>
        <th>@Html.DisplayName("Rank")</th>
        <th>@Html.DisplayName("Name")</th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.RankId)</td>
            <td>@Html.DisplayFor(modelItem => item.Name)</td>
        </tr>
    }
</table>
</code>```

My Leading Model:

```<code>public class Leading
{
    public int RankId { get; set; }
    public string Name { get; set; }
    [Required(ErrorMessage = "Type is Required")]
    public string Type { get; set; }
}
</code>```

When I run this code, it is throwing error:

Compiler Error Message: CS1061: 'IEnumerable<Leading>' does not contain a definition for 'Type' and no extension method 'Type' accepting a first argument of type 'IEnumerable<Leading>' could be found (are you missing a using directive or an assembly reference?)

Please guide me.

答:
The error occurs because the model in your view is IEnumerable<Leading> but you attempting to create controls for a single instance of Leading. Since you wanting to use the value of the dropdownlist to filter your results, then you should start with a view model to represent what you want in the view

```<code>public class LeadingFilterVM
{
    public int? Type { get; set; }
    public IEnumerable<SelectListItem> TypeList { get; set; }
    public IEnumerable<Leading> Leadings { get; set; }
}
</code>```

Then you GET method will be

```<code>[HttpGet]
public ActionResult Leading(int? type)
{
    IEnumerable<Leading> data;
    ReportClassHandle ReportClassHandle = new ReportClassHandle();
    if (type.HasValue)
    {
        data = ReportClassHandle.LeadingAll(type.Value.ToString())
    }
    else
    {
        data = ReportClassHandle.LeadingAll();
    }
    LeadingFilterVM model = new LeadingFilterVM
    {
        Type = type,
        TypeList = new List<SelectListItem>
        {
            new SelectListItem{ Text = "General", Value = "1" },
            new SelectListItem{ Text = "Advance", Value = "2" }
        },
        Leadings = data
    };
    return View(model);
}
</code>```

And change the view to

```<code>@model LeadingFilterVM
// note the FormMethod.Get
@using (Html.BeginForm("Leading", "Home", FormMethod.Get))
{
    @Html.DisplayFor(m => m.Type)
    @Html.DropDownListFor(m => m.Type, Model.TypeList "All types")

    <input type="submit" value="search" />
}
<table class="table table-striped">
    <thead>
        <tr>
            <th>Rank</th>
            <th>Name</th>
            <th></th>
        </tr>
    <thead>
    <tbody>
        @foreach (var item in Model.Leadings)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.RankId)</td>
                <td>@Html.DisplayFor(m => item.Name)</td>
             </tr>
        }
    </tbody>
</table>
</code>```

Body:
I am trying to use this @Html.DropDownListFor for filtering the results.

Controller:

[HttpGet]
public ActionResult Leading()
{
    ReportClassHandle ReportClassHandle = new ReportClassHandle();
    return View(ReportClassHandle.LeadingAll());
}

And LeadingAll method is:

public List<Leading> LeadingAll(string Type)
{
    clsUtilities clsUtilities = new clsUtilities();
    DataSet ds;
    List<Leading> leading = new List<Leading>();
    string sSQL;

    SqlParameter[] prms = new SqlParameter[1];
    sSQL = "exec GetLeading @Type";
    prms[0] = new SqlParameter("@Type", SqlDbType.VarChar);
    prms[0].Value = Type;
    ds = clsUtilities.CreateCommandwithParams(sSQL, prms);
    DataTable dataTable = ds.Tables[0];
    foreach(DataRow dr in dataTable.Rows)
    {
        leading.Add(new Leading
        {
            RankId = Convert.ToInt32(dr["RankId"]),
            Name = Convert.ToString(dr["Name"]),
        });
    }

My complete Leading View is:

@model IEnumerable<ReportProject.Models.Leading>
@using (Html.BeginForm("Leading", "Home", FormMethod.Post))
{
    @Html.DisplayFor(m => m.Type)
    @Html.DropDownListFor(m => m.Type, new List<SelectListItem> {
        new SelectListItem{ Text="General", Value="1" },
        new SelectListItem{Text="Advance", Value="2"}}, "Please select")
    @Html.ValidationMessageFor(m => m.Type, "", new { @class = "error" })
}

        @Html.DisplayName("Rank")
        @Html.DisplayName("Name")

    @foreach (var item in Model)
    {

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

    }

My Leading Model:

public class Leading
{
    public int RankId { get; set; }
    public string Name { get; set; }
    [Required(ErrorMessage = "Type is Required")]
    public string Type { get; set; }
}

When I run this code, it is throwing error:

Compiler Error Message: CS1061: 'IEnumerable<Leading>' does not contain a definition for 'Type' and no extension method 'Type' accepting a first argument of type 'IEnumerable<Leading>' could be found (are you missing a using directive or an assembly reference?)

Please guide me.

Body:
The error occurs because the model in your view is IEnumerable<Leading> but you attempting to create controls for a single instance of Leading. Since you wanting to use the value of the dropdownlist to filter your results, then you should start with a view model to represent what you want in the view

public class LeadingFilterVM
{
    public int? Type { get; set; }
    public IEnumerable<SelectListItem> TypeList { get; set; }
    public IEnumerable<Leading> Leadings { get; set; }
}

Then you GET method will be

[HttpGet]
public ActionResult Leading(int? type)
{
    IEnumerable<Leading> data;
    ReportClassHandle ReportClassHandle = new ReportClassHandle();
    if (type.HasValue)
    {
        data = ReportClassHandle.LeadingAll(type.Value.ToString())
    }
    else
    {
        data = ReportClassHandle.LeadingAll();
    }
    LeadingFilterVM model = new LeadingFilterVM
    {
        Type = type,
        TypeList = new List<SelectListItem>
        {
            new SelectListItem{ Text = "General", Value = "1" },
            new SelectListItem{ Text = "Advance", Value = "2" }
        },
        Leadings = data
    };
    return View(model);
}

And change the view to

@model LeadingFilterVM
// note the FormMethod.Get
@using (Html.BeginForm("Leading", "Home", FormMethod.Get))
{
    @Html.DisplayFor(m => m.Type)
    @Html.DropDownListFor(m => m.Type, Model.TypeList "All types")

    <input type="submit" value="search" />
}
<table class="table table-striped">
    <thead>
        <tr>
            <th>Rank</th>
            <th>Name</th>
            <th></th>
        </tr>
    <thead>
    <tbody>
        @foreach (var item in Model.Leadings)
        {
            <tr>
                <td>@Html.DisplayFor(m => item.RankId)</td>
                <td>@Html.DisplayFor(m => item.Name)</td>
             </tr>
        }
    </tbody>
</table>


问:
Is this smart pointer wrapper for SDL types safe?
I thought about using something like the following so I don't have to remember to explicitly call destroyer functions at the end of methods:

```<code>#include <iostream>
#include <SDL2/SDL.h>
#include <memory>

int main()
{
    SDL_Init(SDL_INIT_VIDEO);

    std::unique_ptr<SDL_Window, decltype((SDL_DestroyWindow))>
        win { SDL_CreateWindow("asdf", 100, 100, 640, 480, SDL_WINDOW_SHOWN),
                  SDL_DestroyWindow };
    if (!win.get())
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow Error: %s",
                SDL_GetError());
        return 1;
    }

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

I'm not sure if it's the best approach. I'm worried that this doesn't do what I want it to do even though it looks simple enough. Are there any subtle bugs to this approach?

答:
If you want to go in the direction of making it "look & feel like modern C++", you could combine the following two techniques:

scope guard (for SDL_Quit),

specialised default deleter (for SDL_Window).

Scope guard

A scope guard is a dummy object that calls the supplied function object from its destructor. Allocating it on the stack will make it call the destructor when it leaves the defining scope; doing that in the main() function means that it will run on program exit. For more details, there is a nice talk by Andrei Alexandrescu about this (the part about scope guards starts at 1:05:14).

The implementation (from the presentation, mostly):

```<code>template<class Fn>
class ScopeGuard {
 public:
  explicit ScopeGuard(Fn fn) noexcept
      : fn_(std::move(fn)),
        active_(true) {}

  ScopeGuard() = delete;
  ScopeGuard(const ScopeGuard &) = delete;
  ScopeGuard(ScopeGuard &&that) noexcept
      : fn_(std::move(that.fn_)),
        active_(that.active_) {
    that.dismiss();
  }

  ScopeGuard &operator=(const ScopeGuard &) = delete;

  ~ScopeGuard() {
    if (active_) {
      try {
        fn_();
      } catch (...) {
        // The destructor must not throw.
      }
    }
  }

  void dismiss() noexcept {
    active_ = false;
  }

 private:
  Fn fn_;
  bool active_;
};
</code>```

Instantiating the class directly wouldn't be very convenient, but on functions we get type inference:

```<code>// Provided purely for type inference.
template<class Fn>
ScopeGuard<Fn> scopeGuard(Fn fn) {
  return ScopeGuard<Fn>(std::move(fn));
}
</code>```

To create a scope guard, you'll simply call scopeGuard(lambda) where lambda is the function you want to run on leaving the scope. The actual type will be inferred; we're not interested in it anyway.

```<code>// Will call SDL_Quit() once 'guard' goes out of scope.
auto guard = scopeGuard([] { SDL_Quit(); });
</code>```

Specialised default deleter

You can specialise std::default_deleter, by defining the following function object (in this case, a struct with operator()):

```<code>template<>
struct std::default_delete<SDL_Window> {
  void operator()(SDL_Window *p) { SDL_DestroyWindow(p); }
};
</code>```

You could do this for most types in SDL, since they have exactly one "destroy" function. (You might want to wrap that in a macro.)

The nice thing about this is that as of SDL 2.0.x, SDL_Window and other types we get them from SDL2/SDL.h are incomplete types, i.e., you can't call sizeof(SDL_Window) on them. This means that the compiler won't be able to delete them out-of-the box (for that it needs sizeof), and therefore you won't be able to instantiate a (plain) std::unique_ptr<SDL_Window>.

With the specialised deleter, however, std::unique_ptr<SDL_Window> will work, and will call SDL_DestroyWindow in the destructor.

Result

The result, using the definitions above, is quite a boilerplate-free example of RAII:

```<code>int main()
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        return 1;
    }
    auto quit_scope_guard = scopeGuard([] { SDL_Quit(); });

    std::unique_ptr<SDL_Window> win(SDL_CreateWindow("asdf", 100, 100,
                                    640, 480, SDL_WINDOW_SHOWN));
    if (!win) {
        // ~quit_scope_guard will call SDL_Quit().
        return 1;
    }

    // ~win will call SDL_DestroyWindow(win.get()).
    // ~quit_scope_guard will call SDL_Quit().
    return 0;
}
</code>```

Body:
I thought about using something like the following so I don't have to remember to explicitly call destroyer functions at the end of methods:

#include <iostream>
#include <SDL2/SDL.h>
#include <memory>

int main()
{
    SDL_Init(SDL_INIT_VIDEO);

    std::unique_ptr<SDL_Window, decltype((SDL_DestroyWindow))>
        win { SDL_CreateWindow("asdf", 100, 100, 640, 480, SDL_WINDOW_SHOWN),
                  SDL_DestroyWindow };
    if (!win.get())
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow Error: %s",
                SDL_GetError());
        return 1;
    }

    SDL_Quit();
}

I'm not sure if it's the best approach. I'm worried that this doesn't do what I want it to do even though it looks simple enough. Are there any subtle bugs to this approach?

Body:
If you want to go in the direction of making it "look & feel like modern C++", you could combine the following two techniques:

scope guard (for SDL_Quit),

specialised default deleter (for SDL_Window).

Scope guard

A scope guard is a dummy object that calls the supplied function object from its destructor. Allocating it on the stack will make it call the destructor when it leaves the defining scope; doing that in the main() function means that it will run on program exit. For more details, there is a nice talk by Andrei Alexandrescu about this (the part about scope guards starts at 1:05:14).

The implementation (from the presentation, mostly):

template<class Fn>
class ScopeGuard {
 public:
  explicit ScopeGuard(Fn fn) noexcept
      : fn_(std::move(fn)),
        active_(true) {}

  ScopeGuard() = delete;
  ScopeGuard(const ScopeGuard &) = delete;
  ScopeGuard(ScopeGuard &&that) noexcept
      : fn_(std::move(that.fn_)),
        active_(that.active_) {
    that.dismiss();
  }

  ScopeGuard &operator=(const ScopeGuard &) = delete;

  ~ScopeGuard() {
    if (active_) {
      try {
        fn_();
      } catch (...) {
        // The destructor must not throw.
      }
    }
  }

  void dismiss() noexcept {
    active_ = false;
  }

 private:
  Fn fn_;
  bool active_;
};

Instantiating the class directly wouldn't be very convenient, but on functions we get type inference:

// Provided purely for type inference.
template<class Fn>
ScopeGuard<Fn> scopeGuard(Fn fn) {
  return ScopeGuard<Fn>(std::move(fn));
}

To create a scope guard, you'll simply call scopeGuard(lambda) where lambda is the function you want to run on leaving the scope. The actual type will be inferred; we're not interested in it anyway.

// Will call SDL_Quit() once 'guard' goes out of scope.
auto guard = scopeGuard([] { SDL_Quit(); });

Specialised default deleter

You can specialise std::default_deleter, by defining the following function object (in this case, a struct with operator()):

template<>
struct std::default_delete<SDL_Window> {
  void operator()(SDL_Window *p) { SDL_DestroyWindow(p); }
};

You could do this for most types in SDL, since they have exactly one "destroy" function. (You might want to wrap that in a macro.)

The nice thing about this is that as of SDL 2.0.x, SDL_Window and other types we get them from SDL2/SDL.h are incomplete types, i.e., you can't call sizeof(SDL_Window) on them. This means that the compiler won't be able to delete them out-of-the box (for that it needs sizeof), and therefore you won't be able to instantiate a (plain) std::unique_ptr<SDL_Window>.

With the specialised deleter, however, std::unique_ptr<SDL_Window> will work, and will call SDL_DestroyWindow in the destructor.

Result

The result, using the definitions above, is quite a boilerplate-free example of RAII:

int main()
{
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        return 1;
    }
    auto quit_scope_guard = scopeGuard([] { SDL_Quit(); });

    std::unique_ptr<SDL_Window> win(SDL_CreateWindow("asdf", 100, 100,
                                    640, 480, SDL_WINDOW_SHOWN));
    if (!win) {
        // ~quit_scope_guard will call SDL_Quit().
        return 1;
    }

    // ~win will call SDL_DestroyWindow(win.get()).
    // ~quit_scope_guard will call SDL_Quit().
    return 0;
}


问:
Do I have to use JavaScript?
When does it become unavoidable and when would you want to choose JavaScript over server side when you have a choice?</p>

答:
"Javascript over server side " JavaScript is client side, not server side.
You would still need to run server side stuff to get the data from the server. Javascript just gives you more control on how the client receives the data from the server.

JavaScript is unavoidable when you want a certain dynamic feature on your website which is not supported by default.
Dynamic feature
- without JavaScript: you can use CSS to change background of an element when the mouse is over the element. You can do the same thing with using JavaScript.
- Only in JavaScript: When you click the element with your mouse, the element disappears. Don't think it is possible in CSS(maybe you be able to use :active in CSS on some elements. Never tested it myself).

OwnerDisplayName: zsharp

Title: Do I have to use JavaScript?


问:
How to make tabbed labels responsive?
I have a tabbed feature on my site, and it is responsive, except for the labels.  I am not sure what to add to my style sheet to get the labels to wrap properly. Right now, when I reduced the size of the div, the labels spill out.

Here is a fiddle of what I have, everything I have tried so far has not worked, any insight would be greatly appreciated.

Thank you!

```<code><https://jsfiddle.net/v9eu9gsL/>
</code>```

答:
I know that technically speaking, if there was a front-end Bible, the responsiveness commandment would sound something like

Thine content shall be visible and accessible on all devices.

However, having a design background, I have a tendency to read it as

Thine content shall work and not look broken on any device.

Now, no matter how I look at this, it looks broken to me, although it's technically responsive:

So... this is how I'd fix it:

@media (max-width: 767px) {
  .tabs {
    display: flex;
  }
  .tabs  li {
    max-width: 33.33%;
    flex: 1 1 33.33%;
  }
  .tabs li a {
    overflow: hidden;
    text-overflow: ellipsis;
    box-sizing: border-box;
    width: 100%;
  }
}
@media (max-width: 419px) {

  .tabs {
    flex-wrap: wrap;
  }
  .tabs li {
    width: 100%;
    flex: 1 0 100%;
    max-width: 100%;
  }
  .tabs li a {
    white-space: normal;
  }
}
```

jsFiddle

Title: How to make tabbed labels responsive?

Body:
I have a tabbed feature on my site, and it is responsive, except for the labels.  I am not sure what to add to my style sheet to get the labels to wrap properly. Right now, when I reduced the size of the div, the labels spill out.

Here is a fiddle of what I have, everything I have tried so far has not worked, any insight would be greatly appreciated.

Thank you!

<https://jsfiddle.net/v9eu9gsL/>

Body:
I know that technically speaking, if there was a front-end Bible, the responsiveness commandment would sound something like

Thine content shall be visible and accessible on all devices.

However, having a design background, I have a tendency to read it as

Thine content shall work and not look broken on any device.

Now, no matter how I look at this, it looks broken to me, although it's technically responsive:

So... this is how I'd fix it:

@media (max-width: 767px) {
  .tabs {
    display: flex;
  }
  .tabs  li {
    max-width: 33.33%;
    flex: 1 1 33.33%;
  }
  .tabs li a {
    overflow: hidden;
    text-overflow: ellipsis;
    box-sizing: border-box;
    width: 100%;
  }
}
@media (max-width: 419px) {

  .tabs {
    flex-wrap: wrap;
  }
  .tabs li {
    width: 100%;
    flex: 1 0 100%;
    max-width: 100%;
  }
  .tabs li a {
    white-space: normal;
  }
}

jsFiddle


问:
sequelize.js orm :Unique email validation for mysql not working
Here is my model validation for check email-id exists or not

```<code>email:{
            type:Sequelize.STRING,
            validate:{
                notEmpty:{
                    args:true,
                    msg:"Email-id required"
                },
                isEmail:{
                    args:true,
                    msg:'Valid email-id required'
                }
            },
            unique: {
                args:true,
                msg: 'Email address already in use!'
            }

        }
</code>```

All other validations are working fine except unique email validion

答:
```<code>email: {
      type : DataTypes.STRING,
      validate : {
        isEmail: {
          msg: "wrong format email"
        },
        notEmpty: {
          msg: 'Email not null'
        },
        isUnique: function(value, next){

          'table'.find({
            where : {
              email:value,
              id:{[Op.ne]: this.id}
            }
          }).then(function(result){
            if(result === null){

              return next()

            }else{
              return next(' Email already use')
            }
          }).catch(err =>{
              return next()
          })
        }
      }
    }
</code>```

Body:
Here is my model validation for check email-id exists or not

email:{
            type:Sequelize.STRING,
            validate:{
                notEmpty:{
                    args:true,
                    msg:"Email-id required"
                },
                isEmail:{
                    args:true,
                    msg:'Valid email-id required'
                }
            },
            unique: {
                args:true,
                msg: 'Email address already in use!'
            }

        }

All other validations are working fine except unique email validion


问:
Change layout based on field value (sitecore)
I have tried to use personalization to adjust the layout (personalize renderings) of a template based on the field value (ie. if "Organization" is equal to "Apple") of a piece of content, but nothing seems to work. Should I be doing this in another way?</p>

答:
Create a new custom rule based on Organization

Configure sitecore with the custom rules.If you are not sure how to configure custom rules in sitecore follow the instructions in url https://www.geekhive.com/buzz/post/2016/11/sitecore-custom-personalization-rule/

personalize your rendering using the above rule.

Your custom sitecore rule code should look like this

```<code>    public class OrganizationName<T> : WhenCondition<T> where T : RuleContext
    {
        protected override bool Execute(T ruleContext)
        {
         try
            {
              var organizationItem = Sitecore.Data.Database.GetDatabase("master").GetItem(ruleContext.NewItemId);
           var orgName = organizationItem["Organization"];
           if(orgName  == "Apple")
            {
              return true;
            }
            }
             return false;
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Unexpected error", ex);
                return false;
            }
        }
    }
</code>```

Body:
Create a new custom rule based on Organization

Configure sitecore with the custom rules.If you are not sure how to configure custom rules in sitecore follow the instructions in url https://www.geekhive.com/buzz/post/2016/11/sitecore-custom-personalization-rule/

personalize your rendering using the above rule.

Your custom sitecore rule code should look like this

    public class OrganizationName<T> : WhenCondition<T> where T : RuleContext
    {
        protected override bool Execute(T ruleContext)
        {
         try
            {
              var organizationItem = Sitecore.Data.Database.GetDatabase("master").GetItem(ruleContext.NewItemId);
           var orgName = organizationItem["Organization"];
           if(orgName  == "Apple")
            {
              return true;
            }
            }
             return false;
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Unexpected error", ex);
                return false;
            }
        }
    }


问:
reactJS material UI Icon button to upload file
I want to know how can I open the directory to upload a file using an IconButton?

```<code><IconButton
  iconClassName="fa fa-plus-square"
  onClick={(e) => e.stopPropagation()}
  type='file'
/>
</code>```

using the code below shows the icon button and another button for the upload file

```<code><IconButton iconClassName="fa fa-plus-square" onClick={(e) => e.stopPropagation()}>
    <input type="file type='file'>
</IconButton>
</code>```

答:
You can achieve the same with IconButton using the following code:

```<code><IconButton onClick={() => this.fileUpload.click()}>
   <FontIcon className="material-icons" >
       add_a_photo
   </FontIcon>
  </IconButton>
<input type="file" ref={(fileUpload) => {
                    this.fileUpload = fileUpload;
                  }}
  style={{ visibility: 'hidden'}} onChange={this.groupImgUpload} />
</code>```

Body:
I want to know how can I open the directory to upload a file using an IconButton?

<IconButton
  iconClassName="fa fa-plus-square"
  onClick={(e) => e.stopPropagation()}
  type='file'
/>

using the code below shows the icon button and another button for the upload file

<IconButton iconClassName="fa fa-plus-square" onClick={(e) => e.stopPropagation()}>
    <input type="file type='file'>
</IconButton>

Body:
You can achieve the same with IconButton using the following code:

<IconButton onClick={() => this.fileUpload.click()}>
   <FontIcon className="material-icons" >
       add_a_photo
   </FontIcon>
  </IconButton>
<input type="file" ref={(fileUpload) => {
                    this.fileUpload = fileUpload;
                  }}
  style={{ visibility: 'hidden'}} onChange={this.groupImgUpload} />