问:
How to have my google oauth only try and authorize the app on a certain route
I have a google Oauth that will make the user authorize when a user goes to my webpage, however I only want them to have to authorize the app so that I can get their access and refresh tokens when they go to certain  page to enter a google api information.Google is making them authorize no matter what route they are on any ideas on how to stop this.Ruby wont let me any of this in a route.</p>

```<code>def user_credentials
# Build a per-request oauth credential based on token stored in
session
# which allows us to use a shared API client.
@authorization ||= (
auth = settings.authorization.dup
auth.redirect_uri = to('/oauth2callback')
auth.update_token!(session)
auth
)
end

configure do

 Google::Apis::ClientOptions.default.application_name = 'Get Login
 info for Google Ad Exchange'
 Google::Apis::ClientOptions.default.application_version = '1.0.0'

 client_secrets = Google::APIClient::ClientSecrets.load
 authorization = client_secrets.to_authorization
 authorization.scope =
 'https://www.googleapis.com/auth/adexchange.seller.readonly'

  set :authorization, authorization
end

before do
# Ensure user has authorized the app
unless user_credentials.access_token || request.path_info =~
/^\/oauth2/
redirect to('/oauth2authorize')
end
end

 after do
 # Serialize the access/refresh token to the session and credential
 store.
# We could potentially need to pull back the client_id and
client_secret as well and add them to the dynamo database.

#   session[:client_id] = user_credentials.client_id
#   session[:client_secret] = user_credentials.client_secret
    session[:access_token] = user_credentials.access_token
    session[:refresh_token] = user_credentials.refresh_token
    session[:expires_in] = user_credentials.expires_in
    session[:issued_at] = user_credentials.issued_at

  end

get '/oauth2authorize' do
 # Request authorization
 redirect user_credentials.authorization_uri.to_s, 303
 end

get '/oauth2callback' do
 # Exchange token
 user_credentials.code = params[:code] if params[:code]
 user_credentials.fetch_access_token!
 redirect to('/')

  end
</code>```

答:
Figured it out, meant to post way earlier but had an alert on this post so i figured id update to what we did to ake it work.</p>

```<code> get '/googleauth' do
   salesforce_username = params[:salesforce_username] || ''
   unless session.has_key?(:credentials)
   redirect to('/oauth2callback')
 end
   client_opts = JSON.parse(session[:credentials])
   auth_client = Signet::OAuth2::Client.new(client_opts)
   redirect to('/googleadx')
 end

 get '/oauth2callback' do
  client_secrets = Google::APIClient::ClientSecrets.load
  auth_client = client_secrets.to_authorization
  auth_client.update!(
  :scope => 'https://www.googleapis.com/auth/adexchange.seller.readonly',
:redirect_uri => url('/oauth2callback'))
 if request['code'] == nil
  auth_uri = auth_client.authorization_uri.to_s
  redirect to(auth_uri)
 else
  auth_client.code = request['code']
  auth_client.fetch_access_token!
  session[:access_token] = auth_client.access_token
  session[:refresh_token] = auth_client.refresh_token
  session[:expires_in] = auth_client.expires_in
  session[:issued_at] = auth_client.issued_at
  auth_client.client_secret = nil
  session[:credentials] = auth_client.to_json
  redirect to('/googleadx')
end
end

get '/googleadx' do

# configure()

if params[:username]
    successmessage = params[:username] + "'s credentials added successfully."
else
    message = ''
end

salesforce_username = session[:salesforce_username] || ''
access_token = session[:access_token]
refresh_token = session[:refresh_token]
googleDollarLimit = ''

erb :googleadx, locals: {message: message, successmessage: successmessage, salesforce_username: salesforce_username, access_token: access_token, refresh_token: refresh_token, googleDollarLimit: googleDollarLimit}
end
</code>```

Body:
I have a google Oauth that will make the user authorize when a user goes to my webpage, however I only want them to have to authorize the app so that I can get their access and refresh tokens when they go to certain  page to enter a google api information.Google is making them authorize no matter what route they are on any ideas on how to stop this.Ruby wont let me any of this in a route.

def user_credentials
# Build a per-request oauth credential based on token stored in
session
# which allows us to use a shared API client.
@authorization ||= (
auth = settings.authorization.dup
auth.redirect_uri = to('/oauth2callback')
auth.update_token!(session)
auth
)
end

configure do

 Google::Apis::ClientOptions.default.application_name = 'Get Login
 info for Google Ad Exchange'
 Google::Apis::ClientOptions.default.application_version = '1.0.0'

 client_secrets = Google::APIClient::ClientSecrets.load
 authorization = client_secrets.to_authorization
 authorization.scope =
 'https://www.googleapis.com/auth/adexchange.seller.readonly'

  set :authorization, authorization
end

before do
# Ensure user has authorized the app
unless user_credentials.access_token || request.path_info =~
/^\/oauth2/
redirect to('/oauth2authorize')
end
end

 after do
 # Serialize the access/refresh token to the session and credential
 store.
# We could potentially need to pull back the client_id and
client_secret as well and add them to the dynamo database.

#   session[:client_id] = user_credentials.client_id
#   session[:client_secret] = user_credentials.client_secret
    session[:access_token] = user_credentials.access_token
    session[:refresh_token] = user_credentials.refresh_token
    session[:expires_in] = user_credentials.expires_in
    session[:issued_at] = user_credentials.issued_at

  end

get '/oauth2authorize' do
 # Request authorization
 redirect user_credentials.authorization_uri.to_s, 303
 end

get '/oauth2callback' do
 # Exchange token
 user_credentials.code = params[:code] if params[:code]
 user_credentials.fetch_access_token!
 redirect to('/')

  end

Body:
Figured it out, meant to post way earlier but had an alert on this post so i figured id update to what we did to ake it work.

 get '/googleauth' do
   salesforce_username = params[:salesforce_username] || ''
   unless session.has_key?(:credentials)
   redirect to('/oauth2callback')
 end
   client_opts = JSON.parse(session[:credentials])
   auth_client = Signet::OAuth2::Client.new(client_opts)
   redirect to('/googleadx')
 end

 get '/oauth2callback' do
  client_secrets = Google::APIClient::ClientSecrets.load
  auth_client = client_secrets.to_authorization
  auth_client.update!(
  :scope => 'https://www.googleapis.com/auth/adexchange.seller.readonly',
:redirect_uri => url('/oauth2callback'))
 if request['code'] == nil
  auth_uri = auth_client.authorization_uri.to_s
  redirect to(auth_uri)
 else
  auth_client.code = request['code']
  auth_client.fetch_access_token!
  session[:access_token] = auth_client.access_token
  session[:refresh_token] = auth_client.refresh_token
  session[:expires_in] = auth_client.expires_in
  session[:issued_at] = auth_client.issued_at
  auth_client.client_secret = nil
  session[:credentials] = auth_client.to_json
  redirect to('/googleadx')
end
end

get '/googleadx' do

# configure()

if params[:username]
    successmessage = params[:username] + "'s credentials added successfully."
else
    message = ''
end

salesforce_username = session[:salesforce_username] || ''
access_token = session[:access_token]
refresh_token = session[:refresh_token]
googleDollarLimit = ''

erb :googleadx, locals: {message: message, successmessage: successmessage, salesforce_username: salesforce_username, access_token: access_token, refresh_token: refresh_token, googleDollarLimit: googleDollarLimit}
end


来源: stackexchange

问:
Suggestive Search From JS Array, Possible?
Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.

So imagine a javascript object or array that is full of people's names:

```<code>var array = (jack,tom,john,sarah,barry,...etc);
</code>```

I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.

I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.

Hope someone can help me with this!

W.

答:
http://wwwo.google.com?q=autosuggest+using+javascript

AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.

ContentLicense: CC BY-SA 2.5

Body:
Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.

So imagine a javascript object or array that is full of people's names:

var array = (jack,tom,john,sarah,barry,...etc);

I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.

I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.

Hope someone can help me with this!

W.


问:
driver.get on selenium giving error
I have tried running the following command after I've imported everything I need (selenium, webdriver, keys):

```<code>>>> driver.get('https://steemit.com/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'
</code>```

I can't find any solution.

答:
from your comment it looks like your code is:

```<code>import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.chrome # should be webdriver.chrome()
driver.get('')
</code>```

and your traceback is:

```<code>Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'
</code>```

which you are missing the instantiation of the driver, also as pointed out below chrome should be capitalised, so this:

```<code>driver = webdriver.chrome
</code>```

needs to become:

```<code>driver = webdriver.Chrome() # the brackets mean the object is created or 'instantiated'
</code>```

ContentLicense: CC BY-SA 3.0

Title: driver.get on selenium giving error

Body:
I have tried running the following command after I've imported everything I need (selenium, webdriver, keys):

