问:
What is new() function here?
I've been learning design patterns and I saw such a method call from a class :

```<code>class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}
</code>```

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.

答:
I was the technical editor of that book; I have a copy right in front of me now. My copy says:

```<code>class Client : SubjectAccessor {
  static void Main() {
    Console.WriteLine("Proxy Pattern\n");

    ISubject subject = new Proxy();
    Console.WriteLine(subject.Request());
    Console.WriteLine(subject.Request());

    ProtectionProxy subject = new ProtectionProxy();
    Console.WriteLine(subject.Request());
</code>```

Now, there is an error here; the variable "subject" has been declared twice.  Apparently I did not catch the error when I reviewed the book. (The correct thing to do here is to remove the type from the second declaration of "subject").

However, that is not the error that you are reporting.

Are you sure that is not what your copy says?  I have the December 2007 first edition; what edition do you have?  Perhaps someone attempted to correct this error in a later edition and messed it up? My guess would be that someone tried to correct the error by removing both mentions of the ProtectionProxy type from the erroneous line rather than removing the first one.

Title: What is new() function here?

Body:
I've been learning design patterns and I saw such a method call from a class :

class Client: SubjectAccessor {
    static void Main() {
        Console.WriteLine("Proxy Pattern\n");

        ISubject subject = new Proxy();
        Console.WriteLine(subject.Requesy());

        subject = new(); //Here is what I am asking
        COnsole.WriteLine(subject.Request());
    }
}

As you can see there is a subject = new(); call there and I am wondering whether it is creating a new instance of Proxy or something else. I've not found anything related to this.

Your help is much appreciated.

If you need, I can paste the whole code or actually it is written on a book so I need to write it down here.

Thanks.

Body:
I was the technical editor of that book; I have a copy right in front of me now. My copy says:

class Client : SubjectAccessor {
  static void Main() {
    Console.WriteLine("Proxy Pattern\n");

    ISubject subject = new Proxy();
    Console.WriteLine(subject.Request());
    Console.WriteLine(subject.Request());

    ProtectionProxy subject = new ProtectionProxy();
    Console.WriteLine(subject.Request());

Now, there is an error here; the variable "subject" has been declared twice.  Apparently I did not catch the error when I reviewed the book. (The correct thing to do here is to remove the type from the second declaration of "subject").

However, that is not the error that you are reporting.

Are you sure that is not what your copy says?  I have the December 2007 first edition; what edition do you have?  Perhaps someone attempted to correct this error in a later edition and messed it up? My guess would be that someone tried to correct the error by removing both mentions of the ProtectionProxy type from the erroneous line rather than removing the first one.


来源: stackexchange

问:
Check if input is a string in C# after converting it to a double
I am  working on a console application that's a simple calculator in C# and I want to check if the user has entered a string instead of a number/decimal. Instead I get a System.Format Exception which breaks the program. I'm unsure how to tell the program not to break if it sees string characters. I've used do while loops as a way to re-prompt the user if they enter a negative number or any other invalid value.

Here's my code:

```<code>using System;

namespace Calc
{
    public class Calc
    {
        public static void Main()
        {

        ///Declare variables
        double p,r,y;
        string input1, input2, input3;

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the principal
            Console.Write("Enter the principal: ");
            input1 = Console.ReadLine();
            p = double.Parse(input1);
        } while(p < 0 );

        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        r = double.Parse(input2);

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the rate
            Console.Write("Enter the rate: ");
            input2 = Console.ReadLine();
            r = double.Parse(input2);

        } while(r < 0);

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the number of years
            Console.Write("Enter the number of years: ");
            input3 = Console.ReadLine();
            y = double.Parse(input3);
        } while (y < 0);

        ///Calculate the user input using the mortgage rate formula
        double p1 = (r / 1200.0);
        double m = y * 12;
        double nm = 0 - m;
        double month = p * p1 / (1 - System.Math.Pow((1 + p1), nm));

        //Output the result of the monthly payment
        Console.WriteLine(String.Format("The amount of the monthly payment is: {0}{1:0.00}", "$", month));
        Console.WriteLine();
        Console.WriteLine("Press Enter to end the calculator program. . .");
        Console.Read();
    }
}
}
</code>```

答:
You can use TryParse which returns a bool to tell if the conversion was successful:

```<code>bool IsValid = double.TryParse(input2,out r);
</code>```

Now you can check if IsValid returns true then it is a valid value coming, otherwise you can prompt user to re-enter:

```<code>    bool IsValid = false;
    ///Prompt user to reenter value if the input is illegal
    do
    {
        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        IsValid = double.TryParse(input2, out r);

    } while(!IsValid && r < 0);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am  working on a console application that's a simple calculator in C# and I want to check if the user has entered a string instead of a number/decimal. Instead I get a System.Format Exception which breaks the program. I'm unsure how to tell the program not to break if it sees string characters. I've used do while loops as a way to re-prompt the user if they enter a negative number or any other invalid value.

Here's my code:

using System;

namespace Calc
{
    public class Calc
    {
        public static void Main()
        {

        ///Declare variables
        double p,r,y;
        string input1, input2, input3;

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the principal
            Console.Write("Enter the principal: ");
            input1 = Console.ReadLine();
            p = double.Parse(input1);
        } while(p < 0 );

        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        r = double.Parse(input2);

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the rate
            Console.Write("Enter the rate: ");
            input2 = Console.ReadLine();
            r = double.Parse(input2);

        } while(r < 0);

        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the number of years
            Console.Write("Enter the number of years: ");
            input3 = Console.ReadLine();
            y = double.Parse(input3);
        } while (y < 0);

        ///Calculate the user input using the mortgage rate formula
        double p1 = (r / 1200.0);
        double m = y * 12;
        double nm = 0 - m;
        double month = p * p1 / (1 - System.Math.Pow((1 + p1), nm));

        //Output the result of the monthly payment
        Console.WriteLine(String.Format("The amount of the monthly payment is: {0}{1:0.00}", "$", month));
        Console.WriteLine();
        Console.WriteLine("Press Enter to end the calculator program. . .");
        Console.Read();
    }
}
}

Body:
You can use TryParse which returns a bool to tell if the conversion was successful:

bool IsValid = double.TryParse(input2,out r);

Now you can check if IsValid returns true then it is a valid value coming, otherwise you can prompt user to re-enter:

    bool IsValid = false;
    ///Prompt user to reenter value if the input is illegal
    do
    {
        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        IsValid = double.TryParse(input2, out r);

    } while(!IsValid && r < 0);


问:
Android programmatically setting up layout for different screen sizes/densities
I am currently creating an Android app that I want to support multiple screen sizes/densities.  When I set up layouts in xml, everything looks fine across different screen sizes.  However, there are rows I need to add programatically.

Whenever I add the rows, I can't seem to get things to look consistent across different devices.  I believe using the dp unit when settings up heights, widths in xml, along with wrap_content and match_parent when appropriate, have allowed things to easily translate between different devices.

Programatically, when I try to set a layout height/width, I have been trying to convert the anticipated dp value to a pixel value.  I've done so using this:

```<code>    public static int convertToPixels(int value) {
        Resources resources = mContext.getResources();
        int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,value,resources.getDisplayMetrics());
        return x;
    }
</code>```

Overall, the heights look ok, but the widths don't look good.  For instance, the width of the row will look such that on a smaller device, the information neatly displays across the row, which is what I want.  However,when I try to run the app on a tablet, for instance, the information will only stretch to half of the row, which doesn't look good.  I want the sizes to scale and neatly display just like on the smaller device.

If anyone has any idea what my problem might be, I would greatly appreciate it.  Below is the source for adding a row using java:

```<code>        LinearLayout row = new LinearLayout(mContext);
        row.setOrientation(LinearLayout.HORIZONTAL);
        row.setId(Integer.parseInt(txn.getId().toString()));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(60));
        params.setMargins(0, convertToPixels(1), 0, 0);

        row.setLayoutParams(params);
        row.setBackgroundColor(mContext.getResources().getColor(R.color.white));

        LinearLayout imageLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(convertToPixels(40), convertToPixels(40));
        imageParams.gravity = Gravity.CENTER;
        imageLayout.setLayoutParams(imageParams);
        ImageView image = new ImageView(mContext);

        if (txn.getTransactionStateID() == Constants.TXN_STATUS_OK) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ok));
        } else if (txn.getTransactionStateID() == Constants.TXN_STATUS_SUSPICIOUS) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alert));
        } else if (txn.getTransactionStateID() == Constants.TXN_STATUS_RED_FLAG) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.flag));
        }

        imageLayout.addView(image);

        row.addView(imageLayout);

        LinearLayout txnMiddleLayout = new LinearLayout(mContext);
        txnMiddleLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams txnTopParams = new LinearLayout.LayoutParams(convertToPixels(400), convertToPixels(60));
        txnTopParams.setMargins(convertToPixels(10), 0, 0, 0);
        txnMiddleLayout.setLayoutParams(txnTopParams);

        TextView txnTopContents = new TextView(mContext);
        txnTopContents.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        txnTopContents.setText(txn.getTopLineContents());
        txnTopContents.setTextColor(Color.BLACK);
    //    txnTopContents.setTextSize(convertToPixels(16));
        TextView txnBottomContents = new TextView(mContext);
        txnBottomContents.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        txnBottomContents.setText(txn.getBottomLineContents());
    //    txnBottomContents.setTextSize(convertToPixels(12));

        txnMiddleLayout.addView(txnTopContents);
        txnMiddleLayout.addView(txnBottomContents);

        row.addView(txnMiddleLayout);

        LinearLayout txnBottomLayout = new LinearLayout(mContext);
        txnBottomLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams txnBottomParams = new LinearLayout.LayoutParams(convertToPixels(120), convertToPixels(60));
        txnBottomLayout.setLayoutParams(txnBottomParams);

        TextView amount = new TextView(mContext);
        amount.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        amount.setText(txn.getAmountStr());
        amount.setTextColor(Color.BLACK);
 //      amount.setTextSize(convertToPixels(16));

        TextView date = new TextView(mContext);
        date.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        date.setText(txn.getDateStr());
    //    date.setTextSize(convertToPixels(12));

        txnBottomLayout.addView(amount);
        txnBottomLayout.addView(date);

        row.addView(txnBottomLayout);

        txnList.addView(row);
