问:
how to load file.babylon ? it only shows loading scene
Hello i have problem with my project. i Try to load my babylon file but the file can't load. it only shows loading scene.
here is my code

```<code>var canvas, engine, scene, camera, score = 0;

document.addEventListener("DOMContentLoaded", function () {
    onload();
}, false);

window.addEventListener("resize", function () {
    if (engine) {
        engine.resize();
    }
},false);

var onload = function () {
    // Engine creation
    canvas = document.getElementById("renderCanvas");
    engine = new BABYLON.Engine(canvas, true);
    scene = new BABYLON.Scene(engine);

    initGame();
    initScene();

    engine.runRenderLoop(function () {
        scene.render();
    });

};

function initScene() {

    // Create the camera
    camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0,4,-10), scene);
    camera.setTarget(new BABYLON.Vector3(0,0,10));
    camera.attachControl(canvas);

    // Create light
    var light = new BABYLON.PointLight("light", new BABYLON.Vector3(0,5,-5), scene);

    engine.runRenderLoop(function () {
    scene.render();
    });

}

function initGame() {
//BABYLON.Mesh.CreateSphere("sphere", 10, 1, scene);
BABYLON.SceneLoader.Load("/assets/", "harimau.babylon", engine, function (newScene) {
   // ...
});
}
</code>```

this is my code and i dont know what to do with it to load my harimau.babylon file. thx

答:
A solution that helped me is go to the Babylon.js main script file you are referencing and search for CrossOrigin and comment the two lines out. Then you will have to rename you SceneFileName.babylon to SceneFileName.js

Since your .babylon file is basically the a json object you can skip the register plugin process of the mimi type that babylon forces.

Cheers!

Body:
Hello i have problem with my project. i Try to load my babylon file but the file can't load. it only shows loading scene.
here is my code

var canvas, engine, scene, camera, score = 0;

document.addEventListener("DOMContentLoaded", function () {
    onload();
}, false);

window.addEventListener("resize", function () {
    if (engine) {
        engine.resize();
    }
},false);

var onload = function () {
    // Engine creation
    canvas = document.getElementById("renderCanvas");
    engine = new BABYLON.Engine(canvas, true);
    scene = new BABYLON.Scene(engine);

    initGame();
    initScene();

    engine.runRenderLoop(function () {
        scene.render();
    });

};

function initScene() {

    // Create the camera
    camera = new BABYLON.FreeCamera("camera", new BABYLON.Vector3(0,4,-10), scene);
    camera.setTarget(new BABYLON.Vector3(0,0,10));
    camera.attachControl(canvas);

    // Create light
    var light = new BABYLON.PointLight("light", new BABYLON.Vector3(0,5,-5), scene);

    engine.runRenderLoop(function () {
    scene.render();
    });

}

function initGame() {
//BABYLON.Mesh.CreateSphere("sphere", 10, 1, scene);
BABYLON.SceneLoader.Load("/assets/", "harimau.babylon", engine, function (newScene) {
   // ...
});
}

this is my code and i dont know what to do with it to load my harimau.babylon file. thx


来源: stackexchange

问:
Guessing a number
I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).

I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.

```<code>import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner ran = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < 3) {
            System.out.println("Too low. Try again.");

            System.out.println("Enter a number: ");
        } else if (x > 3) {
            System.out.println("Too high. Try again");

        } else if(x == 3) {
            System.out.println("You win. Nice job.");
        } else {
            System.out.println("You lose");
        }

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}
</code>```

答:
You can do this using recursion. See this program. Find explanations within comments.</p>

```<code>import java.util.Scanner;

public class HelloWorld {

    private static Scanner ran = new Scanner(System.in);

    //this is number of tries you want to give to user
    private static int counter = 5;

    //The actual number
    private static final int NUM = 3;

    public static boolean guessingMachine() {
        //counter indicates that number of attempts remaining
        if(counter == 0) {
            return false;
        }
        counter--;

        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < NUM) {
            System.out.println("Too low. Try again.");
            //try again... call this method again
            return guessingMachine();
        } else if (x > NUM) {
            System.out.println("Too high. Try again");
            //try again... call this method again
            return guessingMachine();
        } else {
            //x == NUM success
            return true;
        }
    }

    public static void main(String[] args) {
        boolean result = guessingMachine();

        if(result)
            System.out.println("You win. Nice job.");
        else
            System.out.println("You lose");

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Guessing a number

Body:
I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).

I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner ran = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < 3) {
            System.out.println("Too low. Try again.");

            System.out.println("Enter a number: ");
        } else if (x > 3) {
            System.out.println("Too high. Try again");

        } else if(x == 3) {
            System.out.println("You win. Nice job.");
        } else {
            System.out.println("You lose");
        }

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}

Body:
You can do this using recursion. See this program. Find explanations within comments.

import java.util.Scanner;

public class HelloWorld {

    private static Scanner ran = new Scanner(System.in);

    //this is number of tries you want to give to user
    private static int counter = 5;

    //The actual number
    private static final int NUM = 3;

    public static boolean guessingMachine() {
        //counter indicates that number of attempts remaining
        if(counter == 0) {
            return false;
        }
        counter--;

        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < NUM) {
            System.out.println("Too low. Try again.");
            //try again... call this method again
            return guessingMachine();
        } else if (x > NUM) {
            System.out.println("Too high. Try again");
            //try again... call this method again
            return guessingMachine();
        } else {
            //x == NUM success
            return true;
        }
    }

    public static void main(String[] args) {
        boolean result = guessingMachine();

        if(result)
            System.out.println("You win. Nice job.");
        else
            System.out.println("You lose");

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}


问:
CloudFlare and logging visitor IP addresses via in PHP
I'm trying to track and log users/visitors that are accessing my website using PHP's $_SERVER['REMOTE_ADDR'] to do so. A typical method for IP address tracking in PHP.

However, I am using CloudFlare for caching and such and receiving their IP addresses as CloudFlare's:

108.162.212.* - 108.162.239.*

What would be a correct method of retrieving the actual users/visitors IP address while still using CloudFlare?

答:
For magento 1.x users (I haven't try magento 2.0 yet), check https://tall-paul.co.uk/2012/03/13/magento-show-remote-ip-in-cloudflare-the-right-way/ which needs to change app/etc/local.xml and add:

           HTTP_CF_CONNECTING_IP
</p>


问:
Creating 2D matrix from RDD
I have the following RDD of the Type ((UserID, MovieID),1):

```<code>val data_wo_header=dropheader(data).map(_.split(",")).map(x=>((x(0).toInt,x(1).toInt),1))
</code>```

I want to convert this data structure into a 2D array such that all elements(userID Movie ID) present in the original RDD have a 1 else 0.

I think we have to map the user ID's to 0-N if N is the number of distinct users and map Movie ID's to 0-M if Mis the number of distinct movies.

EDIT: example

```<code>        Movie ID->

Userid  1 2 3 4 5 6 7

1       0 1 1 0 0 1 0
2       0 1 0 1 0 0 0
3       0 1 1 0 0 0 1
4       1 1 0 0 1 0 0
5       0 1 1 0 0 0 1
6       1 1 1 1 1 0 0
7       0 1 1 0 0 0 0
8       0 1 1 1 0 0 1
9       0 1 1 0 0 1 0

