问:
iOS AVFoundation read QRcode when vuforia using the AVCaptureDeviceInput
This the code read QRcode

```<code>- (instancetype)init {
    if (self = [super init]) {

        if (self.session == nil)
            self.session = [[AVCaptureSession alloc] init];

        //device
        if (self.device == nil)
            self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

        //output
        if (self.output == nil)
            self.output = [[AVCaptureMetadataOutput alloc] init];
    }
    return self;
}

- (void)creatScanQR{

    NSError *error = nil;
    //input
    if (self.input == nil)
        self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];

    if(self.input) {
        [self.session addInput:self.input];
    } else {
        NSLog(@"%@", error);
        return;
    }

    [self.session addOutput:self.output];
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [self.session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {

    for (AVMetadataMachineReadableCodeObject *metadata in metadataObjects) {
        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {

            NSLog(@"======%@=======",metadata.stringValue);
        }
    }
}
</code>```

It works in native app. But my app is build by Unity, it used Vuforia, When I use AVCapture read QRcode, vuforia is black screen. Because camera are only one which is using by Voforia. How can I use AVCaptureInput to read QRcode and vuforia is still working?

My planB is get the vuforia view , write a image by vuforia view , use iOS CIDetector read the qrcode, but I got a nil image.why ?

```<code>    UIView *view =  UnityGetGLView();
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:[CIContext contextWithOptions:nil] options:@{CIDetectorAccuracy:CIDetectorAccuracyLow}];
    NSArray *features = [detector featuresInImage:[CIImage imageWithData:imageData]];
    for (CIFeature *feature in features) {
         NSLog(@"%@",feature.type);
         if ([feature isKindOfClass:[CIQRCodeFeature class]]) {
             NSLog(@"?????? %@ ????? ", ((CIQRCodeFeature *)feature).messageString);
             dispatch_sync(queue, ^{ dispatch_suspend(timer); });
         }
     }
</code>```

答: sounds like your problem is caused by competition of using camera. The only solution may be to use the exactly same view in vuforia and QRCode reading,  namely workaround the competition, and share the camera images between vuforia and QRCode reading.</p>

Body:
This the code read QRcode

- (instancetype)init {
    if (self = [super init]) {

        if (self.session == nil)
            self.session = [[AVCaptureSession alloc] init];

        //device
        if (self.device == nil)
            self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

        //output
        if (self.output == nil)
            self.output = [[AVCaptureMetadataOutput alloc] init];
    }
    return self;
}

- (void)creatScanQR{

    NSError *error = nil;
    //input
    if (self.input == nil)
        self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];

    if(self.input) {
        [self.session addInput:self.input];
    } else {
        NSLog(@"%@", error);
        return;
    }

    [self.session addOutput:self.output];
    [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [self.session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {

    for (AVMetadataMachineReadableCodeObject *metadata in metadataObjects) {
        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {

            NSLog(@"======%@=======",metadata.stringValue);
        }
    }
}

It works in native app. But my app is build by Unity, it used Vuforia, When I use AVCapture read QRcode, vuforia is black screen. Because camera are only one which is using by Voforia. How can I use AVCaptureInput to read QRcode and vuforia is still working?

My planB is get the vuforia view , write a image by vuforia view , use iOS CIDetector read the qrcode, but I got a nil image.why ?

    UIView *view =  UnityGetGLView();
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:[CIContext contextWithOptions:nil] options:@{CIDetectorAccuracy:CIDetectorAccuracyLow}];
    NSArray *features = [detector featuresInImage:[CIImage imageWithData:imageData]];
    for (CIFeature *feature in features) {
         NSLog(@"%@",feature.type);
         if ([feature isKindOfClass:[CIQRCodeFeature class]]) {
             NSLog(@"?????? %@ ????? ", ((CIQRCodeFeature *)feature).messageString);
             dispatch_sync(queue, ^{ dispatch_suspend(timer); });
         }
     }


来源: stackexchange

问:
How to ignore certain files in Git
I have a repository with a file, Hello.java. When I compile it, an additional Hello.class file is generated.

I created an entry for Hello.class in a .gitignore file. However, the file still appears to be tracked.

How can I make Git ignore Hello.class?

答: The problem is that .gitignore ignores just files that weren't tracked before (by git add). Run git reset name_of_file to unstage the file and keep it. In case you want to also remove the given file from the repository (after pushing), use git rm --cached name_of_file.

ContentLicense: CC BY-SA 4.0

Title: How to ignore certain files in Git


问:
What should the generator passed to predict_generator() return?
I am calling Keras predict_generator() like:

bottleneck_features_train = model.predict_generator(train_gen, len(telemetry))

where train_gen() is defined like

def train_gen():
    # ...
    yield (X, y)

and X is a numpy array with shape (48, 299, 299, 3), y is a numpy array with shape (48,)

I get the error below. What should I do instead?

Otherwise, a link to a working example would help. Only examples I have found are for Keras 1 or using ImageDataGenerator.flow().

I am running Keras 2.0.2.

Here the error:

```<code>Traceback (most recent call last):
  File "/home/fanta/workspace/CarND-Behavioral-Cloning-P3/cache.py", line 143, in <module>
    tf.app.run()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/fanta/workspace/CarND-Behavioral-Cloning-P3/cache.py", line 138, in main
    bottleneck_features_train = model.predict_generator(train_gen, len(telemetry))
  File "/usr/local/lib/python3.5/dist-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 2094, in predict_generator
    outs = self.predict_on_batch(x)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1677, in predict_on_batch
    self._feed_input_shapes)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 100, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 0 input arrays, but only received one array. Found: array with shape (48, 299, 299, 3)

Process finished with exit code 1
</code>```

===== UPDATE =====

The issue is not related to the generator. Here below a short program to reproduce it. Note that if you switch the network from inception to vgg, it works fine.

```<code>from keras.applications.inception_v3 import InceptionV3
from keras.applications.vgg16 import VGG16
from keras.layers import Input, AveragePooling2D
from keras.models import Model
from keras.datasets import cifar10
from scipy.misc import imresize
import pickle
import tensorflow as tf
import keras.backend as K
import numpy as np

network='inception'  # Must be 'inception' or 'vgg'
dataset='cifar10'
batch_size=64

if network == 'vgg':
    size = (224, 224)
elif network == 'inception':
    size = (299, 299)
else:
    assert False, "network must be either 'inception' or 'vgg'"

def create_model():
    input_tensor = Input(shape=(size[0], size[1], 3))
    if network == 'inception':
        model = InceptionV3(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((8, 8), strides=(8, 8))(x)
        model = Model(model.input, x)
    elif network == 'vgg':
        model = VGG16(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((7, 7))(x)
        model = Model(model.input, x)
    else:
        assert False
    return model

def main():

    # Download and load cifar10 dataset
    (X_train, y_train), (_, _) = cifar10.load_data()

    # Reduce the dataset to the first 1000 entries, to save memory and computation time
    X_train = X_train[0:1000]
    y_train = y_train[0:1000]

    # Resize dataset images to comply with expected input image size
    X_train = [imresize(image, size) for image in X_train]
    X_train = np.array(X_train)

    # File name where to save bottlenecked features
    train_output_file = "{}_{}_{}.p".format(network, dataset, 'bottleneck_features_train')
    print("Saving to", train_output_file)

    with tf.Session() as sess:
        K.set_session(sess)
        K.set_learning_phase(1)
        model = create_model()
        # We skip pre-processing and bottleneck the features
        bottleneck_features_train = model.predict(X_train, batch_size=batch_size, verbose=1)
        data = {'features': bottleneck_features_train, 'labels': y_train}
        pickle.dump(data, open(train_output_file, 'wb'))

if __name__ == '__main__':
    main()
</code>```

答:
At prediction step your generator should only yield the input and not the targets. So only the X, not the y.

Does that help?

ContentLicense: CC BY-SA 3.0

Body:
I am calling Keras predict_generator() like:

bottleneck_features_train = model.predict_generator(train_gen, len(telemetry))

where train_gen() is defined like

def train_gen():
    # ...
    yield (X, y)

and X is a numpy array with shape (48, 299, 299, 3), y is a numpy array with shape (48,)

I get the error below. What should I do instead?

Otherwise, a link to a working example would help. Only examples I have found are for Keras 1 or using ImageDataGenerator.flow().

I am running Keras 2.0.2.

Here the error:

Traceback (most recent call last):
  File "/home/fanta/workspace/CarND-Behavioral-Cloning-P3/cache.py", line 143, in <module>
    tf.app.run()
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py", line 44, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "/home/fanta/workspace/CarND-Behavioral-Cloning-P3/cache.py", line 138, in main
    bottleneck_features_train = model.predict_generator(train_gen, len(telemetry))
  File "/usr/local/lib/python3.5/dist-packages/keras/legacy/interfaces.py", line 88, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 2094, in predict_generator
    outs = self.predict_on_batch(x)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 1677, in predict_on_batch
    self._feed_input_shapes)
  File "/usr/local/lib/python3.5/dist-packages/keras/engine/training.py", line 100, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 0 input arrays, but only received one array. Found: array with shape (48, 299, 299, 3)