</code>```

答:
I eventually found a solution.  Instead of trying to set an exact width value, I set the width of the layout or textview to 0, and used layout_weight instead.

https://stackoverflow.com/a/3996104/4056947

Body:
I am currently creating an Android app that I want to support multiple screen sizes/densities.  When I set up layouts in xml, everything looks fine across different screen sizes.  However, there are rows I need to add programatically.

Whenever I add the rows, I can't seem to get things to look consistent across different devices.  I believe using the dp unit when settings up heights, widths in xml, along with wrap_content and match_parent when appropriate, have allowed things to easily translate between different devices.

Programatically, when I try to set a layout height/width, I have been trying to convert the anticipated dp value to a pixel value.  I've done so using this:

    public static int convertToPixels(int value) {
        Resources resources = mContext.getResources();
        int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,value,resources.getDisplayMetrics());
        return x;
    }

Overall, the heights look ok, but the widths don't look good.  For instance, the width of the row will look such that on a smaller device, the information neatly displays across the row, which is what I want.  However,when I try to run the app on a tablet, for instance, the information will only stretch to half of the row, which doesn't look good.  I want the sizes to scale and neatly display just like on the smaller device.

If anyone has any idea what my problem might be, I would greatly appreciate it.  Below is the source for adding a row using java:

        LinearLayout row = new LinearLayout(mContext);
        row.setOrientation(LinearLayout.HORIZONTAL);
        row.setId(Integer.parseInt(txn.getId().toString()));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(60));
        params.setMargins(0, convertToPixels(1), 0, 0);

        row.setLayoutParams(params);
        row.setBackgroundColor(mContext.getResources().getColor(R.color.white));

        LinearLayout imageLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(convertToPixels(40), convertToPixels(40));
        imageParams.gravity = Gravity.CENTER;
        imageLayout.setLayoutParams(imageParams);
        ImageView image = new ImageView(mContext);

        if (txn.getTransactionStateID() == Constants.TXN_STATUS_OK) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ok));
        } else if (txn.getTransactionStateID() == Constants.TXN_STATUS_SUSPICIOUS) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.alert));
        } else if (txn.getTransactionStateID() == Constants.TXN_STATUS_RED_FLAG) {
            image.setImageDrawable(mContext.getResources().getDrawable(R.drawable.flag));
        }

        imageLayout.addView(image);

        row.addView(imageLayout);

        LinearLayout txnMiddleLayout = new LinearLayout(mContext);
        txnMiddleLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams txnTopParams = new LinearLayout.LayoutParams(convertToPixels(400), convertToPixels(60));
        txnTopParams.setMargins(convertToPixels(10), 0, 0, 0);
        txnMiddleLayout.setLayoutParams(txnTopParams);

        TextView txnTopContents = new TextView(mContext);
        txnTopContents.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        txnTopContents.setText(txn.getTopLineContents());
        txnTopContents.setTextColor(Color.BLACK);
    //    txnTopContents.setTextSize(convertToPixels(16));
        TextView txnBottomContents = new TextView(mContext);
        txnBottomContents.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        txnBottomContents.setText(txn.getBottomLineContents());
    //    txnBottomContents.setTextSize(convertToPixels(12));

        txnMiddleLayout.addView(txnTopContents);
        txnMiddleLayout.addView(txnBottomContents);

        row.addView(txnMiddleLayout);

        LinearLayout txnBottomLayout = new LinearLayout(mContext);
        txnBottomLayout.setOrientation(LinearLayout.VERTICAL);
        LinearLayout.LayoutParams txnBottomParams = new LinearLayout.LayoutParams(convertToPixels(120), convertToPixels(60));
        txnBottomLayout.setLayoutParams(txnBottomParams);

        TextView amount = new TextView(mContext);
        amount.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        amount.setText(txn.getAmountStr());
        amount.setTextColor(Color.BLACK);
 //      amount.setTextSize(convertToPixels(16));

        TextView date = new TextView(mContext);
        date.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, convertToPixels(30)));
        date.setText(txn.getDateStr());
    //    date.setTextSize(convertToPixels(12));

        txnBottomLayout.addView(amount);
        txnBottomLayout.addView(date);

        row.addView(txnBottomLayout);

        txnList.addView(row);


问:
Basic Angular app using ui-router won't load login
I'm working on a POC for work and I can't find whatever stupid mistake is hiding here. I have a bare-bones/basic angular app, using ui-router. Plunker can be found here.

In the chrome console I can see my app.module is being created, however the login page never appears. This is a very, very basic app so I figure it must be something simple I'm missing. Any suggestions? Below is a quick sample:

config.js

```<code>(function() {
'use strict'
var app = angular.module('app.core');
app.config(AppRouter);
AppRouter.$inject = ['$stateProvider', '$urlRouterProvider'];

function AppRouter($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('login');
  $stateProvider
    .state('/', {
      templateUrl: 'login.html',
      controller: 'LoginController',
      controllerAs: 'vm',
    })
    .state('login', {
      templateUrl: 'login.html',
      controller: 'LoginController',
      controllerAs: 'vm',
    });
}
})();
</code>```

login.controller.js

```<code>(function() {
'use strict';

var app = angular.module('app.login');

app.controller('LoginController', LoginController);

LoginController.$inject = ['$location', '$filter', '$window', '$rootScope'];

function LoginController($location, $filter, $window, $rootScope) {
  var init = function() {
    console.log('here');
  };

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

app.module.js

```<code>(function() {
  var app = angular.module('app', ['app.core', 'app.login']);
})();
</code>```

login.module.js

```<code>(function(){
    'use strict'
    var app = angular.module('app.login', ['app.core']);
})();
</code>```

core.module.js

```<code>(function(){
    'use strict'
    var app = angular.module('app.core', ['ui.router']);
})();
</code>```

答:
After few changes it worked for me (see forked plunk: https://plnkr.co/edit/D5AL8DTnqYI2g23wjE7W?p=preview):

You forgot to load AngularJS (between </head).
You forgot to add ng-app, I add it on body.
And I made some changes in config.js:

```<code>function AppRouter($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/login');
    $stateProvider
      .state('/', {
        templateUrl: 'login.html',
        controller: 'LoginController',
        controllerAs: 'vm',
      })
      .state('login', {
        url: '/login',
        templateUrl: 'login.html',
        controller: 'LoginController',
        controllerAs: 'vm',
      });
  }
</code>```

I add url to login state, and I made changes to otherwise function: I changed login to /login cause it needs URL, not state name.
I think you overconfigured you app a little bit (too much modules), and it makes it hard to read for me, but it's only my opinion and to be frankly, maybe it's only because I don't use modules very frequently. Try to add this changes to your Plunk and please write if it won't work, casue I could accidentally skip something.

Body:
I'm working on a POC for work and I can't find whatever stupid mistake is hiding here. I have a bare-bones/basic angular app, using ui-router. Plunker can be found here.

In the chrome console I can see my app.module is being created, however the login page never appears. This is a very, very basic app so I figure it must be something simple I'm missing. Any suggestions? Below is a quick sample:

config.js

(function() {
'use strict'
var app = angular.module('app.core');
app.config(AppRouter);
AppRouter.$inject = ['$stateProvider', '$urlRouterProvider'];

function AppRouter($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('login');
  $stateProvider
    .state('/', {
      templateUrl: 'login.html',
      controller: 'LoginController',
      controllerAs: 'vm',
    })
    .state('login', {
      templateUrl: 'login.html',
      controller: 'LoginController',
      controllerAs: 'vm',
    });
}
})();

login.controller.js

(function() {
'use strict';

var app = angular.module('app.login');

app.controller('LoginController', LoginController);

LoginController.$inject = ['$location', '$filter', '$window', '$rootScope'];

function LoginController($location, $filter, $window, $rootScope) {
  var init = function() {
    console.log('here');
  };

  init();
}
})();

app.module.js

(function() {
  var app = angular.module('app', ['app.core', 'app.login']);
})();

login.module.js

(function(){
    'use strict'
    var app = angular.module('app.login', ['app.core']);
})();

core.module.js

(function(){
    'use strict'
    var app = angular.module('app.core', ['ui.router']);
})();

Body:
After few changes it worked for me (see forked plunk: https://plnkr.co/edit/D5AL8DTnqYI2g23wjE7W?p=preview):

You forgot to load AngularJS (between <head></head).
You forgot to add ng-app, I add it on body.
And I made some changes in config.js:

function AppRouter($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/login');
    $stateProvider
      .state('/', {
        templateUrl: 'login.html',
        controller: 'LoginController',
        controllerAs: 'vm',
      })
      .state('login', {
        url: '/login',
        templateUrl: 'login.html',
        controller: 'LoginController',
        controllerAs: 'vm',
      });
  }

I add url to login state, and I made changes to otherwise function: I changed login to /login cause it needs URL, not state name.
I think you overconfigured you app a little bit (too much modules), and it makes it hard to read for me, but it's only my opinion and to be frankly, maybe it's only because I don't use modules very frequently. Try to add this changes to your Plunk and please write if it won't work, casue I could accidentally skip something.


问:
java: jGrasp unchecked or unsafe operations
Please, before pitching this into the duplicate bucket, have mercy and help a Java 'newbie'...my code is:

```<code>//at top of class
List<String> faceStrList             = new ArrayList<String>(cardsPerSuit);
</code>```

Then, the line (in another method) that uses the offending other method:

```<code>faceStrList = readInfo( cardValueFileStr, faceStrList );
</code>```

and the problem-child:

```<code>public static List readInfo( String inputFile, List<String> dataArrayOfStr )
{
    String word = 'dummy';
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}
</code>```

Again, please look kindly.

答:
Here:

```<code>public static List readInfo(
</code>```

You got your generics "correct" all over the place; but not when declaring that method. You are omitting the generic type for the returned list; thus returning a raw type instead (see here for details). And that is what the compiler warns you about.

So the solution is simply to do the same thing that you did in other places, and change the method signature to

```<code>public static List<String> readInfo(
</code>```

And for the record:

```<code>List<String> faceStrList = new ArrayList<String>(cardsPerSuit);
</code>```

could be simplified like

```<code>List<String> faces = new ArrayList<>(cardsPerSuit);
</code>```

You can omit the generic type using the <> diamond operator; no need to repeat that information

Beyond that: there is no point in putting the collection type into your variable name. Just make clear "it is more than one". The point is: maybe you want to change the collection type later on. Believe me, you will get tired of renaming all your variables then!

It is not exactly good practice to return the list that comes in as parameter already. And it is also not required - adding something to the list like you do already affects that incoming list. To return that list simply makes your interface more "complicated" to understand.

Body:
Please, before pitching this into the duplicate bucket, have mercy and help a Java 'newbie'...my code is:

//at top of class
List<String> faceStrList             = new ArrayList<String>(cardsPerSuit);

Then, the line (in another method) that uses the offending other method:

faceStrList = readInfo( cardValueFileStr, faceStrList );

and the problem-child:

public static List readInfo( String inputFile, List<String> dataArrayOfStr )
{
    String word = 'dummy';
    dataArrayOfStr.add(word);
    return dataArrayOfStr;
}

Again, please look kindly.

Body:
Here:

public static List readInfo(

You got your generics "correct" all over the place; but not when declaring that method. You are omitting the generic type for the returned list; thus returning a raw type instead (see here for details). And that is what the compiler warns you about.

So the solution is simply to do the same thing that you did in other places, and change the method signature to

public static List<String> readInfo(

And for the record:

List<String> faceStrList = new ArrayList<String>(cardsPerSuit);

could be simplified like

List<String> faces = new ArrayList<>(cardsPerSuit);

You can omit the generic type using the <> diamond operator; no need to repeat that information

Beyond that: there is no point in putting the collection type into your variable name. Just make clear "it is more than one". The point is: maybe you want to change the collection type later on. Believe me, you will get tired of renaming all your variables then!

It is not exactly good practice to return the list that comes in as parameter already. And it is also not required - adding something to the list like you do already affects that incoming list. To return that list simply makes your interface more "complicated" to understand.


问:
select section name where marks of every student rounded to 10
table

```<code>Sec            marks
....................
a               10
a               20
a               30
b               5
b               10
b               25
c               40
c               53
c               37
</code>```

desired output

```<code>...............
sec      marks
...............
a         10
a         20
a         30
</code>```

but i am getting all the sections a,b&c
i tried
.........

```<code>select sec,marks from students where marks%10=0;
</code>```

答:
If you need only the sect where all the value are "rounded to 10"

you could use a not in with a subselect  this way

```<code>select sec from my_table
where sec not in (select sect
                  from my_table
                  where mod(marks, 10) != 0)
</code>```

Body:
table

Sec            marks
....................
a               10
a               20
a               30
b               5
b               10
b               25
c               40
c               53
c               37

desired output

...............
sec      marks
...............
a         10
a         20
a         30

but i am getting all the sections a,b&c
i tried
.........

select sec,marks from students where marks%10=0;

Body:
If you need only the sect where all the value are "rounded to 10"

you could use a not in with a subselect  this way

select sec from my_table
where sec not in (select sect
                  from my_table
                  where mod(marks, 10) != 0)


问:
Unable to generate UUIDs in Spark SQL

below is the code block and the error recieved

```<code>> creating a temporary views
sqlcontext.sql("""CREATE TEMPORARY VIEW temp_pay_txn_stage
     USING org.apache.spark.sql.cassandra
     OPTIONS (
       table "t_pay_txn_stage",
       keyspace "ks_pay",
       cluster "Test Cluster",
       pushdown "true"
     )""".stripMargin)

sqlcontext.sql("""CREATE TEMPORARY VIEW temp_pay_txn_source
     USING org.apache.spark.sql.cassandra
     OPTIONS (
       table "t_pay_txn_source",
       keyspace "ks_pay",
       cluster "Test Cluster",
       pushdown "true"
     )""".stripMargin)
</code>```

querying the views as below to be able to get new records from stage not present in source .

```<code>Scala> val df_newrecords = sqlcontext.sql("""Select UUID(),
 | |stage.order_id,
 | |stage.order_description,
 | |stage.transaction_id,
 | |stage.pre_transaction_freeze_balance,
 | |stage.post_transaction_freeze_balance,
 | |toTimestamp(now()),
 | |NULL,
 | |1 from temp_pay_txn_stage  stage left join temp_pay_txn_source source on stage.order_id=source.order_id and stage.transaction_id=source.transaction_id where
 | |source.order_id is null and source.transaction_id is null""")`

org.apache.spark.sql.AnalysisException: Undefined function: 'uuid()'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 7
</code>```

i am trying to get the UUIDs generated , but getting this error.

答:
Here is a Simple Example How you can generate timeuuid :

```<code>import org.apache.spark.sql.SQLContext
val sqlcontext = new SQLContext(sc)

import sqlcontext.implicits._

//Import UUIDs that contains the method timeBased()
import com.datastax.driver.core.utils.UUIDs

//user define function timeUUID  which will retrun time based uuid
val timeUUID = udf(() => UUIDs.timeBased().toString)

//sample query to test, you can change it to yours
val df_newrecords = sqlcontext.sql("SELECT 1 as data UNION SELECT 2 as data").withColumn("time_uuid", timeUUID())

//print all the rows
df_newrecords.collect().foreach(println)
</code>```

Output :

```<code>[1,9a81b3c0-170b-11e7-98bf-9bb55f3128dd]
[2,9a831350-170b-11e7-98bf-9bb55f3128dd]
</code>```

Source : https://stackoverflow.com/a/37232099/2320144
https://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html#timeBased--

Title: Unable to generate UUIDs in Spark SQL

Body:
below is the code block and the error recieved

> creating a temporary views
sqlcontext.sql("""CREATE TEMPORARY VIEW temp_pay_txn_stage
     USING org.apache.spark.sql.cassandra
     OPTIONS (
       table "t_pay_txn_stage",
       keyspace "ks_pay",
       cluster "Test Cluster",
       pushdown "true"
     )""".stripMargin)

sqlcontext.sql("""CREATE TEMPORARY VIEW temp_pay_txn_source
     USING org.apache.spark.sql.cassandra
     OPTIONS (
       table "t_pay_txn_source",
       keyspace "ks_pay",
       cluster "Test Cluster",
       pushdown "true"
     )""".stripMargin)

querying the views as below to be able to get new records from stage not present in source .

Scala> val df_newrecords = sqlcontext.sql("""Select UUID(),
 | |stage.order_id,
 | |stage.order_description,
 | |stage.transaction_id,
 | |stage.pre_transaction_freeze_balance,
 | |stage.post_transaction_freeze_balance,
 | |toTimestamp(now()),
 | |NULL,
 | |1 from temp_pay_txn_stage  stage left join temp_pay_txn_source source on stage.order_id=source.order_id and stage.transaction_id=source.transaction_id where
 | |source.order_id is null and source.transaction_id is null""")`

org.apache.spark.sql.AnalysisException: Undefined function: 'uuid()'. This function is neither a registered temporary function nor a permanent function registered in the database 'default'.; line 1 pos 7

i am trying to get the UUIDs generated , but getting this error.

Body:
Here is a Simple Example How you can generate timeuuid :

import org.apache.spark.sql.SQLContext
val sqlcontext = new SQLContext(sc)

import sqlcontext.implicits._

//Import UUIDs that contains the method timeBased()
import com.datastax.driver.core.utils.UUIDs

//user define function timeUUID  which will retrun time based uuid
val timeUUID = udf(() => UUIDs.timeBased().toString)

//sample query to test, you can change it to yours
val df_newrecords = sqlcontext.sql("SELECT 1 as data UNION SELECT 2 as data").withColumn("time_uuid", timeUUID())

//print all the rows
df_newrecords.collect().foreach(println)

Output :

[1,9a81b3c0-170b-11e7-98bf-9bb55f3128dd]
[2,9a831350-170b-11e7-98bf-9bb55f3128dd]

Source : https://stackoverflow.com/a/37232099/2320144
https://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/utils/UUIDs.html#timeBased--


问:
How to avoid an "unreachable statement" due to compile-time-computed values?
If I write the following CUDA code:

```<code>#include <stdio.h>

template <unsigned N>
__global__ void foo()
{
    printf("In kernel foo() with N = %u\n", N);
    if (N < 10) { return; }
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

int main() {
    foo<5><<<1,1>>>();
    foo<20><<<1,1>>>();
    return 0;
}
</code>```

I get a compiler warning:

```<code>a.cu(8): warning: statement is unreachable
          detected during instantiation of "void foo<N>() [with N=5U]"
(12): here
</code>```

I "feel" I shouldn't be getting this warning, since the unreachable code is only unreachable for certain values of the template parameter. And if I write the "CPU equivalent", so to speak:

```<code>#include <cstdio>

template <unsigned N>
void foo()
{
    std::printf("In kernel foo() with N = %u\n", N);
    if (N < 10) { return; }
    std::printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

int main() {
    foo<5>();
    foo<20>();
    return 0;
}
</code>```

and build this with gcc (5.4.0) - I don't get any warnings, even if I compile with -Wall.

Now, I can circumvent this by writing

```<code>if (not (N < 10)) {
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}
</code>```

but I would rather avoid having to reverse my logic to jump through nvcc's "hoop". I could also write

```<code>if (not (N < 10)) {
    return;
}
else {
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}
</code>```

but - I don't want to indent all that code (and the same problem may occur again, requiring even more indentation inside the else block.

Is there something I could do? Also, isn't this a "bug", or a misfeature I should report as a bug?

答:
What about:</p>

```<code>template<unsigned N, bool>
struct FooImpl
{
  static void foo()
  {
    std::printf("In kernel foo() with N = %u\n", N);
  }
};

template<unsigned N>
struct FooImpl<N, false>
{
  static void foo()
  {
    std::printf("In kernel foo() with N = %u\n", N);
    std::printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
  }
};

template <unsigned N>
__global__ void foo()
{
  FooImpl<N, N < 10>::foo();
}
</code>```

Body:
If I write the following CUDA code:

#include <stdio.h>

template <unsigned N>
__global__ void foo()
{
    printf("In kernel foo() with N = %u\n", N);
    if (N < 10) { return; }
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

int main() {
    foo<5><<<1,1>>>();
    foo<20><<<1,1>>>();
    return 0;
}

I get a compiler warning:

a.cu(8): warning: statement is unreachable
          detected during instantiation of "void foo<N>() [with N=5U]"
(12): here

I "feel" I shouldn't be getting this warning, since the unreachable code is only unreachable for certain values of the template parameter. And if I write the "CPU equivalent", so to speak:

#include <cstdio>

template <unsigned N>
void foo()
{
    std::printf("In kernel foo() with N = %u\n", N);
    if (N < 10) { return; }
    std::printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

int main() {
    foo<5>();
    foo<20>();
    return 0;
}

and build this with gcc (5.4.0) - I don't get any warnings, even if I compile with -Wall.

Now, I can circumvent this by writing

if (not (N < 10)) {
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

but I would rather avoid having to reverse my logic to jump through nvcc's "hoop". I could also write

if (not (N < 10)) {
    return;
}
else {
    printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
}

but - I don't want to indent all that code (and the same problem may occur again, requiring even more indentation inside the else block.

Is there something I could do? Also, isn't this a "bug", or a misfeature I should report as a bug?

Body:
What about:

template<unsigned N, bool>
struct FooImpl
{
  static void foo()
  {
    std::printf("In kernel foo() with N = %u\n", N);
  }
};

template<unsigned N>
struct FooImpl<N, false>
{
  static void foo()
  {
    std::printf("In kernel foo() with N = %u\n", N);
    std::printf("Wow, N is really high!\n");
    /* a whole lot of code here which I don't want to indent */
  }
};

template <unsigned N>
__global__ void foo()
{
  FooImpl<N, N < 10>::foo();
}


答:
Use Double.TryParse

Converts the string representation of a number to its double-precision
  floating-point number equivalent. A return value indicates whether the
  conversion succeeded or failed.

this way, you can get if the number is convertible before using it...

Title: Check if input is a string in C# after converting it to a double


问:
Lexing The VHDL ' (tick) Token
In VHDL it the ' character can be used to encapsulate a character token ie '.' or it can as an attribute separator (similarish to CPP's :: token) ie string'("hello").

The issue comes up when parsing an attribute name containing a character ie string'('a','b','c').  In this case a naive lexer will incorrectly tokenize the first '(' as a character, and all of the following actual character will be messed up.

There is a thread in comp.lang.vhdl google group from 2007 which asks a similar question
Titled "Lexing the ' char"  that has an answer by user diogratia

```<code>        case '\'':                          /* IR1045 check */

            if (    last_token == DELIM_RIGHT_PAREN ||
                    last_token == DELIM_RIGHT_BRACKET ||
                    last_token == KEYWD_ALL ||
                    last_token == IDENTIFIER_TOKEN ||
                    last_token == STR_LIT_TOKEN ||
                    last_token == CHAR_LIT_TOKEN || ! (buff_ptr<BUFSIZ-2) )
                token_flag = DELIM_APOSTROPHE;
            else if (is_graphic_char(NEXT_CHAR) &&
                    line_buff[buff_ptr+2] == '\'') { CHARACTER_LITERAL:
                buff_ptr+= 3;               /* lead,trailing \' and char */
                last_token = CHAR_LIT_TOKEN;
                token_strlen = 3;
                return (last_token);
            }
            else token_flag = DELIM_APOSTROPHE;
            break;
</code>```

See Issue Report IR1045:
  http://www.eda-twiki.org/isac/IRs-VHDL-93/IR1045.txt

As you can see from the above code fragment, the last token can be
  captured and used to di"sambiguate something like:

```<code>  foo <= std_logic_vector'('a','b','c');
</code>```

without a large look ahead or backtracking.

However, As far as I know, flex doesn't track the last token that was parsed.

Without having to manually keep track of the last parsed token, is there a better way to accomplish this lexing task?

I am using IntelliJ GrammarKit if that helps.

答:
The idea behind IR1045 is to be able to tell whether a single quote/apostrophe is part of a character literal or not without looking ahead or backtracking when you're wrong, try:

```<code>library ieee;
use ieee.std_logic_1164.all;

entity foo is
    port (
        a:      in      std_logic;
        b:      out     std_logic_vector (3 downto 0)
    );
end entity;

architecture behave of foo is
    begin
    b <= std_logic_vector'('0','1','1','0')     when a = '1' else
         (others =>'0')                         when a = '0' else
         (others => 'X');
end architecture behave;
</code>```

How far ahead are you willing to look?

There is however a practical example of flex disambiguation of apostrophes and character literals for VHDL.

Nick Gasson's nvc uses flex, in which he implemented an Issue Report 1045 solution.

See the nvc/src/lexer.l which is licensed under GPLv3.

Search for last_token:

```<code>#define TOKEN(t) return (last_token = (t))
</code>```

and

```<code>#define TOKEN_LRM(t, lrm)                                       \
   if (standard() < lrm) {                                      \
      warn_at(&yylloc, "%s is a reserved word in VHDL-%s",      \
              yytext, standard_text(lrm));                      \
      return parse_id(yytext);                                  \
   }                                                            \
   else                                                         \
      return (last_token = (t));
</code>```

An added function to check it:

```<code>static int resolve_ir1045(void);

static int last_token = -1;
</code>```

which is:

```<code>%%

static int resolve_ir1045(void)
{
   // See here for discussion:
   //   http://www.eda-stds.org/isac/IRs-VHDL-93/IR1045.txt
   // The set of tokens that may precede a character literal is
   // disjoint from that which may precede a single tick token.

   switch (last_token) {
   case tRSQUARE:
   case tRPAREN:
   case tALL:
   case tID:
      // Cannot be a character literal
      return 0;
   default:
      return 1;
   }
}
</code>```

The IR1045 location has changed since the comp.lang.vhdl post it's now

http://www.eda-twiki.org/isac/IRs-VHDL-93/IR1045.txt

You'll also want to search for resolve_ir1045 in lexer.l.

```<code>static int resolve_ir1045(void);
</code>```

and

```<code>{CHAR}            { if (resolve_ir1045()) {
                       yylval.s = strdup(yytext);
                       TOKEN(tID);
</code>```

Where we find nvc uses the function to filter detecting the first single quote of a character literal.

This was originally an Ada issue. IR-1045 was never adopted but universally used. There are probably Ada flex lexers that also demonstrate disambiguation.

The requirement to disambiguate is discussed in Ada User Journal volume 27 number 3 from September 2006 in an article Lexical Analysis on PDF pages 30 and 31 (Volume 27 pages 159 and 160) where we see the solution is not well known.

The comment that character literals do not precede a single quote is inaccurate:

```<code>entity ir1045 is
end entity;

architecture foo of ir1045 is
begin
THIS_PROCESS:
    process
        type twovalue is ('0', '1');
        subtype string4 is string(1 to 4);
        attribute a: string4;
        attribute a of '1' : literal is "TRUE";
    begin
        assert THIS_PROCESS.'1''a /= "TRUE"
            report "'1''a /= ""TRUE"" is FALSE";
        report "This_PROCESS.'1''a'RIGHT = " &
            integer'image(This_PROCESS.'1''a'RIGHT);
        wait;
    end process;
end architecture;
</code>```

The first use of an attribute with selected name prefix that has a suffix that is a character literal demonstrates the inaccuracy, the second report statement shows it can matter:

```<code>ghdl -a ir1045.vhdl
ghdl -e ir1045
ghdl -r ir1045
ir1045.vhdl:13:9:@0ms:(assertion error): '1''a /= "TRUE" is FALSE
ir1045.vhdl:15:9:@0ms:(report note): This_PROCESS.'1''a'RIGHT = 4
</code>```

In addition to an attribute name prefix containing a selected name with a character literal suffix there's a requirement that an attribute specification 'decorate' a declared entity (of an entity_class, see IEEE Std 1076-2008 7.2 Attribute specification) in the same declarative region the entity is declared in.

This example is syntactically and semantically valid VHDL. You could note that nvc doesn't allow decorating a named entity with the entity class literal. That's not according to 7.2.

Enumeration literals are declared in type declarations, here type twovalue. An enumerated type that has at least one character literal as an enumeration literal is a character type (5.2.2.1).

Title: Lexing The VHDL ' (tick) Token

Body:
In VHDL it the ' character can be used to encapsulate a character token ie '.' or it can as an attribute separator (similarish to CPP's :: token) ie string'("hello").

The issue comes up when parsing an attribute name containing a character ie string'('a','b','c').  In this case a naive lexer will incorrectly tokenize the first '(' as a character, and all of the following actual character will be messed up.

There is a thread in comp.lang.vhdl google group from 2007 which asks a similar question
Titled "Lexing the ' char"  that has an answer by user diogratia

        case '\'':                          /* IR1045 check */

            if (    last_token == DELIM_RIGHT_PAREN ||
                    last_token == DELIM_RIGHT_BRACKET ||
                    last_token == KEYWD_ALL ||
                    last_token == IDENTIFIER_TOKEN ||
                    last_token == STR_LIT_TOKEN ||
                    last_token == CHAR_LIT_TOKEN || ! (buff_ptr<BUFSIZ-2) )
                token_flag = DELIM_APOSTROPHE;
            else if (is_graphic_char(NEXT_CHAR) &&
                    line_buff[buff_ptr+2] == '\'') { CHARACTER_LITERAL:
                buff_ptr+= 3;               /* lead,trailing \' and char */
                last_token = CHAR_LIT_TOKEN;
                token_strlen = 3;
                return (last_token);
            }
            else token_flag = DELIM_APOSTROPHE;
            break;

See Issue Report IR1045:
  http://www.eda-twiki.org/isac/IRs-VHDL-93/IR1045.txt

As you can see from the above code fragment, the last token can be
  captured and used to di"sambiguate something like:

  foo <= std_logic_vector'('a','b','c');

without a large look ahead or backtracking.

However, As far as I know, flex doesn't track the last token that was parsed.

Without having to manually keep track of the last parsed token, is there a better way to accomplish this lexing task?

I am using IntelliJ GrammarKit if that helps.

Body:
The idea behind IR1045 is to be able to tell whether a single quote/apostrophe is part of a character literal or not without looking ahead or backtracking when you're wrong, try:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
    port (
        a:      in      std_logic;
        b:      out     std_logic_vector (3 downto 0)
    );
end entity;

architecture behave of foo is
    begin
    b <= std_logic_vector'('0','1','1','0')     when a = '1' else
         (others =>'0')                         when a = '0' else
         (others => 'X');
end architecture behave;

How far ahead are you willing to look?

There is however a practical example of flex disambiguation of apostrophes and character literals for VHDL.

Nick Gasson's nvc uses flex, in which he implemented an Issue Report 1045 solution.

See the nvc/src/lexer.l which is licensed under GPLv3.

Search for last_token:

#define TOKEN(t) return (last_token = (t))

and

#define TOKEN_LRM(t, lrm)                                       \
   if (standard() < lrm) {                                      \
      warn_at(&yylloc, "%s is a reserved word in VHDL-%s",      \
              yytext, standard_text(lrm));                      \
      return parse_id(yytext);                                  \
   }                                                            \
   else                                                         \
      return (last_token = (t));

An added function to check it:

static int resolve_ir1045(void);

static int last_token = -1;

which is:

%%

static int resolve_ir1045(void)
{
   // See here for discussion:
   //   http://www.eda-stds.org/isac/IRs-VHDL-93/IR1045.txt
   // The set of tokens that may precede a character literal is
   // disjoint from that which may precede a single tick token.

   switch (last_token) {
   case tRSQUARE:
   case tRPAREN:
   case tALL:
   case tID:
      // Cannot be a character literal
      return 0;
   default:
      return 1;
   }
}

The IR1045 location has changed since the comp.lang.vhdl post it's now

http://www.eda-twiki.org/isac/IRs-VHDL-93/IR1045.txt

You'll also want to search for resolve_ir1045 in lexer.l.

static int resolve_ir1045(void);

and

{CHAR}            { if (resolve_ir1045()) {
                       yylval.s = strdup(yytext);
                       TOKEN(tID);

Where we find nvc uses the function to filter detecting the first single quote of a character literal.

This was originally an Ada issue. IR-1045 was never adopted but universally used. There are probably Ada flex lexers that also demonstrate disambiguation.

The requirement to disambiguate is discussed in Ada User Journal volume 27 number 3 from September 2006 in an article Lexical Analysis on PDF pages 30 and 31 (Volume 27 pages 159 and 160) where we see the solution is not well known.

The comment that character literals do not precede a single quote is inaccurate:

entity ir1045 is
end entity;

architecture foo of ir1045 is
begin
THIS_PROCESS:
    process
        type twovalue is ('0', '1');
        subtype string4 is string(1 to 4);
        attribute a: string4;
        attribute a of '1' : literal is "TRUE";
    begin
        assert THIS_PROCESS.'1''a /= "TRUE"
            report "'1''a /= ""TRUE"" is FALSE";
        report "This_PROCESS.'1''a'RIGHT = " &
            integer'image(This_PROCESS.'1''a'RIGHT);
        wait;
    end process;
end architecture;

The first use of an attribute with selected name prefix that has a suffix that is a character literal demonstrates the inaccuracy, the second report statement shows it can matter:

ghdl -a ir1045.vhdl
ghdl -e ir1045
ghdl -r ir1045
ir1045.vhdl:13:9:@0ms:(assertion error): '1''a /= "TRUE" is FALSE
ir1045.vhdl:15:9:@0ms:(report note): This_PROCESS.'1''a'RIGHT = 4

In addition to an attribute name prefix containing a selected name with a character literal suffix there's a requirement that an attribute specification 'decorate' a declared entity (of an entity_class, see IEEE Std 1076-2008 7.2 Attribute specification) in the same declarative region the entity is declared in.

This example is syntactically and semantically valid VHDL. You could note that nvc doesn't allow decorating a named entity with the entity class literal. That's not according to 7.2.

Enumeration literals are declared in type declarations, here type twovalue. An enumerated type that has at least one character literal as an enumeration literal is a character type (5.2.2.1).


答:
You can use NOT IN to exclude those sec which have one or more row with marks not fully divisible by 10:

```<code>select *
from students
where sec not in (
        select sec
        from students
        where marks % 10 <> 0
        );
</code>```

Title: select section name where marks of every student rounded to 10

Body:
You can use NOT IN to exclude those sec which have one or more row with marks not fully divisible by 10:

select *
from students
where sec not in (
        select sec
        from students
        where marks % 10 <> 0
        );


问:
No connected between view and controller
I'm a newbie and I tried finding a solution of this error message:

"The model item passed into the
  dictionary is of type
  'NerdDinner.Controllers.DinnerFormViewModel',
  but this dictionary requires a model
  item of type
  'NerdDinner.Models.Dinner'"

There are similiar problem error but not the same context problem.
I believe that the problem is located in the edit.aspx and still i can't solve it.

DinnersController:

```<code>//
// GET: /Dinners/Create

public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View(new DinnerFormViewModel(dinner));
}
</code>```

Models:

```<code>namespace NerdDinner.Models
{
    [MetadataType(typeof(Dinner_Validation))]
    public partial class Dinner
    {

    }

    public class Dinner_Validation
    {
        [Required(ErrorMessage = "Title is required")]
        [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(265, ErrorMessage =
          "Description must be 256 characters or less")]
        public string Description { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone# is required")]
        public string ContactPhone { get; set; }
    }
}

namespace NerdDinner.Controllers
{
    public class DinnerFormViewModel
    {

        private static string[] _countries = new[]
        {
            "USA",
            "Afghanistan",
            "Akrotiri",
            "Albania",
            //... omitted for brevity
            "Zimbabwe"
        };

        // Properties
        public Dinner Dinner { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DinnerFormViewModel(Dinner dinner)
        {
            Dinner = dinner;

            Countries = new SelectList(_countries, dinner.Country);
        }
    }
}
</code>```

Edit.aspx:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>

<asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
   Edit: <%: Model.Dinner.Title %>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">

   <h2>Edit Dinner</h2>
   <% using (Html.BeginForm()) { %>
       <%: Html.ValidationSummary("Please correct the errors and try again.") %>
       <fieldset>
          <legend>Fields</legend>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Title) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Title)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Title, "*")%>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.EventDate) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.EventDate)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.EventDate, "*")%>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Description) %>
           </div>
           <div class="editor-field">
               <%: Html.TextAreaFor(m => m.Dinner.Description) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Description, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Address) %>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Address) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Address, "*") %>
           </div>
<%: Html.LabelFor(m => m.Dinner.Country) %>
<%: Html.DropDownListFor(m => m.Dinner.Country, Model.Countries) %>
<%: Html.ValidationMessageFor(m => m.Dinner.Country, "*") %>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.ContactPhone)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.ContactPhone)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.ContactPhone, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Latitude)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Latitude)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.Latitude, "*") %>
           </div>
           <div class="editor-label">
               <%: Html.LabelFor(m => m.Dinner.Longitude)%>
           </div>
           <div class="editor-field">
               <%: Html.TextBoxFor(m => m.Dinner.Longitude)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Longitude, "*")%>
           </div>
           <p>
               <input type="submit" value="Save" />
           </p>
       </fieldset>

   <% } %>

