问:
uploading file from android app into desired folder
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever</p>

```<code> $response = array();

    if($_SERVER['REQUEST_METHOD']=='POST'){

        //checking the required parameters from the request
        if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name'])  ){

                //connecting to the database
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');

            $resume_name = $_POST['exp'];
            $employee_id = $_POST['employee_id'];
            $file_data = $_FILES['pdf']['name'];

            $upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';

              //getting file info from the request
            $fileinfo = pathinfo($_FILES['pdf']['name']);

             //getting the file extension
            $extension = $fileinfo['extension'];

            //file url to store in the database
            $file_url = $upload_path . getFileName($employee_id). '.'. $extension;

            //file path to upload in the server
            $file_path = $upload_path . getFileName($employee_id);

         try{

            if(file_exists($upload_path))
            {
               $existing_file = glob($upload_path."/*.*");
               $empty_file = implode(" ",$existing_file);

              move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

    $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

               //adding the path and name to database
               if(mysqli_query($con,$sql)){

                    //filling response array with values

                    $response['Success'] = "File Uploaded Successfully...!";
                    echo json_encode($response);

                }
                else
                {
                  $response['Error'] = "File Uploading Error...!";
                  echo json_encode($response);
                }

            }
                else
                {
                      mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
                      move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

        $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

                            //adding the path and name to database
                            if(mysqli_query($con,$sql))
                            {

                             //filling response array with values

                                 $response['Success'] = "File Uploaded Successfully...!";
                                 echo json_encode($response);

                            }
                        else
                            {
                                $response['Error'] = "File Uploading Error...!";
                                echo json_encode($response);
                            }

                }
            }catch(Exception $e){
                $response['error']=true;
                $response['message']=$e->getMessage();
            }
    }

    }

      //here is my method getFileName

function getFileName($employee_id)
 {

   //mysql query to fetch data
   $sql = mysql_query("SELECT resume_path from employee_registration where
     employee_id = '$employee_id'") or die(mysql_error());
   while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
   {
     $response=$row['resume_path'];
   }
    $resume_name = explode("/", $response);
   echo $resume_name[4];
   return $resume_name;
  }
</code>```

答:
Change below line:

```<code>move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;
</code>```

To

```<code>move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;
</code>```

tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.

Body:
I wan to upload file from android app using PHP in specific folder below is the code which I have tried.
pleas help me what is wrong in this code and please suggest me some easy solution for this or is this method right to upload files from android app on serever

 $response = array();

    if($_SERVER['REQUEST_METHOD']=='POST'){

        //checking the required parameters from the request
        if(isset($_POST['exp']) && isset($_POST['employee_id']) && isset($_FILES['pdf']['name'])  ){

                //connecting to the database
            $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect...');

            $resume_name = $_POST['exp'];
            $employee_id = $_POST['employee_id'];
            $file_data = $_FILES['pdf']['name'];

            $upload_path = 'Images/Employee_Profile_Picture/'.$employee_id.'/Resume/';

              //getting file info from the request
            $fileinfo = pathinfo($_FILES['pdf']['name']);

             //getting the file extension
            $extension = $fileinfo['extension'];

            //file url to store in the database
            $file_url = $upload_path . getFileName($employee_id). '.'. $extension;

            //file path to upload in the server
            $file_path = $upload_path . getFileName($employee_id);

         try{

            if(file_exists($upload_path))
            {
               $existing_file = glob($upload_path."/*.*");
               $empty_file = implode(" ",$existing_file);

              move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

    $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

               //adding the path and name to database
               if(mysqli_query($con,$sql)){

                    //filling response array with values

                    $response['Success'] = "File Uploaded Successfully...!";
                    echo json_encode($response);

                }
                else
                {
                  $response['Error'] = "File Uploading Error...!";
                  echo json_encode($response);
                }

            }
                else
                {
                      mkdir('Images/Employee_Profile_Picture/'.$employee_id.'/Resume');
                      move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

        $sql = "UPDATE employee_registration SET resume_name ='$resume_name', resume_path='$file_url' where employee_id ='$employee_id'";

                            //adding the path and name to database
                            if(mysqli_query($con,$sql))
                            {

                             //filling response array with values

                                 $response['Success'] = "File Uploaded Successfully...!";
                                 echo json_encode($response);

                            }
                        else
                            {
                                $response['Error'] = "File Uploading Error...!";
                                echo json_encode($response);
                            }

                }
            }catch(Exception $e){
                $response['error']=true;
                $response['message']=$e->getMessage();
            }
    }

    }

      //here is my method getFileName

function getFileName($employee_id)
 {

   //mysql query to fetch data
   $sql = mysql_query("SELECT resume_path from employee_registration where
     employee_id = '$employee_id'") or die(mysql_error());
   while ($row = mysql_fetch_array($sql, MYSQL_ASSOC))
   {
     $response=$row['resume_path'];
   }
    $resume_name = explode("/", $response);
   echo $resume_name[4];
   return $resume_name;
  }

Body:
Change below line:

move_uploaded_file($_FILES['pdf']['name'],$upload_path) ;

To

move_uploaded_file($_FILES['pdf']['tmp_name'],$upload_path) ;

tmp_name should be used to upload the file, as it has the full path of the file where it is temporarily stored. Where as the name contain only the name of file without any path information.


来源: stackexchange

问:
When to use Gateway design pattern
while trying to get my head into some design patterns I've run across a sample that confuses me - hopefully it something easy to explain, and I'm just missing it.

my question is "where" does gateway fit into this? it seems redundant, as an added data access point.

the sample code has three classes -

person - which has getter and setter methods for each of the objects attributes

personDAO - which has data calls to do the CRUD.

personGateway - which has getAll and getCount - which are data calls too...???

I totally get making a DAO call for data, and the DAO uses the "person" class to create an object to pass back - but WHY NOT put the getAll and getCount in the DAO???

What LOGICAL position does the "gateway" play in this game?

--- added after reading responses ---

Ok - I apparently missed this while searching - and it does "help" clarify -
Need some clarification with Patterns (DAO x Gateway) - HOWEVER, it seem very java centric and it actually skips the distinction I was hoping for -

I guess the answer is that DAO returns an "object" and an "object" is a single entity...not a collection. If you're retuning a collection (and it's debatable if you "should") then you'd use the gateway... but under no circumstance should you muddy the DAO with collections...

答: The Gateway design pattern is useful when you want to work with a complex SDK, Library or API. To work with them you may need some implementation that lower layers don't have to know about them and of course, that is not important for other layers. In this case, the Gateway design pattern is the best solution. Yo implement what you want with any SDK or library and after that with a contract, other project layers can work easily with the gateway. And if someday you decide to change the mentioned SDK or API, it doesn't affect to the whole of the project. You simply can change the gateway implementation and the contract will be unchanged for the other layers.

ContentLicense: CC BY-SA 3.0