The RDD will be of the sort
(userID, movID,rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0
….
</code>```

答:
HI I managed to generate the 2D matrix using the following function. It takes in the RDD of the format

```<code>((userID, movID),rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0
</code>```

and returns the characteristic Matrix:

```<code>def generate_characteristic_matrix(data_wo_header:RDD[((Int, Int), Int)]):Array[Array[Int]]={
    val distinct_user_IDs=data_wo_header.sortByKey().map(x=>x._1._1).distinct().collect().sorted
    val distinct_movie_IDs=data_wo_header.sortByKey().map(x=>x._1._2).distinct().collect().sorted

    var movie_count=distinct_movie_IDs.size
    var user_count=distinct_user_IDs.size

    var a =0
    var map_movie = new ArrayBuffer[(Int, Int)]()
    var map_user = new ArrayBuffer[(Int, Int)]()
    //map movie ID's from (0,movie_count)
    for( a <- 0 to movie_count-1){
      map_movie+=((distinct_movie_IDs(a),a))
    }
    //map user ID's from (0,user_count)
    for( a <- 0 to user_count-1){
      map_user+=((distinct_user_IDs(a),a))
    }
    //size of char matrix is user_countxmovie_count
    var char_matrix = Array.ofDim[Int](user_count,movie_count)
    data_wo_header.collect().foreach(x => {
      var user =x._1._1
      var movie=x._1._2
      var movie_mappedid=map_movie.filter(x=>x._1==movie).map(x=>x._2).toArray
      var user_mappedid=map_user.filter(x=>x._1==user).map(x=>x._2).toArray
      char_matrix(user_mappedid(0))(movie_mappedid(0))=1
    })
    return char_matrix
  }
</code>```

Title: Creating 2D matrix from RDD

Body:
I have the following RDD of the Type ((UserID, MovieID),1):

val data_wo_header=dropheader(data).map(_.split(",")).map(x=>((x(0).toInt,x(1).toInt),1))

I want to convert this data structure into a 2D array such that all elements(userID Movie ID) present in the original RDD have a 1 else 0.

I think we have to map the user ID's to 0-N if N is the number of distinct users and map Movie ID's to 0-M if Mis the number of distinct movies.

EDIT: example

        Movie ID->

Userid  1 2 3 4 5 6 7

1       0 1 1 0 0 1 0
2       0 1 0 1 0 0 0
3       0 1 1 0 0 0 1
4       1 1 0 0 1 0 0
5       0 1 1 0 0 0 1
6       1 1 1 1 1 0 0
7       0 1 1 0 0 0 0
8       0 1 1 1 0 0 1
9       0 1 1 0 0 1 0

The RDD will be of the sort
(userID, movID,rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0
….

Body:
HI I managed to generate the 2D matrix using the following function. It takes in the RDD of the format

((userID, movID),rating)
101,1002,3.5
101,1003,2.5
101,1006,3
102,1002,3.5
102,1004,4.0
103,1002,1.0
103,1003,1.0
103,1007,5.0

and returns the characteristic Matrix:

def generate_characteristic_matrix(data_wo_header:RDD[((Int, Int), Int)]):Array[Array[Int]]={
    val distinct_user_IDs=data_wo_header.sortByKey().map(x=>x._1._1).distinct().collect().sorted
    val distinct_movie_IDs=data_wo_header.sortByKey().map(x=>x._1._2).distinct().collect().sorted

    var movie_count=distinct_movie_IDs.size
    var user_count=distinct_user_IDs.size

    var a =0
    var map_movie = new ArrayBuffer[(Int, Int)]()
    var map_user = new ArrayBuffer[(Int, Int)]()
    //map movie ID's from (0,movie_count)
    for( a <- 0 to movie_count-1){
      map_movie+=((distinct_movie_IDs(a),a))
    }
    //map user ID's from (0,user_count)
    for( a <- 0 to user_count-1){
      map_user+=((distinct_user_IDs(a),a))
    }
    //size of char matrix is user_countxmovie_count
    var char_matrix = Array.ofDim[Int](user_count,movie_count)
    data_wo_header.collect().foreach(x => {
      var user =x._1._1
      var movie=x._1._2
      var movie_mappedid=map_movie.filter(x=>x._1==movie).map(x=>x._2).toArray
      var user_mappedid=map_user.filter(x=>x._1==user).map(x=>x._2).toArray
      char_matrix(user_mappedid(0))(movie_mappedid(0))=1
    })
    return char_matrix
  }


问:
Datetime conversion in web application
I have a asp.net web application using SQL Server 2012 as the database.

The web server currently has american date time format. The code of the web application passed datetime values as NOW and all works fine.

Now I was trying to deploy this web application by using a clean machine (for internal testing). The web application worked fine again. The problem came when I tries to pass a datetime value to the SQL Server. The error is

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value

To fix the problem I change the datetime format of the machine to American date time format because that is what the first server did. Unfortunately it still does not run.

Any ideas what all can I try?

To Update my code

My SQL Server has user defined type

```<code>MyDataTable.Rows.Add(
                    batchNoRow[0], //Batch ID
                    DateTime.Now, //Creation Date
                    );

// Then pass the table type in a stored procedure as below

SqlParameter param = new SqlParameter("@Array", MyDataTable);
SqlCommand cmd = new SqlCommand();
cmd.connection = myconnection;
cmd.CommandText = mycommandText;
cmd.CommandType = commandType;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
</code>```

The definition of @array is a user defined type in sql server

```<code>CREATE TYPE [dbo].[MyTableType] AS TABLE(
    [BatchNo] [int] NOT NULL,
    [CreationDate] [datetime] NOT NULL,
  PRIMARY KEY CLUSTERED
(
   [BatchNo] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO
</code>```

答:
Suppose you have DataTable setup as this:

```<code>var MyDataTable = new DataTable();
MyDataTable.Columns.Add("BatchNo");
MyDataTable.Columns.Add("CreationDate");
</code>```

Without specifying data type for columns added in DataTable, DataColumn assumes that data type is String by default (see MSDN reference).

Data columns (DataColumn) are created with a default data type of
  String.

Hence, the value returned by DateTime.Now stored as date string, then converted to SQL as nvarchar, thereby throwing SqlException since target CreationDate column in TVP declared as datetime.

To ensure passed values have proper data types, specify data type for each column in DataTable as this:

```<code>MyDataTable.Columns.Add("BatchNo", typeof(int));
MyDataTable.Columns.Add("CreationDate", typeof(DateTime));
</code>```

NB: You can't change or alter DataType after DataTable has filled with data, so that DataType for every column(s) must be specified before adding row(s).

Title: Datetime conversion in web application

Body:
I have a asp.net web application using SQL Server 2012 as the database.

The web server currently has american date time format. The code of the web application passed datetime values as NOW and all works fine.

Now I was trying to deploy this web application by using a clean machine (for internal testing). The web application worked fine again. The problem came when I tries to pass a datetime value to the SQL Server. The error is

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value

To fix the problem I change the datetime format of the machine to American date time format because that is what the first server did. Unfortunately it still does not run.

Any ideas what all can I try?

To Update my code

My SQL Server has user defined type

MyDataTable.Rows.Add(
                    batchNoRow[0], //Batch ID
                    DateTime.Now, //Creation Date
                    );

// Then pass the table type in a stored procedure as below

SqlParameter param = new SqlParameter("@Array", MyDataTable);
SqlCommand cmd = new SqlCommand();
cmd.connection = myconnection;
cmd.CommandText = mycommandText;
cmd.CommandType = commandType;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();

The definition of @array is a user defined type in sql server

CREATE TYPE [dbo].[MyTableType] AS TABLE(
    [BatchNo] [int] NOT NULL,
    [CreationDate] [datetime] NOT NULL,
  PRIMARY KEY CLUSTERED
(
   [BatchNo] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO

Body:
Suppose you have DataTable setup as this:

var MyDataTable = new DataTable();
MyDataTable.Columns.Add("BatchNo");
MyDataTable.Columns.Add("CreationDate");

Without specifying data type for columns added in DataTable, DataColumn assumes that data type is String by default (see MSDN reference).

Data columns (DataColumn) are created with a default data type of
  String.

Hence, the value returned by DateTime.Now stored as date string, then converted to SQL as nvarchar, thereby throwing SqlException since target CreationDate column in TVP declared as datetime.

To ensure passed values have proper data types, specify data type for each column in DataTable as this:

MyDataTable.Columns.Add("BatchNo", typeof(int));
MyDataTable.Columns.Add("CreationDate", typeof(DateTime));

NB: You can't change or alter DataType after DataTable has filled with data, so that DataType for every column(s) must be specified before adding row(s).


问:
Show Wallpaper with AppCompat Theme (Android)
Okay, I cannot seem to find a solution. For a launcher app, I want to use a theme that sets the wallpaper as the background. So far, I tried using

```<code> @android:style/Theme.Holo.Wallpaper.NoTitleBar
</code>```

But I need AppCompat functionality in my app, and that requires an AppCompat theme. Maybe there is something I looked over...

Thanks in advance!

答:
try this:</p>

```<code><style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowShowWallpaper">true</item>
</style>
</code>```

Body:
Okay, I cannot seem to find a solution. For a launcher app, I want to use a theme that sets the wallpaper as the background. So far, I tried using

 @android:style/Theme.Holo.Wallpaper.NoTitleBar

But I need AppCompat functionality in my app, and that requires an AppCompat theme. Maybe there is something I looked over...

Thanks in advance!

Body:
try this:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowShowWallpaper">true</item>
</style>


问:
Angularjs - Single Page Application Not Rendering Page Templates
So I was trying to make a SPA using angular but when I try to open my page on a localhost the navbar displays but none of the content I have in separate HTML documents loads. I feel as if I'm missing something but I'm not sure what.

HTML

```<code><html lang="en" ng-app="App"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--External Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <!-- Internal Styles -->
    <link rel="stylesheet" href="css/style.css">

    <!-- External Scripts -->
    <script src="js/angular.min.js"></script>
    <script src="js/angular-route.min.js"></script>
    <script src="js/anime.min.js"></script>
    <script src="js/anime.js"></script>

    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://use.fontawesome.com/a1dcc6967b.js"></script>

    <!-- Internal Scripts -->
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript">

        var CSStransforms = anime({
            targets: '#CSStransforms .el',
            translateX: 250,
            scale: 2,
            rotate: '1turn'
        });

    </script>

    <title>Bootsrap Shell With Navabar</title>

</head><body ng-controller="mainController">
      <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="/">Navbar</a>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item ">
                    <a class="nav-link active" href="#/">Home<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#/about">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#/Page-Name">Page</a>
                </li>
                <!-- Dropdown - Delete from this comment to the next if you don't want it -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <a class="dropdown-item" href="#">Something else here</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Separted</a>
                    </div>
                </li>
            </ul>
            <ul class="navbar-nav ml-auto">
                <li class="nav-item dropdown user">

                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Signed in as </a>
                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#"><i class="fa fa-user-circle" aria-hidden="true"></i> Edit Profile</a>
                        <a class="dropdown-item" href="/logout.php"><i class="fa fa-sign-out" aria-hidden="true"></i> Log Out</a>
                    </div>

                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">User</a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" data-toggle="modal" data-target="#register-modal" href="#"><i class="fa fa-user-circle" aria-hidden="true"></i> Register</a>
                        <a class="dropdown-item" data-toggle="modal" data-target="#login-modal" href="#"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
                    </div>

                </li>
            </ul>
        </div>

    </nav>

    <div id="login-modal" class="modal fade" aria-labelledby="myModalLabel" aria-hidden="true" tabindex="-1" role="dialog">
        <div class="modal-dialog">
            <div class="login-modal-container">
                <form id="login-form" role="form">
                    <div class="modal-body">
                        <h2 class="modal-text">Login To Your Account </h2>
                        <div id="err-msg"></div>
                        <div class="form-group">
                            <input type="text" id="username" name="username" placeholder="Your Username" class="form-control input-lg" />
                        </div>
                        <div class="form-group">
                            <input type="password" id="password" name="password" placeholder="Password" class="form-control input-lg" />
                        </div>
                        <div class="form-group">
                            <div id="captcha"></div>
                        </div>
                        <div class="form-group">
                            <input type="submit" id="login" name="login" value="Log In" class="btn btn-primary btn-block btn-lg" data-toggle="tooltip" data-placement="bottom" title="Press To Sign In" />
                        </div>
                    </div>
                    <div class="modal-footer modal-text">
                        Don't have an account? <a data-toggle="modal" data-target="#register-modal" href="#" data-dismiss="modal">Sign Up here</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div id="main">

        <div ng-view></div>

    </div>

</body>

</html>
</code>```

JavaScript

```<code>var App = angular.module('App', ['ngRoute']);

// configure our routes
App.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        })

        .otherwise({redirectTo: '/'});
});

