问:
CoreMotion - get left-right, bottom-up movement on iPhone in landscape
I am making an App which able to make panorama video in landscape. In landscape, it supports two directions: left to right and bottom to top.

So I want to move an arrow from left to right when user move the phone from left to right or rotate to right. Also want to move the arrow bottom to top when move the device vertically upwards.
In native iPhone camera app with panorama option, there we can see the correct simulation,

My questions are 1) how do I know user is moving the phone from left to right or right to left. Because like iPhone panorama, I want to stop recording when user move back.

Also 2) how do I know user is moving the phone vertically upwards

Added : Nov 10, 2017:
I did see an app named Spincle in AppStore. It is moving the arrow when rotate the device from left to right to take 360 image. I just managed to achieve this using pitch and roll (see the below code). But this will not work if we stand device to floor or roof a bit.

```<code>import UIKit
import CoreMotion
class ViewController: UIViewController {
    private let motionManager = CMMotionManager()
    let arrowView = UIView()
    func startMotion() {
        var initialAttitude: CMAttitude?
        motionManager.deviceMotionUpdateInterval = 1
        let queue = OperationQueue.current!
        let statusBarOrientation = UIApplication.shared.statusBarOrientation
        motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical, to: queue) { (motiondata, err) in
            guard let data = motiondata else { return }
            if initialAttitude == nil {
                initialAttitude = data.attitude
            } else {
                let attitude = data.attitude
                // translate the attitude
                attitude.multiply(byInverseOf: initialAttitude!)
                // calculate pitch and roll of the change from our initial attitude
                let pitch = self.radiansToDegrees(attitude.pitch)
                let roll = self.radiansToDegrees(attitude.roll)
                print("\nroll = \(roll), pitch = \(pitch), yaw = \(self.radiansToDegrees(attitude.yaw))")
                print("x = \(data.userAcceleration.x), y = \(data.userAcceleration.y), z = \(data.userAcceleration.z)")
                DispatchQueue.main.async {
                    var rect = self.arrowView.frame
                    var addXPixel = self.view.frame.size.width/45
                    var addYPixel = self.view.frame.size.height/45
                    if statusBarOrientation == .landscapeRight {
                        addXPixel *= -1
                    } else {
                        addYPixel *= -1
                    }
                    rect.origin.x = (CGFloat(pitch) * addXPixel)
                    rect.origin.y = (self.view.frame.size.height/2 - 20) + (CGFloat(roll) * addYPixel)
                    self.arrowView.frame = rect
                }
            }
        }
    }
    func stopMotion() {
        motionManager.stopDeviceMotionUpdates()
    }
    func radiansToDegrees(_ radian: Double) -> Float {
        return Float(radian * 180.0/Double.pi)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(arrowView)
        arrowView.backgroundColor = UIColor.red
    }
    @IBAction func tappedButton() {
        arrowView.frame = CGRect(x: 0, y: self.view.frame.size.height/2 - 20, width: 40, height: 40)
        startMotion()
    }
}
</code>```

The issue is it will go left to right a bit and the arrow moving upwards or downwards

答:
You can use CLLocationManager to check the heading of your phone, and write your algorithm to determine the left-right / bottom-top movement by calculating CLHeading's degrees.

```<code>- (void)locationManager:(CLLocationManager*)manager
        didUpdateHeading:(CLHeading*)newHeading
</code>```

https://developer.apple.com/documentation/corelocation/clheading

Body:
I am making an App which able to make panorama video in landscape. In landscape, it supports two directions: left to right and bottom to top.

So I want to move an arrow from left to right when user move the phone from left to right or rotate to right. Also want to move the arrow bottom to top when move the device vertically upwards.
In native iPhone camera app with panorama option, there we can see the correct simulation,

My questions are 1) how do I know user is moving the phone from left to right or right to left. Because like iPhone panorama, I want to stop recording when user move back.

Also 2) how do I know user is moving the phone vertically upwards

Added : Nov 10, 2017:
I did see an app named Spincle in AppStore. It is moving the arrow when rotate the device from left to right to take 360 image. I just managed to achieve this using pitch and roll (see the below code). But this will not work if we stand device to floor or roof a bit.

import UIKit
import CoreMotion
class ViewController: UIViewController {
    private let motionManager = CMMotionManager()
    let arrowView = UIView()
    func startMotion() {
        var initialAttitude: CMAttitude?
        motionManager.deviceMotionUpdateInterval = 1
        let queue = OperationQueue.current!
        let statusBarOrientation = UIApplication.shared.statusBarOrientation
        motionManager.startDeviceMotionUpdates(using: CMAttitudeReferenceFrame.xArbitraryZVertical, to: queue) { (motiondata, err) in
            guard let data = motiondata else { return }
            if initialAttitude == nil {
                initialAttitude = data.attitude
            } else {
                let attitude = data.attitude
                // translate the attitude
                attitude.multiply(byInverseOf: initialAttitude!)
                // calculate pitch and roll of the change from our initial attitude
                let pitch = self.radiansToDegrees(attitude.pitch)
                let roll = self.radiansToDegrees(attitude.roll)
                print("\nroll = \(roll), pitch = \(pitch), yaw = \(self.radiansToDegrees(attitude.yaw))")
                print("x = \(data.userAcceleration.x), y = \(data.userAcceleration.y), z = \(data.userAcceleration.z)")
                DispatchQueue.main.async {
                    var rect = self.arrowView.frame
                    var addXPixel = self.view.frame.size.width/45
                    var addYPixel = self.view.frame.size.height/45
                    if statusBarOrientation == .landscapeRight {
                        addXPixel *= -1
                    } else {
                        addYPixel *= -1
                    }
                    rect.origin.x = (CGFloat(pitch) * addXPixel)
                    rect.origin.y = (self.view.frame.size.height/2 - 20) + (CGFloat(roll) * addYPixel)
                    self.arrowView.frame = rect
                }
            }
        }
    }
    func stopMotion() {
        motionManager.stopDeviceMotionUpdates()
    }
    func radiansToDegrees(_ radian: Double) -> Float {
        return Float(radian * 180.0/Double.pi)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(arrowView)
        arrowView.backgroundColor = UIColor.red
    }
    @IBAction func tappedButton() {
        arrowView.frame = CGRect(x: 0, y: self.view.frame.size.height/2 - 20, width: 40, height: 40)
        startMotion()
    }
}

The issue is it will go left to right a bit and the arrow moving upwards or downwards

Body:
You can use CLLocationManager to check the heading of your phone, and write your algorithm to determine the left-right / bottom-top movement by calculating CLHeading's degrees.

- (void)locationManager:(CLLocationManager*)manager
        didUpdateHeading:(CLHeading*)newHeading

https://developer.apple.com/documentation/corelocation/clheading


来源: stackexchange

问:
Display content after clicking Facebook Like button
I have a section of a webpage that I only want people to be able to access after clicking a Facebook Like button.

How do I hide that particular  area and then display it only after someone clicks the Like button.

As for the Facebook Like code it looks like this:

```<code><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="www.oursite.com" show_faces="false" width="330" font="verdana"></fb:like>

<div id="hidden-area">Hidden Content</div>
</code>```

答:
Use 'edge.create':

http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe

really simple... can even couple it with jQuery.

```<code><script>
    window.fbAsyncInit = function() {
        FB.init({
            appId   : '<?php echo $facebook->getAppId(); ?>',
            session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
            status  : true, // check login status
            cookie  : true, // enable cookies to allow the server to access the session
            xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
            window.location.reload();
        });

        FB.Event.subscribe('edge.create', function(response) {
            $.get('URLlink?uid=' + <?php echo $uid; ?>, function(data) {
                $('#id').html(data);
            });
        });
    };

    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a section of a webpage that I only want people to be able to access after clicking a Facebook Like button.

How do I hide that particular  area and then display it only after someone clicks the Like button.

As for the Facebook Like code it looks like this:

<fb:like href="www.oursite.com" show_faces="false" width="330" font="verdana"></fb:like>

Hidden Content

Body:
Use 'edge.create':

http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe

really simple... can even couple it with jQuery.

<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId   : '<?php echo $facebook->getAppId(); ?>',
            session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
            status  : true, // check login status
            cookie  : true, // enable cookies to allow the server to access the session
            xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
            window.location.reload();
        });

        FB.Event.subscribe('edge.create', function(response) {
            $.get('URLlink?uid=' + <?php echo $uid; ?>, function(data) {
                $('#id').html(data);
            });
        });
    };

    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());
</script>


问:
Javascript Iterator Issue
```<code>let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ')