Title: When to use Gateway design pattern


问:
I want use wechat js-sdk chooseVideo, uploadVideo api.the result is "chooseVideo:fail_nopermission to execute"
When i use wechat js-sdk, i want use chooseVideo, uploadVideo  api. the result is "chooseVideo:fail_nopermission to execute".
I am sure, wx.config(wxConfigData) is right.

enter image description here

答: wx.chooseVideo is an API of WeChat "mini program" (doc). It's NOT an API of WeChat JS-SDK: in JS-SDK's document, no chooseVideo would be found.


问:
"You have already authorized yourApp" when logging in using FBSDK 4.7.1
I was following Facebook's own tutorial for FB login in iOS (Objective-C) but every time I log in - after the initial permission authorization screen - I'm getting the infamous "You have already authorized this app" webview.

I've read a ton of posts but I haven't been able to sort it out, hence the (re)post. I find this rather odd because the app has absolutely nothing except the boilerplate login code. This behaviour happens in both Simulator and real devices.

This app is for iOS 9.0 and I am using FBSDK 4.7.1 (installed via CocoaPods):

```<code>pod 'FBSDKLoginKit', '~> 4.6'
</code>```

The code itself is pretty boilerplate stuff, here's my AppDelegate.m:

```<code>#import "AppDelegate.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBSDKAppEvents activateApp];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];
    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
}
@end
</code>```

and my ViewController.m:

```<code>#import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.readPermissions = @[@"public_profile", @"email", @"user_friends"];
    [loginButton setLoginBehavior:FBSDKLoginBehaviorSystemAccount]; // No difference

    loginButton.center = self.view.center;
    [self.view addSubview:loginButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

And a screenshot of the Info.plist:

Finally, I'm also getting these two errors in the console:

```<code>2015-11-24 11:50:42.855 lixo[26941:389756] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
2015-11-24 11:50:42.860 lixo[26941:389756] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
</code>```

Although from what I've read this can be safely ignored if LSApplicationQueriesSchemes is set in the Info.plist.

Any ideas how to avoid this?

答:
Check if there is a current session before logging in with FBSDKLoginManager.

```<code>if ([FBSDKAccessToken currentAccessToken])
 {
      NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
      // Now get details using graphpath.
 } else {
     // login with permissions using FBSDKLoginManager and get details using graphpath in completion

 }
</code>```

Body:
I was following Facebook's own tutorial for FB login in iOS (Objective-C) but every time I log in - after the initial permission authorization screen - I'm getting the infamous "You have already authorized this app" webview.

I've read a ton of posts but I haven't been able to sort it out, hence the (re)post. I find this rather odd because the app has absolutely nothing except the boilerplate login code. This behaviour happens in both Simulator and real devices.

This app is for iOS 9.0 and I am using FBSDK 4.7.1 (installed via CocoaPods):

pod 'FBSDKLoginKit', '~> 4.6'

The code itself is pretty boilerplate stuff, here's my AppDelegate.m:

#import "AppDelegate.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBSDKAppEvents activateApp];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];
    return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
}
@end

and my ViewController.m:

#import "ViewController.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
    loginButton.readPermissions = @[@"public_profile", @"email", @"user_friends"];
    [loginButton setLoginBehavior:FBSDKLoginBehaviorSystemAccount]; // No difference

    loginButton.center = self.view.center;
    [self.view addSubview:loginButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

And a screenshot of the Info.plist:

Finally, I'm also getting these two errors in the console:

2015-11-24 11:50:42.855 lixo[26941:389756] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
2015-11-24 11:50:42.860 lixo[26941:389756] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"

Although from what I've read this can be safely ignored if LSApplicationQueriesSchemes is set in the Info.plist.

Any ideas how to avoid this?

Body:
Check if there is a current session before logging in with FBSDKLoginManager.

if ([FBSDKAccessToken currentAccessToken])
 {
      NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
      // Now get details using graphpath.
 } else {
     // login with permissions using FBSDKLoginManager and get details using graphpath in completion

 }


问:
Putting labels on a bar chart in R with ggplot2
I am having a little bit of trouble inserting labels on a bar chart in ggplot2.

So far, I have been able to create the bar chart.

```<code>Pizza_bar <- ggplot(Pizza_Data_Research_Rockstar, aes(Number_of_times_eaten_pizza))
Times_eaten_pizza_7_days_bar <- Pizza_bar + geom_bar()
Times_eaten_pizza_7_days_bar
</code>```

Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous.

The challenge becomes labeling the count of the different categories. Since I am newbie at R, I went searching for code examples but keep getting error messages.

```<code>ggplot(Pizza_Data_Research_Rockstar, aes(x= Number_of_times_eaten_pizza, y = count))+
geom_bar(stat = "identity", fill = "steelblue") +
geom_text(aes(label=count), vjust=-0.3, size=3.5) +
theme_minimal()
</code>```

Don't know how to automatically pick scale for object of type
  tbl_df/tbl/data.frame. Defaulting to continuous. Don't know how to
  automatically pick scale for object of type function. Defaulting to
  continuous. Error in (function (..., row.names = NULL, check.rows =
  FALSE, check.names = TRUE,  :    arguments imply differing number of
  rows: 46, 0

That is the closest that I have gotten to adding labels.

Could someone please help? Thank you.

Luis

答:
I really could't understand your data, so I made up my own:

library(ggplot2)

Days = c("Monday", "Tuesday", "Thursday", "Friday")
Pizzas = c(40, 50, 10, 25)
Pizzadf = as.data.frame(cbind(Days, Pizzas))
Pizzadf$Pizzas = as.numeric(as.character(Pizzadf$Pizzas))

Pizzadf
#>       Days Pizzas
#> 1   Monday     40
#> 2  Tuesday     50
#> 3 Thursday     10
#> 4   Friday     25

ggplot(data = Pizzadf, aes(x = Days, y = Pizzas))+
  geom_bar(stat = "identity", fill = "steelblue") +
  geom_text(aes(label=Pizzas), vjust=-0.3, size=3.5) +
  theme_minimal()
```

Try to modify and adjust.

Body:
I am having a little bit of trouble inserting labels on a bar chart in ggplot2.

So far, I have been able to create the bar chart.

Pizza_bar <- ggplot(Pizza_Data_Research_Rockstar, aes(Number_of_times_eaten_pizza))
Times_eaten_pizza_7_days_bar <- Pizza_bar + geom_bar()
Times_eaten_pizza_7_days_bar

Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous.

The challenge becomes labeling the count of the different categories. Since I am newbie at R, I went searching for code examples but keep getting error messages.

ggplot(Pizza_Data_Research_Rockstar, aes(x= Number_of_times_eaten_pizza, y = count))+
geom_bar(stat = "identity", fill = "steelblue") +
geom_text(aes(label=count), vjust=-0.3, size=3.5) +
theme_minimal()

