问:
Unable to run import tensorflow as tf
I installed tensorflow using the following command.

```<code>pip install tensorflow
</code>```

I am running a simple program which is

```<code>import tensorflow as tf
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)
</code>```

I am getting the following error on running the program.

```<code>Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-
packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "first.py", line 1, in <module>
import tensorflow as tf
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\__init__.py", line 51, in <module>
from tensorflow.python import pywrap_tensorflow
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 52, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.
</code>```

I have updated the pip and am running the program on python 3.5

答:
I'm not exactly sure what the problem is, and probably as clueless as you about the error message, but as you are using python 3.x, shouldn't you have installed tensorflow by using:

```<code>pip3 install tensorflow
</code>```

To see if you are using pip3 type:

```<code>pip3 -V
</code>```

If you need more help, visit the official tutorial for mac or linux.

I hope this helps

dan4o

Title: Unable to run import tensorflow as tf

Body:
I installed tensorflow using the following command.

pip install tensorflow

I am running a simple program which is

import tensorflow as tf
node1 = tf.constant(3.0, tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1, node2)

I am getting the following error on running the program.

Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-
packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "first.py", line 1, in <module>
import tensorflow as tf
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
from tensorflow.python import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\__init__.py", line 51, in <module>
from tensorflow.python import pywrap_tensorflow
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 52, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 906, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 41, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "C:\Program Files (x86)\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper
return importlib.import_module('_pywrap_tensorflow_internal')
File "C:\Program Files (x86)\Python\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.

I have updated the pip and am running the program on python 3.5

Body:
I'm not exactly sure what the problem is, and probably as clueless as you about the error message, but as you are using python 3.x, shouldn't you have installed tensorflow by using:

pip3 install tensorflow

To see if you are using pip3 type:

pip3 -V

If you need more help, visit the official tutorial for mac or linux.

I hope this helps

dan4o


来源: stackexchange

问:
Redirect user to specific language url based on OS language in Cordova webview app
I have following code in my index.html in a Cordova project:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="img-src * 'self' data:; default-src * 'self' gap: wss: ws: ; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval';">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>MyBilli</title>
    </head>
    <body>
    <script type="text/javascript">
        document.addEventListener('deviceready', function() {
            var url = 'http://sub.domain.com/app/nl/login/' // change to whatever you want
            cordova.InAppBrowser.open(url, '_blank', 'location=no,zoom=no');
        }, false)
    </script>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