let betterWords =
storyWords.filter(function(word) {
  if (unnecessaryWords.includes(word)) {
    return false;
  } else {
    return true;
  }
});

let superbWords = storyWords.reduce( (currentWordCount, word) => {
  if(overusedWords.includes(word)){
     return currentWordCount + 1;
     }
  return currentWordCount;
}**, 0);**
</code>```

I am having a hard time understanding how this part of the code works and why the zero is there. Could someone please help me understand this better.
    Thank you!

```<code>console.log(superbWords);
</code>```

答:
Have added comments to this snippet , hopefully it will be useful </p>

```<code>let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];
let unnecessaryWords = ['extremely', 'literally', 'actually' ];
let storyWords = story.split(' ')
// This will return an array which does not contain any elements
// which are in unnecessaryWords
let betterWords =
storyWords.filter(function(word) {
  if (unnecessaryWords.includes(word)) {
    return false;
  } else {
    return true;
  }
});
//applying array reduce function,the callback function accepts 4 parameter
// out of which the first two are known as accumulator & currentValue. It does not matter
// how it is named, 0 here is the starting number, you can read it as the
// first value is set to 0.Currently the result of  superbWords is 8 but
// instead of 0 if you pass 1 , the result will be 9

let superbWords = storyWords.reduce( (currentWordCount, word) => {
  if(overusedWords.includes(word)){
     return currentWordCount + 1;
     }
  return currentWordCount;
}, 0);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript Iterator Issue

Body:
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ')

let betterWords =
storyWords.filter(function(word) {
  if (unnecessaryWords.includes(word)) {
    return false;
  } else {
    return true;
  }
});

let superbWords = storyWords.reduce( (currentWordCount, word) => {
  if(overusedWords.includes(word)){
     return currentWordCount + 1;
     }
  return currentWordCount;
}**, 0);**

I am having a hard time understanding how this part of the code works and why the zero is there. Could someone please help me understand this better.
    Thank you!

console.log(superbWords);

Body:
Have added comments to this snippet , hopefully it will be useful

let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];
let unnecessaryWords = ['extremely', 'literally', 'actually' ];
let storyWords = story.split(' ')
// This will return an array which does not contain any elements
// which are in unnecessaryWords
let betterWords =
storyWords.filter(function(word) {
  if (unnecessaryWords.includes(word)) {
    return false;
  } else {
    return true;
  }
});
//applying array reduce function,the callback function accepts 4 parameter
// out of which the first two are known as accumulator & currentValue. It does not matter
// how it is named, 0 here is the starting number, you can read it as the
// first value is set to 0.Currently the result of  superbWords is 8 but
// instead of 0 if you pass 1 , the result will be 9

let superbWords = storyWords.reduce( (currentWordCount, word) => {
  if(overusedWords.includes(word)){
     return currentWordCount + 1;
     }
  return currentWordCount;
}, 0);


问:
Boolean logic for validation is failing
```<code>public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    if (rc.length() != 6 ) {
        validCode = false;
    } else if ( !Character.isLetter(rc.charAt(0)) ||
                !Character.isLetter(rc.charAt(1)) ||
                !Character.isDigit(rc.charAt(2)) ||
                !Character.isDigit(rc.charAt(3)) ||
                !Character.isDigit(rc.charAt(4)) ||
                !Character.isLetter(rc.charAt(5))) {
        validCode = false;
    } else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
        validCode = false;
    }
    return validCode;
}
</code>```

<p>This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help! </p>

答:
Find below logic , it will work . Better to use regular expressions .</p>

```<code>public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    String pattern= "^[a-zA-Z]{2}[0-9]{3}[BN]}$";
    if (rc.length() != 6) {
        validCode = false;
    }
    validCode = rc.matches(pattern);
    return validCode;
}
</code>```

Title: Boolean logic for validation is failing

Body:
public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    if (rc.length() != 6 ) {
        validCode = false;
    } else if ( !Character.isLetter(rc.charAt(0)) ||
                !Character.isLetter(rc.charAt(1)) ||
                !Character.isDigit(rc.charAt(2)) ||
                !Character.isDigit(rc.charAt(3)) ||
                !Character.isDigit(rc.charAt(4)) ||
                !Character.isLetter(rc.charAt(5))) {
        validCode = false;
    } else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
        validCode = false;
    }
    return validCode;
}

This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help!

Body:
Find below logic , it will work . Better to use regular expressions .

public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    String pattern= "^[a-zA-Z]{2}[0-9]{3}[BN]}$";
    if (rc.length() != 6) {
        validCode = false;
    }
    validCode = rc.matches(pattern);
    return validCode;
}


问:
android.widget.FrameLayout cannot be cast to com.example.crowderia.chat.view.SnapTabView?
I have a frame layout call view_snap_tabs.xml that have image and view like below

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    xmlns:tools="http://schemas.android.com/tools"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple">

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

</FrameLayout>
</code>```

I have included this layout in my activity_main.xml like below

```<code><include
        layout="@layout/view_snap_tabs"
        android:id="@+id/am_snap_tabs"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"/>
</code>```

I have created a method call SetUpViewPager and I'm trying to add that method in main activity like below

```<code>SnapTabView snapTabView = findViewById(R.id.am_snap_tabs);
snapTabView.setUpWithViewPager(viewPager);
</code>```

But when I run the application It will crash from there and give a ClassCastExeception how can I fix this?

EDITED====================================================================

```<code>public class SnapTabView extends FrameLayout implements ViewPager.OnPageChangeListener {

    private ImageView mCenterImage;
    private ImageView mStartImage;
    private ImageView mBottomImage;
    private ImageView mEndImage;
    private View mIndicator;
    private ArgbEvaluator mArgbEvaluator;
    private int mCenterColor;
    private int mSideColor;
    private int mEndViewsTranslationX;
    private int mIndicatorTranslationX;
    private int mCenterTransationY;

    public SnapTabView(@NonNull Context context) {
        this(context, null);
    }
    public SnapTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public SnapTabView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_snap_tabs, this, false);
        mCenterImage = (ImageView) findViewById(R.id.vst_center_image);
        mBottomImage = (ImageView) findViewById(R.id.vst_bottom_image);
        mEndImage = (ImageView) findViewById(R.id.vst_end_image);
        mStartImage = (ImageView) findViewById(R.id.vst_start_image);
        mIndicator = (View) findViewById(R.id.vst_indicator);
        mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
        mSideColor = ContextCompat.getColor(getContext(), R.color.dark_grey);
        mArgbEvaluator = new ArgbEvaluator();
        mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
        mBottomImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mEndViewsTranslationX = (int) ((mBottomImage.getX() - mStartImage.getX()) - mIndicatorTranslationX);
                mBottomImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mCenterTransationY = getHeight() - mBottomImage.getBottom();
            }
        });
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if(position == 0) {
            setColor(1 - positionOffset);
            moveViews(1 - positionOffset);
            mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
            moveAndScaleCenter(1 - positionOffset);

        } else if(position == 1) {
            setColor(positionOffset);
            moveViews(positionOffset);
            mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
            moveAndScaleCenter(positionOffset);

        }
    }
    public void setUpWithViewPager(final ViewPager viewPager) {
        viewPager.addOnPageChangeListener(this);
        mStartImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(viewPager.getCurrentItem() != 0)
                    viewPager.setCurrentItem(0);
            }
        });
        mEndImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(viewPager.getCurrentItem() != 2)
                    viewPager.setCurrentItem(2);
            }
        });
    }
    @Override
    public void onPageSelected(int position) {
    }
    @Override
    public void onPageScrollStateChanged(int state) {
    }
    private void setColor(float fractionFromCenter) {
        int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
        mCenterImage.setColorFilter(color);
        mStartImage.setColorFilter(color);
        mEndImage.setColorFilter(color);
    }

    private void moveViews(float fractionFromCenter) {
        mStartImage.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
        mEndImage.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
        mIndicator.setAlpha(fractionFromCenter);
        mIndicator.setScaleX(fractionFromCenter);
    }

    private void moveAndScaleCenter(float fractionFromCenter) {
        float scale = .7f + ((1 - fractionFromCenter) * .3f);
        mCenterImage.setScaleX(scale);
        mCenterImage.setScaleY(scale);
        int translation = (int) (fractionFromCenter * mCenterTransationY);
        mCenterImage.setTranslationY(translation);
        mBottomImage.setTranslationY(translation);
        mBottomImage.setAlpha(1 - fractionFromCenter);
    }
}
</code>```

view_snap_tabs.xml file like below

```<code><?xml version="1.0" encoding="utf-8"?>
<com.example.crowderia.chat.view.SnapTabView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple"
    android:id="@+id/snaps">

    <ImageView
        android:id="@+id/vst_center_image"
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/large_circle"
        android:layout_marginBottom="96dp"/>

    <ImageView
        android:id="@+id/vst_start_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="56dp"
        android:layout_marginStart="24dp"
        android:layout_gravity="start|bottom"
        android:src="@drawable/ic_chat_bubble_24dp"/>

    <ImageView
        android:id="@+id/vst_end_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="56dp"
        android:layout_marginEnd="24dp"
        android:layout_gravity="end|bottom"
        android:src="@drawable/ic_group_work_24dp"/>

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