Don't know how to automatically pick scale for object of type
  tbl_df/tbl/data.frame. Defaulting to continuous. Don't know how to
  automatically pick scale for object of type function. Defaulting to
  continuous. Error in (function (..., row.names = NULL, check.rows =
  FALSE, check.names = TRUE,  :    arguments imply differing number of
  rows: 46, 0

That is the closest that I have gotten to adding labels.

Could someone please help? Thank you.

Luis

Body:
I really could't understand your data, so I made up my own:

library(ggplot2)

Days = c("Monday", "Tuesday", "Thursday", "Friday")
Pizzas = c(40, 50, 10, 25)
Pizzadf = as.data.frame(cbind(Days, Pizzas))
Pizzadf$Pizzas = as.numeric(as.character(Pizzadf$Pizzas))

Pizzadf
#>       Days Pizzas
#> 1   Monday     40
#> 2  Tuesday     50
#> 3 Thursday     10
#> 4   Friday     25

ggplot(data = Pizzadf, aes(x = Days, y = Pizzas))+
  geom_bar(stat = "identity", fill = "steelblue") +
  geom_text(aes(label=Pizzas), vjust=-0.3, size=3.5) +
  theme_minimal()

Try to modify and adjust.

ContentLicense: CC BY-SA 4.0


问:
Number of pixels moved when I move a scrollview
I have tried this several times but I can´t solve it.
I have a ScrollView with several views, which are moved by an ObjectAnimator. When you pulse a button, the views are moved vertically during a given time.
I do PLAY and PAUSE, but when I move the scroll using my finger, I am not able to know the number of pixels that the scroll has been moved.

I want to move the scroll with my finger, pulse Play, and I would like the scroll to start scrolling where I have put it, not from the beginning.
I´ve tried this:

```<code>view.setOnTouchListener(new OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
               //Choose which motion action has been performed
               switch(event.getAction())
               {
               case MotionEvent.ACTION_DOWN:
                   //Get X, Y coordinates from the ImageView
                   X = (int) event.getX();
                   Y = (int) event.getY();
                   startX = event.getRawX();
                   startY = event.getRawY();
                   break;
               case MotionEvent.ACTION_MOVE:
                  Z = (int) event.getX();
                   S = (int) event.getY();
                   K = (int) event.getRawX();
                   P = (int) event.getRawY();
                   V = (int) (event.getRawY() - startY);
                   break;
               case MotionEvent.ACTION_UP:
                   A = (int) event.getX();
                   E = (int) event.getY();
                   break;
               }
               return true;
           }
</code>```

});

It does not give the coordinates when I raise my finger. How could I know the number of pixels moved when I move the scroll? It´s an Android aplication.
Thanks in advance!

答:
There is my solution, works perfectly, try to read the code

```<code>public class CustomScrollView extends NestedScrollView
{

private boolean mIsScrolling;
private boolean mIsTouching;
private OnScrollListener mOnScrollListener;
private Runnable mScrollingRunnable;

public interface OnScrollListener
{
    void onScrollChanged(CustomScrollView scrollView, int x, int y, int oldX, int oldY);

    void onEndScroll(CustomScrollView scrollView);

    void onGoUp();

    void onGoDown();
}

public CustomScrollView(final Context context)
{
    super(context);
}

public CustomScrollView(final Context context, final AttributeSet attrs)
{
    super(context, attrs);
}

public CustomScrollView(final Context context, final AttributeSet attrs, final int defStyleAttr)
{
    super(context, attrs, defStyleAttr);
}

private int y = 0;

@Override
public boolean dispatchTouchEvent(MotionEvent iEv)
{
    if (isEnabled())
    {

        processEvent(iEv);

        super.dispatchTouchEvent(iEv);

        return true; //to keep receive event that follow down event
    }
    return super.dispatchTouchEvent(iEv);
}

private void processEvent(final MotionEvent iEv)
{
    switch (iEv.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            y = (int) iEv.getY();
            break;

        case MotionEvent.ACTION_UP:
            y = (int) iEv.getY();

            if (mIsTouching && !mIsScrolling)
            {
                if (mOnScrollListener != null)
                {
                    //If you need to know when end of scrolling just uncomment
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
            break;
        case MotionEvent.ACTION_MOVE:
            mIsTouching = true;
            mIsScrolling = true;

            int newY = (int) iEv.getY();
            int difY = y - newY;

            int MAX_VALUE = 200;
            int MIN_VALUE = -200;
            if (difY > MAX_VALUE)
            {
                AppUtils.printLog(Log.ERROR, "TAG", "difY down : " + difY + " , y : " + y + ", newY : " + newY);
                if (mOnScrollListener != null)
                {
                    mOnScrollListener.onGoDown();
                }
                y = newY;
            }
            else if (difY < MIN_VALUE)
            {
                AppUtils.printLog(Log.ERROR, "TAG", "difY  up : " + difY + " , y : " + y + ", newY : " + newY);
                if (mOnScrollListener != null)
                {
                    mOnScrollListener.onGoUp();
                }
                y = newY;
            }

            break;
    }
}

@Override
protected void onScrollChanged(int iX, int iY, int iOldX, int iOldY)
{
    super.onScrollChanged(iX, iY, iOldX, iOldY);

    if (Math.abs(iOldX - iX) > 0)
    {
        if (mScrollingRunnable != null)
        {
            removeCallbacks(mScrollingRunnable);
        }

        mScrollingRunnable = new Runnable()
        {
            public void run()
            {
                if (mIsScrolling && !mIsTouching)
                {
                    if (mOnScrollListener != null)
                    {
                        mOnScrollListener.onEndScroll(CustomScrollView.this);
                    }
                }

                mIsScrolling = false;
                mScrollingRunnable = null;
            }
        };

        postDelayed(mScrollingRunnable, 200);
    }

    if (mOnScrollListener != null)
    {
        mOnScrollListener.onScrollChanged(this, iX, iY, iOldX, iOldY);
    }
}

public OnScrollListener getOnScrollListener()
{
    return mOnScrollListener;
}

public void setOnScrollListener(OnScrollListener mOnEndScrollListener)
{
    this.mOnScrollListener = mOnEndScrollListener;
}
}
</code>```

Usage : Just add this custom view in XML

```<code><ui.customWidgets.CustomScrollView
        android:id="@+id/scroll_frag_detail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:scrollbars="none"
        app:behavior_overlapTop="192dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

           <!--Your code here-->

        </LinearLayout>

    </ui.customWidgets.CustomScrollView>
</code>```

in code

```<code>mScrollView.setOnScrollListener(new CustomScrollView.OnScrollListener()
    {
        @Override
        public void onScrollChanged(final CustomScrollView scrollView, final int x, final int y, final int oldX, final int oldY)
        {

        }

        @Override
        public void onEndScroll(final CustomScrollView scrollView)
        {

        }

        @Override
        public void onGoUp()
        {

        }

        @Override
        public void onGoDown()
        {

        }
    });
</code>```

