问:
Can't create a trigger into PHPMyAdmin
I just want to create a trigger for my phpmyadmin. Basically the intended function is whenever I update a credit column of my finance table, the balance column will be automatically updated for each row.

My program is:

```<code>    CREATE TRIGGER UPDATE_BALANCE AFTER UPDATE financeofstudents
    FOR EACH ROW
    BEGIN
    IF financeofstudents.credit > 0
    AND
    financeofstudents.credit <= financeofstudents.debit
    THEN
    UPDATE financeofstudents SET financeofstudents.balance = financeofstudents.debit-    financeofstudents.credit;
    END IF;
    END
</code>```

but it gives me this error:

```<code>    Error

SQL query:

CREATE TRIGGER UPDATE_BALANCE AFTER UPDATE financeofstudents
FOR EACH ROW
BEGIN
IF financeofstudents.credit > 0
AND
financeofstudents.credit <= financeofstudents.debit
THEN
UPDATE financeofstudents SET financeofstudents.balance = financeofstudents.debit-financeofstudents.credit

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'financeofstudents
FOR EACH ROW
BEGIN
IF financeofstudents.credit > 0
AND
f' at line 1
</code>```

I don't know where is the problem. Expert guys, please help me.

答:
The error message is a useful hint here.  It says .. for the right syntax to use near 'some text from your query starting with the first thing it didn't understand'.

In your case, you need the word ON before the name of the table.

```<code>CREATE TRIGGER update_balance
       AFTER UPDATE
       ON financeofstudents

FOR EACH ROW
</code>```

If you observed that MySQL error messages are hard to interpret, you would be correct.

Title: Can't create a trigger into PHPMyAdmin

Body:
I just want to create a trigger for my phpmyadmin. Basically the intended function is whenever I update a credit column of my finance table, the balance column will be automatically updated for each row.

My program is:

    CREATE TRIGGER UPDATE_BALANCE AFTER UPDATE financeofstudents
    FOR EACH ROW
    BEGIN
    IF financeofstudents.credit > 0
    AND
    financeofstudents.credit <= financeofstudents.debit
    THEN
    UPDATE financeofstudents SET financeofstudents.balance = financeofstudents.debit-    financeofstudents.credit;
    END IF;
    END

but it gives me this error:

    Error

SQL query:

CREATE TRIGGER UPDATE_BALANCE AFTER UPDATE financeofstudents
FOR EACH ROW
BEGIN
IF financeofstudents.credit > 0
AND
financeofstudents.credit <= financeofstudents.debit
THEN
UPDATE financeofstudents SET financeofstudents.balance = financeofstudents.debit-financeofstudents.credit

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'financeofstudents
FOR EACH ROW
BEGIN
IF financeofstudents.credit > 0
AND
f' at line 1

I don't know where is the problem. Expert guys, please help me.

Body:
The error message is a useful hint here.  It says .. for the right syntax to use near 'some text from your query starting with the first thing it didn't understand'.

In your case, you need the word ON before the name of the table.

CREATE TRIGGER update_balance
       AFTER UPDATE
       ON financeofstudents

FOR EACH ROW

If you observed that MySQL error messages are hard to interpret, you would be correct.


来源: stackexchange

问:
ERROR ITMS-90171: "Invalid Bundle Structure The binary file APP.app/libswiftRemoteMirror.dylib is not permitted
I'm going to convert sift 2.2 to swfit 3.0 and uploading to itunes store then get one error.

I'm so tired with this error:-

ERROR ITMS-90171: "Invalid Bundle Structure - The binary file 'ideaPitch.app/libswiftRemoteMirror.dylib' is not permitted. Your app can’t contain standalone executables or libraries, other than the CFBundleExecutable of supported bundles. Refer to the Bundle Programming Guide at https://developer.apple.com/go/?id=bundle-structure for information on the iOS app bundle structure."

I have try some solution like this question but did not get proper result.

Any one can hlep me out.

答:
I assume that you're generating the IPA on the command line.

Your best option is to simply use the Xcode7/8 default way to generate an IPA file:

```<code>xcodebuild -scheme $SCHEME clean archive $ARCHIVE_PATH
xcodebuild -exportArchive -archivePath $ARCHIVE_PATH -exportPath $IPA_PATH -exportOptionsPlist $EXPORT_PLIST
</code>```

This approach will automatically take care of removing the libswiftRemoteMirror.dylib from the resulting IPA file.

Alternatively you will have to remove the dylib on your own. You'll have to do it after creating the xcarchive but before exporting it to an IPA file: rm -rf $APP_PATH/libswiftRemoteMirror.dylib

EDIT

In case you can't rebuild the IPA on your own and just want to remove the libswiftRemoteMirror.dylib from it, you'll have to resign it: unzip the IPA, delete the dylib, re-codesign the bundle and zip it together again:

```<code>unzip AppName.ipa -d IPA
cd IPA
rm -rf Payload/$APP_NAME.app/libswiftRemoteMirror.dylib
codesign -vfs '$IDENTITY_NAME' Payload/$APP_NAME.app
zip -r --symlinks New_IPA.ipa *
</code>```

Replace $APP_NAME with the name of your App bundle. Replace $IDENTITY_NAME with the name of the codesign identity used to originally sign the app. If unknown, you display it with codesign -dvv Payload/$APP_NAME.app 2>&1 | grep Authority | head -1 | cut -d= -f2.

The matching Certificate and Private Key must be present in your keychain for a successful resign. If your app uses special entitlements for push, associated domains etc., you'll have to pass a proper --entitlements param to the codesign command above.

ContentLicense: CC BY-SA 3.0

Body:
I assume that you're generating the IPA on the command line.

Your best option is to simply use the Xcode7/8 default way to generate an IPA file:

xcodebuild -scheme $SCHEME clean archive $ARCHIVE_PATH
xcodebuild -exportArchive -archivePath $ARCHIVE_PATH -exportPath $IPA_PATH -exportOptionsPlist $EXPORT_PLIST

This approach will automatically take care of removing the libswiftRemoteMirror.dylib from the resulting IPA file.

Alternatively you will have to remove the dylib on your own. You'll have to do it after creating the xcarchive but before exporting it to an IPA file: rm -rf $APP_PATH/libswiftRemoteMirror.dylib

EDIT

In case you can't rebuild the IPA on your own and just want to remove the libswiftRemoteMirror.dylib from it, you'll have to resign it: unzip the IPA, delete the dylib, re-codesign the bundle and zip it together again:

unzip AppName.ipa -d IPA
cd IPA
rm -rf Payload/$APP_NAME.app/libswiftRemoteMirror.dylib
codesign -vfs '$IDENTITY_NAME' Payload/$APP_NAME.app
zip -r --symlinks New_IPA.ipa *

Replace $APP_NAME with the name of your App bundle. Replace $IDENTITY_NAME with the name of the codesign identity used to originally sign the app. If unknown, you display it with codesign -dvv Payload/$APP_NAME.app 2>&1 | grep Authority | head -1 | cut -d= -f2.

The matching Certificate and Private Key must be present in your keychain for a successful resign. If your app uses special entitlements for push, associated domains etc., you'll have to pass a proper --entitlements param to the codesign command above.


问:
Ideal cross-platform library
One has to create a new software library. This library has no system I/O routines and contains only Init(config), Run(some_data_inputs), and DeInit(config) functions and a few typedefs and defines. Run() function just processes given input data and generates output data, no interrupts, threads, locks, etc. However, it requires some RAM for its internal needs. The interface is described in a header file and a static library contains the implementation.

This library must be as much multi-plarform as possible. It must be matter of minutes to port this library to any new platform onto any new OS+CPU. Sometimes this lib can be used even on the platforms without operating systems.

So, before starting development, one has to decide:

Must this lib be written in ANSI-C or even in a sub-set of ANSI-C because some platforms may not support ANSI-C completely?

Whether to write an abstraction
layer, which encapsulates an
underlying OS+CPU?

Should this abstraction layer
include its own memory manager
(malloc/free routines) or all
platforms today provide it already?

答:
Must this lib be written in ANSI-C or even in a sub-set of ANSI-C
  because some platforms may not support
  ANSI-C completely?

Neither, I suggest ISO C.  ANSI has not been the standards body for C since 1990. ISO C90 should be ubiquitous.  Depending on the target platform capabilities, the accompanying Standard Library may be a subset, or may require implementation of stubs to port it to a particular target.  The Newlib C library, often used in embedded systems using GCC for example, requires basic I/O stubs (not required in this case since you have specified that no I/O operations take place) and the sbrk() function to be implemented. sbrk() provides memory to the heap allocator; it requires no OS, or it could request memory from an OS.

Whether to write an abstraction layer, which encapsulates an
  underlying OS+CPU?

Give the restrictions you have imposed on this library design, it seems that the are no OS issues.  The standard library provides the requirements for memory allocation.

Should this abstraction layer include its own memory manager
  (malloc/free routines) or all
  platforms today provide it already?

Answered in (1); provide them as part of the standard library or use the existing implementation for the platform.

In the end what you need is to write your library to use C90 and the standard library, then it is simply a matter of porting the standard library to the target if it is not already done.

ContentLicense: CC BY-SA 2.5

Title: Ideal cross-platform library


问:
Problems with input shapes at finetuning VGG with Keras
I'm trying to finetune the last layer of the VGG-16. Here is the part of the code where i make the new model:

```<code>def train2false(model):
    for layer in model.layers:
        layer.trainable = False
    return model

def define_training_layers(model):
     model.layers = model.layers[0:21]
     model = train2false(model)
     last_layer = model.get_layer('fc7')
     out = Dense(n_classes, activation='softmax', name='fc8')(last_layer)
     model = Model(input=model.input, output=out)
     return model

def compile_model(epochs, lrate, model):
    decay = lrate / epochs
    sgd = SGD(lr=lrate, momentum=0, decay=0.0002, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    print (model.summary())

    return model

def train_evaluate(model, X_train, y_train, X_test, y_test, epochs):
    model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=epochs, batch_size=32)
    # Final evaluation of the model
    scores = model.evaluate(X_test, y_test, verbose=0)
    print("Accuracy: %.2f%%" % (scores[1]*100))

    return model

X_train, X_test, labels_test, labels_train, n_classes = load_dataset()
image_input = Input(shape=(3, 224, 224))
vgg_model = VGGFace(input_tensor= image_input, include_top=True)
custom_vgg_model = define_training_layers(vgg_model)
custom_vgg_model = compile_model(epochs=50, lrate=0.001, model=custom_vgg_model)
custom_vgg_model = train_evaluate(custom_vgg_model, X_train=X_train, y_train=labels_train, X_test=X_test, y_test=labels_test, epochs=50)
</code>```

I get the following error:

tensorflow.python.framework.errors_impl.InvalidArgumentError:
  Dimension 1 in both shapes must be equal, but are 1000 and 2622 for
  'Assign_30' (op: 'Assign') with input shapes: [4096,1000],
  [4096,2622].

It works for me if i try to finetune all the fully connected part with include_top=False instead of just the softmax activation.

Is there something that i'm missing?

答: Solved!!! I've take the pre-trained weights from https://github.com/rcmalli/keras-vggface/releases/download/v1.0/rcmalli_vggface_th_weights_th_ordering.h5 which has 2622 number of outputs and i had 1000 outputs. So just change the number of outputs for the last layer in VGG.py</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to finetune the last layer of the VGG-16. Here is the part of the code where i make the new model:

def train2false(model):
    for layer in model.layers:
        layer.trainable = False
    return model

def define_training_layers(model):
     model.layers = model.layers[0:21]
     model = train2false(model)
     last_layer = model.get_layer('fc7')
     out = Dense(n_classes, activation='softmax', name='fc8')(last_layer)
     model = Model(input=model.input, output=out)
     return model

def compile_model(epochs, lrate, model):
    decay = lrate / epochs
    sgd = SGD(lr=lrate, momentum=0, decay=0.0002, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    print (model.summary())

    return model

def train_evaluate(model, X_train, y_train, X_test, y_test, epochs):
    model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=epochs, batch_size=32)
    # Final evaluation of the model
    scores = model.evaluate(X_test, y_test, verbose=0)
    print("Accuracy: %.2f%%" % (scores[1]*100))

    return model

X_train, X_test, labels_test, labels_train, n_classes = load_dataset()
image_input = Input(shape=(3, 224, 224))
vgg_model = VGGFace(input_tensor= image_input, include_top=True)
custom_vgg_model = define_training_layers(vgg_model)
custom_vgg_model = compile_model(epochs=50, lrate=0.001, model=custom_vgg_model)
custom_vgg_model = train_evaluate(custom_vgg_model, X_train=X_train, y_train=labels_train, X_test=X_test, y_test=labels_test, epochs=50)

I get the following error:

tensorflow.python.framework.errors_impl.InvalidArgumentError:
  Dimension 1 in both shapes must be equal, but are 1000 and 2622 for
  'Assign_30' (op: 'Assign') with input shapes: [4096,1000],
  [4096,2622].

It works for me if i try to finetune all the fully connected part with include_top=False instead of just the softmax activation.

Is there something that i'm missing?


问:
Is there a way to open camera and view it on screen and make is so it is not able to take pictures or record videos.
I am creating a android app which has the following requirement and can you tell how to implement it.

1) Open Camera in a fragment,
2) Should not be able to record videos or take pictures.

I am new to android, so it will very helpful if you guys help me out here.

Thanks in advance.

答:
The best practice to achieve your requirement is through surface view.

 SurfaceView in android provides a way to show camera on the device to user.
It provides various classes, so that you can customize the camera and add your functionalities to it as per your need.

Mentioned below are few links, that will guide you through surface view:
https://developer.android.com/reference/android/view/SurfaceView.html
https://www.airpair.com/android/android-camera-surface-view-fragment

Hope this helps.


问:
OpenCV, I get segmentation and cant find it
I am pretty new with C++ so i really don't know what went wrong. I have a function here which to get the orignal_image and make it to a oilpaiting.
https://www.codeproject.com/Articles/471994/OilPaintEffect
I followed these steps but I still get a Segmentation fault.</p>

```<code>cv::Mat getFilteredImage(const cv::Mat &original_image,
                     int radius,
                     int levels)
{

for(int i=0;i<original_image.rows;i++)
{
    for(int j=0;j<original_image.cols;j++)
    {
        for(int k=-radius;k<=radius;k++)
        {
            for(int l=-radius;l<=radius;l++)
            {
                int IB = original_image.at<cv::Vec3b>(j,i)[0];
                 int IG = original_image.at<cv::Vec3b>(j,i)[1];
                int IR = original_image.at<cv::Vec3b>(j,i)[2];

                int intervall = floor(((double)((IR+IG+IB)/3.0) * (levels/255.0)));//eine Pixel intensität errechen

                if(intervall>255)
                {
                    intervall = 255;
                }
                std::vector<int> intensityCount;
                intensityCount[intervall]++;

                int averageB[intervall];
                int averageG[intervall];
                int averageR[intervall];

                averageB[intervall] += IB;
                averageG[intervall] += IG;
                averageR[intervall] += IR;

                }

            }

                int Curmax=0;
                int maxIndex;

                for(int nI = 0; nI<256;nI++)
                {
                    if(intensityCount[nI]>Curmax)  //this is not allowed
                    {
                        Curmax = intensityCount[nI];
                        maxIndex = nI;

                    }

        }

    }

}

cv::Mat output = cv::Mat::zeros(original_image.size(),
                                original_image.type());

return output;
}
</code>```

答:
```<code>std::vector<int> intensityCount;
intensityCount[intervall]++;
</code>```

This doesn't do what you whink it does. The first line declares and initialises an empty vector. This means that your second line will access uninitialised memory, which is the cause for your segfault. To fix this, either initialise you vector with a given size (std::vector<int>
 intensityCount(yourSizeHere)) or use push back or emplace back.

Body:
I am pretty new with C++ so i really don't know what went wrong. I have a function here which to get the orignal_image and make it to a oilpaiting.
https://www.codeproject.com/Articles/471994/OilPaintEffect
I followed these steps but I still get a Segmentation fault.

cv::Mat getFilteredImage(const cv::Mat &original_image,
                     int radius,
                     int levels)
{

for(int i=0;i<original_image.rows;i++)
{
    for(int j=0;j<original_image.cols;j++)
    {
        for(int k=-radius;k<=radius;k++)
        {
            for(int l=-radius;l<=radius;l++)
            {
                int IB = original_image.at<cv::Vec3b>(j,i)[0];
                 int IG = original_image.at<cv::Vec3b>(j,i)[1];
                int IR = original_image.at<cv::Vec3b>(j,i)[2];

                int intervall = floor(((double)((IR+IG+IB)/3.0) * (levels/255.0)));//eine Pixel intensität errechen

                if(intervall>255)
                {
                    intervall = 255;
                }
                std::vector<int> intensityCount;
                intensityCount[intervall]++;

                int averageB[intervall];
                int averageG[intervall];
                int averageR[intervall];

                averageB[intervall] += IB;
                averageG[intervall] += IG;
                averageR[intervall] += IR;

                }

            }

                int Curmax=0;
                int maxIndex;

                for(int nI = 0; nI<256;nI++)
                {
                    if(intensityCount[nI]>Curmax)  //this is not allowed
                    {
                        Curmax = intensityCount[nI];
                        maxIndex = nI;

                    }

        }

    }

}

cv::Mat output = cv::Mat::zeros(original_image.size(),
                                original_image.type());

return output;
}

Body:
std::vector<int> intensityCount;
intensityCount[intervall]++;

This doesn't do what you whink it does. The first line declares and initialises an empty vector. This means that your second line will access uninitialised memory, which is the cause for your segfault. To fix this, either initialise you vector with a given size (std::vector<int>
 intensityCount(yourSizeHere)) or use push back or emplace back.


问:
observe form submit response targetting an iframe
I have an app which runs in a new window. There are several forms to generate a PDF export. When I submit one of these forms, the window loses its focus and the original window pops up again when the download appears.

I created an iframe, so the forms can target the iframe and the current window doesn't lose its focus. It works great, but I have no idea how to observe the response inside the iframe if everything went right.

Here is how its working so far. I'm using prototypeJS.

```<code><iframe id="pdf_frame" name="pdf_frame" style="display:none;"></iframe>

<form id="PDF_gen" name="PDF_gen" target="pdf_frame" action="pdf.pl">
      <input type="hidden" name="size" value="">
      <!-- more hidden inputs -->
</form>
<input type="button" id="pdf_submit" value="generate pdf">
</code>```

JS:

```<code>$('pdf_submit').observe('click', function(){
    //write stuff to hidden inputs
    $('PDF_gen').submit();
});
</code>```

If something goes wrong, the download dialogue does not appear. When using prototypes form.request() the browser does not know how to handle the response and does not bring up the download dialogue. How can I do it right?

Thanks in advance!

答:
When something goes wrong in the iframe you can try to fire an event from the iframe to its parent window (assuming we're on the same domain; it won't work cross-domain):

```<code>parent.document.fire('something:went_wrong')
</code>```

and have the parent document listen for that event:

```<code>document.observe('something:went_wrong', function() {...});
</code>```

Body:
I have an app which runs in a new window. There are several forms to generate a PDF export. When I submit one of these forms, the window loses its focus and the original window pops up again when the download appears.

I created an iframe, so the forms can target the iframe and the current window doesn't lose its focus. It works great, but I have no idea how to observe the response inside the iframe if everything went right.

Here is how its working so far. I'm using prototypeJS.

<form id="PDF_gen" name="PDF_gen" target="pdf_frame" action="pdf.pl">
      <input type="hidden" name="size" value="">

</form>
<input type="button" id="pdf_submit" value="generate pdf">

JS:

$('pdf_submit').observe('click', function(){
    //write stuff to hidden inputs
    $('PDF_gen').submit();
});