Process finished with exit code 1

===== UPDATE =====

The issue is not related to the generator. Here below a short program to reproduce it. Note that if you switch the network from inception to vgg, it works fine.

from keras.applications.inception_v3 import InceptionV3
from keras.applications.vgg16 import VGG16
from keras.layers import Input, AveragePooling2D
from keras.models import Model
from keras.datasets import cifar10
from scipy.misc import imresize
import pickle
import tensorflow as tf
import keras.backend as K
import numpy as np

network='inception'  # Must be 'inception' or 'vgg'
dataset='cifar10'
batch_size=64

if network == 'vgg':
    size = (224, 224)
elif network == 'inception':
    size = (299, 299)
else:
    assert False, "network must be either 'inception' or 'vgg'"

def create_model():
    input_tensor = Input(shape=(size[0], size[1], 3))
    if network == 'inception':
        model = InceptionV3(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((8, 8), strides=(8, 8))(x)
        model = Model(model.input, x)
    elif network == 'vgg':
        model = VGG16(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((7, 7))(x)
        model = Model(model.input, x)
    else:
        assert False
    return model

def main():

    # Download and load cifar10 dataset
    (X_train, y_train), (_, _) = cifar10.load_data()

    # Reduce the dataset to the first 1000 entries, to save memory and computation time
    X_train = X_train[0:1000]
    y_train = y_train[0:1000]

    # Resize dataset images to comply with expected input image size
    X_train = [imresize(image, size) for image in X_train]
    X_train = np.array(X_train)

    # File name where to save bottlenecked features
    train_output_file = "{}_{}_{}.p".format(network, dataset, 'bottleneck_features_train')
    print("Saving to", train_output_file)

    with tf.Session() as sess:
        K.set_session(sess)
        K.set_learning_phase(1)
        model = create_model()
        # We skip pre-processing and bottleneck the features
        bottleneck_features_train = model.predict(X_train, batch_size=batch_size, verbose=1)
        data = {'features': bottleneck_features_train, 'labels': y_train}
        pickle.dump(data, open(train_output_file, 'wb'))

if __name__ == '__main__':
    main()


问:
Extracting fields from forms with varying structures
I am trying to extract certain fields from a balance sheet. For example, I would like to be able to tell that the value of 'Inventory' is 1,277,838 for the following balance sheet:

Currently, I am using Tesseract to convert images to text. However, this conversion results in a stream of text, so it is difficult to associate fields with their values (since these values are not always right next to the text of their corresponding fields).

After some searching, I read the Tesseract can use uzn files to read from zones of an image. However, the specific zones of the balance sheet values may shift from form to form, so I am interested in any solutions that can determine that 'Inventory' and 1,277,838 are on the same line. Ideally, I would like a grid structure output of text (so that I can tell the spatially that which chunks of text are in the same rows/columns).

Could anyone help explain how I can achieve this result?

答:
As already mentioned by gaw89, Tesseract can output more information than only the text as a stream. The hocr fileformat gives you also the position (bounding boxes) of each paragraph, line, word:

```<code>$ tesseract 4LV05.png out -l eng hocr
</code>```

Then you can for example find the bounding box of the word "Inventory" by simply

```<code>$ grep 'Inventory' out.hocr
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>
</code>```

Thus, the bounding box of this word spans vertically from 183 to 204 and for corresponding value of this label, we have now to search for boxes in the same vertical space. This can for example been achieved here by

```<code>$ grep 'bbox [0-9]* 18[0-9]' out.hocr
<p class='ocr_par' id='par_1_4' lang='eng' title="bbox 23 183 112 204">
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>
 <span class='ocr_line' id='line_1_30' title="bbox 1082 183 1178 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_82' title='bbox 1082 183 1178 202; x_wconf 93'>1,277,838</span>
 <span class='ocr_line' id='line_1_54' title="bbox 1301 183 1379 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_107' title='bbox 1301 183 1379 202; x_wconf 95'>953,675</span>
</code>```

The second result contains the targeted value. You can compare the vertical coordinates of the bbox to be sure to extract the first column.

The command grep was just enough in this example here, but there are certainly other ways to do something similar. Note also, that the regular expression should maybe replaced with some other calculation depending on how skewed your pages are.

Alternatively, you can try out the open source Tabula, which will try to extract tabular data from pdfs.

Body:
As already mentioned by gaw89, Tesseract can output more information than only the text as a stream. The hocr fileformat gives you also the position (bounding boxes) of each paragraph, line, word:

$ tesseract 4LV05.png out -l eng hocr

Then you can for example find the bounding box of the word "Inventory" by simply

$ grep 'Inventory' out.hocr
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>

Thus, the bounding box of this word spans vertically from 183 to 204 and for corresponding value of this label, we have now to search for boxes in the same vertical space. This can for example been achieved here by

$ grep 'bbox [0-9]* 18[0-9]' out.hocr
<p class='ocr_par' id='par_1_4' lang='eng' title="bbox 23 183 112 204">
 <span class='ocr_line' id='line_1_5' title="bbox 23 183 112 204; baseline 0 -5; x_size 21; x_descenders 5; x_ascenders 4"><span class='ocrx_word' id='word_1_15' title='bbox 23 183 112 204; x_wconf 93'>Inventory</span>
 <span class='ocr_line' id='line_1_30' title="bbox 1082 183 1178 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_82' title='bbox 1082 183 1178 202; x_wconf 93'>1,277,838</span>
 <span class='ocr_line' id='line_1_54' title="bbox 1301 183 1379 202; baseline 0 -3; x_size 22; x_descenders 5.5; x_ascenders 5.5"><span class='ocrx_word' id='word_1_107' title='bbox 1301 183 1379 202; x_wconf 95'>953,675</span>

The second result contains the targeted value. You can compare the vertical coordinates of the bbox to be sure to extract the first column.

The command grep was just enough in this example here, but there are certainly other ways to do something similar. Note also, that the regular expression should maybe replaced with some other calculation depending on how skewed your pages are.

Alternatively, you can try out the open source Tabula, which will try to extract tabular data from pdfs.


问:
Raw SQL 'Insert Into' in ASP MVC
i'm trying to insert data from a form into two tables in db.

```<code>public ActionResult Cr([Bind(Include = "id,name,time")] appointment appointment, [Bind(Include = "pid,phone")] customer customer , string submit)
        {
        string str1 = "Insert Into appointment.id, appointment.name, appointment.time Values id,name,time"
        string str2= "Insert Into customer.pid, customer.phone Values pid,phone"
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str1).ToList();
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str2).ToList();
        return View("Index");
        }
</code>```

I am not sure if my code is wrong but the data are not inserted in the tables.

答:
You need table name  (column name)  and values  (  )</p>

```<code>string str1 = "Insert Into  appointment (id, name, time)  Values (id,name,time)";
string str2= "Insert Into  customer (pid, phone)  Values (pid,phone)";
</code>```

Title: Raw SQL 'Insert Into' in ASP MVC

Body:
i'm trying to insert data from a form into two tables in db.

public ActionResult Cr([Bind(Include = "id,name,time")] appointment appointment, [Bind(Include = "pid,phone")] customer customer , string submit)
        {
        string str1 = "Insert Into appointment.id, appointment.name, appointment.time Values id,name,time"
        string str2= "Insert Into customer.pid, customer.phone Values pid,phone"
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str1).ToList();
        var Query = dbb.Database.SqlQuery<ViewModel.custapp>(str2).ToList();
        return View("Index");
        }

I am not sure if my code is wrong but the data are not inserted in the tables.

Body:
You need table name  (column name)  and values  (  )

string str1 = "Insert Into  appointment (id, name, time)  Values (id,name,time)";
string str2= "Insert Into  customer (pid, phone)  Values (pid,phone)";


问:
Sort a String Array containing Numbers in linq
i have following string array which contain numbers
string[] arr = { "3", "1", "6", "10", "5", "13" };
if i do arr.OrderBy(x=>x) i am getting following result
1
10
13
3
5
6
expected result(in array):
1
3
5
6
10
13
 Any one have better and simple solution.

答:
Yes, you can use int.Parse() inside LINQ like the following:

```<code>var resultArray = arr.OrderBy(x => int.Parse(x)).ToArray();
</code>```

You can checkout this Example

Body:
Yes, you can use int.Parse() inside LINQ like the following:

var resultArray = arr.OrderBy(x => int.Parse(x)).ToArray();

You can checkout this Example


问:
Is EmailComposeTask Class already working?
For example here:

http://msdn.microsoft.com/en-us/library/ff769550(VS.92).asp

```
<code>EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "user@example.com";
emailComposeTask.Body = "Email message body";
emailComposeTask.Cc = "user2@example.com";
emailComposeTask.Subject = "Email subject";
emailComposeTask.Show();
</code>
```

I read it doesnt work yet.

答: Just pasted your code into an app, deployed to a device and was presented with a choice of which of my email accounts I wanted to use for the email after which the email was prepared ready editing and sending.</p>

ContentLicense: CC BY-SA 2.5

Body:
For example here:

http://msdn.microsoft.com/en-us/library/ff769550(VS.92).asp

EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.To = "user@example.com";
emailComposeTask.Body = "Email message body";
emailComposeTask.Cc = "user2@example.com";
emailComposeTask.Subject = "Email subject";
emailComposeTask.Show();

I read it doesnt work yet.


问:
Sourcetree - undo unpushed commits
I am using Sourcetree for Windows for a git-repository and would like to undo an unpushed commit.

Is that possible? If I do "revert commit", it creates a second commit which reverts the first commit, but I don't want the first commit to appear at all in my source control.

I could also delete my local repository and pull it again without my local commit, but maybe there's another way?

答: If You are on another branch, You need first "check to this commit" for commit you want to delete, and only then "reset current branch to this commit" choosing previous wright commit, will work.</p>

Title: Sourcetree - undo unpushed commits


问:
HBase region - region server programmatic assignment
Let's say I have 100 HBase nodes and several tables A, B, C that have keys pre-pended with 000:099 prefixes. Tables are created with splits based on prefix, so each table has 100 regions.

I'd like to assign all rows with prefix:

000 to node-00,

001 to node-01,

and so on.

The idea is to hold data with same prefix on the same machine, because my typical scenario is to process table A, transform the data and put it to table B, then process table B several times doing some transformations and aggregations.

I don't see the instruction in docs and need some suggestions about how to proceed.

答:
You can create a new table with need number of regions. Then do a manual region balancing before populating the table using move command, putting regions to the required servers. See help for it

```<code>hbase(main):004:0> help move

Here is some help for this command:
Move a region.  Optionally specify target regionserver else we choose one
at random.  NOTE: You pass the encoded region name, not the region name so
this command is a little different to the others.  The encoded region name
is the hash suffix on region names: e.g. if the region name were
TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396. then
the encoded region name portion is 527db22f95c8a9e0116f0cc13c680396
A server name is its host, port plus startcode. For example:
host187.example.com,60020,1289493121758
Examples:

  hbase> move 'ENCODED_REGIONNAME'
  hbase> move 'ENCODED_REGIONNAME', 'SERVER_NAME'
</code>```

Or you can try to use HBaseAdmin to do this, see method move.

Body:
You can create a new table with need number of regions. Then do a manual region balancing before populating the table using move command, putting regions to the required servers. See help for it

hbase(main):004:0> help move

Here is some help for this command:
Move a region.  Optionally specify target regionserver else we choose one
at random.  NOTE: You pass the encoded region name, not the region name so
this command is a little different to the others.  The encoded region name
is the hash suffix on region names: e.g. if the region name were
TestTable,0094429456,1289497600452.527db22f95c8a9e0116f0cc13c680396. then
the encoded region name portion is 527db22f95c8a9e0116f0cc13c680396
A server name is its host, port plus startcode. For example:
host187.example.com,60020,1289493121758
Examples:

  hbase> move 'ENCODED_REGIONNAME'
  hbase> move 'ENCODED_REGIONNAME', 'SERVER_NAME'

Or you can try to use HBaseAdmin to do this, see method move.


问:
redux-form doesn't get submitted
I have a strange bug in my app. I want to let the user update the name of a group via redux form. Exchanging the old name with the input field works without problem, but when I click on Submit, then nothing happens. This is very strange for me, because I am using the same form to create the group in the first place and there it works totally fine.

```<code>import React, { Component } from 'react';
import { connect} from 'react-redux';
import { deleteAccessGroup, editAccessGroup } from '../actions/UserActions';
import { showModal } from '../actions/ModalActions';
import * as types from '../actions/index';
import AccessGroupCreation from '../components/AccessGroupCreation';

class AccessGroupElement extends Component {
  constructor(props) {
    super(props);

    this.state = {
      toggle: false
    }
  }

  handleSubmit = values => {
    this.props.editAccessGroup(values);
    console.log(this.state, "Das sind die values: ", values);
    this.edit;
    console.log(this.state);
  }

  edit = () => this.setState({toggle: !this.state.toggle});

  delAccessGroup = () => this.props.deleteAccessGroup(this.props.accessGroup.id);

  showPicModal = () => {
    let id = this.props.accessGroup.id;

    this.props.showModal(types.MODAL_TYPE_PICUPLOAD, {
      title: 'Please upload a Profile Picture',
      onConfirm: (pic) => {
        console.log(this.props.accessGroup.id);
        console.log( pic)
      }
    });
  }

  render() {
    const accessGroup=this.props.accessGroup;

    return(
      <div className="row" id="hoverDiv">
        <div className="col-lg-1"></div>
        {this.state.toggle ?
        <div className="col-lg-9">
          <AccessGroupCreation onSubmit={this.handleSubmit} />
        </div> :
        <div className="col-lg-9">{accessGroup.name}</div>}
        <div className="col-lg-2">
          <button type="button" onClick={this.delAccessGroup}
                  className="btn btn-default btn-sm pull-right">
            <span className="glyphicon glyphicon-trash"></span>
          </button>

          <button type="button" onClick={this.edit}
                  className="btn btn-default btn-sm pull-right">
            <span className="glyphicon glyphicon-pencil"></span>
          </button>
        </div>
      </div>
    );
  }
}

export default connect(null, { deleteAccessGroup, editAccessGroup, showModal })(AccessGroupElement);
</code>```

Here is the form component:

```<code>import React from 'react';
import { Field, reduxForm } from 'redux-form';

const required = value => value ? undefined : 'Required';

const lengthFunction = (min, max) => value =>
  value && (value.length > max || value.length < min) ? `Must be between ${min} and ${max} characters` : undefined

const length = lengthFunction(5, 20);

const renderField = ({ input, label, type, meta: { touched, error } }) => (
  <div>
    <input {...input} placeholder={label} type={type} className="form-control"/>
      {touched && (error && <span>{error}</span>)}
  </div>
);

const AccessGroupCreation = (props) => {
  const { handleSubmit, pristine, submitting } = props;

  return (
    <form className="form-inline" onSubmit={handleSubmit}>
      <div className="input-group">
      <Field name="name" type="text"
             component={renderField} label="Add an Access Group"
             validate={[ required, length]}/>

             <span className="input-group-btn">
               <button className="btn btn-success" disabled={pristine || submitting}
                       value="this.state.value" type="submit">
                <span className="glyphicon glyphicon-send"></span>
                  Submit
               </button>
             </span>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'AccessGroupCreationForm' // a unique identifier for this form
})(AccessGroupCreation)
</code>```

Help, as always, would be very much appreciated.

答:
Change few thing as-

```<code>     ...

class AccessGroupElement extends Component {
  constructor(props) {
      ...
  }

  submit = values => { // rename this function
    this.props.editAccessGroup(values);
    console.log(this.state, "Das sind die values: ", values);
    this.edit;
    console.log(this.state);
  }

     ....

  render() {
    const accessGroup=this.props.accessGroup;

    return(
      <div className="row" id="hoverDiv">
          ........
        <div className="col-lg-9">
          <AccessGroupCreation submit={this.submit} /> // change here
        </div> :
          .........
      </div>
    );
  }
}

export default connect(null, { deleteAccessGroup, editAccessGroup, showModal })(AccessGroupElement);
</code>```

then on your form-

```<code>const AccessGroupCreation = (props) => {
  const { handleSubmit, pristine, submitting, submit } = props; // getting submit function

  return (
    <form className="form-inline" onSubmit={handleSubmit(submit)}>
         .......
    </form>
  )
}

export default reduxForm({
  form: 'AccessGroupCreationForm' // a unique identifier for this form
})(AccessGroupCreation)
</code>```

Title: redux-form doesn't get submitted

Body:
I have a strange bug in my app. I want to let the user update the name of a group via redux form. Exchanging the old name with the input field works without problem, but when I click on Submit, then nothing happens. This is very strange for me, because I am using the same form to create the group in the first place and there it works totally fine.

import React, { Component } from 'react';
import { connect} from 'react-redux';
import { deleteAccessGroup, editAccessGroup } from '../actions/UserActions';
import { showModal } from '../actions/ModalActions';
import * as types from '../actions/index';
import AccessGroupCreation from '../components/AccessGroupCreation';

class AccessGroupElement extends Component {
  constructor(props) {
    super(props);

    this.state = {
      toggle: false
    }
  }

  handleSubmit = values => {
    this.props.editAccessGroup(values);
    console.log(this.state, "Das sind die values: ", values);
    this.edit;
    console.log(this.state);
  }

  edit = () => this.setState({toggle: !this.state.toggle});

  delAccessGroup = () => this.props.deleteAccessGroup(this.props.accessGroup.id);

  showPicModal = () => {
    let id = this.props.accessGroup.id;

    this.props.showModal(types.MODAL_TYPE_PICUPLOAD, {
      title: 'Please upload a Profile Picture',
      onConfirm: (pic) => {
        console.log(this.props.accessGroup.id);
        console.log( pic)
      }
    });
  }

  render() {
    const accessGroup=this.props.accessGroup;

    return(

        {this.state.toggle ?

          <AccessGroupCreation onSubmit={this.handleSubmit} />

 :

{accessGroup.name}
}

          <button type="button" onClick={this.delAccessGroup}
                  className="btn btn-default btn-sm pull-right">

          </button>

          <button type="button" onClick={this.edit}
                  className="btn btn-default btn-sm pull-right">

          </button>

    );
  }
}

export default connect(null, { deleteAccessGroup, editAccessGroup, showModal })(AccessGroupElement);

Here is the form component:

import React from 'react';
import { Field, reduxForm } from 'redux-form';

const required = value => value ? undefined : 'Required';

const lengthFunction = (min, max) => value =>
  value && (value.length > max || value.length < min) ? `Must be between ${min} and ${max} characters` : undefined

const length = lengthFunction(5, 20);

const renderField = ({ input, label, type, meta: { touched, error } }) => (

    <input {...input} placeholder={label} type={type} className="form-control"/>
      {touched && (error && {error})}

);

const AccessGroupCreation = (props) => {
  const { handleSubmit, pristine, submitting } = props;

  return (
    <form className="form-inline" onSubmit={handleSubmit}>

      <Field name="name" type="text"
             component={renderField} label="Add an Access Group"
             validate={[ required, length]}/>

               <button className="btn btn-success" disabled={pristine || submitting}
                       value="this.state.value" type="submit">

                  Submit
               </button>

    </form>
  )
}

export default reduxForm({
  form: 'AccessGroupCreationForm' // a unique identifier for this form
})(AccessGroupCreation)

Help, as always, would be very much appreciated.

Body:
Change few thing as-

     ...

class AccessGroupElement extends Component {
  constructor(props) {
      ...
  }

  submit = values => { // rename this function
    this.props.editAccessGroup(values);
    console.log(this.state, "Das sind die values: ", values);
    this.edit;
    console.log(this.state);
  }

     ....

  render() {
    const accessGroup=this.props.accessGroup;

    return(
      <div className="row" id="hoverDiv">
          ........
        <div className="col-lg-9">
          <AccessGroupCreation submit={this.submit} /> // change here
        </div> :
          .........
      </div>
    );
  }
}

export default connect(null, { deleteAccessGroup, editAccessGroup, showModal })(AccessGroupElement);

then on your form-

const AccessGroupCreation = (props) => {
  const { handleSubmit, pristine, submitting, submit } = props; // getting submit function

  return (
    <form className="form-inline" onSubmit={handleSubmit(submit)}>
         .......
    </form>
  )
}

export default reduxForm({
  form: 'AccessGroupCreationForm' // a unique identifier for this form
})(AccessGroupCreation)


问:
How to select a PDF file using startActivityForResult intent and return result in a second class
I am relatively new to android programming, I want to create a pdf reader that calls the inbuilt file manager to select pdf file and then display the pdf file in a second class. Here is my code so far still having issues, i think second activity is unable to get the selected pdf file and I am unable to fix this error

```<code>     MainActivity

     package com.example.user.projectapp;

     import android.app.Activity;
     import android.app.ListActivity;
     import android.content.Context;
     import android.content.Intent;
     import android.database.Cursor;
     import android.net.Uri;
     import android.provider.OpenableColumns;
     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.View;
     import android.widget.ArrayAdapter;
     import android.widget.ListView;

     import java.io.File;
     import java.io.IOException;
     import java.io.InputStream;
     import java.net.URI;
     import java.net.URISyntaxException;
     import java.util.ArrayList;
     import java.util.Collections;
     import java.util.List;

     public class MainActivity extends AppCompatActivity {

     public static String path;
     private static final int PICKFILE_REQUEST_CODE = 0;
     File tempFile;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     getFile();
     }

      public void getFile() {

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("application/pdf");
      path = intent.getStringExtra("path");
      intent.putExtra("path",path);
      startActivityForResult(intent, PICKFILE_REQUEST_CODE);
      }

      Second Activity

      package com.example.user.projectapp;

      import android.annotation.TargetApi;
      import android.content.Intent;
      import android.graphics.Bitmap;
      import android.graphics.pdf.PdfRenderer;
      import android.os.Build;
      import android.os.Environment;
      import android.os.ParcelFileDescriptor;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      import android.widget.ImageView;

      import java.io.File;

      public class Main2Activity extends AppCompatActivity {

      int pagecount = -1;
      Button buttonnext, buttonprevious;
      ImageView imageView;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      buttonnext = (Button) findViewById(R.id.button1);
      buttonprevious = (Button) findViewById(R.id.button2);
      imageView = (ImageView) findViewById(R.id.imageview);

      buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
       });
     buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
       });

       }

       @TargetApi(Build.VERSION_CODES.LOLLIPOP)
       public void render() {

       try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

        Intent intent = getIntent();
        String data = intent.getStringExtra("path");
        File file = new File(data);

        PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    @Override
    public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

    }
    }
</code>```

And the Logcat gives

```<code>    03-28 17:19:33.387 2492-2492/com.example.user.projectapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.fixSlashes(File.java:185)
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.<init>(File.java:134)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity.render(Main2Activity.java:69)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity$1.onClick(Main2Activity.java:42)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View.performClick(View.java:4764)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View$PerformClick.run(View.java:19844)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Looper.loop(Looper.java:135)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5351)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
</code>```

Code Modified to be based on one activity only......
yet onActivityResult does not return a result, I

```<code>File myFile;
public static String result;
public String path;
private static final int PICKFILE_REQUEST_CODE = 12;
int pagecount = -1;
Button buttonnext, buttonprevious;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getFile();

    buttonnext = (Button) findViewById(R.id.button1);
    buttonprevious = (Button) findViewById(R.id.button2);
    imageView = (ImageView) findViewById(R.id.imageview);

    buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
    });
    buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
    });

}
public void getFile() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    //intent.setType("image/");
    // path = intent.getStringExtra("path");
     //intent.putExtra("path",path);
    //intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 12);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==12){
        if (data != null){
            Toast.makeText(this,"file selected",Toast.LENGTH_LONG).show();
          // result=data.getStringExtra("data");
            Uri uri=data.getData();
          //  String uriString = uri.toString();
             myFile = new File(uri.toString());
            path = myFile.getAbsolutePath();
           // result=data.toString();
           // URI uri=data.getParcelableExtra(path);
           // path=fileUri.toString();
            this.render();
        }

    }

}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void render() {

    try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        //Intent intent = getIntent();
        //String path = intent.getStringExtra("path");

        // Uri uri = Uri.parse(uri_Str);
         File file = new File(path);
        //File storage = Environment.getExternalStorageDirectory();
        // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }

        // Matrix m = imageView.getImageMatrix();
        // Rect rect=new Rect(0,0,width,height);
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        //imageView.setImageMatrix(m);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}
</code>```

And the logcat error...

```<code>    03-29 11:32:47.276 21674-21674/com.example.user.newtry W/System.err: java.io.FileNotFoundException: No such file or directory
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.Parcel.openFileDescriptor(Native Method)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at      android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)
</code>```

答:
Use below code, it will not give you error:

MainActivity

```<code>        import android.app.Activity;
        import android.app.ListActivity;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.net.Uri;
        import android.provider.OpenableColumns;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;

        import java.io.File;
        import java.io.IOException;
        import java.io.InputStream;
        import java.net.URI;
        import java.net.URISyntaxException;
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static String path;
    private static final int PICKFILE_REQUEST_CODE = 0;
    File tempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getFile();
    }

    public void getFile() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //intent.setType("application/pdf");

       // path = intent.getStringExtra("path");
      //  intent = new Intent(this, Main2Activity.class);
      //  intent.putExtra("path", path);
        startActivityForResult(intent, PICKFILE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==PICKFILE_REQUEST_CODE && resultCode==RESULT_OK) {
            Intent intent = new Intent(this, Main2Activity.class);
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            path = myFile.getAbsolutePath();
            Log.d("uri",uriString + " " + path);
            Bundle extras = new Bundle();
            extras.putParcelable("path", uri);
           // intent.putExtra();
            startActivityForResult(intent, PICKFILE_REQUEST_CODE);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

Main2Activity

```<code>import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class Main2Activity extends AppCompatActivity {

    int pagecount = -1;
    Button buttonnext, buttonprevious;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        buttonnext = (Button) findViewById(R.id.button1);
        buttonprevious = (Button) findViewById(R.id.button2);
        imageView = (ImageView) findViewById(R.id.imageview);

        buttonnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pagecount++;

                render();

            }
        });
        buttonprevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pagecount--;

                render();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void render() {

        try {
            int width = imageView.getWidth();
            int height = imageView.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

            Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            Uri data = extras.getParcelable("path");
            Log.d("Soanam","path" + data);
            File file = new File(data.toString());

            PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

            if (pagecount < 0) {
                pagecount = 0;
            } else if (pagecount > renderer.getPageCount()) {
                pagecount = renderer.getPageCount() - 1;
            }
            renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            imageView.setImageBitmap(bitmap);
            imageView.invalidate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

    }
}
</code>```

Body:
I am relatively new to android programming, I want to create a pdf reader that calls the inbuilt file manager to select pdf file and then display the pdf file in a second class. Here is my code so far still having issues, i think second activity is unable to get the selected pdf file and I am unable to fix this error

     MainActivity

     package com.example.user.projectapp;

     import android.app.Activity;
     import android.app.ListActivity;
     import android.content.Context;
     import android.content.Intent;
     import android.database.Cursor;
     import android.net.Uri;
     import android.provider.OpenableColumns;
     import android.support.v7.app.AppCompatActivity;
     import android.os.Bundle;
     import android.util.Log;
     import android.view.View;
     import android.widget.ArrayAdapter;
     import android.widget.ListView;

     import java.io.File;
     import java.io.IOException;
     import java.io.InputStream;
     import java.net.URI;
     import java.net.URISyntaxException;
     import java.util.ArrayList;
     import java.util.Collections;
     import java.util.List;

     public class MainActivity extends AppCompatActivity {

     public static String path;
     private static final int PICKFILE_REQUEST_CODE = 0;
     File tempFile;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     getFile();
     }

      public void getFile() {

      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.setType("application/pdf");
      path = intent.getStringExtra("path");
      intent.putExtra("path",path);
      startActivityForResult(intent, PICKFILE_REQUEST_CODE);
      }

      Second Activity

      package com.example.user.projectapp;

      import android.annotation.TargetApi;
      import android.content.Intent;
      import android.graphics.Bitmap;
      import android.graphics.pdf.PdfRenderer;
      import android.os.Build;
      import android.os.Environment;
      import android.os.ParcelFileDescriptor;
      import android.support.v7.app.AppCompatActivity;
      import android.os.Bundle;
      import android.view.View;
      import android.widget.Button;
      import android.widget.ImageView;

      import java.io.File;

      public class Main2Activity extends AppCompatActivity {

      int pagecount = -1;
      Button buttonnext, buttonprevious;
      ImageView imageView;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      buttonnext = (Button) findViewById(R.id.button1);
      buttonprevious = (Button) findViewById(R.id.button2);
      imageView = (ImageView) findViewById(R.id.imageview);

      buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
       });
     buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
       });

       }

       @TargetApi(Build.VERSION_CODES.LOLLIPOP)
       public void render() {

       try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

        Intent intent = getIntent();
        String data = intent.getStringExtra("path");
        File file = new File(data);

        PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }

    @Override
    public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

    }
    }

And the Logcat gives

    03-28 17:19:33.387 2492-2492/com.example.user.projectapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.fixSlashes(File.java:185)
    03-28 17:19:33.400 2492-2492/com.example.user.projectapp W/System.err:     at java.io.File.<init>(File.java:134)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity.render(Main2Activity.java:69)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.example.user.projectapp.Main2Activity$1.onClick(Main2Activity.java:42)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View.performClick(View.java:4764)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.view.View$PerformClick.run(View.java:19844)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.os.Looper.loop(Looper.java:135)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5351)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
    03-28 17:19:33.401 2492-2492/com.example.user.projectapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

Code Modified to be based on one activity only......
yet onActivityResult does not return a result, I

File myFile;
public static String result;
public String path;
private static final int PICKFILE_REQUEST_CODE = 12;
int pagecount = -1;
Button buttonnext, buttonprevious;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getFile();

    buttonnext = (Button) findViewById(R.id.button1);
    buttonprevious = (Button) findViewById(R.id.button2);
    imageView = (ImageView) findViewById(R.id.imageview);

    buttonnext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount++;

            render();

        }
    });
    buttonprevious.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pagecount--;

            render();
        }
    });

}
public void getFile() {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    //intent.setType("image/");
    // path = intent.getStringExtra("path");
     //intent.putExtra("path",path);
    //intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, 12);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==12){
        if (data != null){
            Toast.makeText(this,"file selected",Toast.LENGTH_LONG).show();
          // result=data.getStringExtra("data");
            Uri uri=data.getData();
          //  String uriString = uri.toString();
             myFile = new File(uri.toString());
            path = myFile.getAbsolutePath();
           // result=data.toString();
           // URI uri=data.getParcelableExtra(path);
           // path=fileUri.toString();
            this.render();
        }

    }

}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void render() {

    try {
        int width = imageView.getWidth();
        int height = imageView.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

        //Intent intent = getIntent();
        //String path = intent.getStringExtra("path");

        // Uri uri = Uri.parse(uri_Str);
         File file = new File(path);
        //File storage = Environment.getExternalStorageDirectory();
        // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if (pagecount < 0) {
            pagecount = 0;
        } else if (pagecount > renderer.getPageCount()) {
            pagecount = renderer.getPageCount() - 1;
        }

        // Matrix m = imageView.getImageMatrix();
        // Rect rect=new Rect(0,0,width,height);
        renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        //imageView.setImageMatrix(m);
        imageView.setImageBitmap(bitmap);
        imageView.invalidate();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

And the logcat error...

    03-29 11:32:47.276 21674-21674/com.example.user.newtry W/System.err: java.io.FileNotFoundException: No such file or directory
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.Parcel.openFileDescriptor(Native Method)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)
    03-29 11:32:47.283 21674-21674/com.example.user.newtry W/System.err:     at      android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)

Body:
Use below code, it will not give you error:

MainActivity

        import android.app.Activity;
        import android.app.ListActivity;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.net.Uri;
        import android.provider.OpenableColumns;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.util.Log;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;

        import java.io.File;
        import java.io.IOException;
        import java.io.InputStream;
        import java.net.URI;
        import java.net.URISyntaxException;
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;

public class MainActivity extends AppCompatActivity {

    public static String path;
    private static final int PICKFILE_REQUEST_CODE = 0;
    File tempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getFile();
    }

    public void getFile() {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //intent.setType("application/pdf");

       // path = intent.getStringExtra("path");
      //  intent = new Intent(this, Main2Activity.class);
      //  intent.putExtra("path", path);
        startActivityForResult(intent, PICKFILE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==PICKFILE_REQUEST_CODE && resultCode==RESULT_OK) {
            Intent intent = new Intent(this, Main2Activity.class);
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            path = myFile.getAbsolutePath();
            Log.d("uri",uriString + " " + path);
            Bundle extras = new Bundle();
            extras.putParcelable("path", uri);
           // intent.putExtra();
            startActivityForResult(intent, PICKFILE_REQUEST_CODE);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Main2Activity

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;

public class Main2Activity extends AppCompatActivity {

    int pagecount = -1;
    Button buttonnext, buttonprevious;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        buttonnext = (Button) findViewById(R.id.button1);
        buttonprevious = (Button) findViewById(R.id.button2);
        imageView = (ImageView) findViewById(R.id.imageview);

        buttonnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pagecount++;

                render();

            }
        });
        buttonprevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pagecount--;

                render();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void render() {

        try {
            int width = imageView.getWidth();
            int height = imageView.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_4444);

            Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            Uri data = extras.getParcelable("path");
            Log.d("Soanam","path" + data);
            File file = new File(data.toString());

            PdfRenderer renderer = new              PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

            if (pagecount < 0) {
                pagecount = 0;
            } else if (pagecount > renderer.getPageCount()) {
                pagecount = renderer.getPageCount() - 1;
            }
            renderer.openPage(pagecount).render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            imageView.setImageBitmap(bitmap);
            imageView.invalidate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

    }
}


问:
RegisterClassEx Fails as Invalid Parameter - C++
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

```<code>memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}
</code>```

Does anyone know what I'm doing wrong?  Thanks.

答:
Usually "The parameter is incorrect" is the WINAPI's way of saying, "dude, you're sending me crap."

So one of the WNDCLASSEX member variables is probably crap.  Start by taking a closer look at the variables that are most likely to have something inappropriate in them:  m_wcx.hInstance, m_wcx.lpfnWndProc, and m_wcx.lpszClassName.

EDIT:

As pointed out by @Johann Gerell, m_wcx.style = WS_ICONIC is an example of this.  The documentation says that this is a class style, but you've sent a window style.  No good.

What's the difference?  Well, you know the difference between a C++ class and an object, right?  A class is like a blueprint.  An object is an instantiation of that blueprint.  Same is true of Window Classes & Windows.  A Window Class is a blueprint for creating a window, and a window is an instantiation of that Window Class.  Window Classes have styles that specify things like what kind of DC to use, when to vertical refresh -- low level stuff like that which applies to every instance of that window class.  Windows also have styles, but these are different.  Window styles specify per-window things like if the window should be visible, minimized, etc.  So RegisterClassEx asked you for an orange, and you tried to give it an apple.

Body:
A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."

memset( &m_wcx, 0, sizeof(WNDCLASSEX) );

m_wcx.cbSize = sizeof(WNDCLASSEX);  // size of structure
m_wcx.style = WS_ICONIC;            // initially minimized
m_wcx.lpfnWndProc = &WndProc;       // points to window procedure
m_wcx.cbClsExtra = 0;               // no extra class memory
m_wcx.cbWndExtra = 0;               // no extra window memory
m_wcx.hInstance = m_hInstance;      // handle to instance
m_wcx.hIcon = ::LoadIcon( NULL, IDI_APPLICATION ); // default app icon
m_wcx.hCursor = ::LoadCursor( NULL, IDC_ARROW ); // standard arrow cursor
m_wcx.hbrBackground = NULL;         // no background to paint
m_wcx.lpszMenuName = NULL;          // no menu resource
m_wcx.lpszClassName = _pwcWindowClass; // name of window class
m_wcx.hIconSm = NULL;               // search system resources for sm icon

m_atom = ::RegisterClassEx( &m_wcx );

if ( m_atom == 0 )
{
    TRACE(_T("CNotifyWindow::CNotifyWindow : Failed to register window class.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    THROW(::GetLastError());
}

Does anyone know what I'm doing wrong?  Thanks.


问:
Need some information about reverse engineering and decompile (android app - jdk)
I'm new to android and I don't know much about software engineering. I wanna know about things should be done to make it harder to decompile an app. I made some research about it and I ran into this debugger JEB which seems like it can monitor some stuff while app running. Yet I don't know the advantages of using it since I don't get the critical points of an android app which is being monitored by JEB. for example:

enter image description here

appearantly the right side shows local variables. what does x / xh means for an int? or for the string value "secretKey" is the value of string seriously? if it is then all variables in my code are at risk!!!??
I think maybe one of the attempts is to make a lot of fake variables in code so that the real ones can't be seen easily. Does it make sense? And are there other leaks that  I should try to prevent for example about this JEB? Does proguard have anything to do with this? As I said I donno much about soft-eng and I didn't get to understand what proguard actually does.

And another thing I've seen is https://ibotpeaches.github.io/Apktool. How to make it more mixed up for such tool to handle?

The last question, I code in java and don't think yet I have the opportunity to start native coding but for future; I've seen people say its safer to code natively. Is it by itself? or there are more libraries to keep more safety? or its because of the final apk structure?

sorry if some words look dumb. thanks in advance

答:
You can protect your code by using some powerful obfuscator tool like: Bg+Anti Decompile/Reverse Java
It has a lot of protection options:

Hide string value (helpful when you keep some sensitive info in java source, ex: "Hello world" ->ß¤ª )

Obfuscate with unicode characters

Hide packagename

Add fakecode to trap the decompiler tools

Check resource-string (helpful when someone try to edit the resources of your APK)

....


问:
Angular 2 Search
I'm trying to use a search box to filter a list of items using Angular 2 but when I type stuff into the search box it never fires the search method on the service. I know I'm probably missing something simple but any help would be much appreciated.

company.service.ts:

```<code>import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/toPromise';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';

