text:
Q: Issue with Jquery Datatable fnAdjustColumnSizing I am getting "TypeError: settings is undefined" issue while calling fnAdjustColumnSizing function.
Currently I am using DataTables 1.10.15 version
$('#myDataTable').dataTable().fnAdjustColumnSizing();

or
var oTable = $('#myDataTable').dataTable();
oTable.fnAdjustColumnSizing();

Giving the same error

console log value for api.settings()
  ({context:[], length:0, selector:{rows:null, cols:null, opts:null}, tables:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), table:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), draw:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), page:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), ajax:{__dt_wrapper:true, json:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), params:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), reload:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), url:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    })}, rows:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), row:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), columns:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), column:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), cells:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), cell:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), order:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), search:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), state:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), $:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), on:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), one:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), off:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), clear:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), settings:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), init:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), data:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), destroy:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    }), i18n:(function () {

                        var ret = fn.apply(scope, arguments);

                        // Method extension
                        _Api.extend(ret, ret, struc.methodExt);
                        return ret;

                    })})

A: The api.settings() returns an object instead of an array. Need to remove [0] to get the settings object.


text:
Q: Plotting pre-binned data of percent time allotments I have 11 data columns in a single data.frame, 10 of the columns are depth categories and one column contains one of two values (Day or Night).
Each row of data is populated with numeric values representing the percent of time spent in each depth category over a 4-hour period and has either Day or Night assigned to it in the Day_Night column indicating whether that 4-hour period was during the day or the night.
I would like to plot this data in a back to back histogram where each depth bin is listed vertically along the plot and values for the day are plotted in one histogram facing one way, while the values for the night are plotted facing the other way.  I can't post a picture since I am new but to see what I mean just look at Figure 5 on page 8 of this publication.
EDIT: Here's the picture:

Thanks for the help!

A: You can use plotrix for example:
set.seed (123)
mm <- matrix (sample(seq(0,330,10),2000,rep=TRUE),ncol=2 )
ll <- lapply(as.data.frame(mm),
       function(x)as.data.frame(table(cut(x,seq(0,330,10)))))

library(plotrix)
par(mar=pyramid.plot(ll$V1$Freq,ll$V2$Freq,
                     labels =ll$V1$Var1,
                     top.labels=c("NIGHT","","DAY"),
                     xlim=c(100,100),
                     main="Swimming depth",
                     lxcol="black",rxcol= "white",
                     gap=0,
                     do.first="plot_bg('pink')"))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remote Desktop Gateway Server is Temporarily Unavailable. AWS remote connection I'm trying to connect using Windows 10 remote desktop connection (default app). Now I was given an RDP credential now upon trying to connect and prompted with User and Password which I inputted
 Username: Administrator
 Password: <The password given to me>
 Server Name: ec2-....compute.amazonaws.com

But I got this error message. Not sure how to go about this. Is there anything I need to do in the AWS Console to make thi work? or do I need to modify something in the local machine I'm using?
Note: remote access to computer is enabled in my LOCAL MACHINE. I'm not sure in the AWS side since I don't have access to it. But the administrator said that the port is already enabled for port number 3389. So I have no idea on what to do now.

A: Ok found the issue. It seems that the provided RDP Connection is defective and I had to create/generate my own user with a new password. And using the IP address of my AWS and the new username/password I was able to create in the RDP


text:
Q: How to add content to added Block magento 2 I made a block from admin side  content->block  And I can add data from admin side in it and add it to a page I know. But How can I add data to it using phtml and xml ? any working example would be highly appreciated as I am confuse and didn't get any example .
Suppose I made a block named 'No-Picture'  using admin side

A: In order to make a custom block with data in it you will need to use xml's and phtml's in your own custom theme or module.
I gave a really big explenation of it on the next url :
Implement a custom theme Magento 2
Knowing and understanding what i said here you can add blocks in 3 different ways. You can add your block by creating it how you think you need to create it. But this limits you to the widgets of Magento and the text editor. You can add that block in a page by using content->page and add the static block in your text editor with a button.
If you want to add a block in a custom page you can do so by creating a custom page layout.
Like how i explained here :
Completely overwrite parent theme layout from the default.xml file of the child theme
If you want to adjust html or add block in existing containers of Magento on product pages etc you can do so by understanding my first url and then search for the propper xml layout that corresponds to the block in that page. Find its phtml and class trough that xml and adjust those using your own theme or module.
If you want to add data from Magento admin settings you can add a Helper to retrieve that data from the database. Unless you want to retrieve things like products, customers and other lists from Magento which you can retrieve via interfaces.
You have a lot of reading in front of you trough those 2 url's. I won't retype everything 10x so i give you the information via URL.
If you need any help after reading that please let me know.

A: Add below code in your CMS block.
{{block class="Magento\Framework\View\Element\Template" name="custom-name" template="Vendor_Module::custom.phtml"}}


text:
Q: BUILD FAILED in 9s Exception: Gradle task assembleDebug failed with exit code 1 I work on VScode Flutter project with bloc i was working normally and restart the application and then an error shows up to me in the DEBUGCONSOLE saying 'Error: Not found: 'dart:js''

THIS IS MY PUBSBEC.YAML CODE

A: flutter clean
Delete pubspec.lock
flutter pub get
flutter run
Please try these. Also please dont add screenshots of error or codes. Copy paste it here.

A: Try to downgrade your flutter and then upgrade again.

flutter downgrade v2.8.0
flutter upgrade


text:
Q: Creating/compiling C# scripts to executable I have this problem, where I have my Windows Application (C#) that is basicly an application builder, just like Visual Studio can build executables from C# scripts.
So my question is, how does one accomplish to build executables with the c# scripts, directly from another Windows application that is already built from the Visual Studio.
UPDATE: I realized this was a duplicate, and the other questions that is similiar to this, had some interesting answers which I could use.
This can be deleted, if a moderator or anyone sees it.


text:
Q: How to add user to websocket chat I've gotten the chat to work but I have hard-coded the user's ID into Chat.php.
My login set's their email to a session ($_SESSION['email']=$email;) when they log into the site.
I can put a hidden field in the chat form with their ID and pass it into Chat.php but I would think there's a better way.
Disclaimer: I know it's not coded very well, I just want to learn it, get it working, and then code it better.
chat_box.php
<?php
echo '
',
    '
',
    '
',
    '
',
        '<input type="text" class="text" id="chatsay" name="chatsay" maxlength="200" autocomplete="off">',
        '<button class="submit-chatsend" id="chatsend">Send</button>',
    '
',
'
';

JS
window.connect = function () {
    window.ws = $.websocket("ws://domain.com:8080/", {
        open: function () {
        },
        close: function () {
        },
        events: {
            fetch: function (e) {
            },
            single: function (e) {
                var elem = e.data;

                if (elem.type == "text") {
                    var html = "

" + elem.name + "

" + elem.msg.linkify() + "
<time class='timeago' datetime='" + elem.posted + "'>" + elem.posted + "</time>

";

                    if (typeof elem.append != "undefined") {
                        $(".msg:last").remove();
                    }

                    if (typeof elem.earlier_msg == "undefined") {
                        $(".chatbox .chatbox-1").append(html);
                        $.scrollToBottom();
                    }
                    else {
                        $(".chatbox .chatbox-1 #load_earlier_messages").remove();
                        $(".chatbox .chatbox-1 .msg:first").before(html);
                    }
                }
                else if (elem.type == "more_messages") {
                    $(".chatbox .chatbox-1 .msg:first").before("Load Earlier Messages...");
                }
                $("time.timeago").timeago();
            }
        }
    });
};
$(document).ready(function () {
    connect();

    $(document).on("click", "#load_earlier_messages", function () {
        ws.send("fetch", {"id": $(".msg:first").attr("id")});
    });

    $('#chatsend').click(function () { //use clicks message send button
        var chatsay_val = $('#chatsay').val(); //get message text
        if (chatsay_val != "") {
            ws.send("send", {"type": "text", "msg": chatsay_val});
            $('#chatsay').val(''); //reset text
        }
    });
});

Chat.php
<?php
namespace MyApp;