// create the controller and inject Angular's $scope
App.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

App.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

App.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
});
</code>```

Edit

Bower was used to get angular

```<code>{"name": "site","authors": ["Luculent"],"description": "","main":"index.php","license": "MIT","homepage": "/","ignore": ["**/.*","node_modules","bower_components","test","tests"]}
</code>```

Edit 2

got angular 1.6.3 but still does not work

Edit 3

when I launch the page it generates the following exception:

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=App&p1=Error%3A%20%…%20%20%20at%20eb%20(http%3A%2F%2Flocalhost%2Fjs%2Fangular.min.js%3A46%3A44)
at angular.min.js:6
at angular.min.js:42
at p (angular.min.js:7)
at g (angular.min.js:41)
at eb (angular.min.js:46)
at c (angular.min.js:21)
at Pc (angular.min.js:22)
at ue (angular.min.js:20)
at angular.min.js:332
at HTMLDocument.b (angular.min.js:38)
</code>```

But as you can see above I have both angular.js and angular-route.

答:
Please try removing ngRoute tag from below line

```<code>var App = angular.module('App', ['ngRoute']);
</code>```

You are already providing $routeProvider here

Body:
So I was trying to make a SPA using angular but when I try to open my page on a localhost the navbar displays but none of the content I have in separate HTML documents loads. I feel as if I'm missing something but I'm not sure what.

HTML

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <link rel="stylesheet" href="css/style.css">

    <title>Bootsrap Shell With Navabar</title>

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        Navbar

                    Home(current)

                    About

                    Page

                    Dropdown

                        Action
                        Another action
                        Something else here

                        Separted

                    Signed in as

                         Edit Profile
                         Log Out

                    User

                         Register
                         Login

                <form id="login-form" role="form">

Login To Your Account

                            <input type="text" id="username" name="username" placeholder="Your Username" class="form-control input-lg" />

                            <input type="password" id="password" name="password" placeholder="Password" class="form-control input-lg" />

                            <input type="submit" id="login" name="login" value="Log In" class="btn btn-primary btn-block btn-lg" data-toggle="tooltip" data-placement="bottom" title="Press To Sign In" />

                        Don't have an account? Sign Up here

                </form>

JavaScript

var App = angular.module('App', ['ngRoute']);

// configure our routes
App.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        })

        .otherwise({redirectTo: '/'});
});

// create the controller and inject Angular's $scope
App.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

App.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

App.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
});

Edit

Bower was used to get angular

{"name": "site","authors": ["Luculent"],"description": "","main":"index.php","license": "MIT","homepage": "/","ignore": ["**/.*","node_modules","bower_components","test","tests"]}

Edit 2

got angular 1.6.3 but still does not work

Edit 3

when I launch the page it generates the following exception:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=App&p1=Error%3A%20%…%20%20%20at%20eb%20(http%3A%2F%2Flocalhost%2Fjs%2Fangular.min.js%3A46%3A44)
at angular.min.js:6
at angular.min.js:42
at p (angular.min.js:7)
at g (angular.min.js:41)
at eb (angular.min.js:46)
at c (angular.min.js:21)
at Pc (angular.min.js:22)
at ue (angular.min.js:20)
at angular.min.js:332
at HTMLDocument.b (angular.min.js:38)

But as you can see above I have both angular.js and angular-route.

Body:
Please try removing ngRoute tag from below line

var App = angular.module('App', ['ngRoute']);

You are already providing $routeProvider here


问:
Read the line from a text file with the particular string using VBScript
I have a text file that contains log data. I have retrieve Serial No, Output status, Pin No etc from the log file.

My log file look like below. It has lot of contents.

```<code>"FORMAT=U2"
"BEGIN HEADER"
"TS=600581"
"ST=1001038"
"TC=60055"
"PIN=100577"
"SN=GXT220.1"
</code>```

I have to read the file and print PIN is 100577 and Serial No is GXT220.1. I have do the same for may files and the line no is not same for all the files.

答:
Not sure if this is what you want ---> Reading through the textfile and extract out specific information in a line with constant indicator.

If so, this is what i will do.

```<code>Option Explicit

Dim FSO, ReadTextFile ' object
Dim Textline ' string/variant
Dim PinNumber, Serial ' Output

FSO = CreateObject("Scripting.FileSystemObject")

Set ReadTextFile = FSO.OpenTextFile("File.txt", 1) ' Open text with read only mode

Do Until ReadTextFile.AtEndOfStream
   Textline = ReadTextFile.Readline()

   If Instr(Textline, "PIN=") Then ' If textline contain string "PIN="
      PinNumber = Split(Textline, "=")(1) ' Split the textline  with "=" indicator
   End If

   If Instr(Textline, "SN=") Then
      Serial = Split(Textline, "=")(1)
   End If

Loop ' Read through every line
</code>```

This example only works if you have only one indicator in one file. And also your indicator is the same to all txt file. Hope it helps :)

Body:
I have a text file that contains log data. I have retrieve Serial No, Output status, Pin No etc from the log file.

My log file look like below. It has lot of contents.

"FORMAT=U2"
"BEGIN HEADER"
"TS=600581"
"ST=1001038"
"TC=60055"
"PIN=100577"
"SN=GXT220.1"

I have to read the file and print PIN is 100577 and Serial No is GXT220.1. I have do the same for may files and the line no is not same for all the files.

Body:
Not sure if this is what you want ---> Reading through the textfile and extract out specific information in a line with constant indicator.

If so, this is what i will do.

Option Explicit

Dim FSO, ReadTextFile ' object
Dim Textline ' string/variant
Dim PinNumber, Serial ' Output

FSO = CreateObject("Scripting.FileSystemObject")

Set ReadTextFile = FSO.OpenTextFile("File.txt", 1) ' Open text with read only mode

Do Until ReadTextFile.AtEndOfStream
   Textline = ReadTextFile.Readline()

   If Instr(Textline, "PIN=") Then ' If textline contain string "PIN="
      PinNumber = Split(Textline, "=")(1) ' Split the textline  with "=" indicator
   End If

   If Instr(Textline, "SN=") Then
      Serial = Split(Textline, "=")(1)
   End If

Loop ' Read through every line

This example only works if you have only one indicator in one file. And also your indicator is the same to all txt file. Hope it helps :)


问:
PDO prepare error, Parse error
I can perform the following PDO query successfully:

```<code>$db = new PDO('mysql:host=' .DB_HOST.';dbname=' .DB_NAME. '', DB_USER, DB_PASSWORD);

$query = "SELECT ITEM_ID, LISTING_TITLE, PURCHASE_AMT FROM INVNTRY.ITEM WHERE ITEM_ID IN (1,2);";

$result = $db->query($query);

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
  echo $row['LISTING_TITLE'];
}
</code>```