</asp:Content>
</code>```

答:
Add the correct name of the view to the ViewResult.</p>

```<code>public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View("Edit", new DinnerFormViewModel(dinner));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm a newbie and I tried finding a solution of this error message:

"The model item passed into the
  dictionary is of type
  'NerdDinner.Controllers.DinnerFormViewModel',
  but this dictionary requires a model
  item of type
  'NerdDinner.Models.Dinner'"

There are similiar problem error but not the same context problem.
I believe that the problem is located in the edit.aspx and still i can't solve it.

DinnersController:

//
// GET: /Dinners/Create

public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View(new DinnerFormViewModel(dinner));
}

Models:

namespace NerdDinner.Models
{
    [MetadataType(typeof(Dinner_Validation))]
    public partial class Dinner
    {

    }

    public class Dinner_Validation
    {
        [Required(ErrorMessage = "Title is required")]
        [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(265, ErrorMessage =
          "Description must be 256 characters or less")]
        public string Description { get; set; }

        [Required(ErrorMessage = "Address is required")]
        public string Address { get; set; }

        [Required(ErrorMessage = "Country is required")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone# is required")]
        public string ContactPhone { get; set; }
    }
}

namespace NerdDinner.Controllers
{
    public class DinnerFormViewModel
    {

        private static string[] _countries = new[]
        {
            "USA",
            "Afghanistan",
            "Akrotiri",
            "Albania",
            //... omitted for brevity
            "Zimbabwe"
        };