@Injectable()
export class CompanyService {

  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  search(term: string): Observable<CompaniesModel> {
      console.log('search service', term);
      return this.http
          .get('/api/Company/Search/?search=' + term)
          .map((r: Response) => r.json().data as CompaniesModel);
  }
}
</code>```

companies.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { FormControl } from '@angular/forms';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';
import { CompanyService } from './company.service';

@Component({
  moduleId: module.id,
  selector: 'companies-list',
  templateUrl: 'companies.component.html'
})
export class CompaniesComponent implements OnInit {
    companiesModel: Observable<CompaniesModel>;
    private searchTerms = new Subject<string>();

  constructor(
      private companyService: CompanyService,
    private router: Router) { }

  search(term: string): void {
      this.searchTerms.next(term);
  }

  ngOnInit(): void {
      this.companiesModel = this.searchTerms
          .debounceTime(300)
          .distinctUntilChanged()
          .switchMap(term => this.companyService.search(term));

  }

  gotoDetail(company: CompanyModel): void {
      let link = ['/company', company.Id];
      this.router.navigate(link);
  }
}
</code>```

companies.component.html

```<code><h2>Companies</h2>
<div>
    <label>Search: </label>
    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
</div>
<div>
    <button (click)="create()">
        Add
    </button>
</div>
<div *ngIf="companiesModel" class="grid grid-pad">
    <ul>
        <li *ngFor="let company of companiesModel.Companies | async" (click)="gotoDetail(company)">
            <div>
                <h4>{{company.Name}}</h4>
            </div>
        </li>
    </ul>
</div>
</code>```

