问:
How to solve the error " missing required header GL/gl.h" while installing the Package mvoutlier in R?
I am trying to install the package mvoutlier but following error occurs during installation:

```<code>install.packages("mvoutlier")
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library /2.15/rgl’
ERROR: dependency ‘rgl’ is not available for package ‘compositions’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/compositions’
ERROR: dependency ‘compositions’ is not available for package ‘mvoutlier’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/mvoutlier’
</code>```

After that I have install the rgl package successfully, then I tried to install the compositions package then the again same error occurs. Then I have again tried to install the mvoutlier package the same error occurs.

Can anyone let me know how I can resolve this problem. Thanking you in advance.

答: On Ubuntu 16.04, I solved this problem (during rgl package installation) with sudo apt-get install libglu1-mesa-dev

Body:
I am trying to install the package mvoutlier but following error occurs during installation:

install.packages("mvoutlier")
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library /2.15/rgl’
ERROR: dependency ‘rgl’ is not available for package ‘compositions’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/compositions’
ERROR: dependency ‘compositions’ is not available for package ‘mvoutlier’
* removing ‘/home/sam/R/x86_64-pc-linux-gnu-library/2.15/mvoutlier’

After that I have install the rgl package successfully, then I tried to install the compositions package then the again same error occurs. Then I have again tried to install the mvoutlier package the same error occurs.

Can anyone let me know how I can resolve this problem. Thanking you in advance.


来源: stackexchange

问:
Provide access to user based on rule in a organisation website
I have a website with user login and dB describing his / her roles .
All the pages in the website are not accessible to everyone . The accessibility of each page should be based on the user role .
Ie the accessibility a manager of the organisation has will be different from that of a technician and both will be different from the accessibility of a trainee .  </p>

<p>How can I implement this in my website easily ? </p>

答:
You should check Angular Acl (Access Control List)

Documentation:
https://github.com/mikemclin/angular-acl

ContentLicense: CC BY-SA 3.0

Body:
I have a website with user login and dB describing his / her roles .
All the pages in the website are not accessible to everyone . The accessibility of each page should be based on the user role .
Ie the accessibility a manager of the organisation has will be different from that of a technician and both will be different from the accessibility of a trainee .

How can I implement this in my website easily ?


问:
Can't replicate a matconvnet CNN architecture in Keras
I have the following architecture of a Convolutional Neural Network in matconvnet which I use to train on my own data:

```<code>function net = cnn_mnist_init(varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;

f= 0.0125 ;
net.layers = {} ;
net.layers{end+1} = struct('name','conv1',...
                           'type', 'conv', ...
                           'weights', {{f*randn(3,3,1,64, 'single'), zeros(1, 64, 'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool1',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [3 3], ...
                           'stride', 1, ...
                           'pad', 0);
net.layers{end+1} = struct('name','conv2',...
                           'type', 'conv', ...
                           'weights', {{f*randn(5,5,64,128, 'single'),zeros(1,128,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool2',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [2 2], ...
                           'stride', 2, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','conv3',...
                           'type', 'conv', ...
                           'weights', {{f*randn(3,3,128,256, 'single'),zeros(1,256,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool3',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [3 3], ...
                           'stride', 1, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','conv4',...
                           'type', 'conv', ...
                           'weights', {{f*randn(5,5,256,512, 'single'),zeros(1,512,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool4',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [2 2], ...
                           'stride', 1, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','ip1',...
                           'type', 'conv', ...
                           'weights', {{f*randn(1,1,256,256, 'single'),  zeros(1,256,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','relu',...
                           'type', 'relu');
net.layers{end+1} = struct('name','classifier',...
                           'type', 'conv', ...
                           'weights', {{f*randn(1,1,256,2, 'single'), zeros(1,2,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','loss',...
                           'type', 'softmaxloss') ;

% optionally switch to batch normalization
if opts.batchNormalization
  net = insertBnorm(net, 1) ;
  net = insertBnorm(net, 4) ;
  net = insertBnorm(net, 7) ;
  net = insertBnorm(net, 10) ;
  net = insertBnorm(net, 13) ;
end

% Meta parameters
net.meta.inputSize = [28 28 1] ;
net.meta.trainOpts.learningRate = [0.01*ones(1,10) 0.001*ones(1,10) 0.0001*ones(1,10)];
disp(net.meta.trainOpts.learningRate);
pause;
net.meta.trainOpts.numEpochs = length(net.meta.trainOpts.learningRate) ;
net.meta.trainOpts.batchSize = 256 ;
net.meta.trainOpts.momentum = 0.9 ;
net.meta.trainOpts.weightDecay = 0.0005 ;

% --------------------------------------------------------------------
function net = insertBnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
ndim = size(net.layers{l}.weights{1}, 4);
layer = struct('type', 'bnorm', ...
               'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...
               'learningRate', [1 1], ...
               'weightDecay', [0 0]) ;
net.layers{l}.biases = [] ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
</code>```

What I want to do is building the same architecture in Keras, that is what I tried so far:

```<code>model = Sequential()

model.add(Conv2D(64, (3, 3), strides=1, input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(3, 3), strides=1))

model.add(Conv2D(128, (5, 5), strides=1))
model.add(MaxPooling2D(pool_size=(2, 2), strides=2))

model.add(Conv2D(256, (3, 3), strides=1))
model.add(MaxPooling2D(pool_size=(3, 3), strides=1))

model.add(Conv2D(512, (5, 5), strides=1))
model.add(MaxPooling2D(pool_size=(2, 2), strides=1))

model.add(Conv2D(256, (1, 1)))
convout1=Activation('relu')
model.add(convout1)

model.add(Flatten())
model.add(Dense(num_classes, activation='softmax'))

opt = keras.optimizers.rmsprop(lr=0.0001, decay=0.0005)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['binary_accuracy'])
</code>```

However, when I run the matconvnet network I have 87% accuracy and if I run the keras version I have 77% accuracy. If they are supposed to be the same network and the data is the same, where is the difference? What is wrong in my Keras architecture?

答:
In your MatConvNet version, you use SGD with momentum.

In Keras, you use rmsprop

With a different learning rule you should try different learning rates. Also sometimes momentum is helpful when training a CNN.

Could you try the SGD+momentum in Keras and let me know what happens?

Another thing that might be different is that the initialization. for example in MatConvNet you use gaussian initialization with f= 0.0125 as the standard deviation. In Keras I'm not sure about the default initialization.

In general, if you don't use batch normalization, the network is prone to many numerical issues. If you use batch normalization in both networks, I bet the results would be similar. Is there any reason you don't want to use batch normalization?

Body:
I have the following architecture of a Convolutional Neural Network in matconvnet which I use to train on my own data:

function net = cnn_mnist_init(varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;

f= 0.0125 ;
net.layers = {} ;
net.layers{end+1} = struct('name','conv1',...
                           'type', 'conv', ...
                           'weights', {{f*randn(3,3,1,64, 'single'), zeros(1, 64, 'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool1',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [3 3], ...
                           'stride', 1, ...
                           'pad', 0);
net.layers{end+1} = struct('name','conv2',...
                           'type', 'conv', ...
                           'weights', {{f*randn(5,5,64,128, 'single'),zeros(1,128,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool2',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [2 2], ...
                           'stride', 2, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','conv3',...
                           'type', 'conv', ...
                           'weights', {{f*randn(3,3,128,256, 'single'),zeros(1,256,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool3',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [3 3], ...
                           'stride', 1, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','conv4',...
                           'type', 'conv', ...
                           'weights', {{f*randn(5,5,256,512, 'single'),zeros(1,512,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','pool4',...
                           'type', 'pool', ...
                           'method', 'max', ...
                           'pool', [2 2], ...
                           'stride', 1, ...
                           'pad', 0) ;
net.layers{end+1} = struct('name','ip1',...
                           'type', 'conv', ...
                           'weights', {{f*randn(1,1,256,256, 'single'),  zeros(1,256,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','relu',...
                           'type', 'relu');
net.layers{end+1} = struct('name','classifier',...
                           'type', 'conv', ...
                           'weights', {{f*randn(1,1,256,2, 'single'), zeros(1,2,'single')}}, ...
                           'stride', 1, ...
                           'pad', 0,...
                           'learningRate', [1 2]) ;
net.layers{end+1} = struct('name','loss',...
                           'type', 'softmaxloss') ;

% optionally switch to batch normalization
if opts.batchNormalization
  net = insertBnorm(net, 1) ;
  net = insertBnorm(net, 4) ;
  net = insertBnorm(net, 7) ;
  net = insertBnorm(net, 10) ;
  net = insertBnorm(net, 13) ;
end

% Meta parameters
net.meta.inputSize = [28 28 1] ;
net.meta.trainOpts.learningRate = [0.01*ones(1,10) 0.001*ones(1,10) 0.0001*ones(1,10)];
disp(net.meta.trainOpts.learningRate);
pause;
net.meta.trainOpts.numEpochs = length(net.meta.trainOpts.learningRate) ;
net.meta.trainOpts.batchSize = 256 ;
net.meta.trainOpts.momentum = 0.9 ;
net.meta.trainOpts.weightDecay = 0.0005 ;

% --------------------------------------------------------------------
function net = insertBnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
ndim = size(net.layers{l}.weights{1}, 4);
layer = struct('type', 'bnorm', ...
               'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...
               'learningRate', [1 1], ...
               'weightDecay', [0 0]) ;
net.layers{l}.biases = [] ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;

What I want to do is building the same architecture in Keras, that is what I tried so far:

model = Sequential()

model.add(Conv2D(64, (3, 3), strides=1, input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(3, 3), strides=1))

model.add(Conv2D(128, (5, 5), strides=1))
model.add(MaxPooling2D(pool_size=(2, 2), strides=2))

model.add(Conv2D(256, (3, 3), strides=1))
model.add(MaxPooling2D(pool_size=(3, 3), strides=1))

model.add(Conv2D(512, (5, 5), strides=1))
model.add(MaxPooling2D(pool_size=(2, 2), strides=1))

model.add(Conv2D(256, (1, 1)))
convout1=Activation('relu')
model.add(convout1)

model.add(Flatten())
model.add(Dense(num_classes, activation='softmax'))

opt = keras.optimizers.rmsprop(lr=0.0001, decay=0.0005)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['binary_accuracy'])

However, when I run the matconvnet network I have 87% accuracy and if I run the keras version I have 77% accuracy. If they are supposed to be the same network and the data is the same, where is the difference? What is wrong in my Keras architecture?


问:
Script is not heading the user to defined page
I have a form which I am using to register an user. Here I the form I am using.

```<code><form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
  <div class="form-group">
    <input type="text" name="username" id="username" class="inputs"><br />
    <input type="text" name="email" id="email" class="inputs" /><br />
    <input type="password" name="password" id="password" class="inputs" /><br />
    <input type="password" name="confirmpwd" id="confirmpwd" class="inputs" /><br />
    <input type="button" name="register" id="register" value="Register" onclick="return regformhash(this.form, this.form.username, this.form.email, this.form.password, this.form.confirmpwd);" class="btn"><br />
  </div>
  <div style="font-weight:bold;color:red"><p><?php
    if (!empty($error_msg)) {
      echo $error_msg;
    }
  ?>
  </p></div>
</form>
</code>```

The register script should send the user, after adding to user to the database to the page register_success.php. But when I click on the submit button the script creates an new user and sends the user back to a blank register page (index.php).

Does someone know why the user dont gets sended to the register_success.php?

Here is my register script:

```<code>if (empty($error_msg)) {
    // Create a random salt
    $random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

    // Create salted password
    $password = hash('sha512', $password . $random_salt);

    // Insert the new user into the database
    if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
        $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
        // Execute the prepared query.
        if (! $insert_stmt->execute()) {
            header('Location: ../error.php?err=Registration failure: INSERT');
            exit();
        }

        $user_id = mysqli_insert_id($mysqli);

        if ($insert_stmt2 = $mysqli->prepare("INSERT INTO members2 (user_id, username, email, password, salt) VALUES (?, ?, ?, ?, ?)")) {
            $insert_stmt2->bind_param('sssss', $user_id, $username, $email, $password, $random_salt);
            // Execute the prepared query.
            if (! $insert_stmt2->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
                exit();
            }
        }
    }
    header('Location: ./register_success.php');
    exit();
}
</code>```

I also tried to add an else statement after:

```<code>if (! $insert_stmt2->execute()) {
    header('Location: ../error.php?err=Registration failure: INSERT');
    exit();
}
</code>```

But the script still sends the user to index.php

Here is the function regformhash:

```<code>function regformhash(form, uid, email, password, conf) {
    // Check each field has a value
    if (uid.value == '' || email.value == '' || password.value == '' || conf.value == '') {
        alert('Error 1');
        return false;
    }

    // Check the username
    re = /^[. \w]+$/;
    if(!re.test(form.username.value)) {
        alert("Error 2");
        form.username.focus();
        return false;
    }

    // Check that the password is sufficiently long (min 6 chars)
    // The check is duplicated below, but this is included to give more
    // specific guidance to the user
    if (password.value.length < 6) {
        alert('Error 3');
        form.password.focus();
        return false;
    }

    // At least one number, one lowercase and one uppercase letter
    // At least six characters
    var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
    if (!re.test(password.value)) {
        alert('Error 4');
        return false;
    }

    // Check password and confirmation are the same
    if (password.value != conf.value) {
        alert('Error 5');
        form.password.focus();
        return false;
    }
</code>```

答:
I believe the problem is with how you're using the header() function.  It appears you're using it like a file browser, when it requires a URL.  There are two possible solutions.

1) If register_success.php is accessible.  E.G., example.com/register_success.php, then you should be using...

header("Location: /register_success.php");

or...

header("Location: example.com/register_success.php");

However, this would not be a good way to structure your code, and I wonder if it actually isn't what you meant.  So...

2) Assuming you are using the better approach of keeping your primary PHP code outside the web document tree, then you shouldn't be using the header() command at all.  Replace the entire line with...

require_once("register_success.php");

Without a path prefix the command assumes register_success.php is in the same file directory as the original file.

If "better approach" doesn't make sense to you, please understand that it's good programming practice for (e.g.) index.php to contain one line: require("/some_directory_outside_web_root/my_index.php"); and all of your PHP files are in /some_directory_outside_web_root.  If you don't do this, then it's possible (depending on how your server is set up) to download your PHP files as text files and users can suddenly get everything from your DB password to how you're using your database.  Ug.  Better to be completely safe.  Cheers.

Body:
I have a form which I am using to register an user. Here I the form I am using.

<form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">

    <input type="text" name="username" id="username" class="inputs">

    <input type="text" name="email" id="email" class="inputs" />

    <input type="password" name="password" id="password" class="inputs" />

    <input type="password" name="confirmpwd" id="confirmpwd" class="inputs" />

    <input type="button" name="register" id="register" value="Register" onclick="return regformhash(this.form, this.form.username, this.form.email, this.form.password, this.form.confirmpwd);" class="btn">

<?php
    if (!empty($error_msg)) {
      echo $error_msg;
    }
  ?>

</form>

The register script should send the user, after adding to user to the database to the page register_success.php. But when I click on the submit button the script creates an new user and sends the user back to a blank register page (index.php).

Does someone know why the user dont gets sended to the register_success.php?

Here is my register script:

if (empty($error_msg)) {
    // Create a random salt
    $random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));

    // Create salted password
    $password = hash('sha512', $password . $random_salt);

    // Insert the new user into the database
    if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
        $insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
        // Execute the prepared query.
        if (! $insert_stmt->execute()) {
            header('Location: ../error.php?err=Registration failure: INSERT');
            exit();
        }

        $user_id = mysqli_insert_id($mysqli);

        if ($insert_stmt2 = $mysqli->prepare("INSERT INTO members2 (user_id, username, email, password, salt) VALUES (?, ?, ?, ?, ?)")) {
            $insert_stmt2->bind_param('sssss', $user_id, $username, $email, $password, $random_salt);
            // Execute the prepared query.
            if (! $insert_stmt2->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
                exit();
            }
        }
    }
    header('Location: ./register_success.php');
    exit();
}

I also tried to add an else statement after:

if (! $insert_stmt2->execute()) {
    header('Location: ../error.php?err=Registration failure: INSERT');
    exit();
}

But the script still sends the user to index.php

Here is the function regformhash:

function regformhash(form, uid, email, password, conf) {
    // Check each field has a value
    if (uid.value == '' || email.value == '' || password.value == '' || conf.value == '') {
        alert('Error 1');
        return false;
    }

    // Check the username
    re = /^[. \w]+$/;
    if(!re.test(form.username.value)) {
        alert("Error 2");
        form.username.focus();
        return false;
    }

    // Check that the password is sufficiently long (min 6 chars)
    // The check is duplicated below, but this is included to give more
    // specific guidance to the user
    if (password.value.length < 6) {
        alert('Error 3');
        form.password.focus();
        return false;
    }

    // At least one number, one lowercase and one uppercase letter
    // At least six characters
    var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
    if (!re.test(password.value)) {
        alert('Error 4');
        return false;
    }

    // Check password and confirmation are the same
    if (password.value != conf.value) {
        alert('Error 5');
        form.password.focus();
        return false;
    }


问:
Resolving ambiguity with using declaration
Look at this snippet:

```<code>namespace A {
int fn();
}
namespace B {
int fn();
}

// namespace Ns {

using namespace A;
using namespace B;
using A::fn;

int z = fn();

// }
</code>```

This code doesn't compile, as fn() is ambiguous at int z = fn();

If I put using's and z into a namespace (remove the two //), the code compiles. Why is that? What is special about the global namespace?

答:
See [namespace.udir]/2

A using-directive specifies that the names in the nominated namespace can be used in the scope in which the
  using-directive appears after the using-directive. During unqualified name lookup (3.4.1), the names appear
  as if they were declared in the nearest enclosing namespace which contains both the using-directive and the
  nominated namespace.

Thus, when you have the namespace Ns, the directives using namespace A; and using namespace B make A::fn and B::fn appear in the global namespace, whereas using A::fn; makes fn appear in Ns. The latter declaration "wins" during name lookup.

Body:
Look at this snippet:

namespace A {
int fn();
}
namespace B {
int fn();
}

// namespace Ns {

using namespace A;
using namespace B;
using A::fn;

int z = fn();

// }

This code doesn't compile, as fn() is ambiguous at int z = fn();

If I put using's and z into a namespace (remove the two //), the code compiles. Why is that? What is special about the global namespace?


问:
RSA encryption in python & decrypt in JS
I am totally new in Cryptography. I want to generate RSA key pairs from server side and send it to all of the clients (browsers). But before that I am testing the scenario by simply encrypting data in python and sending in to index.html file via pubnub and trying to decrypt it in JavaScript. The problem is that when I do encryption by;

```<code>random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
enc = enc_data[0]
</code>```

and send the encrypted data enc, it gives me this error:

```<code>UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 2: invalid continuation byte
</code>```

I tried to convert it into

```<code>enc = base64.b64encode(enc_data[0])
</code>```

and it is send with no error. but the JS decrypt method gets None

```<code>  var enc_from_python = $('#input').val();
  console.log("ENCRYPTED data:", enc_from_python);
  var decrypt = new JSEncrypt();
  decrypt.setPrivateKey($('#privkey').val());
  var uncrypted = decrypt.decrypt(enc_from_python);
  console.log(">>>",uncrypted);  //<-- this is None ! why ?
</code>```

Both of the code do enc/dec very well on their own. I have also tried to enc/dec the data in JS with the received key pairs from python and that works well. I guess the problem is with the unicode encoding format of encoded data from Pycrypto which does not match. Could any one tell me what am I missing over here.

Full code for Python:

```<code>import time
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

from Crypto.PublicKey import RSA
from Crypto import Random
import base64

pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'
pnconfig.publish_key = 'demo'
channel = "my_channel"
pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
    if not status.is_error():
        pass  # Message successfully published to specified channel.
    else:
        pass  # Handle message publish error. Check 'category' property to find out possible issue

time.sleep(1)
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
#enc = enc_data[0]
enc = base64.b64encode(enc_data[0])

print enc
#print type(enc_data[0])
print '----ENCRYPTED DATA----'
print  ''
print '----DECRYPTED DATA begin----'
print key.decrypt(enc_data[0])
print '----DECRYPTED DATA end----'

pubnub.publish().channel(channel).message({"data": enc , "private": (key.exportKey()), "public" : (public_key.exportKey())}).async(my_publish_callback)
</code>```

and full JS code is;

```<code><!doctype html>
<html>
  <head>
    <title>JavaScript RSA Encryption</title>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.min.js"></script>
    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.12.0.min.js"></script>
    <script type="text/javascript">

      // Call this code when the page is done loading.
      $(function() {
        pubnub = new PubNub({
          publish_key: 'demo',
          subscribe_key: 'demo'
        });

        pubnub.subscribe({
            channels: ['my_channel']
        });

    pubnub.addListener({
        message: function(message) {
            var msg = message.message;
            console.log("msg:" + JSON.stringify(msg));

             if (msg.private){
                $("#privkey").val(msg.private);
             }

             if(msg.public){
                $("#pubkey").val(msg.public);
             }

             if(msg.data){
                $("#input").val(msg.data);
             }
        }
    })

        // Run a quick encryption/decryption when they click.
        $('#testme').click(function() {
          var enc_from_python = $('#input').val();
          console.log("ENCRYPTED data:", enc_from_python);
          // Decrypt with the private key...
          var decrypt = new JSEncrypt();
          decrypt.setPrivateKey($('#privkey').val());
          var uncrypted = decrypt.decrypt(enc_from_python);
          console.log(">>>",uncrypted);  //<-- this is None ! why ?
          // Now a simple check to see if the round-trip worked.
          if (uncrypted == $('#input').val()) {
            alert('It works!!!');
          }
          else {
            alert('Something went wrong....');
          }
        });
      });
    </script>
  </head>
  <body>
    <label for="privkey">Private Key</label><br/>
    <textarea id="privkey" rows="15" cols="65">   </textarea><br/>
    <label for="pubkey">Public Key</label><br/>
    <textarea id="pubkey" rows="15" cols="65">    </textarea><br/>
    <label for="input">Text to decrypt:</label><br/>
    <textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea><br/>
    <input id="testme" type="button" value="Decrypt Me!!!" /><br/>
  </body>
</html>
</code>```

答:
If you use Crypto.Cipher.PKCS1_v1_5 it is possible.

Here's the python code.

I have only tested with python 3, but I believe it should work the same in python 2 with the __future__ imports.

```<code>from __future__ import unicode_literals, print_function  # python2
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

private_key = """-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANBOMQo9wX55+w1ijEaPoYRP2T4BOjoFv3ma0QWqYYQ8FH0z14Zc
B/jb0j2PWpyNcsUUBovj+yWxQnQohCck64kCAwEAAQJBAL4s9PbNpO9MfFkfBMSS
8zoyEDtcsYUxpDtojbandDpdXfvn5D279QaOVLb1C3DgQTTEmroYB8dbeZBc5YJC
2AECIQDqyUn68ehRcx/EyLMUB1IuckZBWCIApgfn7phgVwSwiQIhAOMgY4bN+xrx
UV15Ian4ZbkME1IbAvDPcWuNGHxdsaMBAiBoz0K/S44yDfp4lj+bCUmeglTqhrVn
JLcSymgrWa02QQIhAMJFvPvcilGkYl1atCHHt3LN0mTjd+N0/OXq3SvblIsBAiAc
8RzaV1GmjMEJxw9vM/tQwQg0kyAPlITMRXnwGA6E0A==
-----END RSA PRIVATE KEY-----"""

rsa = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(rsa)

def encrypt(msg):
    ciphertext = cipher.encrypt(msg.encode('utf8'))
    return base64.b64encode(ciphertext).decode('ascii')

def decrypt(msg):
    ciphertext = base64.b64decode(msg.encode('ascii'))
    plaintext = cipher.decrypt(ciphertext, b'DECRYPTION FAILED')
    return plaintext.decode('utf8')

ciphertext = encrypt('hello stackoverflow!')
print(ciphertext)
plaintext = decrypt(ciphertext)
print(plaintext)
</code>```

Sample ciphertext output from plaintext "hello stackoverflow!":

```<code>tZDRXXcf7ppbVr9JBHQ3+2k3geofl8BdDmLT3HRoqBGvfknY+xISbvy5hYH2alPAUDu2ae4iSYsLyRFBOnzpgw==
</code>```

In javascript, the original code should work. Here's a simplified version to demonstrate that this specific ciphertext and private rsa key works.

const decrypt = () => {
  const privateKey = document.getElementById('private_key').value
  const cipherText = document.getElementById('ciphertext').value
  const decrypt = new JSEncrypt()
  decrypt.setPrivateKey(privateKey)
  const plainText = decrypt.decrypt(cipherText) || 'DECRYPTION FAILED'
  document.getElementById('plaintext').innerHTML = plainText
}
document.querySelector('button').addEventListener('click', decrypt)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.min.js"></script>
<button>Decrypt</button>

<p>plaintext: <em id=plaintext></em> </p>

<label>ciphertext:</label><br>
<textarea cols=64 rows=3 id=ciphertext>
tZDRXXcf7ppbVr9JBHQ3+2k3geofl8BdDmLT3HRoqBGvfknY+xISbvy5hYH2alPAUDu2ae4iSYsLyRFBOnzpgw==
</textarea>
<br>
<label>private key:</label><br>
<textarea cols=64 rows=10 id=private_key>
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANBOMQo9wX55+w1ijEaPoYRP2T4BOjoFv3ma0QWqYYQ8FH0z14Zc
B/jb0j2PWpyNcsUUBovj+yWxQnQohCck64kCAwEAAQJBAL4s9PbNpO9MfFkfBMSS
8zoyEDtcsYUxpDtojbandDpdXfvn5D279QaOVLb1C3DgQTTEmroYB8dbeZBc5YJC
2AECIQDqyUn68ehRcx/EyLMUB1IuckZBWCIApgfn7phgVwSwiQIhAOMgY4bN+xrx
UV15Ian4ZbkME1IbAvDPcWuNGHxdsaMBAiBoz0K/S44yDfp4lj+bCUmeglTqhrVn
JLcSymgrWa02QQIhAMJFvPvcilGkYl1atCHHt3LN0mTjd+N0/OXq3SvblIsBAiAc
8RzaV1GmjMEJxw9vM/tQwQg0kyAPlITMRXnwGA6E0A==
-----END RSA PRIVATE KEY-----
</textarea></code>```

Body:
I am totally new in Cryptography. I want to generate RSA key pairs from server side and send it to all of the clients (browsers). But before that I am testing the scenario by simply encrypting data in python and sending in to index.html file via pubnub and trying to decrypt it in JavaScript. The problem is that when I do encryption by;

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
enc = enc_data[0]

and send the encrypted data enc, it gives me this error:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 2: invalid continuation byte

I tried to convert it into

enc = base64.b64encode(enc_data[0])

and it is send with no error. but the JS decrypt method gets None

  var enc_from_python = $('#input').val();
  console.log("ENCRYPTED data:", enc_from_python);
  var decrypt = new JSEncrypt();
  decrypt.setPrivateKey($('#privkey').val());
  var uncrypted = decrypt.decrypt(enc_from_python);
  console.log(">>>",uncrypted);  //<-- this is None ! why ?

Both of the code do enc/dec very well on their own. I have also tried to enc/dec the data in JS with the received key pairs from python and that works well. I guess the problem is with the unicode encoding format of encoded data from Pycrypto which does not match. Could any one tell me what am I missing over here.

Full code for Python:

import time
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub

from Crypto.PublicKey import RSA
from Crypto import Random
import base64

pnconfig = PNConfiguration()
pnconfig.subscribe_key = 'demo'
pnconfig.publish_key = 'demo'
channel = "my_channel"
pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
    if not status.is_error():
        pass  # Message successfully published to specified channel.
    else:
        pass  # Handle message publish error. Check 'category' property to find out possible issue

time.sleep(1)
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.exportKey() #<--private key
public_key = key.publickey()
print public_key.exportKey() #<--public key
msg = "hello"
enc_data = public_key.encrypt(msg, 32)
print '----ENCRYPTED DATA----'
#enc = enc_data[0]
enc = base64.b64encode(enc_data[0])

print enc
#print type(enc_data[0])
print '----ENCRYPTED DATA----'
print  ''
print '----DECRYPTED DATA begin----'
print key.decrypt(enc_data[0])
print '----DECRYPTED DATA end----'

pubnub.publish().channel(channel).message({"data": enc , "private": (key.exportKey()), "public" : (public_key.exportKey())}).async(my_publish_callback)

and full JS code is;

<!doctype html>

    <title>JavaScript RSA Encryption</title>

    Private Key

    <textarea id="privkey" rows="15" cols="65">   </textarea>

    Public Key

    <textarea id="pubkey" rows="15" cols="65">    </textarea>

    Text to decrypt:

    <textarea id="input" name="input" type="text" rows=4 cols=70>This is a test!</textarea>

    <input id="testme" type="button" value="Decrypt Me!!!" />

Body:
If you use Crypto.Cipher.PKCS1_v1_5 it is possible.

Here's the python code.

I have only tested with python 3, but I believe it should work the same in python 2 with the __future__ imports.

from __future__ import unicode_literals, print_function  # python2
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

private_key = """-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANBOMQo9wX55+w1ijEaPoYRP2T4BOjoFv3ma0QWqYYQ8FH0z14Zc
B/jb0j2PWpyNcsUUBovj+yWxQnQohCck64kCAwEAAQJBAL4s9PbNpO9MfFkfBMSS
8zoyEDtcsYUxpDtojbandDpdXfvn5D279QaOVLb1C3DgQTTEmroYB8dbeZBc5YJC
2AECIQDqyUn68ehRcx/EyLMUB1IuckZBWCIApgfn7phgVwSwiQIhAOMgY4bN+xrx
UV15Ian4ZbkME1IbAvDPcWuNGHxdsaMBAiBoz0K/S44yDfp4lj+bCUmeglTqhrVn
JLcSymgrWa02QQIhAMJFvPvcilGkYl1atCHHt3LN0mTjd+N0/OXq3SvblIsBAiAc
8RzaV1GmjMEJxw9vM/tQwQg0kyAPlITMRXnwGA6E0A==
-----END RSA PRIVATE KEY-----"""

rsa = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(rsa)

def encrypt(msg):
    ciphertext = cipher.encrypt(msg.encode('utf8'))
    return base64.b64encode(ciphertext).decode('ascii')

def decrypt(msg):
    ciphertext = base64.b64decode(msg.encode('ascii'))
    plaintext = cipher.decrypt(ciphertext, b'DECRYPTION FAILED')
    return plaintext.decode('utf8')

ciphertext = encrypt('hello stackoverflow!')
print(ciphertext)
plaintext = decrypt(ciphertext)
print(plaintext)

Sample ciphertext output from plaintext "hello stackoverflow!":

tZDRXXcf7ppbVr9JBHQ3+2k3geofl8BdDmLT3HRoqBGvfknY+xISbvy5hYH2alPAUDu2ae4iSYsLyRFBOnzpgw==

In javascript, the original code should work. Here's a simplified version to demonstrate that this specific ciphertext and private rsa key works.

const decrypt = () => {
  const privateKey = document.getElementById('private_key').value
  const cipherText = document.getElementById('ciphertext').value
  const decrypt = new JSEncrypt()
  decrypt.setPrivateKey(privateKey)
  const plainText = decrypt.decrypt(cipherText) || 'DECRYPTION FAILED'
  document.getElementById('plaintext').innerHTML = plainText
}
document.querySelector('button').addEventListener('click', decrypt)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.min.js"></script>
<button>Decrypt</button>

<p>plaintext: <em id=plaintext></em> </p>

<label>ciphertext:</label><br>
<textarea cols=64 rows=3 id=ciphertext>
tZDRXXcf7ppbVr9JBHQ3+2k3geofl8BdDmLT3HRoqBGvfknY+xISbvy5hYH2alPAUDu2ae4iSYsLyRFBOnzpgw==
</textarea>
<br>
<label>private key:</label><br>
<textarea cols=64 rows=10 id=private_key>
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANBOMQo9wX55+w1ijEaPoYRP2T4BOjoFv3ma0QWqYYQ8FH0z14Zc
B/jb0j2PWpyNcsUUBovj+yWxQnQohCck64kCAwEAAQJBAL4s9PbNpO9MfFkfBMSS
8zoyEDtcsYUxpDtojbandDpdXfvn5D279QaOVLb1C3DgQTTEmroYB8dbeZBc5YJC
2AECIQDqyUn68ehRcx/EyLMUB1IuckZBWCIApgfn7phgVwSwiQIhAOMgY4bN+xrx
UV15Ian4ZbkME1IbAvDPcWuNGHxdsaMBAiBoz0K/S44yDfp4lj+bCUmeglTqhrVn
JLcSymgrWa02QQIhAMJFvPvcilGkYl1atCHHt3LN0mTjd+N0/OXq3SvblIsBAiAc
8RzaV1GmjMEJxw9vM/tQwQg0kyAPlITMRXnwGA6E0A==
-----END RSA PRIVATE KEY-----
</textarea>


问:
C++ std method listing
I am new to C++ and XCode.

I would like to know how I can get a list of available methods from namespace std or any other namespaces #include'ed in a cpp file., in a similar way you would do method scoping in Eclipse (ctrl+space).

Thanks

答: It depends on IDE you use. In Visual Studio and NetBeans ctrl+space works too. Also you can just type :: operator and see what is aviable in current scope.

ContentLicense: CC BY-SA 2.5

Title: C++ std method listing


问:
Create variable of type Map[string]interface{} in gRPC protoc buffer golang
I'm using grpc golang to communicate between client and server application.
Below is the code for protoc buffer.

```<code>syntax = "proto3";
package Trail;

service TrailFunc {
  rpc HelloWorld (Request) returns (Reply) {}
}

// The request message containing the user's name.
message Request {
  map<string,string> inputVar = 1;
}
// The response message containing the greetings
message Reply {
  string outputVar = 1;
}
</code>```

I need to create a field inputVar of type map[string]interface{} inside message data structure instead of map[string]string.
How can I achieve it?
Thanks in advance.

答:
While it gets a little verbose to deal with, the "struct" type in protocol buffers is probably closer to golang's map[string]interface{}

But like interface{}  will take some reflection-style overhead to determine what the actual stored type is.

for example see comment here: https://github.com/golang/protobuf/issues/370

Body:
I'm using grpc golang to communicate between client and server application.
Below is the code for protoc buffer.

syntax = "proto3";
package Trail;

service TrailFunc {
  rpc HelloWorld (Request) returns (Reply) {}
}

// The request message containing the user's name.
message Request {
  map<string,string> inputVar = 1;
}
// The response message containing the greetings
message Reply {
  string outputVar = 1;
}

I need to create a field inputVar of type map[string]interface{} inside message data structure instead of map[string]string.
How can I achieve it?
Thanks in advance.


问:
If NOT EXISTS in SQL not function
I put this in the SQL Query editor of SQL Server 2008 and doesn't work:

```<code>If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
else
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'
</code>```

Error I am getting:

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword
  'else'.

答:
This is highly not desirable.  You should really create tables before you use them.  But, you can do this using dynamic SQL:

```<code>DECLARE @sql NVARCHAR(MAX);

If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'PK01')
BEGIN
    SET @sql = 'CREATE TABLE [dbo].[''PK01''] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX))';
    EXEC sp_executesql @sql;

    SET @sql = '
    INSERT INTO [UBICACIONES].[dbo].[''PK01''] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES (''998'',''kk'',''ll'',0,''pp'')';
    EXEC sp_executesql @sql;
END;
else
BEGIN
    SET @sql = '
    UPDATE [UBICACIONES].[dbo].[''PK01''] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE ''998''  '  ;

    EXEC sp_executesql @sql;
END;
</code>```

Having done all that, I'll repeat.  This seems like a really bad application design.

Title: If NOT EXISTS in SQL not function

Body:
I put this in the SQL Query editor of SQL Server 2008 and doesn't work:

If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
else
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'

Error I am getting:

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword
  'else'.

Body:
This is highly not desirable.  You should really create tables before you use them.  But, you can do this using dynamic SQL:

DECLARE @sql NVARCHAR(MAX);

If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'PK01')
BEGIN
    SET @sql = 'CREATE TABLE [dbo].[''PK01''] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX))';
    EXEC sp_executesql @sql;

    SET @sql = '
    INSERT INTO [UBICACIONES].[dbo].[''PK01''] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES (''998'',''kk'',''ll'',0,''pp'')';
    EXEC sp_executesql @sql;
END;
else
BEGIN
    SET @sql = '
    UPDATE [UBICACIONES].[dbo].[''PK01''] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE ''998''  '  ;

    EXEC sp_executesql @sql;
END;

Having done all that, I'll repeat.  This seems like a really bad application design.


问:
Keystore file Error:Execution failed for task ':app:validateSigningRelease'
I updated android studio and my keystore path must had changed in the process. I have tried the "Choose Existing " button but cannot find what I am looking for.  I do not know where to find it. Would anyone please give me some instruction where to look?

I looked everywhere, I read a other posts with similar problems but debugging and it didn't help because I am attempting a new release.  I have also searched for a software program to help me retrieve the path but I have been unsuccessful with that as well.

Below is the error message I get when I attempt to generate a signed apk.  I did save the apk's from older versions that I had generated, if that helps at all.

The error is as follows after android studio attempts compiling:

```<code>Information:Gradle tasks [:app:assembleRelease]
Error:Execution failed for task ':app:validateSigningRelease'.
> Keystore file C:\Users\aform\OneDrive\Documents\xxxxxxx\xxxx  not found for signing config 'externalOverride'.
Information:BUILD FAILED
</code>```

I am also working on a new PC, but I got the same error of my previous PC as well.  Thanks for any help.

答: You have misplace the path to the key store.jks file. Search for the file on your computer and use the path and everything will work Great!!</p>

Body:
I updated android studio and my keystore path must had changed in the process. I have tried the "Choose Existing " button but cannot find what I am looking for.  I do not know where to find it. Would anyone please give me some instruction where to look?

I looked everywhere, I read a other posts with similar problems but debugging and it didn't help because I am attempting a new release.  I have also searched for a software program to help me retrieve the path but I have been unsuccessful with that as well.

Below is the error message I get when I attempt to generate a signed apk.  I did save the apk's from older versions that I had generated, if that helps at all.

The error is as follows after android studio attempts compiling:

Information:Gradle tasks [:app:assembleRelease]
Error:Execution failed for task ':app:validateSigningRelease'.
> Keystore file C:\Users\aform\OneDrive\Documents\xxxxxxx\xxxx  not found for signing config 'externalOverride'.
Information:BUILD FAILED

I am also working on a new PC, but I got the same error of my previous PC as well.  Thanks for any help.


问:
Do localhost routes work in live environments?
I have a project on localhost at the following route:

http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php/signup

and I currently post data to the application from javascript like this:

```<code>// Centralised, referenced from each javascript file:
var baseUrl = 'http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php';

// The signup post URL is generated like this:
var postUrl: baseUrl + "/signup",
</code>```

This works for all files on localhost.

Questions:

When this project goes live, do these URLs still work?

Is there a cleaner way to write the baseUrl so that it doesn't need to change when the project goes live?

Apologies if this is an obvious one but I currently only work on localhost. Any suggestions welcome.
Symfony 3 application, XAMPP server, OSX.

EDIT:

Using $.ajax to make posts to server.

答:
I'd strongly suggest that you create a virtual host for your projects and set it's webroot to your project's web folder and access your project from there.

Here's a nice tutorial on how to do that in xampp for macOS:
http://jonathannicol.com/blog/2012/03/11/configuring-virtualhosts-in-xampp-on-mac/

i.e: http://myproject.local

This will allow you to access your URLS by simply writing var postURL: "/signup" which then will be treated as http://myproject.local/signup on your local environment or http://myprojectlive.com/signup on your live environment.

With that you'll save yourself a lot of configuration and coding troubles.

Body:
I have a project on localhost at the following route:

http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php/signup

and I currently post data to the application from javascript like this:

// Centralised, referenced from each javascript file:
var baseUrl = 'http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php';

// The signup post URL is generated like this:
var postUrl: baseUrl + "/signup",

This works for all files on localhost.

Questions:

When this project goes live, do these URLs still work?

Is there a cleaner way to write the baseUrl so that it doesn't need to change when the project goes live?

Apologies if this is an obvious one but I currently only work on localhost. Any suggestions welcome.
Symfony 3 application, XAMPP server, OSX.

EDIT:

Using $.ajax to make posts to server.


问:
Moment js - displaying days and hours away from a date
I am working on a project that requires this kind of text response on a date object.

"1 day 7 hours away"
--- it needs to be this way - not "31 hours away" or "1 day away"
-- also I am using moment js - as I am doing language switching between English and German - so I've tapped into the moment.js language locale

```<code>moment.locale('de')
</code>```

I am using moment js - currently I've created a fake date object

```<code>  var futureDate = new Date()
  futureDate.setDate(futureDate.getDate() + 1)// add a day
  futureDate.setHours(7)// add 7 hours
</code>```

when I try and render the moment js

```<code>moment(futureDate).endOf('day').fromNow()
</code>```

it just says "in a day"

How do I modify the moment function to handle 1 day 7 hours -- and maybe re-jig the sentence?

--- code snippet attempt

moment.locale('de') // switch between en and de -- english and german

var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 4 hours

// Results in hours
console.log(moment(futureDate).endOf('day').fromNow()); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script></code>```

code test 2 using difference

moment.locale('de') // switch between en and de -- english and german

var a = moment();
var b = moment(a).add(31, 'hours');

// Results in days
console.log(b.diff(a, 'days'));
console.log(b.diff(a, 'days', true)); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script></code>```

答:
You can use relativeTimeThreshold and relativeTime (key of moment.updateLocale) to customize how moment shows relative time (e.g. the fromNow() output).

In your case, you can:

Adjust threshold to get difference in seconds (see: How to make moment.js show relative time in seconds?).

Create a duration object using moment.duration(Number, String).

Use moment-duration-format plug-in to show duration value in the format you prefer.

Here a live sample:

var momEn = moment().add({d:1, h:7});
var momDe = moment().locale('de').add({d:1, h:7});

console.log(momEn.fromNow()); // in a day
console.log(momDe.fromNow()); // in einem Tag

// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);

// Update relative time
moment.updateLocale('en', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [day] h [hour]');
    },
  }
});

moment.updateLocale('de', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [Tag] h [Uhr]');
    },
  }
});

console.log(momEn.fromNow()); // in 1 day 7 hour
console.log(momDe.fromNow()); // in 1 Tag 7 Uhr```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script></code>```

Unfortunately you have to manually update each locale you need to support.

Body:
I am working on a project that requires this kind of text response on a date object.

"1 day 7 hours away"
--- it needs to be this way - not "31 hours away" or "1 day away"
-- also I am using moment js - as I am doing language switching between English and German - so I've tapped into the moment.js language locale

moment.locale('de')

I am using moment js - currently I've created a fake date object

  var futureDate = new Date()
  futureDate.setDate(futureDate.getDate() + 1)// add a day
  futureDate.setHours(7)// add 7 hours

when I try and render the moment js

moment(futureDate).endOf('day').fromNow()

it just says "in a day"

How do I modify the moment function to handle 1 day 7 hours -- and maybe re-jig the sentence?

--- code snippet attempt

moment.locale('de') // switch between en and de -- english and german

var futureDate = new Date()
futureDate.setDate(futureDate.getDate() + 1)// add a day
futureDate.setHours(7)// add 4 hours

// Results in hours
console.log(moment(futureDate).endOf('day').fromNow());

code test 2 using difference

moment.locale('de') // switch between en and de -- english and german

var a = moment();
var b = moment(a).add(31, 'hours');

// Results in days
console.log(b.diff(a, 'days'));
console.log(b.diff(a, 'days', true));

Body:
You can use relativeTimeThreshold and relativeTime (key of moment.updateLocale) to customize how moment shows relative time (e.g. the fromNow() output).

In your case, you can:

Adjust threshold to get difference in seconds (see: How to make moment.js show relative time in seconds?).

Create a duration object using moment.duration(Number, String).

Use moment-duration-format plug-in to show duration value in the format you prefer.

Here a live sample:

var momEn = moment().add({d:1, h:7});
var momDe = moment().locale('de').add({d:1, h:7});

console.log(momEn.fromNow()); // in a day
console.log(momDe.fromNow()); // in einem Tag

// Change relativeTimeThreshold
moment.relativeTimeThreshold('s', 60*60*24*30*12);

// Update relative time
moment.updateLocale('en', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [day] h [hour]');
    },
  }
});

moment.updateLocale('de', {
  relativeTime : {
    s: function (number, withoutSuffix, key, isFuture){
      return moment.duration(number, 's').format('d [Tag] h [Uhr]');
    },
  }
});

console.log(momEn.fromNow()); // in 1 day 7 hour
console.log(momDe.fromNow()); // in 1 Tag 7 Uhr

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

Unfortunately you have to manually update each locale you need to support.


问:
Best practice for shifting a sequence in a circular manner
I have to implement a kind of an array or sequence or list, which supports the cheapest way of circulated forwarding and back winding of elements. See this example:

```<code>Original sequence: 1 2 3 4 5

Forwarded once: 5 1 2 3 4
Forwarded twice: 4 5 1 2 3
</code>```

Same but opposite is for the back winding. What would be the cheapest and most Scala-style way of implementing this? In Java I could use LinkedList and it would do great... However, I could not find any definite answer for Scala.

Also, it also has to be easy to replace any given element by index, as in LinkedList.

UPDATE:

For the fastest, but not-so-idiomatic variant of algorithm (you know when you need it), refer to the answer of Petr Pudlák!!!

答:
My take on it: </p>

```<code>@tailrec
 def shift(times:Int, data:Array[Int]):Array[Int] = times match {
        case t:Int if(t <= 0) => data;
        case t:Int if(t <= data.length) => shift(0, (data++data.take(times)).drop(times))
        case _ => shift(times % data.length, data);
}
</code>```

Body:
I have to implement a kind of an array or sequence or list, which supports the cheapest way of circulated forwarding and back winding of elements. See this example:

Original sequence: 1 2 3 4 5

Forwarded once: 5 1 2 3 4
Forwarded twice: 4 5 1 2 3

Same but opposite is for the back winding. What would be the cheapest and most Scala-style way of implementing this? In Java I could use LinkedList and it would do great... However, I could not find any definite answer for Scala.

Also, it also has to be easy to replace any given element by index, as in LinkedList.

UPDATE:

For the fastest, but not-so-idiomatic variant of algorithm (you know when you need it), refer to the answer of Petr Pudlák!!!

Body:
My take on it:

@tailrec
 def shift(times:Int, data:Array[Int]):Array[Int] = times match {
        case t:Int if(t <= 0) => data;
        case t:Int if(t <= data.length) => shift(0, (data++data.take(times)).drop(times))
        case _ => shift(times % data.length, data);
}


问:
Comprehensive list of programs on different operating systems
How would I get a list of EVERY program into a text file for windows 95-windows 10. The uninstall programs in control panel doesn't have the version and publisher for the older operating systems, and wmic does not display every program. Even the uninstall registry, which I thought would be my savior, does not list every program. I can see discrepancies between that and the uninstall programs tab. Powershell and the like are off the table since it is relatively new.</p>

答:
The registry uninstall registration requirements in the 90's was just the display name and the command to start the uninstallation. Windows 2000 added support for more values and exposed them in the new UI but they were still optional. In recent years a couple of them became a requirement to pass the Windows Logo tests but they are still optional for non-certified applications so the uninstall key is not guaranteed to contain version/publisher information for every entry. Portable applications are not listed in the registry so if you need a inventory of everything then you need to inspect all exe files and ignore the registry.

Supporting everything back to Win95 RTM is going to be tough since you have nothing except batch files as a scripting option. VBScript is a optional component that normally gets installed with IE 4 and I don't even remember if it is possible to get Powershell on these systems.

I don't think it is possible to extract the version information with a simple batch file, you probably need the help of a 3rd-party tool. The issue with 3rd-party tools is that a lot of them depend on the Microsoft CRT run-time .DLLs and Windows 95 RTM does not have them out of the box, not even msvcrt.dll.

If you can raise your requirement for Win95 to have Windows Scripting Host installed (redistributable or part of IE4) then you could write a VB/Jscript file that uses the FileSystemObject to both walk the entire directory tree on every drive and to get version information from .exe files.

If that is unacceptable then you need to try to find a tool that can extract version information. There is a Microsoft tool named filever.exe listed here but I don't know if it works on Win95 and a NirSoft tool here but I'm not sure if it supports stdout redirection from the commandline (but it is open source so you could fix that if needed). Even if you find a suitable tool you would still need to walk the directory tree looking for .exe files and that is not going to be fun when you are limited to command.com and its DOS compatible batch handling.

My recommendation is to write a new application. I can't recommend writing it in a .NET language because you would be dealing with versions 1-4 and it is not installed on XP and older by default.

The way I see it, you have 3 options if you are writing it yourself: Visual Basic 6, Delphi (something old, v3 or older perhaps) or C/C++.

For C/C++ any version of Microsoft Visual C++ or MinGW/GCC will do but the older the better and you must not link to or use any C run-time library stuff (you might get away with static linking with MinGW but not recent versions of Visual Studio). If I was doing this I would use Visual Studio 6 or 2003 and build with /Zl & /NODEFAULTLIB. There are multiple small standalone CRT libraries if you need them. If you use any recent version of Visual Studio you will manually have to hex-edit the file to make it run on anything older than XP.

The actual implementation needs to call FindFirstFileA (and friends) on Windows 95/98/ME and FindFirstFileW on other systems to walk the directory tree and GetFileVersionInfoA/W (and friends) to get version info.

If you are feeling fancy you could perhaps filter out files in %WinDir% signed by Microsoft. Good luck...


问:
Change element ID using Javascript?

  Content

```

How would I change the ID of this div using Javascript?

答:
Found this on the first result on a Google search:

```<code>document.getElementById("originalDivId").setAttribute("id", "newDivId");
</code>```

getElementById does exactly what it says, it obtains the information of an element with the Id specified. setAttribute changes a HTML element's attribute, that is the stuff inside of the HTML tags (e.g. class="", id="", style="", etc).

Title: Change element ID using Javascript?

Body:
  Content

How would I change the ID of this div using Javascript?

Body:
Found this on the first result on a Google search:

document.getElementById("originalDivId").setAttribute("id", "newDivId");

getElementById does exactly what it says, it obtains the information of an element with the Id specified. setAttribute changes a HTML element's attribute, that is the stuff inside of the HTML tags (e.g. class="", id="", style="", etc).


问:
Compare the results of a loop one by one
I have a mysql database with numbers in example: 0655456246 or 0641698646 ...
I will search these results in my database with the following script:

```<code>    $result6=mysqli_query($conn2, "SELECT number FROM sms_stop");
    while ($check2=mysqli_fetch_assoc($result6))
    {
        $checknumber = implode(str_replace("+33", "0", $check2));
    }
</code>```

I would now like to compare the results 1 by 1 to see if it corresponds with what the user put in a form field but the problem is that on the 2 numbers of the example the comparison works with the 0641698646 but Not with the 0655456246. I do not understand why .... I just want that if the user puts one of the numbers already present in the database it must refuse the access to him.

$Recipient => is the number entered by the user in the form

```<code>        if ($Recipient != $checknumber)
        {
          ...
        }

        else
        {
            echo '<SCRIPT LANGUAGE="JavaScript">alert("ERROR")</script>';
        }
</code>```

Thank you for your help :)

答:
From the code you posted it looks like you are doing your check after the mysqli_fetch_assoc loop, which means $checknumber will only have the last value retrieved from the database. Try something like this :</p>

```<code>$found=false;
$result6=mysqli_query($conn2, "SELECT number FROM sms_stop");
while ($check2=mysqli_fetch_assoc($result6))
{
  $checknumber = implode(str_replace("+33", "0", $check2));
  if ($checknumber==$Recipient)
     $found=true;
}
if ($found==false)
{
...
}
else
echo '<SCRIPT LANGUAGE="JavaScript">alert("ERROR")</script>';
</code>```

Body:
I have a mysql database with numbers in example: 0655456246 or 0641698646 ...
I will search these results in my database with the following script:

    $result6=mysqli_query($conn2, "SELECT number FROM sms_stop");
    while ($check2=mysqli_fetch_assoc($result6))
    {
        $checknumber = implode(str_replace("+33", "0", $check2));
    }

I would now like to compare the results 1 by 1 to see if it corresponds with what the user put in a form field but the problem is that on the 2 numbers of the example the comparison works with the 0641698646 but Not with the 0655456246. I do not understand why .... I just want that if the user puts one of the numbers already present in the database it must refuse the access to him.

$Recipient => is the number entered by the user in the form

        if ($Recipient != $checknumber)
        {
          ...
        }

        else
        {
            echo '';
        }

Thank you for your help :)

Body:
From the code you posted it looks like you are doing your check after the mysqli_fetch_assoc loop, which means $checknumber will only have the last value retrieved from the database. Try something like this :

$found=false;
$result6=mysqli_query($conn2, "SELECT number FROM sms_stop");
while ($check2=mysqli_fetch_assoc($result6))
{
  $checknumber = implode(str_replace("+33", "0", $check2));
  if ($checknumber==$Recipient)
     $found=true;
}
if ($found==false)
{
...
}
else
echo '<SCRIPT LANGUAGE="JavaScript">alert("ERROR")</script>';


问:
Don't display class name in Visual Studio Test Explorer
I am using Xunit in my vs project. In my Test explorer, I see this:

```<code>Fully.Qualified.Namespace.ClassName.TestName1
Fully.Qualified.Namespace.ClassName.TestName2
etc.
</code>```

I would much rather just see this:

```<code>TestName1
TestName2
etc.
</code>```

or even this (2nd best, but still a big improvement):

```<code>ClassName.TestName1
ClassName.TestName2
etc.
</code>```

Is that possible? If so, how?

答:
add a file to the root directory of your test project named xunit.runner.json
with the following content:

```<code>{
  "methodDisplay": "method"
}
</code>```

Body:
I am using Xunit in my vs project. In my Test explorer, I see this:

Fully.Qualified.Namespace.ClassName.TestName1
Fully.Qualified.Namespace.ClassName.TestName2
etc.

I would much rather just see this:

TestName1
TestName2
etc.

or even this (2nd best, but still a big improvement):

ClassName.TestName1
ClassName.TestName2
etc.

Is that possible? If so, how?

Body:
add a file to the root directory of your test project named xunit.runner.json
with the following content:

{
  "methodDisplay": "method"
}


问:
PHP replace string with ****@mail.com
how can convert ?

Is there a quick and easy way to replace every letter of a word with an ****@mail.com

For example

```<code>$mail = 'stack@mail.com';
echo $mail;
output -> s****@mail.com
</code>```

Thanks for answer me.

答:
Use explode() and str_repeat()</p>

```<code>$a = explode("@", $mail);
$mail = str_repeat("*", strlen($a[0]))."@".$a[1];
</code>```

Title: PHP replace string with ****@mail.com

Body:
how can convert ?

Is there a quick and easy way to replace every letter of a word with an ****@mail.com

For example

$mail = 'stack@mail.com';
echo $mail;
output -> s****@mail.com

Thanks for answer me.

Body:
Use explode() and str_repeat()

$a = explode("@", $mail);
$mail = str_repeat("*", strlen($a[0]))."@".$a[1];


问:
PrimeNG Calendar - can't disable days or dates
I am using Angular 2 and trying to get a PrimeNG calendar datepicker to allow me to disable specific days (holidays) as well as weekends.

Their documentation says I should be able to do both and gives an example which I've tried to implement.  However, no dates ever get disabled!

In my component template:

```<code><p-calendar [(ngModel)]="requestedShipDate" name="requestedShipDate"
                      [disabledDates]="restrictedShipDates" [disabledDays]="[0,6]"></p-calendar>
</code>```

In my component class (with some sample initialization code that I cannot get to work):

```<code>export class OrdersNewComponent implements OnInit {
  requestedShipDate: Date;
  restrictedShipDates: Array<Date>;

  ngOnInit() {
    let today = new Date();
    let invalidDate = new Date();
    invalidDate.setDate(today.getDate() - 1);
    this.restrictedShipDates = [today,invalidDate];
  }
}
</code>```

Is there not a better angular 2 calendar datepicker out there that allows disabling specific dates?  (not just minDate and maxDate)? This is the only one I've found with this feature and it of course doesn't work for me!

And in case it is a issue with some incompatabile packages or something, here are the dependencies from my project.json:

```<code>"dependencies": {
"@angular/common": "2.4.2",
"@angular/compiler": "2.4.2",
"@angular/core": "2.4.2",
"@angular/flex-layout": "2.0.0-beta.3",
"@angular/forms": "2.4.2",
"@angular/http": "2.4.2",
"@angular/material": "2.0.0-beta.2",
"@angular/platform-browser": "2.4.2",
"@angular/platform-browser-dynamic": "2.4.2",
"@angular/router": "3.4.2",
"angular2-select": "1.0.0-alpha.12",
"core-js": "2.4.1",
"hammerjs": "2.0.8",
"jsrsasign": "6.1.1",
"jwt-decode": "2.1.0",
"lodash": "4.16.4",
"material-design-lite": "1.2.1",
"moment": "2.15.1",
"ng2-pagination": "0.5.1",
"ng2-translate": "4.0.0",
"normalize.css": "4.2.0",
"primeng": "1.1.4",
"rxjs": "5.0.3",
"ts-helpers": "1.1.1",
"xmljson": "0.2.0",
"zone.js": "0.7.4"
},
  "devDependencies": {
    "@angular/compiler-cli": "2.4.2",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "4.14.37",
    "@types/node": "6.0.42",
    "angular-cli": "1.0.0-beta.25.5",
    "angular2-perfect-scrollbar": "^2.0.6",
    "codelyzer": "^2.0.0-beta.4",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-remap-istanbul": "0.2.1",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.3.0",
    "typescript": "2.0.10"
  }
</code>```

答:
According to the documentation, it appears you can disable specific dates and/or days like so:

```<code><p-calendar [(ngModel)]="dateValue" [disabledDates]="invalidDates" [disabledDays]="[0,6}" readonlyInput="readonlyInput">></p-calendar>
</code>```

EDIT

Reread the question. My bad! Although is your formatting correct, or is the documentation wrong? Your disabledDays is formatted like this: [disabledDays]="[0,6]", and theirs is like this: [disabledDays]="[0,6}". Yours makes sense reflexively, but could that be a possible error?

Hope it helps!

Additional Source

Body:
I am using Angular 2 and trying to get a PrimeNG calendar datepicker to allow me to disable specific days (holidays) as well as weekends.

Their documentation says I should be able to do both and gives an example which I've tried to implement.  However, no dates ever get disabled!

In my component template:

In my component class (with some sample initialization code that I cannot get to work):

export class OrdersNewComponent implements OnInit {
  requestedShipDate: Date;
  restrictedShipDates: Array<Date>;

  ngOnInit() {
    let today = new Date();
    let invalidDate = new Date();
    invalidDate.setDate(today.getDate() - 1);
    this.restrictedShipDates = [today,invalidDate];
  }
}

Is there not a better angular 2 calendar datepicker out there that allows disabling specific dates?  (not just minDate and maxDate)? This is the only one I've found with this feature and it of course doesn't work for me!

And in case it is a issue with some incompatabile packages or something, here are the dependencies from my project.json:

"dependencies": {
"@angular/common": "2.4.2",
"@angular/compiler": "2.4.2",
"@angular/core": "2.4.2",
"@angular/flex-layout": "2.0.0-beta.3",
"@angular/forms": "2.4.2",
"@angular/http": "2.4.2",
"@angular/material": "2.0.0-beta.2",
"@angular/platform-browser": "2.4.2",
"@angular/platform-browser-dynamic": "2.4.2",
"@angular/router": "3.4.2",
"angular2-select": "1.0.0-alpha.12",
"core-js": "2.4.1",
"hammerjs": "2.0.8",
"jsrsasign": "6.1.1",
"jwt-decode": "2.1.0",
"lodash": "4.16.4",
"material-design-lite": "1.2.1",
"moment": "2.15.1",
"ng2-pagination": "0.5.1",
"ng2-translate": "4.0.0",
"normalize.css": "4.2.0",
"primeng": "1.1.4",
"rxjs": "5.0.3",
"ts-helpers": "1.1.1",
"xmljson": "0.2.0",
"zone.js": "0.7.4"
},
  "devDependencies": {
    "@angular/compiler-cli": "2.4.2",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "4.14.37",
    "@types/node": "6.0.42",
    "angular-cli": "1.0.0-beta.25.5",
    "angular2-perfect-scrollbar": "^2.0.6",
    "codelyzer": "^2.0.0-beta.4",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "2.0.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.0.2",
    "karma-remap-istanbul": "0.2.1",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.3.0",
    "typescript": "2.0.10"
  }

Body:
According to the documentation, it appears you can disable specific dates and/or days like so:

<p-calendar [(ngModel)]="dateValue" [disabledDates]="invalidDates" [disabledDays]="[0,6}" readonlyInput="readonlyInput">></p-calendar>

EDIT

Reread the question. My bad! Although is your formatting correct, or is the documentation wrong? Your disabledDays is formatted like this: [disabledDays]="[0,6]", and theirs is like this: [disabledDays]="[0,6}". Yours makes sense reflexively, but could that be a possible error?

Hope it helps!

Additional Source


问:
I cannot find any way to convert multiple jpg or png to gif in vb.net using ffmpeg
Is there anyway i can get multiples png or jpg images to gif using ffmpeg in vb.net
I have start a new application to capture certain frames from a video but now i want to get all the frames extracted in gif image using ffmpeg.
This is my code so far:
I have in fact all ready try like this but not succeed
I have made some changes and i get the gif file but in empty state
This is my code so far</p>

```<code>Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Public Class Form1
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -filter:v fps=1/15 C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Label3.Text = "cmd" + "/k ffmpeg.exe -i " + TextBox1.Text + " -filter:v fps=1/15 C:\avi to gif converter\out%02d.jpg"
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -framerate 1/5 -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.gif "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")

    'IO.Directory.Delete(tempdir, True)
End Sub
End Class
</code>```

答:
In fact i just finish the code i finally discovery what its wrong.
This is the working code to convert mp4 to gif
So i have decided to convert first the images to mp4 and the convert the mp4 to gif

I have try to move the file to other location but wen i try to move the file to a different location its say i can not find the directory but the directory exist.
what i have miss here
this is the code

```<code>Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Windows.Forms
Imports System.Net

Public Class Form1
Dim fpsx = 10
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()
    TextBox2.Text = fpsx

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    fpsx = TextBox2.Text
    TextBox2.Text = fpsx

    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -framerate 5/1 -filter:v fps=" + TextBox2.Text + " C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        'TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        TextBox1.Text = System.IO.Path.GetDirectoryName(OpenFileDialog1.FileName)
        Dim newdialog As New OpenFileDialog()
        If newdialog.ShowDialog() = DialogResult.OK Then
            System.IO.File.Copy(newdialog.FileName, tempdir)
            MessageBox.Show(System.IO.Path.GetDirectoryName(newdialog.FileName) & "\" & System.IO.Path.GetFileName(newdialog.FileName))
        End If
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -i C:\avitogifconverter\out%02d.jpg -r 10 C:\avitogifconverter\out.gif "
    'args = " -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.mp4 "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")
    Dim directoryName As String = "C:\avitogifconverter\"
    For Each deleteFile In Directory.GetFiles(directoryName, "*.jpg", SearchOption.TopDirectoryOnly)
        File.Delete(deleteFile)
    Next

    'IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Form2.Show()

End Sub
End Class
</code>```

Body:
Is there anyway i can get multiples png or jpg images to gif using ffmpeg in vb.net
I have start a new application to capture certain frames from a video but now i want to get all the frames extracted in gif image using ffmpeg.
This is my code so far:
I have in fact all ready try like this but not succeed
I have made some changes and i get the gif file but in empty state
This is my code so far

Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Public Class Form1
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -filter:v fps=1/15 C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Label3.Text = "cmd" + "/k ffmpeg.exe -i " + TextBox1.Text + " -filter:v fps=1/15 C:\avi to gif converter\out%02d.jpg"
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -framerate 1/5 -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.gif "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")

    'IO.Directory.Delete(tempdir, True)
End Sub
End Class

Body:
In fact i just finish the code i finally discovery what its wrong.
This is the working code to convert mp4 to gif
So i have decided to convert first the images to mp4 and the convert the mp4 to gif

I have try to move the file to other location but wen i try to move the file to a different location its say i can not find the directory but the directory exist.
what i have miss here
this is the code

Imports System.Diagnostics
Imports System.ComponentModel
Imports System
Imports System.IO
Imports System.IO.Compression
Imports System.Windows.Forms
Imports System.Net

Public Class Form1
Dim fpsx = 10
Dim video = ""
Dim startInfo As New ProcessStartInfo("ffmpeg.exe")
Dim frame As Long 'individual frames
Dim tempdir As String = "C:\avitogifconverter\" ' images temp directory
Dim DestPath As String = "C:\avitogifconverter\"
Public Declare Auto Function FindWindowNullClassName Lib "user32.dll" Alias "FindWindow" (ByVal lpClassname As Integer, ByVal lpWindownName As String) As Integer
Dim Counter As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    My.Computer.FileSystem.CreateDirectory(tempdir)
    TextBox1.Text = "exp:-->video.avi or webm or flv"
    TextBox1.Clear()
    TextBox2.Text = fpsx

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    fpsx = TextBox2.Text
    TextBox2.Text = fpsx

    Dim p As Process = Process.Start("cmd", "/k ffmpeg.exe -i " + TextBox1.Text + " -framerate 5/1 -filter:v fps=" + TextBox2.Text + " C:\avitogifconverter\out%02d.jpg")
    p.WaitForExit()

    If p.HasExited Then
        MsgBox("The Extraction Are Finish...")
    End If

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs)

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    If (OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
        'TextBox1.Text = OpenFileDialog1.FileName
        'TextBox1.Text = System.IO.Path.GetFileName(OpenFileDialog1.FileName)
        TextBox1.Text = System.IO.Path.GetDirectoryName(OpenFileDialog1.FileName)
        Dim newdialog As New OpenFileDialog()
        If newdialog.ShowDialog() = DialogResult.OK Then
            System.IO.File.Copy(newdialog.FileName, tempdir)
            MessageBox.Show(System.IO.Path.GetDirectoryName(newdialog.FileName) & "\" & System.IO.Path.GetFileName(newdialog.FileName))
        End If
    End If
    If TextBox1.Text = Nothing Then
        Return
    End If
    If TextBox1.Text <> Nothing Then
        'My.Computer.FileSystem.CopyFile(TextBox1.Text, DestPath)
    End If

End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim args As String 'declare args
    args = " -i C:\avitogifconverter\out%02d.jpg -r 10 C:\avitogifconverter\out.gif "
    'args = " -i C:\avitogifconverter\out%02d.jpg -c:v libx264 -r 30 -pix_fmt yuv420p C:\avitogifconverter\out.mp4 "
    Dim proc As New Process
    Dim proci As New ProcessStartInfo
    proci.FileName = My.Application.Info.DirectoryPath & "\ffmpeg.exe"
    proci.Arguments = args
    proci.WindowStyle = ProcessWindowStyle.Hidden
    proci.CreateNoWindow = True
    proci.UseShellExecute = False
    proc.StartInfo = proci
    proc.Start()
    Do Until proc.HasExited = True
        Me.Text = "Saving"
    Loop
    Me.Text = "your video done"

    MsgBox("Done")
    Dim directoryName As String = "C:\avitogifconverter\"
    For Each deleteFile In Directory.GetFiles(directoryName, "*.jpg", SearchOption.TopDirectoryOnly)
        File.Delete(deleteFile)
    Next

    'IO.Directory.Delete(tempdir, True)
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    Form2.Show()

End Sub
End Class


问:
Install rgl on R-Server Ubuntu
I want to to install rgl on R-Server, running on Ubuntu.
At the bas prompt I installed

```<code>sudo apt-get build-dep r-cran-rgl
</code>```

Reading package lists... Done Building dependency tree Reading state
  information... Done The following extra packages will be installed:

  libglu1-mesa The following NEW packages will be installed:

  libglu1-mesa r-cran-rgl 0 upgraded, 2 newly installed, 0 to remove and
  0 not upgraded. Need to get 1,645 kB of archives. After this
  operation, 3,875 kB of additional disk space will be used. Do you want
  to continue? [Y/n] Y Get:1 http://archive.ubuntu.com/ubuntu/
  trusty/main libglu1-mesa amd64 9.0.0-2 [195 kB] Get:2
  http://archive.ubuntu.com/ubuntu/ trusty/universe r-cran-rgl amd64
  0.93.996-1 [1,450 kB] Fetched 1,645 kB in 1s (1,047 kB/s) Selecting previously unselected package libglu1-mesa:amd64. (Reading database
  ... 55586 files and directories currently installed.) Preparing to
  unpack .../libglu1-mesa_9.0.0-2_amd64.deb ... Unpacking
  libglu1-mesa:amd64 (9.0.0-2) ... Selecting previously unselected
  package r-cran-rgl. Preparing to unpack
  .../r-cran-rgl_0.93.996-1_amd64.deb ... Unpacking r-cran-rgl
  (0.93.996-1) ... Setting up libglu1-mesa:amd64 (9.0.0-2) ... Setting
  up r-cran-rgl (0.93.996-1) ... Processing triggers for libc-bin
  (2.19-0ubuntu6.6) ...

Thats it. The three points at the end do not indicate that there was more to copy. Then I logged in into R-Server and tried to run

```<code>install.packages("rgl", repos="http://R-Forge.R-project.org")
</code>```

which resulted in an error, namely:

```<code>....
configure: using libpng-config
configure: using libpng dynamic linkage
checking for X... libraries , headers
checking GL/gl.h usability... no
checking GL/gl.h presence... no
checking for GL/gl.h... no
checking GL/glu.h usability... no
checking GL/glu.h presence... no
checking for GL/glu.h... no
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/clambio/R/x86_64-pc-linux-gnu-library/3.2/rgl’
Warning in install.packages :
  installation of package ‘rgl’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpT5iyrb/downloaded_packages’
</code>```

Any ideas what is going wrong?!

答:
I solved this problem by installing

```<code>sudo apt-get install mesa-common-dev libglu1-mesa-dev
</code>```

then install in R again:

```<code>install.packages("rgl")
</code>```

Title: Install rgl on R-Server Ubuntu

Body:
I want to to install rgl on R-Server, running on Ubuntu.
At the bas prompt I installed

sudo apt-get build-dep r-cran-rgl

Reading package lists... Done Building dependency tree Reading state
  information... Done The following extra packages will be installed:

  libglu1-mesa The following NEW packages will be installed:

  libglu1-mesa r-cran-rgl 0 upgraded, 2 newly installed, 0 to remove and
  0 not upgraded. Need to get 1,645 kB of archives. After this
  operation, 3,875 kB of additional disk space will be used. Do you want
  to continue? [Y/n] Y Get:1 http://archive.ubuntu.com/ubuntu/
  trusty/main libglu1-mesa amd64 9.0.0-2 [195 kB] Get:2
  http://archive.ubuntu.com/ubuntu/ trusty/universe r-cran-rgl amd64
  0.93.996-1 [1,450 kB] Fetched 1,645 kB in 1s (1,047 kB/s) Selecting previously unselected package libglu1-mesa:amd64. (Reading database
  ... 55586 files and directories currently installed.) Preparing to
  unpack .../libglu1-mesa_9.0.0-2_amd64.deb ... Unpacking
  libglu1-mesa:amd64 (9.0.0-2) ... Selecting previously unselected
  package r-cran-rgl. Preparing to unpack
  .../r-cran-rgl_0.93.996-1_amd64.deb ... Unpacking r-cran-rgl
  (0.93.996-1) ... Setting up libglu1-mesa:amd64 (9.0.0-2) ... Setting
  up r-cran-rgl (0.93.996-1) ... Processing triggers for libc-bin
  (2.19-0ubuntu6.6) ...

Thats it. The three points at the end do not indicate that there was more to copy. Then I logged in into R-Server and tried to run

install.packages("rgl", repos="http://R-Forge.R-project.org")

which resulted in an error, namely:

....
configure: using libpng-config
configure: using libpng dynamic linkage
checking for X... libraries , headers
checking GL/gl.h usability... no
checking GL/gl.h presence... no
checking for GL/gl.h... no
checking GL/glu.h usability... no
checking GL/glu.h presence... no
checking for GL/glu.h... no
configure: error: missing required header GL/gl.h
ERROR: configuration failed for package ‘rgl’
* removing ‘/home/clambio/R/x86_64-pc-linux-gnu-library/3.2/rgl’
Warning in install.packages :
  installation of package ‘rgl’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/RtmpT5iyrb/downloaded_packages’

Any ideas what is going wrong?!

Body:
I solved this problem by installing

sudo apt-get install mesa-common-dev libglu1-mesa-dev

then install in R again:

install.packages("rgl")

ContentLicense: CC BY-SA 4.0


问:
Python Beautiful Soup cannot find table
I have a web scraping code that cannot find a table.
My code looks like:

```<code>site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {"class":"table mm-mobile-table table-striped
table-bordered"})
</code>```

The tables HTML looks like:

```<code><table class="table mm-mobile-table table-striped table-bordered" data-
icons-prefix="fa" data-icons="{"columns":"fa-th"}" data-
striped="true" data-toggle="table">
</code>```

but for some reason my code always returns table as none. I do not know why but any help would be appreciated. Thanks.

答:
The problem is that there is incorrect markup making large sections of the code commented out i.e

```<code><!-->.
</code>```

the fix was to replace these elements then parse the HTML.

```<code>from urllib2 import urlopen, Request
from bs4 import BeautifulSoup
site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
res = urlopen(req)
rawpage = res.read()
page = rawpage.replace("<!-->", "")
soup = BeautifulSoup(page, "html.parser")
table = soup.find("table", {"class":"table mm-mobile-table table-striped table-bordered"})
print (table)
</code>```

Tested on Python 2.7.12

```<code>from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
res = urlopen(req)
rawpage = res.read().decode("utf-8")
page = rawpage.replace('<!-->', '')
soup = BeautifulSoup(page, "html.parser")
table = soup.find("table", {"class":"table mm-mobile-table table-striped table-bordered"})
print (table)
</code>```

Tested on Python 3.5.2

Gives:

```<code> <table class="table mm-mobile-table table-striped table-bordered" data-icons='{"columns":"fa-th"}' data-icons-prefix="fa" data-striped="true" data-toggle="table"><thead><tr><th class="show-td" data-field="symbol">Symbol</th> <th class="show-td" data-field="name">Name</th> <th class="show-td" data-field="aum">AUM</th> <th class="show-td" data-field="avg-volume">Avg Volume</th></tr></thead><tbody><tr><td class="show-td" data-th="Symbol"><a href="/etf/SPY/">SPY</a></td> <td class="show-td" data-th="Name"><a href="/etf/SPY/">SPDR S&P 500 ETF</a></td> <td class="show-td" data-th="AUM">$236,737,519.17</td> <td class="show-td" data-th="Avg Volume">73,039,883</td></tr> <tr><td class="show-td" data-th="Symbol"><a href="/etf/IVV/">IVV</a></td> <td class="show-td" data-th="Name"><a href="/etf/IVV/">iShares Core S&P 500 ETF</a></td> <td class="show-td" data-th="AUM">$115,791,603.10</td> <td class="show-td" data-th="Avg Volume">3,502,931</td></tr> ...
</code>```

Title: Python Beautiful Soup cannot find table

Body:
I have a web scraping code that cannot find a table.
My code looks like:

site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page)
table = soup.find('table', {"class":"table mm-mobile-table table-striped
table-bordered"})

The tables HTML looks like:

but for some reason my code always returns table as none. I do not know why but any help would be appreciated. Thanks.

Body:
The problem is that there is incorrect markup making large sections of the code commented out i.e

<!-->.

the fix was to replace these elements then parse the HTML.

from urllib2 import urlopen, Request
from bs4 import BeautifulSoup
site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
res = urlopen(req)
rawpage = res.read()
page = rawpage.replace("<!-->", "")
soup = BeautifulSoup(page, "html.parser")
table = soup.find("table", {"class":"table mm-mobile-table table-striped table-bordered"})
print (table)

Tested on Python 2.7.12

from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
site = 'http://etfdb.com/compare/market-cap/'
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(site, headers=hdr)
res = urlopen(req)
rawpage = res.read().decode("utf-8")
page = rawpage.replace('<!-->', '')
soup = BeautifulSoup(page, "html.parser")
table = soup.find("table", {"class":"table mm-mobile-table table-striped table-bordered"})
print (table)

Tested on Python 3.5.2

Gives:

 <table class="table mm-mobile-table table-striped table-bordered" data-icons='{"columns":"fa-th"}' data-icons-prefix="fa" data-striped="true" data-toggle="table"><thead><tr><th class="show-td" data-field="symbol">Symbol</th> <th class="show-td" data-field="name">Name</th> <th class="show-td" data-field="aum">AUM</th> <th class="show-td" data-field="avg-volume">Avg Volume</th></tr></thead><tbody><tr><td class="show-td" data-th="Symbol"><a href="/etf/SPY/">SPY</a></td> <td class="show-td" data-th="Name"><a href="/etf/SPY/">SPDR S&amp;P 500 ETF</a></td> <td class="show-td" data-th="AUM">$236,737,519.17</td> <td class="show-td" data-th="Avg Volume">73,039,883</td></tr> <tr><td class="show-td" data-th="Symbol"><a href="/etf/IVV/">IVV</a></td> <td class="show-td" data-th="Name"><a href="/etf/IVV/">iShares Core S&amp;P 500 ETF</a></td> <td class="show-td" data-th="AUM">$115,791,603.10</td> <td class="show-td" data-th="Avg Volume">3,502,931</td></tr> ...