use DateTime;
use DateTimeZone;
use Exception;
use PDO;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface
{
    protected $clients=array();
    private $dbh;

    /**
     * Chat constructor.
     */
    public function __construct()
    {
        global $db_host;
        global $db_username;
        global $db_password;
        global $db;
        require_once BASE_PATH.'modules'.DS.'Database'.DS.'Database.php';
        $database=new Database($db_host, $db, $db_username, $db_password);
        $this->dbh=$database;
    }

    /**
     * @param ConnectionInterface $conn
     */
    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients[$conn->resourceId]=$conn;
        echo "New connection! ({$conn->resourceId})\n";
        $this->fetchMessages($conn);
    }

    /**
     * @param ConnectionInterface $conn
     * @param int /null $id
     */
    public function fetchMessages(ConnectionInterface $conn, $id=NULL)
    {
        $database=$this->dbh;

        if($id===NULL)
        {
            $database->query('SELECT * FROM `chat` ORDER BY `id` ASC', array());
            $msgs=$database->statement->fetchAll(PDO::FETCH_ASSOC);
            $msgCount=$database->count();

            if($msgCount>0)
            {
                # If more then 5 chat messages...
                if($msgCount>5)
                {
                    # Extract a slice of the array.
                    $msgs=array_slice($msgs, $msgCount-5, $msgCount);
                }

                foreach($msgs as $msg)
                {
                    $date=new DateTime($msg['posted']);
                    $date->setTimezone(new DateTimeZone(TIMEZONE));

                    $user=SearchUser($msg['user_id']);

                    $return=array(
                        "id"=>$msg['id'],
                        "name"=>$user['staffname'],
                        "type"=>$msg['type'],
                        "msg"=>$msg['msg'],
                        "posted"=>$date->format("Y-m-d H:i:sP")
                    );
                    $this->send($conn, "single", $return);
                }
                if($msgCount>5)
                {
                    $this->send($conn, "single", array(
                        "type"=>"more_messages"
                    ));
                }
            }
        }
        else
        {
            $database->query('SELECT * FROM `chat` WHERE `id` < :id ORDER BY `id` DESC LIMIT 10', array(':id'=>$id));
            $msgs=$database->statement->fetchAll(PDO::FETCH_ASSOC);
            $msgCount=$database->count();

            if($msgCount>0)
            {
                foreach($msgs as $msg)
                {
                    $date=new DateTime($msg['posted']);
                    $date->setTimezone(new DateTimeZone(TIMEZONE));

                    $user=SearchUser($msg['user_id']);

                    $return=array(
                        "id"=>$msg['id'],
                        "name"=>$user['staffname'],
                        "type"=>$msg['type'],
                        "msg"=>$msg['msg'],
                        "posted"=>$date->format("Y-m-d H:i:sP"),
                        "earlier_msg"=>TRUE
                    );
                    $this->send($conn, "single", $return);
                }

                sort($msgs);
                $firstID=$msgs[0]['id'];
                if($firstID!="1")
                {
                    $this->send($conn, "single", array(
                        "type"=>"more_messages"
                    ));
                }
            }
        }
    }

    /**
     * @param ConnectionInterface $client
     * @param $type
     * @param $data
     */
    public function send(ConnectionInterface $client, $type, $data)
    {
        $send=array(
            "type"=>$type,
            "data"=>$data
        );
        $send=json_encode($send, TRUE);
        $client->send($send);
    }

    /**
     * @param ConnectionInterface $conn
     * @param string $data
     */
    public function onMessage(ConnectionInterface $conn, $data)
    {
        $database=$this->dbh;

        $data=json_decode($data, TRUE);

        if(isset($data['data']) && count($data['data'])!=0)
        {
            $type=$data['type'];
            # How can I get the user's ID?
            $user_id=1;
            $user_name=SearchUser($user_id);

            $return=NULL;

            if($type=="send" && isset($data['data']['type']) && $user_name!=-1)
            {
                $msg=htmlspecialchars($data['data']['msg']);
                $date=new DateTime;
                $date->setTimezone(new DateTimeZone(TIMEZONE));

                if($data['data']['type']=='text')
                {
                    $database->query('SELECT `id`, `user_id`, `msg`, `type` FROM `chat` ORDER BY `id` DESC LIMIT 1', array());
                    $lastMsg=$database->statement->fetch(PDO::FETCH_OBJ);

                    if($lastMsg->user_id==$user_id && (strlen($lastMsg->msg)<=100 || strlen($lastMsg->msg)+strlen($msg)<=100))
                    {
                        # Append message.
                        $msg=$lastMsg->msg."
".$msg;

                        $database->query('UPDATE `chat` SET `msg`=:msg, `posted`=NOW() WHERE `id`=:lastmsg', array(
                            ':msg'=>$msg,
                            ':lastmsg'=>$lastMsg->id
                        ));

                        $return=array(
                            "id"=>$lastMsg->id,
                            "name"=>$user_name['staffname'],
                            "type"=>"text",
                            "msg"=>$msg,
                            "posted"=>$date->format("Y-m-d H:i:sP"),
                            "append"=>TRUE
                        );
                    }
                    else
                    {
                        $database->query('INSERT INTO `chat` (`user_id`, `msg`, `type`, `posted`) VALUES (?, ?, "text", NOW())', array(
                            $user_id,
                            $msg
                        ));

                        # Get last insert ID.
                        $get_chat_id=$database->lastInsertId();
                        $return=array(
                            "id"=>$get_chat_id,
                            "name"=>$user_name['staffname'],
                            "type"=>"text",
                            "msg"=>$msg,
                            "posted"=>$date->format("Y-m-d H:i:sP")
                        );
                    }
                }

                foreach($this->clients as $client)
                {
                    $this->send($client, "single", $return);
                }
            }
            elseif($type=="fetch")
            {
                # Fetch previous messages.
                $this->fetchMessages($conn, $data['data']['id']);
            }
        }
    }

    /**
     * @param ConnectionInterface $conn
     */
    public function onClose(ConnectionInterface $conn)
    {
        # The connection is closed, remove it, as we can no longer send it messages.
        unset($this->clients[$conn->resourceId]);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    /**
     * @param ConnectionInterface $conn
     * @param Exception $e
     */
    public function onError(ConnectionInterface $conn, Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}

start_server.php (start server via command line: php start_server.php)
<?php
# Need this for the database insert.
if(!defined('DOMAIN_NAME'))
{
    define('DOMAIN_NAME', 'domain.com');
}
require_once 'includes/config.php';
include_once BASE_PATH.'modules'.DS.'WS'.DS.'server.php';

server.php
<?php

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;

$ip="domain.com";
$port="8080";

# Need this for the database insert.
if(!defined('DOMAIN_NAME'))
{
    define('DOMAIN_NAME', $ip);
}

require_once '../../vendor/autoload.php';

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ),
    $port,
    $ip
);

$server->run();

Here's my methodToGetSessionData() method as @Sherif suggested
/**
 * @param $sessionId
 * @return mixed
 */
private function methodToGetSessionData($sessionId)
{
    if(file_exists(session_save_path().'/sess_'.$sessionId))
    {
        $file=session_save_path().'/sess_'.$sessionId;
    }
    else
    {
        $file=sys_get_temp_dir().'/sess_'.$sessionId;
    }
    $contents=file_get_contents($file);
    session_decode($contents);

    return $_SESSION;
}

A: Just use the session like you're already doing. In your onOpen method the $conn has the initial HTTP request as a GuzzleHttp object. You can extract the session cookie from that and read in the session to your websocket server.
public function onOpen(ConnectionInterface $conn)
{
    // get the cookies
    $cookies = (string) $conn->WebSocket->request->getHeader('Cookie');

    // look at each cookie to find the one you expect
    $cookies = array_map('trim', explode(';', $cookies));
    $sessionId = null;

    foreach($cookies as $cookie) {
        // If the string is empty keep going
        if (!strlen($cookie)) {
            continue;
        }
        // Otherwise, let's get the cookie name and value
        list($cookieName, $cookieValue) = explode('=', $cookie, 2) + [null, null];
        // If either are empty, something went wrong, we'll fail silently here
        if (!strlen($cookieName) || !strlen($cookieValue)) {
            continue;
        }
        // If it's not the cookie we're looking for keep going
        if ($cookieName !== "PHPSESSID") {
            continue;
        }
        // If we've gotten this far we have the session id
        $sessionId = urldecode($cookieValue);
        break;
    }

    // If we got here and $sessionId is still null, then the user isn't logged in
    if (!$sessionId) {
        return $conn->close(); // close the connection - no session!
    }

    // Extract the session data using the session id from the cookie
    $conn->session = $this->methodToGetSessionData($sessionId);

    // now you have access to things in the session
    $this->clinets[] = $conn;
}

Depending on how you're storing session throughout your site with PHP you'll need to implement the methodToGetSessionData method to be able to read from that session store and deserialize the data. From there you'll have access to anything stored in the session through $conn->session or $client->session in your websocket server.
Typically if you're using the default file based storage in PHP it's easy enough to just read the session file from your session.storage_path and unserialize it. I think Ratchet offers some session components for things like Redis/Memcached that you can easily inject into your websocket app as well.


text:
Q: Stick element to the keyboard bottom during animations I'm struggling with keyboard in iOS 8 trying to glue an element above it during animations. Like in Messages they have input pushing up by appearing keyboard. I've found lots of topics here, but all of them say how to handle appearing keyboard, but not dismissal. Seems Apple use some other curve or speed whatever by dismissal, so I have asynchronism when close the keyboard, while appearing animation is perfectly synchronised.
Here is what I've got by now:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideOrShow:) name:UIKeyboardWillHideNotification object:nil];

- (void)keyboardWillHideOrShow:(NSNotification *)note {
    NSDictionary *userInfo = note.userInfo;
    CGRect keyboardEndFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self adjustFormContainerSize]; // Method opening orange card

    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue];
    UIViewAnimationOptions options = (curve << 16) | UIViewAnimationOptionBeginFromCurrentState;
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    self.buttonContainerBottom.constant = keyboardEndFrame.size.height;
    [UIView animateWithDuration:duration
                          delay:0.0
                        options:options
                     animations:^{
                         [self.view layoutIfNeeded];
                     }
                     completion:nil];
}

And the result in simulator: http://monosnap.com/file/BwxJdthPGzCqJnxeQLEg5bb8smvxdb
What's wrong with backward animation, how to synchronise it?

A: I recommend you to use
DAkeyboard
it's very good component for handle this problem