答:
You can try the same using below code as well

```<code> <input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">
</code>```

Pipe

```<code>@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}
</code>```

You can modify the code as per your requirements.

Title: Angular 2 Search

Body:
I'm trying to use a search box to filter a list of items using Angular 2 but when I type stuff into the search box it never fires the search method on the service. I know I'm probably missing something simple but any help would be much appreciated.

company.service.ts:

import { Injectable }    from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/toPromise';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';

@Injectable()
export class CompanyService {

  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  search(term: string): Observable<CompaniesModel> {
      console.log('search service', term);
      return this.http
          .get('/api/Company/Search/?search=' + term)
          .map((r: Response) => r.json().data as CompaniesModel);
  }
}

companies.component.ts:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { FormControl } from '@angular/forms';

import { CompanyModel } from './company';
import { CompaniesModel } from './company';
import { CompanyService } from './company.service';

@Component({
  moduleId: module.id,
  selector: 'companies-list',
  templateUrl: 'companies.component.html'
})
export class CompaniesComponent implements OnInit {
    companiesModel: Observable<CompaniesModel>;
    private searchTerms = new Subject<string>();

  constructor(
      private companyService: CompanyService,
    private router: Router) { }

  search(term: string): void {
      this.searchTerms.next(term);
  }

  ngOnInit(): void {
      this.companiesModel = this.searchTerms
          .debounceTime(300)
          .distinctUntilChanged()
          .switchMap(term => this.companyService.search(term));

  }