>>> driver.get('https://steemit.com/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'

I can't find any solution.

Body:
from your comment it looks like your code is:

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.chrome # should be webdriver.chrome()
driver.get('')

and your traceback is:

Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'selenium.webdriver.chrome' has no attribute 'get'

which you are missing the instantiation of the driver, also as pointed out below chrome should be capitalised, so this:

driver = webdriver.chrome

needs to become:

driver = webdriver.Chrome() # the brackets mean the object is created or 'instantiated'


问:
Wordpress editor showing white text
I have a problem with a Wordpress site, the editor is showing the text as white (on a white background) so unless you highlight the text, you can't see it. This is only in the admin section of the site, the front-end doesn't seem to be affected

I have found where the css is changing the text to white ( /wp-includes/css/editor.min.css ):

```<code>.js .tmce-active .wp-editor-area{color:#fff}
</code>```

I have removed this and cleared the cache (even tried a different browser) but it's still showing in the editor.

Also, the 'Visual' and 'Text' buttons don't work.

Any ideas?

I have gone through an disabled each plugin, one at a time but it still is a problem.

答:
Check your javascript console. If you see an error like:

"post.php?post=2840&action=edit:2783 Uncaught ReferenceError: tinymce is not defined"

Then the loading of wp-tinymce.php failing. Because the editor hasn't loaded, it appear as if your text is white, or "invisible" in the editor. This can be worked-around by adding:

```<code>define('CONCATENATE_SCRIPTS', false);
</code>```

(Per Tijmen above, or https://wordpress.stackexchange.com/a/63172/118510)

(I use WP Fastest Cache plugin which has it's own concatenation, so if I use that plugin, then I'm OK skipping the default Wordpress concatenation.)

The root problem, however, is that a request to:

/wp-includes/js/tinymce/wp-tinymce.php?c=1&ver=4506-20170408

Is failing or receiving a 404. This could be due to a security restriction on your hosting or CDN.

Title: Wordpress editor showing white text

Body:
I have a problem with a Wordpress site, the editor is showing the text as white (on a white background) so unless you highlight the text, you can't see it. This is only in the admin section of the site, the front-end doesn't seem to be affected

I have found where the css is changing the text to white ( /wp-includes/css/editor.min.css ):

.js .tmce-active .wp-editor-area{color:#fff}

I have removed this and cleared the cache (even tried a different browser) but it's still showing in the editor.

Also, the 'Visual' and 'Text' buttons don't work.

Any ideas?

I have gone through an disabled each plugin, one at a time but it still is a problem.

Body:
Check your javascript console. If you see an error like:

"post.php?post=2840&action=edit:2783 Uncaught ReferenceError: tinymce is not defined"

Then the loading of wp-tinymce.php failing. Because the editor hasn't loaded, it appear as if your text is white, or "invisible" in the editor. This can be worked-around by adding:

define('CONCATENATE_SCRIPTS', false);

(Per Tijmen above, or https://wordpress.stackexchange.com/a/63172/118510)

(I use WP Fastest Cache plugin which has it's own concatenation, so if I use that plugin, then I'm OK skipping the default Wordpress concatenation.)

The root problem, however, is that a request to:

/wp-includes/js/tinymce/wp-tinymce.php?c=1&ver=4506-20170408

Is failing or receiving a 404. This could be due to a security restriction on your hosting or CDN.


问:
Is this a new way to extend an object in JavaScript?
While upgrading a private yeoman generator I stumpled upon this statement while looking through the official generator-webapp:

```<code>const { features } = answers;
</code>```

I wasn't able to find anything about this, aside from the fact that it only works on node >=6.

What does this statement do? Where is this defined?

答:
This:

```<code>const { features } = answers;
</code>```

Is the shorthand of this:

```<code>const features = answers.features;
</code>```

You could also declare many variables in a single line, see following please:

var answers = {"features": "test"};
const { features } = answers;
console.log(features);

var longObj = {"attr1": "val1", "attr2" : "val2"};
const { attr1, attr2 } = longObj;
console.log(attr1, attr2);```

I hope it was clear. Bye.

Body:
While upgrading a private yeoman generator I stumpled upon this statement while looking through the official generator-webapp:

const { features } = answers;

I wasn't able to find anything about this, aside from the fact that it only works on node >=6.

What does this statement do? Where is this defined?

Body:
This:

const { features } = answers;

Is the shorthand of this:

const features = answers.features;

You could also declare many variables in a single line, see following please:

var answers = {"features": "test"};
const { features } = answers;
console.log(features);

var longObj = {"attr1": "val1", "attr2" : "val2"};
const { attr1, attr2 } = longObj;
console.log(attr1, attr2);

I hope it was clear. Bye.


问:
Doctrine mapping issue - Call to a member function setValue() on null
I have a weird issue with Doctrine. I have set up the following structure:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="fp_credit_returned_product")
 */
class ReturnedProduct {
...
    /**
     * @var FpCredit\Models\Credit\ReturnedProductDetail
     * @ORM\OneToMany(targetEntity="\FpCredit\Models\Credit\ReturnedProductDetail", mappedBy="returned_product", cascade={"persist"})
     */
    private $details;

public function getDetails() {
    return $this->details;
}

public function setDetails($details) {
    $this->details = $details;
}
</code>```

and:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="fp_credit_returned_product_detail")
 */
class ReturnedProductDetail {

     /**
     * @var FpCredit\Models\Credit\ReturnedProduct
     * @ORM\ManyToOne(targetEntity="\FpCredit\Models\Credit\ReturnedProduct")
     * @ORM\JoinColumn(name="returned_product_id", nullable=false, referencedColumnName="id")
     */
    private $returnedProduct;

    public function getReturnedProduct() {
        return $this->returnedProduct;
    }

    public function setReturnedProduct($returnedProduct) {
        $this->returnedProduct = $returnedProduct;
    }
</code>```

Then I query all returnedProducts and do the following:

```<code>foreach ($errorLogs as $eLog) {
    $errorDetails = $eLog->getDetails();
    if ($errorDetails) {
        foreach ($errorDetails as $errorDetail) {

            $errorArticle = $errorDetail->getArticle();
        }
    }
}
</code>```

Because of the $errorDetail->getArticle() I get this error:

```<code>PHP Fatal error:  Call to a member function setValue() on null in /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/PersistentCollection.php
</code>```

Does anybody know why this error occurs and how I can fix it? Is something wrong with my mapping? One ReturnedProducts has several ReturnProductDetails.

Thanks for your help!

答:
Can you try in your class ReturnedProduct

```<code>mappedBy="returnedProduct"
</code>```

regards.

Body:
I have a weird issue with Doctrine. I have set up the following structure:

/**
 * @ORM\Entity
 * @ORM\Table(name="fp_credit_returned_product")
 */
class ReturnedProduct {
...
    /**
     * @var FpCredit\Models\Credit\ReturnedProductDetail
     * @ORM\OneToMany(targetEntity="\FpCredit\Models\Credit\ReturnedProductDetail", mappedBy="returned_product", cascade={"persist"})
     */
    private $details;

public function getDetails() {
    return $this->details;
}

public function setDetails($details) {
    $this->details = $details;
}

and:

/**
 * @ORM\Entity
 * @ORM\Table(name="fp_credit_returned_product_detail")
 */
class ReturnedProductDetail {

     /**
     * @var FpCredit\Models\Credit\ReturnedProduct
     * @ORM\ManyToOne(targetEntity="\FpCredit\Models\Credit\ReturnedProduct")
     * @ORM\JoinColumn(name="returned_product_id", nullable=false, referencedColumnName="id")
     */
    private $returnedProduct;

    public function getReturnedProduct() {
        return $this->returnedProduct;
    }

    public function setReturnedProduct($returnedProduct) {
        $this->returnedProduct = $returnedProduct;
    }

Then I query all returnedProducts and do the following:

foreach ($errorLogs as $eLog) {
    $errorDetails = $eLog->getDetails();
    if ($errorDetails) {
        foreach ($errorDetails as $errorDetail) {

            $errorArticle = $errorDetail->getArticle();
        }
    }
}

Because of the $errorDetail->getArticle() I get this error:

PHP Fatal error:  Call to a member function setValue() on null in /var/www/html/vendor/doctrine/orm/lib/Doctrine/ORM/PersistentCollection.php

Does anybody know why this error occurs and how I can fix it? Is something wrong with my mapping? One ReturnedProducts has several ReturnProductDetails.

Thanks for your help!

Body:
Can you try in your class ReturnedProduct

mappedBy="returnedProduct"

regards.


问:
How can I log each request/response using Alamofire?
Is there a way to log each request / response using Alamofire (something similar to AFNetworkActivityLogger) ?

I am aware of Printable, DebugPrintable and Output (cURL) but they are not quite what I am looking for.

答:
SOLUTION FOR SWIFT 3.0+

For Printing Request parameter and headers:

```<code>Alamofire.request(url, method: .get, parameters: parameters, headers: headers)
            .validate()
            .responseObject { (response: DataResponse<T>) in
                self.pendingRequests.removeValue(forKey: endPoint)
                completion!(response)

                if(NetworkConfig.loggingEnable) {
                    debugPrint("************* printing REQUEST parameter and Headers *************")
                    debugPrint("RESPONSE : \(response.debugDescription)")
                }
        }.responseDebugPrint()
</code>```

For Printing Response . use below extension .

```<code>import Foundation
import Alamofire

extension Alamofire.DataRequest {
    func responseDebugPrint() -> Self {
        if NetworkConfig.loggingEnable {

            return responseJSON() {
                response in
                if let  JSON = response.result.value,
                    let JSONData = try? JSONSerialization.data(withJSONObject: JSON, options: .prettyPrinted),
                    let prettyString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) {
                    print(prettyString)
                } else if let error = response.result.error {
                    print("Error Debug Print: \(error.localizedDescription)")
                }
            }
        }
        return self
    }
}
</code>```

Small gist for you :
https://gist.github.com/manishpathak99/348f2eb0167c0ff6e12ecd667612bc9b/edit

Body:
SOLUTION FOR SWIFT 3.0+

For Printing Request parameter and headers:

Alamofire.request(url, method: .get, parameters: parameters, headers: headers)
            .validate()
            .responseObject { (response: DataResponse<T>) in
                self.pendingRequests.removeValue(forKey: endPoint)
                completion!(response)

                if(NetworkConfig.loggingEnable) {
                    debugPrint("************* printing REQUEST parameter and Headers *************")
                    debugPrint("RESPONSE : \(response.debugDescription)")
                }
        }.responseDebugPrint()

For Printing Response . use below extension .

import Foundation
import Alamofire

extension Alamofire.DataRequest {
    func responseDebugPrint() -> Self {
        if NetworkConfig.loggingEnable {

            return responseJSON() {
                response in
                if let  JSON = response.result.value,
                    let JSONData = try? JSONSerialization.data(withJSONObject: JSON, options: .prettyPrinted),
                    let prettyString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) {
                    print(prettyString)
                } else if let error = response.result.error {
                    print("Error Debug Print: \(error.localizedDescription)")
                }
            }
        }
        return self
    }
}

Small gist for you :
https://gist.github.com/manishpathak99/348f2eb0167c0ff6e12ecd667612bc9b/edit


问:
How could I pass std::function as function pointer?
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

```<code>void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );
</code>```

where fn and gr are function pointers of type

```<code>typedef double optimfn(int n, double *par, void *ex);
</code>```

and

```<code>typedef void optimgr(int n, double *par, double *gr, void *ex);
</code>```

respectively. My C++ class template looks like this:

```<code>template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};
</code>```

so that it can be instantiated by any class with two specified member functions, e.g.:

```<code>class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);
</code>```

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

答:
Basically, you need a free function that has the correct signature, takes the void * parameter with the "user data" (without which it won't work), somehow extracts a pointer/reference to the std::function out of that, and calls it with the other arguments. Simple example to illustrate what I mean:

```<code>void call_it(int value, void * user) {
  std::function<void(int)> * f = static_cast<std::function<void(int)>*>(user);
  (*f)(value);
}
// pass it as callback:
registerCallback(call_it, static_cast<void *>(&my_std_function));
</code>```

Of course you need to make sure that the pointer remains valid!

With the code below you don't need to write such call_it functions for every possible signature. Above example would read:

```<code>registerCallback(trampoline<1, Single::Extract<void,int>, void, int, void *>,
                 Single::wrap(my_std_function));
