问:
Apply font family file effect at a time in whole application
I have font file roboto in my asset folder. I want to change the normal font to roboto at once . If i use typeface like below:

```<code> TextView forgotPwd = (TextView) findViewById(R.id.tv_forgot_pwd_text);

     Typeface type = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
            forgotPwd.setTypeface(type);
</code>```

Then i have to check and give the same code for every text view manually.But my need is if i set Typeface or any thing it should reflect in the whole application's text or text view.

Now i used

```<code> public class MyApp extends Application {
              @Override
              public void onCreate() {
                 super.onCreate();
                TypefaceUtil.overrideFont(getApplicationContext(), "Roboto", "fonts/Roboto-Regular.ttf");
              }
              }

I used application class and also took the help of some custom class but its not working .
</code>```

public class TypefaceUtil {

```<code>public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

    final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Map<String, Typeface> newMap = new HashMap<String, Typeface>();
        newMap.put("Roboto", customFontTypeface);
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField("sSystemFontMap");
            staticField.setAccessible(true);
            staticField.set(null, newMap);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } else {
        try {
            final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
            defaultFontTypefaceField.setAccessible(true);
            defaultFontTypefaceField.set(null, customFontTypeface);
        } catch (Exception e) {
            Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
        }
    }
}
</code>```

}

now style.xml is

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="colorControlNormal">#FFFFFF</item>
        <item name="colorControlActivated">#FFFFFF</item>
        <item name="android:textColorHint">@color/black</item>
        <item name="android:typeface">Roboto</item>
    </style>