        // Properties
        public Dinner Dinner { get; private set; }
        public SelectList Countries { get; private set; }

        // Constructor
        public DinnerFormViewModel(Dinner dinner)
        {
            Dinner = dinner;

            Countries = new SelectList(_countries, dinner.Country);
        }
    }
}

Edit.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Controllers.DinnerFormViewModel>" %>

<asp:Content ID="Title" ContentPlaceHolderID="TitleContent" runat="server">
   Edit: <%: Model.Dinner.Title %>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="MainContent" runat="server">

Edit Dinner

   <% using (Html.BeginForm()) { %>
       <%: Html.ValidationSummary("Please correct the errors and try again.") %>
       <fieldset>
          <legend>Fields</legend>

               <%: Html.LabelFor(m => m.Dinner.Title) %>

               <%: Html.TextBoxFor(m => m.Dinner.Title)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Title, "*")%>

               <%: Html.LabelFor(m => m.Dinner.EventDate) %>

               <%: Html.TextBoxFor(m => m.Dinner.EventDate)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.EventDate, "*")%>

               <%: Html.LabelFor(m => m.Dinner.Description) %>

               <%: Html.TextAreaFor(m => m.Dinner.Description) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Description, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Address) %>

               <%: Html.TextBoxFor(m => m.Dinner.Address) %>
               <%: Html.ValidationMessageFor(m => m.Dinner.Address, "*") %>