</code>```

And your case would be:

```<code>// obj and ex passed as parameters
std::function<double(int, double *)> fn =
  [ex, &obj] (int a, double * b) { return obj.fr(a, b, ex); };
std::function<void(int, double *, double *)> gr =
  [ex, &obj] (int a, double * b, double * c) { obj.grr(a, b, c, ex); };
void * fns = Multi<2>::wrap(fn, gr);
vmmin(... ,
      trampoline<2, Multi<2>::Extract<0, double, int, double *>, double, int, double *, void *>,
      trampoline<3, Multi<2>::Extract<1, void, int, double *, double *>, void, int, double *, double *, void *>,
      ..., fns, ...); // fns passed as ex
Multi<2>::free_wrap_result(fns);
</code>```

My "scratch area" on ideone for forking and testing.
Now, Templates to the rescue:

```<code>template<
    std::size_t N, ///> index of parameter with the user data
    typename Extractor,
    typename R,
    typename... Args>
R trampoline (Args... args) {
  auto all = std::make_tuple(std::ref(args)...);
  auto arguments = tuple_remove<N>(all);
  return std::apply(Extractor{}.get_function(std::get<N>(all)),
                    arguments);
}
</code>```

std::apply is a C++17 thing, though you should be able to easily find a C++11 compatible version on this site. The N specifies the (zero based) index of the parameter which contains the "user data" (i.e. the pointer to the actual function). The Extractor is a type that has a static get_function member function, which given a void * returns something "callable" for std::apply to work with. The use case is inspired by your actual issue at hand: If you have only one pointer with "user data" which will be passed to two (or more) different callbacks, then you need a way to "extract" these different functions in the different callbacks.

An "extractor" for a single function:

```<code>struct Single {
  template<typename R, typename... Args>
  struct Extract {
    std::function<R(Args...)> & get_function(void * ptr) {
        return *(static_cast<std::function<R(Args...)>*>(ptr));
    }
  };
  template<typename R, typename... Args>
  static void * wrap(std::function<R(Args...)> & fn) {
    return &fn;
  }
};
</code>```

And one for multiple functions:

```<code>template<std::size_t Num>
struct Multi {
  template<std::size_t I, typename R, typename... Args>
  struct Extract {
    std::function<R(Args...)> & get_function(void * ptr) {
      auto arr = static_cast<std::array<void *, Num> *>(ptr);
      return *(static_cast<std::function<R(Args...)>*>((*arr)[I]));
    }
  };
  template<typename... Fns>
  static void * wrap(Fns &... fns) {
    static_assert(sizeof...(fns) == Num, "Don't lie!");
    std::array<void *, Num> arr = { static_cast<void *>(&fns)... };
    return static_cast<void*>(new std::array<void *, Num>(std::move(arr)));
  }
  static void free_wrap_result(void * ptr) {
    delete (static_cast<std::array<void *, Num>*>(ptr));
  }
};
</code>```

Note that here wrap does an allocation, thus must be met with a corresponding de-allocation in free_wrap_result. This is still very unidiomatic ... should probably be converted to RAII.

tuple_remove still needs to be written:

```<code>template<
    std::size_t N,
    typename... Args,
    std::size_t... Is>
auto tuple_remove_impl(
    std::tuple<Args...> const & t,
    std::index_sequence<Is...>) {
  return std::tuple_cat(if_t<N == Is, Ignore, Use<Is>>::from(t)...);
}
template<
    std::size_t N,
    typename... Args>
auto tuple_remove (std::tuple<Args...> const & t) {
  return tuple_remove_impl<N>(t, std::index_sequence_for<Args...>{});
}
</code>```

if_t (see further down) is just my shorthand for std:: conditional, Use and Ignore need to be implemented:

```<code>struct Ignore {
  template<typename Tuple>
  static std::tuple<> from(Tuple) {
    return {};
  }
};
template<std::size_t N>
struct Use {
  template<typename Tuple>
  static auto from(Tuple t) {
    return std:: make_tuple(std::get<N>(t));
  }
};
</code>```

tuple_remove exploits that std::tuple_cat accepts empty std::tuple<> arguments, and because it cannot get something out of them, basically ignores them.

Shorthand for std::conditional:

```<code>template<bool Condition,
         typename Then,
         typename Else>
using if_t = typename std::conditional<
    Condition, Then, Else>::type;