</html>
</code>```

The list of current Cordova plugins:

```<code>cordova-plugin-camera 2.4.1 "Camera"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-device 1.1.6 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-file-transfer 1.6.3 "File Transfer"
cordova-plugin-inappbrowser 1.7.1 "InAppBrowser"
cordova-plugin-media 3.0.1 "Media"
cordova-plugin-media-capture 1.4.3 "Capture"
cordova-plugin-network-information 1.3.3 "Network Information"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.2 "Whitelist"
</code>```

Is it possible to redirect a user based on his OS language (only 3 languages allowed: en, fr or nl) to a different url: sub.domain.com/app/[en|fr|nl]/login/

If en, fr or nl is not user's OS language, default to en

答:
Looks like you can get the devices language with https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-globalization/

You'd then just have to replace the url parts for what is picked up

ContentLicense: CC BY-SA 3.0

Body:
I have following code in my index.html in a Cordova project:

<!DOCTYPE html>

        <meta http-equiv="Content-Security-Policy" content="img-src * 'self' data:; default-src * 'self' gap: wss: ws: ; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval';">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>MyBilli</title>

The list of current Cordova plugins:

cordova-plugin-camera 2.4.1 "Camera"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-device 1.1.6 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-file-transfer 1.6.3 "File Transfer"
cordova-plugin-inappbrowser 1.7.1 "InAppBrowser"
cordova-plugin-media 3.0.1 "Media"
cordova-plugin-media-capture 1.4.3 "Capture"
cordova-plugin-network-information 1.3.3 "Network Information"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.2 "Whitelist"

Is it possible to redirect a user based on his OS language (only 3 languages allowed: en, fr or nl) to a different url: sub.domain.com/app/[en|fr|nl]/login/

If en, fr or nl is not user's OS language, default to en


问:
remove shadow below AppBarLayout widget android
When using AppBarLayout widget in design support library, a shadow appears on the bottom of the toolbar. How can I remove that shadow?

答: This is the way that I came up with app:elevation="0dp" to remove the shadow.Perfectly works.


问:
add shipping cost in paypal-express-checkout-simple
I have used paypal-express-checkout-simple. I need to add shipping charges per product and display that to paypal checkout page. Do I need to change any account setting in paypal?

I have followed https://www.npmjs.com/package/paypal-express-checkout-simple

Any help on this highly appreciated.

答:
I made changes in  lib/paypal-express-checkout.js file in my local node module files.

I have added params.PAYMENTREQUEST_0_SHIPPINGAMT which was missing in function for shipping cost.

```<code>Paypal.prototype.setExpressCheckoutPayment = function(email, invoiceNumber, amount, totalShipCost, description, currency, returnUrl, cancelUrl, onlyPayPalUsers, callback) {
    var self = this;
    var params = self.params();
    if (email) {
        params.EMAIL = email;
    }

    params.SOLUTIONTYPE = onlyPayPalUsers === true ? 'Mark' : 'Sole';
    params.PAYMENTREQUEST_0_AMT = prepareNumber(amount + totalShipCost); // ***add ship cost here
    params.PAYMENTREQUEST_0_DESC = description;
    params.PAYMENTREQUEST_0_CURRENCYCODE = currency;
    params.PAYMENTREQUEST_0_INVNUM = invoiceNumber;
    params.PAYMENTREQUEST_0_CUSTOM = invoiceNumber + '|' + params.PAYMENTREQUEST_0_AMT + '|' + currency;
    params.PAYMENTREQUEST_0_PAYMENTACTION = 'Sale';
    params.PAYMENTREQUEST_0_ITEMAMT = prepareNumber(amount);
    params.PAYMENTREQUEST_0_SHIPPINGAMT = prepareNumber(totalShipCost); // ***add variable for ship cost
    params = _.extend(params, this.getItemsParams());

    params.RETURNURL = returnUrl;
    params.CANCELURL = cancelUrl;

    params.NOSHIPPING = 0;
    params.ALLOWNOTE = 1;
    params.REQCONFIRMSHIPPING = 1;
    params.METHOD = 'SetExpressCheckout';

    params = _.extend(params, this.payOptions);

    self.request(self.url, 'POST', params, function(err, data) {
        if (err) {
            callback(err);
            return;
        }

        if (data.ACK === 'Success') {
            callback(null, {
                redirectUrl: self.redirect + '?cmd=_express-checkout&useraction=commit&token=' + data.TOKEN,
                token: data.TOKEN
            });
            return;
        }

        callback(new Error('ACK ' + data.ACK + ': ' + data.L_LONGMESSAGE0));
    });

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

And I have passed shipping cost while calling setExpressCheckoutPayment function from api, and that fixed my issue to show shipping cost on paypal checkout page.

Please refer https://github.com/totaljs/node-paypal-express-checkout/issues/24
also for more details.
Happy Coding.

Body:
I made changes in  lib/paypal-express-checkout.js file in my local node module files.

I have added params.PAYMENTREQUEST_0_SHIPPINGAMT which was missing in function for shipping cost.

Paypal.prototype.setExpressCheckoutPayment = function(email, invoiceNumber, amount, totalShipCost, description, currency, returnUrl, cancelUrl, onlyPayPalUsers, callback) {
    var self = this;
    var params = self.params();
    if (email) {
        params.EMAIL = email;
    }

    params.SOLUTIONTYPE = onlyPayPalUsers === true ? 'Mark' : 'Sole';
    params.PAYMENTREQUEST_0_AMT = prepareNumber(amount + totalShipCost); // ***add ship cost here
    params.PAYMENTREQUEST_0_DESC = description;
    params.PAYMENTREQUEST_0_CURRENCYCODE = currency;
    params.PAYMENTREQUEST_0_INVNUM = invoiceNumber;
    params.PAYMENTREQUEST_0_CUSTOM = invoiceNumber + '|' + params.PAYMENTREQUEST_0_AMT + '|' + currency;
    params.PAYMENTREQUEST_0_PAYMENTACTION = 'Sale';
    params.PAYMENTREQUEST_0_ITEMAMT = prepareNumber(amount);
    params.PAYMENTREQUEST_0_SHIPPINGAMT = prepareNumber(totalShipCost); // ***add variable for ship cost
    params = _.extend(params, this.getItemsParams());

    params.RETURNURL = returnUrl;
    params.CANCELURL = cancelUrl;

    params.NOSHIPPING = 0;
    params.ALLOWNOTE = 1;
    params.REQCONFIRMSHIPPING = 1;
    params.METHOD = 'SetExpressCheckout';

    params = _.extend(params, this.payOptions);

    self.request(self.url, 'POST', params, function(err, data) {
        if (err) {
            callback(err);
            return;
        }

        if (data.ACK === 'Success') {
            callback(null, {
                redirectUrl: self.redirect + '?cmd=_express-checkout&useraction=commit&token=' + data.TOKEN,
                token: data.TOKEN
            });
            return;
        }

        callback(new Error('ACK ' + data.ACK + ': ' + data.L_LONGMESSAGE0));
    });

    return self;
};

And I have passed shipping cost while calling setExpressCheckoutPayment function from api, and that fixed my issue to show shipping cost on paypal checkout page.

Please refer https://github.com/totaljs/node-paypal-express-checkout/issues/24
also for more details.
Happy Coding.


问:
Ajax call using php file placed in theme folder in Osclass classified script?
I am using Osclass classified script, trying to alert a message returned by ajax call.
My ajax-test.php file which is saved in my theme folder contains

```<code><?php
$name = $_GET["name"];
echo "I am " . $name
?>
</code>```

and my JavaScript function code is

```<code>function findName() {
    var name = "Jhon";
    $.ajax({
        method: "POST",
//        url: "oc-content/themes/bender/ajax-test.php",
        url: 'http://127.0.0.1/osclass/index.php?page=ajax&action=custom&ajaxfile=ajax-test.php',
        data: { name : name },
        success: function (data) {
            alert(data);
        },
    })
}
</code>```

Anybody tell me what am I doing wrong? it alerts
{"error" => "ajaxFile doesn't exist"}

Note: It works fine with commented line of code

答:
in your theme functions.php

add something like this:

```<code>//name of your custom ajax request
$my_custom_ajax_request_name = 'doSomethingCool';

osc_add_hook('ajax_' . $my_custom_ajax_request_name, $my_custom_ajax_request_name);

function doSomethingCool()
{
    // set default response
    $response = [
        'status' => false,
        'msg'    => 'Default Error Message...',
    ];

    // token protection
    // read more about csrf token:
    // https://dev.osclass.org/2013/02/19/make-your-plugins-more-secure-with-anti-csrf-functions/
    osc_csrf_check();

    // get request parameters
    $param1 = Params::getParam('param1');
    $param2 = Params::getParam('param2');

    // do some logic here ex: check if user is logged in
    if (osc_is_web_user_logged_in()) {
        $response['status'] = true;
        $response['msg']    = 'User is logged in. ;-) ' . $param1 . ' ' . $param2 . '! ' . osc_logged_user_name();
    } else {
        $response['status'] = false;
        $response['msg']    = 'User is not logged in. :-(';
    }

    // return json response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
</code>```

some where in your template files like header.php, footer.php or everything else you need it...

```<code><a data-param1="hello" data-param2="world" href="#" id="make-an-ajax-request">
    Make an AJAX Request!
</a>
<script>
//here we hold some usefull info for easy access
    var mySite = window.mySite || {};
    mySite.base_url = '<?php echo osc_base_url(true); ?>';
    mySite.csrf_token = '<?php echo osc_csrf_token_url(); ?>';

    $(function(){

        $('#make-an-ajax-request').on('click', function(e){
                e.preventDefault();
            // name of our custom ajax hook
            var ajax_hook = 'doSomethingCool';
            // get parameters
            var param1 = $(this).data('param1');
            var param2 = $(this).data('param2');
            // build axjxa url
            var url = mySite.base_url + '?page=ajax&action=runhook&hook='+ajax_hook+'&'+mySite.csrf_token;

            //build data
            var data = {
                param1 : param1,
                param2 : param2
            };

            $.ajax({
                type: 'POST',
                dataType: 'json',
                data: data,
                url: url
            }).done(function (data) {
                console.log(data);
                if (data.status) {

                } else {

                }
            });
        });

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

OSCLASS WAY

to note that the current osclass way of doing an ajax request from a theme page is to call the
  http://example.com/?page=ajax&action=runhook&hook=MY_HOOK_FUNCTION_NAME
  and register it like osc_add_hook('ajax_MY_HOOK_FUNCTION_NAME',
  'MY_HOOK_FUNCTION_NAME'); optionally but very recommended is the use
  of the csrf token that you can implement like i have done for url or
  by calling the osc_csrf_token_form() directly into your form.

NON OSCLASS WAY

just create a file in your theme or everywhere you want and make sure to put this into it <?php require_once __DIR__ . RELATIVE_PATH_TO_OC_LOAD_FILE . 'oc-load.php'; ?> then build your logic into it.

Body:
I am using Osclass classified script, trying to alert a message returned by ajax call.
My ajax-test.php file which is saved in my theme folder contains

<?php
$name = $_GET["name"];
echo "I am " . $name
?>

and my JavaScript function code is

function findName() {
    var name = "Jhon";
    $.ajax({
        method: "POST",
//        url: "oc-content/themes/bender/ajax-test.php",
        url: 'http://127.0.0.1/osclass/index.php?page=ajax&action=custom&ajaxfile=ajax-test.php',
        data: { name : name },
        success: function (data) {
            alert(data);
        },
    })
}

Anybody tell me what am I doing wrong? it alerts
{"error" => "ajaxFile doesn't exist"}

Note: It works fine with commented line of code

Body:
in your theme functions.php

add something like this:

//name of your custom ajax request
$my_custom_ajax_request_name = 'doSomethingCool';

osc_add_hook('ajax_' . $my_custom_ajax_request_name, $my_custom_ajax_request_name);

function doSomethingCool()
{
    // set default response
    $response = [
        'status' => false,
        'msg'    => 'Default Error Message...',
    ];

    // token protection
    // read more about csrf token:
    // https://dev.osclass.org/2013/02/19/make-your-plugins-more-secure-with-anti-csrf-functions/
    osc_csrf_check();

    // get request parameters
    $param1 = Params::getParam('param1');
    $param2 = Params::getParam('param2');

    // do some logic here ex: check if user is logged in
    if (osc_is_web_user_logged_in()) {
        $response['status'] = true;
        $response['msg']    = 'User is logged in. ;-) ' . $param1 . ' ' . $param2 . '! ' . osc_logged_user_name();
    } else {
        $response['status'] = false;
        $response['msg']    = 'User is not logged in. :-(';
    }

    // return json response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

some where in your template files like header.php, footer.php or everything else you need it...

<a data-param1="hello" data-param2="world" href="#" id="make-an-ajax-request">
    Make an AJAX Request!
</a>
<script>
//here we hold some usefull info for easy access
    var mySite = window.mySite || {};
    mySite.base_url = '<?php echo osc_base_url(true); ?>';
    mySite.csrf_token = '<?php echo osc_csrf_token_url(); ?>';

    $(function(){

        $('#make-an-ajax-request').on('click', function(e){
                e.preventDefault();
            // name of our custom ajax hook
            var ajax_hook = 'doSomethingCool';
            // get parameters
            var param1 = $(this).data('param1');
            var param2 = $(this).data('param2');
            // build axjxa url
            var url = mySite.base_url + '?page=ajax&action=runhook&hook='+ajax_hook+'&'+mySite.csrf_token;

            //build data
            var data = {
                param1 : param1,
                param2 : param2
            };

            $.ajax({
                type: 'POST',
                dataType: 'json',
                data: data,
                url: url
            }).done(function (data) {
                console.log(data);
                if (data.status) {

                } else {

                }
            });
        });

        });
</script>

OSCLASS WAY

to note that the current osclass way of doing an ajax request from a theme page is to call the
  http://example.com/?page=ajax&action=runhook&hook=MY_HOOK_FUNCTION_NAME
  and register it like osc_add_hook('ajax_MY_HOOK_FUNCTION_NAME',
  'MY_HOOK_FUNCTION_NAME'); optionally but very recommended is the use
  of the csrf token that you can implement like i have done for url or
  by calling the osc_csrf_token_form() directly into your form.

NON OSCLASS WAY

just create a file in your theme or everywhere you want and make sure to put this into it <?php require_once __DIR__ . RELATIVE_PATH_TO_OC_LOAD_FILE . 'oc-load.php'; ?> then build your logic into it.


问:
Error when using v-model on file input
I have a file input and I need to clear it after file is uploaded. I tried setting null value to v-model, but it generated the following error

File inputs are read only. Use a v-on:change listener instead.

My code is

```<code><input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />
</code>```

How can I clear the file input in vue.js after upload so that I can upload the same file multiple times continuously

答:
You are  using v-on:change="uploadFile" and guessing that your uploadFile has a success callback.

You can do the following:

Wrap your input in a form and add a ref attribute to your form:

```<code><form ref="myFileInputForm">
      <input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />
 </form>
</code>```

In your successful callback uploadFile do this:

this.$refs.myFileInputForm.reset();

Title: Error when using v-model on file input

Body:
I have a file input and I need to clear it after file is uploaded. I tried setting null value to v-model, but it generated the following error

File inputs are read only. Use a v-on:change listener instead.

My code is

<input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />

How can I clear the file input in vue.js after upload so that I can upload the same file multiple times continuously

Body:
You are  using v-on:change="uploadFile" and guessing that your uploadFile has a success callback.

You can do the following:

Wrap your input in a form and add a ref attribute to your form:

<form ref="myFileInputForm">
      <input id="fileupload" type="file" v-model="file" multiple v-on:change="uploadFile" ref="fileInput" />
 </form>

In your successful callback uploadFile do this:

this.$refs.myFileInputForm.reset();

ContentLicense: CC BY-SA 4.0


问:
Xamarin.Forms using PanGestureRecognizer - move outside of Window area on UWP does not trigger Status Canceled or Completed
My question is regarding the PanGestureRecognizer on Xamarin.Forms, specifically on UWP. The pan gesture works great and the menu slides in and out but if you move the mouse cursor outside of the application window it does not trigger GestureStatus.Canceled, or GestureStatus.Completed. I've simplified the code below because it is not important. The pan gesture is working correctly and the menu is sliding in and out with the pan. The issue is it is not triggering anything if you move the cursor outside of the app window.

Code below:

panContainer is a simple ContentView.

```<code>var panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanUpdated;
panContainer.GestureRecognizers.Add(panGesture);

private void PanUpdated(object sender,PanUpdatedEventArgs e) {
        switch(e.StatusType) {
            case GestureStatus.Started:
                break;
            case GestureStatus.Running:
                menuLayout.TranslationX = (float)e.TotalX;
                break;
            case GestureStatus.Completed:
            case GestureStatus.Canceled:  //I assumed this would be called!
                if(menuLayout.TranslationX < 100) {
                    Close();
                } else {
                    Open();
                }
                break;
        }
    }
</code>```

Thanks in advance!

答:
if you move the mouse cursor outside of the application window it does not trigger GestureStatus.Canceled, or GestureStatus.Completed. I've simplified the code below because it is not important. The pan gesture is working correctly and the menu is sliding in and out with the pan. The issue is it is not triggering anything if you move the cursor outside of the app window.

I have tested your code and reproduce the issue. I tried to find the cause of the problem in the source code. I found the following code.

```<code>void OnPointerCanceled(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(false);
    PanComplete(false);
}

void OnPointerExited(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(true);
    PanComplete(true);
}

void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (!_fingers.Contains(id))
        _fingers.Add(id);
}