<%: Html.LabelFor(m => m.Dinner.Country) %>
<%: Html.DropDownListFor(m => m.Dinner.Country, Model.Countries) %>
<%: Html.ValidationMessageFor(m => m.Dinner.Country, "*") %>

               <%: Html.LabelFor(m => m.Dinner.ContactPhone)%>

               <%: Html.TextBoxFor(m => m.Dinner.ContactPhone)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.ContactPhone, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Latitude)%>

               <%: Html.TextBoxFor(m => m.Dinner.Latitude)%>
               <%: Html.ValidationMessageFor(m => Model.Dinner.Latitude, "*") %>

               <%: Html.LabelFor(m => m.Dinner.Longitude)%>

               <%: Html.TextBoxFor(m => m.Dinner.Longitude)%>
               <%: Html.ValidationMessageFor(m => m.Dinner.Longitude, "*")%>

               <input type="submit" value="Save" />

       </fieldset>

   <% } %>

</asp:Content>

Body:
Add the correct name of the view to the ViewResult.

public ActionResult Create()
{

    Dinner dinner = new Dinner()
    {
        EventDate = DateTime.Now.AddDays(7)
    };

    return View("Edit", new DinnerFormViewModel(dinner));
}


问:
How to code it in R that count the probability of succeed once at most in 10times at a Bernoulli which P=0.1
Count the probability of succeed once at most in 10 times at a Bernoulli which P=0.1 I've tried by myself:

```<code>pbinom(0,10,.1)
</code>```

I don't know it is right or not, as I don't know if "at most" here is the same the "at least".

答:
Having at most one success means that you can have either zero success or one success.

If X is the number of successes, then the probability of having at most 1 success is p(X<=1)=p(X=0)+p(X=1).

In R, the function giving the probability p(X=x) is the density function dbinom.

So you want to do dbinom(0,10,0.1)+dbinom(1,10,0.1)

Body:
Count the probability of succeed once at most in 10 times at a Bernoulli which P=0.1 I've tried by myself:

pbinom(0,10,.1)

I don't know it is right or not, as I don't know if "at most" here is the same the "at least".


问:
Trying to create a JSONObject ends with a Cannot evaluate org.json.JSONObject.toString()
I've been following a tutorial (honestly, I was copy pasting, therefore I don't know why it doesn't work as I didn't change a thing) and I have this String response that I need to convert into a Json Object.

response =

Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}

Right after the try at JSONObject jObj = new JSONObject(response); my program jumps to the exception with a message:

Method threw 'java.lang.NullPointerException' exception. Cannot
  evaluate org.json.JSONObject.toString()

Is it the structure of response or something?

Here's where I use it:

```<code>@Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String surname = user.getString("surname");
                        String address = user.getString("address");
                        String email = user.getString("email");

                        // Inserting row in users table
                        db.addUser(name, surname, address, email);

                        // Launch main activity
                        Intent intent = new Intent(LoginScreen.this,
                                MainMenu.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
</code>```

答: Remove the Config.php\r\n prefix from the response before turning it into a JSON object.

Body:
I've been following a tutorial (honestly, I was copy pasting, therefore I don't know why it doesn't work as I didn't change a thing) and I have this String response that I need to convert into a Json Object.

response =

Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}

Right after the try at JSONObject jObj = new JSONObject(response); my program jumps to the exception with a message:

Method threw 'java.lang.NullPointerException' exception. Cannot
  evaluate org.json.JSONObject.toString()

Is it the structure of response or something?

Here's where I use it:

@Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String surname = user.getString("surname");
                        String address = user.getString("address");
                        String email = user.getString("email");

                        // Inserting row in users table
                        db.addUser(name, surname, address, email);

                        // Launch main activity
                        Intent intent = new Intent(LoginScreen.this,
                                MainMenu.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }

ContentLicense: CC BY-SA 4.0


问:
How to define c3p0 properties in the application.properties file of Spring
I want to define c3p0 properties in the application.properties file. But c3p0 properties seem not to be recognised. What goes wrong? Is there an example of an application.properties file with c3p0 settings?</p>

```<code>spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:jtds:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}?autoReconnect=true
spring.datasource.username=${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password=${OPENSHIFT_MYSQL_DB_PASSWORD}
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
c3p0.properties.driverClassName=com.mysql.jdbc.Driver
c3p0.properties.url=jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}?autoReconnect=true
c3p0.properties.username=${OPENSHIFT_MYSQL_DB_USERNAME}
c3p0.properties.password=${OPENSHIFT_MYSQL_DB_PASSWORD}
c3p0.properties.acquire_increment=1
c3p0.properties.idle_test_period
c3p0.properties.timeout=14400
c3p0.properties.max_size=20
c3p0.properties.max_statements=50
c3p0.properties.min_size=3
</code>```

答:
Just in case someone is still interested...

It doesn't work with application.properties. Adding c3p0.properties file works.

Example of c3p0.properties:

```<code>c3p0.maxStatements=50
c3p0.acquireRetryDelay=3000
</code>```

And in application.properties you need to specify data source type you want to use:

```<code>spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource
</code>```

Body:
I want to define c3p0 properties in the application.properties file. But c3p0 properties seem not to be recognised. What goes wrong? Is there an example of an application.properties file with c3p0 settings?

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:jtds:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}?autoReconnect=true
spring.datasource.username=${OPENSHIFT_MYSQL_DB_USERNAME}
spring.datasource.password=${OPENSHIFT_MYSQL_DB_PASSWORD}
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider
c3p0.properties.driverClassName=com.mysql.jdbc.Driver
c3p0.properties.url=jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}?autoReconnect=true
c3p0.properties.username=${OPENSHIFT_MYSQL_DB_USERNAME}
c3p0.properties.password=${OPENSHIFT_MYSQL_DB_PASSWORD}
c3p0.properties.acquire_increment=1
c3p0.properties.idle_test_period
c3p0.properties.timeout=14400
c3p0.properties.max_size=20
c3p0.properties.max_statements=50
c3p0.properties.min_size=3

Body:
Just in case someone is still interested...

It doesn't work with application.properties. Adding c3p0.properties file works.

Example of c3p0.properties:

c3p0.maxStatements=50
c3p0.acquireRetryDelay=3000

And in application.properties you need to specify data source type you want to use:

spring.datasource.type=com.mchange.v2.c3p0.ComboPooledDataSource


问:
c# how to get just date from sql server date column and display in textbox
when i get the date from the selected row and send to a text box in a different form it shows as 04/01/2017 00:00:00 but i just want the date.
this is how i select the row and get the date from the table.

```<code>public static string Dedob;

private void dgvEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dgvEmployee.Rows[e.RowIndex];
        Dename = row.Cells["Name"].Value.ToString();
        Dedob =  row.Cells["DOB"].Value.ToString();
        Deaddress = row.Cells["ADDRESS"].Value.ToString();
        Deusername = row.Cells["USERNAME"].Value.ToString();
    }
}
</code>```

then on form2

```<code>tbdob.Text = form1.Dedob;
</code>```

then the textbox just shows 04/01/2017 00:00:00 how can i remove the time :/

any help would be appreciated.

答:
DateTime.ToShortDateString() works too.

((DateTime)row.Cells["DOB"].Value).ToShortDateString();

Body:
when i get the date from the selected row and send to a text box in a different form it shows as 04/01/2017 00:00:00 but i just want the date.
this is how i select the row and get the date from the table.

public static string Dedob;

private void dgvEmployee_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DataGridViewRow row = this.dgvEmployee.Rows[e.RowIndex];
        Dename = row.Cells["Name"].Value.ToString();
        Dedob =  row.Cells["DOB"].Value.ToString();
        Deaddress = row.Cells["ADDRESS"].Value.ToString();
        Deusername = row.Cells["USERNAME"].Value.ToString();
    }
}

then on form2

tbdob.Text = form1.Dedob;

then the textbox just shows 04/01/2017 00:00:00 how can i remove the time :/

any help would be appreciated.


问:
Which OpenGL version is the first to support Uniform Array of Structures?
I would like to use a Light struct in glsl, and define an array of them as a uniform variable like this:

```<code>uniform Light lights[LIGHT_NUM];
</code>```

Unfortunately I was not able to find, which OpenGL/glsl/GL ES version do I need, to use this feature.

答: All of them. There is no version of GLSL, even 1.10 back from the GL 2.0 days, which does not support uniforms that are declared as structures and/or arrays. So long as LIGHT_NUM is a constant expression, and that the uniform is not too big for the implementation, then that will work in any version of GLSL.

Body:
I would like to use a Light struct in glsl, and define an array of them as a uniform variable like this:

uniform Light lights[LIGHT_NUM];

Unfortunately I was not able to find, which OpenGL/glsl/GL ES version do I need, to use this feature.


问:
CMake and slow MSVC compilation

CMake generate project for MSVC 10 (2010) and build time are relativly low, ie. after I click build for given project it start compiling in like seconds, which is expected.

For Qt Creator I choose CodeBlocks - NMake Makefiles as CMake generator, set build configuration to use the same target as above. When I click build I see

cmake --build . --target name

and silence for like 2 minutes. Then
Scanning dependencies for ...
 and 1,5 minutes more of silence.
To make things even worse - later compilation use only 1 thread. So compilation time is ... unacceptably long.