If something goes wrong, the download dialogue does not appear. When using prototypes form.request() the browser does not know how to handle the response and does not bring up the download dialogue. How can I do it right?

Thanks in advance!

Body:
When something goes wrong in the iframe you can try to fire an event from the iframe to its parent window (assuming we're on the same domain; it won't work cross-domain):

parent.document.fire('something:went_wrong')

and have the parent document listen for that event:

document.observe('something:went_wrong', function() {...});


问:
core -java Exception Handling
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.</p>

```<code> Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }
</code>```

答:
the desired output is Exception.Can anybody explain why the output is
  Exception

Because finally is the last block which executed after try:

```<code>finally {
   m3();
}
</code>```

For that you get Exception and not RuntimeException

Title: core -java Exception Handling

Body:
The Below is a class Question which is propagating Exception handling mechanism,the desired output is Exception.Can anybody explain why the output is Exception ,Thanks in advance.

 Class Question {

  public void m1() throws Exception {

   try {

    m2();

   } finally {

    m3();

   }
  }
  public void m2() throws RuntimeException {

   throw new RuntimeException();

  }

  public void m3() throws Exception {

   throw new Exception();

  }
  public static void main(String[] args) throws Exception {

   Question q = new Question();

   try {

    q.m1();

   } catch (RuntimeException re) {

    System.out.println("RuntimeException");

   } catch (Exception e) {

    System.out.println("Exception");
   }
  }

Body:
the desired output is Exception.Can anybody explain why the output is
  Exception

Because finally is the last block which executed after try:

finally {
   m3();
}

For that you get Exception and not RuntimeException


问:
Can't return my value correctly when recursing a Binary Search Tree
I've tested to see if my trees are being inserted properly and am using pseudoclassical instantiation to make this work. My issue is that the debugger will tell me that truth is being set to true, then when I return the truth value from the end of the function I get false. I have tried everything I can think of but I can't figure out why this is happening. Here's my code that searches the binary search tree.

  var valuetest;
  var truth = false;
  if (this.value === value) {
    var truth = true;
    return truth;
  } else if (value > this.value) {
    valuetest = this.right.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      this.right.contains(value);
    }
  } else {
    valuetest = this.left.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      this.left.contains(value);
    }
  }
  return truth;
  //returns false even if truth is set to true for some reason.```

答:
Updated lines with return. Try this snippet.

  var valuetest;
  var truth = false;
  if (this.value === value) {
    var truth = true;
    return truth;
  } else if (value > this.value) {
    valuetest = this.right.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      return this.right.contains(value);
    }
  } else {
    valuetest = this.left.value;
    if (valuetest === value) {
      truth = true;
      return truth;
    } else {
      return this.left.contains(value);
    }
  }
  return truth;
  //returns false even if truth is set to true for some reason.```


问:
Find distance between two points using latitude and longitude in mysql
Hi I have the following table

```<code> --------------------------------------------
 |  id  |  city  |  Latitude  |  Longitude  |
 --------------------------------------------
 |  1   |   3    |   34.44444 |   84.3434   |
 --------------------------------------------
 |  2   |   4    | 42.4666667 | 1.4666667   |
 --------------------------------------------
 |  3   |   5    |  32.534167 | 66.078056   |
 --------------------------------------------
 |  4   |   6    |  36.948889 | 66.328611   |
 --------------------------------------------
 |  5   |   7    |  35.088056 | 69.046389   |
 --------------------------------------------
 |  6   |   8    |  36.083056 |   69.0525   |
 --------------------------------------------
 |  7   |   9    |  31.015833 | 61.860278   |
 --------------------------------------------
</code>```

Now I want to get distance between two points. Say a user is having a city 3 and a user is having a city 7. My scenario is one user having a city and latitue and longtitude is searching other users distance from his city. For example user having city 3 is searching. He wants to get distance of user of any other city say it is 7. I have searched and found following query

```<code>SELECT `locations`.`city`, ( 3959 * acos ( cos ( radians(31.589167) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(64.363333) ) + sin ( radians(31.589167) ) * sin( radians( Latitude ) ) ) ) AS `distance` FROM `locations` HAVING (distance < 50)
</code>```

As for as I know this query finds distance from one point to all other points. Now I want to get distance from one point to other point.

Any guide line will be much appreciated.

答:
Here's a MySQL function that will take two latitude/longitude pairs, and give you the distance in degrees between the two points. It uses the Haversine formula to calculate the distance. Since the Earth is not a perfect sphere, there is some error near the poles and the equator.

To convert to miles, multiply by 3961.

To convert to kilometers, multiply by 6373.

To convert to meters, multiply by 6373000.

To convert to feet, multiply by (3961 * 5280) 20914080.

```<code>DELIMITER $$

CREATE FUNCTION \`haversine\`(

        lat1 FLOAT, lon1 FLOAT,
        lat2 FLOAT, lon2 FLOAT
     ) RETURNS float
    NO SQL
    DETERMINISTIC
    COMMENT 'Returns the distance in degrees on the Earth between two known points of latitude and longitude. To get miles, multiply by 3961, and km by 6373'

BEGIN

    RETURN DEGREES(ACOS(
              COS(RADIANS(lat1)) *
              COS(RADIANS(lat2)) *
              COS(RADIANS(lon2) - RADIANS(lon1)) +
              SIN(RADIANS(lat1)) * SIN(RADIANS(lat2))
            ));

END;

DELIMITER;
</code>```

Body:
Hi I have the following table

 --------------------------------------------
 |  id  |  city  |  Latitude  |  Longitude  |
 --------------------------------------------
 |  1   |   3    |   34.44444 |   84.3434   |
 --------------------------------------------
 |  2   |   4    | 42.4666667 | 1.4666667   |
 --------------------------------------------
 |  3   |   5    |  32.534167 | 66.078056   |
 --------------------------------------------
 |  4   |   6    |  36.948889 | 66.328611   |
 --------------------------------------------
 |  5   |   7    |  35.088056 | 69.046389   |
 --------------------------------------------
 |  6   |   8    |  36.083056 |   69.0525   |
 --------------------------------------------
 |  7   |   9    |  31.015833 | 61.860278   |
 --------------------------------------------

Now I want to get distance between two points. Say a user is having a city 3 and a user is having a city 7. My scenario is one user having a city and latitue and longtitude is searching other users distance from his city. For example user having city 3 is searching. He wants to get distance of user of any other city say it is 7. I have searched and found following query

SELECT `locations`.`city`, ( 3959 * acos ( cos ( radians(31.589167) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(64.363333) ) + sin ( radians(31.589167) ) * sin( radians( Latitude ) ) ) ) AS `distance` FROM `locations` HAVING (distance < 50)

As for as I know this query finds distance from one point to all other points. Now I want to get distance from one point to other point.

Any guide line will be much appreciated.

Body:
Here's a MySQL function that will take two latitude/longitude pairs, and give you the distance in degrees between the two points. It uses the Haversine formula to calculate the distance. Since the Earth is not a perfect sphere, there is some error near the poles and the equator.

To convert to miles, multiply by 3961.

To convert to kilometers, multiply by 6373.

To convert to meters, multiply by 6373000.

To convert to feet, multiply by (3961 * 5280) 20914080.

DELIMITER $$

CREATE FUNCTION \`haversine\`(

        lat1 FLOAT, lon1 FLOAT,
        lat2 FLOAT, lon2 FLOAT
     ) RETURNS float
    NO SQL
    DETERMINISTIC
    COMMENT 'Returns the distance in degrees on the Earth between two known points of latitude and longitude. To get miles, multiply by 3961, and km by 6373'

BEGIN

    RETURN DEGREES(ACOS(
              COS(RADIANS(lat1)) *
              COS(RADIANS(lat2)) *
              COS(RADIANS(lon2) - RADIANS(lon1)) +
              SIN(RADIANS(lat1)) * SIN(RADIANS(lat2))
            ));

END;

DELIMITER;


问:
New to python and CS. SQlite, flask
I'm new to python and CS so this question might be a bit too easy. Thanks for your help I'm getting an error:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

After implementing a new html template and python function:

```<code>@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""

    session.clear()

    if request.form["name"] == "" or request.form["password"] == "":
        return render_template("apology.html")
    elif request.form["password"] != request.form["confirmation"]:
        return render_template("apology.html")
    hash = pbkdf2_sha256.hash("password")

    do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
        name=request.form.get["name"], hash=hash)

    session["user_id"] = rows[0]["id"]

    return redirect(url_for("index"))
</code>```

```<code>{% extends "layout.html" %}

{% block title %}
    Register
{% endblock %}

{% block main %}
    <form action="{{ url_for('register') }}" method="post">
        <fieldset>
            <div class="form-group">
                <input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"/>
            </div>
            <div class="form-group">
                <input class="form-control" name="password" placeholder="Password" type="password"/>
            </div>
            <div class="form-group">
                <input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>
            </div>
            <div class="form-group">
                <button class="btn btn-default" type="submit">Register</button>
            </div>
        </fieldset>
    </form>
{% endblock %}
</code>```

答:
First you should check if the request type is 'POST', after that you check all the conditions. Do like below to resolve the issue:</p>

```<code>@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""

session.clear()
if request.method == 'POST':
    if request.form["name"] == "" or request.form["password"] == "":
        return render_template("apology.html")
    elif request.form["password"] != request.form["confirmation"]:
        return render_template("apology.html")
    hash = pbkdf2_sha256.hash("password")

    do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
    name=request.form.get["name"], hash=hash)

    session["user_id"] = rows[0]["id"]
    return redirect(url_for("index"))

else:
    // you can render the template to be shown for registration.