void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(true);
    PanComplete(true);
}
</code>```

The PanComplete method will be invoked when you PointerExited,ManipulationCompleted etc. But it has not been invoked when the pointer exited. And then I tried to test PointerExited and  ManipulationCompleted event in uwp native project. Both are working properly.

```<code><Border Width="200" Height="200"  Background="Red" PointerEntered="Border_PointerEntered" PointerExited="Border_PointerExited" ManipulationCompleted="Border_ManipulationCompleted"/>
</code>```

So,there may be some issues with xamarin.

Body:
My question is regarding the PanGestureRecognizer on Xamarin.Forms, specifically on UWP. The pan gesture works great and the menu slides in and out but if you move the mouse cursor outside of the application window it does not trigger GestureStatus.Canceled, or GestureStatus.Completed. I've simplified the code below because it is not important. The pan gesture is working correctly and the menu is sliding in and out with the pan. The issue is it is not triggering anything if you move the cursor outside of the app window.

Code below:

panContainer is a simple ContentView.

var panGesture = new PanGestureRecognizer();
panGesture.PanUpdated += PanUpdated;
panContainer.GestureRecognizers.Add(panGesture);

private void PanUpdated(object sender,PanUpdatedEventArgs e) {
        switch(e.StatusType) {
            case GestureStatus.Started:
                break;
            case GestureStatus.Running:
                menuLayout.TranslationX = (float)e.TotalX;
                break;
            case GestureStatus.Completed:
            case GestureStatus.Canceled:  //I assumed this would be called!
                if(menuLayout.TranslationX < 100) {
                    Close();
                } else {
                    Open();
                }
                break;
        }
    }

Thanks in advance!

Body:
if you move the mouse cursor outside of the application window it does not trigger GestureStatus.Canceled, or GestureStatus.Completed. I've simplified the code below because it is not important. The pan gesture is working correctly and the menu is sliding in and out with the pan. The issue is it is not triggering anything if you move the cursor outside of the app window.

I have tested your code and reproduce the issue. I tried to find the cause of the problem in the source code. I found the following code.

void OnPointerCanceled(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(false);
    PanComplete(false);
}

void OnPointerExited(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(true);
    PanComplete(true);
}

void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (!_fingers.Contains(id))
        _fingers.Add(id);
}

void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
    uint id = e.Pointer.PointerId;
    if (_fingers.Contains(id))
        _fingers.Remove(id);

    PinchComplete(true);
    PanComplete(true);
}

The PanComplete method will be invoked when you PointerExited,ManipulationCompleted etc. But it has not been invoked when the pointer exited. And then I tried to test PointerExited and  ManipulationCompleted event in uwp native project. Both are working properly.

<Border Width="200" Height="200"  Background="Red" PointerEntered="Border_PointerEntered" PointerExited="Border_PointerExited" ManipulationCompleted="Border_ManipulationCompleted"/>

So,there may be some issues with xamarin.


问:
code not working in angular js
```<code>//login.html