How should I configure project to achieve comparable, short compilation times as from under MSVC? I've tried Qt Creator 4.3 Beta and beside

答:
NMake and NMake JOM  are slow.
When I change to Ninja build system - compilation times are similar to those inside MSVC.</p>

Title: CMake and slow MSVC compilation


问:
PHP--How do I put form information into an HTML table once it has been saved to a text file?
This is just a block of code I am struggling with. Not sure if I am correct while trying to get this to format into an HTML table. I've messed with this for the last two hours trying to get it to work, I still don't have a clue what I am doing wrong. I am trying to get the information that comes from my array posted into the HTML table. </p>

```<code>$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');

echo "<table border='1'>";

$count1=0;
foreach ($ExistingSig as $key => $value)
  {
  echo "<tr>";
  if(!is_array($value))
   {
       if($key == 'Name' or $key == 'Version' or $key == 'Hardware' or $key == 'System' or $key == 'Frequency' or $key == 'Solution')
    {
        echo "<td>";
        echo  $key . ':' . $value;
        echo "<br />\n";
        echo "</td>";
    }
   }

  $count2=0;
   foreach ($ExistingSig as $key => $value)
    {
   if($count1==$count2){
     //to eliminate array to string conversion error
     if(!is_array($value))
     {
         if($key == '$AddName' or $key == '$AddVer' or $key == '$AddHard' or $key == '$AddSys' or $key == '$AddFreq' or $key == '$AddSol')
         {
             echo "<td>";
             echo  $key . ':' . $value;
             echo "<br />\n";
             echo "</td>";
         }
     }
      }
      $count2++;
   }
    echo "</tr>";
      $count1++;
  }
echo "</table>";
</code>```

答:
See if this works for you</p>

```<code><?php

$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');

$wantedKeys = array('Name','Version','Hardware','System','Frequency', 'Solution');

$thead = "<thead>";
$tbody="<tbody>";
    foreach ($ExistingSig as $key => $value){
        if(in_array($key,$wantedKeys)){
            $thead .= "<th>$key</th>";
            $tbody .= "<td>$value</td>";
        }
    }

echo "<table border='1'>$thead</thead>$tbody</tbody></table>";
?>
</code>```

Body:
This is just a block of code I am struggling with. Not sure if I am correct while trying to get this to format into an HTML table. I've messed with this for the last two hours trying to get it to work, I still don't have a clue what I am doing wrong. I am trying to get the information that comes from my array posted into the HTML table.

$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');

echo "
";

$count1=0;
foreach ($ExistingSig as $key => $value)
  {
  echo "
";
  if(!is_array($value))
   {
       if($key == 'Name' or $key == 'Version' or $key == 'Hardware' or $key == 'System' or $key == 'Frequency' or $key == 'Solution')
    {
        echo "";
        echo  $key . ':' . $value;
        echo "
\n";
        echo "	";
    }
   }

  $count2=0;
   foreach ($ExistingSig as $key => $value)
    {
   if($count1==$count2){
     //to eliminate array to string conversion error
     if(!is_array($value))
     {
         if($key == '$AddName' or $key == '$AddVer' or $key == '$AddHard' or $key == '$AddSys' or $key == '$AddFreq' or $key == '$AddSol')
         {
             echo "";
             echo  $key . ':' . $value;
             echo "
\n";
             echo "	";
         }
     }
      }
      $count2++;
   }
    echo "
";
      $count1++;
  }
echo "
";

Body:
See if this works for you

<?php

$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');

$wantedKeys = array('Name','Version','Hardware','System','Frequency', 'Solution');

$thead = "<thead>";
$tbody="<tbody>";
    foreach ($ExistingSig as $key => $value){
        if(in_array($key,$wantedKeys)){
            $thead .= "<th>$key</th>";
            $tbody .= "<td>$value</td>";
        }
    }

echo "<table border='1'>$thead</thead>$tbody</tbody></table>";
?>


问:
how to insert text at any cursor position in uitextview?
i want to implement Code by which i can start to insert text at any position of cursor in UITextView in iphone sdk

any idea?
thank you in advance..

i refereed this link: iPhone SDK: How to create a UITextView that inserts text where you tap?

But not Getting it.

答:
Here is the Glorfindel's answer in Swift3. The text its inserting here it pulls out of the clipboard.</p>

```<code>if let textRange = myTextView.selectedTextRange {
   myTextView.replace(textRange, withText:UIPasteboard.general.string!)
}
</code>```

Body:
Here is the Glorfindel's answer in Swift3. The text its inserting here it pulls out of the clipboard.

if let textRange = myTextView.selectedTextRange {
   myTextView.replace(textRange, withText:UIPasteboard.general.string!)
}


问:
How can I tell a control to NOT redraw itself?
I've tried something like:

```<code>horizontalPictureScroller1.SuspendLayout();
horizontalPictureScroller1.DeleteSelectedImages();
horizontalPictureScroller1.ResumeLayout();
</code>```

But it's still lagging visually when I run the DeleteSelectedImages() method.

Is there some way to manually tell a control to NOT redraw itself until I tell it to start drawing itself again?

Using Windows Forms and .NET 4

答:
I suppose that your problem is that your screen updates during the delete operation resulting in flickering.

The SuspendLayout and ResumeLayour methods only suspend the layout of the control. It does not stop the control from redrawing or resizing.

You should enable DoubleBuffering on the control.

You should create a new control class derived from the WinForms control you are using here. In the constructor of this class enable the double buffering using SetStyle method.

Assuming that your control horizontalPictureScroller1 is a PictureBox -

```<code>class MyControl : System.Windows.Forms.PictureBox
    {
        public MyControl()
        {
            this.SetStyle(ControlStyles.DoubleBuffer |
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint,
                true);
        }
    }
</code>```

OwnerDisplayName: delete

Body:
I've tried something like:

horizontalPictureScroller1.SuspendLayout();
horizontalPictureScroller1.DeleteSelectedImages();
horizontalPictureScroller1.ResumeLayout();

But it's still lagging visually when I run the DeleteSelectedImages() method.

Is there some way to manually tell a control to NOT redraw itself until I tell it to start drawing itself again?

Using Windows Forms and .NET 4

Body:
I suppose that your problem is that your screen updates during the delete operation resulting in flickering.

The SuspendLayout and ResumeLayour methods only suspend the layout of the control. It does not stop the control from redrawing or resizing.

You should enable DoubleBuffering on the control.

You should create a new control class derived from the WinForms control you are using here. In the constructor of this class enable the double buffering using SetStyle method.

Assuming that your control horizontalPictureScroller1 is a PictureBox -

class MyControl : System.Windows.Forms.PictureBox
    {
        public MyControl()
        {
            this.SetStyle(ControlStyles.DoubleBuffer |
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint,
                true);
        }
    }


问:
UML Activity Diagram :loop on decision node
I am learning UML and I would like to know if it is possible to loop on the decision node.
Because in my cockburn I have :

3-Enter with ticket

3a1-Enter with card
3a2-Failure: return to 1

If it is possible, how can I do it with Visual Paradigm?
Thanks!

答: I assume you're asking if it's possible to loop from a decision back to itself. Doing so would create an infinite loop. The reason is that the guard condition would never have a chance to change, so the token would cycle forever.</p>


问:
Event tracking in Contact Form 7
I have a WordPress website that uses Contact Form 7 and MonsterInsights for Google Analytics tracking. I want to track a contact form submission in Google Analytics as an event using the Universal code. I believe that I have correctly set up the event tracking code based on a review of the following sites:

https://www.kathirvel.com/universal-analytics-track-wordpress-contact-form-7-submission/
http://contactform7.com/tracking-form-submissions-with-google-analytics/

My code in my Additional Settings for the plugin reads:

```<code>on_sent_ok: "__gaTracker('send', 'event', 'Contact Form', 'Submit');"
</code>```

Note that MonsterInsights uses __gaTracker. When I use the Chrome Tag Assistant to inspect what happens when I submit a form, it appears that the event is correctly tracked:

```<code>https://www.google-analytics.com/collect?v=1&_v=j47&a=1517116654&t=event&_s=2&dl=http://www.EXAMPLE.com/contact/&ul=en-us&de=UTF-8&dt=Contact Us&sd=24-bit&sr=1366x768&vp=1349x662&je=0&fl=23.0 r0&ec=Contact Form&ea=Submit&_u=SACAAUABK~&jid=&cid=1111924964.1481473656&tid=UA-CODE-1&z=1891409473
 Hostname   www.google-analytics.com
Protocol    https
Path    /collect
Hash
 v  1
_v  j47
a   1517116654
t   event
_s  2
dl  http://www.EXAMPLE.com/contact/
ul  en-us
de  UTF-8
dt  Contact Us
sd  24-bit
sr  1366x768
vp  1349x662
je  0
fl  23.0 r0
ec  Contact Form
ea  Submit
_u  SACAAUABK~
jid
cid 1111924964.1481473656
tid UA-CODE-1
z   1891409473
</code>```

However, Google Analytics is not showing any events either under Real Time or Behavior.

I have reviewed the following but not found a solution:
Tracking in Universal Analytics - Contact form 7
JavaScript in Contact Form 7
Tracking in Universal Analytics - Contact form 7

Thanks in advance for your help.

答:
I struggled with this for a couple of hours, same issue as you have.

Finally what worked for me was simple.

You have to match GA 'Category' and CF7 'Title'.

Screenshot:
https://digitalfactory.gr/wp-content/uploads/2017/04/contact_form7_ga.png

Title: Event tracking in Contact Form 7

Body:
I have a WordPress website that uses Contact Form 7 and MonsterInsights for Google Analytics tracking. I want to track a contact form submission in Google Analytics as an event using the Universal code. I believe that I have correctly set up the event tracking code based on a review of the following sites:

https://www.kathirvel.com/universal-analytics-track-wordpress-contact-form-7-submission/
http://contactform7.com/tracking-form-submissions-with-google-analytics/

My code in my Additional Settings for the plugin reads:

on_sent_ok: "__gaTracker('send', 'event', 'Contact Form', 'Submit');"

