问:
Create an array of hashes describing files obtained from a given directory
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

```<code>use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;
</code>```

Here I take a single file and create a hash with the path, size, and sha256sum.

```<code>my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";
</code>```

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

```<code>for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat
</code>```

How can I generate the necessary array?

答:
Here's my approach to a solution. I've saved a lot of code by using File::Spec::Functions instead of File::Spec, and calling rel2abs only once

I've also removed the labels, like "Full path: ", from the values in the hashes. There's no reason to put presentation strings in there: that's for the output code to do

```<code>use strict;
use warnings;

use File::Spec::Functions qw/ catfile rel2abs /;
use Digest::SHA qw/ sha256_hex /;
use Data::Dumper qw/ Dumper /;

my ( $root ) = @ARGV;

$root = rel2abs( $root );    # Allow for relative path input

my @file_data;

{
    opendir my $dh, $root or die qq{Cannot open directory "$root": $!};

    while ( readdir $dh ) {

        next if /^\./;

        my $file = catfile( $root, $_ );

        next unless -f $file;

        push @file_data, {
            path => $file,
            size => -s $file,
            id   => sha256_hex( $file ),
        };
    }
}

print Dumper \@file_data;
</code>```

Body:
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;

Here I take a single file and create a hash with the path, size, and sha256sum.

my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat

How can I generate the necessary array?

Body:
Here's my approach to a solution. I've saved a lot of code by using File::Spec::Functions instead of File::Spec, and calling rel2abs only once

I've also removed the labels, like "Full path: ", from the values in the hashes. There's no reason to put presentation strings in there: that's for the output code to do

use strict;
use warnings;

use File::Spec::Functions qw/ catfile rel2abs /;
use Digest::SHA qw/ sha256_hex /;
use Data::Dumper qw/ Dumper /;

my ( $root ) = @ARGV;

$root = rel2abs( $root );    # Allow for relative path input

my @file_data;

{
    opendir my $dh, $root or die qq{Cannot open directory "$root": $!};

    while ( readdir $dh ) {

        next if /^\./;

        my $file = catfile( $root, $_ );

        next unless -f $file;

        push @file_data, {
            path => $file,
            size => -s $file,
            id   => sha256_hex( $file ),
        };
    }
}

print Dumper \@file_data;


来源: stackexchange

问:
How to implement 3 stacks with one array?
Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.</p>

答:
As long as you try to arrange all items from one stack together at one "end" of the array, you're lacking space for the third stack.

However, you could "intersperse" the stack elements. Elements of the first stack are at indices i * 3, elements of the second stack are at indices i * 3 + 1, elements of the third stack are at indices i * 3 + 2 (where i is an integer).

```<code>+----+----+----+----+----+----+----+----+----+----+----+----+----+..
| A1 : B1 : C1 | A2 : B2 : C2 |    : B3 | C3 |    : B4 :    |    :
+----+----+----+----+----+----+----+----+----+----+----+----+----+..
                  ^                        ^         ^
                  A´s top                  C´s top   B´s top
</code>```

Of course, this scheme is going to waste space, especially when the stacks have unequal sizes. You could create arbitrarily complex schemes similar to the one described above, but without knowing any more constraints for the posed question, I'll stop here.

Update:

Due to the comments below, which do have a very good point, it should be added that interspersing is not necessary, and may even degrade performance when compared to a much simpler memory layout such as the following:

```<code>+----+----+----+----+----+----+----+----+----+----+----+----+----+..
| A1 : A2 :    :    :    | B1 : B2 : B3 : B4 :    | C1 : C2 : C3 :
+----+----+----+----+----+----+----+----+----+----+----+----+----+..
       ^                                  ^                    ^
       A´s top                            B´s top              C´s top
</code>```

i.e. giving each stack it's own contiguous block of memory. If the real question is indeed to how to make the best possible use of a fixed amount of memory, in order to not limit each stack more than necessary, then my answer isn't going to be very helpful.

In that case, I'd go with @belisarius' answer: One stack goes to the "bottom" end of the memory area, growing "upwards"; another stack goes to the "top" end of the memory area, growing "downwards", and one stack is in the middle that grows in any direction but is able to move when it gets too close to one of the other stacks.

ContentLicense: CC BY-SA 2.5

Body:
As long as you try to arrange all items from one stack together at one "end" of the array, you're lacking space for the third stack.

However, you could "intersperse" the stack elements. Elements of the first stack are at indices i * 3, elements of the second stack are at indices i * 3 + 1, elements of the third stack are at indices i * 3 + 2 (where i is an integer).

+----+----+----+----+----+----+----+----+----+----+----+----+----+..
| A1 : B1 : C1 | A2 : B2 : C2 |    : B3 | C3 |    : B4 :    |    :
+----+----+----+----+----+----+----+----+----+----+----+----+----+..
                  ^                        ^         ^
                  A´s top                  C´s top   B´s top

Of course, this scheme is going to waste space, especially when the stacks have unequal sizes. You could create arbitrarily complex schemes similar to the one described above, but without knowing any more constraints for the posed question, I'll stop here.

Update:

Due to the comments below, which do have a very good point, it should be added that interspersing is not necessary, and may even degrade performance when compared to a much simpler memory layout such as the following:

+----+----+----+----+----+----+----+----+----+----+----+----+----+..
| A1 : A2 :    :    :    | B1 : B2 : B3 : B4 :    | C1 : C2 : C3 :
+----+----+----+----+----+----+----+----+----+----+----+----+----+..
       ^                                  ^                    ^
       A´s top                            B´s top              C´s top

i.e. giving each stack it's own contiguous block of memory. If the real question is indeed to how to make the best possible use of a fixed amount of memory, in order to not limit each stack more than necessary, then my answer isn't going to be very helpful.

In that case, I'd go with @belisarius' answer: One stack goes to the "bottom" end of the memory area, growing "upwards"; another stack goes to the "top" end of the memory area, growing "downwards", and one stack is in the middle that grows in any direction but is able to move when it gets too close to one of the other stacks.


问:
How to pop-over a UIViewController
I am trying to get a UIViewController transition effect where ViewControllerB pops over ViewContorllerA- while still revealing ViewcontrllerA in the background. Any idea how I can accomplish this?

Transition:

答:
Try this.  Create a view controller on a storyboard, set the class to CustomDialog.  Add view to this view controller, which will be what you want in your popup.  When you want the dialog to lose, call confirmBlock() or cancelBlock().

//CustomDialog class

```<code>import Foundation

class CustomDialog: UIViewController, UIGestureRecognizerDelegate {

    var confirmBlock: ((_ result: AnyObject) -> ())?
    var cancelBlock: (() -> ())?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        definesPresentationContext = true
        providesPresentationContextTransitionStyle = true
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        makeBlurBackground()
        let tapDismiss = UITapGestureRecognizer(target: self, action: #selector(BaseCustomDialog.tapOutside))
        tapDismiss.delegate = self
        view.addGestureRecognizer(tapDismiss)
        view.tag = GestureRecognizerUniqueTag
    }

    @objc fileprivate func tapOutside() {
        cancelAction()
    }

    func makeBlurBackground() {
        let effectView = UIView(frame: self.frame)
        effectView.backgroundColor = ClickUpConstants.defaultTransparentBackgroundColor
        effectView.isUserInteractionEnabled = false

        view.addSubview(effectView)
        view.sendSubview(toBack: effectView)

    }

    func confirmAction(_ result: AnyObject) {
    confirmBlock?(result)
        cleanupAndDismiss()
    }

    func cancelAction() {
        cancelBlock?()
        cleanupAndDismiss()
    }

    fileprivate func cleanupAndDismiss() {
        self.view.endEditing(true)

        dismiss(animated: true) { () -> Void in
            self.confirmBlock = nil
            self.cancelBlock = nil
        }
    }
}
</code>```

How to call dialog (i.e:  when button is pressed)

```<code>let dialog = UIStoryboard(name: "CustomDialogs", bundle: nil).instantiateViewController(withIdentifier: customDialog") as! CustomDialog
let navigationController = UINavigationController(rootViewController: dialog)
navigationController.isNavigationBarHidden = true

dialog.cancelBlock = {
    //do something when cancel
    dialog.dismiss(animated: true, completion: nil)
}

dialog.confirmBlock = {
//do something when cancel
    dialog.dismiss(animated: true, completion: nil)
}

self.present(navigationController, animated: true, completion: nil)
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to pop-over a UIViewController

Body:
Try this.  Create a view controller on a storyboard, set the class to CustomDialog.  Add view to this view controller, which will be what you want in your popup.  When you want the dialog to lose, call confirmBlock() or cancelBlock().

//CustomDialog class

import Foundation

class CustomDialog: UIViewController, UIGestureRecognizerDelegate {

    var confirmBlock: ((_ result: AnyObject) -> ())?
    var cancelBlock: (() -> ())?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        definesPresentationContext = true
        providesPresentationContextTransitionStyle = true
        modalPresentationStyle = .overFullScreen
        modalTransitionStyle = .crossDissolve
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        makeBlurBackground()
        let tapDismiss = UITapGestureRecognizer(target: self, action: #selector(BaseCustomDialog.tapOutside))
        tapDismiss.delegate = self
        view.addGestureRecognizer(tapDismiss)
        view.tag = GestureRecognizerUniqueTag
    }

    @objc fileprivate func tapOutside() {
        cancelAction()
    }

    func makeBlurBackground() {
        let effectView = UIView(frame: self.frame)
        effectView.backgroundColor = ClickUpConstants.defaultTransparentBackgroundColor
        effectView.isUserInteractionEnabled = false

        view.addSubview(effectView)
        view.sendSubview(toBack: effectView)

    }

    func confirmAction(_ result: AnyObject) {
    confirmBlock?(result)
        cleanupAndDismiss()
    }

    func cancelAction() {
        cancelBlock?()
        cleanupAndDismiss()
    }

    fileprivate func cleanupAndDismiss() {
        self.view.endEditing(true)

        dismiss(animated: true) { () -> Void in
            self.confirmBlock = nil
            self.cancelBlock = nil
        }
    }
}

How to call dialog (i.e:  when button is pressed)

let dialog = UIStoryboard(name: "CustomDialogs", bundle: nil).instantiateViewController(withIdentifier: customDialog") as! CustomDialog
let navigationController = UINavigationController(rootViewController: dialog)
navigationController.isNavigationBarHidden = true

dialog.cancelBlock = {
    //do something when cancel
    dialog.dismiss(animated: true, completion: nil)
}

dialog.confirmBlock = {
//do something when cancel
    dialog.dismiss(animated: true, completion: nil)
}

self.present(navigationController, animated: true, completion: nil)


问:
Kraken Exchange API: AddOrder's expiretm parameter
Does the API AddOrder() command support expiretm for limit orders? I always get an EGeneral:Invalid arguments:expiretm error when I set this parameter.

I tried to expire 3 seconds from now with the following settings:

```<code>1) expiretm = 3             # int
2) expiretm = "+3"          # string
3) expiretm = 1500226507    # int
</code>```

No luck, all return the mentioned error. Only expiretm = 0 is accepted.

Is expiretm supported for limit orders?

Which syntax is the right one: (1) or (2)?

Thx

答:
both expiretm = 1500226507 and expiretm = '1500226507' are correct. However you must make sure 1500226507 is bigger than the current unix time. Also, make sure you are using the notation correct. It is too easy to make a mistake.  A correct usage could be, say

```<code>currentUnixTime = 1500226507
// set expiretm to a min from now
expirationTime = 1500226567 // notice the last two digits