Then close the cursor and db connection.

I mainly showed the above code to illustrate that my database connection is successful:

When I execute this code I get an error on the "prepare" line:

```<code>$db = new PDO('mysql:host=' .DB_HOST.';dbname=' .DB_NAME. '', DB_USER, DB_PASSWORD);

$query = $db->prepare('SELECT ITEM_ID, LISTING_TITLE, PURCHASE_AMT FROM INVNTRY.ITEM WHERE LISTING_TITLE = ?');

$array - array('Black Duffle Bag');
$query->execute($array);
$fetch = $query->fetch();
</code>```

The error is:

```<code>Parse error: syntax error, unexpected '$db' (T_VARIABLE)
</code>```

I know this is normally due to a missing ; or something similar, but I think I have this coded correctly. Is there any configuration file setting required prior to performing a prepare? I am running this second code base on the same instance as the first.

答:
I think the only problem in this code is line:

```<code>$array - array('Black Duffle Bag');
</code>```

It must be:

```<code>$array = array('Black Duffle Bag');
</code>```

I tried your code with modify above and it works with no error!

Title: PDO prepare error, Parse error

Body:
I can perform the following PDO query successfully:

$db = new PDO('mysql:host=' .DB_HOST.';dbname=' .DB_NAME. '', DB_USER, DB_PASSWORD);

$query = "SELECT ITEM_ID, LISTING_TITLE, PURCHASE_AMT FROM INVNTRY.ITEM WHERE ITEM_ID IN (1,2);";

$result = $db->query($query);

while($row = $result->fetch(PDO::FETCH_ASSOC)) {
  echo $row['LISTING_TITLE'];
}

Then close the cursor and db connection.

I mainly showed the above code to illustrate that my database connection is successful:

When I execute this code I get an error on the "prepare" line:

$db = new PDO('mysql:host=' .DB_HOST.';dbname=' .DB_NAME. '', DB_USER, DB_PASSWORD);

$query = $db->prepare('SELECT ITEM_ID, LISTING_TITLE, PURCHASE_AMT FROM INVNTRY.ITEM WHERE LISTING_TITLE = ?');

$array - array('Black Duffle Bag');
$query->execute($array);
$fetch = $query->fetch();

The error is:

Parse error: syntax error, unexpected '$db' (T_VARIABLE)

I know this is normally due to a missing ; or something similar, but I think I have this coded correctly. Is there any configuration file setting required prior to performing a prepare? I am running this second code base on the same instance as the first.

Body:
I think the only problem in this code is line:

$array - array('Black Duffle Bag');

It must be:

$array = array('Black Duffle Bag');

I tried your code with modify above and it works with no error!


问:
Salesforce Apex Google Drive API is creating new file with mimeType "application/json"
Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.

I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.

```<code>public void getDriveFiles(HttpResponse authResponse) {
    http h = new Http();
    Httprequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();

    Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());

    req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
    req.setMethod('POST');
    req.setHeader('Content-type', 'application/json');
    req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));

    String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
    req.setBody(jsonData);
    res = h.send(req);

    system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}
</code>```

I have a feeling it's my request body but I have no idea what to do to fix it.

答:
You've used the wrong endpoint. Instead of the file endpoint, you're posting to the content endpoint.

So

req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');

should be (for the v2 API)

req.setEndpoint('https://www.googleapis.com/drive/v2/files');

or (for the v3 API)

req.setEndpoint('https://www.googleapis.com/drive/v3/files');

If you use v3 (which you probably should), your json should change thus

String jsonData = '{"name":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';

Body:
Trying to create a function in apex that will create Google Drive folders when creating a new record in Salesforce.

I have managed to authenticate and handle GET requests just fine. My issue is regarding the POST requests. The code below should create a folder with the label provided in the "title" parameter. The script executes and instead creates an extension-less file without a label.

public void getDriveFiles(HttpResponse authResponse) {
    http h = new Http();
    Httprequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();

    Map<String, Object> responseObject = (Map<String, Object>) JSON.deserializeUntyped(authResponse.getBody());

    req.setEndpoint('https://www.googleapis.com/upload/drive/v2/files');
    req.setMethod('POST');
    req.setHeader('Content-type', 'application/json');
    req.setHeader('Authorization', 'Bearer '+responseObject.get('access_token'));

    String jsonData = '{"title":"NewFolder", "mimeType":"application/vnd.google-apps.folder"}';
    req.setBody(jsonData);
    res = h.send(req);

    system.debug('Response ='+ res.getBody() +' '+ res.getStatusCode());
}

I have a feeling it's my request body but I have no idea what to do to fix it.


问:
Problem using C# iterator methods with code access security
I have a simple method that uses an iterator block to return an IEnumerable<T>:

```<code>IEnumerable<MyItem> GetItems()
{
    foreach (var item in Items)
    {
        yield return item;
    }
}
</code>```

Ordinarily, this method works fine, but if I apply a [SecurityCritical] attribute to the assembly (or to the class that contains the above method), it throws a TypeLoadException when attempting to invoke the method. The type that is failing to load is the compiler-generated class that corresponds to the iterator method, and it is its GetEnumerator method that is causing the problem, since it is security transparent.

For comparison, if I modify the above method so that it populates and returns a List<MyItem>, everything works fine.

Any suggestions?

Thanks,

Tim.

答:
It isn't the neatest thing to do, so hopefully you can find a better way, but you could always forgo the compiler-generated code and create your own class that implements IEnumerator<MyItem> (and perhaps your own class implementing IEnumerable<MyItem> - depending on complexity, doing so may make things easier or more difficult), and then build the enumerator more or less as you would in the days before .NET2.0.

If the logic of your real iterator block is very complicated, you might find looking at the reflection of the class the compiler created for you to be a good starting point in doing this, though sometimes the generated code is more complicated (or at least, less readable) than the approach one would take oneself.

It's always a bit disappointing to have to build an IEnumerator class when yield has made it so nice for us 99% of the time, but there are still times when its necessary, and it might solve your problem here.

ContentLicense: CC BY-SA 2.5

Body:
I have a simple method that uses an iterator block to return an IEnumerable<T>:

IEnumerable<MyItem> GetItems()
{
    foreach (var item in Items)
    {
        yield return item;
    }
}

Ordinarily, this method works fine, but if I apply a [SecurityCritical] attribute to the assembly (or to the class that contains the above method), it throws a TypeLoadException when attempting to invoke the method. The type that is failing to load is the compiler-generated class that corresponds to the iterator method, and it is its GetEnumerator method that is causing the problem, since it is security transparent.

For comparison, if I modify the above method so that it populates and returns a List<MyItem>, everything works fine.

Any suggestions?

Thanks,

Tim.


问:
Where is the ANDROID_SDK_ROOT in ubuntu server?
I run a build on a ubuntu 16.04 server with no xorg or GUI of any kind, and I am trying to run a simulator on it. this is what I get on the console

```<code>$ /opt/android//tools/emulator -engine classic -ports 5688,5689 -report-console tcp:5815,max=60 -avd Nexus_5X_API_25 -no-snapshot-load -no-snapshot-save -no-window
PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
Build was aborted
</code>```

How do I set the ANDROID_SDK_ROOT in ubuntu?

答:
Type in terminal,

```<code>echo $ANDROID_SDK_ROOT
</code>```

this command will display ANDROID_SDK_ROOT variable path.

IF NOTHING APPEARS THEN SET IT WITH THIS

```<code>export ANDROID_SDK_ROOT = yourandroidsdkpath
</code>```

For displaying follow first command.

You can refer in this topic

Body:
I run a build on a ubuntu 16.04 server with no xorg or GUI of any kind, and I am trying to run a simulator on it. this is what I get on the console

$ /opt/android//tools/emulator -engine classic -ports 5688,5689 -report-console tcp:5815,max=60 -avd Nexus_5X_API_25 -no-snapshot-load -no-snapshot-save -no-window
PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
Build was aborted

How do I set the ANDROID_SDK_ROOT in ubuntu?

Body:
Type in terminal,

echo $ANDROID_SDK_ROOT

this command will display ANDROID_SDK_ROOT variable path.

IF NOTHING APPEARS THEN SET IT WITH THIS

export ANDROID_SDK_ROOT = yourandroidsdkpath

For displaying follow first command.

You can refer in this topic

ContentLicense: CC BY-SA 4.0


答:
You could next conditions:

```<code>get user input
if input is correct, congratulation user and exit
    else
        get user input //second attempt
        if input is correct, congratulation user and exit
...
</code>```

You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.

Title: Guessing a number

Body:
I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).

I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner ran = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int x = ran.nextInt();

        if (x < 3) {
            System.out.println("Too low. Try again.");

            System.out.println("Enter a number: ");
        } else if (x > 3) {
            System.out.println("Too high. Try again");

        } else if(x == 3) {
            System.out.println("You win. Nice job.");
        } else {
            System.out.println("You lose");
        }

        System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
    }
}

