问:
Using AVCapturePhotoOutput in iOS10 - NSGenericException
I am currently trying to figure out how to use iOS 10's AVCapturePhotoOutput method and am having trouble doing so. I feel like I am about to get it right but continue receiving an error:

Terminating app due to uncaught exception 'NSGenericException', reason: '-[AVCapturePhotoOutput capturePhotoWithSettings:delegate:] No active and enabled video connection'

I have tried to put this line of code in either the AVCapturePhotoCaptureDelegate or my didPressTakePhoto function:

```<code>if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
     videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait;
     ...
}
</code>```

Here is the code I have so far:

```<code>import AVFoundation
import UIKit

class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCapturePhotoCaptureDelegate {

    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var imageView: UIImageView!

    var captureSession : AVCaptureSession?
    var stillImageOutput : AVCapturePhotoOutput?
    var stillImageOutputSettings : AVCapturePhotoSettings?
    var previewLayer : AVCaptureVideoPreviewLayer?

    var didTakePhoto = Bool();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);

        previewLayer?.frame = cameraView.bounds;
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);

        captureSession = AVCaptureSession();
        captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080;

        stillImageOutput = AVCapturePhotoOutput();

        let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo);

        do {
            let input = try AVCaptureDeviceInput(device: backCamera)

            if (captureSession?.canAddInput(input))! {
                captureSession?.addInput(input);

                if (captureSession?.canAddOutput(stillImageOutput))! {
                    captureSession?.canAddOutput(stillImageOutput);

                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
                    previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect;
                    previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait;
                    cameraView.layer.addSublayer(previewLayer!);
                    captureSession?.startRunning();
                }
            }
        } catch {
            print(error);
        }
    }

    func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
        if let error = error {
            print(error.localizedDescription);
        }

        if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) {
            print(UIImage(data: dataImage)?.size as Any);

            let dataProvider = CGDataProvider(data: dataImage as CFData);
            let cgImageRef: CGImage! = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent);
            let image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right);

            self.imageView.image = image;
            self.imageView.isHidden = false;
        }
    }

    func didPressTakePhoto() {
            stillImageOutputSettings = AVCapturePhotoSettings();

            let previewPixelType = stillImageOutputSettings?.availablePreviewPhotoPixelFormatTypes.first!;
            let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                                 kCVPixelBufferWidthKey as String: 160,
                                 kCVPixelBufferHeightKey as String: 160];
            stillImageOutputSettings?.previewPhotoFormat = previewFormat;

            stillImageOutput.capturePhoto(with: stillImageOutputSettings!, delegate: self);
    }

    func didPressTakeAnother() {
        if (didTakePhoto == true) {
            imageView.isHidden = true;
            didTakePhoto = false;
        } else {
            captureSession?.startRunning();
            didTakePhoto = true;
            didPressTakePhoto();
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        didPressTakeAnother();
    }
}
</code>```

Any suggestions?

Thanks in advance!

答:
For anyone else that may be trying to figure this out, the following resources helped me:

For reference and code layout

SnapChat: Camera 1

SnapChat: Camera 2

Actual implementation and usage of new iOS10 Camera features

AV Foundation: iOS 10

iOS Custom Camera

Body:
I am currently trying to figure out how to use iOS 10's AVCapturePhotoOutput method and am having trouble doing so. I feel like I am about to get it right but continue receiving an error:

Terminating app due to uncaught exception 'NSGenericException', reason: '-[AVCapturePhotoOutput capturePhotoWithSettings:delegate:] No active and enabled video connection'

I have tried to put this line of code in either the AVCapturePhotoCaptureDelegate or my didPressTakePhoto function:

if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
     videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait;
     ...
}

Here is the code I have so far:

import AVFoundation
import UIKit

class Camera: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCapturePhotoCaptureDelegate {

    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var imageView: UIImageView!

    var captureSession : AVCaptureSession?
    var stillImageOutput : AVCapturePhotoOutput?
    var stillImageOutputSettings : AVCapturePhotoSettings?
    var previewLayer : AVCaptureVideoPreviewLayer?

    var didTakePhoto = Bool();

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);

        previewLayer?.frame = cameraView.bounds;
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);

        captureSession = AVCaptureSession();
        captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080;

        stillImageOutput = AVCapturePhotoOutput();

        let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo);

        do {
            let input = try AVCaptureDeviceInput(device: backCamera)

            if (captureSession?.canAddInput(input))! {
                captureSession?.addInput(input);

                if (captureSession?.canAddOutput(stillImageOutput))! {
                    captureSession?.canAddOutput(stillImageOutput);

                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
                    previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect;
                    previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait;
                    cameraView.layer.addSublayer(previewLayer!);
                    captureSession?.startRunning();
                }
            }
        } catch {
            print(error);
        }
    }

    func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
        if let error = error {
            print(error.localizedDescription);
        }

        if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) {
            print(UIImage(data: dataImage)?.size as Any);

            let dataProvider = CGDataProvider(data: dataImage as CFData);
            let cgImageRef: CGImage! = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent);
            let image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right);

            self.imageView.image = image;
            self.imageView.isHidden = false;
        }
    }

    func didPressTakePhoto() {
            stillImageOutputSettings = AVCapturePhotoSettings();

            let previewPixelType = stillImageOutputSettings?.availablePreviewPhotoPixelFormatTypes.first!;
            let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                                 kCVPixelBufferWidthKey as String: 160,
                                 kCVPixelBufferHeightKey as String: 160];
            stillImageOutputSettings?.previewPhotoFormat = previewFormat;

            stillImageOutput.capturePhoto(with: stillImageOutputSettings!, delegate: self);
    }

    func didPressTakeAnother() {
        if (didTakePhoto == true) {
            imageView.isHidden = true;
            didTakePhoto = false;
        } else {
            captureSession?.startRunning();
            didTakePhoto = true;
            didPressTakePhoto();
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        didPressTakeAnother();
    }
}

Any suggestions?

Thanks in advance!


来源: stackexchange

问:
tf.cond lowers the training speed
I was using tensorflow input pipelines like cifar10 model in tensorflow and try to use tf.cond to do validation and I wrote something like this

```<code>train_data = model.input(istrain=True)
val_data = model.input(istrain=False)

# This selects which stream to use.
select_val = tf.placeholder(dtype=bool,shape=[],name='select_test')
data = tf.cond(
    select_val,
    lambda:val_data,
    lambda:train_data
)

# Here is the model.
loss = ...
train_op = ...
...

with tf.Session():
    ...
</code>```

And if I delete the cond and just use the training data, the speed is 4000 samples/s and if I use the code above, the speed decrease to 2300 samples/s. The validation pipeline capacity is set really small so it won't take too much memory in GPU. The frequency of doing validation is also really low.
I'm not sure what is going wrong and please help me out.

答:
tf.cond is not fully lazy. Any operations that are required by either of the branches of the cond will be run even if the branch that requires it is not the branch to be executed. So in your case, both model.input(istrain=True) and model.input(istrain=False) are being execute every time your data op is being called. The results of one of them is just ignored.

The documentation for cond gives a minimal code example:

Note that the conditional execution applies only to the operations
  defined in fn1 and fn2. Consider the following simple program:

```<code>z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
</code>```

If x < y, the tf.add operation will be executed and tf.square
  operation will not be executed. Since z is needed for at least one
  branch of the cond, the tf.mul operation is always executed,
  unconditionally. Although this behavior is consistent with the
  dataflow model of TensorFlow, it has occasionally surprised some users
  who expected a lazier semantics.

Also note, this means that if your model.input is pulling some set of data from a larger pool (say, a batch from an entire dataset), each time the cond is run, data gets pulled from both validation and training, and one set just gets thrown away. This can cause problems more serious than inefficiencies in some cases. For example, if you're processing only a certain number epochs, then with this code you're not actually processing that number of epochs because data was being pulled that was not used.

ContentLicense: CC BY-SA 3.0

Title: tf.cond lowers the training speed

Body:
I was using tensorflow input pipelines like cifar10 model in tensorflow and try to use tf.cond to do validation and I wrote something like this

train_data = model.input(istrain=True)
val_data = model.input(istrain=False)

# This selects which stream to use.
select_val = tf.placeholder(dtype=bool,shape=[],name='select_test')
data = tf.cond(
    select_val,
    lambda:val_data,
    lambda:train_data
)

# Here is the model.
loss = ...
train_op = ...
...

with tf.Session():
    ...

And if I delete the cond and just use the training data, the speed is 4000 samples/s and if I use the code above, the speed decrease to 2300 samples/s. The validation pipeline capacity is set really small so it won't take too much memory in GPU. The frequency of doing validation is also really low.
I'm not sure what is going wrong and please help me out.

Body:
tf.cond is not fully lazy. Any operations that are required by either of the branches of the cond will be run even if the branch that requires it is not the branch to be executed. So in your case, both model.input(istrain=True) and model.input(istrain=False) are being execute every time your data op is being called. The results of one of them is just ignored.

The documentation for cond gives a minimal code example:

Note that the conditional execution applies only to the operations
  defined in fn1 and fn2. Consider the following simple program:

z = tf.multiply(a, b)
result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))

If x < y, the tf.add operation will be executed and tf.square
  operation will not be executed. Since z is needed for at least one
  branch of the cond, the tf.mul operation is always executed,
  unconditionally. Although this behavior is consistent with the
  dataflow model of TensorFlow, it has occasionally surprised some users
  who expected a lazier semantics.

Also note, this means that if your model.input is pulling some set of data from a larger pool (say, a batch from an entire dataset), each time the cond is run, data gets pulled from both validation and training, and one set just gets thrown away. This can cause problems more serious than inefficiencies in some cases. For example, if you're processing only a certain number epochs, then with this code you're not actually processing that number of epochs because data was being pulled that was not used.


问:
Angular2 : how to call main component function from a child component
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

```<code>@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}
</code>```

button component html

```<code><div (click)="onBtnClick()">
    <button>btn</button>
</div>
</code>```

browser component

```<code>@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}
</code>```

browser component html

```<code><div>
<h1>browser title</h1>
<cb-button (click)="editCampus()"></cb-button>
</div>
</code>```

and finally in main component i'm including browser component

main-component.ts

```<code>editCampus() {
  alert('clicked');
}
</code>```

html

```<code><topology-browser [campus]="campus"></topology-browser>
</code>```

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

答:
```<code>export class CbButtonComponent {

     @Output() onClick: EventEmitter<string> = new EventEmitter<string>();

     onBtnClick(): void {
        this.onClick.emit('clicked');
    }
}
</code>```

In your browser component

HTML

```<code><div>
    <h1>browser title</h1>
    <cb-button (onclick)="buttonclicked($event)"></cb-button>
</div>
</code>```

Component

```<code>@Output() buttonClick: EventEmitter<string> = new EventEmitter<string>();

buttonclicked(clickedEvent){
   this.buttonClick.emit('clicked');
}
</code>```

In your parent Main component

```<code><topology-browser [campus]="campus" (buttonClick)="buttonComponentClicked($event)"></topology-browser>
</code>```

Component code

```<code>buttonComponentClicked(buttonClicked){
       /// method calls goes her

}
</code>```

By this way you are notifying the browser component with the click which is captured again in the main component and handled

Body:
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}

button component html

    <button>btn</button>

browser component

@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}

browser component html

browser title

<cb-button (click)="editCampus()"></cb-button>

and finally in main component i'm including browser component

main-component.ts

editCampus() {
  alert('clicked');
}

html

<topology-browser [campus]="campus"></topology-browser>

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

Body:
export class CbButtonComponent {

     @Output() onClick: EventEmitter<string> = new EventEmitter<string>();

     onBtnClick(): void {
        this.onClick.emit('clicked');
    }
}

In your browser component

HTML

<div>
    <h1>browser title</h1>
    <cb-button (onclick)="buttonclicked($event)"></cb-button>
</div>

Component

@Output() buttonClick: EventEmitter<string> = new EventEmitter<string>();

buttonclicked(clickedEvent){
   this.buttonClick.emit('clicked');
}

In your parent Main component

<topology-browser [campus]="campus" (buttonClick)="buttonComponentClicked($event)"></topology-browser>

Component code

buttonComponentClicked(buttonClicked){
       /// method calls goes her

}

By this way you are notifying the browser component with the click which is captured again in the main component and handled


问:
How to get MIUI Security app auto start permission programmatically?
I am not getting BOOT_COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile.

My BroadcastReciever is ---

```<code>public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Setting singleAlarm
    SingleAlarmHandler.getInstance().setAlarm(context);

    try {
        // Sending System Setting broadcast
        String offDate = SharedPrefrencesHandler.getInstance(context).readString(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        int type = SystemSettingsType.PHONE_SWITCH_ON_OFF.getNumericType();

        if (offDate == null)
            offDate = "";

        SystemSettingsHandler.getSystemSettingsHandler().makeSystemSettingsCall(context, type, offDate);
        SharedPrefrencesHandler.getInstance(context).removePrefrence(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        } catch (Exception e) {
            Log.e(ChaseForceApplication.TAG, e.getMessage());
        }
    }
}
</code>```

and manifest:

```<code>    <receiver
        android:name=".broadcastlisteners.OnBootReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
</code>```

with permission:

```<code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</code>```

Now I am not getting BOOT COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile as alarm is not set. But in other android mobiles it is working correctly.

I searched and found that it is problem in MIUI firmware. In such mobile they provide an in built security app and until you allow auto start permission in that Security app, you are unable to get broad cast (any notification).

And as soon as you check that permission in that app you start to get the broadcast.

Now my question is:

How to get MIUI Security app auto start permission( Phones like Redmi) programmatically?

答:
this question already has answer in two Stack Overflow threads:

thread #1 https://stackoverflow.com/a/40932178/1537413

```<code>String xiaomi = "Xiaomi";
final String CALC_PACKAGE_NAME = "com.miui.securitycenter";
final String CALC_PACKAGE_ACITIVITY = "com.miui.permcenter.autostart.AutoStartManagementActivity";
if (deviceManufacturer.equalsIgnoreCase(xiaomi)) {
    DisplayUtils.showDialog(activity, "Ask for permission", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(CALC_PACKAGE_NAME, CALC_PACKAGE_ACITIVITY));
                activity.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            } catch (Exception e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            }
        }
    }, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

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

thread #2 https://stackoverflow.com/a/41696993/1537413

```<code>String manufacturer = "xiaomi";
        if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
            //this will open auto start screen where user can enable permission for your app
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        }
</code>```

and for similar problem on huawei devices:

https://stackoverflow.com/a/35220476/1537413

```<code>    private void ifHuaweiAlert() {
    final SharedPreferences settings = getSharedPreferences("ProtectedApps", MODE_PRIVATE);
    final String saveIfSkip = "skipProtectedAppsMessage";
    boolean skipMessage = settings.getBoolean(saveIfSkip, false);
    if (!skipMessage) {
        final SharedPreferences.Editor editor = settings.edit();
        Intent intent = new Intent();
        intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
        if (isCallable(intent)) {
            final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(this);
            dontShowAgain.setText("Do not show again");
            dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    editor.putBoolean(saveIfSkip, isChecked);
                    editor.apply();
                }
            });

            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Huawei Protected Apps")
                    .setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", getString(R.string.app_name)))
                    .setView(dontShowAgain)
                    .setPositiveButton("Protected Apps", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            huaweiProtectedApps();
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        } else {
            editor.putBoolean(saveIfSkip, true);
            editor.apply();
        }
    }
}

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

private void huaweiProtectedApps() {
    try {
        String cmd = "am start -n com.huawei.systemmanager/.optimize.process.ProtectActivity";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            cmd += " --user " + getUserSerial();
        }
        Runtime.getRuntime().exec(cmd);
    } catch (IOException ignored) {
    }
}