Body:
I have tried this several times but I can´t solve it.
I have a ScrollView with several views, which are moved by an ObjectAnimator. When you pulse a button, the views are moved vertically during a given time.
I do PLAY and PAUSE, but when I move the scroll using my finger, I am not able to know the number of pixels that the scroll has been moved.

I want to move the scroll with my finger, pulse Play, and I would like the scroll to start scrolling where I have put it, not from the beginning.
I´ve tried this:

view.setOnTouchListener(new OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
               //Choose which motion action has been performed
               switch(event.getAction())
               {
               case MotionEvent.ACTION_DOWN:
                   //Get X, Y coordinates from the ImageView
                   X = (int) event.getX();
                   Y = (int) event.getY();
                   startX = event.getRawX();
                   startY = event.getRawY();
                   break;
               case MotionEvent.ACTION_MOVE:
                  Z = (int) event.getX();
                   S = (int) event.getY();
                   K = (int) event.getRawX();
                   P = (int) event.getRawY();
                   V = (int) (event.getRawY() - startY);
                   break;
               case MotionEvent.ACTION_UP:
                   A = (int) event.getX();
                   E = (int) event.getY();
                   break;
               }
               return true;
           }

});

It does not give the coordinates when I raise my finger. How could I know the number of pixels moved when I move the scroll? It´s an Android aplication.
Thanks in advance!

Body:
There is my solution, works perfectly, try to read the code

public class CustomScrollView extends NestedScrollView
{

private boolean mIsScrolling;
private boolean mIsTouching;
private OnScrollListener mOnScrollListener;
private Runnable mScrollingRunnable;

public interface OnScrollListener
{
    void onScrollChanged(CustomScrollView scrollView, int x, int y, int oldX, int oldY);

    void onEndScroll(CustomScrollView scrollView);

    void onGoUp();

    void onGoDown();
}

public CustomScrollView(final Context context)
{
    super(context);
}

public CustomScrollView(final Context context, final AttributeSet attrs)
{
    super(context, attrs);
}

public CustomScrollView(final Context context, final AttributeSet attrs, final int defStyleAttr)
{
    super(context, attrs, defStyleAttr);
}

private int y = 0;

@Override
public boolean dispatchTouchEvent(MotionEvent iEv)
{
    if (isEnabled())
    {

        processEvent(iEv);

        super.dispatchTouchEvent(iEv);

        return true; //to keep receive event that follow down event
    }
    return super.dispatchTouchEvent(iEv);
}

private void processEvent(final MotionEvent iEv)
{
    switch (iEv.getAction())
    {
        case MotionEvent.ACTION_DOWN:
            y = (int) iEv.getY();
            break;

        case MotionEvent.ACTION_UP:
            y = (int) iEv.getY();

            if (mIsTouching && !mIsScrolling)
            {
                if (mOnScrollListener != null)
                {
                    //If you need to know when end of scrolling just uncomment
                    mOnScrollListener.onEndScroll(this);
                }
            }

            mIsTouching = false;
            break;
        case MotionEvent.ACTION_MOVE:
            mIsTouching = true;
            mIsScrolling = true;

            int newY = (int) iEv.getY();
            int difY = y - newY;

            int MAX_VALUE = 200;
            int MIN_VALUE = -200;
            if (difY > MAX_VALUE)
            {
                AppUtils.printLog(Log.ERROR, "TAG", "difY down : " + difY + " , y : " + y + ", newY : " + newY);
                if (mOnScrollListener != null)
                {
                    mOnScrollListener.onGoDown();
                }
                y = newY;
            }
            else if (difY < MIN_VALUE)
            {
                AppUtils.printLog(Log.ERROR, "TAG", "difY  up : " + difY + " , y : " + y + ", newY : " + newY);
                if (mOnScrollListener != null)
                {
                    mOnScrollListener.onGoUp();
                }
                y = newY;
            }

            break;
    }
}

@Override
protected void onScrollChanged(int iX, int iY, int iOldX, int iOldY)
{
    super.onScrollChanged(iX, iY, iOldX, iOldY);

    if (Math.abs(iOldX - iX) > 0)
    {
        if (mScrollingRunnable != null)
        {
            removeCallbacks(mScrollingRunnable);
        }

        mScrollingRunnable = new Runnable()
        {
            public void run()
            {
                if (mIsScrolling && !mIsTouching)
                {
                    if (mOnScrollListener != null)
                    {
                        mOnScrollListener.onEndScroll(CustomScrollView.this);
                    }
                }

                mIsScrolling = false;
                mScrollingRunnable = null;
            }
        };

        postDelayed(mScrollingRunnable, 200);
    }

    if (mOnScrollListener != null)
    {
        mOnScrollListener.onScrollChanged(this, iX, iY, iOldX, iOldY);
    }
}

public OnScrollListener getOnScrollListener()
{
    return mOnScrollListener;
}

public void setOnScrollListener(OnScrollListener mOnEndScrollListener)
{
    this.mOnScrollListener = mOnEndScrollListener;
}
}

Usage : Just add this custom view in XML

<ui.customWidgets.CustomScrollView
        android:id="@+id/scroll_frag_detail"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:scrollbars="none"
        app:behavior_overlapTop="192dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

           <!--Your code here-->

        </LinearLayout>

    </ui.customWidgets.CustomScrollView>

in code

mScrollView.setOnScrollListener(new CustomScrollView.OnScrollListener()
    {
        @Override
        public void onScrollChanged(final CustomScrollView scrollView, final int x, final int y, final int oldX, final int oldY)
        {

        }

        @Override
        public void onEndScroll(final CustomScrollView scrollView)
        {

        }

        @Override
        public void onGoUp()
        {

        }

        @Override
        public void onGoDown()
        {

        }
    });


问:
Calculate 4point the closest from the User'position ? (Android)
I'm working on a geolocalisation project. And I want to determine which are the 4points the closest from my position. As you can see on the picture below :

Arrow red : Position of the USER (I can get easily his position on the screen)

Blue Point : All the point where I need to determine which are the 4 the more closer from the User.

Here, it would be the ones surounded in red. I also can get their position easily on the screen. I just need the math's equation to know the 4 points concerned.

Thank's for ur precious help !

答:
Problem solved :

I first of all calculate the distance using the basic equation for each points :

sqrt((Xb-Xa)² + (Yb-Ya)²)

then I sort the result of each points (ascending) :

```<code>Object[] a = distance.entrySet().toArray();
        Arrays.sort(a, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Map.Entry<Integer, Double>) o1).getValue()
                        .compareTo(((Map.Entry<Integer, Double>) o2).getValue());
            }
        });
</code>```

And just did a for with the first 4 to got my 4 closest point. ez pz :) !

Body:
Problem solved :

I first of all calculate the distance using the basic equation for each points :