<div ng-controller="loginController">
<form action="/" id="myLogin">
    User Name:<input type="text" ng-model="uname" /> <br />
    Password: <input type="password" ng-model="passwd"/> <br />
    <button type="button"  ng-click="submit()">login</button>
</form>
</div>

//controller.js

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
    $routeProvider

    .when('/', {
        templateUrl: 'login.html'
    })
    .when('/employeeReg', {
        templateUrl: 'employeeReg.html'
    })
    .otherwise({
        redirectTo:'/'
    })
});

app.controller('loginController', function($scope, $location) {
    $scope.submit = function () {
        if ($scope.uname == 'admin' && $scope.passwd == 'admin') {
            $location.path('employeeReg.html');
        } else {
            alert('login failed');
        }
    };
});
</code>```

Attached Image

i very new to angular js, this sample code is for just login page but when i open index page nothing is visible, it should redirect to login page.any help would be appriciated.

答:
Try including the angular first:</p>

```<code><script src='JS/angular.min.js'></script>
<script src='JS/angular-route.min.js'></script>
</code>```

Title: code not working in angular js

Body:
//login.html

<form action="/" id="myLogin">
    User Name:<input type="text" ng-model="uname" />

    Password: <input type="password" ng-model="passwd"/>

    <button type="button"  ng-click="submit()">login</button>
</form>

//controller.js

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
    $routeProvider

    .when('/', {
        templateUrl: 'login.html'
    })
    .when('/employeeReg', {
        templateUrl: 'employeeReg.html'
    })
    .otherwise({
        redirectTo:'/'
    })
});

app.controller('loginController', function($scope, $location) {
    $scope.submit = function () {
        if ($scope.uname == 'admin' && $scope.passwd == 'admin') {
            $location.path('employeeReg.html');
        } else {
            alert('login failed');
        }
    };
});

Attached Image

i very new to angular js, this sample code is for just login page but when i open index page nothing is visible, it should redirect to login page.any help would be appriciated.

Body:
Try including the angular first:

<script src='JS/angular.min.js'></script>
<script src='JS/angular-route.min.js'></script>


问:
How to connect one model variable to mutiple html elements using angularjs data binding?
I'm trying to write some application using ng-repeat and limitTo, but it seems that the input field and the buttons can't work together on the same model value.

The problem is that once I changed the value from the input field, the buttons won't work any more. could you tell me why?

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    $scope.test = 3;
    $scope.dPlus = function(){
       $scope.test++;
    }
    $scope.dMinus = function(){
       $scope.test--;
    }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="namesCtrl">

<div ng-if='true'>

<p>Type a number in the input field:</p>

<p><input type="number" ng-model="test"></p>
<input type="button" value="+" ng-click="dPlus()"/>
<input type="button" value="-" ng-click="dMinus()"/>
<div>{{ test }}</div>

<ul>
  <li ng-repeat="x in names | limitTo:test">
    {{ x }}
  </li>
</ul>

</div>

</body>
</html></code>```