private String getUserSerial() {
    //noinspection ResourceType
    Object userManager = getSystemService("user");
    if (null == userManager) return "";

    try {
        Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle", (Class<?>[]) null);
        Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class, (Object[]) null);
        Method getSerialNumberForUser = userManager.getClass().getMethod("getSerialNumberForUser", myUserHandle.getClass());
        Long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle);
        if (userSerial != null) {
            return String.valueOf(userSerial);
        } else {
            return "";
        }
    } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ignored) {
    }
    return "";
}
</code>```

Body:
I am not getting BOOT_COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile.

My BroadcastReciever is ---

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Setting singleAlarm
    SingleAlarmHandler.getInstance().setAlarm(context);

    try {
        // Sending System Setting broadcast
        String offDate = SharedPrefrencesHandler.getInstance(context).readString(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        int type = SystemSettingsType.PHONE_SWITCH_ON_OFF.getNumericType();

        if (offDate == null)
            offDate = "";

        SystemSettingsHandler.getSystemSettingsHandler().makeSystemSettingsCall(context, type, offDate);
        SharedPrefrencesHandler.getInstance(context).removePrefrence(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        } catch (Exception e) {
            Log.e(ChaseForceApplication.TAG, e.getMessage());
        }
    }
}

and manifest:

    <receiver
        android:name=".broadcastlisteners.OnBootReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

with permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Now I am not getting BOOT COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile as alarm is not set. But in other android mobiles it is working correctly.

I searched and found that it is problem in MIUI firmware. In such mobile they provide an in built security app and until you allow auto start permission in that Security app, you are unable to get broad cast (any notification).

And as soon as you check that permission in that app you start to get the broadcast.

Now my question is:

How to get MIUI Security app auto start permission( Phones like Redmi) programmatically?

Body:
this question already has answer in two Stack Overflow threads:

thread #1 https://stackoverflow.com/a/40932178/1537413

String xiaomi = "Xiaomi";
final String CALC_PACKAGE_NAME = "com.miui.securitycenter";
final String CALC_PACKAGE_ACITIVITY = "com.miui.permcenter.autostart.AutoStartManagementActivity";
if (deviceManufacturer.equalsIgnoreCase(xiaomi)) {
    DisplayUtils.showDialog(activity, "Ask for permission", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(CALC_PACKAGE_NAME, CALC_PACKAGE_ACITIVITY));
                activity.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            } catch (Exception e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            }
        }
    }, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
}

thread #2 https://stackoverflow.com/a/41696993/1537413

String manufacturer = "xiaomi";
        if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
            //this will open auto start screen where user can enable permission for your app
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        }

and for similar problem on huawei devices:

https://stackoverflow.com/a/35220476/1537413

    private void ifHuaweiAlert() {
    final SharedPreferences settings = getSharedPreferences("ProtectedApps", MODE_PRIVATE);
    final String saveIfSkip = "skipProtectedAppsMessage";
    boolean skipMessage = settings.getBoolean(saveIfSkip, false);
    if (!skipMessage) {
        final SharedPreferences.Editor editor = settings.edit();
        Intent intent = new Intent();
        intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
        if (isCallable(intent)) {
            final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(this);
            dontShowAgain.setText("Do not show again");
            dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    editor.putBoolean(saveIfSkip, isChecked);
                    editor.apply();
                }
            });

            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Huawei Protected Apps")
                    .setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", getString(R.string.app_name)))
                    .setView(dontShowAgain)
                    .setPositiveButton("Protected Apps", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            huaweiProtectedApps();
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        } else {
            editor.putBoolean(saveIfSkip, true);
            editor.apply();
        }
    }
}

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

private void huaweiProtectedApps() {
    try {
        String cmd = "am start -n com.huawei.systemmanager/.optimize.process.ProtectActivity";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            cmd += " --user " + getUserSerial();
        }
        Runtime.getRuntime().exec(cmd);
    } catch (IOException ignored) {
    }
}

private String getUserSerial() {
    //noinspection ResourceType
    Object userManager = getSystemService("user");
    if (null == userManager) return "";

    try {
        Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle", (Class<?>[]) null);
        Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class, (Object[]) null);
        Method getSerialNumberForUser = userManager.getClass().getMethod("getSerialNumberForUser", myUserHandle.getClass());
        Long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle);
        if (userSerial != null) {
            return String.valueOf(userSerial);
        } else {
            return "";
        }
    } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ignored) {
    }
    return "";
}


问:
How to convert data unicode in database from latin1 to utf8 without losing current data?
i have mysql databse and it's charset id latin1_swedish_ci  and as example one column apear like that ( ?Œ????? ?‡???£?¤?¦???‡?? )

this is example of table

```<code>-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 27, 2017 at 02:49 PM
-- Server version: 5.5.44-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4.21

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Database: `a`
--

-- --------------------------------------------------------

--
-- Table structure for table `block`
--