</code>```

And in the manifest:

```<code>    android:name="pkgname.MyApp"
</code>```

But still i am not getting the reflection in my application please let me know that where i am missing. And guide me

答:
You can Calligraphy.

It's pretty easy to use.

```<code>CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("Roboto-Regular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
</code>```

Create a BaseActivity or add this to all your activities, your call

```<code>@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
</code>```

Body:
I have font file roboto in my asset folder. I want to change the normal font to roboto at once . If i use typeface like below:

 TextView forgotPwd = (TextView) findViewById(R.id.tv_forgot_pwd_text);

     Typeface type = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
            forgotPwd.setTypeface(type);

Then i have to check and give the same code for every text view manually.But my need is if i set Typeface or any thing it should reflect in the whole application's text or text view.

Now i used

 public class MyApp extends Application {
              @Override
              public void onCreate() {
                 super.onCreate();
                TypefaceUtil.overrideFont(getApplicationContext(), "Roboto", "fonts/Roboto-Regular.ttf");
              }
              }

I used application class and also took the help of some custom class but its not working .

public class TypefaceUtil {

public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

    final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Map<String, Typeface> newMap = new HashMap<String, Typeface>();
        newMap.put("Roboto", customFontTypeface);
        try {
            final Field staticField = Typeface.class
                    .getDeclaredField("sSystemFontMap");
            staticField.setAccessible(true);
            staticField.set(null, newMap);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } else {
        try {
            final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
            defaultFontTypefaceField.setAccessible(true);
            defaultFontTypefaceField.set(null, customFontTypeface);
        } catch (Exception e) {
            Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
        }
    }
}

}

now style.xml is

And in the manifest:

    android:name="pkgname.MyApp"

But still i am not getting the reflection in my application please let me know that where i am missing. And guide me

Body:
You can Calligraphy.

It's pretty easy to use.

CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("Roboto-Regular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()

Create a BaseActivity or add this to all your activities, your call

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}


来源: stackexchange

问:
NodeJS mockgoose save model does not seem to work
Trying to unit test my small api, I need to test the save errors and successes (already signed up, etc).

Currently here is my code:
models/auth.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var AuthSchema = Schema({
    id: String,
    user: String,
    password: String,
    origin: String,
});

//Export model
module.exports = mongoose.model('user', AuthSchema);
</code>```

tests/api.test.js

```<code>const chai = require('chai');
const should  = chai.should;
const expect = chai.expect;
const assert = chai.assert;
/ Node Http Mocks
var httpMocks = require('node-mocks-http');

var util = require('util'),
    express = require('express'),
    bodyParser = require('body-parser'),
    validator = require('express-validator'),
    app = express();

var authController = require('../controllers/auth');

describe("Test AUTH Calls ", function() {
    var mongoHost = 'mongodb://localhost:27017/testingDB';

    // model
    var authModel = require('../models/auth.js');

    var Mongoose = require('mongoose').Mongoose;
    var mongoose = new Mongoose();

    var Mockgoose = require('mockgoose').Mockgoose;
    var mockgoose = new Mockgoose(mongoose);

    // Generate a v1 UUID (time-based)
    const uuidV1 = require('uuid/v1');

    before(function(done) {
        mockgoose.prepareStorage().then(function() {
            mongoose.Promise = global.Promise;
            mongoose.connect(mongoHost, {
                keepAlive: true,
                reconnectTries: Number.MAX_VALUE,
                useMongoClient: true
            },function(err) {
                done(err);
            });
            mongoose.connection.on('connected', function(err) {
                if (err) {
                    console.log('Error on DB Connection: ', err);
                } else {
                    console.log('Db Connection opened!');
                }

            });
        });
    });

it("should warn that the user already exists", function(done) {
        var req = httpMocks.createRequest({
            method: 'GET',
            url: '/signup',
            body: {
                'username': 'tricky',
                'password': 'frasier'
            }
        });
        var res = httpMocks.createResponse();

        var userModel = new authModel({
            id: uuidV1(),
            username: req.body.username,
            password: req.body.password
        });

        userModel.save(function(err) {
            if (err) {
                console.log('Error while registering a user.', err.name);
            } else {
                console.log('User saved successfully.');
            }
        });

        var userN = req.body.username;

        // Check if already exists
        var myUser = null;
        authModel.findOne({
            username: userN,
        }, function(err, user) {
            if (err) {
                console.log('Error while verifying a user.', err.name);
            }
            if (user) {
                console.log('User exists.');
                myUser = user;
            }

        });

        authController.signup(req, res); // Will fail on user existing
        assert.equal(res.statusCode, 401);
        done();
    });

});
</code>```

Now the issue is that the first console.log says 'DB Connection opened!', and if I do a console log of the model (userModel) after filled in, it logs correctly, but my issue is on save. I don't know if it saves or not but no console log from inside shows, failure or success.

Can anyone tell me what I am doing wrong ?

Thank you

答:
To me it worked by changing this:

```<code>var Mongoose = require('mongoose').Mongoose;
var mongoose = new Mongoose();

var Mockgoose = require('mockgoose').Mockgoose;
var mockgoose = new Mockgoose(mongoose);
</code>```

with

```<code>var mongoose = require('mongoose');
var { Mockgoose } = require('mockgoose');

var mockgoose = new Mockgoose(mongoose);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to unit test my small api, I need to test the save errors and successes (already signed up, etc).

Currently here is my code:
models/auth.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var AuthSchema = Schema({
    id: String,
    user: String,
    password: String,
    origin: String,
});

//Export model
module.exports = mongoose.model('user', AuthSchema);

tests/api.test.js

const chai = require('chai');
const should  = chai.should;
const expect = chai.expect;
const assert = chai.assert;
/ Node Http Mocks
var httpMocks = require('node-mocks-http');

var util = require('util'),
    express = require('express'),
    bodyParser = require('body-parser'),
    validator = require('express-validator'),
    app = express();

var authController = require('../controllers/auth');

describe("Test AUTH Calls ", function() {
    var mongoHost = 'mongodb://localhost:27017/testingDB';

    // model
    var authModel = require('../models/auth.js');

    var Mongoose = require('mongoose').Mongoose;
    var mongoose = new Mongoose();

    var Mockgoose = require('mockgoose').Mockgoose;
    var mockgoose = new Mockgoose(mongoose);

    // Generate a v1 UUID (time-based)
    const uuidV1 = require('uuid/v1');

    before(function(done) {
        mockgoose.prepareStorage().then(function() {
            mongoose.Promise = global.Promise;
            mongoose.connect(mongoHost, {
                keepAlive: true,
                reconnectTries: Number.MAX_VALUE,
                useMongoClient: true
            },function(err) {
                done(err);
            });
            mongoose.connection.on('connected', function(err) {
                if (err) {
                    console.log('Error on DB Connection: ', err);
                } else {
                    console.log('Db Connection opened!');
                }

            });
        });
    });

it("should warn that the user already exists", function(done) {
        var req = httpMocks.createRequest({
            method: 'GET',
            url: '/signup',
            body: {
                'username': 'tricky',
                'password': 'frasier'
            }
        });
        var res = httpMocks.createResponse();

        var userModel = new authModel({
            id: uuidV1(),
            username: req.body.username,
            password: req.body.password
        });

        userModel.save(function(err) {
            if (err) {
                console.log('Error while registering a user.', err.name);
            } else {
                console.log('User saved successfully.');
            }
        });

        var userN = req.body.username;

        // Check if already exists
        var myUser = null;
        authModel.findOne({
            username: userN,
        }, function(err, user) {
            if (err) {
                console.log('Error while verifying a user.', err.name);
            }
            if (user) {
                console.log('User exists.');
                myUser = user;
            }

        });

        authController.signup(req, res); // Will fail on user existing
        assert.equal(res.statusCode, 401);
        done();
    });

});

Now the issue is that the first console.log says 'DB Connection opened!', and if I do a console log of the model (userModel) after filled in, it logs correctly, but my issue is on save. I don't know if it saves or not but no console log from inside shows, failure or success.

Can anyone tell me what I am doing wrong ?

Thank you

Body:
To me it worked by changing this:

var Mongoose = require('mongoose').Mongoose;
var mongoose = new Mongoose();

var Mockgoose = require('mockgoose').Mockgoose;
var mockgoose = new Mockgoose(mongoose);

with

var mongoose = require('mongoose');
var { Mockgoose } = require('mockgoose');

var mockgoose = new Mockgoose(mongoose);


问:
Problems with package renaming in Mercurial project
I have been using Mercurial for a while in my Java project. I work in a two man team. When I do merges, I find that file renaming has not caused many problems, but package renaming has caused major issues. Is this a known problem? Is there anything I can do?</p>

答:
Are you using the hg commands to do this?
You shouldn't  move files/directories without using hg.

Use hg move to move files/directories or "hg mv --after" to record a name that has already changed before.

ContentLicense: CC BY-SA 2.5


问:
How to sort an int[] only at the indices at which a BitSet of same length is set to true in Java
While it is no problem sorting a continuous sub-array in Java, I have not found any information on how to sort an array only at certain (non-continous) indices, specified by another data structure, eg. a BitSet.

Specifically, given an array such as

```<code>int[] x = {5,1,8,6,7,0,2,3,9,4};
</code>```

and a BitSet specifying the positions to be sorted

```<code>BitSet pos = new BitSet(10);
pos.set(0);
pos.set(2);
pos.set(5);
pos.set(6);
pos.set(9); // i.e. pos = {1,0,1,0,0,1,1,0,0,1}
</code>```

I would like to sort x inline only at the positions at which the mask pos is 1 while ignoring the remaining indices, i.e.

```<code>SortOnIndices(x,pos);
</code>```

Should result in

```<code>x = {0,1,2,6,7,4,5,3,9,8}
</code>```

Is there any efficient way of archiving this without having to implement a custom sorting solution? Can this be done with JAVA 8 streams?

Edit: Corrected use of BitSet in the example.

答:
First of all, BitSet.valueOf(long[]) doesn’t work the way you’re trying to use it. Each element of the long[] array is representing 64 bits rather than a single bit. In fact, turning your 1,0,1,0,0,1,1,0,0,1 representation into a BitSet was the first challenge:

```<code>BitSet pos = BitSet.valueOf(new long[] { Integer.reverse(0b1010011001)>>>22 });
</code>```

Then, we have the problem that every customizable sorting implementation of the Java API works with objects, which would require boxing and representing the source as array or List. The methods provided for primitive types all are fixed to natural order.

Trying to create a List of positions or similar, that maps to the source array on the fly would suffer from the non-random access when finding the right array position induced by the bitset. But the default implementation of List.sort circumvents this by copying the list contents into an array anyway. This even applies to all Stream approaches that make the operation look fluent, but create intermediate arrays behind the scenes (and also support a custom Comparator only for the boxed values).

So when you want to avoid additional memory allocation, none of the builtin sorting facilities will help. The simplest, efficient and memory saving approach would be

```<code>BitSet ordered = new BitSet();
pos.stream().forEach(ix -> ordered.set(x[ix]));
PrimitiveIterator.OfInt it = ordered.stream().iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();
</code>```

But this only works if the source array does not contain negative numbers nor duplicates, like in your example data set.

Lifting these restrictions requires some more efforts and more memory:

```<code>IntSummaryStatistics stats = pos.stream().map(ix -> x[ix]).summaryStatistics();
int min = stats.getMin(), max = stats.getMax();
int[] counts = new int[max-min+1];
pos.stream().forEach(ix -> counts[x[ix]-min]++);
PrimitiveIterator.OfInt it
  = IntStream.rangeClosed(min, max)
             .flatMap(val -> IntStream.range(0, counts[val-min]).map(ix -> val))
             .iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();
</code>```

This variant of counting sort is still O(n), but its memory consumption depends on the difference between the smallest and largest number within the set of numbers to sort. But it’s the best you can get, unless you want to implement your own Quicksort or similar. Or, if the divergence between minimum and maximum is too large, you can resort to let the JRE provided algorithm sort a copy:

```<code>int[] tmp = pos.stream().map(p -> x[p]).toArray();
Arrays.sort(tmp);
PrimitiveIterator.OfInt it = Arrays.stream(tmp).iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();
</code>```

You could even use the statistics from the second variant to use the variant needing less memory

```<code>PrimitiveIterator.OfInt it;
IntSummaryStatistics stats = pos.stream().map(ix -> x[ix]).summaryStatistics();
int min = stats.getMin(), max = stats.getMax();
if(max-min < stats.getCount()) {
    int[] counts = new int[max-min+1];
    pos.stream().forEach(ix -> counts[x[ix]-min]++);
    it = IntStream.rangeClosed(min, max)
                  .flatMap(val -> IntStream.range(0, counts[val-min]).map(ix -> val))
                  .iterator();
}
else {
    int[] tmp = pos.stream().map(p -> x[p]).toArray();
    Arrays.sort(tmp);
    it = Arrays.stream(tmp).iterator();
}
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();
</code>```

Body:
While it is no problem sorting a continuous sub-array in Java, I have not found any information on how to sort an array only at certain (non-continous) indices, specified by another data structure, eg. a BitSet.

Specifically, given an array such as

int[] x = {5,1,8,6,7,0,2,3,9,4};

and a BitSet specifying the positions to be sorted

BitSet pos = new BitSet(10);
pos.set(0);
pos.set(2);
pos.set(5);
pos.set(6);
pos.set(9); // i.e. pos = {1,0,1,0,0,1,1,0,0,1}

I would like to sort x inline only at the positions at which the mask pos is 1 while ignoring the remaining indices, i.e.

SortOnIndices(x,pos);

Should result in

x = {0,1,2,6,7,4,5,3,9,8}

Is there any efficient way of archiving this without having to implement a custom sorting solution? Can this be done with JAVA 8 streams?

Edit: Corrected use of BitSet in the example.

Body:
First of all, BitSet.valueOf(long[]) doesn’t work the way you’re trying to use it. Each element of the long[] array is representing 64 bits rather than a single bit. In fact, turning your 1,0,1,0,0,1,1,0,0,1 representation into a BitSet was the first challenge:

BitSet pos = BitSet.valueOf(new long[] { Integer.reverse(0b1010011001)>>>22 });

Then, we have the problem that every customizable sorting implementation of the Java API works with objects, which would require boxing and representing the source as array or List. The methods provided for primitive types all are fixed to natural order.

Trying to create a List of positions or similar, that maps to the source array on the fly would suffer from the non-random access when finding the right array position induced by the bitset. But the default implementation of List.sort circumvents this by copying the list contents into an array anyway. This even applies to all Stream approaches that make the operation look fluent, but create intermediate arrays behind the scenes (and also support a custom Comparator only for the boxed values).

So when you want to avoid additional memory allocation, none of the builtin sorting facilities will help. The simplest, efficient and memory saving approach would be

BitSet ordered = new BitSet();
pos.stream().forEach(ix -> ordered.set(x[ix]));
PrimitiveIterator.OfInt it = ordered.stream().iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();

But this only works if the source array does not contain negative numbers nor duplicates, like in your example data set.

Lifting these restrictions requires some more efforts and more memory:

IntSummaryStatistics stats = pos.stream().map(ix -> x[ix]).summaryStatistics();
int min = stats.getMin(), max = stats.getMax();
int[] counts = new int[max-min+1];
pos.stream().forEach(ix -> counts[x[ix]-min]++);
PrimitiveIterator.OfInt it
  = IntStream.rangeClosed(min, max)
             .flatMap(val -> IntStream.range(0, counts[val-min]).map(ix -> val))
             .iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();

This variant of counting sort is still O(n), but its memory consumption depends on the difference between the smallest and largest number within the set of numbers to sort. But it’s the best you can get, unless you want to implement your own Quicksort or similar. Or, if the divergence between minimum and maximum is too large, you can resort to let the JRE provided algorithm sort a copy:

int[] tmp = pos.stream().map(p -> x[p]).toArray();
Arrays.sort(tmp);
PrimitiveIterator.OfInt it = Arrays.stream(tmp).iterator();
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();

You could even use the statistics from the second variant to use the variant needing less memory

PrimitiveIterator.OfInt it;
IntSummaryStatistics stats = pos.stream().map(ix -> x[ix]).summaryStatistics();
int min = stats.getMin(), max = stats.getMax();
if(max-min < stats.getCount()) {
    int[] counts = new int[max-min+1];
    pos.stream().forEach(ix -> counts[x[ix]-min]++);
    it = IntStream.rangeClosed(min, max)
                  .flatMap(val -> IntStream.range(0, counts[val-min]).map(ix -> val))
                  .iterator();
}
else {
    int[] tmp = pos.stream().map(p -> x[p]).toArray();
    Arrays.sort(tmp);
    it = Arrays.stream(tmp).iterator();
}
pos.stream().forEachOrdered(ix -> x[ix]=it.next());
assert !it.hasNext();


问:
Error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools

An error occurred when compiling "process.py" on the above site.

python tools/process.py --input_dir data --operation resize --output_dir data2/resize
data/0.jpg -> data2/resize/0.png

Traceback (most recent call last):
  File "tools/process.py", line 235, in <module>
    main()
  File "tools/process.py", line 167, in main
    src = load(src_path)
  File "tools/process.py", line 113, in load
    contents = open(path).read()
  File"/home/user/anaconda3/envs/tensorflow_2/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
```

What is the cause of the error?
Python's version is 3.5.2.

答:
I've come across this thread when suffering the same error, after doing some research I can confirm, this is an error that happens when you try to decode a UTF-16 file with UTF-8.

With UTF-16 the first characther (2 bytes in UTF-16) is a Byte Order Mark (BOM), which is used as a decoding hint and doesn't appear as a character in the decoded string. This means the first byte will be either FE or FF and the second, the other.

Heavily edited after I found out the real answer

ContentLicense: CC BY-SA 4.0

Body:
https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools

An error occurred when compiling "process.py" on the above site.

python tools/process.py --input_dir data --operation resize --output_dir data2/resize
data/0.jpg -> data2/resize/0.png

Traceback (most recent call last):
  File "tools/process.py", line 235, in <module>
    main()
  File "tools/process.py", line 167, in main
    src = load(src_path)
  File "tools/process.py", line 113, in load
    contents = open(path).read()
  File"/home/user/anaconda3/envs/tensorflow_2/lib/python3.5/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

What is the cause of the error?
Python's version is 3.5.2.


问:
Is using a cached "this" faster than "this" when accessing methods of the same object?
if I access this.something multiple times from another method, would it be faster to cache "this" and access something() or should I just use this.something() over and over?</p>

```<code><script type="text/javascript">
var Foo = (function() {
    return {
        something: function() {
            // Do something
        },
        stuff: function(obj) {
            this.something(obj);
            // ...
            this.something(obj);

            /* OR should I cache this? */
            var $that = this;
            $that.something(obj);
            // ...
            $that.something(obj);
        }
    };
}());
</script>
</code>```

答:
I don't see why a variable should be faster than this.

Something that could have been possibly faster but that I found does NOT work is to cache the whole method lookup... e.g. by doing m = object.method; ... m(x,y,z);. This is something that for example in Python works (because of the bound method concept) but that however is not available in Javascript.

The result of a method lookup in Javascript gives you more or less something like what is a method pointer of C++, in other words a function that doesn't know this and so you must provide this yourself it to be able to call it.

The only difference is that in C++ any method that's not declared static will not be callable without providing a this, while in Javascript saving the method lookup may apparently work only for methods that at runtime don't need this perform as expected.

For example var mycos = Math.cos; mycos(0.3); on chrome at least apparently works because cos doesn't need to access Math (not really that surprising after all).

You can get a closure that functionally works as a cached method...

```<code>var cachedfoo = obj.foo;
var foo = function(x, y, z) { return cachedfoo.call(obj, x, y, z); }
...
foo(1,2,3); // this is the same as obj.foo(1,2,3)
</code>```

that could be useful for other reasons, but that IMO it's not going to be faster (it would probably be slower indeed)...

Body:
I don't see why a variable should be faster than this.

Something that could have been possibly faster but that I found does NOT work is to cache the whole method lookup... e.g. by doing m = object.method; ... m(x,y,z);. This is something that for example in Python works (because of the bound method concept) but that however is not available in Javascript.

The result of a method lookup in Javascript gives you more or less something like what is a method pointer of C++, in other words a function that doesn't know this and so you must provide this yourself it to be able to call it.

The only difference is that in C++ any method that's not declared static will not be callable without providing a this, while in Javascript saving the method lookup may apparently work only for methods that at runtime don't need this perform as expected.

For example var mycos = Math.cos; mycos(0.3); on chrome at least apparently works because cos doesn't need to access Math (not really that surprising after all).

You can get a closure that functionally works as a cached method...

var cachedfoo = obj.foo;
var foo = function(x, y, z) { return cachedfoo.call(obj, x, y, z); }
...
foo(1,2,3); // this is the same as obj.foo(1,2,3)

that could be useful for other reasons, but that IMO it's not going to be faster (it would probably be slower indeed)...


问:
UPDATE query doesn't update in C# while it works in Access
I'm trying to update a column when the value in the column is higher as 0, otherwise it INSERTS a new row.

The UPDATE query is tested in Access first and it worked, tried it in C# and it doens't.

Don't know where to look for. Any help/tips?

```<code>Reservation selection = (Reservation)lstbReservations.SelectedItem;
connection.Open();

command.CommandText = @"SELECT Service_Overzicht.OverzichtID, Service.ServiceID, Service.Beschrijving,
                        IIf(Service_Overzicht.Aantal Is Null,0,Service_Overzicht.Aantal) AS Aantal, Service.Prijs, Service.Categorie
                        FROM Service LEFT JOIN (SELECT * FROM Service_Overzicht WHERE OverzichtID = [@waarde])
                        AS OSF ON Service.ServiceID = OSF.ServiceID;";

command.Connection = connection;

command.Parameters.Add(new OleDbParameter("@waarde", OleDbType.Integer));
command.Parameters["@waarde"].Value = selection.Reserveringsnummer;

reader = command.ExecuteReader();
while(reader.Read())
{
    if(reader.GetString(2) == "Douche Muntjes")
    {
        if(reader.GetInt32(3) == 0)
        {
            command1.CommandText = @"INSERT INTO Service_Overzicht (OverzichtID, ServiceID, Aantal) VALUES (@resID, @sID, @aantal)";
        }
        else
        {
            command1.CommandText = @"UPDATE Service_Overzicht
                                    SET Aantal = @aantal
                                    WHERE OverzichtID = @resID AND ServiceID = @sID";
        }

        command1.Connection = connection;

        command1.Parameters.Add(new OleDbParameter("@resID", OleDbType.Integer));
        command1.Parameters["@resID"].Value = selection.Reserveringsnummer;

        command1.Parameters.Add(new OleDbParameter("@sID", OleDbType.Integer));
        command1.Parameters["@sID"].Value = 1;

        command1.Parameters.Add(new OleDbParameter("@aantal", OleDbType.Integer));
        command1.Parameters["@aantal"].Value = nudShower.Value;

        reader1 = command1.ExecuteReader();
        if(reader1.HasRows)
        {
            MessageBox.Show("Something went wrong!");
        }
        else
        {
            MessageBox.Show("Services updated");
        }
    }
</code>```

答:
In OleDb the parameters are not retrieved looking at their name but at their position. You need to put the parameters in the collection following the order in which they appear in the query.

Inverting the order of the fields in the INSERT query allows you to insert the parameters in the same order both for INSERT and UPDATE.

```<code>if(reader.GetInt32(3) == 0)
{
    command1.CommandText = @"INSERT INTO Service_Overzicht
                            (Aantal, OverzichtID, ServiceID)
                            VALUES ( @aantal, @resID, @sID)";
}
else
{
    command1.CommandText = @"UPDATE Service_Overzicht
                            SET Aantal = @aantal
                            WHERE OverzichtID = @resID AND ServiceID = @sID";
}
command1.Parameters.Add("@aantal", OleDbType.Integer).Value = nudShower.Value;
command1.Parameters.Add("@resID", OleDbType.Integer).Value = selection.Reserveringsnummer;
command1.Parameters.Add("@sID", OleDbType.Integer).Value = 1;
command1.Connection = connection;
</code>```

Finally an UPDATE/INSERT/DELETE query is executed using the ExecuteNonQuery call and looking at the return value that represent the number of rows changed.

Calling ExecuteReader also works, because it executes the query passed, but it tries to build an OleDbDataReader to read the supposed returned set of records.

You don't have records to read back with an update query but just a number.

```<code>  int rows = command1.ExecuteNonQuery();
  if(rows != 0)
      ....success....
</code>```

Body:
I'm trying to update a column when the value in the column is higher as 0, otherwise it INSERTS a new row.

The UPDATE query is tested in Access first and it worked, tried it in C# and it doens't.

Don't know where to look for. Any help/tips?

Reservation selection = (Reservation)lstbReservations.SelectedItem;
connection.Open();

command.CommandText = @"SELECT Service_Overzicht.OverzichtID, Service.ServiceID, Service.Beschrijving,
                        IIf(Service_Overzicht.Aantal Is Null,0,Service_Overzicht.Aantal) AS Aantal, Service.Prijs, Service.Categorie
                        FROM Service LEFT JOIN (SELECT * FROM Service_Overzicht WHERE OverzichtID = [@waarde])
                        AS OSF ON Service.ServiceID = OSF.ServiceID;";

command.Connection = connection;

command.Parameters.Add(new OleDbParameter("@waarde", OleDbType.Integer));
command.Parameters["@waarde"].Value = selection.Reserveringsnummer;

reader = command.ExecuteReader();
while(reader.Read())
{
    if(reader.GetString(2) == "Douche Muntjes")
    {
        if(reader.GetInt32(3) == 0)
        {
            command1.CommandText = @"INSERT INTO Service_Overzicht (OverzichtID, ServiceID, Aantal) VALUES (@resID, @sID, @aantal)";
        }
        else
        {
            command1.CommandText = @"UPDATE Service_Overzicht
                                    SET Aantal = @aantal
                                    WHERE OverzichtID = @resID AND ServiceID = @sID";
        }

        command1.Connection = connection;

        command1.Parameters.Add(new OleDbParameter("@resID", OleDbType.Integer));
        command1.Parameters["@resID"].Value = selection.Reserveringsnummer;

        command1.Parameters.Add(new OleDbParameter("@sID", OleDbType.Integer));
        command1.Parameters["@sID"].Value = 1;

        command1.Parameters.Add(new OleDbParameter("@aantal", OleDbType.Integer));
        command1.Parameters["@aantal"].Value = nudShower.Value;

        reader1 = command1.ExecuteReader();
        if(reader1.HasRows)
        {
            MessageBox.Show("Something went wrong!");
        }
        else
        {
            MessageBox.Show("Services updated");
        }
    }

Body:
In OleDb the parameters are not retrieved looking at their name but at their position. You need to put the parameters in the collection following the order in which they appear in the query.

Inverting the order of the fields in the INSERT query allows you to insert the parameters in the same order both for INSERT and UPDATE.

if(reader.GetInt32(3) == 0)
{
    command1.CommandText = @"INSERT INTO Service_Overzicht
                            (Aantal, OverzichtID, ServiceID)
                            VALUES ( @aantal, @resID, @sID)";
}
else
{
    command1.CommandText = @"UPDATE Service_Overzicht
                            SET Aantal = @aantal
                            WHERE OverzichtID = @resID AND ServiceID = @sID";
}
command1.Parameters.Add("@aantal", OleDbType.Integer).Value = nudShower.Value;
command1.Parameters.Add("@resID", OleDbType.Integer).Value = selection.Reserveringsnummer;
command1.Parameters.Add("@sID", OleDbType.Integer).Value = 1;
command1.Connection = connection;

Finally an UPDATE/INSERT/DELETE query is executed using the ExecuteNonQuery call and looking at the return value that represent the number of rows changed.

Calling ExecuteReader also works, because it executes the query passed, but it tries to build an OleDbDataReader to read the supposed returned set of records.

You don't have records to read back with an update query but just a number.

  int rows = command1.ExecuteNonQuery();
  if(rows != 0)
      ....success....


问:
Validate PHP syntax in VIM
I would like to know how if it's possible to validate if a PHP file is valid in VIM without closing VIM every time?

Thank you

答:
You should try a plugin like Neomake. It will show you in the gutter error markers for every PHP syntax errors. Go on the line to see the error itself. You can as well link it to PHP Mess detector and PHP Stan to show you errors and possible improvements in your code.

This combo is very powerful!

In case you are interested I wrote an article how to make a Vim PHP IDE. This is basically a list of essential plugins you should try out! Of course Neomake is part of it.

Title: Validate PHP syntax in VIM


问:
How to Remove Specific object from firebase Realtime Database
How to remove specific object from Firebase DB. I want to remove fine message from champdecay@gmail.com username.

I have tried following code and i got proper object but remove() not works.

```<code>abcd = ref.orderByChild('message').equalTo('fine');
abcd.on('value', function(abcdSnap){
    console.log(abcdSnap.val());
})
</code>```

above Code returns -L-Kl8ctoi5j4TtMWTsc but now how to remove this object. i tried to remove() as follows but not working...

```<code>abcd = ref.orderByChild('message').equalTo('fine').remove();

abcd.on('value', function(abcdSnap){
   abcdSnap.remove();
})
</code>```

答:
```<code>public void removeUserData()
{
    databaseReferenceC = FirebaseDatabase.getInstance().getReference("users/profiles/");
    FirebaseUser user = firebaseAuth.getCurrentUser();
    databaseReferenceC.child(user.getUid()).removeValue();
}
</code>```

as a example you can use something like that use removeValue()

Body:
How to remove specific object from Firebase DB. I want to remove fine message from champdecay@gmail.com username.

I have tried following code and i got proper object but remove() not works.

abcd = ref.orderByChild('message').equalTo('fine');
abcd.on('value', function(abcdSnap){
    console.log(abcdSnap.val());
})

above Code returns -L-Kl8ctoi5j4TtMWTsc but now how to remove this object. i tried to remove() as follows but not working...

abcd = ref.orderByChild('message').equalTo('fine').remove();

abcd.on('value', function(abcdSnap){
   abcdSnap.remove();
})

Body:
public void removeUserData()
{
    databaseReferenceC = FirebaseDatabase.getInstance().getReference("users/profiles/");
    FirebaseUser user = firebaseAuth.getCurrentUser();
    databaseReferenceC.child(user.getUid()).removeValue();
}

as a example you can use something like that use removeValue()


问:
Javascript document write
How do I get this javascript to populate the textarea?

```<code><body onload="form1.submit();"><div align="center">Loading...</div>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.js"></script> <!-- core code -->
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.en.js"></script> <!-- English stop words -->
<script type="text/javascript">
        $(function() {
            var count = 20;
            $.extend($.wordStats.stopWords, {'retrieved': true, '2007': true});
            $.wordStats.computeTopWords(count);
            var msgcounttext1 = '<%=completehtml%>'
            for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
               msg += $.wordStats.topWords[i].substring(1) + ', ';
            }
            {
            document.form1.textarea.value = document.write(msgcounttext);
            }
            $.wordStats.clear();
        });
        </script>
<div id="content" class="hidden"><%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>
  </div>
</body>
</code>```

Thanks

答:
try</p>

```<code>document.form1.textarea.value= msgcounttext;
</code>```

Title: Javascript document write

Body:
How do I get this javascript to populate the textarea?

Loading...

<%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>

Thanks

Body:
try

document.form1.textarea.value= msgcounttext;


问:
Where to handle parent-child event React
I'm getting start with React basic concepts, and I'm not sure how to proceed...

I'm trying to build a simple Minesweeper game, my structure is a MinesweeperField wrapper, with height, width and minesNumber as props, and a MinesweeperTile, with value (is it a mine/number of close mines) and explored as props.

My problem is, I'm not sure how to handle clicking on the tiles. The MinesweeperField component must be notified when a tile is explored to handle the new game state (ex: in case of game over or win), and it must also be able to trigger explore in other tiles (for example, if you click on a tile with 0 close mines, all of the adjacent tiles must be explored automatically).

From what I understood there are two approaches:

Handle click on the Tile, Tile notifies Field, Field triggers explore also on adjacent Tiles - notifying Field from Tile is easy, but calling Tile from Field would require to use refs, plus a different click handler function is instantiated for each Tile

Handle click on Field, Field updates the prop that in render is used to assign the isExplored prop to the Tile - since I render the Tile based on an array variable in the Field's state, I have to use setState to trigger a redraw of child Tiles components.

this is a simplified sample of the render function, in the "Handle Click on Field" version:

```<code>return (
            <div className="minesweeper-wrapper">
                <div className="minesweeper-field" style={this.getDimensions()}>
                    {this.state.proximityMap.map(function(verticalRow, vIndex){
                        return verticalRow.map(function(tileValue, hIndex){
                            return <MinesweeperTile value={tileValue} hIndex={hIndex} vIndex={vIndex} onClick={this.exploreTile.bind(this, vIndex, hIndex, tileValue)} isExplored={this.state.explorationMap[vIndex][hIndex]} />
                        });
                    })}
                </div>
            </div>
        );
</code>```

and here's the exploreTile function:

```<code>exploreTile(vIndex, hIndex, tileValue) {
        this.unveilTile(vIndex, hIndex);
        if (tileValue < 0) {
            this.gameOver();
        } else {
            if (tileValue === 0) {
                this.propagateTileExplore(vIndex, hIndex);
            }
        }
    }
</code>```

this.state.proximityMap contains values indicating how many mines are close to this tile/is this tile a mine. this.state.explorationMap contains bools indicating which tiles have been explored.

My problem with this approach is that, from what I understood, if I want to redraw a single tile, I have to call setState on Field and update this.state.explorationMap array, which will redraw every tile!

Any ideas as to how I could limit the redraw to a single Tile? Should I keep exploring the "handle click on Field" way or go back to "handle click on Tile"?

I started with "handle click on Tile" but I stopped when I got to the "explore adjacent tiles" problem.

Also please no jQuery/js tricks or hacks to solve this in an unconventional way, it's not about finding a way to do this, but finding the most appropriate. It won't probably make a noticeable difference in the context of a Minesweeper game, but as I said, it's for training purposes :)

答:
The most appropriate way would be to let the parent handle the changes. The children just need to know whom to call when they are clicked and how they should look like. I did the same thing in my Game of Life clone using React.

CodePen Link

```<code>changeTile(row, col) {
    if (!this.state.isPlaying) {
      const newTile = this.state.board[row][col] === 1 ? 0 : 1;
      const newRow = [...this.state.board[row]];
      newRow.splice(col, 1, newTile);
      const newBoard = [...this.state.board];
      newBoard.splice(row, 1, newRow);
      this.setState({
        board: newBoard
      });
    }
  }
</code>```

Body:
I'm getting start with React basic concepts, and I'm not sure how to proceed...

I'm trying to build a simple Minesweeper game, my structure is a MinesweeperField wrapper, with height, width and minesNumber as props, and a MinesweeperTile, with value (is it a mine/number of close mines) and explored as props.

My problem is, I'm not sure how to handle clicking on the tiles. The MinesweeperField component must be notified when a tile is explored to handle the new game state (ex: in case of game over or win), and it must also be able to trigger explore in other tiles (for example, if you click on a tile with 0 close mines, all of the adjacent tiles must be explored automatically).

From what I understood there are two approaches:

Handle click on the Tile, Tile notifies Field, Field triggers explore also on adjacent Tiles - notifying Field from Tile is easy, but calling Tile from Field would require to use refs, plus a different click handler function is instantiated for each Tile

Handle click on Field, Field updates the prop that in render is used to assign the isExplored prop to the Tile - since I render the Tile based on an array variable in the Field's state, I have to use setState to trigger a redraw of child Tiles components.

this is a simplified sample of the render function, in the "Handle Click on Field" version:

return (

                    {this.state.proximityMap.map(function(verticalRow, vIndex){
                        return verticalRow.map(function(tileValue, hIndex){
                            return <MinesweeperTile value={tileValue} hIndex={hIndex} vIndex={vIndex} onClick={this.exploreTile.bind(this, vIndex, hIndex, tileValue)} isExplored={this.state.explorationMap[vIndex][hIndex]} />
                        });
                    })}

        );

and here's the exploreTile function:

exploreTile(vIndex, hIndex, tileValue) {
        this.unveilTile(vIndex, hIndex);
        if (tileValue < 0) {
            this.gameOver();
        } else {
            if (tileValue === 0) {
                this.propagateTileExplore(vIndex, hIndex);
            }
        }
    }

this.state.proximityMap contains values indicating how many mines are close to this tile/is this tile a mine. this.state.explorationMap contains bools indicating which tiles have been explored.

My problem with this approach is that, from what I understood, if I want to redraw a single tile, I have to call setState on Field and update this.state.explorationMap array, which will redraw every tile!

Any ideas as to how I could limit the redraw to a single Tile? Should I keep exploring the "handle click on Field" way or go back to "handle click on Tile"?

I started with "handle click on Tile" but I stopped when I got to the "explore adjacent tiles" problem.

Also please no jQuery/js tricks or hacks to solve this in an unconventional way, it's not about finding a way to do this, but finding the most appropriate. It won't probably make a noticeable difference in the context of a Minesweeper game, but as I said, it's for training purposes :)

Body:
The most appropriate way would be to let the parent handle the changes. The children just need to know whom to call when they are clicked and how they should look like. I did the same thing in my Game of Life clone using React.

CodePen Link

changeTile(row, col) {
    if (!this.state.isPlaying) {
      const newTile = this.state.board[row][col] === 1 ? 0 : 1;
      const newRow = [...this.state.board[row]];
      newRow.splice(col, 1, newTile);
      const newBoard = [...this.state.board];
      newBoard.splice(row, 1, newRow);
      this.setState({
        board: newBoard
      });
    }
  }


问:
How to install the boost through its source?
I use the wget download the boost.1.65.1, but I don't know how to install it:

```<code>wget https://dl.bintray.com/boostorg/release/1.65.1/source/boost_1_65_1.tar.gz
</code>```

I have uncompressed it:

```<code>tar -zxvf boost_1_65_1.tar.gz
</code>```

and I tried to make install it, but failed. Because I cd to boost_1_65_1
then use ./configure --prefix=/usr/local/boost.1.65.1 but says there is no configure:

```<code>[root@localhost boost_1_65_1]# ./configure --prefix=/usr/local/boost1.65.1
-bash: ./configure: No such file or directory
</code>```

So, how to install the boost?

答: Follow the instructions here: Boost. Getting Started on Unix Variants. You need to setup the builder first and then invoke it if you want to use Boost  not header-only libraries. </p>

Body:
I use the wget download the boost.1.65.1, but I don't know how to install it:

wget https://dl.bintray.com/boostorg/release/1.65.1/source/boost_1_65_1.tar.gz

I have uncompressed it:

tar -zxvf boost_1_65_1.tar.gz

and I tried to make install it, but failed. Because I cd to boost_1_65_1
then use ./configure --prefix=/usr/local/boost.1.65.1 but says there is no configure:

[root@localhost boost_1_65_1]# ./configure --prefix=/usr/local/boost1.65.1
-bash: ./configure: No such file or directory

So, how to install the boost?


问:
How to configure tomcat 7 with SSL on Ubuntu 14 - the unanswered questions
There are hundreds of guides to installing SSL on tomcat, but none of them I can find answer these key questions.

There are two ways to install SSL: one is to us keytool, the other is to simply put the cert files on the FS and point the server.xml at these files (not using keytool).

Here are the questions I would be very grateful if someone knows the answer:

Is there any advantage to using the more complex keytool, vs just putting the certs on the FS, e.g. in /etc/ssl

If using keytool, you have to supply "-keystore xxx.jks".  Where should the xxx.jks be located  e.g. /root, /home/tomcat7, /etc /var/lib/tomcat7?  I could only find one guide which said how to setup the keystore, and it said to put it in tomcat dir, which seems mad as when we upgrade tomcat, we lose the certs, but if this is a hard requirement then we can do it.

If using keytool, which user should use the tool to import the cert, tomcat7 or root?

They available examples show how to import a cert into a keystore which was used to generate the original csr.  We didn't use it to generate the csr (we were given the certs from a 3rd party). Does this mean we cant use keystore, or need to generate a dummy csr first?

We don't know which CA was used to issue the cert, so cant look there for answers. We have 3 files: gd_bundle-g2-g1.crt, our.crt and our.key

we use java 7.

----- UPDATE 1 ------

Having received advice that we cant use keytool for our existing key/crt files (issued by go daddy we think), we tried the old way of putting the key/certs right into the server.xml, which certainly used to work with older versions of tomcat:

We get this error:

```<code> java.io.FileNotFoundException: /usr/share/tomcat7/.keystore (No such file or directory)
</code>```

---- UPDATE 2 -----

We found this post which showed how to use existing certs with tomcat:

openssl pkcs12 -export -in mycert.crt -inkey mykey.key -out our.p12 -name tomcat -CAfile myCA.crt -caname root -chain

Then edit the server.xml:

```<code><Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="200" scheme="https" secure="true"
           keystoreType="PKCS12"
           keystoreFile="/etc/ssl/our.p12" keystorePass=""
           clientAuth="false" sslProtocol="TLS" />
</code>```

however, this brings this message in catalina.out:

```<code> SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-bio-443"]
 java.net.SocketException: No such file or directory
</code>```

----- UPDATE 3 -----

So we don't know why 433 fails (port 80 works, and nothing else is on 443, and we are starting it as root), but if we change it to 8443, tomcat starts with no errors (horay!), but when we navigate to www.oursite.com/ourwebapp:8443 we get 404.  If we try https://www.oursite.com/ourwebapp:8443 we get "this web page is not available" from chrome.

```<code>netstat -a
</code>```

Shows that its listening on port 8443 (and 80, but nothing on 443)

Any ideas?

答: Do you actually WANT Tomcat to handle SSL itself, or is it behind a web server that is going to handle SSL for it anyway? If the latter, simply comment out the SSL connector in server.xml.</p>

Body:
There are hundreds of guides to installing SSL on tomcat, but none of them I can find answer these key questions.

There are two ways to install SSL: one is to us keytool, the other is to simply put the cert files on the FS and point the server.xml at these files (not using keytool).

Here are the questions I would be very grateful if someone knows the answer:

Is there any advantage to using the more complex keytool, vs just putting the certs on the FS, e.g. in /etc/ssl

If using keytool, you have to supply "-keystore xxx.jks".  Where should the xxx.jks be located  e.g. /root, /home/tomcat7, /etc /var/lib/tomcat7?  I could only find one guide which said how to setup the keystore, and it said to put it in tomcat dir, which seems mad as when we upgrade tomcat, we lose the certs, but if this is a hard requirement then we can do it.

If using keytool, which user should use the tool to import the cert, tomcat7 or root?

They available examples show how to import a cert into a keystore which was used to generate the original csr.  We didn't use it to generate the csr (we were given the certs from a 3rd party). Does this mean we cant use keystore, or need to generate a dummy csr first?

We don't know which CA was used to issue the cert, so cant look there for answers. We have 3 files: gd_bundle-g2-g1.crt, our.crt and our.key

we use java 7.

----- UPDATE 1 ------

Having received advice that we cant use keytool for our existing key/crt files (issued by go daddy we think), we tried the old way of putting the key/certs right into the server.xml, which certainly used to work with older versions of tomcat:

We get this error:

 java.io.FileNotFoundException: /usr/share/tomcat7/.keystore (No such file or directory)

---- UPDATE 2 -----

We found this post which showed how to use existing certs with tomcat:

openssl pkcs12 -export -in mycert.crt -inkey mykey.key -out our.p12 -name tomcat -CAfile myCA.crt -caname root -chain

Then edit the server.xml:

<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="200" scheme="https" secure="true"
           keystoreType="PKCS12"
           keystoreFile="/etc/ssl/our.p12" keystorePass=""
           clientAuth="false" sslProtocol="TLS" />

however, this brings this message in catalina.out:

 SEVERE: Failed to initialize end point associated with ProtocolHandler ["http-bio-443"]
 java.net.SocketException: No such file or directory

----- UPDATE 3 -----

So we don't know why 433 fails (port 80 works, and nothing else is on 443, and we are starting it as root), but if we change it to 8443, tomcat starts with no errors (horay!), but when we navigate to www.oursite.com/ourwebapp:8443 we get 404.  If we try https://www.oursite.com/ourwebapp:8443 we get "this web page is not available" from chrome.

netstat -a

Shows that its listening on port 8443 (and 80, but nothing on 443)

Any ideas?


问:
how a macro definition is passed from Makefile to a header file?
I am trying to compile the source code twice with a MACRO defined & undefined. So for default the macro is undefined & i want to define this macro through arguments from Makefile, like

```<code>$(MAKE) -c $(present_dir)/new_dir -DONE_MACRO=1
</code>```

so i am using this ONE_MACRO in file.h.
how this definition is reflected and knows to preprocessor. Here im using cygmake. How to pass an MACRO as argument to compiler with cygmake tool.

file.h:-

```<code>#if ONE_MACRO
  #define some_targets
#else
 #define other_targets
#endif
</code>```

So how this ONE_MACRO is defined from make file, im trying to pass macro as argument as below

Makefile:-

```<code>MY_TARGET:
    $(MAKE) -C $(present_dir)/target_dir -D ONE_MACRO=1 $(MAKECMDGOALS)
</code>```

答:
For every compiler there is an environmental variable, which passes the areguments to compiler/linker. while dealing with other than GCC we need to find that environmental variables before usage.

like wise in my case RVCT31_CCOPT is the variable which passes the arguments to compiler while building.

Body:
I am trying to compile the source code twice with a MACRO defined & undefined. So for default the macro is undefined & i want to define this macro through arguments from Makefile, like

$(MAKE) -c $(present_dir)/new_dir -DONE_MACRO=1

so i am using this ONE_MACRO in file.h.
how this definition is reflected and knows to preprocessor. Here im using cygmake. How to pass an MACRO as argument to compiler with cygmake tool.

file.h:-

#if ONE_MACRO
  #define some_targets
#else
 #define other_targets
#endif

So how this ONE_MACRO is defined from make file, im trying to pass macro as argument as below

Makefile:-

MY_TARGET:
    $(MAKE) -C $(present_dir)/target_dir -D ONE_MACRO=1 $(MAKECMDGOALS)


问:
How to set property values in new object from object from List and get a new List of the same objects in which properties are set using java 8?
For example here is my code :

```<code>   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }
</code>```

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

答:
In order to avoid this boiler plate code, you can use Dozer mapping API for transforming your EmployeeVO into EmployeeDto with very minimal code. You can look here for Dozer example.

So, by with Dozer mapping, your code looks like:

EmployeeDtoList class:

```<code>public class EmployeeDtoList {

   private List<EmployeeDto> employees;

   //add getters and setters
}
</code>```

EmployeeVOList class:

```<code>public class EmployeeVOList {

   private List<EmployeeVO> employees;

   //add getters and setters
}
</code>```

Converting beans:

```<code>Mapper mapper = new DozerBeanMapper();

EmployeeVOList employeeVOList =
    mapper.map(employeeListFromUI, EmployeeVOList.class);
</code>```

You can use either dozer annotations (i.e., uses @Mapping annotation, look here) or xml to map each field inside EmployeeDto to EmployeeVO

Note: Dozer API
just avoids the boilerplae code i.e., it does NOT specifically avoid any iterations to copy the bean properties from one object into another.

Body:
For example here is my code :

   List<EmployeeDto> employees = new ArrayList<>();
   if(CollectionUtils.isNotEmpty(employeeListFromUI)){
        for(EmployeeVO employee : employeeListFromUI){
            EmployeeDto employeeDto =  new EmployeeDto();
            employeeDto.setName(employee.getName());
            employeeDto.setAddressLine1(employee.getAddressLine1());
            if(employee.getAddressLine2()!=null && employee.getAddressLine2()!=""){
            employeeDto.setAddressLine2(employee.getAddressLine2());
            }
            employeeDto.setCity(employee.getCity());
            employeeDto.setState(employee.getState());
            employeeDto.setZip(employee.getZip());
            employees.add(employeeDto);
        }
    }

instead of this much of code using java 8 stream and forEach is it possible to write the above code in few lines.

Body:
In order to avoid this boiler plate code, you can use Dozer mapping API for transforming your EmployeeVO into EmployeeDto with very minimal code. You can look here for Dozer example.

So, by with Dozer mapping, your code looks like:

EmployeeDtoList class:

public class EmployeeDtoList {

   private List<EmployeeDto> employees;

   //add getters and setters
}

EmployeeVOList class:

public class EmployeeVOList {

   private List<EmployeeVO> employees;

   //add getters and setters
}

Converting beans:

Mapper mapper = new DozerBeanMapper();

EmployeeVOList employeeVOList =
    mapper.map(employeeListFromUI, EmployeeVOList.class);

You can use either dozer annotations (i.e., uses @Mapping annotation, look here) or xml to map each field inside EmployeeDto to EmployeeVO

Note: Dozer API
just avoids the boilerplae code i.e., it does NOT specifically avoid any iterations to copy the bean properties from one object into another.


问:
AngularJS error injecting module
I'm trying to develop a login with cookies check if a user is already logged or not.

In order, I include the app:

```<code>angular.module('ELOAuthentication', [
    'AuthenticationService',
    'ngRoute',
    'ngCookies',
    'angular-loading-bar'
])
</code>```

Then the service

```<code>angular.module('ELOAuthentication').factory('AuthenticationService', function ($rootScope, $scope, $http) {

    var service = {};

    service.Login = function (email, password, callback) {
        var Url = '/api/user/GetLoginByEmailPassword';

        $http.then(Url, { email: email, password: password }).success(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword: ' + error);
            });
    }

    service.SetCookie = function (email, password) {

    };

    service.ClearCookie = function () {

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

Finally the AngularJS controller.

```<code>angular.module('ELOAuthentication').controller('LoginController', function ($rootScope, $scope, $http) {

    AuthenticationService.ClearCookie();

    $scope.init = function () {

    }

    $scope.login = function () {

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

I receive the error:

Uncaught Error: [$injector:modulerr]

. What is wrong?

答:
You don't need to inject Services in your module.

app.js

```<code>angular.module('ELOAuthentication', [
    'ngRoute',
    'ngCookies',
    'angular-loading-bar'
])
</code>```

LoginController.js

```<code>angular.module('ELOAuthentication').controller('LoginController', function ($rootScope, $scope, $http, AuthenticationService) {

    AuthenticationService.ClearCookie();

    $scope.init = function () {

    }

    $scope.login = function () {

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

As mentioned by Sajal, don't forget to return your service object:

AuthenticationService.js

```<code>angular.module('ELOAuthentication').factory('AuthenticationService', function ($rootScope, $scope, $http) {

    var service = {};

    service.Login = function (email, password, callback) {
        var Url = '/api/user/GetLoginByEmailPassword';

        $http.then(Url, { email: email, password: password }).success(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword: ' + error);
            });
    }

    service.SetCookie = function (email, password) {

    };

    service.ClearCookie = function () {

    };

    return service;
});
</code>```

Official documentation

Title: AngularJS error injecting module

Body:
I'm trying to develop a login with cookies check if a user is already logged or not.

In order, I include the app:

angular.module('ELOAuthentication', [
    'AuthenticationService',
    'ngRoute',
    'ngCookies',
    'angular-loading-bar'
])

Then the service

angular.module('ELOAuthentication').factory('AuthenticationService', function ($rootScope, $scope, $http) {

    var service = {};

    service.Login = function (email, password, callback) {
        var Url = '/api/user/GetLoginByEmailPassword';

        $http.then(Url, { email: email, password: password }).success(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword: ' + error);
            });
    }

    service.SetCookie = function (email, password) {

    };

    service.ClearCookie = function () {

    };
});

Finally the AngularJS controller.

angular.module('ELOAuthentication').controller('LoginController', function ($rootScope, $scope, $http) {

    AuthenticationService.ClearCookie();

    $scope.init = function () {

    }

    $scope.login = function () {

    };
});

I receive the error:

Uncaught Error: [$injector:modulerr]

. What is wrong?

Body:
You don't need to inject Services in your module.

app.js

angular.module('ELOAuthentication', [
    'ngRoute',
    'ngCookies',
    'angular-loading-bar'
])

LoginController.js

angular.module('ELOAuthentication').controller('LoginController', function ($rootScope, $scope, $http, AuthenticationService) {

    AuthenticationService.ClearCookie();

    $scope.init = function () {

    }

    $scope.login = function () {

    };
});

As mentioned by Sajal, don't forget to return your service object:

AuthenticationService.js

angular.module('ELOAuthentication').factory('AuthenticationService', function ($rootScope, $scope, $http) {

    var service = {};

    service.Login = function (email, password, callback) {
        var Url = '/api/user/GetLoginByEmailPassword';

        $http.then(Url, { email: email, password: password }).success(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword: ' + error);
            });
    }

    service.SetCookie = function (email, password) {

    };

    service.ClearCookie = function () {

    };

    return service;
});

Official documentation


问:
Which is better for finding pow(a,b), in terms of complexity?
Which is better in runtime?

```<code>for(i=0;i<n;i*=c) or for(i=0;i<n;i=pow(i,c))
</code>```

I found out the below link that says complexity for pow() is O(log(N)).

Built-in Power Function Complexity

Its still not very much clear to me in terms of comparison.
I had recently encountered this question in an interview.

答:
Dastardly silly question, and setting aside the fact that the first loop is infinite and for (i = 0; i < n; i = pow(i, c)) is computing pow multiple times for the oddest of reasons and could well be infinite too, I hope the interviewer revealed the types for i, c, and n, because that matters a lot.

pow(x, y) is normally implemented as exp(y log x). Both exp and log are normally computed on a modern CPU using a Newton-Raphson type algorithm with certain starting points tabulated. The result normally pops out in a single digit number of clock cycles. I don't believe the assertion that pow is O(log(N)) is correct.

However that goes off for surprisingly small integral values, for reasons centred around floating point computations. That doesn't tend to matter for very many scientific calculations however, and in my opinion at least, the way computers evaluate pow(x, y) is one of the marvels of computer science. For such integral values, a hand-rolled algorithm will perform better in terms of precision, but the one you present can be improved from a naive O(N) using exponentation by squaring which, perhaps, is what the interviewer wanted you to say all along.

Body:
Which is better in runtime?

for(i=0;i<n;i*=c) or for(i=0;i<n;i=pow(i,c))

I found out the below link that says complexity for pow() is O(log(N)).

Built-in Power Function Complexity

Its still not very much clear to me in terms of comparison.
I had recently encountered this question in an interview.


问:
IntelliJ IDEA can not resolve maven project
My IntelliJ IDEA stuck in "Reading .../pom.xml"

I changed my hosts file, added 127.0.0.1 localhost, couldn't work

I deleted IntelliJ IDEA config directory, reinstalled IntelliJ IDEA , couldn't work

I reintalled maven, couldn't work

I use IntelliJ's inner maven version instead of the download one, couldn't work

I changed these two configuration settings in maven, still couldn't work

The error shows in IDEA log file:

```<code>org.jetbrains.idea.maven.indices.MavenIndexException: Cannot read index.properties file
    at org.jetbrains.idea.maven.indices.MavenIndex.<init>(MavenIndex.java:125)
    at org.jetbrains.idea.maven.indices.MavenIndices.load(MavenIndices.java:58)
    at org.jetbrains.idea.maven.indices.MavenIndices.<init>(MavenIndices.java:46)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.ensureInitialized(MavenIndicesManager.java:111)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.getIndicesObject(MavenIndicesManager.java:94)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.ensureIndicesExist(MavenIndicesManager.java:171)
    at org.jetbrains.idea.maven.indices.MavenProjectIndicesManager$3.run(MavenProjectIndicesManager.java:117)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:337)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:327)
    at com.intellij.util.ui.update.MergingUpdateQueue.lambda$flush$1(MergingUpdateQueue.java:277)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:291)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:246)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:246)
    at com.intellij.util.Alarm$Request.runSafely(Alarm.java:417)
    at com.intellij.util.Alarm$Request.access$700(Alarm.java:344)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:384)
    at com.intellij.util.Alarm$Request.run(Alarm.java:395)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at com.intellij.util.concurrency.SchedulingWrapper$MyScheduledFutureTask.run(SchedulingWrapper.java:242)
    at com.intellij.util.concurrency.BoundedTaskExecutor$2.run(BoundedTaskExecutor.java:212)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: C:\Users\ifly\.IntelliJIdea2017.3\system\Maven\Indices\Index0\index.properties (系统找不到指定的文件。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at org.jetbrains.idea.maven.indices.MavenIndex.<init>(MavenIndex.java:116)
    ... 23 more
</code>```

Can anyone help me?

答: try removing .IntelliJIdea2017.3\system\Maven\ directory.</p>

Body:
My IntelliJ IDEA stuck in "Reading .../pom.xml"

I changed my hosts file, added 127.0.0.1 localhost, couldn't work

I deleted IntelliJ IDEA config directory, reinstalled IntelliJ IDEA , couldn't work

I reintalled maven, couldn't work

I use IntelliJ's inner maven version instead of the download one, couldn't work

I changed these two configuration settings in maven, still couldn't work

The error shows in IDEA log file:

org.jetbrains.idea.maven.indices.MavenIndexException: Cannot read index.properties file
    at org.jetbrains.idea.maven.indices.MavenIndex.<init>(MavenIndex.java:125)
    at org.jetbrains.idea.maven.indices.MavenIndices.load(MavenIndices.java:58)
    at org.jetbrains.idea.maven.indices.MavenIndices.<init>(MavenIndices.java:46)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.ensureInitialized(MavenIndicesManager.java:111)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.getIndicesObject(MavenIndicesManager.java:94)
    at org.jetbrains.idea.maven.indices.MavenIndicesManager.ensureIndicesExist(MavenIndicesManager.java:171)
    at org.jetbrains.idea.maven.indices.MavenProjectIndicesManager$3.run(MavenProjectIndicesManager.java:117)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:337)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:327)
    at com.intellij.util.ui.update.MergingUpdateQueue.lambda$flush$1(MergingUpdateQueue.java:277)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:291)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:246)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:246)
    at com.intellij.util.Alarm$Request.runSafely(Alarm.java:417)
    at com.intellij.util.Alarm$Request.access$700(Alarm.java:344)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:384)
    at com.intellij.util.Alarm$Request.run(Alarm.java:395)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at com.intellij.util.concurrency.SchedulingWrapper$MyScheduledFutureTask.run(SchedulingWrapper.java:242)
    at com.intellij.util.concurrency.BoundedTaskExecutor$2.run(BoundedTaskExecutor.java:212)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: C:\Users\ifly\.IntelliJIdea2017.3\system\Maven\Indices\Index0\index.properties (系统找不到指定的文件。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at org.jetbrains.idea.maven.indices.MavenIndex.<init>(MavenIndex.java:116)
    ... 23 more

Can anyone help me?


问:
Nativescript move element by 50% and not by 100%?
I have a simple demo project where :

```<code><GridLayout>

    <StackLayout #myStack1 width="100" height="100" translateX="-50" backgroundColor="red" id="bbb">
    </StackLayout>

    <StackLayout #myStack2 width="100" height="100" translateX="50" backgroundColor="green" id="ccc">
    </StackLayout>
</GridLayout>
</code>```

Notice that width and height are 100.

Now let's add marginTop to the green layout :

```<code>@ViewChild("myStack2") private myStack2: ElementRef;
ngOnInit(): void {
    this.myStack2.nativeElement.marginTop =100;
  }
</code>```

But look what happened :

It moved by 50% of 100 ( box dimensions are 100) . Why is that ?

Question:

Why did that happen and how can I fix my code to actually marginTop 100 ?

I'm not after translateY=100 ( which does show it as expected - I;m after the reason and solution for marginTop).

答:
this is actually the expected behavior based on your used layout structure.
The thing is that the StackLayout used to apply marginTop is stretched (no verticalAlignment set means that by default the layout will be stretched).
To overcome this simply apply verticalAlignment setting.

For example:

```<code><GridLayout>
    <StackLayout  verticalAlignment="top" #myStack1 width="100" height="100" translateX="-50" backgroundColor="red" id="bbb">
    </StackLayout>

    <StackLayout verticalAlignment="top" #myStack2 width="100" height="100" translateX="50" backgroundColor="green" id="ccc">
    </StackLayout>
</GridLayout>
</code>```

Additional solutions can be found here

Body:
I have a simple demo project where :

<GridLayout>

    <StackLayout #myStack1 width="100" height="100" translateX="-50" backgroundColor="red" id="bbb">
    </StackLayout>

    <StackLayout #myStack2 width="100" height="100" translateX="50" backgroundColor="green" id="ccc">
    </StackLayout>
</GridLayout>

Notice that width and height are 100.

Now let's add marginTop to the green layout :

@ViewChild("myStack2") private myStack2: ElementRef;
ngOnInit(): void {
    this.myStack2.nativeElement.marginTop =100;
  }

But look what happened :

It moved by 50% of 100 ( box dimensions are 100) . Why is that ?

Question:

Why did that happen and how can I fix my code to actually marginTop 100 ?

I'm not after translateY=100 ( which does show it as expected - I;m after the reason and solution for marginTop).

Body:
this is actually the expected behavior based on your used layout structure.
The thing is that the StackLayout used to apply marginTop is stretched (no verticalAlignment set means that by default the layout will be stretched).
To overcome this simply apply verticalAlignment setting.

For example:

<GridLayout>
    <StackLayout  verticalAlignment="top" #myStack1 width="100" height="100" translateX="-50" backgroundColor="red" id="bbb">
    </StackLayout>

    <StackLayout verticalAlignment="top" #myStack2 width="100" height="100" translateX="50" backgroundColor="green" id="ccc">
    </StackLayout>
</GridLayout>

Additional solutions can be found here


问:
How do I programmatically access data about my database?
I'd like to access the list of tables and for each table report number of rows, disk space used, etc. It would be nice to get these details at the database level, too.

How do I do this programmatically?

答:
You can just open a connection and query the database:

```<code>using(var connection = new SqlConnection(connectionString)) {
    connection.Open();
    using(var command = connection.CreateCommand()) {
        command.CommandText = "SELECT * FROM SYS.TABLES";
        using(var reader = command.ExecuteReader()) {
            while(reader.Read()) {
                Console.WriteLine(reader["name"]);
            }
        }
    }
}
</code>```

You can Google for the query strings for the other information that you want.

Body:
You can just open a connection and query the database:

using(var connection = new SqlConnection(connectionString)) {
    connection.Open();
    using(var command = connection.CreateCommand()) {
        command.CommandText = "SELECT * FROM SYS.TABLES";
        using(var reader = command.ExecuteReader()) {
            while(reader.Read()) {
                Console.WriteLine(reader["name"]);
            }
        }
    }
}

You can Google for the query strings for the other information that you want.


问:
EDSDK Press Shutter Button remotely
I'm trying to remote control my Canon EOS 1000D with Canon's EDSDK 3.6.1 in C#.

I'm calling

```<code>uint CameraCommand_PressShutterButton  = 0x00000004;
uint CameraCommand_ShutterButton_Completely = 0x00000003;

int error = EdsSendCommand(camRef, CameraCommand_PressShutterButton, CameraCommand_ShutterButton_Completely);
</code>```

However, EdsSendCommand always returns 0x00000060 what means "invalid parameter".

Any ideas, what went wrong here? 3 is the parameter I found on this tutorial. I tried CameraCommand_ShutterButton_Completely_NonAF = 0x00010003 as well with the same result.

Or is there another way to remote shutter this camera?

答:
The 1000D is quite old already and it is most likely that it does not support the shutter button command. This command is (to my knowledge) the only one (besides video) that is only supported by newer cameras.

If you just want to take a picture, you can use the TakePicture command (ID is 0, parameter also 0).

Title: EDSDK Press Shutter Button remotely

Body:
I'm trying to remote control my Canon EOS 1000D with Canon's EDSDK 3.6.1 in C#.

I'm calling

uint CameraCommand_PressShutterButton  = 0x00000004;
uint CameraCommand_ShutterButton_Completely = 0x00000003;

int error = EdsSendCommand(camRef, CameraCommand_PressShutterButton, CameraCommand_ShutterButton_Completely);

However, EdsSendCommand always returns 0x00000060 what means "invalid parameter".

Any ideas, what went wrong here? 3 is the parameter I found on this tutorial. I tried CameraCommand_ShutterButton_Completely_NonAF = 0x00010003 as well with the same result.

Or is there another way to remote shutter this camera?


问:
What is the correct way to stop a checkout from an event observer in Magento?
I am verifying shipping quotes during the event checkout_controller_onepage_save_shipping_method and if the verification fails i want to send the user back to shipping method selection but I would also like to display a message saying why it failed. Does Magento have a way of doing this built in?

I am already verifying the data I just lack the redirect to shipping methods and way to display a message.

答:
I came up with a different approach for this, not having to override the controller. Basically I do the same thing but just in observer methods. So I am using checkout_controller_onepage_save_shipping_method  to validate the shipping methods as well and if there is an error I add that error to a session variable like the following

```<code> $error = array('error' => -1, 'message' => Mage::helper('core')->__("Message here"));
 Mage::getSingleton('checkout/session')->setSavedMethodError($error);
</code>```

Then you can for every action apply another observer to 'controller_action_postdispatch_'.$this->getFullActionName()

So I used that to observe controller_action_postdispatch_checkout_onepage_saveShippingMethod Which in there I check for the session error variable and set the response body if it exists.

```<code>$error =  Mage::getSingleton('checkout/session')->getSavedMethodError();
if($error){
   Mage::app()->getResponse()->setBody(Mage::helper('core')->jsonEncode($error));
}
Mage::getSingleton('checkout/session')->setSavedMethodError(false);
</code>```

I am not sure if this is better or worse, so please leave any comments but I know I preferred to be able to do this without having to do any rewriting of the class.

This works because you are overriding the response body that was set in the saveShippingMethod action.

Body:
I came up with a different approach for this, not having to override the controller. Basically I do the same thing but just in observer methods. So I am using checkout_controller_onepage_save_shipping_method  to validate the shipping methods as well and if there is an error I add that error to a session variable like the following

 $error = array('error' => -1, 'message' => Mage::helper('core')->__("Message here"));
 Mage::getSingleton('checkout/session')->setSavedMethodError($error);

Then you can for every action apply another observer to 'controller_action_postdispatch_'.$this->getFullActionName()

So I used that to observe controller_action_postdispatch_checkout_onepage_saveShippingMethod Which in there I check for the session error variable and set the response body if it exists.

$error =  Mage::getSingleton('checkout/session')->getSavedMethodError();
if($error){
   Mage::app()->getResponse()->setBody(Mage::helper('core')->jsonEncode($error));
}
Mage::getSingleton('checkout/session')->setSavedMethodError(false);

I am not sure if this is better or worse, so please leave any comments but I know I preferred to be able to do this without having to do any rewriting of the class.

This works because you are overriding the response body that was set in the saveShippingMethod action.