答:
It's because you bind value directly in ng-model. Put it in some object and it will work just fine. Like this:

```<code><input type="number" ng-model="vm.counter">
</code>```

https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes

Mistake #2 :)

Body:
I'm trying to write some application using ng-repeat and limitTo, but it seems that the input field and the buttons can't work together on the same model value.

The problem is that once I changed the value from the input field, the buttons won't work any more. could you tell me why?

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Jani',
        'Carl',
        'Margareth',
        'Hege',
        'Joe',
        'Gustav',
        'Birgit',
        'Mary',
        'Kai'
    ];
    $scope.test = 3;
    $scope.dPlus = function(){
       $scope.test++;
    }
    $scope.dMinus = function(){
       $scope.test--;
    }

});

<!DOCTYPE html>

Type a number in the input field:

<input type="number" ng-model="test">

<input type="button" value="+" ng-click="dPlus()"/>
<input type="button" value="-" ng-click="dMinus()"/>

{{ test }}

    {{ x }}

Body:
It's because you bind value directly in ng-model. Put it in some object and it will work just fine. Like this:

<input type="number" ng-model="vm.counter">

https://www.toptal.com/angular-js/top-18-most-common-angularjs-developer-mistakes

Mistake #2 :)


答:
Made plunker. Looks like working

https://plnkr.co/edit/kHXK54?p=preview

```<code>var app = angular.module('myApp', ['ngRoute','ngSanitize']);

app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
        $routeProvider
           .when('/', {
        templateUrl: 'login.html',
        controller  : 'loginController'
        })
        .when('/employee', {
            templateUrl: 'employee.html'
        })
        .otherwise({
            redirectTo:'/'
        })
    }]);

app.controller('loginController', function($scope, $location) {
    $scope.submit = function () {
        if ($scope.uname == 'admin' && $scope.passwd == 'admin') {
            $location.path('/employee');
        } else {
            alert('login failed');
        }
    };
});
</code>```

Title: code not working in angular js

Body:
Made plunker. Looks like working

https://plnkr.co/edit/kHXK54?p=preview

var app = angular.module('myApp', ['ngRoute','ngSanitize']);

app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
        $routeProvider
           .when('/', {
        templateUrl: 'login.html',
        controller  : 'loginController'
        })
        .when('/employee', {
            templateUrl: 'employee.html'
        })
        .otherwise({
            redirectTo:'/'
        })
    }]);

app.controller('loginController', function($scope, $location) {
    $scope.submit = function () {
        if ($scope.uname == 'admin' && $scope.passwd == 'admin') {
            $location.path('/employee');
        } else {
            alert('login failed');
        }
    };
});


问:
Is there any alternate similar to NameValueCollection collection in C#
NameValueCollection can hold multiple string values under a single key.

Is there any collection where I can hold multiple OBJECT (not string) under a single key?

答:
You should consider Lookup<TKey, TElement> if you don't need mutability - https://msdn.microsoft.com/en-us/library/bb460184(v=vs.110).aspx (via ToLookup).

It also means you don't need to check for key existence - https://msdn.microsoft.com/en-us/library/bb292716(v=vs.110).aspx :

If the key is not found in the collection, an empty sequence is
  returned.


问:
Are there any reasons why h2 database shouldn't be used in production?
I am recently considering making an application that uses h2 database as its main database (because it comes with JBoss), but I am bit worried about that. I have read in a few places (discussion boards mainly) that one should not use h2 in production. Are there specific reasons for that? </p>

答: For me me there is no reaseon not to use H2DB in production for mid sized projects. We deployed a production system for about fifteen clients all using H2DB, we experienced very easy installations and backups and yet zero problems regarding the database.</p>


问:
C#: XML Deserialize limitation
I'm kinda newbie with XML serial/deserialize things and tyring to write some Generic classes.
While using  XmlSerializer.Deserialize(typeof(T)), I realize that T object should have the same name as that of the Parent element in my XML. Here is the XML document I'm using for this example i.e. FoodPlaces.xml:

```<code><foodplaces>
            <foodplace>
                <name> The Indian Restaurant</name>
                <week> 47 </week>
                <monday>
                    <food> Pasta </food>
                    <food> chineese food</food>
                    <food> veg food </food>
                </monday>
                <tuesday>
                    <food> Indian food</food>
                    <food> Veg food </food>
                </tuesday>
            </foodplace>
            <foodplace>
                <name> Restauran Italian </name>
                <week> 47 </week>
                <monday>
                    <food> Pizza </food>
                    <food> Checken      </food>
                    <food>  sallad </food>
                </monday>
                <tuesday>
                    <food> Fish </food>
                    <food>  ris </food>
                    <food> Biff </food>
                    <food> Checken </food>
                </tuesday>
            </foodplace>
        </foodplaces>
</code>```