CREATE TABLE IF NOT EXISTS `block` (
  `catid` int(12) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `rtl` int(12) NOT NULL DEFAULT '1',
  `ratteb` int(11) NOT NULL DEFAULT '0',
  `comment` text NOT NULL,
  `showcat` int(11) NOT NULL DEFAULT '0',
  `nostyle` varchar(255) NOT NULL,
  `tab` varchar(255) NOT NULL,
  `additional_locs` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`catid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=285 ;

--
-- Dumping data for table `block`
--

INSERT INTO `block` (`catid`, `name`, `rtl`, `ratteb`, `comment`, `showcat`, `nostyle`, `tab`, `additional_locs`) VALUES
(198, '???â€،?â€ ?آ£?â€° ?آ£?â€?????â€°', 1, 18, '', 2, '', '', NULL),
(2, '?â€،???ث†???â€¹', 2, 1, '', 2, '', '', NULL),
(3, '?????â€،?? ?â€،???â€™?آ¦?â€،?â€ک ?â€،???آ£???آ¦?â€،?إ’???آ?آ¤', 1, 8, '', 2, '', '', NULL);
</code>```

i know how to change the charset but when i change it to uft8 the current data did not changed.
i want to know is it possible to repair the old data to correct one?

thanks

UPDATE:

the charset in php is windows-1256

答:
Since you have question marks coming out, the data is lost.  It was lost during INSERT because latin1 had no encoding for some of your characters.

Start over.

Have your editor/etc. set to UTF-8.

HTML forms should start like <form accept-charset="UTF-8">.

Have your bytes encoded as UTF-8.

Establish UTF-8 as the encoding being used in the client.

Have the column/table declared CHARACTER SET utf8mb4 (Check with SHOW CREATE TABLE.)

<meta charset=UTF-8> at the beginning of HTML output.

More discussion:  Trouble with utf8 characters; what I see is not what I stored

Possibly you needed CHARACTER SET cp1256, which I think is equivalent to Windows-1256.

Since INSERT INTO block... looks like the output from mysqldump, it may have been done incorrectly.  Again, start over, but all the way back before the dump.

Do not use latin1 for Arabic.  It would be better to use CHARACTER SET utf8mb4, but utf8 or cp1256 would work if you don't go beyond English and Arabic.

Body:
i have mysql databse and it's charset id latin1_swedish_ci  and as example one column apear like that ( ?Œ????? ?‡???£?¤?¦???‡?? )

this is example of table

-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 27, 2017 at 02:49 PM
-- Server version: 5.5.44-0ubuntu0.14.04.1
-- PHP Version: 5.5.9-1ubuntu4.21

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Database: `a`
--

-- --------------------------------------------------------

--
-- Table structure for table `block`
--

CREATE TABLE IF NOT EXISTS `block` (
  `catid` int(12) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `rtl` int(12) NOT NULL DEFAULT '1',
  `ratteb` int(11) NOT NULL DEFAULT '0',
  `comment` text NOT NULL,
  `showcat` int(11) NOT NULL DEFAULT '0',
  `nostyle` varchar(255) NOT NULL,
  `tab` varchar(255) NOT NULL,
  `additional_locs` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`catid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=285 ;

--
-- Dumping data for table `block`
--

INSERT INTO `block` (`catid`, `name`, `rtl`, `ratteb`, `comment`, `showcat`, `nostyle`, `tab`, `additional_locs`) VALUES
(198, '???â€،?â€ ?آ£?â€° ?آ£?â€?????â€°', 1, 18, '', 2, '', '', NULL),
(2, '?â€،???ث†???â€¹', 2, 1, '', 2, '', '', NULL),
(3, '?????â€،?? ?â€،???â€™?آ¦?â€،?â€ک ?â€،???آ£???آ¦?â€،?إ’???آ?آ¤', 1, 8, '', 2, '', '', NULL);

i know how to change the charset but when i change it to uft8 the current data did not changed.
i want to know is it possible to repair the old data to correct one?

thanks

UPDATE:

the charset in php is windows-1256


问:
using linq to flatten data
How can I flatten the following data using linq.

Here I want to group by Column1 and Column2 and Column3 are the Key and value of a Dictionary

```<code>Pete, small, 2.0
Pete, medium, 3.5
Sbux, small, 2.5
Sbux, medium, 3.0
Mcd, large, 3.0
Mcd, refill, 5.0
Dd, refill, 4.0
Dd, solo, 2.0
cb, xlarge, 4.0
cb, premium, 5.0
Sb, premium, 4.0
Sb, xlarge,refill,extra, 7.0
</code>```

to following -

```<code>Pete, small, 2.0, medium, 3.5
Sbux, small, 2.5, medium, 3.0
Mcd, large, 3.0, refill, 5.0
Dd, refill, 4.0, solo, 2.0
Cb, xlarge, 4.0, premium, 4.0
Sb, premium, 4.0, xlarge,refill,extra, 7.0
</code>```

答:
Assuming that Column2 values do not repeat within Column1 group, the solution can be as follows:

```<code>var flat = data
    .GroupBy(item => item.Column1)
    .Select(g => new {
        Column1 = g.Key
    ,   Dict = g.ToDictionary(r => r.Column2, r => r.Column3)
    }).ToList();
</code>```

Title: using linq to flatten data

Body:
How can I flatten the following data using linq.

Here I want to group by Column1 and Column2 and Column3 are the Key and value of a Dictionary

Pete, small, 2.0
Pete, medium, 3.5
Sbux, small, 2.5
Sbux, medium, 3.0
Mcd, large, 3.0
Mcd, refill, 5.0
Dd, refill, 4.0
Dd, solo, 2.0
cb, xlarge, 4.0
cb, premium, 5.0
Sb, premium, 4.0
Sb, xlarge,refill,extra, 7.0

to following -

Pete, small, 2.0, medium, 3.5
Sbux, small, 2.5, medium, 3.0
Mcd, large, 3.0, refill, 5.0
Dd, refill, 4.0, solo, 2.0
Cb, xlarge, 4.0, premium, 4.0
Sb, premium, 4.0, xlarge,refill,extra, 7.0

Body:
Assuming that Column2 values do not repeat within Column1 group, the solution can be as follows:

var flat = data
    .GroupBy(item => item.Column1)
    .Select(g => new {
        Column1 = g.Key
    ,   Dict = g.ToDictionary(r => r.Column2, r => r.Column3)
    }).ToList();


问:
How to pass options to this function?
How to pass options to the search function as described in the API section of nlcst-search.

```<code>search(node, patterns, handler[, allowApostrophes|options])
</code>```

I want to pass allowDashes option to it. The code I currently have is:

```<code>search(node, patterns, handler);
function handler(){
//my code
}
</code>```

I tried search(node, patterns, handler, allowDashes) but it fails. Any help appreciated.

答:
According to the docs,

options (Object) — Configuration: allowApostrophes (boolean, default:
  false) — Configuration for nlcst-normalize);

    allowDashes(boolean, default: false) — Configuration for nlcst-normalize);   allowLiterals(boolean, default: false) — Include literal phrases

options is an object with allowDashes as boolean.

Try:

```<code>search(node, patterns, handler, {allowDashes:true})
</code>```

Title: How to pass options to this function?

Body:
How to pass options to the search function as described in the API section of nlcst-search.

search(node, patterns, handler[, allowApostrophes|options])

I want to pass allowDashes option to it. The code I currently have is:

search(node, patterns, handler);
function handler(){
//my code
}

I tried search(node, patterns, handler, allowDashes) but it fails. Any help appreciated.

Body:
According to the docs,

options (Object) — Configuration: allowApostrophes (boolean, default:
  false) — Configuration for nlcst-normalize);

    allowDashes(boolean, default: false) — Configuration for nlcst-normalize);   allowLiterals(boolean, default: false) — Include literal phrases

options is an object with allowDashes as boolean.

Try:

search(node, patterns, handler, {allowDashes:true})


问:
how to replace a string on the second line in a text file using a batch file?
Ok so ive been working on a fairly complex batch file that basicly asks the user to create a text file that contains 6 (or more) lines of text. Then it takes that file and changes every instance of every letter to its respective number (for example if the first line of the text file said "programable" then the program would change all instances of the letter "a" into 1 and "b" into 2 and so on until it was all numbers. It would then read "16 18 15 7 18 1 13 1 2 12 5") and i would do that by using the following script:

```<code>set /p var=< text.txt
set var=%var:a=1%
echo.%var% >> text.txt
</code>```

However the only problem with this script is that it will only change the letter a on the first line to 1, not the letter "a" in the rest of the document.

I also tried splitting the document at the beginning of the program so that when the user types the text for the first line it sends it to a separate hidden file (text1.txt) instead of just sending all of the lines of text that the user types, into one text file (text.txt)

I did so using this:

```<code>set /p line1=type the first line:
echo %line1% >> text1.txt
attrib +h text1.txt
set /p line2=type the second line:
echo %line2% >> text2.txt
attrib +h text2.txt
:: ########################################################################
:: Im not going to repeat this 6 times but hopefully you get my point
:: ########################################################################
</code>```

Now the problem with splitting the lines into separate files is that it would be in-efficient and extremely time consuming to change all instances of every letter into their respective numbers, and do it for each line (or in this situation, file) that the user inputs... If it would help if i put all this in context, here is the script for my program so far, for the ":LOADING" subscript i am currently using the method i explained earlier where i split the lines into files.

Code: (Save As "stringparsing.bat")

```<code> @echo off
 title BETA
 cls
 echo.
 echo.
 echo.
 echo      Setting Variables...
 echo      Loading Language Database...
 :: ###################################################################################
 ::    CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE
 :: ###################################################################################
 :: An Idea i was thinking of trying was to put a subscript here that calls another
 :: batch file that contains a list of the letters set as variables to their
 :: respective numbers (example: SET a=1, SET b=2, SET c=3)
 :: -----------------------------------------------------------------------------------
 PING 1.1.1.1 -n 1 -w 3000 >NUL
 goto MAIN
 :MAIN
 set foo=0
 cls
 echo.
 echo.
 echo.
 echo.
 echo            ===================================
 echo             #################################
 echo             #######     Main Menu:    #######
 echo             #################################
 echo            ===================================
 echo.
 echo.
 echo             1.) Create New Language File...
 echo.
 echo             2.) Load Existing Lanuage File...
 echo.
 echo             3.) Settings...
 echo ---------------------------------------------------------
 SET /p CHOICE= Select a Function:
 IF %CHOICE%== 1 GOTO CREATE
 IF %CHOICE%== 2 GOTO LOAD
 IF %CHOICE%== 3 GOTO SETTINGS
 GOTO MAIN
 :CREATE
 cls
 title Step 1
 echo.
 echo.
 echo.
 echo                echo ============================================================================
 echo.
 set /p name=  please type a name for your new language file:
 echo.
 echo         =================================================================================
 cls
 echo.
 echo.
 echo.
 echo   ==============================================================
 echo   ##############################################################
 echo   #============================================================#
 echo   #                                                            #
 echo   # - After you hit enter you will be redirected               #
 echo   #   to a Live Typer. so anything you type into               #
 echo   #   it will be sent to %name%.txt.                           #
 echo   #                                                            #
 echo   #                                                            #
 echo   # - Next, select load language!                              #
 echo   #                                                            #
 echo   #============================================================#
 echo   ##############################################################
 echo   ==============================================================
 pause
 goto typer1
 :typer1
 cls
 set /p line1= :
 echo %line1% >> %name%1.txt
 attrib +h %name%1.txt
 cls
 set /p line2= :
 echo %line2% >> %name%2.txt
 attrib +h %name%2.txt
 cls
 set /p line3= :
 echo %line3% >> %name%3.txt
 attrib +h %name%3.txt
 cls
 set /p line4= :
 echo %line4% >> %name%4.txt
 attrib +h %name%4.txt
 cls
 set /p line5= :
 echo %line5% >> %name%5.txt
 attrib +h %name%5.txt
 cls
 set /p line6= :
 echo %line6% >> %name%6.txt
 attrib +h %name%6.txt
 cls
 echo.
 echo.
 echo.
 echo ==========================================================
 echo.
 (
 IF EXIST %name%1.txt echo - FIRST LINE CONFIRMED.
 IF EXIST %name%2.txt echo - SECOND LINE CONFIRMED.
 IF EXIST %name%3.txt echo - THIRD LINE CONFIRMED.
 IF EXIST %name%4.txt echo - FOURTH LINE CONFIRMED.
 IF EXIST %name%5.txt echo - FIFTH LINE CONFIRMED.
 IF EXIST %name%6.txt echo - SIXTH LINE CONFIRMED.
 echo %name% > Language_File.txt
 attrib +h Language_File.txt
 set /a foo+ =1
 )
 echo.
 echo ==========================================================
 goto LOAD
 :LOAD
 set /a foo+ =1
 IF %foo%== 2 goto loadexternal
 goto LOAD23
 :loadexternal
 echo.
 echo language file is loading now!
 pause > nul
 cls
 set /p name=<Language_File.txt
 echo.
 echo.
 echo Language_File Loaded!
 pause >nul
 goto LOAD23
 :LOAD23
 cls
 echo.
 echo.
 echo.
 echo.
 echo.
 echo        Encoding Your Language File... Please Wait...
 echo.
 echo.
 echo.
 PING 1.1.1.1 -n 1 -w 3000 >NUL
 :A1
 set /p var=< %name%1.txt
 set var=%var:a=1%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "A" done.
 goto B1
 :B1
 set /p var=< %name%1.txt
 set var=%var:b=2%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "B" done.
 goto C1
 :C1
 set /p var=< %name%1.txt
 set var=%var:c=3%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "C" done.
 goto D1
 :D1
 set /p var=< %name%1.txt
 set var=%var:d=4%
 echo %var% >  %name%1.txt
 echo         "D" done.
 goto E1
 :E1
 set /p var=< %name%1.txt
 set var=%var:e=5%
 echo %var% >  %name%1.txt
 echo         "E" done.
 goto F1
 :F1
 set /p var=< %name%1.txt
 set var=%var:f=6%
 echo %var% >  %name%1.txt
 echo         "F" done.
 pause
 cls
 type %name%.txt
 pause >nul
 goto MAIN
 :END
 cls
 title SHUTTING DOWN...
 echo.
 echo.
 echo.
 echo            Terminating service stream...
 echo.
 echo.
 echo.
 echo.
 echo            Done! Thank you for using this program!
 ping 1.1.1.1 w -n 1 -w 6000 > NUL
 Exit***