</code>```

Body:
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );

where fn and gr are function pointers of type

typedef double optimfn(int n, double *par, void *ex);

and

typedef void optimgr(int n, double *par, double *gr, void *ex);

respectively. My C++ class template looks like this:

template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};

so that it can be instantiated by any class with two specified member functions, e.g.:

class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

Body:
Basically, you need a free function that has the correct signature, takes the void * parameter with the "user data" (without which it won't work), somehow extracts a pointer/reference to the std::function out of that, and calls it with the other arguments. Simple example to illustrate what I mean:

void call_it(int value, void * user) {
  std::function<void(int)> * f = static_cast<std::function<void(int)>*>(user);
  (*f)(value);
}
// pass it as callback:
registerCallback(call_it, static_cast<void *>(&my_std_function));

Of course you need to make sure that the pointer remains valid!

With the code below you don't need to write such call_it functions for every possible signature. Above example would read:

registerCallback(trampoline<1, Single::Extract<void,int>, void, int, void *>,
                 Single::wrap(my_std_function));

And your case would be:

// obj and ex passed as parameters
std::function<double(int, double *)> fn =
  [ex, &obj] (int a, double * b) { return obj.fr(a, b, ex); };
std::function<void(int, double *, double *)> gr =
  [ex, &obj] (int a, double * b, double * c) { obj.grr(a, b, c, ex); };
void * fns = Multi<2>::wrap(fn, gr);
vmmin(... ,
      trampoline<2, Multi<2>::Extract<0, double, int, double *>, double, int, double *, void *>,
      trampoline<3, Multi<2>::Extract<1, void, int, double *, double *>, void, int, double *, double *, void *>,
      ..., fns, ...); // fns passed as ex
Multi<2>::free_wrap_result(fns);

My "scratch area" on ideone for forking and testing.
Now, Templates to the rescue:

template<
    std::size_t N, ///> index of parameter with the user data
    typename Extractor,
    typename R,
    typename... Args>
R trampoline (Args... args) {
  auto all = std::make_tuple(std::ref(args)...);
  auto arguments = tuple_remove<N>(all);
  return std::apply(Extractor{}.get_function(std::get<N>(all)),
                    arguments);
}

std::apply is a C++17 thing, though you should be able to easily find a C++11 compatible version on this site. The N specifies the (zero based) index of the parameter which contains the "user data" (i.e. the pointer to the actual function). The Extractor is a type that has a static get_function member function, which given a void * returns something "callable" for std::apply to work with. The use case is inspired by your actual issue at hand: If you have only one pointer with "user data" which will be passed to two (or more) different callbacks, then you need a way to "extract" these different functions in the different callbacks.

An "extractor" for a single function:

struct Single {
  template<typename R, typename... Args>
  struct Extract {
    std::function<R(Args...)> & get_function(void * ptr) {
        return *(static_cast<std::function<R(Args...)>*>(ptr));
    }
  };
  template<typename R, typename... Args>
  static void * wrap(std::function<R(Args...)> & fn) {
    return &fn;
  }
};

And one for multiple functions:

template<std::size_t Num>
struct Multi {
  template<std::size_t I, typename R, typename... Args>
  struct Extract {
    std::function<R(Args...)> & get_function(void * ptr) {
      auto arr = static_cast<std::array<void *, Num> *>(ptr);
      return *(static_cast<std::function<R(Args...)>*>((*arr)[I]));
    }
  };
  template<typename... Fns>
  static void * wrap(Fns &... fns) {
    static_assert(sizeof...(fns) == Num, "Don't lie!");
    std::array<void *, Num> arr = { static_cast<void *>(&fns)... };
    return static_cast<void*>(new std::array<void *, Num>(std::move(arr)));
  }
  static void free_wrap_result(void * ptr) {
    delete (static_cast<std::array<void *, Num>*>(ptr));
  }
};

Note that here wrap does an allocation, thus must be met with a corresponding de-allocation in free_wrap_result. This is still very unidiomatic ... should probably be converted to RAII.

tuple_remove still needs to be written:

template<
    std::size_t N,
    typename... Args,
    std::size_t... Is>
auto tuple_remove_impl(
    std::tuple<Args...> const & t,
    std::index_sequence<Is...>) {
  return std::tuple_cat(if_t<N == Is, Ignore, Use<Is>>::from(t)...);
}
template<
    std::size_t N,
    typename... Args>
auto tuple_remove (std::tuple<Args...> const & t) {
  return tuple_remove_impl<N>(t, std::index_sequence_for<Args...>{});
}

if_t (see further down) is just my shorthand for std:: conditional, Use and Ignore need to be implemented:

struct Ignore {
  template<typename Tuple>
  static std::tuple<> from(Tuple) {
    return {};
  }
};
template<std::size_t N>
struct Use {
  template<typename Tuple>
  static auto from(Tuple t) {
    return std:: make_tuple(std::get<N>(t));
  }
};

tuple_remove exploits that std::tuple_cat accepts empty std::tuple<> arguments, and because it cannot get something out of them, basically ignores them.

Shorthand for std::conditional:

template<bool Condition,
         typename Then,
         typename Else>
using if_t = typename std::conditional<
    Condition, Then, Else>::type;


问:
MySQL Storing Unlimited Data within Row
What is the best way to store data in this scenario:

ACCOUNT table stores id, username, password and a large set of data comprising of multiple rows. Example: multiple sessions stored with date and other information.

What I'm doing now is creating a new table called sessions_id# for each user, but there has to be a more efficient way.

答: You should be able to create a single sessions table that has a foreign key reference back to the account table.  The session table would have columns for an identity, then the user's ID, then the session-related data (date, context, etc.)</p>

Title: MySQL Storing Unlimited Data within Row


问:
Create multi-level lookup table with lodash
Lets pretend an api is returning the structure in apiResult, and I want to create a two-level index for looking up what comments a given author have made on a given article.

The lookup table for the authors, articles and comments it self is easy enough, but I struggle with the CommentsByArticleAndAuthor-lookup.

In the mapped structure, I'm showing how I'm making the lookup index for the three 'easy' parts, and also how I want the CommentsByArticleAndAuthor to look.

How can I go forward generating this index?

var apiResult = {
  Authors: [
    {
      Id: "author-id-1",
      Name: "Author One"
    },
    {
      Id: "author-id-2",
      Name: "Author Two"
    }
  ],
  Articles: [
    {
      Id: "article-id-1",
      Title: "This Great Article"
    }
  ],
  Comments: [
    {
       Id: "comment-id-1",
       AuthorId: "author-id-1",
       ArticleId: "article-id-1",
       Comment: "that great, hu?"
    },
    {
      Id: "comment-id-2",
      AuthorId: "author-id-2",
      ArticleId: "article-id-1",
      Comment: "yes, that great"
    }
  ]
}

var mapped = {
  Authors: _.keyBy(apiResult.Authors, 'Id'),
  Articles: _.keyBy(apiResult.Articles, 'Id'),
  Comments: _.keyBy(apiResult.Comments, 'Id'),
  CommentsByArticleAndAuthor: {
    "article-id-1": {
      "author-id-1": [ "comment-id-1" ],
      "author-id-2": [ "comment-id-2" ]
    }
  }
}

console.log(JSON.stringify(mapped, null, 2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script></code>```

答:
You could iterate the comments and build a hierarchical object strcture.

var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
    mapped = { CommentsByArticleAndAuthor: {} };

apiResult.Comments.forEach(function (o) {
    var ref = mapped.CommentsByArticleAndAuthor;

    ref[o.ArticleId] = ref[o.ArticleId] || {};
    ref[o.ArticleId][o.AuthorId] = ref[o.ArticleId][o.AuthorId] || [];
    ref[o.ArticleId][o.AuthorId].push(o.Id);
});

console.log(mapped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

For a more dynamic approach, you could use an array for the hierarchy and an object for the default values.

var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
    mapped = { CommentsByArticleAndAuthor: {} };

apiResult.Comments.forEach(function (o) {
    ['ArticleId', 'AuthorId'].reduce(function (r, k) {
        return r[o[k]] = r[o[k]] || { AuthorId: [] }[k] || {};
    }, mapped.CommentsByArticleAndAuthor).push(o.Id);
});

console.log(mapped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could iterate the comments and build a hierarchical object strcture.

var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
    mapped = { CommentsByArticleAndAuthor: {} };

apiResult.Comments.forEach(function (o) {
    var ref = mapped.CommentsByArticleAndAuthor;

    ref[o.ArticleId] = ref[o.ArticleId] || {};
    ref[o.ArticleId][o.AuthorId] = ref[o.ArticleId][o.AuthorId] || [];
    ref[o.ArticleId][o.AuthorId].push(o.Id);
});

console.log(mapped);

.as-console-wrapper { max-height: 100% !important; top: 0; }

For a more dynamic approach, you could use an array for the hierarchy and an object for the default values.

var apiResult = { Authors: [{ Id: "author-id-1", Name: "Author One" }, { Id: "author-id-2", Name: "Author Two" }], Articles: [{ Id: "article-id-1", Title: "This Great Article" }], Comments: [{ Id: "comment-id-1", AuthorId: "author-id-1", ArticleId: "article-id-1", Comment: "that great, hu?" }, { Id: "comment-id-2", AuthorId: "author-id-2", ArticleId: "article-id-1", Comment: "yes, that great" }] },
    mapped = { CommentsByArticleAndAuthor: {} };

apiResult.Comments.forEach(function (o) {
    ['ArticleId', 'AuthorId'].reduce(function (r, k) {
        return r[o[k]] = r[o[k]] || { AuthorId: [] }[k] || {};
    }, mapped.CommentsByArticleAndAuthor).push(o.Id);
});

console.log(mapped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
AES encryption/decryption
Here is some code that works well for strings:

```<code>Public Function AESEncrypt(ByVal PlainText As String, ByVal Password As String, ByVal salt As String)
    Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
    Dim PasswordIterations As String = 2
    Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
    Dim KeySize As Integer = 256 'Can be 128, 192, or 256.

    If (String.IsNullOrEmpty(PlainText)) Then
        Return ""
        Exit Function
    End If
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
    Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText)
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
    SymmetricKey.Mode = CipherMode.CBC

    Dim CipherTextBytes As Byte() = Nothing
    Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
        Using MemStream As New MemoryStream()
            Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
                CryptoStream.FlushFinalBlock()
                CipherTextBytes = MemStream.ToArray()
                MemStream.Close()
                CryptoStream.Close()
            End Using
        End Using
    End Using
    SymmetricKey.Clear()
    Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherText As String, ByVal password As String, ByVal salt As String) As String
    Dim HashAlgorithm As String = "SHA1"
    Dim PasswordIterations As String = 2
    Dim InitialVector As String = "CanEncryption123"
    Dim KeySize As Integer = 256

    If (String.IsNullOrEmpty(CipherText)) Then
        Return ""
    End If
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
    Dim CipherTextBytes As Byte() = Convert.FromBase64String(CipherText)
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
    SymmetricKey.Mode = CipherMode.CBC
    Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}

    Dim ByteCount As Integer = 0

    Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
        Using MemStream As MemoryStream = New MemoryStream(CipherTextBytes)
            Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
                ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
                MemStream.Close()
                CryptoStream.Close()
            End Using
        End Using
    End Using
    SymmetricKey.Clear()
    Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function
</code>```

Can I have some help in modifying these functions to encrypt/decrypt byte arrays rather than strings. Also, to have the functions return the encrypted/decrypted byte array, rather than a string.

thanks

答:
```<code>Public Function AESEncrypt(ByVal PlainBytes As Byte, ByVal Password As String, ByVal salt As String)
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.

Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC

Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
    Using MemStream As New MemoryStream()
        Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
            CryptoStream.Write(PlainBytes, 0, PlainBytes.Length)
            CryptoStream.FlushFinalBlock()
            CipherTextBytes = MemStream.ToArray()
            MemStream.Close()
            CryptoStream.Close()
        End Using
    End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherBytes As Byte, ByVal password As String, ByVal salt As String) As String
Dim HashAlgorithm As String = "SHA1"
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123"
Dim KeySize As Integer = 256

If (String.IsNullOrEmpty(CipherText)) Then
    Return ""
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim PlainTextBytes As Byte() = New Byte(CipherBytes.Length - 1) {}

Dim ByteCount As Integer = 0

Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
    Using MemStream As MemoryStream = New MemoryStream(CipherBytes)
        Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
            MemStream.Close()
            CryptoStream.Close()
        End Using
    End Using
End Using
SymmetricKey.Clear()
Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function
</code>```

The code you are using actually converts the input string to byte array. This code accepts byte array.

Title: AES encryption/decryption

Body:
Here is some code that works well for strings:

Public Function AESEncrypt(ByVal PlainText As String, ByVal Password As String, ByVal salt As String)
    Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
    Dim PasswordIterations As String = 2
    Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
    Dim KeySize As Integer = 256 'Can be 128, 192, or 256.

    If (String.IsNullOrEmpty(PlainText)) Then
        Return ""
        Exit Function
    End If
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
    Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText)
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
    SymmetricKey.Mode = CipherMode.CBC

    Dim CipherTextBytes As Byte() = Nothing
    Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
        Using MemStream As New MemoryStream()
            Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
                CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
                CryptoStream.FlushFinalBlock()
                CipherTextBytes = MemStream.ToArray()
                MemStream.Close()
                CryptoStream.Close()
            End Using
        End Using
    End Using
    SymmetricKey.Clear()
    Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherText As String, ByVal password As String, ByVal salt As String) As String
    Dim HashAlgorithm As String = "SHA1"
    Dim PasswordIterations As String = 2
    Dim InitialVector As String = "CanEncryption123"
    Dim KeySize As Integer = 256

    If (String.IsNullOrEmpty(CipherText)) Then
        Return ""
    End If
    Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
    Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
    Dim CipherTextBytes As Byte() = Convert.FromBase64String(CipherText)
    Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
    Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
    Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
    SymmetricKey.Mode = CipherMode.CBC
    Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}

    Dim ByteCount As Integer = 0

    Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
        Using MemStream As MemoryStream = New MemoryStream(CipherTextBytes)
            Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
                ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
                MemStream.Close()
                CryptoStream.Close()
            End Using
        End Using
    End Using
    SymmetricKey.Clear()
    Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function