Body:
You could next conditions:

get user input
if input is correct, congratulation user and exit
    else
        get user input //second attempt
        if input is correct, congratulation user and exit
...

You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.


问:
Why is an object needed to refer to a class member inside of a static method?
Compare the way I print the value of the members of this class, in the static method (main) v/s a non-static method (the print method). In the static method, I need to use an object of this class, whereas, in the non-static method, I can refer to the class members directly.

I understand that the scope of static is class-wide, and is not tied to an object. Could someone elaborate a bit further on why I need to use an object in the static method, and it's not needed in a non-static method.

```<code>public class TreeDriver {
    Tree tree;
    TreeNode p;

    public TreeDriver() {
        tree = new Tree();
        p =null;
    }

    public static void main(String[] args) {
        TreeDriver obj = new TreeDriver();

        obj.print(obj.tree.root, obj.p);
    }

    public void print(TreeNode nodeA, TreeNode nodeB)
    {
        System.out.print(nodeA.val + ", " + nodeB.val);
        System.out.print(tree.root.val + ", " + p.val);
    }
}
</code>```

答:
The print method isn't a static method, so it can only be called on an instance of the TreeDriver class (i.e. it can't be called from the class directly, like TreeDriver.print(...))

From your perspective, there's no way around this really, as you're accessing the instance variables p and tree in your method.

I would add that it'd probably make more sense if you split out your driver methods (e.g. main(String[] args) away from your data model (i.e. the instance variables and the print method).

Body:
Compare the way I print the value of the members of this class, in the static method (main) v/s a non-static method (the print method). In the static method, I need to use an object of this class, whereas, in the non-static method, I can refer to the class members directly.

I understand that the scope of static is class-wide, and is not tied to an object. Could someone elaborate a bit further on why I need to use an object in the static method, and it's not needed in a non-static method.

public class TreeDriver {
    Tree tree;
    TreeNode p;

    public TreeDriver() {
        tree = new Tree();
        p =null;
    }

    public static void main(String[] args) {
        TreeDriver obj = new TreeDriver();

        obj.print(obj.tree.root, obj.p);
    }

    public void print(TreeNode nodeA, TreeNode nodeB)
    {
        System.out.print(nodeA.val + ", " + nodeB.val);
        System.out.print(tree.root.val + ", " + p.val);
    }
}


问:
Pass and consume a named function in Elixir?
The following Elixir code is incorrect but conveys (I think) the desired result:

```<code>defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(xs, f) do
    Enum.filter(xs, f.(x) > 5)
  end
end

Question.consumer([1, 2, 3], dbl) # [3]
Question.consumer([1, 2, 3], trp) # [2, 3]
</code>```

How should the consumer method be written to consume dbl and trp correctly? And then how would you call it?

Thank you!

EDIT:

A related question please. How would you write and call the Scala code below in Elixir:

```<code>def dbl(n: Int): Int = n * 2
def trp(n: Int): Int = n * 3

def consume(xs: List[Int], f: (Int) => Int): List[Int] =
  xs.filter(x => f(x) > 5)

consume(List(1, 2, 3), dbl) # List(3)
consume(List(1, 2, 3), trp) # List(2, 3)
</code>```

(Thank you) * 2

答:
The Elixir equivalent of Scala's x => f(x) > 5 is fn x -> f.(x) > 5 end. This is how you use it:

```<code>defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(list, f) do
    Enum.filter(list, fn x -> f.(x) > 5 end)
  end
end
</code>```

You can then call it using:

```<code>Question.consumer([1, 2, 3], &Question.dbl/1)   # => [3]
Question.consumer([1, 2, 3], &Question.trp/1)   # => [2, 3]
</code>```

Additional Notes:

You can also use the short-hand &(f.(&1) > 5) instead of the full function

Notice the & and /1  - You need to pass a complete reference to the named module methods. See the Elixir guide on the Function captures.

On the other hand, if you make the dbl and trp functions anonymous, you can pass them directly as arguments:

```<code>dbl = fn n -> n * 2 end
trp = fn n -> n * 3 end

Question.consumer([1, 2, 3], dbl)   # => [3]
Question.consumer([1, 2, 3], trp)   # => [2, 3]
</code>```

For reference, read: Why are there two kinds of functions in Elixir?

Body:
The following Elixir code is incorrect but conveys (I think) the desired result:

defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(xs, f) do
    Enum.filter(xs, f.(x) > 5)
  end
end

Question.consumer([1, 2, 3], dbl) # [3]
Question.consumer([1, 2, 3], trp) # [2, 3]

How should the consumer method be written to consume dbl and trp correctly? And then how would you call it?

Thank you!

EDIT:

A related question please. How would you write and call the Scala code below in Elixir:

def dbl(n: Int): Int = n * 2
def trp(n: Int): Int = n * 3

def consume(xs: List[Int], f: (Int) => Int): List[Int] =
  xs.filter(x => f(x) > 5)

consume(List(1, 2, 3), dbl) # List(3)
consume(List(1, 2, 3), trp) # List(2, 3)

(Thank you) * 2

Body:
The Elixir equivalent of Scala's x => f(x) > 5 is fn x -> f.(x) > 5 end. This is how you use it:

defmodule Question do
  def dbl(n), do: n * 2
  def trp(n), do: n * 3

  def consumer(list, f) do
    Enum.filter(list, fn x -> f.(x) > 5 end)
  end
end

You can then call it using:

Question.consumer([1, 2, 3], &Question.dbl/1)   # => [3]
Question.consumer([1, 2, 3], &Question.trp/1)   # => [2, 3]

Additional Notes:

You can also use the short-hand &(f.(&1) > 5) instead of the full function

Notice the & and /1  - You need to pass a complete reference to the named module methods. See the Elixir guide on the Function captures.

On the other hand, if you make the dbl and trp functions anonymous, you can pass them directly as arguments:

dbl = fn n -> n * 2 end
trp = fn n -> n * 3 end

Question.consumer([1, 2, 3], dbl)   # => [3]
Question.consumer([1, 2, 3], trp)   # => [2, 3]

For reference, read: Why are there two kinds of functions in Elixir?


问:
Unable to download jersey-quickstart-webapp from maven
I am trying download a jersey-quickstart-webapp using maven. I am unable to figure out what is wrong with my command below.

```<code>mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.2
</code>```

The errors I get are below: what am I doing wrong here?

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom

[INFO] Generating project in Interactive mode
[WARNING] No archetype found in remote catalog. Defaulting to internal catalog
[WARNING] Archetype not found in any catalog. Falling back to central repository
(http://repo.maven.apache.org/maven2).
[WARNING] Use -DarchetypeRepository=<your repository> if archetype's repository is elsewhere.
Downloading: http://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
Downloading: https://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.330 s
[INFO] Finished at: 2017-03-29T20:46:00+05:30
[INFO] Final Memory: 14M/139M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.glassfish.jersey.archetypes:jersey-quickstart-webapp:2.2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
</code>```

答:
The issue was not with the command but the settings.xml.
I had to add my local artifactory setton</p>

Body:
I am trying download a jersey-quickstart-webapp using maven. I am unable to figure out what is wrong with my command below.

mvn archetype:generate -DarchetypeGroupId=org.glassfish.jersey.archetypes  -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeVersion=2.2

The errors I get are below: what am I doing wrong here?

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom

[INFO] Generating project in Interactive mode
[WARNING] No archetype found in remote catalog. Defaulting to internal catalog
[WARNING] Archetype not found in any catalog. Falling back to central repository
(http://repo.maven.apache.org/maven2).
[WARNING] Use -DarchetypeRepository=<your repository> if archetype's repository is elsewhere.
Downloading: http://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
Downloading: https://repo.maven.apache.org/maven2/org/glassfish/jersey/archetypes/jersey-quickstart-webapp/2.2/jersey-quickstart-webapp-2.2.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.330 s
[INFO] Finished at: 2017-03-29T20:46:00+05:30
[INFO] Final Memory: 14M/139M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (org.glassfish.jersey.archetypes:jersey-quickstart-webapp:2.2) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.


答:
Static methods do not need an object instance to be called.

In your above example, another class could call your main function like so.

```<code>TreeDriver.main(args);
</code>```

Notice that TreeDriver is not an instantiated object. Contrast this with how a different class would need to call print.

```<code>TreeDrvier newTreeDrvier = new TreeDriver();
newTreeDriver.print(nodeA, nodeB);
</code>```

You need an instance of the TreeDriver object. Members are defined for an instance of the class, not for the class itself, unless the member itself is static, which in that case would make it a class variable.

Title: Why is an object needed to refer to a class member inside of a static method?

Body:
Static methods do not need an object instance to be called.

In your above example, another class could call your main function like so.

TreeDriver.main(args);

Notice that TreeDriver is not an instantiated object. Contrast this with how a different class would need to call print.

TreeDrvier newTreeDrvier = new TreeDriver();
newTreeDriver.print(nodeA, nodeB);

You need an instance of the TreeDriver object. Members are defined for an instance of the class, not for the class itself, unless the member itself is static, which in that case would make it a class variable.


问:
How many characters does bin2hex(random_bytes()) depending on input?
I'm using the following code to genrate a simple UID for my app:

```<code>private function _createUid() {
    $bytes = random_bytes(128);
    $uid = bin2hex($bytes);

    return $uid;
}
</code>```

By doing this, the result of _createUid() will be a 256 character string. My question is, will this string always be 256 characters if run on the same server, I'm aware of some differences on different servers. Also, is one byte equal to two characters?

Any help would be great, thanks!

答:
In hex a byte is always expressed as 2 characters.

Hexadecimal representation of a byte is a sequence of two character pairs. The first character represents the most significant 4 bits and the second character represents the least significant 4 bits of a byte.

Body:
I'm using the following code to genrate a simple UID for my app:

private function _createUid() {
    $bytes = random_bytes(128);
    $uid = bin2hex($bytes);

    return $uid;
}

By doing this, the result of _createUid() will be a 256 character string. My question is, will this string always be 256 characters if run on the same server, I'm aware of some differences on different servers. Also, is one byte equal to two characters?

Any help would be great, thanks!


问:
Ambiguous use of 'mutableCopy()' Swift3
I tried to update Swift 3 and I got the following error :

```<code>Ambiguous use of 'mutableCopy()'
</code>```

Before update to swift 3. It runs well.

Swift 2.3

```<code>NSUserDefaults.standardUserDefaults().objectForKey("listsavednews")?.mutableCopy() as! NSMutableArray
</code>```

Swift 3.0

```<code>(UserDefaults.standard.object(forKey: "listsavednews")? as AnyObject).mutableCopy() as! NSMutableArray
</code>```

I found that mutableCopy in Swift3 return Any that doesnt have method mutableCopy() so that it needs to cast to AnyObject.

Any helps thanks.

I dont know why I can't comment.

Thanks all, I'll be using :

```<code>UserDefaults.standard.mutableArrayValue(forKey: "listsavednews")
</code>```

答:
mutableCopy is an Objective-C method from NSObject. There's little reason to use it in Swift 3.

Since you are dealing with UserDefaults and mutableCopy, you must be dealing with either an array or dictionary. Or it could be a string.

The proper way to do this in Swift 3 is to use the proper UserDefaults method to get an array or dictionary. And assign the result to a var. That combination will give you a mutable array or mutable dictionary.

```<code>var someArray = UserDefaults.standard.array(forKey: "somekey")
</code>```

or:

```<code>var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey")
</code>```

In the two above cases, you end up with an optional since there might not be any data for the given key. And you also get a non-specific array or dictionary which isn't ideal. It would be better to cast the result to the appropriate type.

Let's say you have an array of strings and you want an empty array if there is nothing currently in user defaults. You can then do:

```<code>var someArray = UserDefaults.standard.array(forKey: "somekey" as? [String]) ?? []
</code>```

Adjust as necessary if the array contains something other than String.

If you actually have a dictionary, the code would be similar.

```<code>var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey") as? [String:String] ?? [:]
</code>```

If your original object is just a string, then you could do:

```<code>var someString = UserDefaults.standard.string(forKey: "somekey") ?? ""
</code>```

Title: Ambiguous use of 'mutableCopy()' Swift3

Body:
I tried to update Swift 3 and I got the following error :

Ambiguous use of 'mutableCopy()'

Before update to swift 3. It runs well.

Swift 2.3

NSUserDefaults.standardUserDefaults().objectForKey("listsavednews")?.mutableCopy() as! NSMutableArray

Swift 3.0

(UserDefaults.standard.object(forKey: "listsavednews")? as AnyObject).mutableCopy() as! NSMutableArray

I found that mutableCopy in Swift3 return Any that doesnt have method mutableCopy() so that it needs to cast to AnyObject.

Any helps thanks.

I dont know why I can't comment.

Thanks all, I'll be using :

UserDefaults.standard.mutableArrayValue(forKey: "listsavednews")

Body:
mutableCopy is an Objective-C method from NSObject. There's little reason to use it in Swift 3.

Since you are dealing with UserDefaults and mutableCopy, you must be dealing with either an array or dictionary. Or it could be a string.

The proper way to do this in Swift 3 is to use the proper UserDefaults method to get an array or dictionary. And assign the result to a var. That combination will give you a mutable array or mutable dictionary.

var someArray = UserDefaults.standard.array(forKey: "somekey")

or:

var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey")

In the two above cases, you end up with an optional since there might not be any data for the given key. And you also get a non-specific array or dictionary which isn't ideal. It would be better to cast the result to the appropriate type.

Let's say you have an array of strings and you want an empty array if there is nothing currently in user defaults. You can then do:

var someArray = UserDefaults.standard.array(forKey: "somekey" as? [String]) ?? []

Adjust as necessary if the array contains something other than String.

If you actually have a dictionary, the code would be similar.

var someDictionary = UserDefaults.standard.dictionary(forKey: "somekey") as? [String:String] ?? [:]

If your original object is just a string, then you could do:

var someString = UserDefaults.standard.string(forKey: "somekey") ?? ""


问:
Restart pm2 app every 12h with cron
Tried this, but it doesn't work:

```<code>SHELL=/bin/bash
PATH=/usr/lib/node_modules/pm2/bin
* 0,12 * * * pm2 restart all
</code>```

What am I doing wrong?

答:
Edit cron with crontab -e and add the following:

0 */12 * * * /usr/bin/node /usr/bin/pm2 restart all

For the schedule, use 0 */12 * * * for every 12 hours, or 0 0,12 * * * for 0:00 and 12:00 specifically. (Your schedule, * 0,12 * * *, would trigger every minute of hour 0 and hour 12, 0:00, 0:01, 0:02...)

For the command, as fedorqui mentioned, use the path to node followed by the path to pm2 and the pm2 options. Use which node and which pm2 to get the path to node and pm2.

Title: Restart pm2 app every 12h with cron

Body:
Tried this, but it doesn't work:

SHELL=/bin/bash
PATH=/usr/lib/node_modules/pm2/bin
* 0,12 * * * pm2 restart all

What am I doing wrong?


问:
Check parameter in Lambda Expression
I have this code:

```<code> Function<Integer, String> converter = (num) -> Integer.toString(num);
</code>```

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

答:
You will get a compile time error as soon as you will try to pass the converter.</p>

```<code>public static void main(String[] args) {
        Function<Integer, String> converter = (num) -> Integer.toString(num);
        Stream<String> stream = asList(1, 3, 4.5).stream().map(converter); //compilation error here as soon as you enter a float in asList.
        stream.forEach(System.out::println);
    }
</code>```

Title: Check parameter in Lambda Expression

Body:
I have this code:

 Function<Integer, String> converter = (num) -> Integer.toString(num);

As I see here the "num" is the parameter of the function, however, if my user accidentally input a float, there will be error.
I only create the "num" parameter in the Function code?
How can I add an exception like if(!(num instanceOf Integer)) {//throw exception}.

Body:
You will get a compile time error as soon as you will try to pass the converter.

public static void main(String[] args) {
        Function<Integer, String> converter = (num) -> Integer.toString(num);
        Stream<String> stream = asList(1, 3, 4.5).stream().map(converter); //compilation error here as soon as you enter a float in asList.
        stream.forEach(System.out::println);
    }


问:
raise ValueError('image width cannot be zero') ValueError: image width cannot be zero
when l try to crop an image l get this following error. here is my code.
I don't understand the error since my image is in a good shape in png format. what's wrong ?

```<code>from __future__ import print_function
    from wand.image import Image
    f = 'image1.png'
    with Image(filename=f) as img:
        print('width =', img.width)
        print('height =', img.height)
        #left,top,right,bottom
        x=img.crop(275, 347, 147, 239)
        x.size
        print(x.size)
</code>```

l got this error

```<code>    x=img.crop(275, 347, 147, 239)
  File "/usr/local/lib/python2.7/dist-packages/wand/image.py", line 543, in wrapped
    result = function(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/wand/image.py", line 1504, in crop
    raise ValueError('image width cannot be zero')
ValueError: image width cannot be zero
</code>```

Body:
when l try to crop an image l get this following error. here is my code.
I don't understand the error since my image is in a good shape in png format. what's wrong ?

from __future__ import print_function
    from wand.image import Image
    f = 'image1.png'
    with Image(filename=f) as img:
        print('width =', img.width)
        print('height =', img.height)
        #left,top,right,bottom
        x=img.crop(275, 347, 147, 239)
        x.size
        print(x.size)

l got this error

    x=img.crop(275, 347, 147, 239)
  File "/usr/local/lib/python2.7/dist-packages/wand/image.py", line 543, in wrapped
    result = function(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/wand/image.py", line 1504, in crop
    raise ValueError('image width cannot be zero')
ValueError: image width cannot be zero

Body:
Image.crop() takes left, top, right, and bottom offsets in the order. As the diagram in the docs shows, right and bottom offsets are from left and top, not right and bottom:

+--------------------------------------------------+
|              ^                         ^         |
|              |                         |         |
|             top                        |         |
|              |                         |         |
|              v                         |         |
| <-- left --> +-------------------+  bottom       |
|              |             ^     |     |         |
|              | <-- width --|---> |     |         |
|              |           height  |     |         |
|              |             |     |     |         |
|              |             v     |     |         |
|              +-------------------+     v         |
| <--------------- right ---------->               |
+--------------------------------------------------+

In your code img.crop(275, 347, 147, 239), 147 is on 275's left and 239 is above 347, and it's why ValueError is raised.


问:
How can I take more control in ASP.NET?
I'm trying to build a very, very simple "micro-webapp" which I suspect will be of interest to a few Stack Overflow'rs if I ever get it done. I'm hosting it on my C# in Depth site, which is vanilla ASP.NET 3.5 (i.e. not MVC).

The flow is very simple:

If a user enters the app with a URL which doesn't specify all the parameters (or if any of them are invalid) I want to just display the user input controls. (There are only two.)

If a user enters the app with a URL which does have all the required parameters, I want to display the results and the input controls (so they can change the parameters)

Here are my self-imposed requirements (mixture of design and implementation):

I want the submission to use GET rather than POST, mostly so users can bookmark the page easily.

I don't want the URL to end up looking silly after submission, with extraneous bits and pieces on it. Just the main URL and the real parameters please.

Ideally I'd like to avoid requiring JavaScript at all. There's no good reason for it in this app.

I want to be able to access the controls during render time and set values etc. In particular, I want to be able to set the default values of the controls to the parameter values passed in, if ASP.NET can't do this automatically for me (within the other restrictions).

I'm happy to do all the parameter validation myself, and I don't need much in the way of server side events. It's really simple to set everything on page load instead of attaching events to buttons etc.

Most of this is okay, but I haven't found any way of completely removing the viewstate and keeping the rest of the useful functionality. Using the post from this blog post I've managed to avoid getting any actual value for the viewstate - but it still ends up as a parameter on the URL, which looks really ugly.

If I make it a plain HTML form instead of an ASP.NET form (i.e. take out runat="server") then I don't get any magic viewstate - but then I can't access the controls programmatically.

I could do all of this by ignoring most of ASP.NET and building up an XML document with LINQ to XML, and implementing IHttpHandler. That feels a bit low level though.

I realise that my problems could be solved by either relaxing my constraints (e.g. using POST and not caring about the surplus parameter) or by using ASP.NET MVC, but are my requirements really unreasonable?

Maybe ASP.NET just doesn't scale down to this sort of app? There's a very likely alternative though: I'm just being stupid, and there's a perfectly simple way of doing it that I just haven't found.

Any thoughts, anyone? (Cue comments of how the mighty are fallen, etc. That's fine - I hope I've never claimed to be an ASP.NET expert, as the truth is quite the opposite...)

答:
I would create an HTTP module that handles routing (similar to MVC but not sophisticated, just a couple if statements) and hand it to aspx or ashx pages. aspx is preferred since it's easier to modify the page template. I wouldn't use WebControls in the aspx however. Just Response.Write.

By the way, to simplify things, you can do parameter validation in the module (as it shares code with routing probably) and save it to HttpContext.Items and then render them in the page. This will work pretty much like the MVC without all the bell and whistles. This is what I did a lot before ASP.NET MVC days.

OwnerDisplayName: Jon Skeet

Title: How can I take more control in ASP.NET?

LastEditorDisplayName: Jon Skeet

OwnerDisplayName: Mehrdad Afshari

LastEditorDisplayName: Mehrdad Afshari


问:
python: is there a disadvantage to from package import * besides namespace collision
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

```<code>from package import *
</code>```

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

```<code>for name in [namespace,namespace]:
    from package import name
</code>```

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

答:
When importing * you get everything in the module dumped straight into your namespace. This is not always a good thing as you could accentually overwrite something like;

```<code>from time import *
sleep = None
</code>```

This would render the time.sleep function useless...

The other way of taking functions, variables and classes from a module would be saying

```<code>from time import sleep
</code>```

This is a nicer way but often the best way is to just import the module and reference the module directly like

```<code>import time
time.sleep(3)
</code>```

Body:
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

from package import *

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

for name in [namespace,namespace]:
    from package import name

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

Body:
When importing * you get everything in the module dumped straight into your namespace. This is not always a good thing as you could accentually overwrite something like;

from time import *
sleep = None

This would render the time.sleep function useless...

The other way of taking functions, variables and classes from a module would be saying

from time import sleep

This is a nicer way but often the best way is to just import the module and reference the module directly like

import time
time.sleep(3)


问:
Most efficient way to group, count, then sort?
The data is two columns, City, I need to group by city based on sum.

Table looks something like this (times a million):

```<code>City, People
Boston, 1000
Boston, 2000
New York, 2500
Chicago, 2000
</code>```

In this case Boston would be number 1 with 3000 people. I would need to return the top 5% cities and their people count (sum).

What is the most efficient way to do this? Can pandas scale this up well? Should I keep track of the top 5% or do a sort at the end?

答:
If you would prefer to use Python without external libraries, you could do as follows.  First, I open the file with csv.  Then we can use the built in sorted function to sort our array at a custom key (basically, check the second element).  Then we grab the part we want with a [].

```<code>import csv, math

out = []
with open("data.csv","r") as fi:
    inCsv = csv.reader(fi,delimiter=',')
    for row in inCsv:
        out.append([col.strip() for col in row])
print (sorted(out[1:], key=lambda a: a[1], reverse=True)[:int(math.ceil(len(out)*.05))])
</code>```

Body:
The data is two columns, City, I need to group by city based on sum.

Table looks something like this (times a million):

City, People
Boston, 1000
Boston, 2000
New York, 2500
Chicago, 2000

In this case Boston would be number 1 with 3000 people. I would need to return the top 5% cities and their people count (sum).

What is the most efficient way to do this? Can pandas scale this up well? Should I keep track of the top 5% or do a sort at the end?

Body:
If you would prefer to use Python without external libraries, you could do as follows.  First, I open the file with csv.  Then we can use the built in sorted function to sort our array at a custom key (basically, check the second element).  Then we grab the part we want with a [].

import csv, math

out = []
with open("data.csv","r") as fi:
    inCsv = csv.reader(fi,delimiter=',')
    for row in inCsv:
        out.append([col.strip() for col in row])
print (sorted(out[1:], key=lambda a: a[1], reverse=True)[:int(math.ceil(len(out)*.05))])


问:
what's the reason for "Current SwiftyJSON (via Swift 3.0.2) cannot be imported with Swift 3.1"
When I tried to update Xcode8.3 (8E162) today - after updating carthage - an error occurred:

Current SwiftyJSON (via Swift 3.0.2) cannot be imported with Swift 3.1 balabala

and I found out that SwiftyJSON did not checkout successful in terminal. Later, after boring me for a few hours, I found that the solution is contained in the official

GitHub repository issue #771:

"Current SwiftyJSON (via Swift 3.0) cannot be imported with Swift 3.0.2.".

And also with the command

```<code>:carthage update --no-use-binaries SwiftyJSON --platform iOS
</code>```

you need to remove and add the SwiftyJSON.framwork again.

Although this problem is solved, but i do not know the reason, does any buddy know why？

答: Please make sure that use run swift 3.1 by type "swift --version" in CLI. If you still see "Apple Swift version 3.0.2" that mean your mac use swift  3.0.2 complier. Try to replace xcode 8.3 to xcode 8.2.1 may help. </p>

Body:
When I tried to update Xcode8.3 (8E162) today - after updating carthage - an error occurred:

Current SwiftyJSON (via Swift 3.0.2) cannot be imported with Swift 3.1 balabala

and I found out that SwiftyJSON did not checkout successful in terminal. Later, after boring me for a few hours, I found that the solution is contained in the official

GitHub repository issue #771:

"Current SwiftyJSON (via Swift 3.0) cannot be imported with Swift 3.0.2.".

And also with the command

:carthage update --no-use-binaries SwiftyJSON --platform iOS

you need to remove and add the SwiftyJSON.framwork again.

Although this problem is solved, but i do not know the reason, does any buddy know why？


答:
By definition, you don't need an instance to call a static method. There's really nothing more to say about "why" than just "that's the definition of a static method."

A non-static method is associated with a specific instance. As an analogy, if I tell you to start the car, you go start a specific car - you can't just grab the key and turn it in mid-air and expect it to "work."

Body:
Compare the way I print the value of the members of this class, in the static method (main) v/s a non-static method (the print method). In the static method, I need to use an object of this class, whereas, in the non-static method, I can refer to the class members directly.

I understand that the scope of static is class-wide, and is not tied to an object. Could someone elaborate a bit further on why I need to use an object in the static method, and it's not needed in a non-static method.

public class TreeDriver {
    Tree tree;
    TreeNode p;

    public TreeDriver() {
        tree = new Tree();
        p =null;
    }

    public static void main(String[] args) {
        TreeDriver obj = new TreeDriver();

        obj.print(obj.tree.root, obj.p);
    }

    public void print(TreeNode nodeA, TreeNode nodeB)
    {
        System.out.print(nodeA.val + ", " + nodeB.val);
        System.out.print(tree.root.val + ", " + p.val);
    }
}


问:
Create view with primary key?
I create a view with following codes

```<code>SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T1) AS TotalUsageValue, 'T1' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)