And this is how, I'm deserializing this xml:

```<code>var serializer = new XmlSerializer(typeof(foodplaces));
var fs = new FileStream(@"D:\FoodPlaces.xml", FileMode.Open);
var reader = XmlReader.Create(fs);

var fp = (foodplaces)serializer.Deserialize(reader);
fs.Close();
</code>```

This will work absolutely fine because my storage class name is "foodplaces" which is the topmost/parent element in the XML file.

When I tried to rename my storage class to MyFoodPlaces, this happened:

```<code>*System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There is an error in XML document (1, 2).
  Source=System.Xml
//Skipping stack trace:
InnerException:
       HResult=-2146233079
       **Message=<foodplaces xmlns=''> was not expected.**
       Source=Microsoft.GeneratedCode*
</code>```

This would be corrected if I rename it back to "foodplaces" which is the topmost/parent element in the XML.

Questions:

 1. What if I want to store this XML data in some other class with different name e..g MyfoodPlaces?

 2. Is there any solution in using LinQ?

答:
```<code>[XmlRoot("foodplaces")]
public class ThisCanBeAnything {...}
</code>```

There are a range of attributes that impact this, including [XmlRoot(...)], [XmlElement(...)], [XmlAttribute(...)], [XmlArrayItem(...)], [XmlArray(...)], [XmlInclude(...)], [XmlIgnore(...)], etc. They also allow full control of xml namespaces (rather than just the default namespace).

See: https://msdn.microsoft.com/en-us/library/83y7df3e(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx for more info.

Note that [Serializable] does not impact xml serialization; don't believe anyone who tells you to include that when you are using XmlSerializer.

Title: C#: XML Deserialize limitation

Body:
I'm kinda newbie with XML serial/deserialize things and tyring to write some Generic classes.
While using  XmlSerializer.Deserialize(typeof(T)), I realize that T object should have the same name as that of the Parent element in my XML. Here is the XML document I'm using for this example i.e. FoodPlaces.xml:

<foodplaces>
            <foodplace>
                <name> The Indian Restaurant</name>
                <week> 47 </week>
                <monday>
                    <food> Pasta </food>
                    <food> chineese food</food>
                    <food> veg food </food>
                </monday>
                <tuesday>
                    <food> Indian food</food>
                    <food> Veg food </food>
                </tuesday>
            </foodplace>
            <foodplace>
                <name> Restauran Italian </name>
                <week> 47 </week>
                <monday>
                    <food> Pizza </food>
                    <food> Checken      </food>
                    <food>  sallad </food>
                </monday>
                <tuesday>
                    <food> Fish </food>
                    <food>  ris </food>
                    <food> Biff </food>
                    <food> Checken </food>
                </tuesday>
            </foodplace>
        </foodplaces>

And this is how, I'm deserializing this xml:

var serializer = new XmlSerializer(typeof(foodplaces));
var fs = new FileStream(@"D:\FoodPlaces.xml", FileMode.Open);
var reader = XmlReader.Create(fs);

var fp = (foodplaces)serializer.Deserialize(reader);
fs.Close();

This will work absolutely fine because my storage class name is "foodplaces" which is the topmost/parent element in the XML file.

When I tried to rename my storage class to MyFoodPlaces, this happened:

*System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There is an error in XML document (1, 2).
  Source=System.Xml
//Skipping stack trace:
InnerException:
       HResult=-2146233079
       **Message=<foodplaces xmlns=''> was not expected.**
       Source=Microsoft.GeneratedCode*

This would be corrected if I rename it back to "foodplaces" which is the topmost/parent element in the XML.

Questions:

 1. What if I want to store this XML data in some other class with different name e..g MyfoodPlaces?

 2. Is there any solution in using LinQ?

Body:
[XmlRoot("foodplaces")]
public class ThisCanBeAnything {...}

There are a range of attributes that impact this, including [XmlRoot(...)], [XmlElement(...)], [XmlAttribute(...)], [XmlArrayItem(...)], [XmlArray(...)], [XmlInclude(...)], [XmlIgnore(...)], etc. They also allow full control of xml namespaces (rather than just the default namespace).

See: https://msdn.microsoft.com/en-us/library/83y7df3e(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx for more info.

Note that [Serializable] does not impact xml serialization; don't believe anyone who tells you to include that when you are using XmlSerializer.


问:
Error TokenMismatchException in VerifyCsrfToken.php line 68:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

```<code><form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>
<div class="table table-responsive">
    <table id="example1" class="table table-bordered">
        <thead>
        <tr class="info">
            <th width="3%"><input type="checkbox" name="select_all" id="select_all" value=""/></th>
            <th>No</th>
            <th>Data lengkap</th>
            <th>Aksi</th>
        </tr>
        </thead>
        <tbody>
        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )
            <tr>
                <td>
                    <label class="checkbox-inline"><input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>
                    </label>
                </td>
                <td width="5%">{{ $i }}</td>
                <td width="95%">
                    <table class="table">
                        <tr>
                            <td class="info">Nama panggilan</td>
                            <td>{{$row->nm_panggilan}}</td>
                            <td class="warning">Pekerjaan ibu</td>
                            <td>{{$row->pekerjaan_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Jenis kelamin</td>
                            <td>{{$row->jenis_kelamin}}</td>
                            <td class="warning">No. Handphone</td>
                            <td>{{$row->hp_ibu}}</td>
                        </tr>
                        <tr>
                            <td class="info">Tempat, Tanggal lahir</td>
                            <td>{{$row->tempat}}, {{$row->tanggal_lahir}}</td>
                            <td class="warning">Alamat</td>
                            <td>{{$row->alamat}}</td>
                        </tr>
                        <tr>
                            <td class="info">Status anak</td>
                            <td>{{$row->status_anak}}</td>
                            <td class="warning">Golongan darah</td>
                            <td>{{$row->goldar}}</td>
                        </tr>
                        <tr>
                            <td class="info">Agama</td>
                            <td>{{$row->agama}}</td>
                            <td class="warning">Nama wali</td>
                            <td>{{$row->nm_wali}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kewarganegaraan</td>
                            <td>{{$row->kewarganegaraan}}</td>
                        </tr>
                        <tr>
                            <td class="info">Anak ke-</td>
                            <td>{{$row->anak_ke}}</td>
                        </tr>
                        <tr>
                            <td class="info">Kelas</td>
                            <td>{{$row->kelas}}</td>
                        </tr>
                    </table>
                </td>
                <td>
                    <a href="{!! url('/'.$row->id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"><i class="fa fa-edit"></i></button><br>
                    </a>
                    <a href="{!! url('/'.$row->id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"><i class="fa fa-trash"></i></button>
                    </a>
                </td>
                </td>
            </tr>
            <?php $i++; ?>
        @endforeach
        </tbody>
    </table>
    <div class="col-md-3">
        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>
    </div>
</div>
</form>
</code>```