Can I have some help in modifying these functions to encrypt/decrypt byte arrays rather than strings. Also, to have the functions return the encrypted/decrypted byte array, rather than a string.

thanks

Body:
Public Function AESEncrypt(ByVal PlainBytes As Byte, ByVal Password As String, ByVal salt As String)
Dim HashAlgorithm As String = "SHA1" 'Can be SHA1 or MD5
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123" 'This should be a string of 16 ASCII characters.
Dim KeySize As Integer = 256 'Can be 128, 192, or 256.

Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC

Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
    Using MemStream As New MemoryStream()
        Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
            CryptoStream.Write(PlainBytes, 0, PlainBytes.Length)
            CryptoStream.FlushFinalBlock()
            CipherTextBytes = MemStream.ToArray()
            MemStream.Close()
            CryptoStream.Close()
        End Using
    End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Public Function AESDecrypt(ByVal CipherBytes As Byte, ByVal password As String, ByVal salt As String) As String
Dim HashAlgorithm As String = "SHA1"
Dim PasswordIterations As String = 2
Dim InitialVector As String = "CanEncryption123"
Dim KeySize As Integer = 256

If (String.IsNullOrEmpty(CipherText)) Then
    Return ""
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(salt)
Dim DerivedPassword As PasswordDeriveBytes = New PasswordDeriveBytes(password, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = DerivedPassword.GetBytes(KeySize / 8)
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim PlainTextBytes As Byte() = New Byte(CipherBytes.Length - 1) {}

Dim ByteCount As Integer = 0

Using Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes)
    Using MemStream As MemoryStream = New MemoryStream(CipherBytes)
        Using CryptoStream As CryptoStream = New CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read)
            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
            MemStream.Close()
            CryptoStream.Close()
        End Using
    End Using
End Using
SymmetricKey.Clear()
Return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount)
End Function

The code you are using actually converts the input string to byte array. This code accepts byte array.


问:
Running Gulp in Docker - not found
I'm trying to create a docker-compose setup of NodeJs, Alpine, MongoDB and gulp to run typescript but I'm struggling to get gulp to run.

When running docker-compose build, I get the following:

```<code>node1_1 /bin/sh: [gulp]: not found
</code>```

docker-compose.yml:

```<code>version: '3'
services:
 node1:
 build: ./node1
 ports:
  - "3031:3031"
volumes:
  - .:/src
links:
  - mongo
mongo:
 image: mongo
 ports:
  - "27018:27017"
 volumes:
  - /data/mongodb/db:/data/db
</code>```

Dockerfile

```<code>FROM node:8.0-alpine
RUN mkdir -p /src
WORKDIR /src
ADD . /src

RUN apk update && apk upgrade

COPY package.json .
RUN npm install --quiet
RUN npm install gulp-cli -g
RUN npm install gulp -D
RUN npm i gulp

EXPOSE 3031
VOLUME ["/src"]
CMD ['gulp']
</code>```

Please, can someone suggest a solution?

答:
The problem is in the link of the alpine OS commands, if you change this line of the dockerfile, it should work.</p>

```<code>CMD gulp
</code>```

ContentLicense: CC BY-SA 4.0

Title: Running Gulp in Docker - not found

Body:
I'm trying to create a docker-compose setup of NodeJs, Alpine, MongoDB and gulp to run typescript but I'm struggling to get gulp to run.

When running docker-compose build, I get the following:

node1_1 /bin/sh: [gulp]: not found

docker-compose.yml:

version: '3'
services:
 node1:
 build: ./node1
 ports:
  - "3031:3031"
volumes:
  - .:/src
links:
  - mongo
mongo:
 image: mongo
 ports:
  - "27018:27017"
 volumes:
  - /data/mongodb/db:/data/db

Dockerfile

FROM node:8.0-alpine
RUN mkdir -p /src
WORKDIR /src
ADD . /src

RUN apk update && apk upgrade

COPY package.json .
RUN npm install --quiet
RUN npm install gulp-cli -g
RUN npm install gulp -D
RUN npm i gulp

EXPOSE 3031
VOLUME ["/src"]
CMD ['gulp']

Please, can someone suggest a solution?

Body:
The problem is in the link of the alpine OS commands, if you change this line of the dockerfile, it should work.

CMD gulp


问:
Count the films per genre watched by a person
I am using a graph db (neo4j) and Cypher.
I have three nodes: Person, Film, Genre, and two relationships: GUARDATO and GENRETOFILM.

A person can watch multiple films.
A genre is related to multiple films.

```<code>(p:Person)-[gu:GUARDATO]->(f:Film)
(g:Genre)-[ge:GENRETOFILM]->(f)
</code>```

I want to get the genres watched by a person and the number of films s/he watched of each genre.

答:
I have to count number of relationships named GENRETOFILM of the films
  watched by a certain Person

Try this:

```<code>MATCH(p:Person {name:'Jon Doe'})-[:GUARDATO]->(film:Film)<-[ge:GENRETOFILM]-(genre:Genre)
RETURN genre, count(film)
</code>```

Body:
I am using a graph db (neo4j) and Cypher.
I have three nodes: Person, Film, Genre, and two relationships: GUARDATO and GENRETOFILM.

A person can watch multiple films.
A genre is related to multiple films.

(p:Person)-[gu:GUARDATO]->(f:Film)
(g:Genre)-[ge:GENRETOFILM]->(f)

I want to get the genres watched by a person and the number of films s/he watched of each genre.

Body:
I have to count number of relationships named GENRETOFILM of the films
  watched by a certain Person

Try this:

MATCH(p:Person {name:'Jon Doe'})-[:GUARDATO]->(film:Film)<-[ge:GENRETOFILM]-(genre:Genre)
RETURN genre, count(film)


问:
ruby on rails diff two dates
I have two differnt dates in Rails

the current date:

```<code>DateTime.now
</code>```

and one which is stored in database (belongs to a object)

The format of those two is different:

```<code>DateTime.now:  2017-06-06T13:06:14+00:00
From Database: 2017-06-06 14:05:00 +0200
</code>```

I want to do a slect like this:

```<code>@lessons =  self.where("start_date < ? AND active IS NULL", DateTime.now)
</code>```

Problem is that those two dates are different ..

how can I format one of these to the same like the other?

Probably the DateTime.now to the same like one from db?

答:
You don't need to convert it, rails will take care for you</p>

```<code>User.where("created_at < ?",  DateTime.now).take
# generate sql
# SELECT  `users`.* FROM `users` WHERE (created_at < '2017-06-06 13:41:27.649070') LIMIT 1
</code>```

Title: ruby on rails diff two dates

Body:
I have two differnt dates in Rails

the current date:

DateTime.now

and one which is stored in database (belongs to a object)

The format of those two is different:

DateTime.now:  2017-06-06T13:06:14+00:00
From Database: 2017-06-06 14:05:00 +0200

I want to do a slect like this:

@lessons =  self.where("start_date < ? AND active IS NULL", DateTime.now)

Problem is that those two dates are different ..

how can I format one of these to the same like the other?

Probably the DateTime.now to the same like one from db?

Body:
You don't need to convert it, rails will take care for you

User.where("created_at < ?",  DateTime.now).take
# generate sql
# SELECT  `users`.* FROM `users` WHERE (created_at < '2017-06-06 13:41:27.649070') LIMIT 1


问:
How do you test a jQuery UI Dialog using WatiN?
I can't seem to get a hold of it!

First attempt failed:

```<code>string url = "http://jquery_ui_dialog.aspx";
IE jQueryDialog = IE.AttachTo<IE>(Find.ByUrl(url));
</code>```

Second attempt failed:

```<code>Process[] processes = Process.GetProcessesByName("iexplore");
foreach (Process p in processes)
{
    if (p.MainWindowTitle == url + " - Microsoft Internet Explorer")
    {
        // this doesn't find it.
    }
}
</code>```

3rd tries the charm?

答:
A jquery UI dialog is just a html element that is powered by JQuery UI to make it look like a window, but it is NOT a window. you cannot attach to it, but you can simply retrieve it from the DOM.

If you dialog was initialized like this:

```<code>$('div#dialog_id').dialog();
</code>```

you can simply access to it by doing:

```<code>Div dialog = Browser.Div("dialog_id");
</code>```

Body:
I can't seem to get a hold of it!

First attempt failed:

string url = "http://jquery_ui_dialog.aspx";
IE jQueryDialog = IE.AttachTo<IE>(Find.ByUrl(url));