</code>```

If you have a solution i would be glad to hear it because i have been searching high and low for a solution to this problem but have found nothing. Also, if any one notices any other mistakes or errors in my script then please feel free to comment!

Thanks in advance!

PS. If the last script i posted in this topic didnt come out right or it was all mixed up then just download the script from this link:

[http://home.danieljewison.operaunite.com/f/content/Documents/stringparsing.bat][1]

答:
Let me introduce you to my friend, the for loop.  Save all the lines the user entered into a single file.  I'll call this file input.txt.  Use a for loop with the /f switch and the delims= option to loop through every line in the file, and store the lines in the variable %%i.  Without delims=, it'd read only until the first whitespace character.

For each line it reads, do your text substitution.  The "gotcha" with batch programming is when you set variables inside a for loop, you have to add the line setlocal enabledelayedexpansion at the top of your file, and use ! instead of % to access the variable contents.

```<code>@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in (input.txt) do (
echo translating "%%i"... ^<insert fake delay here^>
set var=%%i
set var=!var:a=1 !
set var=!var:b=2 !
set var=!var:c=3 !
set var=!var:d=4 !
set var=!var:e=5 !
set var=!var:f=6 !
set var=!var:g=7 !
set var=!var:h=8 !
set var=!var:i=9 !
set var=!var:j=10 !
set var=!var:k=11 !
set var=!var:l=12 !
set var=!var:m=13 !
set var=!var:n=14 !
set var=!var:o=15 !
set var=!var:p=16 !
set var=!var:q=17 !
set var=!var:r=18 !
set var=!var:s=19 !
set var=!var:t=20 !
set var=!var:u=21 !
set var=!var:v=22 !
set var=!var:w=23 !
set var=!var:x=24 !
set var=!var:y=25 !
set var=!var:z=26 !
echo !var!
)
</code>```

If input.txt has these contents:

```<code>programable
this is line 2
third line
</code>```

Then the output would look like this:

```<code>C:\batch>encode.cmd
translating "programable"... <insert fake delay here>
16 18 15 7 18 1 13 1 2 12 5
translating "this is line 2"... <insert fake delay here>
20 8 9 19  9 19  12 9 14 5  2
translating "third line"... <insert fake delay here>
20 8 9 18 4  12 9 14 5
</code>```

As you can see, I left out the fake delay.  I like my programs fast. :)

ContentLicense: CC BY-SA 2.5

Body:
Ok so ive been working on a fairly complex batch file that basicly asks the user to create a text file that contains 6 (or more) lines of text. Then it takes that file and changes every instance of every letter to its respective number (for example if the first line of the text file said "programable" then the program would change all instances of the letter "a" into 1 and "b" into 2 and so on until it was all numbers. It would then read "16 18 15 7 18 1 13 1 2 12 5") and i would do that by using the following script:

set /p var=< text.txt
set var=%var:a=1%
echo.%var% >> text.txt

However the only problem with this script is that it will only change the letter a on the first line to 1, not the letter "a" in the rest of the document.

I also tried splitting the document at the beginning of the program so that when the user types the text for the first line it sends it to a separate hidden file (text1.txt) instead of just sending all of the lines of text that the user types, into one text file (text.txt)

I did so using this:

set /p line1=type the first line:
echo %line1% >> text1.txt
attrib +h text1.txt
set /p line2=type the second line:
echo %line2% >> text2.txt
attrib +h text2.txt
:: ########################################################################
:: Im not going to repeat this 6 times but hopefully you get my point
:: ########################################################################

Now the problem with splitting the lines into separate files is that it would be in-efficient and extremely time consuming to change all instances of every letter into their respective numbers, and do it for each line (or in this situation, file) that the user inputs... If it would help if i put all this in context, here is the script for my program so far, for the ":LOADING" subscript i am currently using the method i explained earlier where i split the lines into files.

Code: (Save As "stringparsing.bat")

 @echo off
 title BETA
 cls
 echo.
 echo.
 echo.
 echo      Setting Variables...
 echo      Loading Language Database...
 :: ###################################################################################
 ::    CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE CALLING VARIABLE DATABASE
 :: ###################################################################################
 :: An Idea i was thinking of trying was to put a subscript here that calls another
 :: batch file that contains a list of the letters set as variables to their
 :: respective numbers (example: SET a=1, SET b=2, SET c=3)
 :: -----------------------------------------------------------------------------------
 PING 1.1.1.1 -n 1 -w 3000 >NUL
 goto MAIN
 :MAIN
 set foo=0
 cls
 echo.
 echo.
 echo.
 echo.
 echo            ===================================
 echo             #################################
 echo             #######     Main Menu:    #######
 echo             #################################
 echo            ===================================
 echo.
 echo.
 echo             1.) Create New Language File...
 echo.
 echo             2.) Load Existing Lanuage File...
 echo.
 echo             3.) Settings...
 echo ---------------------------------------------------------
 SET /p CHOICE= Select a Function:
 IF %CHOICE%== 1 GOTO CREATE
 IF %CHOICE%== 2 GOTO LOAD
 IF %CHOICE%== 3 GOTO SETTINGS
 GOTO MAIN
 :CREATE
 cls
 title Step 1
 echo.
 echo.
 echo.
 echo                echo ============================================================================
 echo.
 set /p name=  please type a name for your new language file:
 echo.
 echo         =================================================================================
 cls
 echo.
 echo.
 echo.
 echo   ==============================================================
 echo   ##############################################################
 echo   #============================================================#
 echo   #                                                            #
 echo   # - After you hit enter you will be redirected               #
 echo   #   to a Live Typer. so anything you type into               #
 echo   #   it will be sent to %name%.txt.                           #
 echo   #                                                            #
 echo   #                                                            #
 echo   # - Next, select load language!                              #
 echo   #                                                            #
 echo   #============================================================#
 echo   ##############################################################
 echo   ==============================================================
 pause
 goto typer1
 :typer1
 cls
 set /p line1= :
 echo %line1% >> %name%1.txt
 attrib +h %name%1.txt
 cls
 set /p line2= :
 echo %line2% >> %name%2.txt
 attrib +h %name%2.txt
 cls
 set /p line3= :
 echo %line3% >> %name%3.txt
 attrib +h %name%3.txt
 cls
 set /p line4= :
 echo %line4% >> %name%4.txt
 attrib +h %name%4.txt
 cls
 set /p line5= :
 echo %line5% >> %name%5.txt
 attrib +h %name%5.txt
 cls
 set /p line6= :
 echo %line6% >> %name%6.txt
 attrib +h %name%6.txt
 cls
 echo.
 echo.
 echo.
 echo ==========================================================
 echo.
 (
 IF EXIST %name%1.txt echo - FIRST LINE CONFIRMED.
 IF EXIST %name%2.txt echo - SECOND LINE CONFIRMED.
 IF EXIST %name%3.txt echo - THIRD LINE CONFIRMED.
 IF EXIST %name%4.txt echo - FOURTH LINE CONFIRMED.
 IF EXIST %name%5.txt echo - FIFTH LINE CONFIRMED.
 IF EXIST %name%6.txt echo - SIXTH LINE CONFIRMED.
 echo %name% > Language_File.txt
 attrib +h Language_File.txt
 set /a foo+ =1
 )
 echo.
 echo ==========================================================
 goto LOAD
 :LOAD
 set /a foo+ =1
 IF %foo%== 2 goto loadexternal
 goto LOAD23
 :loadexternal
 echo.
 echo language file is loading now!
 pause > nul
 cls
 set /p name=<Language_File.txt
 echo.
 echo.
 echo Language_File Loaded!
 pause >nul
 goto LOAD23
 :LOAD23
 cls
 echo.
 echo.
 echo.
 echo.
 echo.
 echo        Encoding Your Language File... Please Wait...
 echo.
 echo.
 echo.
 PING 1.1.1.1 -n 1 -w 3000 >NUL
 :A1
 set /p var=< %name%1.txt
 set var=%var:a=1%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "A" done.
 goto B1
 :B1
 set /p var=< %name%1.txt
 set var=%var:b=2%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "B" done.
 goto C1
 :C1
 set /p var=< %name%1.txt
 set var=%var:c=3%
 echo.%var%
 echo %var% >  %name%1.txt
 echo.
 echo.
 echo.
 echo         "C" done.
 goto D1
 :D1
 set /p var=< %name%1.txt
 set var=%var:d=4%
 echo %var% >  %name%1.txt
 echo         "D" done.
 goto E1
 :E1
 set /p var=< %name%1.txt
 set var=%var:e=5%
 echo %var% >  %name%1.txt
 echo         "E" done.
 goto F1
 :F1
 set /p var=< %name%1.txt
 set var=%var:f=6%
 echo %var% >  %name%1.txt
 echo         "F" done.
 pause
 cls
 type %name%.txt
 pause >nul
 goto MAIN
 :END
 cls
 title SHUTTING DOWN...
 echo.
 echo.
 echo.
 echo            Terminating service stream...
 echo.
 echo.
 echo.
 echo.
 echo            Done! Thank you for using this program!
 ping 1.1.1.1 w -n 1 -w 6000 > NUL
 Exit***

If you have a solution i would be glad to hear it because i have been searching high and low for a solution to this problem but have found nothing. Also, if any one notices any other mistakes or errors in my script then please feel free to comment!

Thanks in advance!

PS. If the last script i posted in this topic didnt come out right or it was all mixed up then just download the script from this link:

[http://home.danieljewison.operaunite.com/f/content/Documents/stringparsing.bat][1]

Body:
Let me introduce you to my friend, the for loop.  Save all the lines the user entered into a single file.  I'll call this file input.txt.  Use a for loop with the /f switch and the delims= option to loop through every line in the file, and store the lines in the variable %%i.  Without delims=, it'd read only until the first whitespace character.

For each line it reads, do your text substitution.  The "gotcha" with batch programming is when you set variables inside a for loop, you have to add the line setlocal enabledelayedexpansion at the top of your file, and use ! instead of % to access the variable contents.

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%i in (input.txt) do (
echo translating "%%i"... ^<insert fake delay here^>
set var=%%i
set var=!var:a=1 !
set var=!var:b=2 !
set var=!var:c=3 !
set var=!var:d=4 !
set var=!var:e=5 !
set var=!var:f=6 !
set var=!var:g=7 !
set var=!var:h=8 !
set var=!var:i=9 !
set var=!var:j=10 !
set var=!var:k=11 !
set var=!var:l=12 !
set var=!var:m=13 !
set var=!var:n=14 !
set var=!var:o=15 !
set var=!var:p=16 !
set var=!var:q=17 !
set var=!var:r=18 !
set var=!var:s=19 !
set var=!var:t=20 !
set var=!var:u=21 !
set var=!var:v=22 !
set var=!var:w=23 !
set var=!var:x=24 !
set var=!var:y=25 !
set var=!var:z=26 !
echo !var!
)

If input.txt has these contents:

programable
this is line 2
third line

Then the output would look like this:

C:\batch>encode.cmd
translating "programable"... <insert fake delay here>
16 18 15 7 18 1 13 1 2 12 5
translating "this is line 2"... <insert fake delay here>
20 8 9 19  9 19  12 9 14 5  2
translating "third line"... <insert fake delay here>
20 8 9 18 4  12 9 14 5

As you can see, I left out the fake delay.  I like my programs fast. :)


问:
How to update test box in Serial_data_received event?
I found tons of answers to this question, but none worked for me so far and I am desperate to fix my issue.
This is using C#.

I am using delegate method to invoke my function which updates the test box and some other controls.

I open the Form with Frm.ShowDialog() and close with this.Close();

My delegate declarations are in Class header :

```<code>    public delegate void AddDataDelegate(String myString);
    public AddDataDelegate myDelegate;