UNION ALL

SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T2' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T2) AS TotalUsageValue, 'T2' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)

UNION ALL

SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T3' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T3) AS TotalUsageValue, 'T3' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)
</code>```

I want to define CONVERT(nvarchar, YEAR(okuma_tarihi)) + 'T1' AS sno as a primary key is that possible? If is this possible how can I do?

答: You may not be able to create a primary key (per say) but if your view is based on a table with a primary key and the key is included in the view, then the primary key will be reflected in the view also.  Applications requiring a primary key may accept the view as it is the case with Lightswitch.</p>

Title: Create view with primary key?

Body:
I create a view with following codes

SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T1) AS TotalUsageValue, 'T1' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)

UNION ALL

SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T2' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T2) AS TotalUsageValue, 'T2' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)

UNION ALL

SELECT
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T3' AS sno,
    YEAR(okuma_tarihi) AS Yillar,
    SUM(toplam_kullanim_T3) AS TotalUsageValue, 'T3' AS UsageType
FROM
    TblSayacOkumalari
GROUP BY
    CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1', YEAR(okuma_tarihi)

I want to define CONVERT(nvarchar, YEAR(okuma_tarihi)) + 'T1' AS sno as a primary key is that possible? If is this possible how can I do?


问:
How to reference a .css file on a razor view?
I know how to set .css files on the _Layout.cshtml file, but what about applying a stylesheet on a per-view basis?

My thinking here is that, in _Layout.cshtml, you have  tags to work with, but not so in one of your non-layout views. Where do the <link> tags go?

答:
You can this structure in _Layout.cshtml file

```<code><link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />
</code>```

Body:
You can this structure in _Layout.cshtml file

<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />


问:
Comparing tm Type in C++
I have a vector<tm> times(x); object of assorted tm structs, each different than the other.  I would like to check every item in the vector and determine which time is the biggest/lowest.

For example, out of the tm items with times as follows:

```<code>01:00:00
00:01:00
00:00:01
</code>```

The first would be the largest time, and the last, which is closest to 00:00:00 is the smallest.  Is there any special way to go about finding the largest/smallest struct in the vector, or will I need to design a long looping program to compare each tm struct's hours, minutes and seconds respectively from scratch?

答: The standard template library contains std::min_element, std::max_element and std::minmax_element. The last one was introduced with c++11 (see cppreference) and should help you if tm is comparable.

Title: Comparing tm Type in C++

Body:
I have a vector<tm> times(x); object of assorted tm structs, each different than the other.  I would like to check every item in the vector and determine which time is the biggest/lowest.

For example, out of the tm items with times as follows:

01:00:00
00:01:00
00:00:01

The first would be the largest time, and the last, which is closest to 00:00:00 is the smallest.  Is there any special way to go about finding the largest/smallest struct in the vector, or will I need to design a long looping program to compare each tm struct's hours, minutes and seconds respectively from scratch?


答:
You can create a wrapper method that returns your converter Function wrapped in a try catch.</p>

```<code>Function<Integer, String> converter = num -> num.toString();