sqrt((Xb-Xa)² + (Yb-Ya)²)

then I sort the result of each points (ascending) :

Object[] a = distance.entrySet().toArray();
        Arrays.sort(a, new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Map.Entry<Integer, Double>) o1).getValue()
                        .compareTo(((Map.Entry<Integer, Double>) o2).getValue());
            }
        });

And just did a for with the first 4 to got my 4 closest point. ez pz :) !


问:
Functional dependency and many-to-many relationships
I have these fields:

```<code>A   book_id
B   book_title
C   book_isbn
D   book_year
G   reader_id
H   reader_name
I   reader_birthday
L   reader_phone
M   reader_email
N   reader_registration_date
O   loan_id
P   loan_date_issued
S   loan_date_for_return
T   loan_date_returned
U   author_id
V   author_name
W   category_id
X   category_name
</code>```

and these dependencies:

```<code>A->BCD
G->HILMN
O->AGPST
U->AV
W->AX
</code>```

After all calculations I get this:

```<code>R1 = ABCD       k1 = {A}    Books
R2 = GHILMN     k2 = {G}    Readers
R3 = AGOPST     k3 = {O}    Loans
R4 = AUV        k4 = {U}    Authors
R5 = AWX        k5 = {W}    Category
R6 = OUW        k6 = {OUW}  {Don’t know}
</code>```

But this is not good because table Book has a many to many relationship with table Category, and so do the Book and Author tables.
I'm stuck. I think I'm doing something wrong from the start and after that all goes wrong. Maybe you have some example for this.

答:
Let's treat "category" as "cover" of a "book"-as-object or "copy" of a "book"-as-text, where a "book" is associated with some O values unique to it. Then W -> A makes more intuitive sense. (Other FDs seem unintuitive too.)

Universal relations

Every table (base or query result) has a predicate (statement template) that a row makes either into a true statement (and goes in the table) or a false statement (and stays out). We say the table represents the business relationship/association characterized by the predicate. A guess at a predicate here is:

```<code>book A titled B with isbn C published in year D
    was borrowed by a reader G named H born on date I
        with phone# L and email address M registered on date N
    in loan O issued on date P due on date S
    and either it was returned on date T or it is not yet returned and T=NULL
    and it was written by author U named V
    and the library has A in cover/copy W named X
</code>```

You seem to be using the "universal relation" decomposition design/normalization technique. But this is only applicable if your one table satisfies the "universal relation assumption". Which is that all your situations can be described via the one predicate and its one table.

Eg: Suppose you can have books that have not been loaned or users that haven't borrowed. Then the example predicate/table above could not record them. So a decomposition wouldn't be able to record them. So you would instead start with a different predicate/table. (Typically multiple ones.)

Eg: If the last line was and A was borrowed in cover/copy W named X then the table could hold a different value in a given situation than before. But depending on the borrowing policy the table could satisfy the same set of FDs.

What is the predicate for this table? If it's not what you guessed, your expectations might not be met.

Your decomposition

Let's ignore the properties of entities.

```<code>-- O is G borrowing A by U with W

A   book_id
G   reader_id
O   loan_id
U   author_id
W   cover/copy_id

O->AG
U->A
W->A
</code>```

The only CK is OUW. Here is an obvious decomposition to BCNF. It agrees with your version.

```<code>-- O is G borrowing A by someone with some cover/copy
-- O is G borrowing A
Loan(O,G,A)

-- some loan is somebody borrowing A by U with some cover/copy
-- the book of U is A
The_book_of_author(U,A)

-- some loan is somebody borrowing A by someone with W
-- the book of W is A
The_book_of_cover/copy(W,A)

-- O is somebody borrowing some book by U with W
-- O is the borrowing of the book of U and W
Author_and_cover/copy(O,U,W)
</code>```

The original relation is the join of the components:

```<code>--     O is G borrowing A
    and the book of U is A
    and the book of W is A
    and O is the borrowing of the book of U and W
-- O is G borrowing A by U with W
Loan JOIN The_book_of_author JOIN The_book_of_cover/copy JOIN Author_and_cover/copy
</code>```

this is not good because table Book has a many to many relationship with table Category, and so do the Book and Author tables

Unfortunately this is unintelligible. So I can't address what you mean to say is wrong.

Database design

If you generated this design yourself, you should be using some reference information modeling method. This will guide you to determine reasonable predicates/tables to record all the situations that can arise according to your business rules.

Predicates applied to what situations can arise determine what states can arise. Those valid states are described by constraints--FDs (functional dependencies), JDs (join dependencies), CKs (candidate keys), FKs (foreign keys) (aka "relationships" in a different sense than above), etc.

Part of a method is normalizing provisional tables to others. This uses FDs & JDs to decompose to an appropriate NF (normal form) via an appropriate algorithm. A good method always normalizes to 5NF. (Even if you denormalize it later for implementation reasons.)

Body:
I have these fields:

A   book_id
B   book_title
C   book_isbn
D   book_year
G   reader_id
H   reader_name
I   reader_birthday
L   reader_phone
M   reader_email
N   reader_registration_date
O   loan_id
P   loan_date_issued
S   loan_date_for_return
T   loan_date_returned
U   author_id
V   author_name
W   category_id
X   category_name

and these dependencies:

A->BCD
G->HILMN
O->AGPST
U->AV
W->AX

After all calculations I get this:

R1 = ABCD       k1 = {A}    Books
R2 = GHILMN     k2 = {G}    Readers
R3 = AGOPST     k3 = {O}    Loans
R4 = AUV        k4 = {U}    Authors
R5 = AWX        k5 = {W}    Category
R6 = OUW        k6 = {OUW}  {Don’t know}

But this is not good because table Book has a many to many relationship with table Category, and so do the Book and Author tables.
I'm stuck. I think I'm doing something wrong from the start and after that all goes wrong. Maybe you have some example for this.

Body:
Let's treat "category" as "cover" of a "book"-as-object or "copy" of a "book"-as-text, where a "book" is associated with some O values unique to it. Then W -> A makes more intuitive sense. (Other FDs seem unintuitive too.)

Universal relations

Every table (base or query result) has a predicate (statement template) that a row makes either into a true statement (and goes in the table) or a false statement (and stays out). We say the table represents the business relationship/association characterized by the predicate. A guess at a predicate here is:

book A titled B with isbn C published in year D
    was borrowed by a reader G named H born on date I
        with phone# L and email address M registered on date N
    in loan O issued on date P due on date S
    and either it was returned on date T or it is not yet returned and T=NULL
    and it was written by author U named V
    and the library has A in cover/copy W named X

You seem to be using the "universal relation" decomposition design/normalization technique. But this is only applicable if your one table satisfies the "universal relation assumption". Which is that all your situations can be described via the one predicate and its one table.