</code>```

Title: New to python and CS. SQlite, flask

Body:
I'm new to python and CS so this question might be a bit too easy. Thanks for your help I'm getting an error:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

After implementing a new html template and python function:

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""

    session.clear()

    if request.form["name"] == "" or request.form["password"] == "":
        return render_template("apology.html")
    elif request.form["password"] != request.form["confirmation"]:
        return render_template("apology.html")
    hash = pbkdf2_sha256.hash("password")

    do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
        name=request.form.get["name"], hash=hash)

    session["user_id"] = rows[0]["id"]

    return redirect(url_for("index"))

{% extends "layout.html" %}

{% block title %}
    Register
{% endblock %}

{% block main %}
    <form action="{{ url_for('register') }}" method="post">
        <fieldset>

                <input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"/>

                <input class="form-control" name="password" placeholder="Password" type="password"/>

                <input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>

                <button class="btn btn-default" type="submit">Register</button>

        </fieldset>
    </form>
{% endblock %}

Body:
First you should check if the request type is 'POST', after that you check all the conditions. Do like below to resolve the issue:

@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""

session.clear()
if request.method == 'POST':
    if request.form["name"] == "" or request.form["password"] == "":
        return render_template("apology.html")
    elif request.form["password"] != request.form["confirmation"]:
        return render_template("apology.html")
    hash = pbkdf2_sha256.hash("password")

    do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
    name=request.form.get["name"], hash=hash)

    session["user_id"] = rows[0]["id"]
    return redirect(url_for("index"))

else:
    // you can render the template to be shown for registration.


问:
Scrollable div inside section of Fullpage.js doesn't work
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

```<code>$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});
</code>```

答:
Your markup seems to be not what jquery.fullPage.js expects. It expects an element with the class fp-scrollable to have children, which is not the case in your jsfiddle.

If you move the class so that

```<code><div class="section">
    <div class="test fp-scrollable">
    ...
</code>```

becomes

```<code><div class="section fp-scrollable">
    <div class="test">
    ...
</code>```

you'll see it working. Maybe this is not the markup you want to end up with, maybe you want to further nest .test instead, but regardless this gives you an idea on how to tackle the error.

Body:
I want to have a scrollable div inside a section of fullpage.js but when I include scrollOverflow: true then I get this error: Cannot read property 'scrollHeight' of undefined.

The scrollOverflow library is included:

http://jsfiddle.net/97tbk/1827/

I wonder what am I missing:

$('#fullpage').fullpage({
    sectionsColor: ['yellow', 'orange', '#C0C0C0', '#ADD8E6'],
    scrollOverflow: true
});
$('.fp-scrollable').slimScroll({
    alwaysVisible: true,
    color: 'black',
    size: '10px',
    allowPageScroll: true,
});

Body:
Your markup seems to be not what jquery.fullPage.js expects. It expects an element with the class fp-scrollable to have children, which is not the case in your jsfiddle.

If you move the class so that

<div class="section">
    <div class="test fp-scrollable">
    ...

becomes

<div class="section fp-scrollable">
    <div class="test">
    ...

you'll see it working. Maybe this is not the markup you want to end up with, maybe you want to further nest .test instead, but regardless this gives you an idea on how to tackle the error.


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答:
calloc(a,b) and malloc(a*b) are equivalent except for the possibility of arithmetic overflow or type issues, and the fact that calloc ensures the memory is zero-byte-filled. Either allocated memory that can be used for an array of a elements each of size b (or vice versa). On the other hand, calling malloc(b) a times will results in a individual objects of size b which can be freed independently and which are not in an array (though you could store their addresses in an array of pointers).

Hope this helps.

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}


问:
Unicode error while converting RDD to Spark DataFrame
I am getting the following error when I run show method on the data frame.

```<code>Py4JJavaError: An error occurred while calling o14904.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 23450.0 failed 1 times, most recent failure: Lost task 0.0 in stage 23450.0 (TID 120652, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 172, in main
    process()
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 167, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "<ipython-input-8-b76896bc4e43>", line 320, in <lambda>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:156)
</code>```

When I only fetch 12 rows, it doesn't throw the error.

```<code>jpsa_rf.features_df.show(12)
+------------+--------------------+
|Feature_name|    Importance_value|
+------------+--------------------+
| competitive|0.019380017988201638|
|         new|0.012416277407924172|
|self-reliant|0.009044388916918005|
|     related|0.008968947484358822|
|      retail|0.008729510712416655|
|      sales,|0.007680271475590303|
|        work|0.007548541044789985|
| performance|0.007209008630295571|
|    superior|0.007065626808393139|
|     license|0.006436001036918034|
|    industry|0.006416712169788629|
|      record|0.006227581067732823|
+------------+--------------------+
only showing top 12 rows
</code>```

But when I do .show(15) I get the error.

I created this data frame as below: it is basically a data frame of features with the their importance values from a Random Forest Model

```<code>vocab=np.array(self.cvModel.bestModel.stages[3].vocabulary)
        if est_name=="rf":
            feature_importance=self.cvModel.bestModel.stages[5].featureImportances.toArray()
            argsort_feature_indices=feature_importance.argsort()[::-1]
        elif est_name=="blr":
            feature_importance=self.cvModel.bestModel.stages[5].coefficients.toArray()
            argsort_feature_indices=abs(feature_importance).argsort()[::-1]
        # Sort the features importance array in descending order and get the indices

        feature_names=vocab[argsort_feature_indices]

        self.features_df=sc.parallelize(zip(feature_names,feature_importance[argsort_feature_indices])).\
        map(lambda x: (str(x[0]),float(x[1]))).toDF(["Feature_name","Importance_value"])
</code>```

答:
I assume you're using Python 2. The problem at hand is most likely the str(x[0]) part in your df.map. It seems x[0] refers to a unicode string and the str is supposed to convert it to a bytestring. It does so however by implicitly assuming an ASCII encoding, which will only work for plain english text.

This is not how things are supposed to be done.

The short answer is: Change str(x[0]) to x[0].encode('utf-8').

The long answer can be found e.g. here or here.

Body:
I am getting the following error when I run show method on the data frame.

Py4JJavaError: An error occurred while calling o14904.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 23450.0 failed 1 times, most recent failure: Lost task 0.0 in stage 23450.0 (TID 120652, localhost): org.apache.spark.api.python.PythonException: Traceback (most recent call last):
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 172, in main
    process()
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/worker.py", line 167, in process
    serializer.dump_stream(func(split_index, iterator), outfile)
  File "/Users/i854319/spark2/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "<ipython-input-8-b76896bc4e43>", line 320, in <lambda>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-5: ordinal not in range(128)

    at org.apache.spark.api.python.PythonRunner$$anon$1.read(PythonRDD.scala:193)
    at org.apache.spark.api.python.PythonRunner$$anon$1.next(PythonRDD.scala:156)

When I only fetch 12 rows, it doesn't throw the error.

jpsa_rf.features_df.show(12)
+------------+--------------------+
|Feature_name|    Importance_value|
+------------+--------------------+
| competitive|0.019380017988201638|
|         new|0.012416277407924172|
|self-reliant|0.009044388916918005|
|     related|0.008968947484358822|
|      retail|0.008729510712416655|
|      sales,|0.007680271475590303|
|        work|0.007548541044789985|
| performance|0.007209008630295571|
|    superior|0.007065626808393139|
|     license|0.006436001036918034|
|    industry|0.006416712169788629|
|      record|0.006227581067732823|
+------------+--------------------+
only showing top 12 rows

But when I do .show(15) I get the error.

I created this data frame as below: it is basically a data frame of features with the their importance values from a Random Forest Model

vocab=np.array(self.cvModel.bestModel.stages[3].vocabulary)
        if est_name=="rf":
            feature_importance=self.cvModel.bestModel.stages[5].featureImportances.toArray()
            argsort_feature_indices=feature_importance.argsort()[::-1]
        elif est_name=="blr":
            feature_importance=self.cvModel.bestModel.stages[5].coefficients.toArray()
            argsort_feature_indices=abs(feature_importance).argsort()[::-1]
        # Sort the features importance array in descending order and get the indices

        feature_names=vocab[argsort_feature_indices]

        self.features_df=sc.parallelize(zip(feature_names,feature_importance[argsort_feature_indices])).\
        map(lambda x: (str(x[0]),float(x[1]))).toDF(["Feature_name","Importance_value"])


问:
Map[String,Array[Byte]] to CaseClass with Scala Shapeless
So I have a working implementation of this except I cannot get my HList in the correct order before I use LabelledGenerics to build the CaseClass Object.

What works right now is

```<code>case class Foo(a:int, b:String)
val serializedRecord("a" -> somebytes, "b" -> someotherbytes)
val caseClassObject = HBaseSerDe[Foo].deserialize(serializedRecord)
</code>```

What doesn't work is:

```<code>case class Foo(a:int, b:String)
val serializedRecord(x -> value1 ,"a" -> somebytes, "b" -> someotherbytes, z -> value2)
//expected Foo(somebytes, someotherbytes)
val caseClassObject = HBaseSerDe[Foo].deserialize(serializedRecord)
</code>```

From what I have read I am supposed to use Align and Intersect to get my Hlist sorted out before deserializing but in all examples i could find they use something like the following (taken from github.com/underscoreio/shapeless-guide)

```<code>implicit def genericMigration[
    A, B,
    ARepr <: HList, BRepr <: HList,
    Unaligned <: HList
](
    implicit
    aGen : LabelledGeneric.Aux[A, ARepr],
    bGen : LabelledGeneric.Aux[B, BRepr],
    inter : hlist.Intersection.Aux[ARepr, BRepr, Unaligned],
    align : hlist.Align[Unaligned, BRepr]
): Migration[A, B] = new Migration[A, B] {
    def apply(a: A): B =
        bGen.from(align.apply(inter.apply(aGen.to(a))))
}
</code>```

However I do not have a CaseClass A and i couldn't figure out how to build its representation on the fly. Below you can find the current code:

```<code> implicit val hNilEncoder = instance[HNil](
    r => Map(),
    l => HNil
  )

  implicit def hListSerDe[
      Key <: Symbol,
      H,
      T <: HList
    ](
     implicit
     key: Witness.Aux[Key],
     headSerDe: HBaseFieldShapelessSerDe[H],
     tailSerDe: HBaseRecordShapelessSerDe[T]
     ): HBaseRecordShapelessSerDe[FieldType[Key, H] :: T] =
    instance[FieldType[Key, H] :: T](
      hList => {
        Map(key.value.name -> headSerDe.serialize(hList.head)) ++ tailSerDe.serialize(hList.tail)
      },
      byteList => {
        field[Key](headSerDe.deSerialize(byteList.head._2)) :: tailSerDe.deSerialize(byteList.tail)
      }
    )

  implicit def caseClassSerDe[
      TargetType,
      L <: HList
  ](
    implicit
    genRepr: LabelledGeneric.Aux[TargetType, L],
    hListSerDe: HBaseRecordShapelessSerDe[L]
    ): HBaseRecordShapelessSerDe[TargetType] =
    instance[TargetType](
      hList => {
        hListSerDe.serialize(genRepr.to(hList))
      },
      byteList => {

        genRepr.from(hListSerDe.deSerialize(byteList))
      }
    )

  def apply[RecordSerDeType](implicit serde: HBaseRecordShapelessSerDe[RecordSerDeType]): HBaseRecordShapelessSerDe[RecordSerDeType] = serde

  def instance[RecordSerDeType](serializeFunc: RecordSerDeType => Map[String, Array[Byte]], deserializeFunc: Map[String, Array[Byte]] => RecordSerDeType): HBaseRecordShapelessSerDe[RecordSerDeType] = {
    new HBaseRecordShapelessSerDe[RecordSerDeType] {
      override def serialize(value: RecordSerDeType): Map[String, Array[Byte]] = serializeFunc(value)

      override def deSerialize(value: Map[String, Array[Byte]]): RecordSerDeType = deserializeFunc(value)
    }
  }