But I still have error, what causes it?

```<code>public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}
</code>```

答:
You can resolve this issue in two ways:-
First One:-

```<code>{{ csrf_field() }}
  or
<input type="hidden" name="_token" value="{{ csrf_token() }}"/> // add this in form
</code>```

Or the other (simpler) way, inside your app\Http\Middleware/VerifyCsrfToken.php add

```<code>protected $except = [
'update-kb', // your route name
];
</code>```

Hope it helps!

Body:
I want to do multiple edit, I want to edit from the data I checked following script .blade, I found the TokenMismatchException error in VerifyCsrfToken.php line 68: when updating.

<form name="form" action="{{url('/update-kb')}}" method="post" onsubmit="return deleteConfirm();"/>

            <input type="checkbox" name="select_all" id="select_all" value=""/>
            No
            Data lengkap
            Aksi

        <?php $i = 1; ?>
        @foreach( $datasiswa as $row )

                    <input type="checkbox" name="checked_id[]" class="checkbox" value="{{$row->id}}"/>

                {{ $i }}

                            Nama panggilan
                            {{$row->nm_panggilan}}
                            Pekerjaan ibu
                            {{$row->pekerjaan_ibu}}

                            Jenis kelamin
                            {{$row->jenis_kelamin}}
                            No. Handphone
                            {{$row->hp_ibu}}

                            Tempat, Tanggal lahir
                            {{$row->tempat}}, {{$row->tanggal_lahir}}
                            Alamat
                            {{$row->alamat}}

                            Status anak
                            {{$row->status_anak}}
                            Golongan darah
                            {{$row->goldar}}

                            Agama
                            {{$row->agama}}
                            Nama wali
                            {{$row->nm_wali}}

                            Kewarganegaraan
                            {{$row->kewarganegaraan}}

                            Anak ke-
                            {{$row->anak_ke}}

                            Kelas
                            {{$row->kelas}}

                    id.'/edit-siswa') !!}">
                        <button class="btn btn-default btn-block"></button>

                    id.'/delete-siswa') !!}">
                        <button class="btn btn-danger btn-block"></button>

            <?php $i++; ?>
        @endforeach

        <input type="submit" class="btn btn-danger" name="delete_submit" value="Hapus"/>

</form>

But I still have error, what causes it?

public function updatekb($id, Request $request)
{
    $data = Datasiswa::find($id);
    if (isset($request->delete_submit)) {
        $idArr = $request->checked_id;
        foreach ($idArr as $id) {
            DB::update('update tb_siswa, tb_pernyataan set tb_pernyataan.kelas = "cekcek" where tb_pernyataan.kelas = "TK A" and tb_siswa.sekolah = "KB TK KHALIFAH 25" and id = "' . $id . '" ');
        }

        return back();
        Session::flash('sukses', 'Data berhasil di update', compact('data'));
    }
}

Body:
You can resolve this issue in two ways:-
First One:-

{{ csrf_field() }}
  or
<input type="hidden" name="_token" value="{{ csrf_token() }}"/> // add this in form

Or the other (simpler) way, inside your app\Http\Middleware/VerifyCsrfToken.php add

protected $except = [
'update-kb', // your route name
];

Hope it helps!


问:
Fixing street names with regex
I've got to solve a regex problem that might be to specific, looking through Stack overflow I've made some good discoveries, but have not been able to piece them together to make it work.

Basically I want this:

lorem ipsum north road => lorem ipsum rd (n)

north lorem ipsum rd => lorem ipsum rd (n)

lorem ipsum road north => lorem ipsum rd (n)

As part of an auto complete program i need to convert partial text to the correct version so it can check the database

lorem ipsum south rd => lorem ipsum rd (s)

west lorem ipsum road => lorem ipsum rd (w)

I don't want somebody to code this program for me, but I would like to know the best way of tackling the problem.

Now you might ask me why I bother, as people would not write with such f'd up grammar, but that's because I'm not only dealing with English :(

Cheers

答:
For the first part of your question, would the following pseudo regex look something like what you are after?

```<code>(<direction>?) <road name> (<direction>?) <road type> (<direction>?)
</code>```

Then you check for each of the three optional <direction> regex, including whatever condition you want to give it. You will need to come up with the <direction>, <road name>, and <road type> regex yourself. Those regex should probably be specific, e.g. (road)|(rd)|(street)|(st).

For the 2nd part of the question (i.e. auto-complete), you may need to index some or all of the regex categories mentioned above (i.e. directions, road names, and road types), depending how much you want to auto-complete.

ContentLicense: CC BY-SA 2.5

Title: Fixing street names with regex

Body:
For the first part of your question, would the following pseudo regex look something like what you are after?

(<direction>?) <road name> (<direction>?) <road type> (<direction>?)

Then you check for each of the three optional <direction> regex, including whatever condition you want to give it. You will need to come up with the <direction>, <road name>, and <road type> regex yourself. Those regex should probably be specific, e.g. (road)|(rd)|(street)|(st).

For the 2nd part of the question (i.e. auto-complete), you may need to index some or all of the regex categories mentioned above (i.e. directions, road names, and road types), depending how much you want to auto-complete.