Second attempt failed:

Process[] processes = Process.GetProcessesByName("iexplore");
foreach (Process p in processes)
{
    if (p.MainWindowTitle == url + " - Microsoft Internet Explorer")
    {
        // this doesn't find it.
    }
}

3rd tries the charm?

Body:
A jquery UI dialog is just a html element that is powered by JQuery UI to make it look like a window, but it is NOT a window. you cannot attach to it, but you can simply retrieve it from the DOM.

If you dialog was initialized like this:

$('div#dialog_id').dialog();

you can simply access to it by doing:

Div dialog = Browser.Div("dialog_id");


问:
Apache Flink: calculating and outputting multiple values in one window
We plan to use Apache Flink to perform real-time aggregations on multiple types of objects.
We need to support several types of aggregations such as sum, max, min, average etc. - nothing special so far

Our requirement is to output the data to kafka where one message contains multiple aggregated values for multiple object attributes.

for example, the message should include the sum, max, and average values for attribute A and also the sum and min values of attribute B for the last 10 minutes

My question is what is the best way to implement such a requirement with Flink?

We though about using a custom window function that will run on all objects at the end of the window and calculate by itself all required values and output a new object that holds all of these aggregated values.
The thing we are concerned about with this solution is the affect on the memory consumption having to hold all the window data in memory waiting for the window to fire  (we will have many such windows opened at the same time)

Any suggestions / comments are highly appreciated!

Thanks

答:
The best approach would be to use incremental aggregation to compute the count, sum, min, and max for each window -- and you can compute the average in your window function, given the sum and count. In this way the only state you'll need to keep are these four values (the count, sum, min, and max), rather than having to buffer the entire stream for processing at the end of the window.

This example from the documentation should be enough to get you started.


问:
Strange sum problem

Possible Duplicate:

  Elegant workaround for JavaScript floating point number problem

```<code>var sum = 0;
$('[id$=percentOfTotalEditor]').each(
    function () {
        var igEditor = $find(this.id);
        var value = igEditor.get_value();
        sum += value;
    }
);
</code>```

Then you'll see the magic:

sum == 1.1, value == 0.1. But after sum += value, sum == 1.2000000000000001

WTF!?

答: Yes, this question is a duplicate as Paddy has suggested.  Still, here's another Javascript library that will allow you to work with precise decimal numbers (up to a point): http://blog.brewsession.com/2008/06/28/problematic-decimal-arithmetic-in-javascript/</p>

Title: Strange sum problem

Body:
Possible Duplicate:

  Elegant workaround for JavaScript floating point number problem

var sum = 0;
$('[id$=percentOfTotalEditor]').each(
    function () {
        var igEditor = $find(this.id);
        var value = igEditor.get_value();
        sum += value;
    }
);

Then you'll see the magic:

sum == 1.1, value == 0.1. But after sum += value, sum == 1.2000000000000001

WTF!?


问:
How to detect Line Debugging in on & the debugger is running?
We have a ColdFusion 8 application running in JRun4 on Windows Server 2003.

How do we detect (& display) whether the debugger is running with Allow Line Debugging enabled in CF Administrator. After detecting, we want to display a warning on the application that the debugger is running.

答:
You should be able to use the ColdFusion Administrator API for this. Of course you will need the security/permissions in order to use this. If you are using sandbox security, enable access to the cf_web_root/CFIDE/adminapi directory to use the Administrator API. Basically the Administrator API gives you programmatic access to most of the ColdFusion Administrator settings.

From the documentation:

You can use the Administrator API to perform most ColdFusion Administrator tasks programmatically. The Administrator API consists of a set of ColdFusion components (CFCs) that contain methods you call to perform Administrator tasks.

The CFC for managing the debug settings is debugging.cfc.

Here is some pseudo code (this has not been tested):

```<code><cfscript>

// Instantiate the administrator.cfc
adminObj = createObject("component","cfide.adminapi.administrator");

// Call the administrator.cfc login method, passing the ColdFusion Administrator password
adminObj.login("#password#","#username#");

// Instantiate the debugging CFC
debugObj = createObject("component","cfide.adminapi.debugging");

// Call the desired CFC method
if (debugObj.isLineDebuggerEnabled()) {

    if (debugObj.isLineDebuggerRunning()) {

        // Stop line debugger
        debugObj.stopLineDebugger();
    }

    // Disable the line debugger
    debugObj.setLineDebuggerEnabled(enabled="false");
}

</cfscript>
</code>```

That should get you started. Here is some documentation on the debugging.cfc and it's methods.

```<code>Manages debug settings.

hierarchy:  WEB-INF.cftags.component
            CFIDE.adminapi.base
            CFIDE.adminapi.debugging
path:   {web-root}\CFIDE\adminapi\debugging.cfc
serializable:   Yes
properties:
methods:  addDebugEvent,
          deleteIP,
          getCurrentIP,
          getDebugProperty,
          getDebugRecordset,
          getIPList,
          getLineDebuggerPort,
          getLogProperty,
          getMaxDebuggingSessions,
          isLineDebuggerEnabled,
          isLineDebuggerRunning,
          restartLineDebugger,
          setDebugProperty,
          setIP,
          setLineDebuggerEnabled,
          setLineDebuggerPort,
          setLogProperty,
          setMaxDebuggingSessions,
          startLineDebugger,
          stopLineDebugger,
          validateIP*
inherited methods:  dump,
                    getEdition,
                    getInstallType,
                    getJRunRootDir,
                    isAdminUser,
                    RDSInvoker,
                    setJrunSN
</code>```

Body:
You should be able to use the ColdFusion Administrator API for this. Of course you will need the security/permissions in order to use this. If you are using sandbox security, enable access to the cf_web_root/CFIDE/adminapi directory to use the Administrator API. Basically the Administrator API gives you programmatic access to most of the ColdFusion Administrator settings.

From the documentation:

You can use the Administrator API to perform most ColdFusion Administrator tasks programmatically. The Administrator API consists of a set of ColdFusion components (CFCs) that contain methods you call to perform Administrator tasks.

The CFC for managing the debug settings is debugging.cfc.

Here is some pseudo code (this has not been tested):

<cfscript>

// Instantiate the administrator.cfc
adminObj = createObject("component","cfide.adminapi.administrator");

// Call the administrator.cfc login method, passing the ColdFusion Administrator password
adminObj.login("#password#","#username#");

// Instantiate the debugging CFC
debugObj = createObject("component","cfide.adminapi.debugging");

// Call the desired CFC method
if (debugObj.isLineDebuggerEnabled()) {

    if (debugObj.isLineDebuggerRunning()) {

        // Stop line debugger
        debugObj.stopLineDebugger();
    }

    // Disable the line debugger
    debugObj.setLineDebuggerEnabled(enabled="false");
}

</cfscript>

That should get you started. Here is some documentation on the debugging.cfc and it's methods.

Manages debug settings.

hierarchy:  WEB-INF.cftags.component
            CFIDE.adminapi.base
            CFIDE.adminapi.debugging
path:   {web-root}\CFIDE\adminapi\debugging.cfc
serializable:   Yes
properties:
methods:  addDebugEvent,
          deleteIP,
          getCurrentIP,
          getDebugProperty,
          getDebugRecordset,
          getIPList,
          getLineDebuggerPort,
          getLogProperty,
          getMaxDebuggingSessions,
          isLineDebuggerEnabled,
          isLineDebuggerRunning,
          restartLineDebugger,
          setDebugProperty,
          setIP,
          setLineDebuggerEnabled,
          setLineDebuggerPort,
          setLogProperty,
          setMaxDebuggingSessions,
          startLineDebugger,
          stopLineDebugger,
          validateIP*
inherited methods:  dump,
                    getEdition,
                    getInstallType,
                    getJRunRootDir,
                    isAdminUser,
                    RDSInvoker,
                    setJrunSN


问:
Change CLLocationDegrees into a Double/NSNumber to save in Core Data (Swift)
In trying to change all my objective C code into Swift (which is a pretty steep learning curve in itself), I've hit a problem.

I'm simply trying to save a CLLocationDegrees value into Core Data. But nothing I do is working.

I started with:

```<code>self.myLocation?.locationCurrentLat = self.fixedLocation?.coordinate.latitude
</code>```