</code>```

答:
I solved it by now and here's the solution for posterity. In hindsight it was pretty simple.</p>

```<code>import shapeless.labelled.FieldType
import shapeless.{::, Generic, HList, HNil, LabelledGeneric, Witness}
import shapeless.labelled.{FieldType, _}

object MapToCaseClass {

  sealed trait RecordConverter[V, TargetType] {
    def convert(rawRecord: Map[String,V]):TargetType
  }

  implicit def hNilConverter[V]:RecordConverter[V, HNil] = instance[V,HNil](
    _ => HNil
  )

  implicit def hListConverter[V, H, T <: HList, K <: Symbol](implicit fieldConverter: FieldConverter[V, H], tailConverter:RecordConverter[V, T], key: Witness.Aux[K]):RecordConverter[V, FieldType[K, H] :: T] =
    instance[V, FieldType[K, H] :: T](
      fieldMap => {
        val currentKeyName = key.value.name
        val value = fieldMap(currentKeyName)
        val mapRest = fieldMap.filterKeys(_!=currentKeyName)
        //TODO: Add a way for default value providing, Option handling and nested HLists for in case no value was found
        field[K](fieldConverter.convert(value)) :: tailConverter.convert(mapRest)
      }
    )

  implicit def caseClassConverter[V, C, CRepr <: HList](implicit caseClassGenRepr: LabelledGeneric.Aux[C,CRepr], recordConverter:RecordConverter[V, CRepr]):RecordConverter[V, C] =
    instance[V, C](
      fieldMap => {
        caseClassGenRepr.from(recordConverter.convert(fieldMap))
      }
    )

  private[this] def instance[V, T](func: Map[String,V] => T) : RecordConverter[V, T] = new RecordConverter[V, T] {
    override def convert(rawRecord: Map[String, V]): T = func(rawRecord)
  }

  //summoner
  def apply[V, T](implicit recordConverter: RecordConverter[V, T]):RecordConverter[V, T] = recordConverter

}
</code>```

Body:
So I have a working implementation of this except I cannot get my HList in the correct order before I use LabelledGenerics to build the CaseClass Object.

What works right now is

case class Foo(a:int, b:String)
val serializedRecord("a" -> somebytes, "b" -> someotherbytes)
val caseClassObject = HBaseSerDe[Foo].deserialize(serializedRecord)

What doesn't work is:

case class Foo(a:int, b:String)
val serializedRecord(x -> value1 ,"a" -> somebytes, "b" -> someotherbytes, z -> value2)
//expected Foo(somebytes, someotherbytes)
val caseClassObject = HBaseSerDe[Foo].deserialize(serializedRecord)

From what I have read I am supposed to use Align and Intersect to get my Hlist sorted out before deserializing but in all examples i could find they use something like the following (taken from github.com/underscoreio/shapeless-guide)

implicit def genericMigration[
    A, B,
    ARepr <: HList, BRepr <: HList,
    Unaligned <: HList
](
    implicit
    aGen : LabelledGeneric.Aux[A, ARepr],
    bGen : LabelledGeneric.Aux[B, BRepr],
    inter : hlist.Intersection.Aux[ARepr, BRepr, Unaligned],
    align : hlist.Align[Unaligned, BRepr]
): Migration[A, B] = new Migration[A, B] {
    def apply(a: A): B =
        bGen.from(align.apply(inter.apply(aGen.to(a))))
}

However I do not have a CaseClass A and i couldn't figure out how to build its representation on the fly. Below you can find the current code:

 implicit val hNilEncoder = instance[HNil](
    r => Map(),
    l => HNil
  )

  implicit def hListSerDe[
      Key <: Symbol,
      H,
      T <: HList
    ](
     implicit
     key: Witness.Aux[Key],
     headSerDe: HBaseFieldShapelessSerDe[H],
     tailSerDe: HBaseRecordShapelessSerDe[T]
     ): HBaseRecordShapelessSerDe[FieldType[Key, H] :: T] =
    instance[FieldType[Key, H] :: T](
      hList => {
        Map(key.value.name -> headSerDe.serialize(hList.head)) ++ tailSerDe.serialize(hList.tail)
      },
      byteList => {
        field[Key](headSerDe.deSerialize(byteList.head._2)) :: tailSerDe.deSerialize(byteList.tail)
      }
    )

  implicit def caseClassSerDe[
      TargetType,
      L <: HList
  ](
    implicit
    genRepr: LabelledGeneric.Aux[TargetType, L],
    hListSerDe: HBaseRecordShapelessSerDe[L]
    ): HBaseRecordShapelessSerDe[TargetType] =
    instance[TargetType](
      hList => {
        hListSerDe.serialize(genRepr.to(hList))
      },
      byteList => {

        genRepr.from(hListSerDe.deSerialize(byteList))
      }
    )

  def apply[RecordSerDeType](implicit serde: HBaseRecordShapelessSerDe[RecordSerDeType]): HBaseRecordShapelessSerDe[RecordSerDeType] = serde

  def instance[RecordSerDeType](serializeFunc: RecordSerDeType => Map[String, Array[Byte]], deserializeFunc: Map[String, Array[Byte]] => RecordSerDeType): HBaseRecordShapelessSerDe[RecordSerDeType] = {
    new HBaseRecordShapelessSerDe[RecordSerDeType] {
      override def serialize(value: RecordSerDeType): Map[String, Array[Byte]] = serializeFunc(value)

      override def deSerialize(value: Map[String, Array[Byte]]): RecordSerDeType = deserializeFunc(value)
    }
  }

Body:
I solved it by now and here's the solution for posterity. In hindsight it was pretty simple.

import shapeless.labelled.FieldType
import shapeless.{::, Generic, HList, HNil, LabelledGeneric, Witness}
import shapeless.labelled.{FieldType, _}

object MapToCaseClass {

  sealed trait RecordConverter[V, TargetType] {
    def convert(rawRecord: Map[String,V]):TargetType
  }

  implicit def hNilConverter[V]:RecordConverter[V, HNil] = instance[V,HNil](
    _ => HNil
  )

  implicit def hListConverter[V, H, T <: HList, K <: Symbol](implicit fieldConverter: FieldConverter[V, H], tailConverter:RecordConverter[V, T], key: Witness.Aux[K]):RecordConverter[V, FieldType[K, H] :: T] =
    instance[V, FieldType[K, H] :: T](
      fieldMap => {
        val currentKeyName = key.value.name
        val value = fieldMap(currentKeyName)
        val mapRest = fieldMap.filterKeys(_!=currentKeyName)
        //TODO: Add a way for default value providing, Option handling and nested HLists for in case no value was found
        field[K](fieldConverter.convert(value)) :: tailConverter.convert(mapRest)
      }
    )

  implicit def caseClassConverter[V, C, CRepr <: HList](implicit caseClassGenRepr: LabelledGeneric.Aux[C,CRepr], recordConverter:RecordConverter[V, CRepr]):RecordConverter[V, C] =
    instance[V, C](
      fieldMap => {
        caseClassGenRepr.from(recordConverter.convert(fieldMap))
      }
    )

  private[this] def instance[V, T](func: Map[String,V] => T) : RecordConverter[V, T] = new RecordConverter[V, T] {
    override def convert(rawRecord: Map[String, V]): T = func(rawRecord)
  }

  //summoner
  def apply[V, T](implicit recordConverter: RecordConverter[V, T]):RecordConverter[V, T] = recordConverter

}


问:
How to make rvalue method correctly call move constructor
I have base class with copy and move constructors like this:

```<code>class Test {
 public:
    Test( int i ) {
        iptr = new int( i );
    }
    Test( const Test & other ) {
        printf("copy constructor\n");
        iptr = new int( *other.iptr );
    }
    Test( Test && other ) {
        printf("move constructor\n");
        iptr = other.iptr;
        other.iptr = NULL;
    }
    virtual ~Test() {
        delete iptr;
    }
    virtual Test * copy() {
        return new Test( *this );
    }
    virtual Test * move() && {
        return new Test( *this );
    }
 protected:
    int * iptr;
};
</code>```

I added a copy and move methods to allow polymorphic copying and moving the object from a pointer, that can potentialy point to an instance of some subclass.

However when i write the following

```<code>Test t1( 5 );
Test * t2 = t1.copy();
Test * t3 = Test( 6 ).move();
</code>```

first case correctly calls copy constructor, but second case incorrectly calls copy constructor too.

Why does the constructor overloading not work properly and how do i make it to call the move constructor?

答:
In the same way any rvalue reference parameter is an lvalue inside a function, the object for which an rvalue ref qualified member function is called is an lvalue within that member function.

```<code>void foo(Test&& x)
{
    /* here x is an lvalue ! */
    Test y(std::move(x)); // need explicit cast to actually move
}
</code>```

Thus you need:

```<code>virtual Test * move() && {
    return new Test( std::move(*this) );
}
</code>```

(Don't forget #include <utility>.)

The reason why *this is an lvalue is because pointer indirection always produces an lvalue where this is always a T* (or T cv *) within a member function of a type T. While the member function cv qualification affects the this pointer, the ref qualification of the function does not. (There is no "pointer to rvalue" or "pointer to lvalue" but only "pointer to const" or "pointer to volatile" etc.)

Rvalue Reference is Treated as an Lvalue?

Rvalue reference: Why aren't rvalues implicitly moved?

C++ move constructor not called for rvalue reference

What is "rvalue reference for *this"?

Body:
I have base class with copy and move constructors like this:

class Test {
 public:
    Test( int i ) {
        iptr = new int( i );
    }
    Test( const Test & other ) {
        printf("copy constructor\n");
        iptr = new int( *other.iptr );
    }
    Test( Test && other ) {
        printf("move constructor\n");
        iptr = other.iptr;
        other.iptr = NULL;
    }
    virtual ~Test() {
        delete iptr;
    }
    virtual Test * copy() {
        return new Test( *this );
    }
    virtual Test * move() && {
        return new Test( *this );
    }
 protected:
    int * iptr;
};

I added a copy and move methods to allow polymorphic copying and moving the object from a pointer, that can potentialy point to an instance of some subclass.

However when i write the following

Test t1( 5 );
Test * t2 = t1.copy();
Test * t3 = Test( 6 ).move();

first case correctly calls copy constructor, but second case incorrectly calls copy constructor too.

Why does the constructor overloading not work properly and how do i make it to call the move constructor?

Body:
In the same way any rvalue reference parameter is an lvalue inside a function, the object for which an rvalue ref qualified member function is called is an lvalue within that member function.

void foo(Test&& x)
{
    /* here x is an lvalue ! */
    Test y(std::move(x)); // need explicit cast to actually move
}

Thus you need:

virtual Test * move() && {
    return new Test( std::move(*this) );
}

(Don't forget #include <utility>.)

The reason why *this is an lvalue is because pointer indirection always produces an lvalue where this is always a T* (or T cv *) within a member function of a type T. While the member function cv qualification affects the this pointer, the ref qualification of the function does not. (There is no "pointer to rvalue" or "pointer to lvalue" but only "pointer to const" or "pointer to volatile" etc.)

Rvalue Reference is Treated as an Lvalue?

Rvalue reference: Why aren't rvalues implicitly moved?

C++ move constructor not called for rvalue reference

What is "rvalue reference for *this"?


问:
Learn C# on mac?
Is mono the only route , any specific visual studio like editors that you recommend?</p>

答: I would go the virtualization route, either Parallels or VMware Fusion. Both will run Windows XP and Visual Studio very well on a modern Mac. Windows has the best tools for .NET and C# development and it only makes to use them, especially when you're just starting out.</p>

Title: Learn C# on mac?

OwnerDisplayName: Marc Charbonneau


问:
2 foreach loops tripling submitted data
I have 3 hidden fields and 3 text fields. I need to loop through both to UPDATE database records. If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date. So instead of looking like this:

1 - 2017-04-05

2 - 2017-04-06

3 - 2017-04-07

It looks like this:

1 - 2017-04-05

2 - 2017-04-05

3 - 2017-04-05

1 - 2017-04-06

2 - 2017-04-06

3 - 2017-04-06

1 - 2017-04-07

2 - 2017-04-07

3 - 2017-04-07

```<code>        foreach($_POST['commit_date'] as $commitdate) {
            foreach($_POST['unit'] as $units) {

                echo $units .= $commitdate . "<br/>";

            }
        }