</com.example.crowderia.chat.view.SnapTabView>
</code>```

答:
It's because you are trying to assign a view with FrameLayout to SnapTabView, modify your xml as below

view_snap_tabs.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<com.example.crowderia.chat.view.SnapTabView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    xmlns:tools="http://schemas.android.com/tools">

 <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="184dp"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple">

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

  </FrameLayout>

</com.example.crowderia.chat.view.SnapTabView>
</code>```

Body:
I have a frame layout call view_snap_tabs.xml that have image and view like below

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    xmlns:tools="http://schemas.android.com/tools"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple">

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

</FrameLayout>

I have included this layout in my activity_main.xml like below

<include
        layout="@layout/view_snap_tabs"
        android:id="@+id/am_snap_tabs"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"/>

I have created a method call SetUpViewPager and I'm trying to add that method in main activity like below

SnapTabView snapTabView = findViewById(R.id.am_snap_tabs);
snapTabView.setUpWithViewPager(viewPager);

But when I run the application It will crash from there and give a ClassCastExeception how can I fix this?

EDITED====================================================================

public class SnapTabView extends FrameLayout implements ViewPager.OnPageChangeListener {

    private ImageView mCenterImage;
    private ImageView mStartImage;
    private ImageView mBottomImage;
    private ImageView mEndImage;
    private View mIndicator;
    private ArgbEvaluator mArgbEvaluator;
    private int mCenterColor;
    private int mSideColor;
    private int mEndViewsTranslationX;
    private int mIndicatorTranslationX;
    private int mCenterTransationY;

    public SnapTabView(@NonNull Context context) {
        this(context, null);
    }
    public SnapTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public SnapTabView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_snap_tabs, this, false);
        mCenterImage = (ImageView) findViewById(R.id.vst_center_image);
        mBottomImage = (ImageView) findViewById(R.id.vst_bottom_image);
        mEndImage = (ImageView) findViewById(R.id.vst_end_image);
        mStartImage = (ImageView) findViewById(R.id.vst_start_image);
        mIndicator = (View) findViewById(R.id.vst_indicator);
        mCenterColor = ContextCompat.getColor(getContext(), R.color.white);
        mSideColor = ContextCompat.getColor(getContext(), R.color.dark_grey);
        mArgbEvaluator = new ArgbEvaluator();
        mIndicatorTranslationX = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
        mBottomImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mEndViewsTranslationX = (int) ((mBottomImage.getX() - mStartImage.getX()) - mIndicatorTranslationX);
                mBottomImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mCenterTransationY = getHeight() - mBottomImage.getBottom();
            }
        });
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if(position == 0) {
            setColor(1 - positionOffset);
            moveViews(1 - positionOffset);
            mIndicator.setTranslationX((positionOffset - 1) * mIndicatorTranslationX);
            moveAndScaleCenter(1 - positionOffset);

        } else if(position == 1) {
            setColor(positionOffset);
            moveViews(positionOffset);
            mIndicator.setTranslationX(positionOffset * mIndicatorTranslationX);
            moveAndScaleCenter(positionOffset);

        }
    }
    public void setUpWithViewPager(final ViewPager viewPager) {
        viewPager.addOnPageChangeListener(this);
        mStartImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(viewPager.getCurrentItem() != 0)
                    viewPager.setCurrentItem(0);
            }
        });
        mEndImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(viewPager.getCurrentItem() != 2)
                    viewPager.setCurrentItem(2);
            }
        });
    }
    @Override
    public void onPageSelected(int position) {
    }
    @Override
    public void onPageScrollStateChanged(int state) {
    }
    private void setColor(float fractionFromCenter) {
        int color = (int) mArgbEvaluator.evaluate(fractionFromCenter, mCenterColor, mSideColor);
        mCenterImage.setColorFilter(color);
        mStartImage.setColorFilter(color);
        mEndImage.setColorFilter(color);
    }

    private void moveViews(float fractionFromCenter) {
        mStartImage.setTranslationX(fractionFromCenter * mEndViewsTranslationX);
        mEndImage.setTranslationX(-fractionFromCenter * mEndViewsTranslationX);
        mIndicator.setAlpha(fractionFromCenter);
        mIndicator.setScaleX(fractionFromCenter);
    }

    private void moveAndScaleCenter(float fractionFromCenter) {
        float scale = .7f + ((1 - fractionFromCenter) * .3f);
        mCenterImage.setScaleX(scale);
        mCenterImage.setScaleY(scale);
        int translation = (int) (fractionFromCenter * mCenterTransationY);
        mCenterImage.setTranslationY(translation);
        mBottomImage.setTranslationY(translation);
        mBottomImage.setAlpha(1 - fractionFromCenter);
    }
}

view_snap_tabs.xml file like below

<?xml version="1.0" encoding="utf-8"?>
<com.example.crowderia.chat.view.SnapTabView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple"
    android:id="@+id/snaps">

    <ImageView
        android:id="@+id/vst_center_image"
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/large_circle"
        android:layout_marginBottom="96dp"/>

    <ImageView
        android:id="@+id/vst_start_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="56dp"
        android:layout_marginStart="24dp"
        android:layout_gravity="start|bottom"
        android:src="@drawable/ic_chat_bubble_24dp"/>

    <ImageView
        android:id="@+id/vst_end_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="56dp"
        android:layout_marginEnd="24dp"
        android:layout_gravity="end|bottom"
        android:src="@drawable/ic_group_work_24dp"/>

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

</com.example.crowderia.chat.view.SnapTabView>

Body:
It's because you are trying to assign a view with FrameLayout to SnapTabView, modify your xml as below

view_snap_tabs.xml

<?xml version="1.0" encoding="utf-8"?>
<com.example.crowderia.chat.view.SnapTabView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="184dp"
    xmlns:tools="http://schemas.android.com/tools">

 <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="184dp"
    tools:layout_gravity="bottom"
    tools:background="@color/light_purple">

    <ImageView
        android:id="@+id/vst_bottom_image"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginBottom="48dp"
        android:layout_gravity="center|bottom"
        android:src="@drawable/small_circle"/>

    <View
        android:id="@+id/vst_indicator"
        android:layout_width="48dp"
        android:layout_height="4dp"
        android:layout_gravity="bottom|center"
        android:layout_marginBottom="44dp"
        android:background="@drawable/indicator_background"/>

  </FrameLayout>

</com.example.crowderia.chat.view.SnapTabView>


问:
what is the meaning of the following line in php smarty?
I'm new to smarty and I'm seeing this line

```<code>   <link rel="shortcut icon" href="
   {$system['system_url']}/themes/{$system['theme']}/images/favicon.png" />
</code>```

This line is used to set favicon but they can use direct the image url "images/favicon.png" so why they used

答:
It is a best practice to isolate different resources as much as possible. Referencing a static file such as a favicon directly creates a direct link between the web framework and web layout. </p>

<p>Using the types of variables you see in your example, makes the path address to the favicon dynamic so if the app where to be moved, or renamed, the links between layout and framework would still work without needing to manually change all path addresses. </p>