Eg: Suppose you can have books that have not been loaned or users that haven't borrowed. Then the example predicate/table above could not record them. So a decomposition wouldn't be able to record them. So you would instead start with a different predicate/table. (Typically multiple ones.)

Eg: If the last line was and A was borrowed in cover/copy W named X then the table could hold a different value in a given situation than before. But depending on the borrowing policy the table could satisfy the same set of FDs.

What is the predicate for this table? If it's not what you guessed, your expectations might not be met.

Your decomposition

Let's ignore the properties of entities.

-- O is G borrowing A by U with W

A   book_id
G   reader_id
O   loan_id
U   author_id
W   cover/copy_id

O->AG
U->A
W->A

The only CK is OUW. Here is an obvious decomposition to BCNF. It agrees with your version.

-- O is G borrowing A by someone with some cover/copy
-- O is G borrowing A
Loan(O,G,A)

-- some loan is somebody borrowing A by U with some cover/copy
-- the book of U is A
The_book_of_author(U,A)

-- some loan is somebody borrowing A by someone with W
-- the book of W is A
The_book_of_cover/copy(W,A)

-- O is somebody borrowing some book by U with W
-- O is the borrowing of the book of U and W
Author_and_cover/copy(O,U,W)

The original relation is the join of the components:

--     O is G borrowing A
    and the book of U is A
    and the book of W is A
    and O is the borrowing of the book of U and W
-- O is G borrowing A by U with W
Loan JOIN The_book_of_author JOIN The_book_of_cover/copy JOIN Author_and_cover/copy

this is not good because table Book has a many to many relationship with table Category, and so do the Book and Author tables

Unfortunately this is unintelligible. So I can't address what you mean to say is wrong.

Database design

If you generated this design yourself, you should be using some reference information modeling method. This will guide you to determine reasonable predicates/tables to record all the situations that can arise according to your business rules.

Predicates applied to what situations can arise determine what states can arise. Those valid states are described by constraints--FDs (functional dependencies), JDs (join dependencies), CKs (candidate keys), FKs (foreign keys) (aka "relationships" in a different sense than above), etc.

Part of a method is normalizing provisional tables to others. This uses FDs & JDs to decompose to an appropriate NF (normal form) via an appropriate algorithm. A good method always normalizes to 5NF. (Even if you denormalize it later for implementation reasons.)


问:
Free-jqGrid – Button on caption click works only at center
I have a free-jqGrid as shown below. It has a button with a + icon in it.

Expected Behavior:  On mouseover the color of the plus icon become white and on click, it shows an alert message.

But this functionality works only when the mouse is pointed towards the center of the button. If I move mouse from right edge of browser and reach the bottom right part of the button, no visual change happen – and on click nothing happens.  However if I do it on a simple dynamic button (without grid) as shown in second fiddle, it works correctly.

Button in Grid Caption: Fiddle 1

Dynamic Button alone: Fiddle 2

How to fix / workaround this in free-jqgrid?

Note: I am using Google Chrome version 58.

Caption Script

```<code>var htmlButtonElement = '<button id="btnAddProvider" type="button" class="btn btn-info toolbar-button" title="Add Provider" style="float:left;">'+
              '<span id="spanAddProvider" class="glyphicon glyphicon-plus" style="pointer-events: none;"></span>'+
          '</button>'

        function getGridCaption() {
            return "<div style='font-size:15px; font-weight:bold; display:inline; padding-left:10px;'><span class='glyphicon glyphicon-check' style='margin-right:3px;font-size:14px;'></span>" + getCurrentPractice() + " " + "</div>" +
            "<div style='float:right; padding-right:20px; padding-bottom:10px; display:inline;>" +
           "<div style='float:right;width:550px;  padding-bottom:20px;'>" +
                 "<div class='btn-group' style='float:right; padding-top:1px;'> " +
                  htmlButtonElement+
                "</div>" +
                "<input type='text' class='form-control' id='filter' placeholder='Search'  style='width:250px; height:30px; float:right; ' />" +
            " </div>" +
            "</div><div class='ui-helper-clearfix'></div>";
        }
</code>```

Update:

Fixed as per Oleg's answer: Fiddle 3

答:
It seems to me that your question more about jQuery UI CSS, which you use as about free jqGrid. The most elements of jQuery UI classes defines background-image additionally to background-color. To be exact, jQuery UI uses background to define background-image, background-color and some other background-xxx CSS properties at once. Thus you should use background: silver instead of background-color: silver or continue to use background-color: silver, but to add background-image: none additionally. You can additionally define :hover rules (like .toolbar-button:hover) to define CSS properties of the button in the hover state. For example, the demo https://jsfiddle.net/OlegKi/x59xx4n1/3/ uses the following properties

.toolbar-button {
    background-color: silver;
    background-image: none;
    color: darkblue;
}
.toolbar-button:hover {
    background-color: green;
    color: yellow;
}
```

UPDATED: One more demo https://jsfiddle.net/OlegKi/x59xx4n1/5/ uses hidegrid: false option and remove ui-jqgrid-caption class from the header of the grid.

Body:
I have a free-jqGrid as shown below. It has a button with a + icon in it.

Expected Behavior:  On mouseover the color of the plus icon become white and on click, it shows an alert message.

But this functionality works only when the mouse is pointed towards the center of the button. If I move mouse from right edge of browser and reach the bottom right part of the button, no visual change happen – and on click nothing happens.  However if I do it on a simple dynamic button (without grid) as shown in second fiddle, it works correctly.

Button in Grid Caption: Fiddle 1

Dynamic Button alone: Fiddle 2

How to fix / workaround this in free-jqgrid?

Note: I am using Google Chrome version 58.

Caption Script

var htmlButtonElement = '<button id="btnAddProvider" type="button" class="btn btn-info toolbar-button" title="Add Provider" style="float:left;">'+
              ''+
          '</button>'

        function getGridCaption() {
            return "
" + getCurrentPractice() + " " + "
" +
            "
" +
           "
" +
                 "
 " +
                  htmlButtonElement+
                "
" +
                "<input type='text' class='form-control' id='filter' placeholder='Search'  style='width:250px; height:30px; float:right; ' />" +
            "
" +
            "

";
        }

Update:

Fixed as per Oleg's answer: Fiddle 3

Body:
It seems to me that your question more about jQuery UI CSS, which you use as about free jqGrid. The most elements of jQuery UI classes defines background-image additionally to background-color. To be exact, jQuery UI uses background to define background-image, background-color and some other background-xxx CSS properties at once. Thus you should use background: silver instead of background-color: silver or continue to use background-color: silver, but to add background-image: none additionally. You can additionally define :hover rules (like .toolbar-button:hover) to define CSS properties of the button in the hover state. For example, the demo https://jsfiddle.net/OlegKi/x59xx4n1/3/ uses the following properties

.toolbar-button {
    background-color: silver;
    background-image: none;
    color: darkblue;
}
.toolbar-button:hover {
    background-color: green;
    color: yellow;
}

UPDATED: One more demo https://jsfiddle.net/OlegKi/x59xx4n1/5/ uses hidegrid: false option and remove ui-jqgrid-caption class from the header of the grid.


问:
Can I call a copy constructor explicitly?
I'm a little confused as to the mechanics of the copy constructor. Correct me if I'm wrong:

If a method takes a reference to an object as a parameter, and the class defines a copy construtor, then the class uses the constructor to create a copy of itself and that gets passed to the function instead of a reference to the original object?

Furthermore, one can call

```<code>Object * obj = new Object(&anotherObject);
</code>```

to create a copy of anotherObject?

答:
yes using placement new like so:</p>

```<code>Object dstObject;
new(&dstObject) Object(&anotherObject);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm a little confused as to the mechanics of the copy constructor. Correct me if I'm wrong:

If a method takes a reference to an object as a parameter, and the class defines a copy construtor, then the class uses the constructor to create a copy of itself and that gets passed to the function instead of a reference to the original object?

Furthermore, one can call

Object * obj = new Object(&anotherObject);

to create a copy of anotherObject?

Body:
yes using placement new like so:

Object dstObject;
new(&dstObject) Object(&anotherObject);


问:
Mysql Check If Data Exists, otherwise Query to Another Table
I'm trying to avoid 2 queries here.. so what i'm trying to do is First, check if data exists on that table.. if it does exists, then fetch data from that table.. otherwise, query to another table.. my script looks like this

```<code>select if( exists(
    select 1
    from emoney_promo.promo_participants pp
    left join emoney_promo.promo_dtl_child pdc on pdc.active_promo_id = pp.id
    where pp.applied_to = '4518'
),
(
    select pdc.*
    from emoney_promo.promo_participants pp
    left join emoney_promo.promo_dtl_child pdc on pdc.active_promo_id = pp.id
    where pp.applied_to = '4518'
),
(
    select pp.id as pp_id, pv.id as pv_id, pv.validation_type as pv_validationtype, pv.validation_value as pv_validationvalue,
    pc.id as pc_id, pc.tanggal as pc_tanggal, pc.counter as pc_counter, pc.member_id as pc_memberid, pc.mid as pc_mid,
    pd.min_amount_trx as pd_minamounttrx, pd.max_amount_trx as pd_maxamounttrx, pd.cashback_type as pd_cashbacktype
    from emoney_promo.promo_validation pv
    join emoney_promo.promo_counter pc on pv.promo_id = pc.promo_id
    join emoney_promo.promo_dtl pd on pd.promo_id = pv.promo_id
    join emoney_promo.promo_participants pp on pp.promo_id = pv.promo_id
    where pc.member_id = '0867667762'
    and pp.applied_to = '4518'
    and pc.mid = '4518'
));
</code>```

But it shows Error Code: 1241. Operand should contain 1 column(s)
is there any way to achieve this? Once again, i'm trying to avoid 2 queries, that's why i'm using this :)

答:
As mentioned: when your first query doesn't return any record, the second won't either (as you are applying the same criteria). So you can simply execute the first query only and either you get a result or not.

Anyway, the typical method to write such query as you describe is:

```<code>select a, b, c from ... -- <== first query
union all
select d, e, f from ... -- <== second query
where not exists (<first query again>)
</code>```

As to performence: yes you send just one query to the DBMS and save time thus. However, the combined query is more complicated than the separate ones. This can take way longer to execute. I'd usually go for two separate queries hence, but sometimes it may make sense to have such a combined query (especially when the first query almost always returns no rows).

Body:
I'm trying to avoid 2 queries here.. so what i'm trying to do is First, check if data exists on that table.. if it does exists, then fetch data from that table.. otherwise, query to another table.. my script looks like this

select if( exists(
    select 1
    from emoney_promo.promo_participants pp
    left join emoney_promo.promo_dtl_child pdc on pdc.active_promo_id = pp.id
    where pp.applied_to = '4518'
),
(
    select pdc.*
    from emoney_promo.promo_participants pp
    left join emoney_promo.promo_dtl_child pdc on pdc.active_promo_id = pp.id
    where pp.applied_to = '4518'
),
(
    select pp.id as pp_id, pv.id as pv_id, pv.validation_type as pv_validationtype, pv.validation_value as pv_validationvalue,
    pc.id as pc_id, pc.tanggal as pc_tanggal, pc.counter as pc_counter, pc.member_id as pc_memberid, pc.mid as pc_mid,
    pd.min_amount_trx as pd_minamounttrx, pd.max_amount_trx as pd_maxamounttrx, pd.cashback_type as pd_cashbacktype
    from emoney_promo.promo_validation pv
    join emoney_promo.promo_counter pc on pv.promo_id = pc.promo_id
    join emoney_promo.promo_dtl pd on pd.promo_id = pv.promo_id
    join emoney_promo.promo_participants pp on pp.promo_id = pv.promo_id
    where pc.member_id = '0867667762'
    and pp.applied_to = '4518'
    and pc.mid = '4518'
));

But it shows Error Code: 1241. Operand should contain 1 column(s)
is there any way to achieve this? Once again, i'm trying to avoid 2 queries, that's why i'm using this :)

Body:
As mentioned: when your first query doesn't return any record, the second won't either (as you are applying the same criteria). So you can simply execute the first query only and either you get a result or not.

Anyway, the typical method to write such query as you describe is:

select a, b, c from ... -- <== first query
union all
select d, e, f from ... -- <== second query
where not exists (<first query again>)

As to performence: yes you send just one query to the DBMS and save time thus. However, the combined query is more complicated than the separate ones. This can take way longer to execute. I'd usually go for two separate queries hence, but sometimes it may make sense to have such a combined query (especially when the first query almost always returns no rows).


问:
Jquery not working to hide and show div until Bootstrap tab clicked
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rental">
DOWNLOAD APPLICATION
</div>

<div id="homeo">
Test
</div>

  <ul class="nav nav-pills">
    <li id="myTab" class="overview active">RENTAL</li>
    <li>HOMEOWNER</li>
  </ul></code>```

答:
Why not use CSS or style attribute to hide the element on pageload. Suppose you want to only show rental at page load

```<code><div id="homeo" style="display:none;">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">Test</a>
</div>
</code>```

Or with CSS

```<code>#homeo {
    display: none;
}
</code>```

Body:
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

DOWNLOAD APPLICATION

Test

RENTAL

HOMEOWNER

Body:
Why not use CSS or style attribute to hide the element on pageload. Suppose you want to only show rental at page load

<div id="homeo" style="display:none;">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">Test</a>
</div>

Or with CSS

#homeo {
    display: none;
}


问:
Create list of tuples , tuple elements taken as Input
I wish to create a list whose members are tuples, taken from console input. I've seen other questions which describe about tuples and lists. But how to create tuples from input and append them to list till the choice to take tuple elements is no, 'n'? I tried the following code.

```<code>"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    print("Add an element for the tuple ? y/n : ")
    ch=str(input())
    while(ch=='y') :
        print("Enter the tuple element : ")
        i=input()
        l=l.append(tuple(i))
        print("Add an element for the tuple ? y/n : ")
        ch=str(input())
    return l