  gotoDetail(company: CompanyModel): void {
      let link = ['/company', company.Id];
      this.router.navigate(link);
  }
}

companies.component.html

Companies

    Search:
    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

    <button (click)="create()">
        Add
    </button>

{{company.Name}}

Body:
You can try the same using below code as well

 <input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">

Pipe

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}

You can modify the code as per your requirements.


问:
Grant access to private constructor without friends?
I am working on some code, where I encountered a situation similar to this one:

```<code>struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}
</code>```

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

答:
This is precisely what the attorney-client idiom is for:

```<code>struct Bar;

struct Foo {
    friend struct FooAttorney;
private:
    Foo(){}
    void f(){}
    void g(){}
};

class FooAttorney {
  static Foo* makeFoo() { return new Foo; }
  friend struct Bar;
};

struct Bar {
   Foo* f;
   Bar()  { f = FooAttorney::makeFoo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}
</code>```

In a code imitates life fashion, the class declares an attorney that will mediate the secrets it's willing to share with the selected parties.

Body:
I am working on some code, where I encountered a situation similar to this one:

struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

Body:
This is precisely what the attorney-client idiom is for:

struct Bar;

struct Foo {
    friend struct FooAttorney;
private:
    Foo(){}
    void f(){}
    void g(){}
};