</code>```

答:
Assuming you are posting unit and commit_date with size 3

```<code>   foreach($_POST['commit_date'] as $commitdate) { \\ this will iterate 3
        foreach($_POST['unit'] as $units) { \\ this will iterate 9 times

            echo $units .= $commitdate . "<br/>";

        }
    }
</code>```

You will see output as below:

```<code>**First Iteration**
1 - 2017-04-05
2 - 2017-04-05
3 - 2017-04-05

**Second Iteration**
1 - 2017-04-06
2 - 2017-04-06
3 - 2017-04-06

**Third Iteration**
1 - 2017-04-07
2 - 2017-04-07
3 - 2017-04-07
</code>```

Title: 2 foreach loops tripling submitted data

Body:
I have 3 hidden fields and 3 text fields. I need to loop through both to UPDATE database records. If I use the foreach loops separately, it posts 3 values correctly. If I try use them together it seems to triple the text input value which is a date. So instead of looking like this:

1 - 2017-04-05

2 - 2017-04-06

3 - 2017-04-07

It looks like this:

1 - 2017-04-05

2 - 2017-04-05

3 - 2017-04-05

1 - 2017-04-06

2 - 2017-04-06

3 - 2017-04-06

1 - 2017-04-07

2 - 2017-04-07

3 - 2017-04-07

        foreach($_POST['commit_date'] as $commitdate) {
            foreach($_POST['unit'] as $units) {

                echo $units .= $commitdate . "
";

            }
        }

Body:
Assuming you are posting unit and commit_date with size 3

   foreach($_POST['commit_date'] as $commitdate) { \\ this will iterate 3
        foreach($_POST['unit'] as $units) { \\ this will iterate 9 times

            echo $units .= $commitdate . "<br/>";

        }
    }

You will see output as below:

**First Iteration**
1 - 2017-04-05
2 - 2017-04-05
3 - 2017-04-05

**Second Iteration**
1 - 2017-04-06
2 - 2017-04-06
3 - 2017-04-06

**Third Iteration**
1 - 2017-04-07
2 - 2017-04-07
3 - 2017-04-07


问:
How many map and reduce task for hive partition and bucketed table
I have a partitioned table(on col1)  in hive which is also bucketed(on col2 in 16 buckets), now if i want to run a select query how many mapper and reducers task will be spawned? </p>

答:
For every input split of the input table one mapper will be dispatched, where the default size of the input split will the block size.

You could alter the number of mappers by modifying the mapreduce.input.fileinputformat.split.maxsize and mapreduce.input.fileinputformat.split.minsize properties.

Speaking about the number of reducers in Hive, by default it is calculated using the hive.exec.reducers.bytes.per.reducer property where its default value is 1GB.

You will be able to configure the number of reducers by modifying the above property. Still you may also set the constant number of reducers for a job by using the mapred.reduce.tasks property.

You can find more details on the following links

How hadoop decides how many nodes will do map and reduce tasks


问:
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"
I'm trying to run the following statement but am receiving the error messages just below.  I have researched answers to no end and none have worked for me.  I'm running Office 365 (64bit).  I have loaded the Microsoft Access Database Engine (64bit).  This is in Visual Studio 2013 with SSDT as well as SQL Server 2012.  I do not have access to changing environment or startup parameters to SQL Server.  Any help is appreciated.

```<code>SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0',
    'Excel 12.0;Database=C:\Users\UserName\Folder\SomeFile.xlsx;;HDR=NO;IMEX=1', [Table 1$])
</code>```

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider
"Microsoft.ACE.OLEDB.15.0" for linked server "(null)" reported an
error. The provider did not give any information about the error.

Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source
object of OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked
server "(null)".

Here's what I have tried:

First, I ran...

```<code>sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
</code>```

Followed by...with no love.

```<code>EXEC sys.sp_addsrvrolemember @loginame = N'<<Domain\User>>', @rolename = N'sysadmin';
GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.15.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.15.0', N'DynamicParameters', 1
GO
</code>```

I have changed the code to read Microsoft.ACE.OLEDB.12.0 as I have seen that as well, still no love.

I have also checked permissions of C:\Users\MSSQLSERVER\AppData\Local\Temp and C:Windows\ServiceProfiles\NetworkService\AppData\Local which have granted Full Control for the following: System, MSSQLSERVER, and Administrators, Network Service (on the latter).

Still no love.

Lastly, I have tried changing to the 32bit version of the Microsoft Access Database Engine which has persisted in not working.

Help, anyone?

答:
I had the exact same error message, and tried the suggested solutions in this thread but without success.

what solved the problem for me is opening the .xlsx file and saving it as .xls (excel 2003) file.

maybe the file was corrupted or in a different format, and saving it again fixed it.

Body:
I'm trying to run the following statement but am receiving the error messages just below.  I have researched answers to no end and none have worked for me.  I'm running Office 365 (64bit).  I have loaded the Microsoft Access Database Engine (64bit).  This is in Visual Studio 2013 with SSDT as well as SQL Server 2012.  I do not have access to changing environment or startup parameters to SQL Server.  Any help is appreciated.

SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0',
    'Excel 12.0;Database=C:\Users\UserName\Folder\SomeFile.xlsx;;HDR=NO;IMEX=1', [Table 1$])

Msg 7399, Level 16, State 1, Line 1 The OLE DB provider
"Microsoft.ACE.OLEDB.15.0" for linked server "(null)" reported an
error. The provider did not give any information about the error.

Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source
object of OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked
server "(null)".

Here's what I have tried:

First, I ran...

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

Followed by...with no love.

EXEC sys.sp_addsrvrolemember @loginame = N'<<Domain\User>>', @rolename = N'sysadmin';
GO

EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.15.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.15.0', N'DynamicParameters', 1
GO

I have changed the code to read Microsoft.ACE.OLEDB.12.0 as I have seen that as well, still no love.

I have also checked permissions of C:\Users\MSSQLSERVER\AppData\Local\Temp and C:Windows\ServiceProfiles\NetworkService\AppData\Local which have granted Full Control for the following: System, MSSQLSERVER, and Administrators, Network Service (on the latter).

Still no love.

Lastly, I have tried changing to the 32bit version of the Microsoft Access Database Engine which has persisted in not working.

Help, anyone?


问:
feathers.js -> Authentication token missing
I have a feathters.js application and now I want to secure the create and update hooks. I use a socket.io client and currently am going for JWT. I have added what I think I needed to add but am getting Error: Authentication token missing and Error Authenticating. The later I understand for that is from my code. I have a backend / frontend situation

So this is what I've implemented so far.

File: backend\backend.js (called in backend\index.js for the configuration of the app)

```<code>'use strict';