问:
POST method is sent as GET to the servlet
I am trying to fill a table using a POST command to my servlet, but instead of sending a POST request, my webpage sends a GET request to the servlet. Here is my

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("

");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("
Success!
" + data);
      } else {
        $("#error").html("
Information is Invalid!
" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}
```

<pre class="lang-html prettyprint-override"><code><h1>League Table</h1>
<table cellspacing="0" id="tableleague" style="width:100%">
  <tr>
    <th scope="col">Teams</th>
    <th scope="col">Won</th>
    <th scope="col">Tie</th>
    <th scope="col">Lost</th>
    <th scope="col">Scored</th>
    <th scope="col">Received</th>
    <th scope="col">Points</th>
  </tr>
</table>

<form method="POST">
  <div class="form_group">
    <label for="FirstTeam">FirstTeam:</label>
    <input type="text" class="form_control" id="firstteam">
  </div>
  <div class="form_group">
    <label for="Score1">Score1:</label>
    <input type="text" class="form_control" id="score1">
  </div>
  <div class="form_group">
    <label for="Score2">Score2:</label>
    <input type="text" class="form_control" id="score2">
  </div>
  <div class="form_group">
    <label for="SecondTeam">SecondTeam:</label>
    <input type="text" class="form_control" id="secondteam">
  </div>
  <div class="form_group">
    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>
  </div>
</form>

<div id="error"></div>
</code>```

Here is what I see in my debugger immediately after I press the Add match button:

The error I receive in the console is this one:

POST http://localhost:8080/league/league 500 (Internal Server Error)

What am I doing wrong with my code? I tried many solutions but nothing worked.

My servlet code:

```<code>@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

}
</code>```

答:
Well, have done below changes to your addData() function.
Inside$.ajax() function, create a param object to hold the form data and it can be passed to servlet like this.

```<code>var param = 'formdata='+JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "/league",
    data: param,
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
</code>```

You can access this data object in your PopulateTable servlet with HttpServletRequest object. You can access like

```<code>String formData = request.getParameter("formdata");
</code>```

The above formData holds form input values in json format and it is good for parsing.

Hope this helps!!!

Body:
I am trying to fill a table using a POST command to my servlet, but instead of sending a POST request, my webpage sends a GET request to the servlet. Here is my

$(document).ready(function() {
  $.get("league", function(responseJson) {
    if (responseJson != null) {
      $("#tableleague").find("tr:gt(0)").remove();
      var table1 = $("#tableleague");
      $.each(responseJson, function(key, value) {
        var rowNew = $("

");
        rowNew.children().eq(0).text(value['teams']);
        rowNew.children().eq(1).text(value['playedgames']);
        rowNew.children().eq(2).text(value['wongames']);
        rowNew.children().eq(3).text(value['tiegames']);
        rowNew.children().eq(4).text(value['lostgames']);
        rowNew.children().eq(5).text(value['scoredgoal']);
        rowNew.children().eq(6).text(value['scoredgoal']);
        rowNew.children().eq(7).text(value['scoredgoal']);
        rowNew.appendTo(table1);
      });
    }
  });
});

function addData() {
  var t1 = $("#firstteam").val();
  var t2 = $("#secondteam").val();
  var s1 = $("#score1").val();
  var s2 = $("#score2").val();
  $("#firstteam").val('');
  $("#secondteam").val('');
  $("#score1").val('');
  $("#score2").val('');
  var data = {
    firstteam: "t1",
    secondteam: "t2",
    score1: "s1",
    score2: "s2"
  }

  $.ajax({
    type: "POST",
    url: "league",
    data: JSON.stringify(data),
    contentType: "application/x-www-form-urlencoded",
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("
Success!
" + data);
      } else {
        $("#error").html("
Information is Invalid!
" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });
}

League Table

    Teams
    Won
    Tie
    Lost
    Scored
    Received
    Points

<form method="POST">

    FirstTeam:
    <input type="text" class="form_control" id="firstteam">

    Score1:
    <input type="text" class="form_control" id="score1">

    Score2:
    <input type="text" class="form_control" id="score2">

    SecondTeam:
    <input type="text" class="form_control" id="secondteam">

    <button type="submit" class="addbutton" id="addbut" onclick="addData();">Add match</button>

</form>

Here is what I see in my debugger immediately after I press the Add match button:

The error I receive in the console is this one:

POST http://localhost:8080/league/league 500 (Internal Server Error)

What am I doing wrong with my code? I tried many solutions but nothing worked.

My servlet code:

@WebServlet("/league/*")
public class PopulateTable extends HttpServlet {
private static final long serialVersionUID = 1L;

public PopulateTable()
{

}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try
    {
        ArrayList<League> league = new ArrayList<League>();
        league= Controller.getAllController();
        Gson gson = new Gson();
        JsonElement element = gson.toJsonTree(league, new TypeToken<List<League>>() {}.getType());

        JsonArray jsonArray = element.getAsJsonArray();
        response.setContentType("application/json");
        response.getWriter().print(jsonArray);
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    try {
        PrintWriter out = response.getWriter();
        JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);

        int s1 = Integer.parseInt(data.get("score1").getAsString());
        int s2 = Integer.parseInt(data.get("score2").getAsString());

        String t1 = data.get("firstteam").getAsString();;
        String t2 = data.get("secondteam").getAsString();;
        int ok = Controller.update(t1, t2, s1, s2);
        JsonObject myObj = new JsonObject();

        if(ok ==  1)
        {
            myObj.addProperty("success", true);
        }
        else {
            myObj.addProperty("success", false);
        }
        out.println(myObj.toString());

        out.close();

    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
    }
}

}

Body:
Well, have done below changes to your addData() function.
Inside$.ajax() function, create a param object to hold the form data and it can be passed to servlet like this.

var param = 'formdata='+JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "/league",
    data: param,
    dataType:'json',
    success: function(data, textStatus, jqXHR) {
      if (data.success) {
        $("#error").html("<div><b>Success!</b></div>" + data);
      } else {
        $("#error").html("<div><b>Information is Invalid!</b></div>" + data);
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Something really bad happened " + textStatus);
      $("#error").html(jqXHR.responseText);
    }
  });

You can access this data object in your PopulateTable servlet with HttpServletRequest object. You can access like

String formData = request.getParameter("formdata");

The above formData holds form input values in json format and it is good for parsing.

Hope this helps!!!