l2=createTupledList()
print(l2)
</code>```

Please help.

My inputs and error output :

```<code>C:\Users\vikranth\myproject\Python\Lists\Day 0>py tuplesortlist.py
Add an element for the tuple ? y/n :
y
Enter the tuple element :
1
Add an element for the tuple ? y/n :
y
Enter the tuple element :
2
Traceback (most recent call last):
  File "tuplesortlist.py", line 19, in <module>
    l2=createTupledList()
  File "tuplesortlist.py", line 12, in createTupledList
    l=l.append(tuple(i))
AttributeError: 'NoneType' object has no attribute 'append'
</code>```

答:
The append() function does not return an appended list, it returns a NoneType because it performs the append in place, so you can simply change the line:

```<code>l=l.append(tuple(i))
</code>```

to:

```<code>l.append(tuple(i))
</code>```

and this should work.

Body:
I wish to create a list whose members are tuples, taken from console input. I've seen other questions which describe about tuples and lists. But how to create tuples from input and append them to list till the choice to take tuple elements is no, 'n'? I tried the following code.

"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    print("Add an element for the tuple ? y/n : ")
    ch=str(input())
    while(ch=='y') :
        print("Enter the tuple element : ")
        i=input()
        l=l.append(tuple(i))
        print("Add an element for the tuple ? y/n : ")
        ch=str(input())
    return l

l2=createTupledList()
print(l2)

Please help.

My inputs and error output :

C:\Users\vikranth\myproject\Python\Lists\Day 0>py tuplesortlist.py
Add an element for the tuple ? y/n :
y
Enter the tuple element :
1
Add an element for the tuple ? y/n :
y
Enter the tuple element :
2
Traceback (most recent call last):
  File "tuplesortlist.py", line 19, in <module>
    l2=createTupledList()
  File "tuplesortlist.py", line 12, in createTupledList
    l=l.append(tuple(i))
AttributeError: 'NoneType' object has no attribute 'append'

Body:
The append() function does not return an appended list, it returns a NoneType because it performs the append in place, so you can simply change the line:

l=l.append(tuple(i))

to:

l.append(tuple(i))

and this should work.


问:
StructureMap and .Net Core
I am creating a barebones .NET Core web api project (Started from blank template below) https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

The code below was working fine, until I added StructureMap. Now, I am getting this error.

StructureMap.StructureMapConfigurationException: No default Instance
  is registered and cannot be automatically determined for type
  'System.IServiceProvider'

There is no configuration specified for System.IServiceProvider

1.) Container.GetInstance()

at StructureMap.SessionCache.GetDefault(Type pluginType,
  IPipelineGraph pipelineGraph)    at
  StructureMap.Container.GetInstanceT    at
  WebApplication4.Startup.ConfigureServices(IServiceCollection services)
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at
  Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection
  services)    at
  Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
  at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Any ideas?

Please note: We are not using builder.AppMvc() as we are trying to slim this api down as much as possible.

Here is the relevant code.

```<code>    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddMvcCore();
        builder.AddApiExplorer();

        builder.AddAuthorization();
        builder.AddFormatterMappings();
        builder.AddJsonFormatters();
        builder.AddCors();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });

        var container = ContainerConfigurator.Configure();

        return container.GetInstance<IServiceProvider>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseMvc();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }

public class ContainerConfigurator
{
    public static Container Configure()
    {
        var container = new Container(
            x => x.Scan
            (
                s =>
                {
                    s.TheCallingAssembly();
                    s.WithDefaultConventions();
                    s.AddAllTypesOf<IStartupTask>();
                    s.LookForRegistries();
                    s.AssembliesAndExecutablesFromApplicationBaseDirectory();

                }
            )
        );

        return container;
    }
}
</code>```

答:
You forgot to populate the container using the service collection, that's why container doesn't know how to resolve IServiceProvider.

Add x.Populate(services); line where services is an instance of IServiceCollection that you have in ConfigureServices method. Something like this should work:

```<code> public static Container Configure(IServiceCollection services)
 {
    var container = new Container( config  =>
      {
          config.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
                s.AddAllTypesOf<IStartupTask>();
                s.LookForRegistries();
                s.AssembliesAndExecutablesFromApplicationBaseDirectory();
            });
          config.Populate(services);
       });

    return container;
}
</code>```

Title: StructureMap and .Net Core

Body:
I am creating a barebones .NET Core web api project (Started from blank template below) https://andrewlock.net/removing-the-mvc-razor-dependencies-from-the-web-api-template-in-asp-net-core/

The code below was working fine, until I added StructureMap. Now, I am getting this error.

StructureMap.StructureMapConfigurationException: No default Instance
  is registered and cannot be automatically determined for type
  'System.IServiceProvider'

There is no configuration specified for System.IServiceProvider

1.) Container.GetInstance()

at StructureMap.SessionCache.GetDefault(Type pluginType,
  IPipelineGraph pipelineGraph)    at
  StructureMap.Container.GetInstanceT    at
  WebApplication4.Startup.ConfigureServices(IServiceCollection services)
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at
  Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection
  services)    at
  Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
  at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

Any ideas?

Please note: We are not using builder.AppMvc() as we are trying to slim this api down as much as possible.

Here is the relevant code.

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        var builder = services.AddMvcCore();
        builder.AddApiExplorer();

        builder.AddAuthorization();
        builder.AddFormatterMappings();
        builder.AddJsonFormatters();
        builder.AddCors();

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
        });

        var container = ContainerConfigurator.Configure();

        return container.GetInstance<IServiceProvider>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        app.UseMvc();

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }

public class ContainerConfigurator
{
    public static Container Configure()
    {
        var container = new Container(
            x => x.Scan
            (
                s =>
                {
                    s.TheCallingAssembly();
                    s.WithDefaultConventions();
                    s.AddAllTypesOf<IStartupTask>();
                    s.LookForRegistries();
                    s.AssembliesAndExecutablesFromApplicationBaseDirectory();

                }
            )
        );

        return container;
    }
}

Body:
You forgot to populate the container using the service collection, that's why container doesn't know how to resolve IServiceProvider.

Add x.Populate(services); line where services is an instance of IServiceCollection that you have in ConfigureServices method. Something like this should work:

 public static Container Configure(IServiceCollection services)
 {
    var container = new Container( config  =>
      {
          config.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
                s.AddAllTypesOf<IStartupTask>();
                s.LookForRegistries();
                s.AssembliesAndExecutablesFromApplicationBaseDirectory();
            });
          config.Populate(services);
       });

    return container;
}