Body:
I'm new to smarty and I'm seeing this line

   <link rel="shortcut icon" href="
   {$system['system_url']}/themes/{$system['theme']}/images/favicon.png" />

This line is used to set favicon but they can use direct the image url "images/favicon.png" so why they used

Body:
It is a best practice to isolate different resources as much as possible. Referencing a static file such as a favicon directly creates a direct link between the web framework and web layout.

Using the types of variables you see in your example, makes the path address to the favicon dynamic so if the app where to be moved, or renamed, the links between layout and framework would still work without needing to manually change all path addresses.


问:
What to do, Learn while Developing the app or Learn first and then develop the app
I am planning to develop a web and mobile application. Have a look on this Question on OnStartups

I have some PHP & MySql knowledge, however I didn't do any major projects so far.

My skills on a scale of 5

PHP&MySql 3/5,

Javascript 3/5

CSS 3/5

Android 1.5/5

IPhone    0/5

web development (2/5)

web    design(2/5)

Software Development &    management
(1.5/5)

My app, as said in one of the answers
in the question, is not much complex
as Mint. If the complexity of Mint is
rated 8. My app would be 5/8

I have lot of interest in programming. Only thing bothering and bogging me is the time to make the app live. I don't understand how to estimate the time as I am not so experienced.

Should I start developing the app and learn all the concepts on the way?

or

should I wait learn programming completely first and then develop the app.?

Edit: A small Edit based on below answers. How should I test myself to know whether I have the minimum web development knowledge to start developing the application.

答:
It is impossible to "programming completely" first. So you have to start to code your app learn, refactor your code, learn again, code, lear and refactor....

Don't be afraid to start coding while you are still learning.

Don't stop learning, if you already started to code.


问:
What is the mAP metric and how is it calculated?
In Computer Vision and Object Detection, a common evaluation method is mAP.
What is it and how is it calculated?</p>

答:
I think the important part here is linking how object detection can be considered the same as the standard information retrieval problems for which there exists at least one excellent description of average precision.

The output of some object detection algorithm is a set of proposed bounding boxes, and for each one, a confidence and classification scores (one score per class). Let's ignore the classification scores for now, and use the confidence as input to a threshold binary classification. Intuitively, the average precision is an aggregation over all choices for the threshold/cut-off value. But wait; in order to calculate precision, we need to know if a box is correct!

This is where it gets confusing/difficult; as opposed to typical information retrieval problems, we actually have an extra level of classification here. That is, we can't do exact matching between boxes, so we need to classify if a bounding box is correct or not. The solution is to essentially do a hard-coded classification on the box dimensions; we check if it sufficiently overlaps with any ground truth to be considered 'correct'. The threshold for this part is chosen by common sense. The dataset you are working on will likely define what this threshold for a 'correct' bounding box is. Most datasets just set it at 0.5 IoU and leave it at that (I recommend doing a few manual IoU calculations [they're not hard] to get a feel for how strict IoU of 0.5 actually is).

Now that we have actually defined what it means to be 'correct', we can just use the same process as information retrieval.

To find mean average precision (mAP), you just stratify your proposed boxes based on the maximum of the classification scores associated with those boxes, then average (take the mean) of the average precision (AP) over the classes.

TLDR; make the distinction between determining if a bounding box prediction is 'correct' (extra level of classification) and evaluating how well the box confidence informs you of a 'correct' bounding box prediction (completely analogous to information retrieval case) and the typical descriptions of mAP will make sense.

It's worth noting that Area under the Precision/Recall curve is the same thing as average precision, and we are essentially approximating this area with the trapezoidal or right-hand rule for approximating integrals.

ContentLicense: CC BY-SA 4.0


问:
Logging all presto queries
How can I store all queries submitted to presto cluster in a file (ORC file) or may be some other database. Purpose is the keep the record of all queries executed on presto workers.

I am aware that I need to overwrite queryCompleted method, I have also tried to follow this and other link mentioned over there but I am unable to create correct jar using maven. After placing the presto jar file generated by maven, my presto stopped working.

I am new to presto as well as in maven. It would be great if someone can help me with this.

答:
This is my way, and It works on EMR5.9 (presto 0.184).

Firstly, as you already know, you can use event-listener.
In my case, I use https://github.com/wyukawa/presto-fluentd for collecting query logs because fluentd is convenient.(easy to retry, easy to send
 to multiple data store)
if you want to create new event-listener plugin, also you can reference this because it's very simple. (or https://github.com/zz22394/presto-audit can also use for it)

Next, you have to install event-listener plugin.
If you use EMR, you can use this script for installing presto-fluentd on bootstrap actions

```<code># cf. https://github.com/mozilla/emr-bootstrap-presto/blob/master/files/bootstrap/presto-plugins.sh
#!/bin/bash

set -exo pipefail

# re-exec with sudo into background
if [ $(whoami) != root ]; then
  sudo "$0" "$@" &
  exit 0
fi

# set variables
s3uri=$1
fluentd_endpoint=$2

# wait until presto is installed and running
until test -s /var/run/presto/presto-server.pid; do sleep 1; done

# make symbolic link
sudo mkdir -p /usr/lib/presto/etc 2>/dev/null
sudo ln -s /usr/lib/presto/etc /mnt/var/lib/presto/data

# download presto plugins
aws s3 sync $s3uri/jar/ /usr/lib/presto/plugin/
aws s3 sync $s3uri/properties /usr/lib/presto/etc/

# make sure all plugins are owned by presto user
chown -R presto:presto /usr/lib/presto/plugin
chown -R presto:presto /usr/lib/presto/etc

# set event-listner.properties endpoint parameter
echo "event-listener.fluentd-host=$fluentd_endpoint" >>
/usr/lib/presto/etc/event-listener.properties

# restart presto
stop  presto-server
start presto-server
</code>```

event-listener.properties:

```<code>event-listener.name=presto-fluentd
event-listener.fluentd-port=24224
event-listener.fluentd-tag=presto.query
</code>```

inside s3 dir:

```<code>$ aws s3 ls s3://<s3 bucket>/emr/bootstrap_actions/plugins/jar/presto-fluentd/
2017-10-30 19:12:59      90318 fluency-1.3.0.jar
2017-10-30 19:12:59    2521113 guava-21.0.jar
2017-10-30 19:12:59      55783 jackson-annotations-2.8.1.jar
2017-10-30 19:12:59     252303 jackson-core-2.7.1.jar
2017-10-30 19:12:59    1199160 jackson-databind-2.7.1.jar
2017-10-30 19:12:59      30488 jackson-dataformat-msgpack-0.8.12.jar
2017-10-30 19:12:59       3907 log-0.148.jar
2017-10-30 19:12:59     116125 msgpack-core-0.8.12.jar
2017-10-30 19:12:59       5509 phi-accural-failure-detector-0.0.4.jar
2017-10-30 19:12:59       6130 presto-fluentd-0.0.1.jar
2017-10-30 19:12:59      41077 slf4j-api-1.7.22.jar

$ aws s3 ls s3://<s3 bucket>/emr/bootstrap_actions/plugins/properties/
2017-10-30 19:12:59        109 event-listener.properties
</code>```

and just receive query logs by fluentd working on another host like below

```<code><match presto.query>
  @type copy
  <store>
    # another data store
  </store>

  <store>
    @type relabel
    @label @presto-query-storage
  </store>
</match>

# In my case, I use bigquery for storing query log
<label @presto-query-storage>
  <match **>
    @label @presto-bigquery-out
    @type record_reformer
    renew_record true
    tag presto.query_storage.big_query
    <record>
      query_id ${record["queryId"]}
      user_name ${record["user"]}
      elapsed_time ${(record["endTime"] - record["createTime"]) / 1000.0}
      start_at
${Time.at(record["executionStartTime"]/1000).utc.strftime("%Y-%m-%d %H:%M:%S.%3N")}
      end_at ${Time.at(record["endTime"]/1000).utc.strftime("%Y-%m-%d %H:%M:%S")}
      query ${record["query"]}
      status ${record["state"]}
    </record>
  </match>
</label>
</code>```

Tips

I use this script for collecting dependencies of presto-fluentd.