</code>```

I call the following in Form_Load with event attachment to serial port data received event.

```<code>    private void frmNewRecipe_Load(object sender, EventArgs e)
    {

    //    if (Singleton.wickController.tinyGConnected) { panel1.Enabled = true; }
        populateRecipeNames();
        populatePalletNames();

        this.myDelegate = new AddDataDelegate(AddDataMethod);

        globalSingleTon.Singleton.Instance.tinyGSerialPort.DataReceived += new SerialDataReceivedEventHandler(tinyGSerialPort_DataReceived);
    }
</code>```

```<code>public void AddDataMethod(String s)
    {

        int i = 0;
        txtSerial.AppendText(s + "\n");

        if (s.Contains("stat:3") || s.Contains("Stop"))
        {
            globalSingleTon.Singleton.wickController.stageReady = true;
        }

        if (s.Contains("pos"))
            {................
</code>```

Data received event:

```<code>    private void tinyGSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs args)
    {
        string s = "";
        //            try
        {
            while (globalSingleTon.Singleton.Instance.tinyGSerialPort.BytesToRead > 0)
            {
                s = globalSingleTon.Singleton.Instance.tinyGSerialPort.ReadLine();

                {
                    if (InvokeRequired)
                    {
                        txtSerial.BeginInvoke(this.myDelegate, new Object[] { s });
                    }
                    else AddDataMethod(s);
                }
            }

        }
    }
</code>```

Here is the issue now. This whole thing works fine when I open the form for the first time after running the application. I found that during debugging that
"InvokeRequired" is true for the first time when I run but fail when I open the form second time (without closing the application). It is likely that my txtSerial control is in a different thread than the delegate.

When InvokeRequired is False, I see that the txtSerial.appendText triggers but nothing gets into the control.

If I close the form and reopen, nothing works. No change with using dispose() either. Could some one help fixing this issue ? I am really frustrated with this now. I am sure this is related to threading but could not get it fixed with many solutions I found here so far.

I have more updates. I was able to narrow it little further down. Problem happens when InvokeRequired is false. When I call text update method when "InvokeRequired" is false (IsHandleCreated is true), Text boxes aren't getting anything. (No errors either.) However interestingly, Message Box shows all incoming data in "s" string.

Why is not the controls getting values ?

```<code>private void tinyGSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs args)
    {
        string s = "";
        //            try
        {
    //        if (!txtSerial.IsHandleCreated) { txtSerial.CreateControl(); }
            while (globalSingleTon.Singleton.Instance.tinyGSerialPort.BytesToRead > 0)
            {
                s = globalSingleTon.Singleton.Instance.tinyGSerialPort.ReadLine();

                {
                    if (InvokeRequired)
                        {
                        IAsyncResult result = this.BeginInvoke(this.myDelegate, new Object[] { s });
                        this.EndInvoke(result);
                    }
                    else
                    {
                        if (IsHandleCreated)
                        {
                            txtSerial.Text = s + "\n";
                            txtSerial.Text = "This is the test";
                            txtReceipeName.Text = s;
                            MessageBox.Show(s);
                        }
                    }
                }
            }
        }
    }