const path = require('path');
const serveStatic = require('feathers').static;
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const feathers = require('feathers');
const configuration = require('feathers-configuration');
const authentication = require('feathers-authentication');
const hooks = require('feathers-hooks');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const socketio = require('feathers-socketio');
const middleware = require('./middleware/index');
const services = require('./services/index');

const appFeathers = feathers();

appFeathers.configure(configuration(path.join(__dirname, '..')));

appFeathers.use(compress())
    .options('*', cors())
    .use(cors())
    .use(favicon(path.join(appFeathers.get('public'), 'favicon.ico')))
    .use('/', serveStatic(appFeathers.get('public')))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .configure(hooks())
    .configure(rest())
    .configure(socketio())
    .configure(services)
    .configure(middleware)
    .configure(authentication());

module.exports = appFeathers;
</code>```

File: backend\config\default.json

```<code>{
    "host": "localhost",
    "port": 3001,
    "mysql_connection": "mysql://CONNECTION_STRING",
    "public": "../public/",
    "auth": {
        "idField": "id",
        "token": {
            "secret": "SECRET_KEY"
        },
        "local": {}
    }
}
</code>```

In a working component of the frontend:

```<code><template>
    <div class="vttIndex">
        idnex.vue
        todo: eagle.js slideshow
        todo: first info
        <ul>
            <li v-for="message in listMessages">
                {{ message }}
            </li>
        </ul>
    </div>
</template>

<script>
    import feathers from 'feathers/client';
    import socketio from 'feathers-socketio/client';
    import hooks from 'feathers-hooks';
    import io from 'socket.io-client';
    import authentication from 'feathers-authentication/client';
    import * as process from "../nuxt.config";

    const vttSocket = io(process.env.backendUrl);
    const vttFeathers = feathers()
        .configure(socketio(vttSocket))
        .configure(hooks())
        .configure(authentication());

    const serviceMessage = vttFeathers.service('messages');

vttFeathers.authenticate({
    type: 'token',
    'token ': 'SECRET_KEY'
}).then(function(result){
    console.log('Authenticated!', result);
}).catch(function(error){
    console.error('Error authenticating!', error);
});

    export default {
        layout: 'default',
        data: function() {
            return {
                listMessages: []
            }
        },
        mounted: function() {
            serviceMessage.find().then(page => {
                this.listMessages = page.data;
            });
            serviceMessage.on('created', (serviceMessage) => {
                this.listMessages.push(serviceMessage);
            });
        }
    }
</script>
</code>```

As token, I have the secret key of the backend json file. As you see, now I only try to log console messages. It is doing something for my error message is coming from there.

Question

Where am I missing what to have this functioning?

Goal

Just in case it's needed. My goal is for all 'public' data to be select with a token in my client and then an admin section maybe with 0auth. So the general 'SELECT' stuff is secured through a token instead of no authentication at all.

Solution

Okay I solved it, sort of. I first needed to create a user. Then I needed to do a local login with the user. That returns a token. If I use that, then there is no problem at all.

答: To use a token, you must first make sure it is generated. I was using the secret key as token what isn't correct. When you first athenticate with the 'local' type (default email and password) it will create a token and that is what you could then use with the method 'token'</p>

Body:
I have a feathters.js application and now I want to secure the create and update hooks. I use a socket.io client and currently am going for JWT. I have added what I think I needed to add but am getting Error: Authentication token missing and Error Authenticating. The later I understand for that is from my code. I have a backend / frontend situation

So this is what I've implemented so far.

File: backend\backend.js (called in backend\index.js for the configuration of the app)

'use strict';

const path = require('path');
const serveStatic = require('feathers').static;
const favicon = require('serve-favicon');
const compress = require('compression');
const cors = require('cors');
const feathers = require('feathers');
const configuration = require('feathers-configuration');
const authentication = require('feathers-authentication');
const hooks = require('feathers-hooks');
const rest = require('feathers-rest');
const bodyParser = require('body-parser');
const socketio = require('feathers-socketio');
const middleware = require('./middleware/index');
const services = require('./services/index');

const appFeathers = feathers();

appFeathers.configure(configuration(path.join(__dirname, '..')));

appFeathers.use(compress())
    .options('*', cors())
    .use(cors())
    .use(favicon(path.join(appFeathers.get('public'), 'favicon.ico')))
    .use('/', serveStatic(appFeathers.get('public')))
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .configure(hooks())
    .configure(rest())
    .configure(socketio())
    .configure(services)
    .configure(middleware)
    .configure(authentication());

module.exports = appFeathers;

File: backend\config\default.json

{
    "host": "localhost",
    "port": 3001,
    "mysql_connection": "mysql://CONNECTION_STRING",
    "public": "../public/",
    "auth": {
        "idField": "id",
        "token": {
            "secret": "SECRET_KEY"
        },
        "local": {}
    }
}

In a working component of the frontend:

<template>

        idnex.vue
        todo: eagle.js slideshow
        todo: first info

                {{ message }}

</template>

As token, I have the secret key of the backend json file. As you see, now I only try to log console messages. It is doing something for my error message is coming from there.

Question

Where am I missing what to have this functioning?

Goal

Just in case it's needed. My goal is for all 'public' data to be select with a token in my client and then an admin section maybe with 0auth. So the general 'SELECT' stuff is secured through a token instead of no authentication at all.

Solution

Okay I solved it, sort of. I first needed to create a user. Then I needed to do a local login with the user. That returns a token. If I use that, then there is no problem at all.


问:
sqlite select minimum function value of grouped result
I have a table with gps locations of restaurants chains and would like to return the addresses of the restaurants closest to point (A) within a certain radius

```<code>SELECT *
    , MIN(distance($lat, $lon, lat, lon)) as miles
FROM all_restaurants
WHERE lat between $lat1 and $lat2
    AND lon between $lon1 and $lon2
    AND miles < $miles
GROUP BY restaurant_id
ORDER BY miles ASC
    , company_name ASC
LIMIT 500
</code>```

returns error

misuse of aggregate: MIN()

答:
I bet that you're calling a function which is distance($lat, $lon, lat, lon), don't you?

Have you tried using a simple subtraction between $lat and lat and have it return the minimum value using the MIN function?

MIN's purpose is for use with a table field or some basic operation such as a subtraction, I guess. This might be the cause of the encountered error.

Up and foremost, avoid using * while using aggregation functions, list the columns you require in your query.

Perhaps providing us with sample data might help us find a way around to work you through.

Body:
I have a table with gps locations of restaurants chains and would like to return the addresses of the restaurants closest to point (A) within a certain radius

SELECT *
    , MIN(distance($lat, $lon, lat, lon)) as miles
FROM all_restaurants
WHERE lat between $lat1 and $lat2
    AND lon between $lon1 and $lon2
    AND miles < $miles
GROUP BY restaurant_id
ORDER BY miles ASC
    , company_name ASC
LIMIT 500

returns error

misuse of aggregate: MIN()


问:
What's wrong with this foreach?
I'm trying to make a function which will use a foreach to determine whether the string supplied to it contains any words from an array. I've tried debugging by putting echo "iteration...
"; after the foreach so I can see how many times it loops, and it doesn't seem to ever begin looping, so I'm assuming there's a problem with the way I've setup my foreach or maybe my array. Any ideas? Thanks.

```<code>$badwords = array("example", "word");

function containsBad($st) {
    $isbad = false;
    foreach($badwords as $word) {
        echo "iteration...<br>";
        if (strpos($st, $word)) {
            $isbad = true;
        }
    }
    return $isbad ? 'true' : 'false';
}

echo containsBad("example");
</code>```

答:
You must define $badwords variable as global inside the function before you use it:

```<code>global $badwords;
</code>```

But there is another improvements in your program:

your program can't determine if bad word begins at the beginning of your string.

Using of boolean variable $isbad

$badwords = array("example", "word");

```<code>function containsBad($st)
  {
  global $badwords;
  $isbad = false;
  foreach($badwords as $word)
    {
    echo "iteration...<br>";
    if (strpos($st, $word)!==false)
      $isbad = true;
    }
    return $isbad;
  }