blablabla{AddOrder{'pair: 'x', 'price: 'xx', 'volume: 'xxx', 'type: 'y', 'expiretm: expirationTime}};
</code>```

BTW this is for nodejs.

Body:
Does the API AddOrder() command support expiretm for limit orders? I always get an EGeneral:Invalid arguments:expiretm error when I set this parameter.

I tried to expire 3 seconds from now with the following settings:

1) expiretm = 3             # int
2) expiretm = "+3"          # string
3) expiretm = 1500226507    # int

No luck, all return the mentioned error. Only expiretm = 0 is accepted.

Is expiretm supported for limit orders?

Which syntax is the right one: (1) or (2)?

Thx

Body:
both expiretm = 1500226507 and expiretm = '1500226507' are correct. However you must make sure 1500226507 is bigger than the current unix time. Also, make sure you are using the notation correct. It is too easy to make a mistake.  A correct usage could be, say

currentUnixTime = 1500226507
// set expiretm to a min from now
expirationTime = 1500226567 // notice the last two digits

blablabla{AddOrder{'pair: 'x', 'price: 'xx', 'volume: 'xxx', 'type: 'y', 'expiretm: expirationTime}};

BTW this is for nodejs.


问:
When reading from file, it's add an item twice to the combobox
I'm reading from a file, and then add a specific String to a jcombobox, but I only need it once. I tried something like this: (even with contains), but it still has the element twice</p>

```<code>public void beolvas() {
    gyarto_cmb.removeAllItems();
    try {
        BufferedReader be = null;

        be = new BufferedReader(new FileReader("F:\\telefonok.txt"));
        String sor = null;
        while ((sor = be.readLine()) != null) {
            StringTokenizer felbont = new StringTokenizer(sor, ";");
            String gyarto_meg = felbont.nextToken();

            String tel_tip = felbont.nextToken();
            double kijel_meret = (double) Double.parseDouble(felbont.nextToken());
            String kijel_felbontas = felbont.nextToken();

            int tarhely_merete = (int) Integer.parseInt(felbont.nextToken());
            int akkumulator_kap = (int) Integer.parseInt(felbont.nextToken());
            int telefon_ara = (int) Integer.parseInt(felbont.nextToken());

            Gyarto gyart_1 = new Gyarto();

            gyart_1.megnevezes = gyarto_meg;
            Tipus tipus1 = new Tipus(tel_tip, kijel_meret, kijel_felbontas, tarhely_merete, akkumulator_kap,
                    telefon_ara);
            gyart_1.tipuska.add(tipus1);

            telefonok.add(gyart_1);

            if (telefonok.indexOf(gyarto_meg) == -1) {
                gyarto_cmb.addItem(gyarto_meg);
            }

        }
    } catch (Exception ex) {
        System.out.println("Error:" + ex.toString());
    }
}
</code>```

答:
I don't see the declaration for gyarto_cmb, so I don't know what methods are available</p>

```<code>Set<String> added = new HashSet<String>();

while((sor=be.readLine())!=null){
    ...

    if(!added.contains(gyarto_meg)) {
        added.add(gyarto_meg);
        gyarto_cmb.addItem(gyarto_meg);
    }
}
</code>```

Body:
I'm reading from a file, and then add a specific String to a jcombobox, but I only need it once. I tried something like this: (even with contains), but it still has the element twice

public void beolvas() {
    gyarto_cmb.removeAllItems();
    try {
        BufferedReader be = null;

        be = new BufferedReader(new FileReader("F:\\telefonok.txt"));
        String sor = null;
        while ((sor = be.readLine()) != null) {
            StringTokenizer felbont = new StringTokenizer(sor, ";");
            String gyarto_meg = felbont.nextToken();

            String tel_tip = felbont.nextToken();
            double kijel_meret = (double) Double.parseDouble(felbont.nextToken());
            String kijel_felbontas = felbont.nextToken();

            int tarhely_merete = (int) Integer.parseInt(felbont.nextToken());
            int akkumulator_kap = (int) Integer.parseInt(felbont.nextToken());
            int telefon_ara = (int) Integer.parseInt(felbont.nextToken());

            Gyarto gyart_1 = new Gyarto();

            gyart_1.megnevezes = gyarto_meg;
            Tipus tipus1 = new Tipus(tel_tip, kijel_meret, kijel_felbontas, tarhely_merete, akkumulator_kap,
                    telefon_ara);
            gyart_1.tipuska.add(tipus1);

            telefonok.add(gyart_1);

            if (telefonok.indexOf(gyarto_meg) == -1) {
                gyarto_cmb.addItem(gyarto_meg);
            }

        }
    } catch (Exception ex) {
        System.out.println("Error:" + ex.toString());
    }
}

Body:
I don't see the declaration for gyarto_cmb, so I don't know what methods are available

Set<String> added = new HashSet<String>();

while((sor=be.readLine())!=null){
    ...

    if(!added.contains(gyarto_meg)) {
        added.add(gyarto_meg);
        gyarto_cmb.addItem(gyarto_meg);
    }
}


问:
Getting the sum of 2 different indices from 2 separate arrays
Very new to Java, so please bear with me here. I have to write a program based on the resident status of a student to determine the total cost for the term.  I must use Abstract methods (separate class), and then create classes based on Tuition for Full time and Part Time. The full and part-time classes must use arrays.  I probably wrote the array list wrong, but this is what I have so far, and I need to create an object "county" so I can calculate the cost for the student who resides in the county.

How do I call the tuition and capital fee to add them together for the index C only? Or, would it be easier if I write an array for just county with the tuition and capital fee then sum those together, then add that total to the other costs listed?  Also, when I try to create the object under county, it comes up with an error.  I will be using Radio Buttons to determine what the resident status of the student is, (not sure if that changes things for my calculations). Any help is appreciated.

The abstract class:

```<code>package collegecost1;

public abstract class collegeAbMain {
    public abstract double tuition();
    public abstract double capitalFee();
    public abstract double accidentIns();
    public abstract double collegeFee();

    //public abstract double county();
    //public abstract double outCounty();
    //public abstract double outState();

}
</code>```

fullTime class:

```<code> package collegecost1;

 public class fullTime extends collegeAbMain {
     double  C;
     double OC;
     double OS;
     double Ins;
     double fee;
     double total;

     @Override
     public double tuition() {
         double resident = 3;
         double [] tuition = new double [(int) resident];

         // I have to use the variables C, OC, and OS
         tuition[0] = C;
         C = 1571.25;

         tuition[1] = OC;
         OC = 3142.50;

         tuition[2] = OS;
         OS = 4713.75;
         return resident;
     }

     @Override
     public double capitalFee() {
         double resident = 3;
         double[] capitalFee = new double [(int) resident];

         capitalFee[0] = C;
         C = 0.00;

         capitalFee[1] = OC;
         OC = 78.00;

         capitalFee[2] = OS;
         OS = 78.00;

         return resident ;
     }

     @Override
     public double accidentIns() {
        Ins = 0.00;
        return Ins;
    }

    @Override
    public double collegeFee() {
        fee = 50.40;
        return fee;
    }

    public double county() {
     county total = new county()
    //ERROR (wants me to create class or interface for the 1st word county
    // have written objects the exact same way in other programs and never
    // had an issue.
        {
          //NOT THE ACTUAL CODE

                  //total = (index[0] from resident tution +
          //index [0] from resident caplitalFee)
                  //+ (Ins) + (fee);

              return total();
        }

    }
}
</code>```

答:
You do not need arrays for this job. Further in your code you always return resident instead of the array. Try something like this:

```<code>public double tuition(String s) {

    double acc = 0;

    if (s.equals("C")) {
        acc = 1571.25;
    } else if (s.equals("OC")) {
        acc = 3142.50;
    } else if (s.equals("OS")) {
        acc = 4713.75;
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return acc;

}

public double capitalFee(String s) {

    double acc = 0;

    if (s.equals("C")) {
        acc = 0.00;
    } else if (s.equals("OC") || s.equals("OS")) {
        acc = 78.00;
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return acc;

}

public double accidentIns() {
    double ins = 0.00;
    return ins;
}

public double collegeFee() {
    double fee = 50.40;
    return fee;
}

public double county(String a, String b) {
    return tuition(a) + capitalFee(b) + accidentIns() + collegeFee();

}
</code>```

And you can't do county total = new county(). You are trying to create an object of a method. You will need a class called County with a constructor to do this.

Here an example with arrays:

```<code>public double[] tuition() {

    double[] tuition = new double[3];

    double C = 1571.25;
    tuition[0] = C;

    double OC = 3142.50;
    tuition[1] = OC;

    double OS = 4713.75;
    tuition[2] = OS;

    return tuition;

}

public double[] capitalFee() {

    double[] capitalFee = new double[3];

    double C = 0.00;
    capitalFee[0] = C;

    double OC = 78.00;
    capitalFee[1] = OC;

    double OS = 78.00;
    capitalFee[2] = OS;

    return capitalFee;
}

public double accidentIns() {
    double ins = 0.00;
    return ins;
}

public double collegeFee() {
    double fee = 50.40;
    return fee;
}

public double county(String s) {
    double result = 0;
    double[] tuition = tuition();
    double[] capitalFee = capitalFee();
    if (s.equals("C")) {
        result = tuition[0] + capitalFee[0] + accidentIns() + collegeFee();
    } else if (s.equals("OC")) {
        result = tuition[1] + capitalFee[1] + accidentIns() + collegeFee();
    } else if (s.equals("OS")) {
        result = tuition[2] + capitalFee[2] + accidentIns() + collegeFee();
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return result;

}
</code>```

Body:
Very new to Java, so please bear with me here. I have to write a program based on the resident status of a student to determine the total cost for the term.  I must use Abstract methods (separate class), and then create classes based on Tuition for Full time and Part Time. The full and part-time classes must use arrays.  I probably wrote the array list wrong, but this is what I have so far, and I need to create an object "county" so I can calculate the cost for the student who resides in the county.

How do I call the tuition and capital fee to add them together for the index C only? Or, would it be easier if I write an array for just county with the tuition and capital fee then sum those together, then add that total to the other costs listed?  Also, when I try to create the object under county, it comes up with an error.  I will be using Radio Buttons to determine what the resident status of the student is, (not sure if that changes things for my calculations). Any help is appreciated.

The abstract class:

package collegecost1;

public abstract class collegeAbMain {
    public abstract double tuition();
    public abstract double capitalFee();
    public abstract double accidentIns();
    public abstract double collegeFee();

    //public abstract double county();
    //public abstract double outCounty();
    //public abstract double outState();

}

fullTime class:

 package collegecost1;

 public class fullTime extends collegeAbMain {
     double  C;
     double OC;
     double OS;
     double Ins;
     double fee;
     double total;

     @Override
     public double tuition() {
         double resident = 3;
         double [] tuition = new double [(int) resident];

         // I have to use the variables C, OC, and OS
         tuition[0] = C;
         C = 1571.25;

         tuition[1] = OC;
         OC = 3142.50;

         tuition[2] = OS;
         OS = 4713.75;
         return resident;
     }

     @Override
     public double capitalFee() {
         double resident = 3;
         double[] capitalFee = new double [(int) resident];

         capitalFee[0] = C;
         C = 0.00;

         capitalFee[1] = OC;
         OC = 78.00;

         capitalFee[2] = OS;
         OS = 78.00;

         return resident ;
     }

     @Override
     public double accidentIns() {
        Ins = 0.00;
        return Ins;
    }

    @Override
    public double collegeFee() {
        fee = 50.40;
        return fee;
    }

    public double county() {
     county total = new county()
    //ERROR (wants me to create class or interface for the 1st word county
    // have written objects the exact same way in other programs and never
    // had an issue.
        {
          //NOT THE ACTUAL CODE

                  //total = (index[0] from resident tution +
          //index [0] from resident caplitalFee)
                  //+ (Ins) + (fee);

              return total();
        }

    }
}

Body:
You do not need arrays for this job. Further in your code you always return resident instead of the array. Try something like this:

public double tuition(String s) {

    double acc = 0;

    if (s.equals("C")) {
        acc = 1571.25;
    } else if (s.equals("OC")) {
        acc = 3142.50;
    } else if (s.equals("OS")) {
        acc = 4713.75;
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return acc;

}

public double capitalFee(String s) {

    double acc = 0;

    if (s.equals("C")) {
        acc = 0.00;
    } else if (s.equals("OC") || s.equals("OS")) {
        acc = 78.00;
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return acc;

}

public double accidentIns() {
    double ins = 0.00;
    return ins;
}

public double collegeFee() {
    double fee = 50.40;
    return fee;
}

public double county(String a, String b) {
    return tuition(a) + capitalFee(b) + accidentIns() + collegeFee();

}

And you can't do county total = new county(). You are trying to create an object of a method. You will need a class called County with a constructor to do this.

Here an example with arrays:

public double[] tuition() {

    double[] tuition = new double[3];

    double C = 1571.25;
    tuition[0] = C;

    double OC = 3142.50;
    tuition[1] = OC;

    double OS = 4713.75;
    tuition[2] = OS;

    return tuition;

}

public double[] capitalFee() {

    double[] capitalFee = new double[3];

    double C = 0.00;
    capitalFee[0] = C;

    double OC = 78.00;
    capitalFee[1] = OC;

    double OS = 78.00;
    capitalFee[2] = OS;

    return capitalFee;
}

public double accidentIns() {
    double ins = 0.00;
    return ins;
}

public double collegeFee() {
    double fee = 50.40;
    return fee;
}

public double county(String s) {
    double result = 0;
    double[] tuition = tuition();
    double[] capitalFee = capitalFee();
    if (s.equals("C")) {
        result = tuition[0] + capitalFee[0] + accidentIns() + collegeFee();
    } else if (s.equals("OC")) {
        result = tuition[1] + capitalFee[1] + accidentIns() + collegeFee();
    } else if (s.equals("OS")) {
        result = tuition[2] + capitalFee[2] + accidentIns() + collegeFee();
    } else {
        throw new IllegalArgumentException("Enter C, OC or OS!");
    }
    return result;

}


问:
CSS3 specifications on w3.org
http://www.w3.org/TR/css3-roadmap/

Hasn't CSS3 been out since a while now? Why is most of the specification not complete?

Is there a complete reference anywhere on the web (or in a book)?

答:
Does this link help: http://www.w3.org/TR/#tr_CSS

Standards are a slow process -- you can see newer stuff in that list.  A book is probably your best bet to see a "distilled" version.

Title: CSS3 specifications on w3.org


问:
Checking a voucher code on a Demandware online store
I'm working for a startup and we have a customer who uses Demandware for their online store.

Our company provides vouchers which are worth a specific amount of money. So customers on the retail site can enter the voucher number near the end of the checkout experience and if it's worth, say, 10 dollars, their shopping cart is updated (-10).

I have the CTO saying we just need to "drop a few lines of javascript" onto the retailer online store. But I think this requires a Demandware plugin (especially updating a shopping cart), which involves signing up for a developer or partnership account (which takes some time), learning Demand Script and building the plugin, then releasing it to Saleforce's app store. Am I correct? Is this the only way to achieve this?

Just to be clear, the functionality is: the voucher code box needs to take a voucher number, an API request is made to our service to check what it's worth, then update the cart.

答:
The first tip from me is that Demandware got bought by Salesforce and is now branded as Salesforce Commerce Cloud, so if you hear either, they are the same thing.

You are right that you are going to have to work with Salesforce to get going.  They are a cloud provider and there is no self-hosted version of the platform, so in order to do any development, you need to have a relationship with them.

So then it depends on how you get access.  If the client has any sandbox environments they are willing to share with you, you could do this as a custom build working in their environment, modifying cart code to make the service call as you ask and as the previous response suggests.  But then (depending on the terms you have with the client) your company may or may not be able to reuse that code for other clients.  You will also have to work with them to get that integrated into their existing site, get it deployed through their processes, etc.

If you want to write something that other Commerce Cloud clients could use, then you should set up your own partner relationship with Salesforce and get a software package they call a cartridge to what they call their LINK marketplace, which is basically a big clearinghouse of integrations like yours.

Technology-wise, the platform has gone through some changes recently, going from an XML-based GUI tool to specify business logic to using CommonJS scripts to define them.  If your client is a new client within the last year or two they probably have this new fully javascript implementation, but if they are an older client than that they may be using the old way, which has a steeper (read: more proprietary) learning curve.


问:
PHP - How do I read all attributes of XML items using simpleXML?
I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:

```<code>$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

                echo str_repeat('--', $i)." <$name2> \n";
                    showTree($value2, ($i+1));
                echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function
</code>```

As I said, it works fine, but doesn't display the attributes, for example:

```<code><item id=2>Item</item>
</code>```

returns only the:

```<code><item>Item</item>
</code>```

Thanks for any responses, Mike.

答:
Unless I missread your code something like this should probably be about right.</p>

```<code>$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

              $attribsStr = '';
              foreach($value2->attributes() as $attribName => $attribValue) {
                $attribsStr .= $attribName . '="' . $attribValue . '"' . ' ';
              }

              echo str_repeat('--', $i)." <$name2 $attribsStr> \n";
                showTree($value2, ($i+1));
              echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function
</code>```

Body:
I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:

$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

                echo str_repeat('--', $i)." <$name2> \n";
                    showTree($value2, ($i+1));
                echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function

As I said, it works fine, but doesn't display the attributes, for example:

<item id=2>Item</item>

returns only the:

<item>Item</item>

Thanks for any responses, Mike.

Body:
Unless I missread your code something like this should probably be about right.

$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

              $attribsStr = '';
              foreach($value2->attributes() as $attribName => $attribValue) {
                $attribsStr .= $attribName . '="' . $attribValue . '"' . ' ';
              }

              echo str_repeat('--', $i)." <$name2 $attribsStr> \n";
                showTree($value2, ($i+1));
              echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function


问:
Update data array in the same row
I would like to approve leave application based on dates for example as below :

```<code>echo "<select name='app_status[]' required>
<option value='' selected>Pending</option>
<option value='1'>Approve</option>
<option value='2'>Reject</option></select>";

$app_status = array();
if(is_array($app_status)) {
  foreach($_POST['app_status'] as $key1=>$value1) {
     $app_status[]=$value1;
  }
}

for($loop = 0; $loop < count($app_status); $loop++) {
  if($app_status[$loop]=="" || $app_status[$loop]==null)
  $error=1;
}

if(isset($error))
$error=1;
else
$error=0;

if($error==0) {
  for ($i = 0; $i < count($app_status); $i++) {
     $str = $app_status[$i];
     $sql= "UPDATE leaves_apply SET app_status ='$str' WHERE app_id='$app_id'";
     $query2 = mysqli_query($sql);
  }
}
</code>```

For example if I approve the leaves for 12/8/2017 - 15/8/2017 except for 16/8/2017, I will get an output like this 11112 And when I check the database, the column app_status will only update 2, as if it only read the last data and not the first four data. If possible I would like the data 11112 to be update in the app_status column for app_id no 1357. I'm not sure if this is the right way, please help me as I'm new to this. Thank you.

答:
I think this modification should do what you would like...

```<code>if($error==0) {

  // Declare the string for the app_status
  $str = "";

  // Loop though the statuses and put together the statuses
  for ($i = 0; $i < count($app_status); $i++) {
     $str .= $app_status[$i];
  }

  // Update the database record
  $sql= "UPDATE leaves_apply SET app_status = '$str' WHERE app_id='$app_id'";
  $query2 = mysqli_query($sql);
}
</code>```

Please remember to escape your database queries to prevent SQL injection.

Title: Update data array in the same row

Body:
I would like to approve leave application based on dates for example as below :

echo "<select name='app_status[]' required>
<option value='' selected>Pending</option>
<option value='1'>Approve</option>
<option value='2'>Reject</option></select>";

$app_status = array();
if(is_array($app_status)) {
  foreach($_POST['app_status'] as $key1=>$value1) {
     $app_status[]=$value1;
  }
}

for($loop = 0; $loop < count($app_status); $loop++) {
  if($app_status[$loop]=="" || $app_status[$loop]==null)
  $error=1;
}

if(isset($error))
$error=1;
else
$error=0;

if($error==0) {
  for ($i = 0; $i < count($app_status); $i++) {
     $str = $app_status[$i];
     $sql= "UPDATE leaves_apply SET app_status ='$str' WHERE app_id='$app_id'";
     $query2 = mysqli_query($sql);
  }
}

For example if I approve the leaves for 12/8/2017 - 15/8/2017 except for 16/8/2017, I will get an output like this 11112 And when I check the database, the column app_status will only update 2, as if it only read the last data and not the first four data. If possible I would like the data 11112 to be update in the app_status column for app_id no 1357. I'm not sure if this is the right way, please help me as I'm new to this. Thank you.

Body:
I think this modification should do what you would like...

if($error==0) {

  // Declare the string for the app_status
  $str = "";

  // Loop though the statuses and put together the statuses
  for ($i = 0; $i < count($app_status); $i++) {
     $str .= $app_status[$i];
  }

  // Update the database record
  $sql= "UPDATE leaves_apply SET app_status = '$str' WHERE app_id='$app_id'";
  $query2 = mysqli_query($sql);
}

Please remember to escape your database queries to prevent SQL injection.


问:
Storing multiple integers in a string
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:

```<code>for (int a = 0; a < 5; a++)
        {
            string ans;
            int number;
            int num;
            number = rand() % 9 + 1;
            cout << number << " ";
            num = number;
            to_string(num);
            ans =+ num;
        }
</code>```

Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?

答:
There are a number of problems with your code.

you are declaring ans inside the loop, so it is created and destroyed on each loop iteration.  If you want the loop to append 5 numbers to ans, you have to declare it outside of the loop instead.

std::to_string() outputs a new std::string as its return value. It does not "magically" turn the input value into a string type, like your code is assuming.  You are not appending the returned string to ans at all.

=+ is not a valid append operator.  It is interpreted as separate operators = and +.  std::string does not have a = operator that takes an int as input, and does not have a unary + operator.  You need to use the += operator instead.

Try this:

```<code>#include <string>
#include <iostream>

std::string ans;
for (int a = 0; a < 5; ++a)
{
    int number = ...
    ...
    ans += std::to_string(number);
}
// use ans as needed...
</code>```

Alternatively, use std::ostringstream instead of std::to_string():

```<code>#include <string>
#include <sstream>
#include <iostream>

std::ostringstream oss;
for (int a = 0; a < 5; ++a)
{
    int number = ...
    ...
    oss << number;
}
std::string ans = oss.str();
// use ans as needed...
</code>```

With that said, you are clearly using C++11 (when std::to_string() was introduced) or later, so you should be using a C++ random number generator instead of the one from C, eg:

```<code>#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 9);

for (int a = 0; a < 5; ++a)
{
    int number = dis(gen);
    ...
}
</code>```

Title: Storing multiple integers in a string

Body:
I am trying to store 5 integers into a string, but I am having trouble. Here is the code:

for (int a = 0; a < 5; a++)
        {
            string ans;
            int number;
            int num;
            number = rand() % 9 + 1;
            cout << number << " ";
            num = number;
            to_string(num);
            ans =+ num;
        }

Essentially, I would like "ans" to be something along the lines of "12345" but when I run it, it either doesn't show anything or shows 5 boxes with question marks inside of them. Any help?

Body:
There are a number of problems with your code.

you are declaring ans inside the loop, so it is created and destroyed on each loop iteration.  If you want the loop to append 5 numbers to ans, you have to declare it outside of the loop instead.

std::to_string() outputs a new std::string as its return value. It does not "magically" turn the input value into a string type, like your code is assuming.  You are not appending the returned string to ans at all.

=+ is not a valid append operator.  It is interpreted as separate operators = and +.  std::string does not have a = operator that takes an int as input, and does not have a unary + operator.  You need to use the += operator instead.

Try this:

#include <string>
#include <iostream>

std::string ans;
for (int a = 0; a < 5; ++a)
{
    int number = ...
    ...
    ans += std::to_string(number);
}
// use ans as needed...

Alternatively, use std::ostringstream instead of std::to_string():

#include <string>
#include <sstream>
#include <iostream>

std::ostringstream oss;
for (int a = 0; a < 5; ++a)
{
    int number = ...
    ...
    oss << number;
}
std::string ans = oss.str();
// use ans as needed...

With that said, you are clearly using C++11 (when std::to_string() was introduced) or later, so you should be using a C++ random number generator instead of the one from C, eg:

#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 9);

for (int a = 0; a < 5; ++a)
{
    int number = dis(gen);
    ...
}


问:
Render named children in React component?
I have a modal component which take a trigger to open the modal, and the content to go inside the modal.

```<code><Modal>
  <button className="btn btn--primary">Open modal</button>
  <div>
    <p>Modal content</p>
    <p>More modal content</p>
  </div>
</Modal>
</code>```

And in the Modal component:

```<code>  return (
    <div className="Modal">
      {props.children[0]}
      <div className="Modal__container">
        <div className="Modal__header">
          <button className="Modal__close btn btn--secondary btn--small">
            Close
          </button>
          <h1 className="Modal__heading">Here is my modal</h1>
        </div>
        <div className="Modal__content">{props.children[1]}</div>
      </div>
    </div>
  );
</code>```

This is working but very fragile as Im using an index on props.children. Can I instead name the components I pass to Modal? So something like:

```<code><Modal>
  <Modal.Trigger>
    <button className="btn btn--primary">Open modal</button>
  </Modal.Trigger>
  <Modal.Content>
    <p>Modal content</p>
    <p>More modal content</p>
  </Modal.Content>
</Modal>
</code>```

答:
I suggest you use props instead:

declare your Modal like so:

```<code><Modal action={<button className="btn btn--primary">Open modal</button>}>
  <div>
    <p>Modal content</p>
    <p>More modal content</p>
  </div>
</Modal>
</code>```

and your render method will then look something like

```<code>return (
  <div className="Modal">
    {props.action}
    <div className="Modal__container">
      <div className="Modal__header">
        <button className="Modal__close btn btn--secondary btn--small">
          Close
        </button>
        <h1 className="Modal__heading">Here is my modal</h1>
      </div>
      <div className="Modal__content">{props.children[1]}</div>
    </div>
  </div>
);
</code>```

Body:
I have a modal component which take a trigger to open the modal, and the content to go inside the modal.

<Modal>
  <button className="btn btn--primary">Open modal</button>

Modal content

More modal content

</Modal>

And in the Modal component:

  return (

      {props.children[0]}

          <button className="Modal__close btn btn--secondary btn--small">
            Close
          </button>

Here is my modal

{props.children[1]}

  );

This is working but very fragile as Im using an index on props.children. Can I instead name the components I pass to Modal? So something like:

<Modal>
  <Modal.Trigger>
    <button className="btn btn--primary">Open modal</button>
  </Modal.Trigger>
  <Modal.Content>

Modal content

More modal content

  </Modal.Content>
</Modal>

Body:
I suggest you use props instead:

declare your Modal like so:

<Modal action={<button className="btn btn--primary">Open modal</button>}>
  <div>
    <p>Modal content</p>
    <p>More modal content</p>
  </div>
</Modal>

and your render method will then look something like

return (
  <div className="Modal">
    {props.action}
    <div className="Modal__container">
      <div className="Modal__header">
        <button className="Modal__close btn btn--secondary btn--small">
          Close
        </button>
        <h1 className="Modal__heading">Here is my modal</h1>
      </div>
      <div className="Modal__content">{props.children[1]}</div>
    </div>
  </div>
);

ContentLicense: CC BY-SA 4.0


问:
How to convert JSON column values into separated schema with many rows in SQL Server?
I have a data set that has only one column has JSON format. Here is snap from the table:

Here are only Genres column in JSON that I want to create another table to have many rows for each row in this table to list the genre id and name and connect the two table by the primary key

I have used OPENJSON available in SQL Server but all what I get only for one record and not for the whole table

```<code>DECLARE @json nvarchar(MAX) = (SELECT TOP (1) [Genres]
  FROM [IMDB_movies].[dbo].[Genre_movies])

 SELECT *
 FROM OPENJSON(@json)
 WITH (id FLOAT,
 name VARCHAR(100))
</code>```

But I have no idea how to convert the whole Genres records in the table  into new table of many rows for each tag in Genres record in the main table.

答:
Try this answer:</p>

```<code>DECLARE @Genre_movies TABLE(Generes VARCHAR(8000))
INSERT INTO @Genre_movies VALUES('[{"id":"28","name":"Action"},{"id":"12","name":"Adventure"}]')
INSERT INTO @Genre_movies VALUES('[{"id":"16","name":"Animation"},{"id":"14","name":"Fantasy"}]')

DECLARE @Result TABLE(ID INT,Name VARCHAR(20))

SELECT Generes,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) RN
INTO #Temp
FROM @Genre_movies

DECLARE @MIN INT,@MAX INT,@JSONValue VARCHAR(MAX)
SELECT @MAX=MAX(RN),@MIN=MIN(RN) FROM #Temp

WHILE(@MAX>=@MIN)
BEGIN
    SELECT @JSONValue=Generes FROM #Temp WHERE RN=@MIN

    INSERT INTO @Result
    SELECT *
     FROM OPENJSON(@JSONValue)
     WITH (id FLOAT,
     name VARCHAR(100))

    SET @MIN=@MIN+1
END

SELECT * FROM @Result
DROP TABLE #Temp
</code>```

Body:
I have a data set that has only one column has JSON format. Here is snap from the table:

Here are only Genres column in JSON that I want to create another table to have many rows for each row in this table to list the genre id and name and connect the two table by the primary key

I have used OPENJSON available in SQL Server but all what I get only for one record and not for the whole table

DECLARE @json nvarchar(MAX) = (SELECT TOP (1) [Genres]
  FROM [IMDB_movies].[dbo].[Genre_movies])

 SELECT *
 FROM OPENJSON(@json)
 WITH (id FLOAT,
 name VARCHAR(100))

But I have no idea how to convert the whole Genres records in the table  into new table of many rows for each tag in Genres record in the main table.

Body:
Try this answer:

DECLARE @Genre_movies TABLE(Generes VARCHAR(8000))
INSERT INTO @Genre_movies VALUES('[{"id":"28","name":"Action"},{"id":"12","name":"Adventure"}]')
INSERT INTO @Genre_movies VALUES('[{"id":"16","name":"Animation"},{"id":"14","name":"Fantasy"}]')

DECLARE @Result TABLE(ID INT,Name VARCHAR(20))

SELECT Generes,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) RN
INTO #Temp
FROM @Genre_movies

DECLARE @MIN INT,@MAX INT,@JSONValue VARCHAR(MAX)
SELECT @MAX=MAX(RN),@MIN=MIN(RN) FROM #Temp

WHILE(@MAX>=@MIN)
BEGIN
    SELECT @JSONValue=Generes FROM #Temp WHERE RN=@MIN

    INSERT INTO @Result
    SELECT *
     FROM OPENJSON(@JSONValue)
     WITH (id FLOAT,
     name VARCHAR(100))

    SET @MIN=@MIN+1
END

SELECT * FROM @Result
DROP TABLE #Temp


答:
You can mark your children with a boolean flag that will serve as a name.

Within Modal you find the child marked as trigger and the child marked as content:

```<code>// within Modal
render() {
  let trigger, content;
  React.Children.forEach(this.props.children, child => {
    if (!child) return;
    if (child.props.trigger) { trigger = child }
    if (child.props.content) { content = child }
  })

  return (
    <div className="Modal">
      {trigger}
      <div className="Modal__container">
        <div className="Modal__header">
          <button className="Modal__close btn btn--secondary btn--small">
            Close
          </button>
        <h1 className="Modal__heading">Here is my modal</h1>
      </div>
      <div className="Modal__content">
        {content}
      </div>
    </div>
  )
}
</code>```

And you mark the appropriate children when rendering Modal:

```<code><Modal>
  <button trigger className="btn btn--primary">Open modal</button>
  <div content>
    <p>Modal content</p>
    <p>More modal content</p>
  </div>
</Modal>
</code>```

We wrote a library called seapig that you might find useful for this use case.

Title: Render named children in React component?

Body:
You can mark your children with a boolean flag that will serve as a name.

Within Modal you find the child marked as trigger and the child marked as content:

// within Modal
render() {
  let trigger, content;
  React.Children.forEach(this.props.children, child => {
    if (!child) return;
    if (child.props.trigger) { trigger = child }
    if (child.props.content) { content = child }
  })

  return (
    <div className="Modal">
      {trigger}
      <div className="Modal__container">
        <div className="Modal__header">
          <button className="Modal__close btn btn--secondary btn--small">
            Close
          </button>
        <h1 className="Modal__heading">Here is my modal</h1>
      </div>
      <div className="Modal__content">
        {content}
      </div>
    </div>
  )
}

And you mark the appropriate children when rendering Modal:

<Modal>
  <button trigger className="btn btn--primary">Open modal</button>
  <div content>
    <p>Modal content</p>
    <p>More modal content</p>
  </div>
</Modal>

We wrote a library called seapig that you might find useful for this use case.


问:
Consequences of Java 32bit on Win(any) 64bit?
I am trying to install JAI (Java Advanced Imaging) 1.1.3 in my Vista 64 and it says that in order for it to be installed JDK 1.3 and up must be installed. The problem is that I have already installed the latest JDK for Win64 and it seems that it is not willing to work with it.

I would like to know if there are any severe consequences if I install JDK 32bit instead of the 64bit in Vista 64.

Thanks in advance for any advice on the subject!

John

答: It is unlikely that using a 32-bit version instead of a 64-bit will make any difference unless your library uses 32-bit shared libraries. (and doesn't have a 64-bit version)</p>

OwnerDisplayName: imoschak

OwnerDisplayName: Peter Lawrey


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答:
The fastest way is a sorting network implemented in hardware. Barring that, the fastest way is determined only by measuring. I'd try

std::sort,

pigeonhole (bucket) sort with reuse of the buckets,

a bunch of if statements, and

insertion sort

in that order, because it's the easiest-to-hardest order (try to get insertion sort right the first time...) until you find something that's maintainable once the constant eight turns out to have the value nine.

Also, bubble sort, selection deserve and shell sort deserve notice. I've never actually implemented those because they have bad rep, but you could try them.


问:
Swarmed with identifier errors
I've been programming a Monopoly game for a final project. So I thought I was on a roll, and that I had everything figured out with my psuedocode. But, it seems I forgot how to deal with includes properly, I know that is the issue since I was able to refine it to that point, but I'm not sure how to fix it.

In this super stripped down version of my code I have three .h files "Space.h" which is an abstract/virtual class which has to be inherited by a variety of different spaces that can appear on a typical Monopoly board: properties, jail, taxes, Chance, Community Chest, etc. The function that has to be inherited is run(Player&) which is what is "run" when you land on that particular space on the board, all functions that use run use a player passed by argument.

```<code>#pragma once
#include <string>
#include "Player.h"

class Space
{
public:
    virtual void run(Player&) = 0;
};
</code>```

My second .h file is the "Property.h" this inherits from Space

```<code>#pragma once
#include "Space.h"

class Property : Space
{
public:
    void run(Player&) override;
    int i{ 0 };
};
</code>```

Lastly I have the "Player.h" which has two variables a name and a vector of properties it owns.

```<code>#pragma once
#include <string>
#include <vector>
#include "Property.h"

class Player
{
public:
    std::string name{ "foo" };
    void addProperty(Property p);
private:
    std::vector <Property> ownedProperties;
};
</code>```

Here's a very basic Property implementation

```<code>#include "Property.h"
#include <iostream>

void Property::run(Player & p)
{
    std::cout << p.name;
}
</code>```

Player implementation

```<code>#include "Player.h"
#include <iostream>

void Player::addProperty(Property p)
{
    ownedProperties.push_back(p);
}
</code>```

And finally main

```<code>#include "Player.h"
#include "Space.h"
#include "Property.h"

int main()
{
    Player p{};
    Property prop{};
    prop.run(p);
    system("pause");
}
</code>```

Every time this is run I get a slew of errors, I'm sure it's got to do something with the circular include logic, with player including property, and property including space, which includes player. But, I don't see a workaround considering #include is needed to know how everything is defined isn't? Or are these errors referring to something else?

答:
You have a circular include problem. Player includes Property which includes Space which includes Player again.

You can break the circle by not including Player.h in Space.h and only forward declare the class

```<code>#pragma once

class Player;

class Space
{
public:
    virtual void run(Player&) = 0;
};
</code>```

Title: Swarmed with identifier errors

Body:
I've been programming a Monopoly game for a final project. So I thought I was on a roll, and that I had everything figured out with my psuedocode. But, it seems I forgot how to deal with includes properly, I know that is the issue since I was able to refine it to that point, but I'm not sure how to fix it.

In this super stripped down version of my code I have three .h files "Space.h" which is an abstract/virtual class which has to be inherited by a variety of different spaces that can appear on a typical Monopoly board: properties, jail, taxes, Chance, Community Chest, etc. The function that has to be inherited is run(Player&) which is what is "run" when you land on that particular space on the board, all functions that use run use a player passed by argument.

#pragma once
#include <string>
#include "Player.h"

class Space
{
public:
    virtual void run(Player&) = 0;
};

My second .h file is the "Property.h" this inherits from Space

#pragma once
#include "Space.h"

class Property : Space
{
public:
    void run(Player&) override;
    int i{ 0 };
};

Lastly I have the "Player.h" which has two variables a name and a vector of properties it owns.

#pragma once
#include <string>
#include <vector>
#include "Property.h"

class Player
{
public:
    std::string name{ "foo" };
    void addProperty(Property p);
private:
    std::vector <Property> ownedProperties;
};

Here's a very basic Property implementation

#include "Property.h"
#include <iostream>

void Property::run(Player & p)
{
    std::cout << p.name;
}

Player implementation

#include "Player.h"
#include <iostream>

void Player::addProperty(Property p)
{
    ownedProperties.push_back(p);
}

And finally main

#include "Player.h"
#include "Space.h"
#include "Property.h"

int main()
{
    Player p{};
    Property prop{};
    prop.run(p);
    system("pause");
}

Every time this is run I get a slew of errors, I'm sure it's got to do something with the circular include logic, with player including property, and property including space, which includes player. But, I don't see a workaround considering #include is needed to know how everything is defined isn't? Or are these errors referring to something else?

Body:
You have a circular include problem. Player includes Property which includes Space which includes Player again.

You can break the circle by not including Player.h in Space.h and only forward declare the class

#pragma once

class Player;

class Space
{
public:
    virtual void run(Player&) = 0;
};


问:
webix dynamic loading via php

Webix DataTable

I have it reading from a php script, but it only ever grabs the first dataset.  The php script accepts &page= [current page] and &size= [number of records]
I can only get it to pagify if i give all the records to it. (which won't work because thats about 1 gig lol.

Here is an example of the data. [i've limited it to 2 results]

```<code>{
"count": 84,
"count_filtered": 84,
"rows": [
    {
        "id": 1,
        "accountName": "test",
        "status": 2,
        "notes": null,
        "globalIframe": null,
        "globalPostback": null,
        "postBackDelayMS": 0,
        "streetAddress1": null,
        "streetAddress2": null,
        "postalCode": null,
        "city": null,
        "countryCode": null,
        "stateProvince": null,
        "accountManager": 1,
        "paymentCycle": 0,
        "minimumPayment": 100,
        "paymentType": 0,
        "paymentDetails": null,
        "created_at": "2017-12-02 19:03:41",
        "updated_at": "2017-12-02 19:03:41"
    },
    {
        "id": 2,
        "accountName": "ta",
        "status": 2,
        "notes": null,
        "globalIframe": null,
        "globalPostback": null,
        "postBackDelayMS": 0,
        "streetAddress1": null,
        "streetAddress2": null,
        "postalCode": null,
        "city": null,
        "countryCode": null,
        "stateProvince": null,
        "accountManager": 1,
        "paymentCycle": 0,
        "minimumPayment": 100,
        "paymentType": 0,
        "paymentDetails": null,
        "created_at": "2017-12-02 19:07:49",
        "updated_at": "2017-12-02 19:07:49"
    }
],
"listable": []
</code>```

}

Here is the JS I use to pull that data into the webix data table.

```<code>var datatable = webix.ui({
    view:"datatable",
    container:"dataTable",
    datafetch:20,
    datathrottle: 500,
    loadahead:100,
    autoheight:true,
    autowidth:true,
    yCount:10,
    autoConfig:true,
    columns:[
{ id:"accountName",    header:"Affiliate Name",  width:tableWidth}
],
on:{
    onBeforeLoad:function(){
        this.showOverlay("Loading...");
    },
    onAfterLoad:function(){
        this.hideOverlay();
    }
},

url:function(details){
    return webix.ajax("/affiliates/data?1").then(function(data){
        var js = data.json();
        var new_js = [];

        for (key in js['rows']){
            new_js.push({
                id:js['rows'][key].id,
                accountName:js['rows'][key].accountName
            });

        };

        return new_js;
    })
},
navigation:"true",
pager:{
    container:"dataPager",
    size:10,
    group:4

}
});

datatable.attachEvent("onDataRequest", function(start, count, callback){     //count
    var view = this;
    console.log("GETTING DATA");
    webix.ajax().get("/affiliates/data?size=10&page="+start/10).then(function(data){
        console.log(data);

    this.parse(data.json());
     var js = data.json();
    var new_js = [];

    for (key in js['rows']){
        new_js.push({
            id:js['rows'][key].id,
            accountName:js['rows'][key].accountName
        });

    };
    return new_js;
})
    return false;
})
</code>```

I've spent about a week trying to figure this out, so be gentle.
Thanks in advance.

答:
So I solved it.

```<code>var datatable = webix.ui({
    view:"datatable",
    container:"dataTable",
    datafetch:25,
    datathrottle: 500,
    loadahead:0,
    autoheight:true,
    autowidth:true,
    yCount:25,
    autoConfig:true,
    columns:[
{ id:"accountName",    header:"Affiliate Name",  width:tableWidth, sort:"server"}
],
on:{
    onBeforeLoad:function(){
        this.showOverlay("Loading...");
    },
    onAfterLoad:function(){
        this.hideOverlay();
    }
},
url:'/affiliates/webixdata',
navigation:"true",
pager:{
    container:"dataPager",
    size:25

}
});
</code>```

Then I changed the controller to match the server side response of
https://docs.webix.com/desktop__plain_dynamic_loading.html#serversideresponse

This works better than the documented webix promise style function to manipulate the data in JS prior to it parsing.

Title: webix dynamic loading via php

Body:
Webix DataTable

I have it reading from a php script, but it only ever grabs the first dataset.  The php script accepts &page= [current page] and &size= [number of records]
I can only get it to pagify if i give all the records to it. (which won't work because thats about 1 gig lol.

Here is an example of the data. [i've limited it to 2 results]

{
"count": 84,
"count_filtered": 84,
"rows": [
    {
        "id": 1,
        "accountName": "test",
        "status": 2,
        "notes": null,
        "globalIframe": null,
        "globalPostback": null,
        "postBackDelayMS": 0,
        "streetAddress1": null,
        "streetAddress2": null,
        "postalCode": null,
        "city": null,
        "countryCode": null,
        "stateProvince": null,
        "accountManager": 1,
        "paymentCycle": 0,
        "minimumPayment": 100,
        "paymentType": 0,
        "paymentDetails": null,
        "created_at": "2017-12-02 19:03:41",
        "updated_at": "2017-12-02 19:03:41"
    },
    {
        "id": 2,
        "accountName": "ta",
        "status": 2,
        "notes": null,
        "globalIframe": null,
        "globalPostback": null,
        "postBackDelayMS": 0,
        "streetAddress1": null,
        "streetAddress2": null,
        "postalCode": null,
        "city": null,
        "countryCode": null,
        "stateProvince": null,
        "accountManager": 1,
        "paymentCycle": 0,
        "minimumPayment": 100,
        "paymentType": 0,
        "paymentDetails": null,
        "created_at": "2017-12-02 19:07:49",
        "updated_at": "2017-12-02 19:07:49"
    }
],
"listable": []

}

Here is the JS I use to pull that data into the webix data table.

var datatable = webix.ui({
    view:"datatable",
    container:"dataTable",
    datafetch:20,
    datathrottle: 500,
    loadahead:100,
    autoheight:true,
    autowidth:true,
    yCount:10,
    autoConfig:true,
    columns:[
{ id:"accountName",    header:"Affiliate Name",  width:tableWidth}
],
on:{
    onBeforeLoad:function(){
        this.showOverlay("Loading...");
    },
    onAfterLoad:function(){
        this.hideOverlay();
    }
},

url:function(details){
    return webix.ajax("/affiliates/data?1").then(function(data){
        var js = data.json();
        var new_js = [];

        for (key in js['rows']){
            new_js.push({
                id:js['rows'][key].id,
                accountName:js['rows'][key].accountName
            });

        };

        return new_js;
    })
},
navigation:"true",
pager:{
    container:"dataPager",
    size:10,
    group:4

}
});

datatable.attachEvent("onDataRequest", function(start, count, callback){     //count
    var view = this;
    console.log("GETTING DATA");
    webix.ajax().get("/affiliates/data?size=10&page="+start/10).then(function(data){
        console.log(data);

    this.parse(data.json());
     var js = data.json();
    var new_js = [];

    for (key in js['rows']){
        new_js.push({
            id:js['rows'][key].id,
            accountName:js['rows'][key].accountName
        });

    };
    return new_js;
})
    return false;
})

I've spent about a week trying to figure this out, so be gentle.
Thanks in advance.

Body:
So I solved it.

var datatable = webix.ui({
    view:"datatable",
    container:"dataTable",
    datafetch:25,
    datathrottle: 500,
    loadahead:0,
    autoheight:true,
    autowidth:true,
    yCount:25,
    autoConfig:true,
    columns:[
{ id:"accountName",    header:"Affiliate Name",  width:tableWidth, sort:"server"}
],
on:{
    onBeforeLoad:function(){
        this.showOverlay("Loading...");
    },
    onAfterLoad:function(){
        this.hideOverlay();
    }
},
url:'/affiliates/webixdata',
navigation:"true",
pager:{
    container:"dataPager",
    size:25

}
});

Then I changed the controller to match the server side response of
https://docs.webix.com/desktop__plain_dynamic_loading.html#serversideresponse

This works better than the documented webix promise style function to manipulate the data in JS prior to it parsing.


问:
SQL Server: How to get averages of Top (n) and Bottom (n) records
I have a table of scores:

```<code>Student ¦ Score
  A     ¦ 23.5
  B     ¦ 34.9
</code>```

How to get Average of ALL, top 15% and Bottom 15% like this:

```<code>Average ¦ top15Avg ¦ bottom15Avg
</code>```

Thanks.

答:
You first calculate how many rows that 15% would be.
Then you can do the selects and averages like this:</p>

```<code>declare @pct int, @all float, @top float, @bottom float
select  @pct = 0.15 * COUNT(*) from Students

select @all = AVG(score) from Students
select @top = AVG(score) from (select top (@pct) score from Students order by score desc)
select @bottom = AVG(score) as 'bottom15Avg' from (select top (@pct) score from Students order by score asc)
select @all as 'Average', @top as 'top15Avg', @bottom  as 'bottom15Avg'
</code>```

Body:
I have a table of scores:

Student ¦ Score
  A     ¦ 23.5
  B     ¦ 34.9

How to get Average of ALL, top 15% and Bottom 15% like this:

Average ¦ top15Avg ¦ bottom15Avg

Thanks.

Body:
You first calculate how many rows that 15% would be.
Then you can do the selects and averages like this:

declare @pct int, @all float, @top float, @bottom float
select  @pct = 0.15 * COUNT(*) from Students

select @all = AVG(score) from Students
select @top = AVG(score) from (select top (@pct) score from Students order by score desc)
select @bottom = AVG(score) as 'bottom15Avg' from (select top (@pct) score from Students order by score asc)
select @all as 'Average', @top as 'top15Avg', @bottom  as 'bottom15Avg'


问:
how to make checkbox checked work
In my project, $('#cenDiv').html(data) can work successfully in ajax. Then I want to click the checkbox of selAllAttId, and do something;

If I use onclick="selAllAtt()", and selAllAtt() method can be called successfully, but $(this).attr("checked") became to be true always after finishing the selAllAtt() method, so $(this).attr("checked") is always false and alert("checked") always can not work.

So I want to change another way with $('#selAllAttId').on("change",function(){}) But unlucky, alert("test) can no work. Who can help me?

Here is js code:

```<code><script>
$(document).ready(function()
{
 $('#selAllAttId').on("change",function(){
  alert("test");//can not work
  });
});

function corpAnn()
{
 $.ajax({
        dataType:'html',
        type:"POST",
        url:"oat.php",
        data: {oaAnn:oaAnn},
        success:function(data)
        {
            $('#cenDiv').html(data);
        }
      });
}

 function selAllAtt(){
  alert("checkbox");
  var xzyId=document.getElementById('xzyId');//fetch other table id
  var checked=xzyId.getElementsByTagName('input');//fetch all table checkbox successfully
  if($(this).attr("checked"))//always false.
  {
    alert("checked");
    for(i=0;i<checked.length;i++)
    {
      checked[i].checked=true;
    }
  }
  else
  {
   alert("delete");
   for(i=0;i<checked.length;i++)
   {
    checked[i].checked=false;
   }
  }
});
</script>

<div id="cenDiv"></div>
</code>```

The code of oat.php is:

```<code> echo '<td  style="color:Maroon" bgcolor="#888888">
       <input type="checkbox" id="selAllAttId" onclick="selAllAtt()">
       <b>Num</b>
       </td>';
</code>```

答:
You can use the native HTML node like this:</p>

```<code>var checkbox = document.getElementById('selAllAttId');
if(checkbox.checked)
{
  // do something
}else{
 // do something else
}
</code>```

Title: how to make checkbox checked work

Body:
In my project, $('#cenDiv').html(data) can work successfully in ajax. Then I want to click the checkbox of selAllAttId, and do something;

If I use onclick="selAllAtt()", and selAllAtt() method can be called successfully, but $(this).attr("checked") became to be true always after finishing the selAllAtt() method, so $(this).attr("checked") is always false and alert("checked") always can not work.

So I want to change another way with $('#selAllAttId').on("change",function(){}) But unlucky, alert("test) can no work. Who can help me?

Here is js code:

The code of oat.php is:

 echo '
       <input type="checkbox" id="selAllAttId" onclick="selAllAtt()">
       Num
       	';

Body:
You can use the native HTML node like this:

var checkbox = document.getElementById('selAllAttId');
if(checkbox.checked)
{
  // do something
}else{
 // do something else
}


问:
Running Bigquery query uncached using Python API
Hi I am using BigQuery and with its Python API submitting Queries to get results. I am using the method - bqclient.query("PASS THE QUERY") to execute the query programmatically. I am trying to do a performance test but BigQuery returns cached results. Is there a way I can set cache = False in the Python API while calling the bqclient.query method. Through the BigQuery documentation I have see that we can set useQueryCache property to false, but am not sure where to set it.

Current Code

```<code>job_config = bigquery.QueryJobConfig()
job_config.use_query_cache = False
query_job = bigquery.query(select_query, job_config = job_config)
</code>```

query represents the query that I want to run.

Thank you

答:
You need to set useQueryCache. See here for more info. Not the lower case underscore format:

```<code>[..]
QUERY = ('SELECT ..')
job_config = bigquery.QueryJobConfig()
job_config.use_query_cache = False
query_job = client.query(QUERY, job_config=job_config)
[..]
</code>```

Body:
Hi I am using BigQuery and with its Python API submitting Queries to get results. I am using the method - bqclient.query("PASS THE QUERY") to execute the query programmatically. I am trying to do a performance test but BigQuery returns cached results. Is there a way I can set cache = False in the Python API while calling the bqclient.query method. Through the BigQuery documentation I have see that we can set useQueryCache property to false, but am not sure where to set it.

Current Code

job_config = bigquery.QueryJobConfig()
job_config.use_query_cache = False
query_job = bigquery.query(select_query, job_config = job_config)

query represents the query that I want to run.

Thank you

Body:
You need to set useQueryCache. See here for more info. Not the lower case underscore format:

[..]
QUERY = ('SELECT ..')
job_config = bigquery.QueryJobConfig()
job_config.use_query_cache = False
query_job = client.query(QUERY, job_config=job_config)
[..]


问:
Cassandra and cleaning old data with counter type
So I know that TTL is not available for counters because of design reasons and I've read https://issues.apache.org/jira/browse/CASSANDRA-2103 as well as some other SO questions regarding this but there seems to be no clear answer(unless I am missing something which is entirely plausible):

How do we elegantly handle the expiration of counters in Cassandra?

Example use case: page views on a specific day.

For this we might have a table such as

CREATE TABLE pageviews (page varchar, date varchar, views counter, PRIMARY KEY(page, date));

One year from now the information of how many views we had on one specific day is not very relevant (instead we might have aggregated it into a view/month table or similar) and we don't want unnecessary data hanging around in our db for no reason. Normally we would put a TTL on this and let Cassandra handle it for us - elegant! But since we aren't allowed to use TTL for counter tables this is not an option..

You also cant just run delete from pageviews where date > 'xxxx' since both key must be defined in the where clause.
You would first need to query all the page first then issue individual deletes, which is not scalable.
Is there any proper way of achieving this ?

答:
Its significantly slower, but thats kinda the price if you dont want to manage the expiration yourself - you can use LWTs and actually insert TTL'd columns instead of updating a counter. ie:

```<code>CREATE TABLE pageviews (
  page varchar,
  date timestamp,
  views int,
  PRIMARY KEY(page, date))
WITH compaction = {'class': 'LeveledCompactionStrategy'};
</code>```

To update a page view:

```<code>UPDATE pageviews USING TTL 604800
   SET views = *12*
   WHERE page = '/home' AND date = YYYY-MM-DD
   IF views = *11*
</code>```

if it fails, reread and try again. This can be very slow if high contention, but in that case you can do some batching per app, say only flush updates every 10 seconds or something and increment by more than 1 at a time

To see total in range of dates:

```<code>SELECT sum(views) FROM pageviews WHERE page='/home' and date >= '2017-01-01 00:00:00+0200' AND date <= '2017-01-13 23:59:00+0200'
</code>```

Fastest approach would be to use counters and just have a job during a less busy time that deletes things older than X days.

Another idea if you are Ok with some % error, you can use a single counter per page and use forward decay to "expire" (make insignificant) old view increments, will still need a job to adjust landmark periodically though. This will not be as useful for looking at ranges though and will only give you an estimate of "total so far".

Body:
Its significantly slower, but thats kinda the price if you dont want to manage the expiration yourself - you can use LWTs and actually insert TTL'd columns instead of updating a counter. ie:

CREATE TABLE pageviews (
  page varchar,
  date timestamp,
  views int,
  PRIMARY KEY(page, date))
WITH compaction = {'class': 'LeveledCompactionStrategy'};

To update a page view:

UPDATE pageviews USING TTL 604800
   SET views = *12*
   WHERE page = '/home' AND date = YYYY-MM-DD
   IF views = *11*

if it fails, reread and try again. This can be very slow if high contention, but in that case you can do some batching per app, say only flush updates every 10 seconds or something and increment by more than 1 at a time

To see total in range of dates:

SELECT sum(views) FROM pageviews WHERE page='/home' and date >= '2017-01-01 00:00:00+0200' AND date <= '2017-01-13 23:59:00+0200'

Fastest approach would be to use counters and just have a job during a less busy time that deletes things older than X days.

Another idea if you are Ok with some % error, you can use a single counter per page and use forward decay to "expire" (make insignificant) old view increments, will still need a job to adjust landmark periodically though. This will not be as useful for looking at ranges though and will only give you an estimate of "total so far".


问:
SQL condition: (A=B AND C LIKE %D%) OR (A LIKE %B% AND C=D)
I've got a table of first names and last names.

I'm trying to make a jQuery instant search on an input, in order to find very quickly and precisely a person in a huge list of people.

When the first word is entered in the input, it might be the first name or the last name.

I do this : SELECT * FROM myTable WHERE firstName LIKE %content% OR lastName LIKE %content%

When two words are entered, it might be:
* the full firstname and a bit of the lastname
* the full lastname and a bit of the firstame

So I tried this query : SELECT * FROM myTable WHERE (firstName = content1 AND lastName LIKE %content2%) OR ( lastName = content1 AND firstName LIKE %content2%)

Unfortunately parenthesis seems to do nothing, and the query is not interpreted this way, I've got a lot of results, basically produced by the two LIKE %% condition

Anyone had deal with this before and could give me a hand?

Thanx

答:
```<code>SELECT * FROM myTable WHERE
    (firstName = 'content1' AND lastName LIKE content2%)
OR
    (lastName = 'content1' AND firstName LIKE content2%)
</code>```


问:
How can objects access attributes of the class in which they are contained?
Let's imagine I have a code that simulate the working of a country education system. This country contain Cities, which contain Schools, which contain Classes, which contain Students. I use a global singleton called CountryInformation that all classes (City, School, Class and Students) are accessing.

I would like to expand my code to consider several countries. Each country need their own CountryInformation, therefore CountryInformation is not a singleton anymore. I would like that each elements contained in a given Country can access to the countryInformation associated to their country. How can I do that?

A simplified version of the problem is to consider that below is my current code

```<code>int info = 3;

class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:
  City city;
  void callFoo(){this->city.foo();}
};

int main()
{
  Country C;
  C.callFoo();
}
</code>```

and I would now like to have something like

```<code>class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:
  City city;
  int info;
  void callFoo(){this->city.foo();}
  Country(int i):info(i){}
};

int main()
{
  std::vector<Country> countries;
  Country C1(0);
  Country C2(0);
  countries.push_back(C1);
  countries.push_back(C2);
  countries[0].callFoo();
  countries[1].callFoo();
}
</code>```

but the above code does not compile as the City object in a given Country does not have access to the attribute of the Country object.

I have been considering friendship and nested classes but I fail to wrap my head around how to give this access.

EDIT

I would like to avoid the need of every City, School and Student to carry a pointer around. A pointer is typically 4 to 8 bytes and a Studentis typically 8 bytes. So, doing so would double the RAM need.

答:
Your classes are not "nested;" one class simply has the other classes as members. City objects can only communicate with Country objects via the public API. However, actual nested classes, or inner classes, are able to access the private variables of the outer class:

```<code>class Country
{
  class City
  {
  public:
    City(Country& c) : country(c) {}
    void foo() {
      country.info = 1;
    }
  private:
    Country& country;
  };
  int info;
};
</code>```

Either way, you will have to explicitly pass the Country object to the City object.

Body:
Let's imagine I have a code that simulate the working of a country education system. This country contain Cities, which contain Schools, which contain Classes, which contain Students. I use a global singleton called CountryInformation that all classes (City, School, Class and Students) are accessing.

I would like to expand my code to consider several countries. Each country need their own CountryInformation, therefore CountryInformation is not a singleton anymore. I would like that each elements contained in a given Country can access to the countryInformation associated to their country. How can I do that?

A simplified version of the problem is to consider that below is my current code

int info = 3;

class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:
  City city;
  void callFoo(){this->city.foo();}
};

int main()
{
  Country C;
  C.callFoo();
}

and I would now like to have something like

class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:
  City city;
  int info;
  void callFoo(){this->city.foo();}
  Country(int i):info(i){}
};

int main()
{
  std::vector<Country> countries;
  Country C1(0);
  Country C2(0);
  countries.push_back(C1);
  countries.push_back(C2);
  countries[0].callFoo();
  countries[1].callFoo();
}

but the above code does not compile as the City object in a given Country does not have access to the attribute of the Country object.

I have been considering friendship and nested classes but I fail to wrap my head around how to give this access.

EDIT

I would like to avoid the need of every City, School and Student to carry a pointer around. A pointer is typically 4 to 8 bytes and a Studentis typically 8 bytes. So, doing so would double the RAM need.

Body:
Your classes are not "nested;" one class simply has the other classes as members. City objects can only communicate with Country objects via the public API. However, actual nested classes, or inner classes, are able to access the private variables of the outer class:

class Country
{
  class City
  {
  public:
    City(Country& c) : country(c) {}
    void foo() {
      country.info = 1;
    }
  private:
    Country& country;
  };
  int info;
};

Either way, you will have to explicitly pass the Country object to the City object.


问:
htaccess <Directory> deny from all apache2 ubuntu
How can I prevent direct URL access for files and folders on apache web server ?

lets say I have folder like

mysite.me/img
that folder contains a lot of files like jpg php pdf mp4 etc...

How to prevent surfers from direct accessing those files and folders inside img folder from browser URL ?
i'm on ubuntu server and using :  Apache/2.4.18
i try to add some .htaccess file to my folder but din;t work
thank you

答:
You should enable the mod_rewrite module on apache first. To enable the module on Ubuntu:

```<code>sudo a2enmod rewrite
sudo service apache2 restart
</code>```

After that, set the directive AllowOverride of the directory, has the minimum configuration to AllowOverride FileInfo Options. You may find this directive in the file /etc/apache2/apache2.conf, <Directory> block.

Then, update your .htaccess as follows, all the traffic will route to index.php

```<code><IfModule mod_rewrite.c>

    RewriteEngine on
    RewriteRule ^(.*) index.php?route=$1 [QSA,L]

</IfModule>
</code>```

Body:
You should enable the mod_rewrite module on apache first. To enable the module on Ubuntu:

sudo a2enmod rewrite
sudo service apache2 restart

After that, set the directive AllowOverride of the directory, has the minimum configuration to AllowOverride FileInfo Options. You may find this directive in the file /etc/apache2/apache2.conf, <Directory> block.

Then, update your .htaccess as follows, all the traffic will route to index.php

<IfModule mod_rewrite.c>

    RewriteEngine on
    RewriteRule ^(.*) index.php?route=$1 [QSA,L]

</IfModule>


答:
For positive integers, the fastest sort is known as abacus sort- it's O(n)

http://en.wikipedia.org/wiki/Abacus_sort

If you only have a very few items, then it's unlikely that you will notice any performance difference from choosing any particular algorithm.

Title: What is the fastest sorting algorithm for a small number of integers?

Body: I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.


问:
Register an instance of a service in Prism.Unity which relies on another service
I have an authentification service, that I register in my Unity Container like so:

```<code>Container.RegisterInstance<IAuthenticationService>(new AuthenticationService());
</code>```

My problem is that my AuthentificationService relies on INavigationService, and its constructor takes this as an argument:

```<code>public AuthenticationService(INavigationService navigationService)
</code>```

From my understanding, the Unity Container is responsible for injecting the INavigationService implementation. But in this case, I am providing the AuthenticationService instance, so how can I tell Unity to inject the INavigationService in my AuthentificationService implementation?

答:
What you are trying to do is unsupported. In order for navigation to work properly Prism's NavigationService requires an understanding of the current Page. The ViewModelLocator handles this and injects an appropriate instance of the Service.

A better way to handle this scenario is to return an Authentication result, and make a determination of how to handle that result in your ViewModel where you can use a properly constructed instance of INavigationService.

Body:
I have an authentification service, that I register in my Unity Container like so:

Container.RegisterInstance<IAuthenticationService>(new AuthenticationService());

My problem is that my AuthentificationService relies on INavigationService, and its constructor takes this as an argument:

public AuthenticationService(INavigationService navigationService)

From my understanding, the Unity Container is responsible for injecting the INavigationService implementation. But in this case, I am providing the AuthenticationService instance, so how can I tell Unity to inject the INavigationService in my AuthentificationService implementation?


问:
How can I get a w3-cell to not auto adjust?
Working on a HTML page that requires me to have two elements side by side to replicate a 50/50 scenario sort of thing. I am using w3.css to help me since I am not so familiar with HTML/CSS.

My code is below for the section. So when the AWords/BWords grows too big, the cell grows so it does not match the other half. What I'm trying to ask is how can I implement a uniformly increase in size? So that both halves match each other, and the halfway mark stays in the middle of the screen?

```<code><div class="Options w3-cell-row w3-center" style="width:75%;margin: 0 auto;">
        <div class="OptionA w3-container w3-cell" style="background-color: #EA4D63;border-style: solid;border-top-left-radius:25px;border-bottom-left-radius: 25px;">
            <div class="w3-container">
                <p class="AWords w3-xxlarge"></p>
            </div>
            <div class="w3-container">
                <p class="AVotes w3-large"></p>
            </div>
        </div>
        <div class="OptionB w3-container w3-cell" style="background-color:#2BA9E5;border-style: solid;border-top-right-radius: 25px;border-bottom-right-radius: 25px;">
            <div class="w3-container">
                <p class="BWords w3-xxlarge"></p>
            </div>
            <div class="w3-container">
                <p class="BVotes w3-large"></p>
            </div>
        </div>
    </div>
</code>```

JSFiddle of what the code currently does

答:
Assuming by the 'halfway' mark you mean the line that divides the two elements vertically, this arises due to the fact that W3 uses a table-based layout. Tables automatically expand to contain their contents.

As such, in order to ensure that both elements occupy the same amount of horizontal space, you simply give your cells a fixed width. This can be done by targeting .w3-cell:

```<code>.w3-cell {
    width: 200px;
}
</code>```

And can be seen in the following:

.w3-cell {
  width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>

<div class="Options w3-cell-row w3-center" style="width:75%;margin: 0 auto;">
  <div class="OptionA w3-container w3-cell" style="background-color: #EA4D63;border-style: solid;border-top-left-radius:25px;border-bottom-left-radius: 25px;">
    <div class="w3-container">
      <p class="AWords w3-xxlarge">Idk what to do</p>
    </div>
    <div class="w3-container">
      <p class="AVotes w3-large"></p>
    </div>
  </div>
  <div class="OptionB w3-container w3-cell" style="background-color:#2BA9E5;border-style: solid;border-top-right-radius: 25px;border-bottom-right-radius: 25px;">
    <div class="w3-container">
      <p class="BWords w3-xxlarge">If this side gets too big it looks weird</p>
    </div>
    <div class="w3-container">
      <p class="BVotes w3-large"></p>
    </div>
  </div>
</div></code>```

I've also created a Fiddle showcasing this here.

Note that if you want to continue to use inline styles everywhere, you'll have to apply this to both
 elements with this class.

Hope this helps :)

Body:
Working on a HTML page that requires me to have two elements side by side to replicate a 50/50 scenario sort of thing. I am using w3.css to help me since I am not so familiar with HTML/CSS.

My code is below for the section. So when the AWords/BWords grows too big, the cell grows so it does not match the other half. What I'm trying to ask is how can I implement a uniformly increase in size? So that both halves match each other, and the halfway mark stays in the middle of the screen?

JSFiddle of what the code currently does

Body:
Assuming by the 'halfway' mark you mean the line that divides the two elements vertically, this arises due to the fact that W3 uses a table-based layout. Tables automatically expand to contain their contents.

As such, in order to ensure that both elements occupy the same amount of horizontal space, you simply give your cells a fixed width. This can be done by targeting .w3-cell:

.w3-cell {
    width: 200px;
}

And can be seen in the following:

.w3-cell {
  width: 200px;
}

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>

<div class="Options w3-cell-row w3-center" style="width:75%;margin: 0 auto;">
  <div class="OptionA w3-container w3-cell" style="background-color: #EA4D63;border-style: solid;border-top-left-radius:25px;border-bottom-left-radius: 25px;">
    <div class="w3-container">
      <p class="AWords w3-xxlarge">Idk what to do</p>
    </div>
    <div class="w3-container">
      <p class="AVotes w3-large"></p>
    </div>
  </div>
  <div class="OptionB w3-container w3-cell" style="background-color:#2BA9E5;border-style: solid;border-top-right-radius: 25px;border-bottom-right-radius: 25px;">
    <div class="w3-container">
      <p class="BWords w3-xxlarge">If this side gets too big it looks weird</p>
    </div>
    <div class="w3-container">
      <p class="BVotes w3-large"></p>
    </div>
  </div>
</div>

I've also created a Fiddle showcasing this here.

Note that if you want to continue to use inline styles everywhere, you'll have to apply this to both <div> elements with this class.

Hope this helps :)