</code>```

Thanks,
Pubudu

答:
Try below. Added this.Invoke((MethodInvoker)delegate for the statement which requires UI controls property change e.g. txtSerial.AppendText(s + "\n");

```<code>public void AddDataMethod(String s)
{
    this.Invoke((MethodInvoker)delegate
    {
        int i = 0;
        txtSerial.AppendText(s + "\n");

        if (s.Contains("stat:3") || s.Contains("Stop"))
        {
            globalSingleTon.Singleton.wickController.stageReady = true;
        }

        if (s.Contains("pos"))
            {................
        :
        :
    });
}
</code>```

Body:
I found tons of answers to this question, but none worked for me so far and I am desperate to fix my issue.
This is using C#.

I am using delegate method to invoke my function which updates the test box and some other controls.

I open the Form with Frm.ShowDialog() and close with this.Close();

My delegate declarations are in Class header :

    public delegate void AddDataDelegate(String myString);
    public AddDataDelegate myDelegate;

I call the following in Form_Load with event attachment to serial port data received event.

    private void frmNewRecipe_Load(object sender, EventArgs e)
    {

    //    if (Singleton.wickController.tinyGConnected) { panel1.Enabled = true; }
        populateRecipeNames();
        populatePalletNames();

        this.myDelegate = new AddDataDelegate(AddDataMethod);

        globalSingleTon.Singleton.Instance.tinyGSerialPort.DataReceived += new SerialDataReceivedEventHandler(tinyGSerialPort_DataReceived);
    }

public void AddDataMethod(String s)
    {

        int i = 0;
        txtSerial.AppendText(s + "\n");

        if (s.Contains("stat:3") || s.Contains("Stop"))
        {
            globalSingleTon.Singleton.wickController.stageReady = true;
        }

        if (s.Contains("pos"))
            {................

Data received event:

    private void tinyGSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs args)
    {
        string s = "";
        //            try
        {
            while (globalSingleTon.Singleton.Instance.tinyGSerialPort.BytesToRead > 0)
            {
                s = globalSingleTon.Singleton.Instance.tinyGSerialPort.ReadLine();

                {
                    if (InvokeRequired)
                    {
                        txtSerial.BeginInvoke(this.myDelegate, new Object[] { s });
                    }
                    else AddDataMethod(s);
                }
            }

        }
    }

Here is the issue now. This whole thing works fine when I open the form for the first time after running the application. I found that during debugging that
"InvokeRequired" is true for the first time when I run but fail when I open the form second time (without closing the application). It is likely that my txtSerial control is in a different thread than the delegate.

When InvokeRequired is False, I see that the txtSerial.appendText triggers but nothing gets into the control.

If I close the form and reopen, nothing works. No change with using dispose() either. Could some one help fixing this issue ? I am really frustrated with this now. I am sure this is related to threading but could not get it fixed with many solutions I found here so far.

I have more updates. I was able to narrow it little further down. Problem happens when InvokeRequired is false. When I call text update method when "InvokeRequired" is false (IsHandleCreated is true), Text boxes aren't getting anything. (No errors either.) However interestingly, Message Box shows all incoming data in "s" string.

Why is not the controls getting values ?

private void tinyGSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs args)
    {
        string s = "";
        //            try
        {
    //        if (!txtSerial.IsHandleCreated) { txtSerial.CreateControl(); }
            while (globalSingleTon.Singleton.Instance.tinyGSerialPort.BytesToRead > 0)
            {
                s = globalSingleTon.Singleton.Instance.tinyGSerialPort.ReadLine();

                {
                    if (InvokeRequired)
                        {
                        IAsyncResult result = this.BeginInvoke(this.myDelegate, new Object[] { s });
                        this.EndInvoke(result);
                    }
                    else
                    {
                        if (IsHandleCreated)
                        {
                            txtSerial.Text = s + "\n";
                            txtSerial.Text = "This is the test";
                            txtReceipeName.Text = s;
                            MessageBox.Show(s);
                        }
                    }
                }
            }
        }
    }

Thanks,
Pubudu

Body:
Try below. Added this.Invoke((MethodInvoker)delegate for the statement which requires UI controls property change e.g. txtSerial.AppendText(s + "\n");

public void AddDataMethod(String s)
{
    this.Invoke((MethodInvoker)delegate
    {
        int i = 0;
        txtSerial.AppendText(s + "\n");

        if (s.Contains("stat:3") || s.Contains("Stop"))
        {
            globalSingleTon.Singleton.wickController.stageReady = true;
        }

        if (s.Contains("pos"))
            {................
        :
        :
    });
}


问:
Jmockit MissingInvocation in mocking findComponentInParents
```<code>public abstract class AbstractValidator implements Validator
{
    @Override
    public abstract void validate(
        FacesContext context, UIComponent component, Object value)
        throws ValidatorException;

  protected String buildValidationMessage(String param)
    {
        return param;
    }

}

public abstract class AbstractMatchValidator extends AbstractValidator {

    protected String field1ComponentId;
    protected String field1InputLabel;
    protected String inputLabel;

    protected abstract String cleanBeforeComparing(String value);

    @Override
    public void validate(FacesContext context,
                         UIComponent component,
                         Object value) throws ValidatorException {
        UIInput input1 = Components.findComponentInParents(component,
                field1ComponentId);
        if (null == input1) {
            return;
        }
        String field1 = null;
        if (input1.isValid()) {
            field1 = this.cleanBeforeComparing((String)input1.getValue());
        }
        String confirmField = this.cleanBeforeComparing((String) value);

        if (!StringUtils.isBlank(field1) && !field1.equals(confirmField)) {
            input1.setValid(false);
            FacesMessage msg = buildValidationMessage(context,
                    this.inputLabel,
                    this.fieldToMatchInputLabel);
            throw new ValidatorException(msg);
        }
    }

public class EmployeeIDMatchValidator extends AbstractFieldMatchValidator {

    protected String cleanBeforeComparing(String value) {
        return value.replace("_",":");
    }

public class SSNMatchValidator extends AbstractFieldMatchValidator {

    protected String cleanBeforeComparing(String value) {
        return value.replace("_","-");
    }
</code>```

And I have this Jmockit test:

```<code>@RunWith(JMockit.class)
public class EmployeeIDMatchValidatorTest {

@Tested
EmployeeIDMatchValidator validator;

    @Test
    @SuppressWarnings(value = "unchecked")
    public final void testNoExceptionIsThrownForNoEmployeeIDValue(
            @Mocked FacesContext facesContext,
            @Mocked UIInput textInput,
            @Mocked UIInput uiInput){
        new MockUp<Components>() {
            @Mock
            public  <C extends UIComponent> C findComponentInParents(UIComponent component, String clientId) {
                return (C) textInput;
            }
        };

        new Expectations() {{
            textInput.getSubmittedValue();
                result="9-9192121-1";

            MessageFormat.format(anyString, any);
            result = "Employee ID is invalid.";

            }};

        validator.validate(facesContext, uiInput, "9-91921211");
    }

}
</code>```

When I ran this test, the textInput and uiInput values shows as null. Can someone please tell me why the values are not passed to findComponentInParents method.

I am getting this error in the logs:

```<code>mockit.internal.MissingInvocation: Missing 1 invocation to:
javax.faces.component.UIInput#getSubmittedValue()
   on mock instance: javax.faces.component.UIInput@1a04f701
</code>```

what is that I am missing here in this test? please help.

答:
JMockit is letting you know that you're not invoking that method, and according to the code you shared, you're "expecting" one invocation by using the block:

```<code> new Expectations() {{
            textInput.getSubmittedValue();
                result="9-9192121-1"; ...
  }};
</code>```

If what you want to return an specific value that ok, but the method that you're testing doesn't call the getSubmittedValue(), but it call the getValue() method.

```<code>new Expectations() {{
                uiInput.getValue();
                    result="9-9192121-1";
  //... more code
}};
</code>```

You might want to add to your expectations the isValid() method too, for the getValue() to be called.

```<code>new Expectations() {{
            uiInput.isValid(); result = true;
            uiInput.getValue(); result="9-9192121-1";

           // ... more code
    }};
</code>```

Don't forget everything you mentioned inside the static block of Expectations should be called at least once. For more information:
http://jmockit.org/api1x/mockit/Expectations.html

Body:
public abstract class AbstractValidator implements Validator
{
    @Override
    public abstract void validate(
        FacesContext context, UIComponent component, Object value)
        throws ValidatorException;

  protected String buildValidationMessage(String param)
    {
        return param;
    }

}

public abstract class AbstractMatchValidator extends AbstractValidator {

    protected String field1ComponentId;
    protected String field1InputLabel;
    protected String inputLabel;

    protected abstract String cleanBeforeComparing(String value);

    @Override
    public void validate(FacesContext context,
                         UIComponent component,
                         Object value) throws ValidatorException {
        UIInput input1 = Components.findComponentInParents(component,
                field1ComponentId);
        if (null == input1) {
            return;
        }
        String field1 = null;
        if (input1.isValid()) {
            field1 = this.cleanBeforeComparing((String)input1.getValue());
        }
        String confirmField = this.cleanBeforeComparing((String) value);

        if (!StringUtils.isBlank(field1) && !field1.equals(confirmField)) {
            input1.setValid(false);
            FacesMessage msg = buildValidationMessage(context,
                    this.inputLabel,
                    this.fieldToMatchInputLabel);
            throw new ValidatorException(msg);
        }
    }

public class EmployeeIDMatchValidator extends AbstractFieldMatchValidator {

    protected String cleanBeforeComparing(String value) {
        return value.replace("_",":");
    }

public class SSNMatchValidator extends AbstractFieldMatchValidator {

    protected String cleanBeforeComparing(String value) {
        return value.replace("_","-");
    }

And I have this Jmockit test:

@RunWith(JMockit.class)
public class EmployeeIDMatchValidatorTest {

@Tested
EmployeeIDMatchValidator validator;

    @Test
    @SuppressWarnings(value = "unchecked")
    public final void testNoExceptionIsThrownForNoEmployeeIDValue(
            @Mocked FacesContext facesContext,
            @Mocked UIInput textInput,
            @Mocked UIInput uiInput){
        new MockUp<Components>() {
            @Mock
            public  <C extends UIComponent> C findComponentInParents(UIComponent component, String clientId) {
                return (C) textInput;
            }
        };

        new Expectations() {{
            textInput.getSubmittedValue();
                result="9-9192121-1";

            MessageFormat.format(anyString, any);
            result = "Employee ID is invalid.";

            }};

        validator.validate(facesContext, uiInput, "9-91921211");
    }

}

When I ran this test, the textInput and uiInput values shows as null. Can someone please tell me why the values are not passed to findComponentInParents method.

I am getting this error in the logs:

mockit.internal.MissingInvocation: Missing 1 invocation to:
javax.faces.component.UIInput#getSubmittedValue()
   on mock instance: javax.faces.component.UIInput@1a04f701

what is that I am missing here in this test? please help.

Body:
JMockit is letting you know that you're not invoking that method, and according to the code you shared, you're "expecting" one invocation by using the block:

 new Expectations() {{
            textInput.getSubmittedValue();
                result="9-9192121-1"; ...
  }};

If what you want to return an specific value that ok, but the method that you're testing doesn't call the getSubmittedValue(), but it call the getValue() method.

new Expectations() {{
                uiInput.getValue();
                    result="9-9192121-1";
  //... more code
}};

You might want to add to your expectations the isValid() method too, for the getValue() to be called.

new Expectations() {{
            uiInput.isValid(); result = true;
            uiInput.getValue(); result="9-9192121-1";

           // ... more code
    }};

Don't forget everything you mentioned inside the static block of Expectations should be called at least once. For more information:
http://jmockit.org/api1x/mockit/Expectations.html


问:
Need some help on a beam break sensor code for Arduino
I am working on this code and I cant figure out how to implement a loop reset.

I want the program to return to idle if anytime during the initial 10 second countdown the beam is reconnected.   So in other words here is what I want to tell the Arduino: if at any time during the 10 second
count down you see beamPin high (beam connected) reset the loop.
There has to be a simple way to do this.

I am trying to use this code but it is not working like I want it to.

```<code>if (state == PAUSE_BEFORE_ON) {

//Wait in tight loop while counting down 10 second pause...
while (millis() - start_time >= PAUSE_BEFORE_ON_ms) {

  //Check if BEAM is reconnected...
  //If it is, reset to IDLE mode
  if ( !beamIsBroken() ) {

    state = IDLE;
  }
</code>```

Here is the entire code

```<code>//Diesels High Tech Pet beam break sensor
//This sketch activates and deactivates the "hold Up" function which is build into the HIGH TECH pet door
//By imitating pressing and holding "ON BUTTON" while pressing "OPEN BUTTON" and then releasing both buttons

enum State {
  IDLE, PAUSE_BEFORE_ON, ON_DELAY, OPEN_DELAY, WAIT_BEAM, PAUSE_BEFORE_CLOSE, OFF_DELAY
} state = IDLE;

uint32_t start_time;

const uint32_t PAUSE_BEFORE_ON_ms = 10L * 1000L; //pause for 10 seconds before initiating sequence
const uint32_t ON_DELAY_ms = 500L;  // pause for half a second before sending ON signal
const uint32_t OPEN_DELAY_ms = 500L;  // pause for half a second before sending OPEN signal
const uint32_t PAUSE_BEFORE_CLOSE_ms = 2L * 1000L; // pause for 2 seconds before sending ground signal to openPin which deactivates "hold Up" funtion
const uint32_t OFF_DELAY_ms = 250L;// pause for quarter of a second

const byte onPin = 2;    // On button
const byte openPin = 3;  // Open button
const byte beamPin = 4;  // QT50CM yellow wire of receiver

void activateButton(byte pin) {
  // to activate a button, we ground the pin
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void deactivateButton(byte pin) {
  // to deactivate a button, we float the pin
  pinMode(pin, INPUT);
  digitalWrite(pin, LOW);
}

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

  deactivateButton(onPin);
  deactivateButton(openPin);
  pinMode(beamPin, INPUT_PULLUP);  // turn on internal 5.1k pullup resistor

  state = IDLE;
  start_time = millis();
}

boolean beamIsBroken() {
  //'broken beam' grounds the output
  return digitalRead(beamPin) == LOW;

}

/**
  --wait for beam to break (IDLE)
  --beam breaks
  --wait 10 seconds  (PAUSE_BEFORE_ON)
  --send signal to ON
  --wait half a second  (ON_DELAY)
  --send signal to OPEN
  --wait half a second  (OPEN_DELAY)
  --release/turn off/float both signals
  --wait for beam to reconnect  (WAIT_BEAM)
  --wait another 2 seconds (PAUSE_BEFORE_CLOSE)
  --send ground signal to ON(which deactivates function)
  --wait 1/4 of a second (OFF_DELAY)
  --turn off "hold Up funtion" by sending ground signal to openPin
  --wait for beam to break again  (IDLE)
*/

void loop() {

 switch (state) {
   case IDLE:
      if (beamIsBroken()) {
        state = PAUSE_BEFORE_ON;
        start_time = millis();

      }
      break;

    case PAUSE_BEFORE_ON:
      if (millis() - start_time >= PAUSE_BEFORE_ON_ms) {
        activateButton(onPin);

        state = ON_DELAY;
        start_time = millis();
      }
      break;

    case ON_DELAY:
      if (millis() - start_time >= ON_DELAY_ms) {
        activateButton(openPin);

        state = OPEN_DELAY;
        start_time = millis();
      }
      break;

    case OPEN_DELAY:
      if (millis() - start_time >= OPEN_DELAY_ms) {
        deactivateButton(openPin);
        deactivateButton(onPin);

        state = WAIT_BEAM;
        start_time = millis();
      }
      break;

    case WAIT_BEAM:
      if (!beamIsBroken()) {
        state = PAUSE_BEFORE_CLOSE;
        start_time = millis();
      }
      break;

    case PAUSE_BEFORE_CLOSE:
      if (beamIsBroken()) {
        state = WAIT_BEAM;
        start_time = millis();
      }
      else  if (millis() - start_time >= PAUSE_BEFORE_CLOSE_ms) {
        activateButton(openPin);

        state = OFF_DELAY;
        start_time = millis();
      }
      break;

    case OFF_DELAY:
      if (millis() - start_time >= OFF_DELAY_ms) {
        deactivateButton(openPin);

        state = IDLE;
        start_time = millis();
      }
      break;
  }

}
</code>```

答:
Try adding a second if statement to route the state machine back to the IDLE state in the PAUSE_BEFORE_ON state. </p>

```<code>case PAUSE_BEFORE_ON:
  if (millis() - start_time >= PAUSE_BEFORE_ON_ms) {
    activateButton(onPin);

    state = ON_DELAY;
    start_time = millis();
  }
  if ( !beamIsBroken() ) {
    state = IDLE;
  }
  break;
</code>```

Body:
I am working on this code and I cant figure out how to implement a loop reset.

I want the program to return to idle if anytime during the initial 10 second countdown the beam is reconnected.   So in other words here is what I want to tell the Arduino: if at any time during the 10 second
count down you see beamPin high (beam connected) reset the loop.
There has to be a simple way to do this.

I am trying to use this code but it is not working like I want it to.

if (state == PAUSE_BEFORE_ON) {

//Wait in tight loop while counting down 10 second pause...
while (millis() - start_time >= PAUSE_BEFORE_ON_ms) {

  //Check if BEAM is reconnected...
  //If it is, reset to IDLE mode
  if ( !beamIsBroken() ) {

    state = IDLE;
  }

Here is the entire code

//Diesels High Tech Pet beam break sensor
//This sketch activates and deactivates the "hold Up" function which is build into the HIGH TECH pet door
//By imitating pressing and holding "ON BUTTON" while pressing "OPEN BUTTON" and then releasing both buttons

enum State {
  IDLE, PAUSE_BEFORE_ON, ON_DELAY, OPEN_DELAY, WAIT_BEAM, PAUSE_BEFORE_CLOSE, OFF_DELAY
} state = IDLE;

uint32_t start_time;

const uint32_t PAUSE_BEFORE_ON_ms = 10L * 1000L; //pause for 10 seconds before initiating sequence
const uint32_t ON_DELAY_ms = 500L;  // pause for half a second before sending ON signal
const uint32_t OPEN_DELAY_ms = 500L;  // pause for half a second before sending OPEN signal
const uint32_t PAUSE_BEFORE_CLOSE_ms = 2L * 1000L; // pause for 2 seconds before sending ground signal to openPin which deactivates "hold Up" funtion
const uint32_t OFF_DELAY_ms = 250L;// pause for quarter of a second

const byte onPin = 2;    // On button
const byte openPin = 3;  // Open button
const byte beamPin = 4;  // QT50CM yellow wire of receiver

void activateButton(byte pin) {
  // to activate a button, we ground the pin
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void deactivateButton(byte pin) {
  // to deactivate a button, we float the pin
  pinMode(pin, INPUT);
  digitalWrite(pin, LOW);
}

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

  deactivateButton(onPin);
  deactivateButton(openPin);
  pinMode(beamPin, INPUT_PULLUP);  // turn on internal 5.1k pullup resistor

  state = IDLE;
  start_time = millis();
}

boolean beamIsBroken() {
  //'broken beam' grounds the output
  return digitalRead(beamPin) == LOW;

}

/**
  --wait for beam to break (IDLE)
  --beam breaks
  --wait 10 seconds  (PAUSE_BEFORE_ON)
  --send signal to ON
  --wait half a second  (ON_DELAY)
  --send signal to OPEN
  --wait half a second  (OPEN_DELAY)
  --release/turn off/float both signals
  --wait for beam to reconnect  (WAIT_BEAM)
  --wait another 2 seconds (PAUSE_BEFORE_CLOSE)
  --send ground signal to ON(which deactivates function)
  --wait 1/4 of a second (OFF_DELAY)
  --turn off "hold Up funtion" by sending ground signal to openPin
  --wait for beam to break again  (IDLE)
*/

void loop() {

 switch (state) {
   case IDLE:
      if (beamIsBroken()) {
        state = PAUSE_BEFORE_ON;
        start_time = millis();

      }
      break;

    case PAUSE_BEFORE_ON:
      if (millis() - start_time >= PAUSE_BEFORE_ON_ms) {
        activateButton(onPin);

        state = ON_DELAY;
        start_time = millis();
      }
      break;

    case ON_DELAY:
      if (millis() - start_time >= ON_DELAY_ms) {
        activateButton(openPin);

        state = OPEN_DELAY;
        start_time = millis();
      }
      break;

    case OPEN_DELAY:
      if (millis() - start_time >= OPEN_DELAY_ms) {
        deactivateButton(openPin);
        deactivateButton(onPin);

        state = WAIT_BEAM;
        start_time = millis();
      }
      break;

    case WAIT_BEAM:
      if (!beamIsBroken()) {
        state = PAUSE_BEFORE_CLOSE;
        start_time = millis();
      }
      break;

    case PAUSE_BEFORE_CLOSE:
      if (beamIsBroken()) {
        state = WAIT_BEAM;
        start_time = millis();
      }
      else  if (millis() - start_time >= PAUSE_BEFORE_CLOSE_ms) {
        activateButton(openPin);

        state = OFF_DELAY;
        start_time = millis();
      }
      break;

    case OFF_DELAY:
      if (millis() - start_time >= OFF_DELAY_ms) {
        deactivateButton(openPin);

        state = IDLE;
        start_time = millis();
      }
      break;
  }

}

Body:
Try adding a second if statement to route the state machine back to the IDLE state in the PAUSE_BEFORE_ON state.

case PAUSE_BEFORE_ON:
  if (millis() - start_time >= PAUSE_BEFORE_ON_ms) {
    activateButton(onPin);

    state = ON_DELAY;
    start_time = millis();
  }
  if ( !beamIsBroken() ) {
    state = IDLE;
  }
  break;