System.out.println(wrapper(converter).apply(5));

private static Function<Integer, String> wrapper(Function<Integer, String> function) {
        return x -> {
            try {
                return function.apply(x);
            } catch (Exception e) {
                return "Error";
            }
        };
    }
</code>```

Title: Check parameter in Lambda Expression

Body:
You can create a wrapper method that returns your converter Function wrapped in a try catch.

Function<Integer, String> converter = num -> num.toString();

System.out.println(wrapper(converter).apply(5));

private static Function<Integer, String> wrapper(Function<Integer, String> function) {
        return x -> {
            try {
                return function.apply(x);
            } catch (Exception e) {
                return "Error";
            }
        };
    }


问:
I cant call the functions on my django using react, mobx, axios, django
The function in my mobx store is being called but axios cant find my django function.

store.jsx

import { autorun, observable, action, computed } from 'mobx';
import axios from 'axios';

axios.defaults.xsrfHeaderName = "X-CSRFToken";

class ProductyTypeStore {
  @observable producttypelist = [];

  @action addProductType(description){
    console.log("before store add");
    axios.post('/addproducttype/')
        .then(function( res ){
          console.log(res);
        }) // then
        .catch(function(err){
         console.log(err);
        })
        console.log("after store add");

  }
}

var store1 = window.store = new ProductyTypeStore

export default store1```
</div>
</div>
</p>

<p>urls.py</p>

```urlpatterns = [
url(r'^', erp, name="erp"),
url(r'^addproducttype/$', addProductType, name = "addProductType")
```

<p>]</p>

<p>views.py</p>

```def erp(request):
context = {}
template = 'index.html'
return render( request, template, context )

def addProductType(request):
print("here @ add")
```

log on my manage.py runserver

--Starting development server at http://127.0.0.1:8000/
--Quit the server with CONTROL-C.
--[30/Mar/2017 03:51:19] "GET / HTTP/1.1" 200 524
--[30/Mar/2017 03:51:19] "GET /static/bundles/local/vendors.js HTTP/1.1" 200 366564
--[30/Mar/2017 03:51:19] "GET /static/bundles/local/erp-2a384599697b15811b6c.js HTTP/1.1" 200 2088371
--[30/Mar/2017 03:51:22] "POST /addproducttype/ HTTP/1.1" 200 524

My print("here @ add") in the django view is never printed. I have no idea whats wrong with my code.

答: It turns out that it has something to do with my URLS.PY configuration. It should be url(r'^$', erp, name="erp") instead of url(r'^', erp, name="erp"). </p>

Body:
The function in my mobx store is being called but axios cant find my django function.

store.jsx

import { autorun, observable, action, computed } from 'mobx';
import axios from 'axios';

axios.defaults.xsrfHeaderName = "X-CSRFToken";

class ProductyTypeStore {
  @observable producttypelist = [];

  @action addProductType(description){
    console.log("before store add");
    axios.post('/addproducttype/')
        .then(function( res ){
          console.log(res);
        }) // then
        .catch(function(err){
         console.log(err);
        })
        console.log("after store add");

  }
}

var store1 = window.store = new ProductyTypeStore

export default store1

urls.py

urlpatterns = [
url(r'^', erp, name="erp"),
url(r'^addproducttype/$', addProductType, name = "addProductType")

]

views.py

def erp(request):
context = {}
template = 'index.html'
return render( request, template, context )

def addProductType(request):
print("here @ add")

log on my manage.py runserver

--Starting development server at http://127.0.0.1:8000/
--Quit the server with CONTROL-C.
--[30/Mar/2017 03:51:19] "GET / HTTP/1.1" 200 524
--[30/Mar/2017 03:51:19] "GET /static/bundles/local/vendors.js HTTP/1.1" 200 366564
--[30/Mar/2017 03:51:19] "GET /static/bundles/local/erp-2a384599697b15811b6c.js HTTP/1.1" 200 2088371
--[30/Mar/2017 03:51:22] "POST /addproducttype/ HTTP/1.1" 200 524

My print("here @ add") in the django view is never printed. I have no idea whats wrong with my code.


问:
Scala - Convert a string to a timestamp
I'm working with PostgreSQL and PlayFramework, and I need to convert an Option[String] to a Timestamp for execute my query.

My Option[String] is a date in that format: 2016/07/26

And the format of the timestamp is: 2016-07-26

I know I can add  to_stimetamp(myDate, 'YYYY-MM-DD') to my query but I don't want use that (actually I don't know if I will use MySQL or PostgreSQL later an that function doesn't exist in MySQL)

So how can I do ?

答:
Here's an implicit conversion for timestamp literals.</p>

```<code>import java.sql.Timestamp
import java.time.Instant

object util {
  implicit class StringTimeConversions(sc: StringContext) {
    def t(args: Any*): Timestamp =
      Timestamp.from(Instant.parse(sc.s(args:_*)))
  }
}

import util._
val time: Timestamp = t"2007-01-01T00:00:00.00Z"
</code>```

Title: Scala - Convert a string to a timestamp

Body:
Here's an implicit conversion for timestamp literals.

import java.sql.Timestamp
import java.time.Instant

object util {
  implicit class StringTimeConversions(sc: StringContext) {
    def t(args: Any*): Timestamp =
      Timestamp.from(Instant.parse(sc.s(args:_*)))
  }
}

import util._
val time: Timestamp = t"2007-01-01T00:00:00.00Z"