text:
Q: How to run grid-search for custom estimator which has a custom pipeline? I am trying to run grid-search for a custom case that involves a estimator that contains pipeline as one of its constructor input.
class DefaultEstimator(BaseEstimator, TransformerMixin):
  def __init__(self, preprocessor, pipelines):
    self.pipelines = pipelines

  def fit(self, X, y=None):
    for idx, each_pipeline in enumerate(self.pipelines):
      each_pipeline.fit(X[idx], y)
    return self

  def transform(self, X):
   transformed_data = []
   for idx, each_pipeline in enumerate(self.pipelines):
     transformed_data.append(each_pipeline.transform(X[idx))
   return sp.hstack(transformed_data)

My pipeline looks something like this:
pipeline1 = trainer.create_pipeline(num_features=100)
pipeline2 = trainer.create_pipeline(num_features=50)

Composite pipeline looks like:
aggregated_pipeline = Pipeline([('contextual', DefaultEstimator([pipeline1, pipeline2])),
                                ('classifier', Pipeline([('clf', SVM(random_state=1234, probability=True)]))
                              ])

Input data has two columns and for each column, there is a respective pipeline (pipeline1 and pipeline2) respectively.
The keys for grid_params for clf can be written as classifier__clf__C, classifier__clf__gamma etc.
The question is: How to write grid_params for GridSearchCV(...) as one of the pipeline steps isn't a pipeline object rather a custom-estimator object?

A: GridSearchCV and Pipeline use the estimator's set_params to set the parameters to test. So, you have to implement this in your DefaultEstimator, and set the pipeline parameters appropriately. A common pattern in scikit is to use double underscore to separate parameters of nested objects, so for example:
class DefaultEstimator:
    def set_params(self, **kwargs):
        for k, v in kwargs.items():
            parts = k.split('__')
            if parts[0].startswith('pipeline'):
                pipe_num = int(parts[0].split('_')[1])
                param_name = '__'.join(parts[1:])
                self.pipelines[pipe_num].set_params(*{param_name: v})
            else:
                # other logic

This would allow you to use parameters such as contextual__pipeline_1__num_features (contextual__ will be stripped away by the grid search, so no need to handle it).


text:
Q: Como salvar uma página html em java Estou com um projeto o qual preciso fazer um relatório para cada código. E salva-lo no disco no formato de PDF. Após gerar o relatório,  não sei como passar a página (gerada) para o Servlet e assim salvar em PDF.
Consegui fazer o envio do html para o servlet, agora preciso saber como converter as tags (html) para que o java possa interpreta-las e transformar em PDF.
Servlet
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package br.com.drz.paraopeba.servlets;

    import com.itextpdf.text.Document;
    import com.itextpdf.text.html.simpleparser.HTMLWorker;
    import com.itextpdf.text.pdf.PdfWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.io.StringReader;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
     *
     * @author douglas
     */
    @WebServlet(name = "salvarPDF", urlPatterns = {"/salvarPDF"})
    public class salvarPDF extends HttpServlet {

        private static final String SAVE_DIR = "relatorios";

        /**
         * Processes requests for both HTTP GET and POST
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) {

            }
        }

        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /**
         * Handles the HTTP GET method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            processRequest(request, response);
        }

        /**
         * Handles the HTTP POST method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            String  html = request.getParameter("conteudo");

            try {

                String appPath = request.getServletContext().getRealPath("");
                String savePath = appPath  + SAVE_DIR + File.separator;

                OutputStream file = new FileOutputStream(new File(savePath + "teste.pdf"));
                Document document = new Document();
                PdfWriter.getInstance(document, file);
                document.open();
                HTMLWorker htmlWorker = new HTMLWorker(document);
                htmlWorker.parse(new StringReader(html));
                document.close();
                file.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            processRequest(request, response);
        }

        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>

    }

A: Uma opção para geração de PDF seria gerar um relatório mesmo utilizando iReports ou Jasper.
Se isso não é uma opção, voce pode se aventurar em bibliotecas que convertem HTML para PDF, alguns casos aqui
Não recomendo muito a utilização desse tipo de biblioteca, já que normalmente a geração do PDF não é muito consistente. Cada uma dessas bibliotecas interpreta o CSS de um jeito diferente, e alguns casos, nem interpreta. O resultado final normalmente fica grosseiro e feio.
Se o seu HTML for simples o suficiente, talvez voce possa minimizar esses problemas.


text:
Q: Google Sheets AVERAGE function in ARRAYFORMULA I want to use the ARRAYFORMULA version of =IFERROR(AVERAGE(B29:H29),""). This is to calculate a 7 column rolling average that will automatically drag across using the array formula. I am aware the AVERAGE cannot be used with ARRAYFORMULA but I have struggled to find an alternative.

A: As discussed in the comments you can modify the previous answer.
Another approach to get the running average of the current number and the next 6 numbers is to take the difference of two running sums and divide by the count like this:
=ArrayFormula(if(C1:1="","",
   (sumif(column(C1:1),"<"&column(C1:1)+7,C1:1)-sumif(column(C1:1),"<"&column(C1:1),C1:1))/
   countifs(column(C1:1),"<"&column(C1:1)+7,column(C1:1),">="&column(C1:1),C1:1,"<>")))

(you can't use AVERAGEIFS or SUMIFS because they don't work with array formulas).
For completeness, the more usual running average starting with the first number, then the average of the first two numbers etc. would be given by:
=ArrayFormula(if(C1:1="","",
    (sumif(column(C1:1),"<="&column(C1:1),C1:1)-sumif(column(C1:1),"<="&column(C1:1)-7,C1:1))/
    countifs(column(C1:1),"<="&column(C1:1),column(C1:1),">"&column(C1:1)-7,C1:1,"<>")))


text:
Q: In semantic HTML does the class attribute mean anything in the absence of CSS or Javascript? For example, does the class film_review mean anything in
 (example from MDN) if there's no CSS or Javascript interacting with the page, or does it provide semantic information?

A: It doesn't provide an information that contemporary browsers would interpret or use without CSS or Javascript per se.
However it can carry semantic information - see e.g. microformats. For example, you could put an hcard

  John Doe

Cool Institute, Inc.

Prague

on your page and it carries a semantic information. A search engine like Google could infer that "John Doe" is a name of a person located in "Prague". There are other microformats that can represent geo information, calendar events, etc.
Anyone can write their own processor of HTML documents that would interpret class attribute values, so the answer is yes, it provides semantic information.
Quoting from hcard microformat example:

Per the HTML4.01 specification, authors should be using the  element to indicate the "contact information for a document or a major part of a document." E.g.
<address>
  Tantek Çelik</address>
By adding hCard to such existing semantic XHTML, you can explicitly indicate the name of the person, their URL, etc.:
<address class="vcard">
     Tantek Çelik
  </address>

A: It provides semantics purely in the sense that it semantically connects that element with other elements of the same class.
There's no rule which states that anything (specifically CSS and/or JavaScript in this case) must use that class.  The class itself is simply part of the markup and is coincidentally being ignored by the current styling rules.
You might have other elements with the film_review class, and they are "semantically" connected in the sense that they represent "film reviews" in the markup.  That's really all semantic information is... context about the thing being represented in the code.  Well-named classes can provide such additional context.
But there's nothing special that the browser is going to do with this information.  It's just there in case anybody (styling, code, or even just somebody looking at the markup) wants to know that this article belongs to a named class of elements.

A: Semantics on HTML5 are more oriented on standarizing the most used elements around the web. As described on HTML Semantic Elements:

With HTML4, developers used their own favorite attribute names to style page elements:
  header, top, bottom, footer, menu, navigation, main, container, content, article, sidebar, topnav, ...
  This made it impossible for search engines to identify the correct web page content.
  With HTML5 elements like:

, this will become easier.

So an element so specific as a "Film Review" would not provide that much semantic information at HTML5 level.

A: That depends. Who and what else is processing your HTML?
For example, microformats sometimes use classes to add semantic information to elements which don't naturally possess rich semantics. In that case, neither ECMAScript nor CSS process that information, but a microformats parser might. film_review doesn't belong to any well-known microformat, however.

A: Everything on the page gets parsed (read) by a search-engine, so your answer is, YES, it does provide semantic information, however there are different weighted value associated with different HTML tokens (elements, attribute-names, attribute-values).
However what really defines how much weight a HTML token gets, is really dependent on the type of document that you declare it is (HTML4/HTML5), the <!DOCTYPE> tag at the top of your page declares that to the search-engine bot/parser what type of document it is, which in turn controls the search-engine bot's parsing-schema (behavior) on how to read your document.
The entire purpose of HTML5 was to provide "semantics", allowing you to use different tags so you can markup/define your document giving content more importance allowing search-engines to understand it better. This allows the search-engine a much better way to then supply the end-user, whom is searching for something with more relevant content associated with their search term... if your not using HTML5 and using HTML4 then the bots are relying mostly on HTML attributes to define the content within tags such as a
 which provides no semantic meaning to the content inside it.


text:
Q: How does the naturalness problem of the Higgs mass changes depending on the cut off scale of the Standard Model (SM)? In this year's paper (check introduction) James D. Wells brings Susskind's 1979 argument that the SM is valid to a very high energy scale, say the Planck scale, $\Lambda \approx M_{Pl} \approx 10^{18} GeV$. This implies that the bare mass of the Higgs is very large, and thus for the effective (experimental) Higgs mass to be 125GeV there must be a very large fine tuning so the quantum corrections can cancel that big number. The equation helps understand the problem:
$$ m_H^2=m_{bare}^2 +\frac{y_t^2}{16\pi^2}\Lambda^2 +\delta\cal O (m_{weak}^2),$$
where $m_H$ is the Higgs effective mass, $m_{bare}$ its bare mass and the other two terms the quantum corrections. Note this equation highlights the contribution of the top quark loop only.
My questions are:

*

*How would the Higgs bare mass change if $\Lambda \ll M_{Pl}$? I imagine it would be much smaller, so the fine tuning wouldn't be a problem. Am I right?

*How can one calculate that? An equation (or even a proportionality relation) relating $m_{bare}$ to $\Lambda$ would be enough. Resources are welcome.


text:
Q: AngularFire used to have a orderByPriority filter From Google result it looks like AngularFire used to have a orderByPriority filter. But I cannot find this in the current AngularFire api docs: https://www.firebase.com/docs/web/libraries/angular/api.html. As I understand it, orderByPriority converted an objects properties into to an array. I guess this filter is gone because there is another and better way to do it now, but what is that method?

A: There is no longer a need for orderByPriority since you can utilize a synchronized array, which is already implicitly ordered.
So in ancient days, you would do something like:
$scope.data = $firebase(ref);

In not so ancient times (i.e. 0.8.x or greater) you would simply choose an array format:
$scope.data = $firebase(ref).$asArray();


text:
Q: QGIS + PostgreSQL - file that works on one PC will not work on another I have QGIS on 2 different standalone PC and I share/sync files between them.
I now need my second PC QGIS to work with a file that includes PostgreSQL queries.
PC 1 is original PC and all is well there.  Various versions of QGIS and all deployed versions of postgres/postgis behave as expected.  All hosted on standalone PC (localhost)
PC 2 - QGIS works fine, I have created an identical Postgresql database including GIS extensions, name, credentials etc and populated this with identical underlying data.  QGIS can connect and query this database.
Issue: If I then open one of my sync'd QGIS files on PC 2 it fails to connect/open any vectors linked to the PostgreSQL database.  I've tried to troubleshoot/google, used various V3 QGIS and failed to resolve this. Same file opens fine on PC 1. On the face of it I can see no reason this won't work - however need some expert opinion/advice.


text:
Q: connected components, product Let $(X, \tau_1)$, $(Y, \tau_1)$ be topological spaces with $\# (X) = \text{number of connected components} < \infty$ and $\# (Y) = \text{number of connected components} < \infty$.
How can I show that this implies $\# (X \times Y) = \# (X) \cdot \# (Y)$ (in the sense of the product topology)?


text:
Q: How do I mix a normal map into a reflection of a skybox? Im triying to create a water example and I know that the first thig requiered is to be able to make a reflection, that is done.
I'm stuck in the next step which is to combine the reflection with a normal map.
What I tried was to load the cube texture as I normally would, calculate the reflection and then load the normal map and combine them in the final step, but the water disappears.
Here's my code:
Vertex Shader
attribute vec3 a_normBT;
attribute vec3 a_normL;
attribute vec3  a_normTan;
attribute vec3 a_posL;
attribute vec2 a_uv;
uniform mat4 u_W;
uniform mat4 u_WVP;
varying vec3 v_normW;
varying vec3 v_normBT;
varying vec3 v_normTan;
varying vec3 v_posW;
varying vec2 v_uv;
void main()
{
    gl_Position  = u_WVP * vec4(a_posL, 1.0);
    v_uv = a_uv;
    v_normW = normalize((u_W*vec4(a_normL, 0.0)).xyz);
    v_normBT = normalize((u_W*vec4(a_normBT,0.0)).xyz);
    v_normTan = normalize((u_W*vec4(a_normTan,0.0)).xyz);
    v_posW = (u_W*vec4(a_posL, 1.0)).xyz;
}

Fragment shader
precision mediump float;
uniform samplerCube u_s_texture;
uniform sampler2D u_s_normalMap;
uniform vec3 u_cpos;// the camera position is already in world space
varying vec3 v_normW;
varying vec3 v_normBT;
varying vec3 v_normTan;
varying vec3 v_posW;
varying vec2 v_uv;
void main()
{
    vec4 tempText =  texture2D(u_s_normalMap, v_uv);
    vec3 Normal = normalize(v_normW);
    vec3 totalDifusse = vec3(0.0,0.0,0.0);
    vec3 totalSpecular = vec3(0.0,0.0,0.0);
    vec3 toEye = u_cpos- v_posW;
    vec3 reflectDir = reflect(normalize(-toEye), normalize(v_normW));  // reflect() in non linear
    gl_FragColor = tempText*textureCube(u_s_texture,reflectDir);
}

What I expect to happen is that the quad I have should have static ripples.
Thank you.

A: Do not know the coordinate system setup of your system and therefore uniforms exact meaning and too lazy to analyze/debug unknown code to help you.
Instead look at this: Normal mapping gone horribly wrong

*

*which is very similar to your task

*The main idea is to compute the fragments normal vector in [GCS] global (world coordinate) system

*and use that as 3D cubemap texture coordinate where your environment skybox texture is holding...

*This is not physically correct (unless surface is fluorescent) but is easy enough as start point and looks good

*when done then compute vector from fragment to camera in [GCS]

*then compute its reflection around computed normal

*and use that as 3D cubemap texture coordinate

Also have you check glGetShaderInfoLog ?

*

*very often a small syntax error prevent GLSL linkage using fixed function instead shader and if you have not compatible written layouts then you see nothing rendered or black ...

*see simple compelte GL+GLSL+VAO/VBO example in C++ how the glGetShaderInfoLog is used.


text:
Q: Divide a number into equal range and return as rows using select for oracle database? I am just asking, not sure if its feasible in an Oracle database select syntax, but below is a high level requirement.
Inputs

*

*Suppose I have a number: 6534

*Our dividing factor is "2000" for equal ranges

Output

RowNum  StartRange    EndRange
1       1             2000
2       2001          4000
3       4001          6000
4       6001          6534

A: You can do this by using (abusing?) hierarchical queries.
select min(data_column) StartRange,max(data_column) EndRange
from
(
  SELECT rownum data_column, trunc((rownum - 1)/ 2000, 0) round_col
  from DUAL
  connect by level <= 6534
)
group by round_col
order by round_col asc;

Helpful documentation:

*

*Oracle trunc(number) function.  Keep in mind trunc(date) does something different.

*Oracle Hierarchical Queries.

A: Use a Hierarchical Query to Create the Intervals
I just used a hierarchical query to create the intervals.  My query does not check for division by zero.
It just checks that the level of the hierarchy is less than or equal to ceiling of the quotient (ceiling function returns the minimum integer greater than or equal to n).
    SCOTT@db>SELECT
  2      level intrvl,
  3      ( level - 1 ) * (:l_denominator ) + 1 low_bnd,
  4      least(:l_numerator,level *:l_denominator) up_bnd
  5  FROM
  6      dual
  7  CONNECT BY
  8      level <= ceil(:l_numerator /:l_denominator)
  9  /
  INTRVL   LOW_BND   UP_BND
       1         1     2000
       2      2001     4000
       3      4001     6000
       4      6001     6534

My initial answer had two query blocks to address the final interval where the modulus was greater than zero. This has been removed.
Also, mathguy made the observation that I really did not need my common table expression (serves no additional value). The common table expression has been removed.

A: Here is how you can do this with a recursive query (which requires Oracle version 11.2 or higher).
You need a way to provide the inputs to the query, too. In the illustration below I use the mechanism offered by SQL*Plus: I define two bind variables and I assign values to them. Then I reference these bind variables in the query. Depending on what you use (SQL Developer? A graphical user interface? Perhaps you may call the query from PL/SQL, or from Java, etc.?) - you will use the appropriate mechanism to provide the values to the query. (Or, alternatively, you may hard-code them directly in the query; not recommended!)
SQL> variable input_number    number     -- SQL*Plus command, no need for ; after it!
SQL> variable dividing_factor number
SQL> begin                               -- PL/SQL anonymous procedure to assign values
  2    :input_number    := 6534;
  3    :dividing_factor := 2000;
  4  end;
  5  /

PL/SQL procedure successfully completed.

SQL> with
  2    r ( r_num, start_range, end_range ) as (
  3      select  1, 1, least(:dividing_factor, :input_number)
  4        from  dual
  5      union all
  6      select  r.r_num + 1, r.start_range + :dividing_factor,
  7              least(r.end_range + :dividing_factor, :input_number)
  8        from  r
  9        where r.end_range < :input_number
 10    )
 11  select   r_num, start_range, end_range
 12  from     r
 13  order by r_num    --    If needed.
 14  ;

     R_NUM START_RANGE  END_RANGE
---------- ----------- ----------
         1           1       2000
         2        2001       4000
         3        4001       6000
         4        6001       6534


text:
Q: md5 is not working on complex data types in pyspark I am trying to calculate hash using md5 function in pyspark on entire row. In pyspark dataframe I have multiple complex data types present for few columns.
for e.g :  col: array (nullable = true)
 |    |-- element: struct (containsNull = true)

 for e.g :  col: array (nullable = true)
 |    |-- element: array (containsNull = true)

when I try to calculate md5 on entire row , md5 throws an error with below message:
**`col`' is of array<array<string>> type. argument 28 requires (array<string> or string) type, however, '`col`' is of array<array<string>> type**

code to calculate md5:
def prepare_data_md5(data):
    """ Prepare the data with md5 column.

    :param data: input DataFrame object
    :return: output DataFrame object
    """
    return data.withColumn("hash", md5(concat_ws(*data.columns)))

1.Is there some other function I could use for hash and that works for complex data types too ?
2. Is there some library available in pyspark or python for flattening complex data types , so that I could calculate md5 over flattened data-frame ?

A: I don't think there is some function available in that calculates hash for complex types.
If you have array and string columns then use concat_ws and array_concat to convert complex types to strings then apply md5.
Example:
df.show()
#+---+------+
#| id|   arr|
#+---+------+
#|  a|[1, 2]|
#|  b|[3, 4]|
#+---+------+

from pyspark.sql.functions import *

df.withColumn("tmp",concat_ws(",",col("arr"))).\
withColumn("new",md5(concat_ws(",",col("id"),array_join(col("arr"),",")))).\
drop("tmp").\
show(10,False)
#+---+------+--------------------------------+
#|id |arr   |new                             |
#+---+------+--------------------------------+
#|a  |[1, 2]|9f357697a277b1e5a8315035e7d95984|
#|b  |[3, 4]|578bec981ad992ddb641a45969babab1|
#+---+------+--------------------------------+

#dynamic way

df1=df.withColumn("arr",array_join(col("arr"),","))

df1.withColumn("md5",md5(concat_ws(",",*[col(x) for x in df1.columns]))).show(10,False)
#+---+---+--------------------------------+
#|id |arr|md5                             |
#+---+---+--------------------------------+
#|a  |1,2|9f357697a277b1e5a8315035e7d95984|
#|b  |3,4|578bec981ad992ddb641a45969babab1|
#+---+---+--------------------------------+


text:
Q: Collect multiple data from PHP page? I am using the following ajax script to login a user to my site. The ajax script upon submit passes the form data to my page validate_login.php:
index.php:

validate_login.php, in this page I run a MySQL query to check If the username and password match. Upon a successful query I echo 'login_success' or upon a fail I echo 'login_wrong'.
validate_login.php:
session_start();
$query = "SELECT * FROM $tbl_name WHERE user_name = '$username' UNION
SELECT * FROM $tbl_name2 where user_name = '$username'";
$result = mysql_query($query) or die( mysql_error() );
$row = mysql_fetch_assoc($result);

$hashed_pass = crypt($password, $Blowfish_Pre . $row['salt'] . $Blowfish_End);

if(mysql_num_rows($result) > 0) {   // Check Username Exists

if($hashed_pass === $row['user_password_hash']) {   // Check Password is valid
$_SESSION['username']=$row['user_first_name'];      //Start User Session
$_SESSION['id']=$row['user_id'];
$_SESSION['user']=$username;
$_SESSION['username2']=$row['user_last_name'];
$_SESSION['allowance']=$row['allowance'];
$_SESSION['privelleges']=$row['privelleges'];
$sql2 = mysql_query("UPDATE $tbl_name2 SET user_failed_logins = '0', user_status = 'online' WHERE user_name = '".$username."'");
$result2=mysql_query($sql2);
$sql3 = mysql_query("UPDATE $tbl_name SET user_failed_logins = '0', user_status = 'online' WHERE user_name = '".$username."'");
$result3=mysql_query($sql2); //Start User Session

echo "login_success";
}else{
echo "login_wrong";

I then use my ajax code to collect these echoed values as data where I perform a check in my ajax to see if the data equals 'login_success' or login_wrong'
if(data == 'login_success') {

If the login is successful I perform an effect which causes my div to flip and display a welcome message:
if(data == 'login_success') {
$(".home_column").flip({
        direction:'lr',
            color: 'rgba(138, 138, 138, 0.2)',
                content:'<h21>Hello <? echo $_SESSION['username']; ?></h21>

<h21>Please Wait...</h21>'
    })

where I have put <?php echo $_SESSION['username']; ?> this is suppose to display the users first name where we earlier set this variable in validate_login.php. However, the ajax appears to be running before the session has time to set/start. This means the session is empty and instead of Hello MichaelI getHello.
So I am trying to echo <?php echo $_SESSION['username']; ?> along with my echo "login_success"; in my validate_login.php instead of in my ajax like so:
echo "login_success";
echo $_SESSION['username'];
    }else{
    echo "login_wrong";

in theory the data (i.e. the user's name) should then be collected along with the other data 'login_success'.
However, I can I collect multiple data in ajax? because if I do this I can no longer perform an if statement to see if data = 'login_success' it just stops the whole script from working completely, thanks in advance

A: You can send back data as JSON by doing so :
echo json_encode( array(
        "item1" => $value1,
        "item2" => $value2
    ));

Then in JS :
$.post("include/validate_login.php", {
    username1: myusername,
    password1: mypassword
}, function(json) {

    console.log(json.item1);
    console.log(json.item2);

}, 'json'); // Don't forget this


text:
Q: Do $Un \to l $ and $f_n(U_n) \to l'$ imply $ f_n(l) \to l' $ Being given a real sequence $(U_n)_n$ $$Un \to l \in R$$
And considering a sequence $(f_n)_n$ of continuous functions such as $$f_n(U_n) \to l' \in R$$
Does if follow that $$ f_n(l) \to l' $$
I tried proving this using another variable $m$ but I don't really know what are the legal operations I can do with that. Here is some suggestion that seems reasonable in the case of continuous functions (but here again, can't prove it):
Is it legal to do : $$\lim_{n \to \infty} f_n(U_n) = \lim_{n \to \infty} \lim_{m \to \infty} f_n(U_m)$$
Thanks <3

A: It does not follow (it is simply not true). Pick the sequence $U_n=1/n$, then $l=0$. Now pick a sequence of continuous functions $(f_n)$ such that $f_n(0)=1$ and $f_n(x)=0$ for $x>1/(2n)$ (construct such functions!). Then $f_n(U_n)=0$ and $f_n(l)=f_n(0)=1$ and thus you will not get equality of your limits.


text:
Q: logical and physical adress in C code in real mode Suppose I write boot loader on C. What happens when I create some global variable? What is it's logical address? How does it correspond to physical address? For example if I created some string (global)
const char* s = "some string";

Am I right that s stored in .data section? What would be the physical address of s and what would be a logical one? Should we do some extra work to make this addresses correspond each other.
My OS is Linux and I compile my code like this:
 as --32 boot.S -o boot.o
 gcc -c -m32 -g -Os -ffreestanding -Wall -Werror -I. -o mbr.o mbr.c
 ld -Tlinker.ld -nostdlib -o mbr boot.o mbr.o

boot.S is just where I initilize some registers and call c code:
.code16

.text
.global _start
_start:
    cli

    xor %ax, %ax
    mov %ax, %ds
    mov %ax, %es
    mov %ax, %ss
    mov $0x7c00, %sp

    ljmp $0, $mmain

mmain -- function in C code. My linker script is:
OUTPUT_FORMAT(binary)
OUTPUT_ARCH(i8086)
ENTRY(_start)

SECTIONS
{
    . = 0x7C00;
    .text : { *(.text) }
    .sig : AT(0x7DFE)
    {
        SHORT(0xaa55);
    }
}


text:
Q: How can I catch only a certain type of ValueError in Python? I process data and for some examples the data are problematic. Python raises a

ValueError: Residuals are not finite in the initial point.

Is there a possibility to catch Value errors only with the message "Residuals are not finite in the initial point."?
I tried:
try:
    [code that could raise the error]
except Exception as e:
    if e=='ValueError(\'Residuals are not finite in the initial point.\')':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

But it still raised the error all the time. Is there a way to achieve what I imagined?
Thanks

A: try:
    [code that could raise the error]
except ValueError as e:
    if len(e.args) > 0 and e.args[0] == 'Residuals are not finite in the initial point.':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

You may have to check if e.args[0] exactly contains this string (provoke the error and print e.args[0])
See also documentation about BaseException.args

A: You can catch a ValueError Exception like this:
try:

    #[code that could raise the error]

except ValueError as e:

    print("Residuals are not finite in the initial point. ...")
    #[do stuff I want when the Residuals are not finite]


text:
Q: Isomorphisms of maximal toral subalgebras Take $L$ a semisimple complex Lie algebra and $H$ a maximal toral subalgebra. I want to prove that given a second maximal toral subalgebra $H'$ then exists an inner automorphism of $L$, $\omega$, such that $\omega(H)=H'$.
I think that a such automorphism must exist from the unicity of the root system but I can't prove that it can be taken inner.
Thanks in advance


text:
Q: Looking for original reference/derivation for expansion of $J_0\left(z\sin\alpha\right)$ in terms of squared Bessel functions and cosines Several tables list the following equality for the Bessel functions $J_{\nu}\left(x\right)$:
$$J_0\left(z\sin\alpha\right)= J_0\left(\frac{z}{2}\right) + 2\sum_{l=1}^{\infty}J_l^2\left(\frac{z}{2}\right) \cos\left(2l\alpha\right)$$
Examples:

*

*Magnus, Wilhelm et al. Formulas and Theorems for the Special Functions of Mathematical Physics. DOI: 10.1007/978-3-662-11761-3

referenced by

*

*Gradshteyn, Izrail Solomonovich et al. Zwillinger, Daniel; Moll, Victor Hugo (eds.). Table of Integrals, Series, and Products
I am trying to find the original source of this expression to see how it was derived (I am not looking for a derivation with this question). Magnus, Wilhelm et al. listed above is the oldest source I have found so far.

A: I traced this expression for $J_0\left(z\sin\alpha\right)$ back to
Carl Neumann. Theorie der Bessel'schen Functionen: Ein Analogon zur Theorie der Kugelfunktionen. B. G. Teubner, Leipzig 1867.
as referenced from
G. N. Watson. A Treatise on the Theory of Bessel Functions, Cambridge University Press.
Actually, the former does not contain the actual expression, but it can be easily constructed from the expressions given and it analyzes the convergence of this series.


text:
Q: Repository class returning null values in ViewModel to recycler view list Here is so far my implementation. I am trying to get the list of Bluetooth devices after the scan is finished. But the observer is not returning a list of devices.
MainActivity.java
public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_CODE_OPEN_GPS = 1;
private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
BluetoothAdapter bluetoothAdapter;

private MutableLiveData<List<DataModel>> deviceLiveData;
public static List<BleDevice> bleDeviceList;
private List<BleDevice> deviceList = new ArrayList<>();

private RecyclerView rvDevices;
private MAdapter devicesAdapter;
private MainViewModel mainViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bleDeviceList = new ArrayList<>();
    rvDevices = findViewById(R.id.main_rv);

    BleManager.getInstance().init(getApplication());
    BleManager.getInstance()
            .enableLog(true)
            .setReConnectCount(5, 5000)
            .setConnectOverTime(20000)
            .setOperateTimeout(5000);
    checkPermissions();
}

private void checkPermissions() {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (!bluetoothAdapter.isEnabled()) {
        Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
        return;
    }

    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    List<String> permissionDeniedList = new ArrayList<>();
    for (String permission : permissions) {
        int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            onPermissionGranted(permission);
        } else {
            permissionDeniedList.add(permission);
        }
    }
    if (!permissionDeniedList.isEmpty()) {
        String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
        ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
    }
}

Observer<List<BleDevice>> userListUpdateObserver = new Observer<List<BleDevice>>() {
    @Override
    public void onChanged(List<BleDevice> userArrayList) {
        devicesAdapter = new MAdapter(MainActivity.this, userArrayList, new MAdapter.OnClick() {
            @Override
            public void onItemClick(View v) {
                Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        rvDevices.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        rvDevices.setAdapter(devicesAdapter);
        devicesAdapter.notifyDataSetChanged();
    }
};

private void onPermissionGranted(String permission) {
    switch (permission) {
        case Manifest.permission.ACCESS_FINE_LOCATION:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                new AlertDialog.Builder(this)
                        .setTitle("Prompt")
                        .setMessage(R.string.gpsNotifyMsg)
                        .setNegativeButton(R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                })
                        .setPositiveButton(R.string.setting,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                        startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                    }
                                })

                        .setCancelable(false)
                        .show();
            } else {
                startScan();

                mainViewModel = new ViewModelProvider(MainActivity.this).get(MainViewModel.class);
                mainViewModel.getUserMutableLiveData().observe(this, userListUpdateObserver);
            }
            break;
    }
}

private boolean checkGPSIsOpen() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager == null)
        return false;
    return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE_OPEN_GPS) {
        if (checkGPSIsOpen()) {
            startScan();
        }
    }
}

@Override
public final void onRequestPermissionsResult(int requestCode,
                                             @NonNull String[] permissions,
                                             @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST_CODE_PERMISSION_LOCATION:
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        onPermissionGranted(permissions[i]);
                    }
                }
            }
            break;
    }
}

public static void startScan() {
    BleManager.getInstance().scan(new BleScanCallback() {
        @Override
        public void onScanStarted(boolean success) {
        }

        @Override
        public void onLeScan(BleDevice bleDevice) {
            super.onLeScan(bleDevice);
        }

        @Override
        public void onScanning(BleDevice bleDevice) {
        }

        @Override
        public void onScanFinished(List<BleDevice> scanResultList) {
            bleDeviceList.addAll(scanResultList);
        }
    });
}

public static void clearScanDevice() {
    for (int i = 0; i < bleDeviceList.size(); i++) {
        BleDevice device = bleDeviceList.get(i);
        if (!BleManager.getInstance().isConnected(device)) {
            bleDeviceList.remove(i);
        }
    }
}

public void addDevice(BleDevice bleDevice) {
    removeDevice(bleDevice);
    String newBleDeviceName = bleDevice.getMac();
    if (newBleDeviceName == null) return;
}

public void removeDevice(BleDevice bleDevice) {
    for (int i = 0; i < bleDeviceList.size(); i++) {
        BleDevice device = bleDeviceList.get(i);
        if (bleDevice.getKey().equals(device.getKey())) {
            bleDeviceList.remove(i);
        }
    }
}

@Override
public void onBackPressed() {
    AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
    builder1.setTitle("Exit?");
    builder1.setMessage("Are you sure you want to disconnect?.");
    builder1.setCancelable(true);

    builder1.setPositiveButton(
            "Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    BleManager.getInstance().disconnectAllDevice();
                    BleManager.getInstance().destroy();
                    Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                    finish();
                }
            });

    builder1.setNegativeButton(
            "No",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

    AlertDialog alert11 = builder1.create();
    alert11.show();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    BleManager.getInstance().disconnectAllDevice();
    BleManager.getInstance().destroy();
}

@Override
protected void onResume() {
    super.onResume();
}

public void clearConnectedDevice() {
    for (int i = 0; i < bleDeviceList.size(); i++) {
        BleDevice device = bleDeviceList.get(i);
        if (BleManager.getInstance().isConnected(device)) {
            bleDeviceList.remove(i);
        }
      }
   }
}

I have the startScan() method in MainActivity.java. There I can get the list of discoverable BleDevices in onScanFinished(). I am trying to implement the same method in the repository class MainDataRepository.java. I am getting null data from that class in MainViewModel.java. Here is my implementation of all classes.
MainDataRepository.java
public class MainDataRepository {
private static final String TAG = "MainDataRepository";
private static final MainDataRepository ourInstance = new MainDataRepository();

private MutableLiveData<List<BleDevice>> deviceListLiveData = new MutableLiveData<>();

public static MainDataRepository getInstance() {
    return ourInstance;
}

public MutableLiveData<List<BleDevice>> getTodos() {
    BleManager.getInstance().scan(new BleScanCallback() {
        @Override
        public void onScanStarted(boolean success) {
            Log.d("View Model", "scAN started");
        }

        @Override
        public void onLeScan(BleDevice bleDevice) {
            super.onLeScan(bleDevice);
            Log.d("onLeScan", "onLeScan: View Model");
        }

        @Override
        public void onScanning(BleDevice bleDevice) {
            Log.d("View Model", "scannig");
        }

        @Override
        public void onScanFinished(List<BleDevice> scanResultList) {
            Log.d("View Model", "onScanFinished: " + scanResultList.size());
            for (int i = 0; i < scanResultList.size(); i++) {
                Log.d("View Model", "onScanFinished: " + scanResultList.get(i).getName() + " and " + scanResultList.get(i).getMac());
            }
        }
    });
    return deviceListLiveData;
  }
}

MainViewModel.java
 public class MainViewModel extends ViewModel {

private MutableLiveData<List<BleDevice>> userLiveData;
public static List<BleDevice> deviceArrayList = new ArrayList<>();
private MainDataRepository repository = MainDataRepository.getInstance();

public MainViewModel() {
    super();
    userLiveData = new MutableLiveData<>();
    userLiveData = repository.getTodos();
    Log.d("View Model", "MainViewModel: " + userLiveData.getValue());
    init();
}

public MutableLiveData<List<BleDevice>> getUserMutableLiveData() {
    return userLiveData;
}

public void init() {
    populateList();
    userLiveData.setValue(deviceArrayList);
}

public void populateList() {
    deviceArrayList = new ArrayList<>();
    Log.d("Inside Populate", "populateList: ");
  }
}

MAdapter.java
public class MAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context mContext;
private List<BleDevice> bleDeviceList;
public OnClick click;

public MAdapter(Context mContext, List<BleDevice> bleDeviceList, OnClick click) {
    this.mContext = mContext;
    this.bleDeviceList = bleDeviceList;
    this.click = click;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View rootView = LayoutInflater.from(mContext).inflate(R.layout.card_ll, parent, false);
    return new MViewHolder(rootView);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    BleDevice device = bleDeviceList.get(position);
    ((MViewHolder) holder).tvName.setText(device.getName());
    ((MViewHolder) holder).tvMac.setText(device.getMac());
    ((MViewHolder) holder).btnConnect.setText("Pair");

    ((MViewHolder) holder).btnConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            click.onItemClick(v);
            ((MViewHolder) holder).btnConnect.setText("Paired");
            ((MViewHolder) holder).btnConnect.setClickable(false);
        }
    });
}

@Override
public int getItemCount() {
    return bleDeviceList.size();
}

static class MViewHolder extends RecyclerView.ViewHolder {

    private TextView tvName, tvMac;
    private Button btnConnect;

    public MViewHolder(@NonNull View itemView) {
        super(itemView);

        tvName = itemView.findViewById(R.id.device_name);
        tvMac = itemView.findViewById(R.id.device_mac_address);
        btnConnect = itemView.findViewById(R.id.btn_connect);
    }
}

public interface OnClick {
    public void onItemClick(View v);
 }
}

Thanks in advance.


text:
Q: LG G2 call log types are different from Android CallLog.Calls reference I am trying to write an app the analyses user's call logs and find out 'close' people from the recent call activities.  I am working with a G2, and I am facing an issue.
Reading from the CallLog.Calls Android Developers References, there are pre-defined values that should match the call activities.  But, the G2 is giving me very different values at the moment.
For example, OUTGOING ought to be of value 2, but the examining the call log, it seems to hold value 6502.  All calls have "650" in front of the desired values.  Also, SMS/MMS are showing up in CallLog.Calls with values that are 3 integers long and start with 8.
Is this the case only for LG G2, or other recently release smart phones?  How should I develop the app so it can be used on all phones?  If LG does it in its own way, other manufacturers may as well?  I cannot afford phones from all manufacturers to check their values.
Please advise me regarding the issue!  I am using the following piece of code to get the Type value.
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
String callType = cursor.getString(type);


text:
Q: Distance from eigenspace of matrix In linear algebra, is there a separate name / concept for the notion of distance between linear vector subspaces?
I'm asking this because I'm considering a problem in numerical linear algebra where a Krylov subspace iterative method is used. Since for every subsequent $n$ a Krylov subspace method implicitly generates an additional basis vector in Krylov subspace, which approaches the eigenspace of the matrix for which the problem $$Ax=b$$ is being solved, it must be true that if $b$ is in the span of the eigenspace of $A$ then the convergence will happen faster.
But what if $b$ is very "far" from the eigenspace? I'm trying to think about what the notion of a distance between two vector subspaces could mean or how it could be defined. Would a vector $b$ contained in a subspace "far away" from the eigenspace of $A$ make iteration of a Krylov subspace method take longer than in a general case?

A: The common notion of distance is to consider an orthogonal projection $P$ onto the first linear subspace $V$, and an orthogonal projection $Q$ onto the other subspace $W$.
At this point we can define
$$d(V,W) = \| P - Q \|$$ as the distance between these subspaces, where the norm used is the operator norm. For properties and applications see Section 2.5.3 of Golub and Van Loan.
This distance metric is used throughout GVL's exposition on unsymmetrical eigenvalue problems (which involve Krylov methods) — see Chapter 7.


text:
Q: Pytorch : Pass from grid to image coordinate convention for use of grid_sample I need to interpolate some deformation grid in PyTorch and decided to use the function grid_sample (see doc). I need to reshape grids as images back and forth with theses conventions :

*

*N Batch size

*D grid depth (for 3D images)

*H grid height

*W grid width

*d grid dimension (=2 or 3)

images format is (N,2,H,W) in 2D (resp. (N,3,D,H,W) in 3D)
when grid format is (N,H,W,2) (resp. (N,D,H,W,3)in 3D)
I can't use reshape or view because they do not arrange the data as I wish. I need to have (for example)
grid_in_grid_convention[0,:,:,0] == grid_in_image_convention[0,0,:,:]

I came up with theses functions to make the reshaping which works fine but I am sure that there is a more compact/fast way to do so. What are your taught ?
def grid2im(grid):
    """Reshape a grid tensor into an image tensor
        2D  [T,H,W,2] -> [T,2,H,W]
        3D  [T,D,H,W,2] -> [T,D,H,W,3]
    """
    if grid.shape[0] == 1 and grid.shape[-1] == 2: # 2D case, batch =1
        return torch.stack((grid[0,:,:,0],grid[0,:,:,1]),dim = 0).unsqueeze(0)

    elif grid.shape[0] == 1 and grid.shape[-1] == 3: # 3D case, batch =1
        return torch.stack((grid[0,:,:,:,0],grid[0,:,:,:,1],grid[0,:,:,:,2]),
                            dim = 0).unsqueeze(0)

    elif grid.shape[-1] == 2:
        N,H,W,d = grid.shape
        temp = torch.zeros((N,H,W,d))
        for n in range(N):
            temp[n,:,:,:] = torch.stack((grid[n,:,:,0],grid[n,:,:,1]),dim = 0).unsqueeze(0)
        return temp

    elif grid.shape[-1] == 3:
        N,D,H,W,d =grid.shape
        temp = torch.zeros((N,D,H,W,d))
        for n in range(N):
            temp[n,:,:,:,:] = torch.stack((grid[n,:,:,:,0],
                                           grid[n,:,:,:,1],
                                           grid[n,:,:,:,2]),
                            dim = 0).unsqueeze(0)
    else:
        raise ValueError("input argument expected is [N,H,W,2] or [N,D,H,W,3]",
                         "got "+str(grid.shape)+" instead.")

def im2grid(image):
    """Reshape an image tensor into a grid tensor
        2D case [T,2,H,W]   ->  [T,H,W,2]
        3D case [T,3,D,H,W] ->  [T,D,H,W,3]
    """
    # No batch
    if image.shape[0:2] == (1,2):
        return torch.stack((image[0,0,:,:],image[0,1,:,:]),dim= 2).unsqueeze(0)
    elif image.shape[0:2] == (1,3):
        return torch.stack((image[0,0,:,:],image[0,1,:,:],image[0,2,:,:]),
                           dim = 2).unsqueeze(0)
    # Batch size > 1
    elif image.shape[0] > 0 and image.shape[1] == 2 :
        N,d,H,W = image.shape
        temp = torch.zeros((N,H,W,d))
        for n in range(N):
            temp[n,:,:,:] = torch.stack((image[n,0,:,:],image[n,1,:,:]),dim= 2).unsqueeze(0)
        return temp
    elif image.shape[0] > 0 and image.shape[1] == 3 :
        N,d,D,H,W = image.shape
        temp = torch.zeros((N,D,H,W,d))
        for n in range(N):
            temp[n,:,:,:] = torch.stack((image[n,0,:,:],
                                         image[n,1,:,:],
                                         image[n,2,:,:]),
                           dim = 2).unsqueeze(0)
        return temp
    else:
        raise ValueError("input argument expected is [1,2,H,W] or [1,3,D,H,W]",
                         "got "+str(image.shape)+" instead.")

A: You can use transpose(). For example, if you want [T,H,W,2] -> [T,2,H,W] for a tensor, say grid, you can do
grid = grid.transpose(2,3).transpose(1,2)

A: The ihdv answer is correct. Thank you !
I complete here the answer with the two functions above corrected in a way more efficient and elegant way.
def grid2im(grid):
    """Reshape a grid tensor into an image tensor
        2D  [T,H,W,2] -> [T,2,H,W]
        3D  [T,D,H,W,2] -> [T,D,H,W,3]
    """
    if grid.shape[-1] == 2: # 2D case
        return grid.transpose(2,3).transpose(1,2)

    elif grid.shape[-1] == 3: # 3D case
        return grid.transpose(3,4).transpose(2,3).transpose(1,2)
    else:
        raise ValueError("input argument expected is [N,H,W,2] or [N,D,H,W,3]",
                         "got "+str(grid.shape)+" instead.")

def im2grid(image):
    """Reshape an image tensor into a grid tensor
        2D case [T,2,H,W]   ->  [T,H,W,2]
        3D case [T,3,D,H,W] ->  [T,D,H,W,3]
    """
    # No batch
    if image.shape[1] == 2:
        return image.transpose(1,2).transpose(2,3)
    elif image.shape[1] == 3:
        return image.transpose(1,2).transpose(2,3).transpose(3,4)
    else:
        raise ValueError("input argument expected is [1,2,H,W] or [1,3,D,H,W]",
                         "got "+str(image.shape)+" instead.")


text:
Q: R: Customizing the Travelling Salesman Problem I am working with the R programming language.
I found this (very good) tutorial that shows how to implement the Genetic Algorithm for the Travelling Salesman Problem (for a set of European cities) in R: https://rstudio-pubs-static.s3.amazonaws.com/132872_620c10f340f348b88453d75ec99960ff.html
library(GA)
data("eurodist", package = "datasets")
D <- as.matrix(eurodist)

tourLength <- function(tour, distMatrix) {
   tour <- c(tour, tour[1])
   route <- embed(tour, 2)[,2:1]
   sum(distMatrix[route])
}

#Firness function to be maximized

tspFitness <- function(tour, ...) 1/tourLength(tour, ...)

GA <- ga(type = "permutation", fitness = tspFitness, distMatrix = D,
          min = 1, max = attr(eurodist, "Size"), popSize = 50, maxiter = 5000,
          run = 500, pmutation = 0.2)

In the end, the algorithm returns the order in which you should visit these cities (indexed by their number):
    summary(GA)

## Solutions              =
##      x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19
## [1,] 20  7 11  3  4  5 18 13 12   9  14   2  15   8  16  19   1  21  17
## [2,]  6 10 20  7 11  3  4  5 18  13  12   9  14   2  15   8  16  19   1
## [3,] 10  6 17 21  1 19 16  8 15   2  14   9  12  13  18   5   4   3  11
##      x20 x21
## [1,]   6  10
## [2,]  21  17
## [3,]   7  20

We can even see a visualization of the path returned by the algorithm:

My Question:

*

*Is it possible to "customize" this problem by adding some constraints? For instance, suppose you absolutely want to start your trip in Vienna - is there a way to tell the Genetic Algorithm to begin searching for the optimal path with the first city being Vienna?

*Is it possible to instruct the Genetic Algorithm to have certain cities in certain positions? For example, you want the first city to be Vienna and the sixth city to be Athens - and then, search for the optimal path given these constraints?
Is it possible to customize the Genetic Algorithm in R to take these "considerations" into account when optimizing the Travelling Salesman Problem?

A: To expand on my comment. When dealing with constraints in genetic algorithm you have two options:

*

*incorporate conditions in fitness function

*insure that genetic operators create feasible solutions

With first approach you need to decide what to do with infeasible solutions (ex. penalization) and that is extremely problem dependent. If conditions are hard to achieve most of the solutions that evolutionary algorithm creates in the process will be infeasible and it will cause premature convergence.
Which approach to adapt is problem dependent, I'll show you how to implement 2nd approach for this problem.
matrix transformation:
transformMatrix <- function(fixed_points, D){

  if(length(fixed_points) == 0) return(D)

  p <- integer(nrow(D))
  pos <- match(names(fixed_points), colnames(D))
  p[fixed_points] <- pos
  p[-fixed_points] <- sample(setdiff(seq_len(nrow(D)), pos))

  D[p, p]
}

goal of this function is to permute rows and columns of matrix to get cities to their specified  positions:
popSize <- 100
fixed_points <- c(
  "Vienna" = 1,
  "Athens" = 6
)
D_perm <- transformMatrix(fixed_points, D)

feasible initial population
feasiblePopulation <- function(n, size, fixed_points){

  positions <- setdiff(seq_len(n), fixed_points)

  m <- matrix(0, size, n)
  if(length(fixed_points) > 0){

    m[, fixed_points] <- rep(fixed_points, each = size)

    for(i in seq_len(size))
      m[i, -fixed_points] <- sample(positions)

  } else {

    for(i in seq_len(size))
      m[i,] <- sample(positions)
  }

  m
}

this function creates feasible solutions
mutation
mutation <- function(n, fixed_points){

  positions <- setdiff(seq_len(n), fixed_points)

  function(obj, parent){

    vec <- obj@population[parent,]
    if(length(positions) < 2) return(vec)

    indices <- sample(positions, 2)
    replace(vec, indices, vec[rev(indices)])
  }
}

we need to ensure that mutation operator keeps fixed positions in place. This function returns one such mutation operator.
fitness function
fitness <- function(tour, distMatrix) {

  tour <- c(tour, tour[1])
  route <- embed(tour, 2)[,2:1]
  1/sum(distMatrix[route])
}

We want to minimize distance hence taking the reciprocal.
optimization step
res <- ga(
  type = "permutation",
  fitness = fitness,
  distMatrix = D_perm,
  lower = 1,
  upper = nrow(D_perm),
  mutation = mutation(nrow(D_perm), fixed_points),
  crossover = gaperm_pmxCrossover,
  suggestions = feasiblePopulation(nrow(D_perm), popSize, fixed_points),
  popSize = popSize,
  maxiter = 5000,
  run = 500,
  pmutation = 0.2
)

gaperm_pmxCrossover will insure that fixed positions stay fixed during the crossover process (that is why I didn't write custom crossover operator)
solution
colnames(D_perm)[res@solution[1,]]
solution_distance <- 1 / fitness(res@solution[1,], D_perm)

Also first city is last (route)


text:
Q: MousePressEvent Not Functioning Correctly on Touchscreen I am noticing that my MousePressEvent functions are not working as intended when I use the touchscreen functionality of my computer.
The buttons on my GUI are intended to change color on a press event and on release, return to original color and perform a function.
There are four scenarios:

*

*Mouse press on the QLabel button and instantly release - Works as intended

*Mouse press on the QLabel button, drag mouse, and release (slight delay in hold) - Works as intended

*Finger press on the QLabel and instantly release (normal tap) - does not change image color but performs the function in MouseReleaseEvent.

*Finger press on the QLabel, drag finger, and release (slight delay in hold) - Works as intended

Even a long hold in the same position on scenario 3 doesn't cause the image to change color, I have to drag my finger for a 1/4 second to make it work.
This is my code:
self.saveImageBTN = QtWidgets.QLabel(self.cameraViewer)
self.saveImageBTN.setPixmap(QPixmap("Graphics/saveImageButton.png").scaled(100,100))
self.saveImageBTN.setGeometry(QtCore.QRect(110, 610, 100, 100))
self.saveImageBTN.setObjectName("saveImageBTN")
self.saveImageBTN.mousePressEvent = self.saveImageButtonPress
self.saveImageBTN.mouseReleaseEvent = self.saveImageButtonRelease

def saveImageButtonPress(self, event):
       self.saveImageBTN.setPixmap(QPixmap("Graphics/saveImageButtonPressed.png").scaled(100,100))

def saveImageButtonRelease(self, event):
       self.saveImageBTN.setPixmap(QPixmap("Graphics/saveImageButton.png").scaled(100,100))
       self.ImagePlayer.saveImage()

I have tried to add delays around the code in my saveImageButtonPress function to account for touchscreen latency but it doesn't seem to help.
Any help appreciated.


text:
Q: Swift Animation To 'Throw' Image to Center of Screen So I was playing around with animations tonight and trying to code the one I had in mind. So I have these two UIImageViews in opposite corners and I want them to go to the center of the screen (over the course of say, two seconds). I don't want the animiation to be linear though, I want it to be a trajectory motion. I tried the CGAffineTransformation struct to transform my images, but I don't  think that was what I was looking for because the transformation is linear movement. I have only been working with animations for a couple of hours and I don't know much. I know you can animate with a spring effect, but how would I get the image to spring vertically instead of horizontally?
I'm not sure if there is an easy way to create this animation, or if I have to create physics properties on the images and tinker around with it for awhile. If none of this is clear, here is image that might help (pardon my bad MS paint skills lol). So the bottom left image is the red/orange path and I want it shoot up and reach the center. The same idea applies for the top right (green); I'm fine with the image leaving the screen for a fraction of a second, as you can see.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var theImage: UIImageView! //top right image
    @IBOutlet weak var profilepic: UIImageView! //bottom left image

    override func viewDidLoad() {
        super.viewDidLoad()
        UIView.animate(withDuration: 2.0) {
            //don't know what goes here
        }
    }
}

A: This will help you to animate imageview to the center.
UIView.animate(withDuration: 1.0, animations: {

  //Your imageview
  self.imageView.center = CGPoint(x: self.view.frame.size.width/2, y: self.view.frame.size.height/2)

  self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

 }, completion:nil)


text:
Q: Implement stream with multicast that doesn't complete the underlying subject I'm implementing the cache using BehaviorSubject and multicast. The stream returned from the cache should start with HTTP request. I should also be able to force refresh the cache by triggering manually next on subject. The common approach with two subjects outlined by Poul Kruijt is well known and suggested everywhere. My idea is to find a way to achieve the following using only one subject throughout lifecycle of a stream.
It would be easy to achieve with multicast like this
const cache = new BehaviorSubject(null);
const shared = queryThatCompletes.pipe(multicast(cache)) as any;

// sets up subscription, waits for connect
shared.subscribe((values) => console.log(values));

// triggers http request
shared.connect();

setTimeout(() => {
  // will only emit COMPLETE from subject
  shared.subscribe((values) => console.log(values));
}, 2000);

// force refresh the cache
cache.next();

but since the HTTP query stream completes, the second subscription doesn't get any value, just COMPLETE notification from subject. This behavior is described in detail here.
The other option is to pass a factory function instead of the subject instance like this:
const cache = ()=> new BehaviorSubject(null);
const shared = queryThatCompletes.pipe(multicast(cache)) as any;

This will re-create the subject, that will subscribe to queryThatCompletes and re-trigger HTTP request. But the downsides is the need to call connect multiple times and redundant queries.
const cache = () => new BehaviorSubject(null);
const shared = queryThatCompletes.pipe(multicast(cache)) as any;

// sets up subscription, waits for connect
shared.subscribe((values) => console.log(values));

// triggers http request
shared.connect();

setTimeout(() => {
// sets up subscription, waits for connect
  shared.subscribe((values) => console.log(values));

  // triggers http request
  shared.connect();
}, 2000);

So I simply implemented HTTP stream that doesn't complete by itself and use it like this:
const queryOnceButDontComplete = new Observable((observer) => {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(data => observer.next(data));

  return () => {};
});

const cache = new BehaviorSubject(null);
const shared = queryOnceButDontComplete.pipe(multicast(cache)) as any;

// sets up subscription, waits for connect
shared.subscribe((values) => console.log(values));

// triggers http request
shared.connect();

setTimeout(() => {
// sets up subscription, waits for connect
  shared.subscribe((values) => console.log(values));
}, 2000);

This works, but I'm wondering if there's a way to achieve what I want without the use of custom observable. Any ideas?

A: Best would be to just use a shareReplay(1):
const shared = queryThatCompletes.pipe(shareReplay(1));

// sets up subscription, waits for connect
shared.subscribe((values) => console.log(values));

// triggers http request
shared.connect();

setTimeout(() => {
  shared.subscribe((values) => console.log(values));
}, 2000);

Not entirely sure what the subscribe and connect are doing there, but if you are just returning a HttpClient get call, then you should just return the shared observable, and whomever subscribes first to it, will trigger the http request. No need for connect. Any subsequent subscriptions will wait for the request to finish or receive the last emitted value from the observable.

Based on your comment, let's wrap this in a service (untested):
@Injectable()
SomeDataService {
  readonly refresh$ = new BehaviorSubject(undefined);

  readonly get$ = this.httpClient.get(/*url here*/);

  readonly shared$ = this.refresh$.pipe(
    switchMap(() => this.get$),
    shareReplay(1)
  );

  constructor(private httpClient: HttpClient) {}

  getData(): Observable<unknown> {
    return this.shared$;
  }

  refreshData(): void {
    this.refresh$.next();
  }
}

Does this make sense? Basically you start with a refresh subject, which get mapped to the actual network call. On the first getData(), the network request gets triggered. Any call on getData() after that will get the cached value. Calling refreshData will refresh the data for any subscription

A: I have made functional approach that I believe is much more simpler
it uses two observables refresh$ and the desired observable,
I hope this solution might give you some thoughts
 const makeRestartableCahcedObservable = (ob:Observable<any>)=>{
  const refresh$ = new BehaviorSubject(null)
  return [
    refresh$.pipe(
    switchMap(()=>ob),
    shareReplay(1)
  ),
  ()=>refresh$.next(null)
]
}

const [ob, refreshFun] = makeRestartableCahcedObservable(of('string'))

ob.subscribe(console.log)

setTimeout(()=>{refreshFun()}, 3000)

this basically can refresh your data with much more simpler API,
you can even wrap it with an object to make it a proxy with included refresh function
const makeRestartableCahcedObservable = (ob:Observable<any>)=>{
  const refresh$ = new BehaviorSubject(null)
  const wrappedOb$ = refresh$.pipe(switchMap(()=>ob),shareReplay(1))
  return {
    subscribe:(...args)=>wrappedOb$.subscribe(...args),
    pipe:(...funs)=>wrappedOb$.pipe(...funs),
    refresh:()=>refresh$.next(null)
  }
}

const ob = makeRestartableCahcedObservable(of('string'))

ob.subscribe(console.error)

setTimeout(()=>{ob.refresh()}, 3000)