```<code>require 'fileutils'
require 'open3'
include FileUtils

TMP_PATH = File.expand_path('../../tmp', __FILE__)
JAR_PATH = File.expand_path('../bootstrap_actions/plugins/jar', __FILE__)
CLONE_URI = 'https://github.com/wyukawa/presto-fluentd'

NEEDED_JAR = %w(
  fluency-1.3.0.jar
  guava-21.0.jar
  jackson-annotations-2.8.1.jar
  jackson-core-2.7.1.jar
  jackson-databind-2.7.1.jar
  jackson-dataformat-msgpack-0.8.12.jar
  log-0.148.jar
  msgpack-core-0.8.12.jar
  phi-accural-failure-detector-0.0.4.jar
  presto-fluentd-0.0.1.jar
  slf4j-api-1.7.22.jar
)

def cleanup_dir
  puts "Clean up #{TMP_PATH}/presto-fluentd ..."
  rm_r(Dir.glob("#{TMP_PATH}/presto-fluentd"))
  mkdir_p("#{JAR_PATH}/presto-fluentd")

  puts "Clean up #{JAR_PATH}/presto-fluentd ..."
  rm(Dir.glob("#{JAR_PATH}/presto-fluentd/*.jar"))
end

def clone
  cd(TMP_PATH)

  puts "Download presto-fluentd repo ..."
  out, err, status = Open3.capture2("git clone #{CLONE_URI} #{TMP_PATH}/presto-fluentd")
  puts out
end

def mvn
  cd("#{TMP_PATH}/presto-fluentd")

  puts "Build presto-fluentd ..."
  out, err, status = Open3.capture2("mvn clean package")
  puts out

  out, err, status = Open3.capture2("mvn dependency:copy-dependencies -DoutputDirectory=target -DincludeScope=runtime")
  puts out
end

def copy_dependencies
  cd("#{TMP_PATH}/presto-fluentd/target")
  puts "Copy jar files to #{JAR_PATH} ..."

  # FIXME: it's better to fix actual pom.xml for assign scope
  mv(Dir.glob("*.jar").select{|file| NEEDED_JAR.include?(file)}, "#{JAR_PATH}/presto-fluentd")
  puts "done !!"
end

cleanup_dir
clone
mvn
copy_dependencies
</code>```

Title: Logging all presto queries

Body:
This is my way, and It works on EMR5.9 (presto 0.184).

Firstly, as you already know, you can use event-listener.
In my case, I use https://github.com/wyukawa/presto-fluentd for collecting query logs because fluentd is convenient.(easy to retry, easy to send
 to multiple data store)
if you want to create new event-listener plugin, also you can reference this because it's very simple. (or https://github.com/zz22394/presto-audit can also use for it)

Next, you have to install event-listener plugin.
If you use EMR, you can use this script for installing presto-fluentd on bootstrap actions

# cf. https://github.com/mozilla/emr-bootstrap-presto/blob/master/files/bootstrap/presto-plugins.sh
#!/bin/bash

set -exo pipefail

# re-exec with sudo into background
if [ $(whoami) != root ]; then
  sudo "$0" "$@" &
  exit 0
fi

# set variables
s3uri=$1
fluentd_endpoint=$2

# wait until presto is installed and running
until test -s /var/run/presto/presto-server.pid; do sleep 1; done

# make symbolic link
sudo mkdir -p /usr/lib/presto/etc 2>/dev/null
sudo ln -s /usr/lib/presto/etc /mnt/var/lib/presto/data

# download presto plugins
aws s3 sync $s3uri/jar/ /usr/lib/presto/plugin/
aws s3 sync $s3uri/properties /usr/lib/presto/etc/

# make sure all plugins are owned by presto user
chown -R presto:presto /usr/lib/presto/plugin
chown -R presto:presto /usr/lib/presto/etc

# set event-listner.properties endpoint parameter
echo "event-listener.fluentd-host=$fluentd_endpoint" >>
/usr/lib/presto/etc/event-listener.properties

# restart presto
stop  presto-server
start presto-server

event-listener.properties:

event-listener.name=presto-fluentd
event-listener.fluentd-port=24224
event-listener.fluentd-tag=presto.query

inside s3 dir:

$ aws s3 ls s3://<s3 bucket>/emr/bootstrap_actions/plugins/jar/presto-fluentd/
2017-10-30 19:12:59      90318 fluency-1.3.0.jar
2017-10-30 19:12:59    2521113 guava-21.0.jar
2017-10-30 19:12:59      55783 jackson-annotations-2.8.1.jar
2017-10-30 19:12:59     252303 jackson-core-2.7.1.jar
2017-10-30 19:12:59    1199160 jackson-databind-2.7.1.jar
2017-10-30 19:12:59      30488 jackson-dataformat-msgpack-0.8.12.jar
2017-10-30 19:12:59       3907 log-0.148.jar
2017-10-30 19:12:59     116125 msgpack-core-0.8.12.jar
2017-10-30 19:12:59       5509 phi-accural-failure-detector-0.0.4.jar
2017-10-30 19:12:59       6130 presto-fluentd-0.0.1.jar
2017-10-30 19:12:59      41077 slf4j-api-1.7.22.jar

$ aws s3 ls s3://<s3 bucket>/emr/bootstrap_actions/plugins/properties/
2017-10-30 19:12:59        109 event-listener.properties

and just receive query logs by fluentd working on another host like below

<match presto.query>
  @type copy
  <store>
    # another data store
  </store>

  <store>
    @type relabel
    @label @presto-query-storage
  </store>
</match>

# In my case, I use bigquery for storing query log
<label @presto-query-storage>
  <match **>
    @label @presto-bigquery-out
    @type record_reformer
    renew_record true
    tag presto.query_storage.big_query
    <record>
      query_id ${record["queryId"]}
      user_name ${record["user"]}
      elapsed_time ${(record["endTime"] - record["createTime"]) / 1000.0}
      start_at
${Time.at(record["executionStartTime"]/1000).utc.strftime("%Y-%m-%d %H:%M:%S.%3N")}
      end_at ${Time.at(record["endTime"]/1000).utc.strftime("%Y-%m-%d %H:%M:%S")}
      query ${record["query"]}
      status ${record["state"]}
    </record>
  </match>
</label>

Tips

I use this script for collecting dependencies of presto-fluentd.

require 'fileutils'
require 'open3'
include FileUtils

TMP_PATH = File.expand_path('../../tmp', __FILE__)
JAR_PATH = File.expand_path('../bootstrap_actions/plugins/jar', __FILE__)
CLONE_URI = 'https://github.com/wyukawa/presto-fluentd'

NEEDED_JAR = %w(
  fluency-1.3.0.jar
  guava-21.0.jar
  jackson-annotations-2.8.1.jar
  jackson-core-2.7.1.jar
  jackson-databind-2.7.1.jar
  jackson-dataformat-msgpack-0.8.12.jar
  log-0.148.jar
  msgpack-core-0.8.12.jar
  phi-accural-failure-detector-0.0.4.jar
  presto-fluentd-0.0.1.jar
  slf4j-api-1.7.22.jar
)

def cleanup_dir
  puts "Clean up #{TMP_PATH}/presto-fluentd ..."
  rm_r(Dir.glob("#{TMP_PATH}/presto-fluentd"))
  mkdir_p("#{JAR_PATH}/presto-fluentd")

  puts "Clean up #{JAR_PATH}/presto-fluentd ..."
  rm(Dir.glob("#{JAR_PATH}/presto-fluentd/*.jar"))
end

def clone
  cd(TMP_PATH)

  puts "Download presto-fluentd repo ..."
  out, err, status = Open3.capture2("git clone #{CLONE_URI} #{TMP_PATH}/presto-fluentd")
  puts out
end

def mvn
  cd("#{TMP_PATH}/presto-fluentd")

  puts "Build presto-fluentd ..."
  out, err, status = Open3.capture2("mvn clean package")
  puts out

  out, err, status = Open3.capture2("mvn dependency:copy-dependencies -DoutputDirectory=target -DincludeScope=runtime")
  puts out
end

def copy_dependencies
  cd("#{TMP_PATH}/presto-fluentd/target")
  puts "Copy jar files to #{JAR_PATH} ..."

  # FIXME: it's better to fix actual pom.xml for assign scope
  mv(Dir.glob("*.jar").select{|file| NEEDED_JAR.include?(file)}, "#{JAR_PATH}/presto-fluentd")
  puts "done !!"