Note that MonsterInsights uses __gaTracker. When I use the Chrome Tag Assistant to inspect what happens when I submit a form, it appears that the event is correctly tracked:

https://www.google-analytics.com/collect?v=1&_v=j47&a=1517116654&t=event&_s=2&dl=http://www.EXAMPLE.com/contact/&ul=en-us&de=UTF-8&dt=Contact Us&sd=24-bit&sr=1366x768&vp=1349x662&je=0&fl=23.0 r0&ec=Contact Form&ea=Submit&_u=SACAAUABK~&jid=&cid=1111924964.1481473656&tid=UA-CODE-1&z=1891409473
 Hostname   www.google-analytics.com
Protocol    https
Path    /collect
Hash
 v  1
_v  j47
a   1517116654
t   event
_s  2
dl  http://www.EXAMPLE.com/contact/
ul  en-us
de  UTF-8
dt  Contact Us
sd  24-bit
sr  1366x768
vp  1349x662
je  0
fl  23.0 r0
ec  Contact Form
ea  Submit
_u  SACAAUABK~
jid
cid 1111924964.1481473656
tid UA-CODE-1
z   1891409473

However, Google Analytics is not showing any events either under Real Time or Behavior.

I have reviewed the following but not found a solution:
Tracking in Universal Analytics - Contact form 7
JavaScript in Contact Form 7
Tracking in Universal Analytics - Contact form 7

Thanks in advance for your help.


问:
Multicast delegate C#
Am studying about delegates. As I read. I learned that adding more than one function in a delegate is called multicast delegate. Based on that I wrote a program. Here two functions (AddNumbers and MultiplyNumbers) I added in the MyDelegate.
Is the below program is an example for multicast delegate ?. </p>

```<code>public partial class MainPage : PhoneApplicationPage
{
    public delegate void MyDelegate(int a, int b);
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        MyDelegate myDel = new MyDelegate(AddNumbers);
        myDel += new MyDelegate(MultiplyNumbers);
        myDel(10, 20);
    }

    public void AddNumbers(int x, int y)
    {
        int sum = x + y;
        MessageBox.Show(sum.ToString());
    }

    public void MultiplyNumbers(int x, int y)
    {
        int mul = x * y;
        MessageBox.Show(mul.ToString());
    }

}
</code>```

答:
Multicast delegates is one of the feature of delegates, it wraps the reference of multiple methods and calls it sequentially and it is also known as Delegate Chaining.

Below is the example of multicast delegates.

```<code>    // Declare Delegates
public delegate void MultiCast(int num1, int num2);

class Program
{
    public void Add(int num1, int num2)
    {
        Console.WriteLine(num1 + num2);
    }
    public  void Sub(int num1, int num2)
    {
        Console.WriteLine(num1 - num2);
    }
    public  void Mul(int num1, int num2)
    {
        Console.WriteLine(num1 * num2);
    }

    static void Main(string[] args)
    {
        MultiCast del1, del2, del3, multAddDel, multSubDel;
        del1 = new Program().Add;
        del2 = new Program().Sub;
        del3 = new Program().Mul;

    //`There are three ways to define the multicast delegate.`

        //1 way

        //Adding delegates
        multAddDel = del1 + del2 + del3;
        multAddDel(10, 10);
        //Removing Delegates
        multSubDel = multAddDel - del3;
        multSubDel(10, 10);

        Console.WriteLine();
        Console.WriteLine("Second Way");

        //2 way

        MultiCast multAddDel1 = null;
        //Adding delegates
        multAddDel1 += del1;
        multAddDel1 += del2;
        multAddDel1 +=  del3;
        multAddDel1(10, 10);
        //Removing Delegates
        multAddDel1 -= del3;
        multAddDel1(10, 10);

        Console.WriteLine();
        Console.WriteLine("Third Way");

        //3 way

        MultiCast multAddDel2 = null;
        //Adding delegates
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del1);
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del2);
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del3);
        multAddDel2(10, 10);

        //Removing Delegates
        multAddDel2 = (MultiCast)
            Delegate.Remove(multAddDel2, del3);

        multAddDel2(10, 10);
        Console.ReadLine();
    }
}
</code>```

Title: Multicast delegate C#

Body:
Am studying about delegates. As I read. I learned that adding more than one function in a delegate is called multicast delegate. Based on that I wrote a program. Here two functions (AddNumbers and MultiplyNumbers) I added in the MyDelegate.
Is the below program is an example for multicast delegate ?.

public partial class MainPage : PhoneApplicationPage
{
    public delegate void MyDelegate(int a, int b);
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        MyDelegate myDel = new MyDelegate(AddNumbers);
        myDel += new MyDelegate(MultiplyNumbers);
        myDel(10, 20);
    }

    public void AddNumbers(int x, int y)
    {
        int sum = x + y;
        MessageBox.Show(sum.ToString());
    }

    public void MultiplyNumbers(int x, int y)
    {
        int mul = x * y;
        MessageBox.Show(mul.ToString());
    }

}

Body:
Multicast delegates is one of the feature of delegates, it wraps the reference of multiple methods and calls it sequentially and it is also known as Delegate Chaining.

Below is the example of multicast delegates.

    // Declare Delegates
public delegate void MultiCast(int num1, int num2);

class Program
{
    public void Add(int num1, int num2)
    {
        Console.WriteLine(num1 + num2);
    }
    public  void Sub(int num1, int num2)
    {
        Console.WriteLine(num1 - num2);
    }
    public  void Mul(int num1, int num2)
    {
        Console.WriteLine(num1 * num2);
    }

    static void Main(string[] args)
    {
        MultiCast del1, del2, del3, multAddDel, multSubDel;
        del1 = new Program().Add;
        del2 = new Program().Sub;
        del3 = new Program().Mul;

    //`There are three ways to define the multicast delegate.`

        //1 way

        //Adding delegates
        multAddDel = del1 + del2 + del3;
        multAddDel(10, 10);
        //Removing Delegates
        multSubDel = multAddDel - del3;
        multSubDel(10, 10);

        Console.WriteLine();
        Console.WriteLine("Second Way");

        //2 way

        MultiCast multAddDel1 = null;
        //Adding delegates
        multAddDel1 += del1;
        multAddDel1 += del2;
        multAddDel1 +=  del3;
        multAddDel1(10, 10);
        //Removing Delegates
        multAddDel1 -= del3;
        multAddDel1(10, 10);

        Console.WriteLine();
        Console.WriteLine("Third Way");

        //3 way

        MultiCast multAddDel2 = null;
        //Adding delegates
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del1);
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del2);
        multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del3);
        multAddDel2(10, 10);

        //Removing Delegates
        multAddDel2 = (MultiCast)
            Delegate.Remove(multAddDel2, del3);

        multAddDel2(10, 10);
        Console.ReadLine();
    }
}


问:
How can I get the list of function calls that are performed in each function of a program, from the intermediate representation of LLVM?
I am trying to build a simple version of a code analysis tool with LLVM.

I have a few .ll files which contain the intermediate LLVM representation of certain programs.

How can I get the list of function calls that are performed in each function of a program, from the intermediate representation of LLVM?

The input parameter I have is an instance of the LLVM: Module class which represents the program. Then, I get the list of functions present in the program with the function getFunctionList ().

```<code>void getFunctionCalls(const Module *M)
{

  // Iterate functions in program
  for (auto curFref = M->getFunctionList().begin(), endFref = M->getFunctionList().end();
 curFref != endFref; ++curFref) {

        // For each function
        // Get list of function calls

  }

}
</code>```

答:
This is a fragment from our working code here:

```<code>for (auto &module : Ctx.getModules()) {
  auto &functionList = module->getModule()->getFunctionList();
  for (auto &function : functionList) {
    for (auto &bb : function) {
      for (auto &instruction : bb) {
        if (CallInst *callInst = dyn_cast<CallInst>(&instruction)) {
          if (Function *calledFunction = callInst->getCalledFunction()) {
            if (calledFunction->getName().startswith("llvm.dbg.declare")) {
</code>```

Also keep in mind that there are also invoke instructions InvokeInst which may be obtained in a similar way.

Google CallInst vs InvokeInst and also learn about the functions with or without a called function. If a function does not have a called function this is indirect call. Indirect calls appear in LLVM IR when the source code instead of calling a function directly, calls a function pointer. In C++ this often happens when some class operates through an abstract interface (polymorphism). So keep in mind that it is not 100% always possible to trace a called function even though you have a call instruction in place.

Body:
I am trying to build a simple version of a code analysis tool with LLVM.

I have a few .ll files which contain the intermediate LLVM representation of certain programs.

How can I get the list of function calls that are performed in each function of a program, from the intermediate representation of LLVM?

The input parameter I have is an instance of the LLVM: Module class which represents the program. Then, I get the list of functions present in the program with the function getFunctionList ().

void getFunctionCalls(const Module *M)
{

  // Iterate functions in program
  for (auto curFref = M->getFunctionList().begin(), endFref = M->getFunctionList().end();
 curFref != endFref; ++curFref) {

        // For each function
        // Get list of function calls

  }

}

Body:
This is a fragment from our working code here:

for (auto &module : Ctx.getModules()) {
  auto &functionList = module->getModule()->getFunctionList();
  for (auto &function : functionList) {
    for (auto &bb : function) {
      for (auto &instruction : bb) {
        if (CallInst *callInst = dyn_cast<CallInst>(&instruction)) {
          if (Function *calledFunction = callInst->getCalledFunction()) {
            if (calledFunction->getName().startswith("llvm.dbg.declare")) {

Also keep in mind that there are also invoke instructions InvokeInst which may be obtained in a similar way.

Google CallInst vs InvokeInst and also learn about the functions with or without a called function. If a function does not have a called function this is indirect call. Indirect calls appear in LLVM IR when the source code instead of calling a function directly, calls a function pointer. In C++ this often happens when some class operates through an abstract interface (polymorphism). So keep in mind that it is not 100% always possible to trace a called function even though you have a call instruction in place.