But have no idea how to get the CLLocationDegrees to downcast (if that's the right thing) to a Double or NSNumber and nothing I can search on Google is helping!

I'm still obviously foggy about lots of things. This is certainly one of them.

What might I be doing wrong ... or need to do?

Thanks in advance

答:
Here's how to convert to NSNumber in Objective-C;</p>

```<code>[NSNumber numberWithDouble:newLocation.coordinate.longitude]
</code>```

Body:
In trying to change all my objective C code into Swift (which is a pretty steep learning curve in itself), I've hit a problem.

I'm simply trying to save a CLLocationDegrees value into Core Data. But nothing I do is working.

I started with:

self.myLocation?.locationCurrentLat = self.fixedLocation?.coordinate.latitude

But have no idea how to get the CLLocationDegrees to downcast (if that's the right thing) to a Double or NSNumber and nothing I can search on Google is helping!

I'm still obviously foggy about lots of things. This is certainly one of them.

What might I be doing wrong ... or need to do?

Thanks in advance

Body:
Here's how to convert to NSNumber in Objective-C;

[NSNumber numberWithDouble:newLocation.coordinate.longitude]


问:
D3.js bar element not adding dynamically
I've created a basic example with dummy data to try and get my head around what is happening when adding or removing data to a graph in D3. The example fiddle can be seen here.

To my understanding, inside the generateBars(data) function;

I update the x and y domain, ensuring that the next call to the axes causes them to scale correctly:

```<code>testUpdateX.domain(data.map(function(d) {return d.destination;}));
testUpdateY.domain([0, d3.max(data, function(d) {return d.p_in;})]);
</code>```

Pass the new data variable from the parameter:

```<code>var bars = svg.selectAll(".testUpdateBar").data(data);
</code>```

Update the current bars' x, y, width and height:

```<code>bars.transition().duration(2500)
    .attr("x", function(d) {return testUpdateX(d.destination);})
    .attr("y", function(d) {return testUpdateY(d.p_in);})
    .attr("width", testUpdateX.bandwidth() - 5)
    .attr("height", function(d) {return testUpdateHeight - testUpdateY(d.p_in);})
    .style("fill", function(d) {
        var maxIn = d3.max(data, function(d) {return d.p_in;});
        if (d.p_in < maxIn * 0.3) {
            return "red";
        } else if (d.p_in > maxIn * 0.3 && d.p_in < maxIn * 0.6) {
            return "orange";
        } else {
            return "green";
        }
    });
</code>```

Then, append new "rect" elements to the new data via invocation of the .enter() function and applying the same attributes and styles to it:

```<code> bars.enter().append("rect").attr("class", "testUpdateBar")
     .attr("x", //...)
     .attr("y", //...)
      etc...
</code>```

Invoking .exit() and .remove() in order to remove the bars of any data that has been removed:

```<code>bars.exit().transition().duration(2500).remove();
</code>```

Then finally, re-calling my axes in order to update them in accordance to the newly specified domain:

```<code>svg.select(".testUpdateXaxis").transition().duration(2500).call(testUpdateXaxis);
svg.select(".testUpdateYaxis").transition().duration(2500).call(testUpdateYaxis);
</code>```

Why does the final bar for 'Spar' not appear? The y-axis correctly itself for it's new value and a space is created, yet no rectangle elements seems to be appended.

Apologies for the unnecessarily long variable names. I was testing this within an existing file and wanted to ensure the names didn't conflict.

答:
Look at your code. You have this inside your generateBars function:

```<code>var svg = d3.select("body");
</code>```

Therefore, when you click the button you are in fact appending the Spar rectangle of your enter selection... outside the SVG!

It should be simply:

```                   ```

That is, nothing!

Here is the updated jsfiddle: https://jsfiddle.net/pugya97h/

Body:
I've created a basic example with dummy data to try and get my head around what is happening when adding or removing data to a graph in D3. The example fiddle can be seen here.

To my understanding, inside the generateBars(data) function;

I update the x and y domain, ensuring that the next call to the axes causes them to scale correctly:

testUpdateX.domain(data.map(function(d) {return d.destination;}));
testUpdateY.domain([0, d3.max(data, function(d) {return d.p_in;})]);

Pass the new data variable from the parameter:

var bars = svg.selectAll(".testUpdateBar").data(data);

Update the current bars' x, y, width and height:

bars.transition().duration(2500)
    .attr("x", function(d) {return testUpdateX(d.destination);})
    .attr("y", function(d) {return testUpdateY(d.p_in);})
    .attr("width", testUpdateX.bandwidth() - 5)
    .attr("height", function(d) {return testUpdateHeight - testUpdateY(d.p_in);})
    .style("fill", function(d) {
        var maxIn = d3.max(data, function(d) {return d.p_in;});
        if (d.p_in < maxIn * 0.3) {
            return "red";
        } else if (d.p_in > maxIn * 0.3 && d.p_in < maxIn * 0.6) {
            return "orange";
        } else {
            return "green";
        }
    });

Then, append new "rect" elements to the new data via invocation of the .enter() function and applying the same attributes and styles to it:

 bars.enter().append("rect").attr("class", "testUpdateBar")
     .attr("x", //...)
     .attr("y", //...)
      etc...

Invoking .exit() and .remove() in order to remove the bars of any data that has been removed:

bars.exit().transition().duration(2500).remove();

Then finally, re-calling my axes in order to update them in accordance to the newly specified domain:

svg.select(".testUpdateXaxis").transition().duration(2500).call(testUpdateXaxis);
svg.select(".testUpdateYaxis").transition().duration(2500).call(testUpdateYaxis);

Why does the final bar for 'Spar' not appear? The y-axis correctly itself for it's new value and a space is created, yet no rectangle elements seems to be appended.

Apologies for the unnecessarily long variable names. I was testing this within an existing file and wanted to ensure the names didn't conflict.

Body:
Look at your code. You have this inside your generateBars function:

var svg = d3.select("body");

Therefore, when you click the button you are in fact appending the Spar rectangle of your enter selection... outside the SVG!

It should be simply:

That is, nothing!

Here is the updated jsfiddle: https://jsfiddle.net/pugya97h/


问:
Share an object list externally using ShareActionProvider
I have a RecyclerView which needed to be sent/shared with external apps like WhatsApp etc. Using ShareActionProvider to achieve this.
Have created a menu and inflated in the overflow area in ToolBar using SharedActionProvider.

sample code.

```<code>  public void prepareShareIntent() {

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, "Sample Text.");
    shareIntent.setType("text/plain");
    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
}
</code>```

If data sharing between internal activities, we usually pass objects/object list by serialising/ Parcelable or using gson , no issue here since we can easily parse the data in the receiving activity. But in case, if I need to share a list Object to external apps what should be done. Does the external apps interpret as only specific types?

Appreciate the possible approaches.
Thanks in advance.

答:
I have a RecyclerView which needed to be sent/shared with external apps like WhatsApp etc.

That is not possible. First, you cannot pass a View to another process. Second, WhatsApp and other apps would not know what to do with it.

If data sharing between internal activities, we usually pass objects/object list by serialising/ Parcelable or using gson , no issue here since we can easily parse the data in the receiving activity.

You cannot convert a RecyclerView into a Serializable, a Parcelable, or JSON. You might be able to convert the model data that the RecyclerView uses into one of those things, but third-party apps (e.g., WhatsApp) may not know what to do with it.

Does the external apps interpret as only specific types?

Correct. The MIME type of the ACTION_SEND Intent needs to be the MIME type of the content shared via EXTRA_TEXT or EXTRA_STREAM.

I recommend that you spend some time thinking about what exactly you expect WhatsApp to do when you share content with it, where that content is somehow tied to a RecyclerView. For example, if you want WhatsApp to send a screenshot of the RecyclerView to somebody, then you should be sharing a screenshot of the RecyclerView, not the RecyclerView itself.

Body:
I have a RecyclerView which needed to be sent/shared with external apps like WhatsApp etc. Using ShareActionProvider to achieve this.
Have created a menu and inflated in the overflow area in ToolBar using SharedActionProvider.

sample code.

  public void prepareShareIntent() {

    shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.putExtra(Intent.EXTRA_TEXT, "Sample Text.");
    shareIntent.setType("text/plain");
    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
}

If data sharing between internal activities, we usually pass objects/object list by serialising/ Parcelable or using gson , no issue here since we can easily parse the data in the receiving activity. But in case, if I need to share a list Object to external apps what should be done. Does the external apps interpret as only specific types?

Appreciate the possible approaches.
Thanks in advance.


问:
key_load_public: invalid format
I used PuTTY Key Generator to generate a 4096 bit RSA-2 key with a passphrase.

I save the .ppk and an openSSL format public key. The putty format public key doesn't work.

In any case, my error is as follows:

```<code>$ ssh -T git@github.com
key_load_public: invalid format
Enter passphrase for key '/c/Users/Dan/.ssh/id_rsa':
Hi Dan! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

What's the issue?

I use Pageant to load the keys and i use Git Bash to try the ssh connection. I've also loaded the key into GitHub, not sure what i'm doing wrong.

I've tried adding a new line and not adding a new line in GitHub

答:
As Roland mentioned in their answer, it's a warning that the ssh-agent doesn't understand the format of the public key and even then, the public key will not be used locally.

However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.

Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be ~/.ssh/. Adjust these details to suit your needs as desired.

The Formats

Link to the relevant PuTTY documentation

SSH-2

When you save a key using the PuTTY Key Generator using the "Save public key" button, it will be saved in the format defined by RFC 4716.

Example:

```<code>---- BEGIN SSH2 PUBLIC KEY ----
Comment: "github-example-key"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYF
i2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcp
pY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3
oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEA
ip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9
tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw==
---- END SSH2 PUBLIC KEY ----
</code>```

OpenSSH

Contrary to popular belief, this format doesn't get saved by the generator. However it is generated and shown in the text box titled "Public key for pasting into OpenSSH authorized_keys file". To save it as a file, you have to manually copy it from the text box and paste it into a new text file.

For the key shown above, this would be:

```<code>ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw== github-example-key
</code>```

The format of the key is simply ssh-rsa <signature> <comment> and can be created by rearranging the SSH-2 formatted file.

Regenerating Public Keys

If you are making use of ssh-agent, you will likely also have access to ssh-keygen.

If you have your OpenSSH Private Key (id_rsa file), you can generate the OpenSSH Public Key File using:

```<code>ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub
</code>```

If you only have the PUTTY Private Key (id_rsa.ppk file), you will need to convert it first.

Open the PuTTY Key Generator

On the menu bar, click "File" > "Load private key"

Select your id_rsa.ppk file

On the menu bar, click "Conversions" > "Export OpenSSH key"

Save the file as id_rsa (without an extension)

Now that you have an OpenSSH Private Key, you can use the ssh-keygen tool as above to perform manipulations on the key.

Bonus: The PKCS#1 PEM-encoded Public Key Format

To be honest, I don't know what this key is used for as I haven't needed it. But I have it in my notes I've collated over the years and I'll include it here for wholesome goodness. The file will look like this:

```<code>-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5Ew
gnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8D
Gm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48
ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8
hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D
6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElwIBJQ==
-----END RSA PUBLIC KEY-----
</code>```

This file can be generated using an OpenSSH Private Key (as generated in "Regenerating Public Keys" above) using:

```<code>ssh-keygen -f ~/.ssh/id_rsa -y -e -m pem > ~/.ssh/id_rsa.pem
</code>```

Alternatively, you can use an OpenSSH Public Key using:

```<code>ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pem > ~/.ssh/id_rsa.pem
</code>```

##References:##

"key_load_public: invalid format..." on AskUbuntu

The Secure Shell (SSH) Public Key File Format

Converting OpenSSH public keys

Title: key_load_public: invalid format

Body:
I used PuTTY Key Generator to generate a 4096 bit RSA-2 key with a passphrase.

I save the .ppk and an openSSL format public key. The putty format public key doesn't work.

In any case, my error is as follows:

$ ssh -T git@github.com
key_load_public: invalid format
Enter passphrase for key '/c/Users/Dan/.ssh/id_rsa':
Hi Dan! You've successfully authenticated, but GitHub does not provide shell access.

What's the issue?

I use Pageant to load the keys and i use Git Bash to try the ssh connection. I've also loaded the key into GitHub, not sure what i'm doing wrong.

I've tried adding a new line and not adding a new line in GitHub

Body:
As Roland mentioned in their answer, it's a warning that the ssh-agent doesn't understand the format of the public key and even then, the public key will not be used locally.

However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.

Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be ~/.ssh/. Adjust these details to suit your needs as desired.

The Formats

Link to the relevant PuTTY documentation

SSH-2

When you save a key using the PuTTY Key Generator using the "Save public key" button, it will be saved in the format defined by RFC 4716.

Example:

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "github-example-key"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYF
i2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcp
pY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3
oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEA
ip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9
tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw==
---- END SSH2 PUBLIC KEY ----

OpenSSH

Contrary to popular belief, this format doesn't get saved by the generator. However it is generated and shown in the text box titled "Public key for pasting into OpenSSH authorized_keys file". To save it as a file, you have to manually copy it from the text box and paste it into a new text file.

For the key shown above, this would be:

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw== github-example-key

The format of the key is simply ssh-rsa <signature> <comment> and can be created by rearranging the SSH-2 formatted file.

Regenerating Public Keys

If you are making use of ssh-agent, you will likely also have access to ssh-keygen.

If you have your OpenSSH Private Key (id_rsa file), you can generate the OpenSSH Public Key File using:

ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub

If you only have the PUTTY Private Key (id_rsa.ppk file), you will need to convert it first.

Open the PuTTY Key Generator

On the menu bar, click "File" > "Load private key"

Select your id_rsa.ppk file

On the menu bar, click "Conversions" > "Export OpenSSH key"

Save the file as id_rsa (without an extension)

Now that you have an OpenSSH Private Key, you can use the ssh-keygen tool as above to perform manipulations on the key.

Bonus: The PKCS#1 PEM-encoded Public Key Format

To be honest, I don't know what this key is used for as I haven't needed it. But I have it in my notes I've collated over the years and I'll include it here for wholesome goodness. The file will look like this:

-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5Ew
gnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8D
Gm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48
ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8
hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D
6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElwIBJQ==
-----END RSA PUBLIC KEY-----

This file can be generated using an OpenSSH Private Key (as generated in "Regenerating Public Keys" above) using:

ssh-keygen -f ~/.ssh/id_rsa -y -e -m pem > ~/.ssh/id_rsa.pem

Alternatively, you can use an OpenSSH Public Key using:

ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pem > ~/.ssh/id_rsa.pem

##References:##

"key_load_public: invalid format..." on AskUbuntu

The Secure Shell (SSH) Public Key File Format

Converting OpenSSH public keys


问:
Return List of T where T is one of x classes (where x is greater than zero)
Please see the two classes below:

```<code>public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }
</code>```

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

```<code>public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }
</code>```

Can this be done?

答:
In your particular case I'd say your question smells, I mean it looks like you're just looking in the wrong direction.

So I agree with @Jamiec comment:

If you have separate classes for separate purpose (model, vs database entity) then its not clear why you need one generic method to "Build a list".

To answer the question in the title, here's the code (but doing this way is just weird):

```<code>public interface IPerson
{
    public int Id {get;}
    public string Name {get;}
}

public GoodPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int GoodDeedCount {get; set;}

    void SayGoodDay(IPerson toPerson)
    {
        GoodDeedCount++;
        return $"Good day, {toPerson.Name}! :)"
    }
}

public BadPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Badness {get; set;}

    void SayShutUp(IPerson toPerson)
    {
        Badness++;
        return $"Shut up, {toPerson.Name}!"
    }
}

public UglyPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}

    void SayNothing() { }
}

public static List<T> BuildList<T>()
    where T: new()
{
    var result = new List<T>();
    if (T is GoodPeson)
    {
         result.Add(new GoodPerson{Id = 1, Name = "Pinky", GoodDeedCount = 0});
         result.Add(new GoodPerson{Id = 2, Name = "Brain", GoodDeedCount = 0});
    }
    else if (T is BadPerson)
    {
         result.Add(new BadPerson{Id = 1, Name = "Sunshine", Badness = 0});
    }
    else if (T is UglyPerson)
    {
         result.Add(new UglyPerson{Id = 1, Name = "No", Badness = 0});
    }
    return result;
}
</code>```

Body:
Please see the two classes below:

public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }

Can this be done?

Body:
In your particular case I'd say your question smells, I mean it looks like you're just looking in the wrong direction.

So I agree with @Jamiec comment:

If you have separate classes for separate purpose (model, vs database entity) then its not clear why you need one generic method to "Build a list".

To answer the question in the title, here's the code (but doing this way is just weird):

public interface IPerson
{
    public int Id {get;}
    public string Name {get;}
}

public GoodPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int GoodDeedCount {get; set;}

    void SayGoodDay(IPerson toPerson)
    {
        GoodDeedCount++;
        return $"Good day, {toPerson.Name}! :)"
    }
}

public BadPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Badness {get; set;}

    void SayShutUp(IPerson toPerson)
    {
        Badness++;
        return $"Shut up, {toPerson.Name}!"
    }
}

public UglyPerson : IPerson
{
    public int Id {get; set;}
    public string Name {get; set;}

    void SayNothing() { }
}

public static List<T> BuildList<T>()
    where T: new()
{
    var result = new List<T>();
    if (T is GoodPeson)
    {
         result.Add(new GoodPerson{Id = 1, Name = "Pinky", GoodDeedCount = 0});
         result.Add(new GoodPerson{Id = 2, Name = "Brain", GoodDeedCount = 0});
    }
    else if (T is BadPerson)
    {
         result.Add(new BadPerson{Id = 1, Name = "Sunshine", Badness = 0});
    }
    else if (T is UglyPerson)
    {
         result.Add(new UglyPerson{Id = 1, Name = "No", Badness = 0});
    }
    return result;
}


问:
Last Row Paste to different Worksheet VBA
I am trying to paste info on the last row of a different worksheet.  I already have the info copied and this macro is just to paste it.  With the code that I have now, I am getting an error that says "Paste Method of Worksheet Class Failed"  how can I fix this?

here is the code:

```<code>Windows("m.xlsx").Activate
Cells(Application.Rows.Count, 1).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
Range("D45").Select
Windows("d.xlsx").Activate
</code>```

答:
Excel is known to clear the clipboard and hence you should put the copy command one line before you paste.

So in your case the copy command will go before

```<code>ActiveSheet.Paste
</code>```

Also please avoid the use of .Select/Activate. Please read How to avoid using Select in Excel VBA macros

Is this what you are trying (Untested)?

```<code>Sub Sample()
    Dim thisWb As Workbook, thatWb As Workbook
    Dim lRow As Long

    Set thisWb = Workbooks("d.xlsx")
    Set thatWb = Workbooks("m.xlsx")

    '~~> Change Sheet1 to the relevant sheet
    With thatWb.Sheets("Sheet1")
        '~~> Find last Row to paste
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

        '~~> Change Sheet1 to the relevant sheet
        '~~> Replace A1:A10 with the relevant range that you are trying to copy
        thisWb.Sheets("Sheet1").Range("A1:A10").Copy .Range("A" & lRow)
    End With
End Sub
</code>```

Body:
I am trying to paste info on the last row of a different worksheet.  I already have the info copied and this macro is just to paste it.  With the code that I have now, I am getting an error that says "Paste Method of Worksheet Class Failed"  how can I fix this?

here is the code:

Windows("m.xlsx").Activate
Cells(Application.Rows.Count, 1).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
Range("D45").Select
Windows("d.xlsx").Activate

Body:
Excel is known to clear the clipboard and hence you should put the copy command one line before you paste.

So in your case the copy command will go before

ActiveSheet.Paste

Also please avoid the use of .Select/Activate. Please read How to avoid using Select in Excel VBA macros

Is this what you are trying (Untested)?

Sub Sample()
    Dim thisWb As Workbook, thatWb As Workbook
    Dim lRow As Long

    Set thisWb = Workbooks("d.xlsx")
    Set thatWb = Workbooks("m.xlsx")

    '~~> Change Sheet1 to the relevant sheet
    With thatWb.Sheets("Sheet1")
        '~~> Find last Row to paste
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1

        '~~> Change Sheet1 to the relevant sheet
        '~~> Replace A1:A10 with the relevant range that you are trying to copy
        thisWb.Sheets("Sheet1").Range("A1:A10").Copy .Range("A" & lRow)
    End With
End Sub