class FooAttorney {
  static Foo* makeFoo() { return new Foo; }
  friend struct Bar;
};

struct Bar {
   Foo* f;
   Bar()  { f = FooAttorney::makeFoo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

In a code imitates life fashion, the class declares an attorney that will mediate the secrets it's willing to share with the selected parties.


问:
How to add an Android Studio project to GitHub
I have a project in Android Studio. I want to add that project to a GitHub repository using android studio. How can I do that?</p>

答:
If you are using the latest version of Android studio, then you don't need to install additional software for Git other than GIT itself - https://git-scm.com/downloads

Steps

Create an account on Github - https://github.com/join

Install Git

Open your working project in Android studio

GoTo - File -> Settings -> Version Controll -> GitHub

Enter Login and Password which you have created just on Git Account and click on test

Once all credentials are true - it shows Success message Or Invalid Cred.

Now click on VCS in android studio menu bar

Select Import into Version Control -> Share Project on GitHub

The popup dialog that will occur contains all your files with check mark, do ok or commit all

At next time whenever you want to push your project just click on VCS - > Commit Changes -> Commit and Push.

That's it. You can find your project on your GitHub now.


问:
Android - Custom EditText prefix color
I've created a prefix modification for my custom EditText by the help of SO and Copy Paste.

Here's the particular code for prefix :

```<code>private String mPrefix = "";
private Rect mPrefixRect = new Rect();

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

private void applyPrefix(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);
    String fontFace;

    try {
        fontFace = a.getString(R.styleable.OpenSansET_prefix);
    } finally {
        a.recycle();
    }
    if (fontFace != null){
        mPrefix = fontFace;
    } else {
        mPrefix = "";
    }
}

protected void setmPrefix(String prefix){
    this.mPrefix = prefix;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")){
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}
</code>```

Basically what it does is if I've supplied a prefix from xml or through code, it draws that prefix onto the start of the EditText. For example :

```<code><com.asta.classes.OpenSansEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/min"
    app:prefix="$"/>
</code>```

This code produces :

But the problem is, if I set textColorHint, the color of the prefix will be the same as the color of the hint like :

How to modify the color of the prefix to a specified color? In my case it is to let it have its own color rather than using hint color.

答:
Try these:</p>

```<code>Typeface font = Typeface.createFromAsset(getAssets(), "OpenSans_Semibold.ttf");

SpannableStringBuilder builder = new SpannableStringBuilder();

String a = "$" + " ";

SpannableString aSpannable = new SpannableString(a);

aSpannable.setSpan(newForegroundColorSpan(getResources().getColor(R.color.color_yellow)), 0, a.length(), 0);

aSpannable.setSpan(new CustomTypefaceSpan("", font), 0, a.length(),    Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

builder.append(aSpannable);

String b = "Min";

SpannableString bSpannable = new SpannableString(b);

bSpannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_white)), 0, b.length(), 0);

bSpannable.setSpan(new CustomTypefaceSpan("", font), 0, b.length(),       Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

builder.append(bSpannable);

final EditText textV = new EditText(this);

textV.setHint(builder,textV.BufferType.SPANNABLE)`
</code>```

Title: Android - Custom EditText prefix color

Body:
I've created a prefix modification for my custom EditText by the help of SO and Copy Paste.

Here's the particular code for prefix :

private String mPrefix = "";
private Rect mPrefixRect = new Rect();

public OpenSansEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

public OpenSansEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    applyCustomFont(context, attrs);
    applyPrefix(context, attrs);
}

private void applyPrefix(Context context, AttributeSet attrs) {
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.OpenSansET);
    String fontFace;

    try {
        fontFace = a.getString(R.styleable.OpenSansET_prefix);
    } finally {
        a.recycle();
    }
    if (fontFace != null){
        mPrefix = fontFace;
    } else {
        mPrefix = "";
    }
}

protected void setmPrefix(String prefix){
    this.mPrefix = prefix;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (!mPrefix.equals("")){
        getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
        mPrefixRect.right += getPaint().measureText(" "); // add some offset
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mPrefix.equals("")) {
        canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
    }
}

@Override
public int getCompoundPaddingLeft() {
    return mPrefix.equals("") ? super.getCompoundPaddingLeft()
            : super.getCompoundPaddingLeft() + mPrefixRect.width();
}

Basically what it does is if I've supplied a prefix from xml or through code, it draws that prefix onto the start of the EditText. For example :

<com.asta.classes.OpenSansEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/min"
    app:prefix="$"/>

This code produces :

But the problem is, if I set textColorHint, the color of the prefix will be the same as the color of the hint like :

How to modify the color of the prefix to a specified color? In my case it is to let it have its own color rather than using hint color.

Body:
Try these:

Typeface font = Typeface.createFromAsset(getAssets(), "OpenSans_Semibold.ttf");

SpannableStringBuilder builder = new SpannableStringBuilder();

String a = "$" + " ";

SpannableString aSpannable = new SpannableString(a);

aSpannable.setSpan(newForegroundColorSpan(getResources().getColor(R.color.color_yellow)), 0, a.length(), 0);

aSpannable.setSpan(new CustomTypefaceSpan("", font), 0, a.length(),    Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

builder.append(aSpannable);

String b = "Min";

SpannableString bSpannable = new SpannableString(b);

bSpannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_white)), 0, b.length(), 0);

bSpannable.setSpan(new CustomTypefaceSpan("", font), 0, b.length(),       Spanned.SPAN_EXCLUSIVE_INCLUSIVE);

builder.append(bSpannable);

final EditText textV = new EditText(this);

textV.setHint(builder,textV.BufferType.SPANNABLE)`


问:
Spring Boot with urlencoded data from post man and curl
How to handle the curl/postman request like this in spring boot

```<code>curl -X POST -H "Accept: application/json" -H "Authorization: Basic mytoken" -d '{"searchText":["aaa","bbb", "ccc", "ddd", "eee","fff"]}' "http://localhost:8080/api/loc
</code>```

Here is my controller code

```<code>@RequestMapping(value = "/search", method = RequestMethod.POST, headers="Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getWordCountList(@ModelAttribute WordCount searchText) {
}
</code>```

note that, the WordCount is the model class and it contains two strings. However, When the above curl request is sent, the searchText is always empty.. Any suggestions please ?

答:
Try to change the @RequestMapping value from "/search" to "/api/loc".

Also, try the following template. The one for the REST-ful style:

```<code>@RestController
public class MyController {

    @RequestMapping(value = "/api/loc", method = RequestMethod.POST)
    public String getWordCountList(@RequestBody WordCount searchText) {
       return "hello";
    }

}
</code>```

The @RestController is a convenience annotation that emphasises the REST-full nature of the controller and adds @ResponseBody semantic @RequestMapping methods return types. You could rewrite the example with the @Controller annotation instead:

```<code>@Controller
public class MyController {

    @RequestMapping(value = "/api/loc", method = RequestMethod.POST)
    public @ResponseBody String getWordCountList(@RequestBody WordCount searchText) {
       return "hello";
    }

}
</code>```

Body:
How to handle the curl/postman request like this in spring boot

curl -X POST -H "Accept: application/json" -H "Authorization: Basic mytoken" -d '{"searchText":["aaa","bbb", "ccc", "ddd", "eee","fff"]}' "http://localhost:8080/api/loc

Here is my controller code

@RequestMapping(value = "/search", method = RequestMethod.POST, headers="Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getWordCountList(@ModelAttribute WordCount searchText) {
}

note that, the WordCount is the model class and it contains two strings. However, When the above curl request is sent, the searchText is always empty.. Any suggestions please ?

Body:
Try to change the @RequestMapping value from "/search" to "/api/loc".

Also, try the following template. The one for the REST-ful style:

@RestController
public class MyController {

    @RequestMapping(value = "/api/loc", method = RequestMethod.POST)
    public String getWordCountList(@RequestBody WordCount searchText) {
       return "hello";
    }

}

The @RestController is a convenience annotation that emphasises the REST-full nature of the controller and adds @ResponseBody semantic @RequestMapping methods return types. You could rewrite the example with the @Controller annotation instead:

@Controller
public class MyController {

    @RequestMapping(value = "/api/loc", method = RequestMethod.POST)
    public @ResponseBody String getWordCountList(@RequestBody WordCount searchText) {
       return "hello";
    }

}