end

cleanup_dir
clone
mvn
copy_dependencies


问:
ASP.NET / Webforms / C# - populating 2nd dropdown based on 1st dropdown without postback with code behind binding
Please help.

I have 3 dropdowns :
1. Country
2. Port
3. Company Name

Once 1st dropdown (countries) is selected, 2nd dropdown should be populated with a list of specific ports, then based on 1st and 2nd dropdown, the 3rd dropdown will be populated also.

this is a one time key-in. Meaning once selection is done, the user will save it in db and the value should remain in the dropdown unless the user change.

Right now, i'm using OnSelectedIndexChanged which is very slow because of the postback.

let me know if there's any other way of doing.

Thanks,
Jack

答:
there could have several ways to achieve this. One of the ways is using WebService [WebMethod]. Ajax and JSON.</p>

```<code>//You databinding method must be public and add [WebMethod] attribute
[WebMethod]
public static List<ListItem> GetCustomers()
{
    string query = "SELECT CustId, CustName FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand(query))
    {
        List<ListItem> custListItem = new List<ListItem>();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                custListItem.Add(new ListItem
                {
                    Value = Convert.ToString(sdr["CustId"]),
                    Text = Convert.ToString(sdr["CustName"])
                });
            }
        }
        con.Close();
        return custListItem;
    }
}
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $.ajax({
        type: "POST",
        url: "CustomerList.aspx/GetCustomers",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlCustomers = $("[id*=ddlCustomers]");
            ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });
});
</script>
</code>```

Body:
there could have several ways to achieve this. One of the ways is using WebService [WebMethod]. Ajax and JSON.

//You databinding method must be public and add [WebMethod] attribute
[WebMethod]
public static List<ListItem> GetCustomers()
{
    string query = "SELECT CustId, CustName FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
    using (SqlCommand cmd = new SqlCommand(query))
    {
        List<ListItem> custListItem = new List<ListItem>();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                custListItem.Add(new ListItem
                {
                    Value = Convert.ToString(sdr["CustId"]),
                    Text = Convert.ToString(sdr["CustName"])
                });
            }
        }
        con.Close();
        return custListItem;
    }
}
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $.ajax({
        type: "POST",
        url: "CustomerList.aspx/GetCustomers",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlCustomers = $("[id*=ddlCustomers]");
            ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });
});
</script>


问:
React components not getting displayed on running the code in asp.net
I am new to react. I have created a simple form with reactjs in mvc asp.net. But on execution, react components are not getting displayed in the webpage. I have shared my code below. Please let me know where I have gone wrong.

Below is the Model class for my data:

```<code>public partial class ContactsData
    {
        public int ContactID { get; set; }
        public string Fullname { get; set; }
        public string Email { get; set; }
        public string Message { get; set; }
    }
</code>```

Below is the HomeController:

```<code>namespace ReactForm.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult SaveContactData(ContactsData contact)
        {
            bool status = false;
            string message = "";
            if(ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    dc.ContactsDatas.Add(contact);
                    dc.SaveChanges();
                    status = true;
                    message = "Thank you for submitting your query";
                }
            }
            else
            {
                status = false;
                message = "Failed! Please try again";
            }

                return new JsonResult { Data = new { status = status, message = message } };
        }
    }
}
</code>```

Below is the Index.cshtml:

```<code>@{
    ViewBag.Title = "Create simple form with validation in React.JS";
}

<div class="container">
    <h2>Create simple form with validation in React</h2>
    <div id="contactFormArea">
        </div>
</div>
@* LoaderOptimization css and js library *@

@* Bootstrap css*@
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
@* jquery library*@
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
@* React library *@
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
@* Our react component *@
<script src="~/scripts/ContactForm.js"></script>
<style type="text/css">
    .form-control.error {
    border-color:red;
    background-color:#FFF6F6;
    }
    spam.error{
        color:red;
    }
    .servermessage{
        font-size:32px;
        margin-top:20px;
    }
    </style>
</code>```

Below is the Reactjs code ContactForm.js:

```<code> //React component for input component
var MyInput = React.createClass({
    //onchange event
    handleChange: function (e) {
        this.props.onChange(e.target.value);
        var isValidField = this.isValid(e.target);
    },
    //validation function
    isValid: function (input) {
        //check required field
        if (input.getAttribute('required') != null && input.value === "") {
            input.classList.add('error'); //add class error
            input.nextSibling.textContent = this.props.messageRequired; //show error message
            return false;
        }
        else {
            input.classList.remove('error');
            input.nextSibling.textContent = "";
        }
        //check data type
        if (input.getAttribute('type') == "email" && input.value != "") {
            if (!this.validateEmail(input.value)) {
                input.classList.add('error');
                input.nextSibling.textContent = this.props.messageEmail;
            }
            else {
                input.classList.remove('error');
                input.nextSibling.textContent = "";
            }
        }
        return true;

    },
    //email validation function
    validateEmail: function (value) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(value);
    },
    componentDidMount: function () {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this); //register this input in the form
        }
    },
    //render
    render: function () {
        var inputField;
        if (this.props.type == 'textarea') {
            inputField = <textarea value={this.props.value} ref={this.props.name} name={this.props.name} className='form-control' required={this.props.isrequired} onChange={this.handleChange}/>
            }
        else{
            inputField = <input type={this.props.type} ref={this.props.name} name={this.props.name} className='form-control' required={this.props.isrequired} onChange={this.handleChange}/>
            }
        return (
            <div className="form-group">
                <lable htmlFor={this.props.htmlFor}>{this.props.lable}</label>
                {inputField}
                <span className="error"></span>
            </div>
            );
    }

});

//React component for generate form

var ContactForm = React.createClass({
    //get initial statement
    getInitialState : function(){
        return{
            Fullname : '',
            Email : '',
            Message : '',
            Fields : [],
            ServerMessage : ''
        }
    },
    // submit function
    handleSubmit : function(e){
        e.preventDefault();
        //validate entire form here
        var validForm = true;
        this.state.Fields.forEach(function(field){
            if(typeof field.isValid === "function"){
                var validField = field.isValid(field.refs[field.props.name]);
                validForm = validForm && validField;
            }
        });
        //after validation complete post to server
        if(validForm){
            var d={
                Fullname: this.state.Fullname,
                Email : this.state.Email,
                Message : this.state.Message
            }
            $.ajax({
                type :"POST",
                url : this.props.urlPost,
                data: d,
                success : function(data){
                    //will clear form here
                    this.setState({
                        Fullname : '',
                        Email : '',
                        Message: '',
                        ServerMessage: data.message
                    });

                }.bind(this),
                error : function(e){
                    console.log(e);
                    alert('Error! Please try again');
                }
            });
        }
    },
    //handle change full name
    onChangeFullname : function(value){
        this.setState({
            Fullname : value
        });
    },
    //handle change email
    onChangeEmail : function(value){
        this.setState({
            Email : value
        });
    },
    //handle change message
    onChangeMessage : function(value){
        this.setState({
            Message : value
        });
    },
    //register input controls
    register : function(field){
        var s = this.state.Fields;
        s.push(field);
        this.setState({
            Fields : s
        });
    },
    //render
    render : function(){
        //Render form
        return{
            <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
            <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
            <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
            <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
            <button type="submit" className="btn btn-default">submit</button>
                <p className="servermessage">{this.state.ServerMessage}</p>
                </form>
};
    }
});

//Render react component into the page
                ReactDOM.render(<ContactForm urlPost="/home/SaveContactData" />, document.getElementById('contactFormArea'));
</code>```

答:
The render() method of your ContactForm module is returning the form inside curly braces:

```<code>return {
    <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
        <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
        <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
        <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
        <button type="submit" className="btn btn-default">submit</button>
        <p className="servermessage">{this.state.ServerMessage}</p>
    </form>
};
</code>```

It should be returning the form inside parentheses:

```<code>return (
    <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
        <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
        <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
        <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
        <button type="submit" className="btn btn-default">submit</button>
        <p className="servermessage">{this.state.ServerMessage}</p>
    </form>
);
</code>```

Body:
I am new to react. I have created a simple form with reactjs in mvc asp.net. But on execution, react components are not getting displayed in the webpage. I have shared my code below. Please let me know where I have gone wrong.

Below is the Model class for my data:

public partial class ContactsData
    {
        public int ContactID { get; set; }
        public string Fullname { get; set; }
        public string Email { get; set; }
        public string Message { get; set; }
    }

Below is the HomeController:

namespace ReactForm.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult SaveContactData(ContactsData contact)
        {
            bool status = false;
            string message = "";
            if(ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    dc.ContactsDatas.Add(contact);
                    dc.SaveChanges();
                    status = true;
                    message = "Thank you for submitting your query";
                }
            }
            else
            {
                status = false;
                message = "Failed! Please try again";
            }

                return new JsonResult { Data = new { status = status, message = message } };
        }
    }
}

Below is the Index.cshtml:

@{
    ViewBag.Title = "Create simple form with validation in React.JS";
}

Create simple form with validation in React

@* LoaderOptimization css and js library *@

@* Bootstrap css*@
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
@* jquery library*@

@* React library *@

@* Our react component *@

Below is the Reactjs code ContactForm.js:

 //React component for input component
var MyInput = React.createClass({
    //onchange event
    handleChange: function (e) {
        this.props.onChange(e.target.value);
        var isValidField = this.isValid(e.target);
    },
    //validation function
    isValid: function (input) {
        //check required field
        if (input.getAttribute('required') != null && input.value === "") {
            input.classList.add('error'); //add class error
            input.nextSibling.textContent = this.props.messageRequired; //show error message
            return false;
        }
        else {
            input.classList.remove('error');
            input.nextSibling.textContent = "";
        }
        //check data type
        if (input.getAttribute('type') == "email" && input.value != "") {
            if (!this.validateEmail(input.value)) {
                input.classList.add('error');
                input.nextSibling.textContent = this.props.messageEmail;
            }
            else {
                input.classList.remove('error');
                input.nextSibling.textContent = "";
            }
        }
        return true;

    },
    //email validation function
    validateEmail: function (value) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(value);
    },
    componentDidMount: function () {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this); //register this input in the form
        }
    },
    //render
    render: function () {
        var inputField;
        if (this.props.type == 'textarea') {
            inputField = <textarea value={this.props.value} ref={this.props.name} name={this.props.name} className='form-control' required={this.props.isrequired} onChange={this.handleChange}/>
            }
        else{
            inputField = <input type={this.props.type} ref={this.props.name} name={this.props.name} className='form-control' required={this.props.isrequired} onChange={this.handleChange}/>
            }
        return (

                <lable htmlFor={this.props.htmlFor}>{this.props.lable}
                {inputField}

            );
    }

});

//React component for generate form

var ContactForm = React.createClass({
    //get initial statement
    getInitialState : function(){
        return{
            Fullname : '',
            Email : '',
            Message : '',
            Fields : [],
            ServerMessage : ''
        }
    },
    // submit function
    handleSubmit : function(e){
        e.preventDefault();
        //validate entire form here
        var validForm = true;
        this.state.Fields.forEach(function(field){
            if(typeof field.isValid === "function"){
                var validField = field.isValid(field.refs[field.props.name]);
                validForm = validForm && validField;
            }
        });
        //after validation complete post to server
        if(validForm){
            var d={
                Fullname: this.state.Fullname,
                Email : this.state.Email,
                Message : this.state.Message
            }
            $.ajax({
                type :"POST",
                url : this.props.urlPost,
                data: d,
                success : function(data){
                    //will clear form here
                    this.setState({
                        Fullname : '',
                        Email : '',
                        Message: '',
                        ServerMessage: data.message
                    });

                }.bind(this),
                error : function(e){
                    console.log(e);
                    alert('Error! Please try again');
                }
            });
        }
    },
    //handle change full name
    onChangeFullname : function(value){
        this.setState({
            Fullname : value
        });
    },
    //handle change email
    onChangeEmail : function(value){
        this.setState({
            Email : value
        });
    },
    //handle change message
    onChangeMessage : function(value){
        this.setState({
            Message : value
        });
    },
    //register input controls
    register : function(field){
        var s = this.state.Fields;
        s.push(field);
        this.setState({
            Fields : s
        });
    },
    //render
    render : function(){
        //Render form
        return{
            <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
            <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
            <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
            <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
            <button type="submit" className="btn btn-default">submit</button>

{this.state.ServerMessage}

                </form>
};
    }
});

//Render react component into the page
                ReactDOM.render(<ContactForm urlPost="/home/SaveContactData" />, document.getElementById('contactFormArea'));

Body:
The render() method of your ContactForm module is returning the form inside curly braces:

return {
    <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
        <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
        <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
        <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
        <button type="submit" className="btn btn-default">submit</button>
        <p className="servermessage">{this.state.ServerMessage}</p>
    </form>
};

It should be returning the form inside parentheses:

return (
    <form name="contactForm" noValidate onSubmit=[this.handleSubmit]>
        <MyInput type={'text'} value={this.state.Fullname} label={'Full Name'} name={'Fullname'} htmlFor={'Fullname'} isrequired={true} onchange={this.onChangeFullname} onComponentMounted={this.register} messageRequired={'Fullname required'} />
        <MyInput type={'email'} value={this.state.Email} label={'Email'} name={'Email'} htmlFor={'Email'} isrequired={false} onchange={this.onChangeEmail} onComponentMounted={this.register} messageRequired={'Invalid Email'} />
        <MyInput type={'textarea'} value={this.state.Message} label={'Message'} name={'Message'} htmlFor={'Message'} isrequired={true} onchange={this.onChangeMessage} onComponentMounted={this.register} messageRequired={'Message required'} />
        <button type="submit" className="btn btn-default">submit</button>
        <p className="servermessage">{this.state.ServerMessage}</p>
    </form>
);


问:
How to run my application on my jailBreaked iPhone
I have a jailbreaked iPhone....
is there any way to run my application on my device without intracting with apple website....i mean

without adhoc....

getting that certificate from any other website for free....

i am really not aware of jailbreaked iPhones......What should i do..

答:
Duplicate of Test app on iPhone without paying $99 to Apple

First, you need to install SSH to your device to be able to copy files via scp.

Build your application and grab the binary from your build directory. Copy it to the device's /Applications folder using scp. Change the permissions to 755 recursively using chmod -R 755 ApplicationName.app, reboot your iPhone.

And I strongly encourage you to enroll in the Developer Program and pay Apple for the work they have done in creating this great SDK.


问:
Polymorphism and STL containers...are pointers unnecessary?
I came across this question and answer on the software engineering stack exchange earlier. The question is, "Why are pointers not recommended when coding with c++?". The top rated answer offers two points, the second being the one of interest. It states:

Most uses of pointers in C++ are unnecessary.

His specification is somewhat lengthy, but in it the author states, "...modern C++ idioms often don’t need pointers at all.".

The first thing this brings to mind is polymorphism in STL containers. How is this, among many other things in C++ possible without the use of pointers?