</code>```

Title: What's wrong with this foreach?

Body:
I'm trying to make a function which will use a foreach to determine whether the string supplied to it contains any words from an array. I've tried debugging by putting echo "iteration...
"; after the foreach so I can see how many times it loops, and it doesn't seem to ever begin looping, so I'm assuming there's a problem with the way I've setup my foreach or maybe my array. Any ideas? Thanks.

$badwords = array("example", "word");

function containsBad($st) {
    $isbad = false;
    foreach($badwords as $word) {
        echo "iteration...
";
        if (strpos($st, $word)) {
            $isbad = true;
        }
    }
    return $isbad ? 'true' : 'false';
}

echo containsBad("example");

Body:
You must define $badwords variable as global inside the function before you use it:

global $badwords;

But there is another improvements in your program:

your program can't determine if bad word begins at the beginning of your string.

Using of boolean variable $isbad

$badwords = array("example", "word");

function containsBad($st)
  {
  global $badwords;
  $isbad = false;
  foreach($badwords as $word)
    {
    echo "iteration...<br>";
    if (strpos($st, $word)!==false)
      $isbad = true;
    }
    return $isbad;
  }


问:
Getting error while installing phpmyadmin in ubuntu 14.04
Getting error when installing phpmyadmin in ubuntu 14.04

I ran below 2 commands for installing it.

```<code>sudo apt-get update
sudo apt-get install phpmyadmin
</code>```

During installation I selected apache and gave administrators password and phpmyadmin password then got the following error.

答:
It seems like phpmyadmin tries to auto-configure connection to local mysql-server during the installation. But one of the steps of installation asks if you want to configure database immediately or to do it later manually (see attached screen).

So, if you'd like to use local mysql-server, you need to install it first, but if you want to configure connection to some remote mysql-server, skip automatic configuration and do it later manually.

Body:
Getting error when installing phpmyadmin in ubuntu 14.04

I ran below 2 commands for installing it.

sudo apt-get update
sudo apt-get install phpmyadmin

During installation I selected apache and gave administrators password and phpmyadmin password then got the following error.


问:
Example of multi-section Google Form built using Apps Script?
[Updated to narrow the focus] I can't get a multi-section form built using GAS to build.

Sections are delineated using form.addPageBreakItem, but if you then put in a widget that alters the flow of the sections (such as .addMultipleChoiceItem), it won't build because the section you're navigating to hasn't been defined yet.

Using the .setGoToPage() function has the same issues.

How are these functions supposed to be used to control the flow?

答:
Finally figured it out.  Here's a demo, which is a form to collect tennis match results. (The matches allowed can be short-sets i.e. 5 games)

/*
 * makeMultiForm - Build a multi-sections to collect Singles or Doubles results
 */
function makeMultiForm() {
  var form = FormApp.create('Match Results Entry')
                    .setConfirmationMessage('Thank you! Your results have been recorded');
  form.setTitle("Demo Tennis Results Form");

  // Start by laying out the bare-bones structure.  This defines the different
  // sections, and the bare widgets in each section.
  // Note that you can't add any flow-routing details at this point, because
  // the destinations most likely haven't been defined yet
  var itemCompetition = form.addMultipleChoiceItem().setTitle("Which Competition");
  var itemMatchDate = form.addDateItem().setTitle("Match Date");

  var sectSingles = form.addPageBreakItem().setTitle("Singles Competition");
  var itemPlay1 = form.addListItem().setTitle("Player 1");
  var itemPlay2 = form.addListItem().setTitle("Player 2");
  var itemMatchFormat = form.addMultipleChoiceItem().setTitle("Match Format");

  var sectDoubles = form.addPageBreakItem().setTitle("Doubles Competition");
  var itemTeam1Player1 = form.addListItem().setTitle("Team 1: Player 1");
  var itemTeam1Player2 = form.addListItem().setTitle("Team 1: Player 2");
  var itemTeam2Player1 = form.addListItem().setTitle("Team 2: Player 1");
  var itemTeam2Player2 = form.addListItem().setTitle("Team 2: Player 2");
  var itemMatchFormat2 = form.addMultipleChoiceItem().setTitle("Match Format");

  var sectOneSet = form.addPageBreakItem().setTitle("5-Games / One Set");
  var itemSet1 = form.addGridItem().setTitle("Score for first set");

  var sectTwoSets = form.addPageBreakItem().setTitle("Two Sets");
  var item2SetsSet1 = form.addGridItem().setTitle("Score for first set");
  var item2SetsSet2 = form.addGridItem().setTitle("Score for second set");

  // Having defined the bare bones, this adds a jump to the end (submitting
  // the form). Look carefully which section this is - it's not intuitive!
  // The jump is actually defined for section "sectTwoSets", but the
  // jump is actioned at the end of the section before this one
  sectTwoSets.setGoToPage(FormApp.PageNavigationType.SUBMIT);

  // Now flesh out the contents of the various widgets.  Routing info for
  // the .createChoice methods can now be defined, because all the
  // variables defining sections have aleady been defined
  itemCompetition.setChoices([
      itemCompetition.createChoice("Singles", sectSingles),
      itemCompetition.createChoice("Doubles", sectDoubles)]);
  itemMatchDate.setRequired(false);

  var players = ["Jack", "Gill", "Jim", "Sally"];
  itemPlay1.setChoiceValues(players);
  itemPlay2.setChoiceValues(players);
  itemMatchFormat.setChoices([
      itemMatchFormat.createChoice("5 Games", sectOneSet),
      itemMatchFormat.createChoice("One Set", sectOneSet),
      itemMatchFormat.createChoice("Two Sets", sectTwoSets)]);

  itemTeam1Player1.setChoiceValues(players);
  itemTeam1Player2.setChoiceValues(players);
  itemTeam2Player1.setChoiceValues(players);
  itemTeam2Player2.setChoiceValues(players);
  itemMatchFormat2.setChoices([
      itemMatchFormat2.createChoice("5 Games", sectOneSet),
      itemMatchFormat2.createChoice("One Set", sectOneSet),
      itemMatchFormat2.createChoice("Two Sets", sectTwoSets)]);

  itemSet1.setRows(["Player 1", "Player 2"])
          .setColumns(["0", "1", "2", "3", "4", "5", "6", "7"]);

  item2SetsSet1.setRows(["Team 1", "Team 2"])
          .setColumns(["0", "1", "2", "3", "4", "5", "6", "7"]);
  item2SetsSet2.setRows(["Team 1", "Team 2"])
          .setColumns(["0", "1", "2", "3", "4", "5", "6", "7"]);
}```


问:
should I use junction table or not?
I'm developing a site using asp.net mvc5 and I'm working with a dba who has  a long experience in the field .
we had a conflict about the following relation between the following tables.

```<code>Award table
-ID
-.. the table fields
-supplierID
-employeeID
-otherID

Supplier
-ID
-.. the table fields

employee table
-ID
-.. the table fields

other table
-ID
-.. the table fields
</code>```

the last three rows in the awards table are the types of beneficiaries of the award. and u can't have multiple beneficiaries.

so my suggestion was to use linking table "beneficiary" to link between the different "beneficiaries" and "awards" table.

what u think ?

答:
You have a "one-of" relationship.  This is tricky in SQL and the method of using three columns is a good way of doing it.  Why?  It allows proper foreign key declarations.

I would look for a table definition such as this:

```<code>create table Awards (
    awardsId int identity primary key,
    . . .
    supplierId int,
    employeeID int,
    otherID int,
    beneficiaryType as (case when supplierId is not null then 'S'
                             when employeeId is not null then 'E'
                             when otherId is not null then 'O'
                        end),
    constraint chk_beneficiary
        check ( (supplierId is not null and employeeId is null and otherid is null) or
                (supplierId is null and employeeId is not null and otherid is null) or
                (supplierId is null and employeeId is null and otherid is not null)
             ),
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);
</code>```

If it is really unusual that another type of beneficiary is added, then database maintenance is not a big problem.

I should note that you can also do the above with "generic" columns and persisted computed columns:

```<code>create table Awards (
    awardsId int identity primary key,
    . . .
    beneficiaryType char(1) not null,
    beneficiaryId int not null,
    constraint chk_awards_beneficiaryType check (beneficiaryType in ('E', 'S', 'O')),
    supplierId as (case when beneficiaryType = 'S' then beneficiaryId end) persisted,
    employeeID as (case when beneficiaryType = 'E' then beneficiaryId end) persisted,
    otherID as (case when beneficiaryType = 'O' then beneficiaryId end) persisted,
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);
</code>```

Because the computed columns have to be persisted in order to be used as foreign keys, this does not save space.  However, adding a new type is a matter of just doing:

Changing the check constraint for beneficiaryType

Adding a new computed column

Adding a new foreign key constraint

This does require that all ids to all tables have the same type.  However, I (almost) always use identity columns as primary keys, so this is true automatically in any database I design.

Title: should I use junction table or not?

Body:
I'm developing a site using asp.net mvc5 and I'm working with a dba who has  a long experience in the field .
we had a conflict about the following relation between the following tables.

Award table
-ID
-.. the table fields
-supplierID
-employeeID
-otherID

Supplier
-ID
-.. the table fields

employee table
-ID
-.. the table fields

other table
-ID
-.. the table fields

the last three rows in the awards table are the types of beneficiaries of the award. and u can't have multiple beneficiaries.

so my suggestion was to use linking table "beneficiary" to link between the different "beneficiaries" and "awards" table.

what u think ?

Body:
You have a "one-of" relationship.  This is tricky in SQL and the method of using three columns is a good way of doing it.  Why?  It allows proper foreign key declarations.

I would look for a table definition such as this:

create table Awards (
    awardsId int identity primary key,
    . . .
    supplierId int,
    employeeID int,
    otherID int,
    beneficiaryType as (case when supplierId is not null then 'S'
                             when employeeId is not null then 'E'
                             when otherId is not null then 'O'
                        end),
    constraint chk_beneficiary
        check ( (supplierId is not null and employeeId is null and otherid is null) or
                (supplierId is null and employeeId is not null and otherid is null) or
                (supplierId is null and employeeId is null and otherid is not null)
             ),
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);

If it is really unusual that another type of beneficiary is added, then database maintenance is not a big problem.

I should note that you can also do the above with "generic" columns and persisted computed columns:

create table Awards (
    awardsId int identity primary key,
    . . .
    beneficiaryType char(1) not null,
    beneficiaryId int not null,
    constraint chk_awards_beneficiaryType check (beneficiaryType in ('E', 'S', 'O')),
    supplierId as (case when beneficiaryType = 'S' then beneficiaryId end) persisted,
    employeeID as (case when beneficiaryType = 'E' then beneficiaryId end) persisted,
    otherID as (case when beneficiaryType = 'O' then beneficiaryId end) persisted,
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);

Because the computed columns have to be persisted in order to be used as foreign keys, this does not save space.  However, adding a new type is a matter of just doing:

Changing the check constraint for beneficiaryType

Adding a new computed column

Adding a new foreign key constraint

This does require that all ids to all tables have the same type.  However, I (almost) always use identity columns as primary keys, so this is true automatically in any database I design.