After some research, this is all I was able to uncover (spoiler: it wasn't helpful).

答:
It is possible, at least in C++11, but IMO, a bad idea:

```<code>#include <vector>
#include <iostream>
#include <functional>

namespace
{
struct A
{
  virtual void operator()(void) { std::cout << "in A" << std::endl; }
};

struct B : public A
{
  virtual void operator()(void) { std::cout << "in B" << std::endl; }
};
}

int main(void)
{
  A a;
  B b;
  std::vector<std::reference_wrapper<A>> v;
  v.push_back(a);
  v.push_back(b);
  v[0]();
  v[1]();
  return 0;
}
</code>```

I agree with the comments above. Use smart pointers when you need to do dynamic polymorphism in a container. They work well. Pointers are not bad when they are wrapped in smart pointers. WARNING: in the above, you MUST ensure that a and b exist at least as long as that vector, else the references become undefined (the above code is bad).

Body:
It is possible, at least in C++11, but IMO, a bad idea:

#include <vector>
#include <iostream>
#include <functional>

namespace
{
struct A
{
  virtual void operator()(void) { std::cout << "in A" << std::endl; }
};

struct B : public A
{
  virtual void operator()(void) { std::cout << "in B" << std::endl; }
};
}

int main(void)
{
  A a;
  B b;
  std::vector<std::reference_wrapper<A>> v;
  v.push_back(a);
  v.push_back(b);
  v[0]();
  v[1]();
  return 0;
}

I agree with the comments above. Use smart pointers when you need to do dynamic polymorphism in a container. They work well. Pointers are not bad when they are wrapped in smart pointers. WARNING: in the above, you MUST ensure that a and b exist at least as long as that vector, else the references become undefined (the above code is bad).


问:
Problems running npm with node to increase memory
I have an Ubuntu docker container that has npm installed using nvm. In order to compile my code I am trying to run:

```<code>   node --max_old_space_size=4096 npm run build
</code>```

But I get:

```<code>  root@faf3418e77d0:/myproject# node --max_old_space_size=4096 npm run build
  module.js:538
  throw err;
  ^

 Error: Cannot find module '/myproject/npm'
     at Function.Module._resolveFilename (module.js:536:15)
     at Function.Module._load (module.js:466:25)
     at Function.Module.runMain (module.js:676:10)
     at startup (bootstrap_node.js:187:16)
     at bootstrap_node.js:608:3
   root@faf3418e77d0:/myproject#
</code>```

I have npm so I do not understand how this is happening. I can run npm from any folder at my docker container. Any ideas?

答:
Using the command:  which npm

I found where it is located and used that complete info in my script.
Thx

Body:
I have an Ubuntu docker container that has npm installed using nvm. In order to compile my code I am trying to run:

   node --max_old_space_size=4096 npm run build

But I get:

  root@faf3418e77d0:/myproject# node --max_old_space_size=4096 npm run build
  module.js:538
  throw err;
  ^

 Error: Cannot find module '/myproject/npm'
     at Function.Module._resolveFilename (module.js:536:15)
     at Function.Module._load (module.js:466:25)
     at Function.Module.runMain (module.js:676:10)
     at startup (bootstrap_node.js:187:16)
     at bootstrap_node.js:608:3
   root@faf3418e77d0:/myproject#

I have npm so I do not understand how this is happening. I can run npm from any folder at my docker container. Any ideas?


问:
How to write two operations at a time inside function in node.js?
I have two tables in my database, i want to get both datas with one function using nodejs

My table name is ContactGroup and Group

My code:

```<code>exports.getNewGroup = function (req, res) {
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => {
        console.log('seenData:', seenData);
    });

    Group.findAll().then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};
</code>```

Like above code, i am writing ContactGroup.findandcount and Group.findall, i checked this api via postman, but only one working here,
I want both of them working? help me!

答:
Change your code to this and try : </p>

```<code>exports.getNewGroup = function (req, res) {
ContactGroup.findAndCountAll({
    attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
        'contactCount'
    ]],
    include: [{
        model: Group,
    }],
}).then(seenData => {
    console.log('seenData:', seenData);
    Group.findAll().then(function (data) {
       return res.status(200).send(data);
    }).catch(function (err) {
       return res.status(400).send(err.message);
    });
 });
};
</code>```

Body:
I have two tables in my database, i want to get both datas with one function using nodejs

My table name is ContactGroup and Group

My code:

exports.getNewGroup = function (req, res) {
    ContactGroup.findAndCountAll({
        attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
            'contactCount'
        ]],
        include: [{
            model: Group,
        }],
    }).then(seenData => {
        console.log('seenData:', seenData);
    });

    Group.findAll().then(function (data) {
        return res.status(200).send(data);
    }).catch(function (err) {
        return res.status(400).send(err.message);
    });
};

Like above code, i am writing ContactGroup.findandcount and Group.findall, i checked this api via postman, but only one working here,
I want both of them working? help me!

Body:
Change your code to this and try :

exports.getNewGroup = function (req, res) {
ContactGroup.findAndCountAll({
    attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
        'contactCount'
    ]],
    include: [{
        model: Group,
    }],
}).then(seenData => {
    console.log('seenData:', seenData);
    Group.findAll().then(function (data) {
       return res.status(200).send(data);
    }).catch(function (err) {
       return res.status(400).send(err.message);
    });
 });
};


问:
Dynamic link or App Indexing or App Invite?
If a user clicks a hyperlink it should take the user to the app if installed or corresponding app in the Google play. After installation the auto fill in the login page with credentials in the hyperlink.

To do this which feature should I enable - Dynamic link or App Indexing or App Invite ?

答:
Firebase Dynamic Links will work for your purpose.

App Invite generally serves similar purpose, but a bit less configurable. App Invite has built-in people picker.

App Indexing is different kind of library.

As a bonus the Firebase Dynamic Links will work with iOS App, if you have one.


问:
Does the Photos App register a URL Handler on the iPhone?
I have read the Apple documentation.  They list the apps registered, yet in their example they use a handler not mentioned.
https://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/chapter_3_section_6.html

This post attempts to list the handlers.  But it too appears incomplete since the iPod handler is not listed.
http://quinagh.com/applookup/index.php/2009/01/07/iphone-apps-with-special-url-shortcuts/

Is there a complete list available?  Does anyone know if the Photos app has a registered handler or not for certain?

答: There is, afaik, no way to tell beyond those that are documented.</p>

OwnerDisplayName: Jared Brown

OwnerDisplayName: Genericrich


问:
GenericFactory as Singleton
I read the article Abstract Factory, Template Style by Jim Hyslop and Herb Sutter. This factory is implemented as a Singleton. They provided an easy way to register classes automatically with the RegisterInFactory helper class.

Now i've read several times that Singletons should be avoided, some even consider them as Anti-Patterns and that there are just a few cases where they are usefull.
Is this one of them? Or is there an alternative approach which provides such an easy way to autoregister classes?

答:
As ever for this sort of subject, there is no answer that applies to every problems. Some said that singleton should be avoided when they are used as an access to a service. It is a use that is akin to the use of global variables. This way you mask the fact that you use service X in your implementation :

```<code>// in header
class MyUsefulClass
{
    public:
    void doSomethingUseful();
};

// in .cpp
MyUsefulClass::doSomethingUseful()
{
    // ...
    MyWonderfulService::instance().doService1();
    // ...
    MyWonderfulService::instance().doService2();
}
</code>```

You create a coupling with MyWonderfulService that the users of your class can not guess.
Moreover, You can not easily test your useful class with a mock service ...

That's why I usually prefer dependancy inversion :

```<code>// in header
class MyUsefulClass
{
    public:
    void setServiceToUse(MyService&);
    void doSomethingUseful();

    // [...]
};

// in .cpp
MyUsefulClass::doSomethingUseful()
{
    // ...
    _myService->doService1();
    // ...
    _myService->doService2();
}
</code>```

This way is usually considered better as the coupling between class is lighter. Nevertheless, for some services, which are well known to be of widespread use in a framework, it is simplier to use a singleton. It makes sense for a single service that is the service which give you access to all other services in a framework for example ^^ It is often use for technical services like logging for instance.

my2c

Edit: I read the article, as the focus is on AbstractFactories, the use of a singleton is a casual one, not a design decision. It is understandable in an article in which you do not want to write things that will not get you to your point.

Title: GenericFactory as Singleton

Body:
As ever for this sort of subject, there is no answer that applies to every problems. Some said that singleton should be avoided when they are used as an access to a service. It is a use that is akin to the use of global variables. This way you mask the fact that you use service X in your implementation :

// in header
class MyUsefulClass
{
    public:
    void doSomethingUseful();
};

// in .cpp
MyUsefulClass::doSomethingUseful()
{
    // ...
    MyWonderfulService::instance().doService1();
    // ...
    MyWonderfulService::instance().doService2();
}

You create a coupling with MyWonderfulService that the users of your class can not guess.
Moreover, You can not easily test your useful class with a mock service ...

That's why I usually prefer dependancy inversion :

// in header
class MyUsefulClass
{
    public:
    void setServiceToUse(MyService&);
    void doSomethingUseful();

    // [...]
};

// in .cpp
MyUsefulClass::doSomethingUseful()
{
    // ...
    _myService->doService1();
    // ...
    _myService->doService2();
}

This way is usually considered better as the coupling between class is lighter. Nevertheless, for some services, which are well known to be of widespread use in a framework, it is simplier to use a singleton. It makes sense for a single service that is the service which give you access to all other services in a framework for example ^^ It is often use for technical services like logging for instance.

my2c

Edit: I read the article, as the focus is on AbstractFactories, the use of a singleton is a casual one, not a design decision. It is understandable in an article in which you do not want to write things that will not get you to your point.