text:
Q: There are something wrong with variable in PHP. the variable can't be added. Why? There are something wrong with the variable in PHP.
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);

require_once( dirname( __FILE__ ) .'/class.responsive-bbs.php' );

class Responsive_Bbs_Write Extends Responsive_Bbs {

    // property init
    protected $post_title           = 'タイトルなし';
    protected $post_time            = '';
    protected $post_name            = '';
    protected $post_contents        = '';
    protected $post_note            = '';
    protected $addr                 = '';
    protected $remote_addr                 = '';
    protected $remote_host                 = '';
    protected $remote_port                 = '';
    protected $http_user_agent                 = '';
    protected $http_referer                 = '';
    protected $http_accept_language                 = '';

    // mail-notification addon property
    protected $order_isset          = array();
    protected $order_count          = '0';

    // public construct
    public function __construct() {

        parent::__construct();

    }

    //投稿内容を取得してグローバル変数に保存
    // public post_check
    public function post_check() {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( isset( $_POST['title'] ) && $_POST['title'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['title']."\n","3","./log/debug.log");

            $this->post_title = htmlspecialchars( $_POST['title'], ENT_QUOTES, 'UTF-8' );
        }

        $this->post_time = date( 'Y-m-d H:i:s' );

        if ( isset( $_POST['name'] ) && $_POST['name'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['name']."\n","3","./log/debug.log");

            $this->post_name = htmlspecialchars( $_POST['name'], ENT_QUOTES, 'UTF-8' );
        }

        if ( isset( $_POST['subscribe2'] ) && $_POST['subscribe2'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['subscribe2']."\n","3","./log/debug.log");

        //  $this->post_name = htmlspecialchars( $_POST['subscribe'], ENT_QUOTES, 'UTF-8' );
        }
        //ここでチェックボックスの内容を取得できる。
        if ( isset( $_POST['subscribe'] ) && $_POST['subscribe'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['subscribe']."\n","3","./log/debug.log");
            $subscribe=$_POST['subscribe'];
            foreach($subscribe as $subscribe_name){
                error_log(__FILE__.'('.__LINE__.')'.$subscribe_name."\n","3","./log/debug.log");
                $this->post_contents=$this->post_contents.$subscribe_name;
                }
            error_log(__FILE__.'('.__LINE__.')'.$subscribe."\n","3","./log/debug.log");

            error_log(__FILE__.'('.__LINE__.')'.$_POST['subscribe']."\n","3","./log/debug.log");

        //  $this->post_name = htmlspecialchars( $_POST['subscribe'], ENT_QUOTES, 'UTF-8' );
        }
        //書き換えた内容を取得。
        if ( isset( $_POST['input-note'] ) && $_POST['input-note'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['input-note']."\n","3","./log/debug.log");
            $this->post_note=$_POST['input-note'];
            error_log(__FILE__.'('.__LINE__.')'.$this->$post_note."\n","3","./log/debug.log");

        //  $this->post_name = htmlspecialchars( $_POST['subscribe'], ENT_QUOTES, 'UTF-8' );
        }

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( isset( $_POST['contents'] ) && $_POST['contents'] !== '' ) {
            error_log(__FILE__.'('.__LINE__.')'.$_POST['contents']."\n","3","./log/debug.log");

            $this->post_contents = htmlspecialchars( $_POST['contents'], ENT_QUOTES, 'UTF-8' );
            $this->post_contents = nl2br( $this->post_contents );
            $this->post_contents = str_replace( array( "\n", "\r", "\r\n" ), '', $this->post_contents );
        }

        if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
            error_log(__FILE__.'('.__LINE__.')'.$_SERVER."\n","3","./log/debug.log");
            foreach($_SERVER as $servername){
                error_log(__FILE__.'('.__LINE__.')'.$servername."\n","3","./log/debug.log");
                }
            $this->addr = htmlspecialchars( $_SERVER['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8' );
            //HTTP変数
            $this->$remote_addr         = htmlspecialchars($_SERVER['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8' );
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_addr ."\n","3","./log/debug.log");

            $this->$remote_host         = htmlspecialchars($_SERVER['REMOTE_HOST'], ENT_QUOTES, 'UTF-8' );
            $this->$remote_port         = htmlspecialchars($_SERVER['REMOTE_PORT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_user_agent     = htmlspecialchars($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_referer            = htmlspecialchars($_SERVER['HTTP_REFERER'], ENT_QUOTES, 'UTF-8' );
            $this->$http_accept_language    = htmlspecialchars($_SERVER['HTTP_ACCEPT_LANGUAGE'], ENT_QUOTES, 'UTF-8' );
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_addr ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_host ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_port ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$http_user_agent ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->addr."\n","3","./log/debug.log");

        }
    }

    // public bbs_write
    public function knowlege_write() {

        $post_res  = '0';

        if ( isset( $_POST['response-number'] ) && $_POST['response-number'] !== '' ) {
            $post_res = htmlspecialchars( $_POST['response-number'], ENT_QUOTES, 'UTF-8' );
        }
        // uniqid関数、ID作成
        $main_data_id = uniqid();
        $ref_data_id = uniqid();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        $stmt = $this->pdo->prepare( "INSERT INTO rb_post ( id, title, time, user_id, contents, res, delegate, remote_addr ) VALUES ( :id, :title, :time, :user_id, :contents, :res, 'true', :remote_addr)" );
        $stmt->bindParam( ':id', $main_data_id );
        $stmt->bindParam( ':title', $this->post_title );
        $stmt->bindParam( ':time', $this->post_time );
        $stmt->bindParam( ':user_id', $this->post_name );
        $stmt->bindParam( ':contents', $this->post_contents );
        $stmt->bindParam( ':res', $post_res );
        $stmt->bindParam( ':remote_addr', $this->addr );
        $stmt->execute();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( $stmt->errorInfo()[0] !== '00000' ) {
            echo 'write_failed,'.$this->post_time.','.$this->url;
        } else {
            $this->mail_send();
            echo 'write_success,'.$this->post_time.','.$this->url;
        }
        //自分が書き換えた書き込み
        $stmt = $this->pdo->prepare( "INSERT INTO rb_post ( id, title, time, user_id, contents, res, delegate, remote_addr ) VALUES ( :id, :title, :time, :user_id, :contents, :res, 'true', :remote_addr)" );
        $stmt->bindParam( ':id', $ref_data_id );
        $stmt->bindParam( ':title', $this->post_title );
        $stmt->bindParam( ':time', $this->post_time );
        $stmt->bindParam( ':user_id', $this->post_name );
        $stmt->bindParam( ':contents', $this->post_note );
        $stmt->bindParam( ':res', $post_res );
        $stmt->bindParam( ':remote_addr', $this->addr );
        $stmt->execute();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( $stmt->errorInfo()[0] !== '00000' ) {
            echo 'write_failed,'.$this->post_time.','.$this->url;
        } else {
            $this->mail_send();
            echo 'write_success,'.$this->post_time.','.$this->url;
        }
        $category_no=0;

        $stmt = $this->pdo->prepare( "INSERT INTO rb_main ( id, title, time, user_id, reference_id, category, res, remote_addr, remote_host, remote_port, http_user_agent, http_referer, http_accept_language ) VALUES ( :id, :title, :time, :user_id, :reference_id, :category, :res, :remote_addr, :remote_host, :remote_port, :http_user_agent, :http_referer, :http_accept_language)" );
        $stmt->bindParam( ':id', $main_data_id );
        $stmt->bindParam( ':title', $this->post_title );
        $stmt->bindParam( ':time', $this->post_time );
        $stmt->bindParam( ':user_id', $this->post_name );
        $stmt->bindParam( ':reference_id', NULL );
        $stmt->bindParam( ':category', $category_no );
        $stmt->bindParam( ':res', $post_res );
        $stmt->bindParam( ':remote_addr', $this->$remote_addr );
        $stmt->bindParam( ':remote_host', $this->$remote_host );
        $stmt->bindParam( ':remote_port', $this->$remote_port );
        $stmt->bindParam( ':http_user_agent', $this->$http_user_agent );
        $stmt->bindParam( ':http_referer', $this->$http_referer );
        $stmt->bindParam( ':http_accept_language', $this->$http_accept_language );
        $stmt->execute();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( $stmt->errorInfo()[0] !== '00000' ) {
            error_log(__FILE__.'('.__LINE__.')'.'write_failed,'.$this->post_time.','.$this->url."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.'write_failed,'.$this->post_time.','.$this->url.$stmt->errorInfo()[0]."\n","3","./log/debug.log");

            echo 'write_failed,'.$this->post_time.','.$this->url;
        } else {
            $this->mail_send();
            error_log(__FILE__.'('.__LINE__.')'.'write_success,'.$this->post_time.','.$this->url."\n","3","./log/debug.log");

            echo 'write_success,'.$this->post_time.','.$this->url;
        }
        //自分が書き換えた書き込み
        $stmt = $this->pdo->prepare( "INSERT INTO rb_main ( id, title, time, user_id, reference_id, category, res, remote_addr, remote_host, remote_port, http_user_agent, http_referer, http_accept_language ) VALUES ( :id, :title, :time, :user_id, :reference_id, :category, :res, :remote_addr, :remote_host, :remote_port, :http_user_agent, :http_referer, :http_accept_language)" );
        $stmt->bindParam( ':id', $ref_data_id );
        $stmt->bindParam( ':title', $this->post_title );
        $stmt->bindParam( ':time', $this->post_time );
        $stmt->bindParam( ':user_id', $this->post_name );
        $stmt->bindParam( ':reference_id', $main_data_id );
        $stmt->bindParam( ':category', $category_no );
        $stmt->bindParam( ':res', $post_res );
        $stmt->bindParam( ':remote_addr', $this->$remote_addr );
        $stmt->bindParam( ':remote_host', $this->$remote_host );
        $stmt->bindParam( ':remote_port', $this->$remote_port );
        $stmt->bindParam( ':http_user_agent', $this->$http_user_agent );
        $stmt->bindParam( ':http_referer', $this->$http_referer );
        $stmt->bindParam( ':http_accept_language', $this->$http_accept_language );
        $stmt->execute();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( $stmt->errorInfo()[0] !== '00000' ) {
            error_log(__FILE__.'('.__LINE__.')'.'write_failed,'.$this->post_time.','.$this->url."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.'write_failed,'.$this->post_time.','.$this->url.$stmt->errorInfo()[0]."\n","3","./log/debug.log");

            echo 'write_failed,'.$this->post_time.','.$this->url;
        } else {
            $this->mail_send();
            error_log(__FILE__.'('.__LINE__.')'.'write_success,'.$this->post_time.','.$this->url."\n","3","./log/debug.log");

            echo 'write_success,'.$this->post_time.','.$this->url;
        }

    }

    // public bbs_write
    public function bbs_write() {

        $post_res  = '0';

        if ( isset( $_POST['response-number'] ) && $_POST['response-number'] !== '' ) {
            $post_res = htmlspecialchars( $_POST['response-number'], ENT_QUOTES, 'UTF-8' );
        }

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        $stmt = $this->pdo->prepare( "INSERT INTO rb_post ( id, title, time, user_id, contents, res, delegate, remote_addr ) VALUES ( :id, :title, :time, :user_id, :contents, :res, 'true', :remote_addr)" );
        $stmt->bindParam( ':id', $this->post_title );
        $stmt->bindParam( ':title', $this->post_title );
        $stmt->bindParam( ':time', $this->post_time );
        $stmt->bindParam( ':user_id', $this->post_name );
        $stmt->bindParam( ':contents', $this->post_contents );
        $stmt->bindParam( ':res', $post_res );
        $stmt->bindParam( ':remote_addr', $this->addr );
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        $stmt->execute();

        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( $stmt->errorInfo()[0] !== '00000' ) {
            echo 'write_failed,'.$this->post_time.','.$this->url;
        } else {
            $this->mail_send();
            echo 'write_success,'.$this->post_time.','.$this->url;
        }

    }

    // public bbs_edit
    public function bbs_edit() {

            $update_stmt = $this->pdo->prepare( "UPDATE rb_post SET title = :title, name = :name, contents = :contents WHERE ( id = :id )" );

    }

    // public bbs_delete
    public function bbs_delete() {

        $delete_post_id = '';

        if ( isset( $_POST['delete-number'] ) && $_POST['delete-number'] !== '' ) {
            $delete_post_id = htmlspecialchars( $_POST['delete-number'], ENT_QUOTES, 'UTF-8' );
        }

        $stmt = $this->pdo->prepare( "SELECT * FROM rb_post WHERE ( id = :id )" );
        $stmt->bindParam( ':id', $delete_post_id );
        $stmt->execute();

        $row = $stmt->fetch();
        if ( $row['res'] === '0' ) {

            $delete_stmt = $this->pdo->prepare( "DELETE FROM rb_post WHERE ( id = :id )" );
            $delete_stmt->bindParam( ':id', $delete_post_id );
            $delete_stmt->execute();

        } else {

        }

        if ( $delete_stmt->errorInfo()[0] !== '00000' ) {
            echo 'delete_failed,'.$this->url;
        } else {
            echo 'delete_success,'.$this->url;
        }

    }

    // public url_check
    public function url_check() {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

    }

    // public block_ip
    public function block_ip() {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

    }

    // public block_word
    public function block_word() {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

    }

    // public mail_send
    public function mail_send() {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

        if ( ! isset( $_SESSION['responsive_bbs_login'] ) ) {

        }

    }

    // public approval_change
    public function approval_change( $mode ) {
        error_log(__FILE__.'('.__LINE__.')'."\n","3","./log/debug.log");

    }

}

?>

When I tried to use "$post_note" that is grobal variable, even I add the some variable there. It bacame empty!
I checked my code many times but there are no problem.
But other grobal variable can use normaly only "$post_note" has problem.
Additional question.
And when I tried to use
    protected $remote_addr                 = '';
    protected $remote_host                 = '';
    protected $remote_port                 = '';
    protected $http_user_agent                 = '';
    protected $http_referer                 = '';
    protected $http_accept_language                 = '';

these global variable, everything add same variable.
            $this->$remote_addr         = htmlspecialchars($_SERVER['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8' );
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_addr ."\n","3","./log/debug.log");

            $this->$remote_host         = htmlspecialchars($_SERVER['REMOTE_HOST'], ENT_QUOTES, 'UTF-8' );
            $this->$remote_port         = htmlspecialchars($_SERVER['REMOTE_PORT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_user_agent     = htmlspecialchars($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_referer            = htmlspecialchars($_SERVER['HTTP_REFERER'], ENT_QUOTES, 'UTF-8' );
            $this->$http_accept_language    = htmlspecialchars($_SERVER['HTTP_ACCEPT_LANGUAGE'], ENT_QUOTES, 'UTF-8' );
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_addr ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_host ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$remote_port ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->$http_user_agent ."\n","3","./log/debug.log");
            error_log(__FILE__.'('.__LINE__.')'.$this->addr."\n","3","./log/debug.log");

When I see the variable
            $this->$remote_addr         = htmlspecialchars($_SERVER['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8' );

remote_addr has "::1"
but after go through
            $this->$remote_host         = htmlspecialchars($_SERVER['REMOTE_HOST'], ENT_QUOTES, 'UTF-8' );
            $this->$remote_port         = htmlspecialchars($_SERVER['REMOTE_PORT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_user_agent     = htmlspecialchars($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8' );
            $this->$http_referer            = htmlspecialchars($_SERVER['HTTP_REFERER'], ENT_QUOTES, 'UTF-8' );

here, it changes "ja,en-US;q=0.9,en;q=0.8"
Why?
I also add logs.
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(106)/Brain/editor1.php
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(106)/Brain/editor1.php
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(106)/Brain/editor1.php
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(106)1640755666.5604
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(106)1640755666
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(111)::1
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(118)ja,en-US;q=0.9,en;q=0.8
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(119)ja,en-US;q=0.9,en;q=0.8
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(120)ja,en-US;q=0.9,en;q=0.8
/Applications/MAMP/htdocs/Brain/php/class.responsive-bbs-write.php(121)ja,en-US;q=0.9,en;q=0.8

Thank you!


text:
Q: Why increase the size by 2B when adding only one? Software parted takes automatically size of sector (512B for GPT).
I enter exact size to MB, but I can't create swap partition with exact size.
mkpart swap linux-swap 15.5GB 17013
print

Number     Start     End     Size     File system     Name     Flags
1          1049kB    10.0GB  10.0GB   ext4
2          10.0GB    15.0GB  5000MB   ext4
3          15.0GB    15.5GB  512MB    ext4
4          15.5GB    17.0GB  1499MB   linux-swap(v1)

When I enter another size:
    mkpart swap linux-swap 15.5GB 17014
    print
Number     Start     End     Size     File system     Name     Flags
1          1049kB    10.0GB  10.0GB   ext4
2          10.0GB    15.0GB  5000MB   ext4
3          15.0GB    15.5GB  512MB    ext4
4          15.5GB    17.0GB  1501MB   linux-swap(v1)

Why increase the size by 2B when adding only one?

redpajama_set_name: RedPajamaStackExchange


text:
Q: The subgraph obtained by removing an edge incident to a degree 1 vertex in a connected graph
Suppose that $v$ is a vertex of degree $1$ in a connected graph $G$ and that $e$ is the edge incident on $v$. Let $G′$ be the sub- graph of G obtained by removing $v$ and $e$ from $G$. Must $G′$ be connected? Why?

My solution:
If I understand correctly I think G′ will be disconnected. The reason is that for graph to be connected each pair of vertexes must be connected. By removing one vertex and edge the node will be disconnected.
Is this correct?

A: If the vertex $v$ has degree $1$, then $v$ is incident to only one edge, namely $e$. This means that $v$ is connected to the rest of $G$ by way of only one edge, and $v$ will only have one other vertex connected to it. So removing $v$ and its only incident edge $e$ from connected graph $G$ means what?

A: Think about the problem a little. What does a vertex of degree $1$ look like? What does a cut-edge look like?


text:
Q: Hide WVD url using Azure services. FrontDoor? AppGW? we are doing POC for one client of Windows Virtual Desktop service(2020 spring version)
and client requested to hide url that is being used by default: https://rdweb.wvd.microsoft.com/arm/webclient/index.html, there is no customization of this in WVD service., client want to see like: https://customdomainmain.com/arm/webclient/index.html
So trying to do this with FrontDoor or AppGW (ready to hear other solutions as well)
In both cases I get: 'Message: AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application:' searching info for this: suggests to register app in AAD, not sure how but what I tried nothing works.

A: You can benefit of Azure Functions, which allows you to execute your code in a serverless compute platform and setting your own Custom URL using the corporate domain name. the same idea as myapps.3tallah.com or mail.3tallah.com, for sure it would be up to you to set your preferred subdomain name.
Please refer to this blogpost Configure Custom URL redirection for Windows Virtual Desktop – WVD


text:
Q: why my python in visual studio code give me error when ever I run this code its give me this error please help me is my code is wrong???

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

from playsound import playsound
playsound('C:\akan\Hp\Documents\bird-in-tree\play.mp3')

A: in python '\' is used as an escape character meaning that it and the following character are not treated as text but as code such as with the newline character \n
to use a '\' in a string you need to use '\\' or in this case the best option is to use '/'


text:
Q: Decode/Encode multi-line string fields from YAML using golang YAML files can contain fields with "multi-line string" data. Example below:
Data:
  Foo: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten

How can I properly encode and decode these in Golang and what should be the type of the Data field, map[string][]byte?
I tried:
import (
    yamlv2 "gopkg.in/yaml.v2"
)

type data struct {
  Data map[string][]byte
}

func decode(bytes []byte) (*data, error) {
  d := &data{}

  err := yamlv2.Unmarshal(bytes, d)
  if err != nil {
    return nil, err
  }
  return d, nil
}

Also see in Playground.

A: You would parse a multi-line string the same way as a normal string:
package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "log"
)

var yamlString = `
Data:
  Foo: |
    enemies=aliens
    lives=3
    enemies.cheat=true
    enemies.cheat.level=noGoodRotten`

type data struct {
    Data map[string]string `yaml:"Data"`
}

func main() {
    t := data{}

    err := yaml.Unmarshal([]byte(yamlString), &t)
    if err != nil {
        log.Fatalf("error: %v", err)
    }

    if foo, ok := t.Data["Foo"]; ok {
        fmt.Printf("--- t:\n%v\n\n", foo)
    }
}


text:
Q: Passing in a Bitmap as the EXTRA_STREAM parameter when launching an Intent From the JavaDoc, the EXTRA_STREAM parameter when launching an intent needs to be an URI.
How can I pass a Bitmap object which I get from launching a "android.provider.MediaStore.ACTION_IMAGE_CAPTURE" intent?
/**
     * A content: URI holding a stream of data associated with the Intent,
     * used with {@link #ACTION_SEND} to supply the data being sent.
     */
    public static final String EXTRA_STREAM = "android.intent.extra.STREAM";

A: I think you will have to save it to disk and pass a file: URI in the EXTRA_STREAM extra.


text:
Q: Anaconda Spyder integrated IPython display for dataframes The new anaconda spyder has an integrated iPython console.  I really dislike the way dataframes are displayed in this console.  There are some border graphics around the dataframe and resizing that occurs with window resizing that make it difficult to examine the contents.  In addition, often for large dataframes if one just types the variable name, we can only see a XX rows x YY columns display, not a display of the top corner of the dataframe.
How can I reset the dataframe display so that it displays the way a standard iPython (or iPython QT) console would display a dataframe, i.e. with no graphics?
Thanks.

A: The development version of Spyder has a Pandas Dataframe editor (and an numpy array editor, up to 3d). You can run this from source or wait for the next release, 2.3.1.
This is probably more adequate to edit or visualize dataframe than using the embedded qtconsole.


text:
Q: Ubuntu Server installation freezes during installation I have an old Gateway Tower that was running Windows XP, but after XP stopped working on me, I decided to make it into a server, and install Ubuntu Server.
BUT, it keeps freezing on me.
During this setup, this happened once to me while I was Selecting the keyboard layout, but now, it happened after I partioned the disk. (Right now it is at 34% of "Installing the Base System") Last time, I just turned the computer off, and it worked again, but I remember hearing someone say that if you turn off your computer while it is partioning the disk, that it could corrupt your files.
Is it safe to turn off, and is there any other way to fix this?

A: If you're installing, then yes there's a chance that it will corrupt the files... but to be fair, if you cut it off during the installation you're going to have to install again and, if you wanted to be safe, remake the partition tables so that's not really a concern (at least not to me.)
You said Windows XP stopped working... What went wrong? If it was hardware related the same problems could be affecting Ubuntu and causing it to lock up as well.
Since you're new here, you can comment on my post to reply to me. Also, if this is a helpful reply you can click the up arrow next to it.


text:
Q: Permission denied when I try to open VSCode using a command line I'm trying to edit a file by openning it via git using VS Code as an editor
$code texte.txt

and I got this

/c/Users/MAYA/AppData/Local/Programs/Microsoft VS Code/bin/code: line 61: /c/Users/MAYA/AppData/Local/Programs/Microsoft VS Code/Code.exe: Permission denied

I google it but didn' find anything usefull, any help please?
P.S: my environement: windows 7, MINGW64

A: Thought it would be useful to share this as well.

WSL is not able to run VS Code with Windows environment administrator permissions.

*

*Right-click on your Visual Studio Code shortcut and select "Properties" in C:\Users\<myUsername>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Visual Studio Code

*In the Compatibility tab's settings section un-check "Run this program as an administrator"
A wonderful person brought this up on this Reddit post.

A: Follow the steps below and be proud of the OS you use.

*

*Search for "Advanced System Setting" from Start.

*Click on Environment Variables

*On System Variables choose "path" from Variable tab and click on Edit.

*Click on New on the right side of the popup window.

*Copy your path from the Explorer's breadcrumb path and paste it into the
new opened path in step 4, example:- C:\Program Files\Microsoft VS
Code\bin

*Click Ok on all the open windows to confirm changes and restart your  cmd

*Now you run it  $code.cmd file.extension

A: I added the path from the Explorer's breadcrumb to Environment Variables under Advanced System Setting then I used $code.cmd file.extension


text:
Q: jQuery Accordion Children not hiding So I'm trying to get my accordion menu to function so that when you have click on one menu and it opens, then click on another, the previous menu should close - but seems to automatically open then close the menu when you click on it.
Can someone check my code to see what I'm missing? I tried using the siblings function but it wouldn't function at all, and the find function is causing the aforementioned problem.
HTML

      design series

Assorted Designs

Kiss Me Goodnight

Into the Wild

Alice n Stripes

Magical Kingdom

  decoden cases

WhipCream

Rhinestones/Pearls

jQuery:
$(document).ready(function () {
    $('.sideContent').hide();
    $('.sideHeader').click(function () {
        event.preventDefault();
        $(this).next().slideToggle('fast')
        //.parent().parent().find('.sideContent:visible').slideUp('fast');
        .parent().parent().siblings.find('.sideContent:visible').slideUp('fast');
    });
});

Here's a jFiddle link to show it in action

A: You could do something like this
$(document).ready(function () {
    $('.sideContent').hide();
    $('.sideHeader').click(function () {
        event.preventDefault();
        $('.sideContent').slideUp('fast');
        $(this).next().slideToggle('fast');

    });
});

DEMO
EDIT: New version to cover scenario described by @nevermind
$(document).ready(function () {
    $('.sideContent').hide();
    $('.sideHeader').click(function () {
        event.preventDefault();
        var $slideContent = $(this).next();
        var slideDown =  $slideContent.is(":not(:visible)");
        $('.sideContent').slideUp('fast');

        if (slideDown)
            $slideContent.slideDown('fast');
    });
});

DEMO

A: $(document).ready(function () {
    $('.sideContent').hide();
    $('.sideHeader').click(function (event) {
        event.preventDefault();
      //  $(this).next()
    $(this).next().slideToggle('fast');
    $('#sidenav').find('a').not(this).next().slideUp('fast');

    });
});

This will work. jsfiddle is extremely slow currently... http://jsfiddle.net/sinisake/76MbN/3/


text:
Q: Test for equality between two discrete distributions with lots of ties My two empirical distributions have the same number $n$ of observations, where $n$ is in the hundreds or thousands.  I can make more observations if I need to.  Each observation is a relatively small integer, often in the range 0-5.  The observations are actually paired: The $k$th observation of each distribution comes from examining the same object in two different ways.
I want to answer questions such as: Can I reject the hypothesis that

*

*The two distributions have the same mean?

*The two distributions exceed some integer $t$ the same proportion of the time?

*No distribution "beats" the other (where distribution 1 "beating" distribution 2 means that the paired observation in distribution 1 exceeds the observation in distribution 2 more often than the other way round)?

Is there anything better than the sample mean, sample standard variation and a two-sigma confidence interval?


text:
Q: PyPDF2 split pdf keeping original pdf format I am spliting a pdf file by ranges. My code works fine, but the problem is that the new pdf file does not preserve the format of the original pdf.
How can I splita pdf file without losing the original format?
from PyPDF2 import PdfFileReader, PdfFileWriter
#split range
pgi=30 #start
pgf=37 #end

pdf_document = "test.pdf"
pdf = PdfFileReader(pdf_document)
pdf_writer = PdfFileWriter()
for page in range(pgi-1,pgf):
    current_page = pdf.getPage(page)
    pdf_writer.addPage(current_page)

with open(f'test-{pgi}-{pgf}.pdf', "wb") as out:
    pdf_writer.write(out)

PS: I don't have this problem when I use Adobe or MasterPdfEditor software.
The image below shows the original and new pdf format.
out format pdf


text:
Q: Compute the posterior on a Gamma distribution with a gaussian random variable i have the following problem:
given a variable $x \in \mathbb{R}$ drawn from a Gaussian distribution with known mean $\mu$ and unknown precision $\tau$ (the inverse of the variance).
So: $$p(x \vert \tau) = \mathcal{N}(x; \mu, \tau^{-1})$$
Now we assume as our prior that $\tau$ is Gamma distributed: $$p(\tau) = \mathcal{G}(\tau; k, \theta) = \frac{\tau^{k-1}}{\Gamma(k)\theta^k} \exp\left(\frac{-\tau}{\theta}\right)$$
The goal now is to compute the posterior distribution : $p(\tau \vert x)$
What I have so far:
I want to calculate the posterior via the Bayes theorem: $$p(\tau \vert x) = \frac{p(x \vert \tau) \cdot p(\tau)}{\int p(x \vert \tau) \cdot p(\tau) d\tau}$$
After doing some calculations I came up with $$p(x \vert \tau) \cdot p(\tau) = \frac{\tau^{k-1}}{\sqrt{2 \pi \tau^{-1}} \cdot\Gamma(k)\theta^k} \exp\left(-\frac{(x - \mu)^2}{2\tau^{-1}} + \frac{-\tau}{\theta}\right)$$
So is there any other way than integrating this term and to some nasty calculations or is this the way I have to go? Or am I completely wrong here using the Bayesian approach?
Tanks for answers!

A: There is an error in you posterior formula, normalization should be wrt $\tau$.
The correct formula is
\begin{equation}
p(\tau|x)=\frac{p(x|\tau)p(\tau)}{\int d\tau p(x|\tau) p(\tau)}
\end{equation}
You have that
\begin{equation}
p(x|\tau)p(\tau)\propto \tau^{k-\frac{1}{2}}e^{-\tau\Bigg(\frac{(x-\mu)^2}{2}+\frac{1}{\theta}\Bigg)}
\end{equation}
which is proportional to $\mathcal{G}\Bigg(\tau,k-\frac{1}{2},\Bigg(\frac{(x-\mu)^2}{2}+\frac{1}{\theta}\Bigg)^{-1}\Bigg)$ for the purposes of integration in $\tau$ and thus you can calculate the renormalization constant. I leave to you the details of the calculation and collecting all factors.


text:
Q: Node.js App Crashing Constantly - memory I have a Node.js app that is basically the boilerplate that CONSTANTLY crashes due to this error:
an instance of the app crashed: out of memory

I have no idea how this app could crash with 256mb of memory. It does almost nothing server side beside respond to http requests and I am wondering how this could be. Garbage collection problem?
app.js

require('newrelic'); //monitoring

var express = require('express');//middleware
var app = express();

var cfenv = require('cfenv');// Cloud Foundry library
var appEnv = cfenv.getAppEnv();

app.use(express.static(__dirname + '/public'));

app.listen(appEnv.port, appEnv.bind, function() {
 console.log("server starting on " + appEnv.url);
});

UPDATE
This appears to be the issue. Can't do anything at this point but remove the service. :(

A: when running an app in a low memory environment, it can happen that garbage collection is not triggered early enough. You can invoke it manully and see if that helps.
Add --expose-gcto the start command of your app - e.g.:
node --expose-gc myapp.js

Then in your code do this periodically:
Global.gc()

In order to monitor the memory consumption of your app you can do a cf curl:
cf curl /v2/apps/<your app guid>


text:
Q: How do I get a variable out of a completion block?
*

*(void)fetchLastMessageInChannel

{
          __weak id weakSelf = self;
    for (ANKChannel *channel in self.channelArray)
    {
            NSLog(@"channels %@",channel);

             NSLog(@"channel last message %@",channel.latestMessageID);

        [[ClientManager currentClient] fetchMessageWithID:channel.latestMessageID inChannel:channel
                                               completion:^(id responseObject, ANKAPIResponseMeta *meta, NSError *error)
         {
             NSLog(@"message object %@",responseObject);
             ANKMessage *message = responseObject;

             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf populateTextViews:message.text];
             });

             NSLog(@"message text %@",message.text);

         }];

    }

}
-(void)populateTextViews:(NSString *)message
{
NSMutableArray *textViews = [@[] mutableCopy];

NSMutableAttributedString *postText = [[NSMutableAttributedString alloc] initWithString:message];
[postText addAttributes:@{
                          NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody],
                          NSForegroundColorAttributeName : [UIColor darkTextColor]
                          }
                  range:NSMakeRange(0, postText.length)];

UITextView *postTextView = [[UITextView alloc] initWithFrame:CGRectMake(80, 30, kPostLabelMaxWidth, 44)];
postTextView.attributedText = postText;
postTextView.dataDetectorTypes = UIDataDetectorTypeAll;
postTextView.backgroundColor = [UIColor whiteColor];
postTextView.editable = NO;
postTextView.scrollEnabled = NO;
postTextView.clipsToBounds = NO; // So it doesn't clip the text selector

CGRect textViewBounds = postTextView.bounds;
textViewBounds.origin = CGPointMake(80, 30);
textViewBounds.size.width = MAX(textViewBounds.size.width, kPostLabelMaxWidth);
textViewBounds.size.height = postTextView.contentSize.height;

postTextView.bounds = textViewBounds;

[postTextView sizeToFit]; // Reload the content size

[textViews addObject:postTextView];

self.channelTextViewArray = [textViews copy];

}
This is where I stand now as far as my methods go with the help I've received. The self.channelTextViewArray is returning nil and causing a crash because the populateTextViews(NSString*)message never gets called.
Any ideas?

A: If ClientManager call is async, the populateTextViews method will complete before the async call returns, which is why you can't use the value set in its completion block.
Either put...
NSMutableAttributedString *postText = [[NSMutableAttributedString alloc] initWithString:messageText];

...inside the completion block, or call out to a method inside the completion block once you have the messageText. In doing that you will not have to declare the __block variable either.
If there will be a UI update, make sure that happens on the main thread.
EDIT
This the basic idea, but I'm guessing you're updating more than one text view so you may need to change the signatures around. If you get the basic idea -- calling an async method doesn't interrupt the flow of your code (basically it says "do this when you have a chance, possibly on another thread"). That's the reason you have a completion block -- it's a place in your code where you know that the async method you called has completed.
If what's inside the block isn't getting called at all, make sure that self.channelArray has values, and look at what fetchMessageWithID does if something goes wrong.
- (void)populateTextViews
{
    __weak id weakSelf = self;
    for (ANKChannel *channel in self.channelArray)
    {
        [[ClientManager currentClient] fetchMessageWithID:channel.latestMessageID inChannel:channel
                                               completion:^(id responseObject, ANKAPIResponseMeta *meta, NSError *error)
         {
             NSLog(@"message object %@",responseObject);
             ANKMessage *message = responseObject;
             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf updateTextView:message.text];
             });
         }];
    }
}

- (void)updateTextView:(NSString *)message
{
    // Make an attributed string from the post text content
    NSMutableAttributedString *postText = [[NSMutableAttributedString alloc] initWithString:messageText];
    self.textView.attributedText = postText;
}


text:
Q: failed to install grub, ubuntu 17.04 installation Linux newbie here
I've tried to install Ubuntu 17.04 but it crashed and show this message dialog " the 'grub-efi-amd64-signed' package failed to install into /target/. Without the GRUB boot loader, the installed system will not boot. "
This is my boot-info link http://paste.ubuntu.com/25585644/
Then i try to repair it using boot-repair and follow the instruction until it finish(im not sure i've done it correctly). next, i can boot ubuntu but crash report show up "sorry, a problem occured while installing software. Package :grub-efi-amd64-signed 1.80.2+2.02~beta3-4ubuntu2.2"
Is there any correlation with forcing uefi installation?
Thanks for your help

A: Probably your system hasn't been configured to boot UEFI files while your installation medium is UEFI enabled. That's why you're getting the error.
You can configure your system to allow UEFI by going into your BIOS and turning off fast boot or Secure boot.
I believe this should work as it worked for me.


text:
Q: Why am I getting "method without body" error when using Groovy Grape? Below is a code snippet and below that is the error. Am I doing something wrong that's obvious? I'm very new to Grapes.
   @Grab('com.microsoft:ms-sql-server-jdbc-dependencies')
    GrabConfig(systemClassLoader=true)
    import groovy.sql.Sql

    println "Hello World"

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
cfwdUpdate.groovy: 1: You defined a method without body. Try adding a body, or d
eclare it abstract.
at line: 1 column: 1

A: You missed the @ off
@GrabConfig(systemClassLoader=true)


text:
Q: How to go up and down in a for loop I actually have this piece of code
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
    int i, row;

    for(i=0; i<9; i++){
        row =3-i%3;
        printf("%d ",row);
    }
    printf("\n");
    return 0;
}

The output is
3 2 1 3 2 1 3 2 1

but I would like that it is
3 2 1 1 2 3 3 2 1

this means "inverting" the counter at each 3 elements but I cannot figure out how to do this...

A: You may recognize whether you're in an odd or in an even triple and calculate the row value accordingly:
int i, row;

for (i = 0; i < 9; ++ i)
{
    if (i % 6 < 3)       // the first triple in a six ?
        row = 3 - i % 3;
    else                 // the second triple in a six
        row = 1 + i % 3;
    printf("%d ", row);
}

See it working at godbolt.
For a condition if (i % 6 < 3) you may use a more explicit, but also a bit more complicated condition:
((i / 3) % 2 == 0)

– calculate the current triple's number first: i / 3, and then check if it's odd or even.

A: Try switch :-)
#include <stdio.h>

int main(void) {
    int row = 3;
    int direction = -1;

    for (int i = 0; i < 9; i++) {
        printf("%d ", row);
        switch (i) {
            default: break;
            case 2: case 5: direction = 0; break;
            case 3: direction = 1; break;
            case 6: direction = -1; break;
        }
        row += direction;
    }
    printf("\n");
    return 0;
}

A: Use modulo to toggle increment from 1 to -1.
If 9 is change to 18 or 24 the pattern will continue.
#include <stdio.h>
#include <stdlib.h>

int main ( void) {
    int row = 3;
    int increment = -1;

    for ( int i = 0; i < 9; i++) {
        printf ( "%d ",row + (1 == increment));
        row += increment;
        if ( 0 == row % 3) {
            increment *= -1;
        }
    }
    printf ( "\n");
    return 0;
}

With 24 the output
3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3

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

int main(int argc, char* argv[]){
    int i, row,incre=0,change=0;

    for(i=0; i<18; i++){
        if(change==0)
        {
            incre++;
            row =3-i%3;
            printf("%d ",row);
            if(incre>=3){
                change=1;
                incre=0;
                //printf("\n");
            }
        }
        else{
            incre++;
            row =1+i%3;
            printf("%d ",row);
            if(incre>=3){
                change=0;
                incre=0;
                //printf("\n");
            }
        }
    }
    printf("\n");
    return 0;
}


text:
Q: How do I get the top-ranked products within a category? Given a product (product_name is a parameter in the view), I am trying to return the 5 top-ranked products within that category (as defined by the method "get_avg_rating") as a list that I can loop through in a template.  Any advice on how to do this?
class Productbackup(models.Model):
    website = models.CharField('Product name', max_length = 200)
    url_friendly = models.CharField('URL friendly', max_length = 200)
    website_url = models.URLField('Product URL')
    description= models.CharField('Description', max_length = 2000)
    category = models.ForeignKey(Categories)
    #category = models.ManyToManyField(Categories)
    image_hero = models.URLField('Hero image url')
    image_second = models.URLField('Second image url')
    image_third = models.URLField('Third image url')
    created_on = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    def __unicode__(self):
        return self.website

    def get_avg_rating(self):
        reviews = Reviewbackup.objects.filter(product=self)
        count = len(reviews)
        sum = 0.0
        for rvw in reviews:
            sum += rvw.rating
        return (sum/count)

    def get_num_reviews(self):
        reviews = Reviewbackup.objects.filter(product=self)
        count = len(reviews)
        return count

RATING_OPTIONS = (
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
                (6, '6'),
    (7, '7'),
    (8, '8'),
    (9, '9'),
    (10, '10'),
)
class Reviewbackup(models.Model):
    review = models.CharField('Review', max_length = 2000)
    created_on = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    user = models.CharField('Username', max_length =  200)
    rating = models.IntegerField(max_length=2, choices=RATING_OPTIONS)
    product = models.ForeignKey(Productbackup)
    def __unicode__(self):
        return self.review

class Categories(models.Model):
    category = models.CharField('Category_second', max_length = 200)
        url_friendly = models.CharField('url_friendly', max_length = 200)
    def __unicode__(self):
        return unicode(self.category)

def view_reviews(request, product_name):
    product = get_object_or_404(Productbackup, url_friendly=product_name)
    product_id = product.id
    #get reviews for the this product
    reviews = Reviewbackup.objects.filter(product_id=product_id).order_by("-created_on")
    #similar products in category comparison
    prod_category = Productbackup.objects.filter(category=product.category)
    #top_ranked = Productbackup.objects.order_by('get_avg_rating')[0:5]
    #recently added
    recent_added = Productbackup.objects.order_by('-created_on')[0:5]
    return render_to_response('reserve/templates/view_reviews.html', {'prod_category': prod_category, 'product':product, 'reviews':reviews, 'recent_added':recent_added},
    context_instance=RequestContext(request))

A: Try to implement that:
Create a dictionary. It will have the Product as the key and the rating as the value.
Loop through your items (Product.objects)
In that loop, put each item in the dictionary
Out of that loop, sort the dictionary by value.
(See Sort a Python dictionary by value)
Get the last items of the dictionary (dictionary[-5]).
Note that you will have to handle items with ex-aequo ratings. Indeed, if 10 items have the same score, then your Top 5 doesn't mean anything using the above method.
This would result in a code similar to this:
items_with_rating = {}
for product in Product.objects:
    items_with_rating[product] = product.get_avg_rating()

items_sorted_by_rating = sorted(items_with_rating.iteritems(), key=operator.itemgetter(1))

top5_items = items_sorted_by_rating[-5]

A: You can use annotate for that
from django.db.models import Sum, Avg

def get_top_products(amount=5):
    try:
         Productbackup.objects.annotate(review_amount=Sum("reviewbackup__product")).\
                               order_by("review_amount")[:amount]
    except Productbackup.DoesNotExist:
        return None

This is just a basic example, which can be extended to your needs

A: Maybe something like this could work?
products = [[prod, prod.get_avg_rating()] for prod in Productbackup.objects()]

top_5_items = sorted(products, key=lambda x: x[1], reverse=True)[:5]


text:
Q: QR scanner in Swift 5 I built a QR scanner in Swift 5. It will acknowledge the QR Code and scan it, however it only pulls up the url that is embedded in the QR code. Does anyone have any advice on how to make it so that I can tap the link and open it in a browser?
This is the code I have for the scanner:
import UIKit
import AVFoundation

extension QRScannerController: AVCaptureMetadataOutputObjectsDelegate {

}

class QRScannerController: UIViewController {

    var captureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    var qrcodeFrameView: UIView?

    @IBOutlet var messageLabel: UILabel!
    @IBOutlet var topBar: UIView!

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        // Check if the metadataObjects array is not nil and it cotains at least one object
        if metadataObjects.count == 0 {
            qrcodeFrameView?.frame = CGRect.zero
            messageLabel.text = "No QR Code is detected"
            return
        }

        //Get the metadata object
        let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

        if metadataObj.type == AVMetadataObject.ObjectType.qr {
            // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        qrcodeFrameView?.frame = barCodeObject!.bounds

        if metadataObj.stringValue != nil {
            messageLabel.text = metadataObj.stringValue
            }

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // get back camera for capture
        guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            print("Failed to get camera device")
            return
        }

        do {
            // Get an instance of the AVCaptureDeviceInput class using the previous device object
            let input = try AVCaptureDeviceInput(device: captureDevice)

            //Set the input device on the capture session
            captureSession.addInput(input)

            //Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session
            let captureMetadataOutput = AVCaptureMetadataOutput()
            captureSession.addOutput(captureMetadataOutput)

            //Set delegate and use the default dispatch queue to execute the call back
            captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]

            // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer
            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
            videoPreviewLayer?.frame = view.layer.bounds
            view.layer.addSublayer(videoPreviewLayer!)

            //Start video capture
            captureSession.startRunning()

            // Move the message label and top bar to the front
            view.bringSubviewToFront(messageLabel)
            view.bringSubviewToFront(topBar)

            // Initialize QR Code Frame to highlight the QR Code
            qrcodeFrameView = UIView()

            if let qrcodeFrameView = qrcodeFrameView {
                qrcodeFrameView.layer.borderColor = UIColor.yellow.cgColor
                qrcodeFrameView.layer.borderWidth = 2
                view.addSubview(qrcodeFrameView)
                view.bringSubviewToFront(qrcodeFrameView)
            }

        } catch {
            print(error)
            return
        }
    }
}


text:
Q: mapping j function (used defined) over a list I've written my own version of the exponential (^) function which works fine for simple scalars :
3 : '+/ (y&^%!) i.50'
It doesn't work over a list, so I thought of modifying it with "0
3 : '+/ (y"0&^%!) i.50'
This works over a list but gives the wrong answers.
Two questions arise:
1) Given my usage of "0 doesn't work, is there one that does ?
2) If I don't have access to a functional definition like this, what is the best way to apply it to the individual elements of an array ?

A: You need to apply the rank conjunction "0 over the function you want to map (y&^%!), instead of its argument y:
 3 : '+/(y&^%!)"0 i.50'

However, the precision isn't as good as the native ^:
   a =: 3 : '+/(y&^%!)"0 i.50' 4 4 $ 10+i.20
   b =: ^ 4 4 $ 10+i.20
   a = b
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0


text:
Q: C++ access to static class member variables, not friend I'm sorry in advance if this is a stupid or nonsense question, but:
Can a non-constant static class variable for one class be used by another class without using friend or base/derived classes?  The (abbreviated) situation is:
class Decl {
    public:
          static string searchVal;
          ... (other irrelevant stuff)
};

class Conj {
    public:
        static string searchVal;
        ... (other irrelevant stuff)
};

I don't want to repeat searchVal in both classes, and because of the rest of the program, I'm not keen on using friend (but I will if it's the only option).

A: Since your static members are public, if your class definitions are both visible, then their static members can be accessed using Decl::searchVal or Conj::searchVal respectively.
For example
class Decl
{
     public: static string searchVal;
};

class Conj
{
    public:
        static string searchVal;
};

// within ANY function, including members of either class above
//    ... as long as both definitions above are visible to the compiler

 if (Conj::searchVal == Decl::searchVal)
 {
       // do something
 }


text:
Q: How can I add a delay before it continues Is there a way in the normal obj-c or cocos2d to make a delay inside a if-else block?
Like
if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    //perform another task
}

Just a simple lag to wait between two tasks, or stalling an action. Is there any simple way to do this?

A: There are many ways to do this. I would use GCD
if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
        //perform another task;
    });
}

A: You can use the performSelector: withObject: afterDelay: method to delay tasks:
if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
    [self addChild:circle0];
    //wait two seconds
    [self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0];

}

And in the selector method:
-(void)continueTask
{
    //perform another task
}

A: Inside the cocos2d you can also run an Action on the node like,
[self runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2.0],[CCCallFunc actionWithTarget:self selector:@selector(anothertaks)],nil]];

Perform selector will also work but the problem is that all the schedulers of cocos2D get paused when the app go to background but on the other side perform selector will still count the time, so some time it create task,animation,etc syncing problems.
Perform selector:
    [self performSelector:@selector(continueTask) withObject:nil afterDelay:2.0];


text:
Q: New panel activating only when window resized: WxPython I want to delete a panel ( mainPanel )and replace a panel ( secPanel )in its place. The code I have tried:
import wx

class secPanel ( wx.Panel ):
    def __init__ ( self, parent ):
        wx.Panel.__init__ ( self, parent = parent )
        wx.TextCtrl ( self, pos = ( 100, 100 ) )

class mainPanel ( wx.Panel ):
    def __init__ ( self, parent ):
        wx.Panel.__init__ ( self, parent = parent )
        self.parent = parent
        b = wx.Button ( self, label = "Test", pos = ( 100, 100 ) )
        self.Bind ( wx.EVT_BUTTON, self.onPress, b )

    def onPress ( self, event ):
        parent = self.parent
        self.Destroy()
        secPanel ( parent )

class Window ( wx.Frame ):
    def __init__ ( self ):
        wx.Frame.__init__ ( self, parent = None, title = "" )

        mainPanel ( self )
        self.Show()

if __name__ == "__main__":
    app = wx.App()
    window = Window()
    app.MainLoop()

The mainPanel gets deleted but the secPanel only shows when the window is resized ( even just a pixel works ). Until I resize it shows a grey screen ( the one which would show without any panel ). This is quite annoying.

A: In this case Layout() is your friend.
Normally Layout() is used when sizers are involved but in this case, there are no sizers but the parent is a wx.TopLevelWindow.
Layout lays out the children using the window sizer or resizes the only child of the window to cover its entire area.
wx.TopLevelWindow.Layout overrides the base class Layout method to check if this window contains exactly one child – which is commonly the case, with wx.Panel being often created as the only child of wx.TopLevelWindow – and, if this is the case, resizes this child window to cover the entire client area.
See parent.Layout() below:
import wx

class secPanel ( wx.Panel ):
    def __init__ ( self, parent ):
        wx.Panel.__init__ ( self, parent = parent )
        wx.TextCtrl ( self, pos = ( 100, 100 ) )

class mainPanel ( wx.Panel ):
    def __init__ ( self, parent ):
        wx.Panel.__init__ ( self, parent = parent )
        self.parent = parent
        b = wx.Button ( self, label = "Test", pos = ( 100, 100 ) )
        self.Bind ( wx.EVT_BUTTON, self.onPress, b )

    def onPress ( self, event ):
        parent = self.parent
        self.Destroy()
        secPanel ( parent )
        parent.Layout()

class Window ( wx.Frame ):
    def __init__ ( self ):
        wx.Frame.__init__ ( self, parent = None, title = "" )

        mainPanel ( self )
        self.Show()

if __name__ == "__main__":
    app = wx.App()
    window = Window()
    app.MainLoop()


text:
Q: Как узнать процент покрытия кода тестами JUnit в IntelliJ IDEA? Как узнать процент покрытия кода тестами JUnit в IntelliJ IDEA?

A: Edit Configurations -> Add new configuration -> JUnit

Test kind: All in package и в поле package выберите корневой пакет проекта (Если вам нужно прогнать все тесты)

На закладке "Code Coverage" выберите корневой пакет проекта (опять же, если надо прогнать все тесты).

Конфигурацию настроили. Её необходимо запускать кнопкой "Run with Coverage" (см. картинку ниже). В результате вы получите процент покрытия, а в подарок увидите детализацию, какие именно строки покрыты, а какие - нет.

A: Тут IntelliJ IDEA 2017.1 Help :: Running with Coverage все подробно описано.
То есть запускаете тест с Покрытием

В правом боку "Editor" откроется таблица в которой показано покрытие кода в процентах и внизу появится пункт "Coverage".


text:
Q: How do I translate this dynamic collection expression from VB.NET into C#? I have this very succinct expression in vb.NET which makes it easy to test to see if a value is in a list of known string literals but I don't know how to translate it to C#. (It is made all the more difficult because I cannot search for it knowing exactly how to describe what the name of this type of expression is)
Dim test as String = "test"
If {"test", "test2"}.Contains(test) Then

End If

A: You can use:
if (new [] {"test1, test2"}.Contains(test)) {
}


text:
Q: How to access step over Signature Pad ActiveX object in chrome through javascript? This step over signature pad does not work in Google Chrome, but it works with IE.

    <object id="signDevice" width="850" height="200" classid="CLSID:F5C74079-C195-4DA9-B60D-F6F5365042D1"></object>

    <input id="btnStartSign" type="button" value="start" onclick="return StartCapture()"></input>
    <input id="btnStopSign" type="button" value="save" onclick="return StopCapture()"></input>
    @*<input id="btnShowBase64" type="button" value="sign base 64" onclick="return GetImageBase64()"></input>*@
    <input id="btnUploadSign" type="button" value="update" onclick="return SaveSign()"></input>

I think I will change CLSID.


text:
Q: Why pulsed drain current is higher than continuous drain current in MOSFETs? Why is pulsed drain current higher than continuous drain current in MOSFETs?
In MOSFET data-sheets, pulsed drain current is much higher than (by at least 2x) continuous drain current. What is the reason behind this?

A: The main problem of current is that when it runs through a resistance it drops a voltage and hence generates heat, which causes a rise in temperature. A lot of things will break down at a certain temperature (think of light bulbs, fuses).
When the spot where the heat is generated is thermally-connected to something that can quickly absorb a lot of heat and pass it off to the surroundings at a slower rate, a small 'heat-pulse' will not generate much rise in temperature, hence it will not be a problem, provided that it is not repeated too often. In such a case a high current pulse can be tolerated, but is subject to certain limitations (pulse duration, repetition frequency). This type of limitation is typical for a semiconductor that is intimately coupled to a metal tab.
The bonding wire(s) of a chip or MOSFET have a very different characteristic: they are suspended in air (or some other stuff that does not conduct heat very well), hence they have a hard limit on the current, that is almost independent of the pulse duration.
In a datasheet you will often find a graph that expressed the maximum current under various circumstances. In the graph below the DC and 5ms ... 100uS lines show the average-heat limits of the Safe Operating Area. They depend on the VCE, because the heat is generated in the semiconductor area where this volateg drop occurs. The horizontal line at 5A is the DC limit. It is (for a large part) independent of the VCE, because it is about a bonding wire, which is Ohmic (voltage drop and hence heat is determined only by I * R).
There are other limits, like the maximum emitter-collector voltage, that are also expressed in this diagram.

A: The pulsed drain current will have some duty cycle or ON time and OFF time specified in the datasheet. The reason that the Pulsed current is much more than the continuous current is that, the average value of the pulsed current becomes equal the continuous current.
For the average value to be equal to the continuous current, the ON time current of the pulsed current is made high, or in other words, ON time of the pulsed current is allowable to a more value.


text:
Q: Is there a state beyond gas? If you could boil water in a sealed container until it became vapor and you still kept applying heat to it would  something happen? Maybe gas to super-gas?
This has been on my mind for a long time I really hope someone can help out.

A: It would start to ionize and them you would get plasma, the 4th state of matter. The "gas" would begin to become an electrical conductor

A: Gas is indeed not the highest state of matter, the next step in from it is in-fact plasma: a super-heated gas which acts as a liquid even though it has gone far beyond and vastly different from that form.
Super-heating that water to the state of plasma would take a fair bit more heat than a kettle or stovetop could ever produce, but if persistent pressure and energy were applied to it, eventually it would change to this fourth, higher, state of matter.
This material is found naturally in and around our galaxy but also on Earth, plasma forming directly below where particularly large lightning bolts have struck; the ground, or whatever upon which the bolt impacted, heating so fast and violently because of the extreme electrical voltage it goes through all stages of matter [solid, liquid and gas] before turning momentarily into this "super gas" as you think it as being...

A: Plasma is described as the 4th state of matter, which is what you get if you give so much heat energy that the molecules begin to break up and ionize into positively and negatively charged fragments.
Another Claim on the title '4th State of matter' is a 'supercritical fluid'. Sometimes people draw phase diagrams with it to show this '4th state of matter'. (Strictly speaking Supercritical fluids may be a different phase from liquid, solid and gas and more '4th phase of matter' than '4th state of matter' as pointed out in the good comment from Jim. - the state of a supercritical fluid is gas - whether supercritical fluid is a phase or state maybe something that is up for debate at the moment.)

phase diagram of carbon dioxide showing supercritical phase (from wikipedia)
As can be see from the diagram the supercritical state exists above the critical temperature and pressure.
Supercritical fluids have many interesting properties. For example supercritical water dissolves organic molecules (such as organic solvents), which would not normally dissolve in water. It is also very acid and very alkaline at the same time because there is a high concentration in the liquid of both H$^+$ and OH$^-$ ions.
Supercritical carbon dioxide is used to remove caffeine from coffee beans.
Finally to go back to your question, if you took water and heated it in a sealed container it would 'go supercritical' if it did not break the container first - please don't do this at home, because if the container breaks then you would have alot of very hot dangerous steam --- people who research this for science tend to work with very small volumes for safety.

A: One more state - the most extreme plasma that only existed microseconds after the Big Bang or in high energy accelerators like CERN - the quark gluon plasma. That's where temperature is so high the constituent quarks found in nucleons become fluid and flow freely through the mass.

A: There are in fact two more beyond gas.
1) Plasma: the temperature is sufficient to ionize the atoms.
2) Degenerate matter (or Degenerate gas): the temperature is sufficient to fully ionize and the pressure sufficient to compress to the packing limit of the particles (for example: white dwarfs are degenerate as the electrons have reached the required density and neutron stars have reached the required density for neutrons).

A: As much as I know there are two more states after gas plasma and Bose-Einstien Condensate


text:
Q: index out of range concerning CSV reader I am trying to store the 2nd 1 delimited spot in a csv UTF-8 file. My logic seems right but I KEEP GETTING an index out of range error which I can't seem to extrapolate. Here is my code:
    mylist_n = []
    with open(r'/home/main/Documents/AMCO/mypythonAMCO/ralco_Info.csv') as     csvfile:
        spamreader = csv.reader(csvfile,delimiter=',', quotechar='|')
        reader = csv.reader(csvfile)
    for row in spamreader:

        print(', '.join(row))
        mylist_n.append(row[1])

'''

IndexError                                Traceback (most recent call last)
<ipython-input-46-5b4beea38798> in <module>
      6
      7         print(', '.join(row))
----> 8         print(row[3]) #read the make -- write to list

IndexError: list index out of range

I know it has something to do with the output of row and a particular module/function call. That's all I need. I plan on getting position 3, storing it in a list and other respective positions related to make/model and eventually making a dictionary of dates with respective values to make the otherwise extraordinarily long name condensed.
sam

A: with open(r'/home/main/Documents/AMCO/mypythonAMCO/ralco_Info.csv') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    #reader = csv.reader(csvfile)

    for row in spamreader:
        #print("->".join(csvfile))

        #print(row[1])

    make_n.append(row[1].lower)
    print("appended")
    print(row)
    print("\n")

To make a long story short, make sure to watch out for your comma's in CSV and I am to bolster my string manipulation and json skills tonight so I can parse through these individual strings within the list of which contain comma's from the source data.


text:
Q: c# setting datasource to datagridview, updating source datatable i have a datagridview whose datasource is attached to a datatable
how do i update the datatable and then make sure to refresh the datagridview to reflect the changes in the datasource? or do i need to do this at all?

A: You shouldn't need to do this.  If you delete or update a row in the datatable, the bound datagridview should update its display to reflect the changes.


text:
Q: Can a Matlab GUI (created in Guide) appear in or in front of a Psychtoolbox window? I'm using psychtoolbox 3 with Matlab 2019b on a Mac running OSX 10.12.
I'm presenting static image stimuli using psychtoolbox (PTB) and would like to have a floating audio player gui object that I created using guide to appear on the screen as well. Importantly, the audio player has its own functions (slider bar to fastFWD and rewind the audio and a play/pause button) and I need to preserve the button's functionality. Rather than attempting to recreate the  the player and buttons etc. within PTB, is it possible to display the gui above the window's screen content?
I've seen other threads about displaying a figure within a PTB window, but this was for graph rather than a gui. I don't believe PTB retains the functionality of the buttons when displaying the figure. I've also considered making the window smaller than the full screen in order to display the figure on the side, but I'd prefer to remain full screen if at all possible.
So to summarize, is there a way for a figure window appear in front of the PTB window? Alternatively, can a PTB window appear within a figure window (i.e., within the axes of a gui created in guide?
Thank you!

A: Unfortunately I don't believe what you want - to have a full screen Psychtoolbox window as well as a MATLAB GUI .fig as an overlay - is possible. Even if the Psychtoolbox window is less than full screen, you can't give the MATLAB .fig focus and have it overlay the Psychtoolbox window, it will be placed underneath the Psychtoolbox window. You also won't be able to plot the Psychtoolbox window inside of a MATLAB GUI window. What I think your options are:

*

*Make the Psychtoolbox window less than full screen, place the player GUI next to it.

*Use a secondary monitor to host the MATLAB GUI, so the Psychtoolbox screen can be full size on the main monitor.


text:
Q: Architecture for MongoDB "relational" application This is the project, roughly: We have users and we have polls, users can both create polls or vote existing polls. Of course one user can vote just once each poll.
To me this is clearly relational, so in principle NoSQL makes no sense. But then I read a little and came to the conclusion that you can indeed make relations in MongoDB so I came to this scheme, I want to know if it is Mongo-ok or not before going on.
In a table/collection called users we store all the user data including an id (I guess default _id of mongo documents will be ok?)
In another table/collection called polls, we will have an id, the question, the possible answers and (here is where I start to have doubts) an array containing all the userIDs that had already voted? And then additionally the author's userID and also its username (I know this is duplicating but I read somewhere that I makes sense to do this in mongo, so that you don't have to launch another query just to know the user's username).
In MySQL I would have created a table with the voting relations (userID has voted pollID), but I guess in Mongo it makes sense to include this data in the poll document itself? Of course this array of userIDs will be constantly being updated, is that OK?
And what if I want to list all the polls created by a given userID? I know you can use find(), but is it as efficient as in MySQL at least for this case? Also each poll will be in a category and you would also must be able to sort by category and so, but I didn't wanted to complicate it further.

A: In my opinion, one efficient way to go about this would be to have a Users collection in which you store all the data relating to your users, and then have a Polls collection that, as you mentioned, stores an array of ObjectId references back to your users.
This array can also contain some additional information such as a timestamp of when any given user has answered and the answer that was provided.
Still, be aware that it is not always a good practice to embed objects in an array, especially when it is unbounded (i.e.: the number of users will increase in time, thus making it possible for the references array on the Polls objects to also increase in time).
Nevertheless, I think that in your case this is a good approach to your application use case scenarios, especially since a user can only answer once to any given poll, thus limiting the rate of expansion of the array of objects.
Moreover, regarding your concern about querying the Polls collection by UserId, I think you will have no issue firing a find query as long as you properly index your collection. If you are only interested in retrieving the total number of polls created by a certain user without retrieving data about those polls, an alternative might be having a counter field defined on the user which would get incremented each time a user creates a poll.


text:
Q: Solving $\sqrt{(x-2)^2 + (y-1)^2} = \sqrt 2$ What is the answer of this:
$\sqrt{(x-2)^2 + (y-1)^2} = \sqrt 2$

A: There is not a single solution, but rather several possible $(x,y)$ that satisfy that relation. If you don't recognize it right off - let's see what we can think of.
$\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$ is the distance formula between points $(x_1, y_1)$ and $(x_2, y_2)$. So you are asking for the set of $(x,y)$ that are distance $\sqrt 2$ away from the point $(2,1)$.
The locus of points equidistant to a single point is a circle. So the set of solutions form a circle in the plane.

A: That's just an equation, not a question. But if there are some written instructions attached to the equation, such as

Identify the set of solutions to
  $ \sqrt{(x-2)^2 + (y-1)^2} = \sqrt 2 $

then almost certainly the expected answer is not just another equation, but a description of the solution set in words, such as

The solutions are the points on the circle of radius ___ centered at the point ( ___ , ___ ).

A: $\textbf{Hint}$ : First, try to relate this to the pythagorean theorem. Also note.
$\sqrt{(x - 2)^2 + (y - 1)^2} = \sqrt{2}$
$(x - 2)^2 + (y - 1)^2 = 2$
Think about circles.


text:
Q: Django: Put multiple widgets/fields into one field I'm making a form to let users edit their photo gallery. So when I show the form I need 2 fields/widget per photo.
For each photo there will be one
CheckBox(label='Delete photo', value=<Id of photo>)
and one RadioSelect(label='Set as cover image', value=<Id of photo>)
In the form class I guess I should put something like this in the __init__:
for image in images:
    #make a checkbox widget
    #make a radio select
    #store the url of the image
    self.fields[..] = gallery_field_widget

I would prefer to put as much code in the form class instead of the template. I've played around with MultpleSelect widget but I can't figure out how to iterate through it together with the rest of the widgets.. and help on this?

A: This isn't two widgets per field, this is two fields per form and one form per instance. For that we have formsets.


text:
Q: Undefined reference error on linking - Makefile and includes configured I have two sources file, main.cpp & functions.cpp, and a header filed main.h, and finally a Makefile:
main.cpp
#include "main.h"

int main()
{
    Application game;

    game.update();
    game.draw();
}

functions.cpp
#include "main.h"

Application::Application()
{
    window = SDL_CreateWindow("SDL GAME",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            SCREEN_WIDTH,
            SCREEN_HEIGHT, 0);

    if(!window)
    {
        printf("Error: %s\n", SDL_GetError());
    }

    windowSurface = SDL_GetWindowSurface(window);

    if(!windowSurface)
    {
        printf("Error: %s\n", SDL_GetError());
    }
}

Application::~Application()
{
    SDL_FreeSurface(windowSurface);
    SDL_DestroyWindow(window);
}

void Application::update()
{
    bool quit = false;
    while(!quit)
    {
        SDL_Event e;
        while(SDL_PollEvent(&e) > 0) //Event queue
        {
            switch(e.type)
            { //Add events here
                case SDL_QUIT:
                    quit = true;
                    break;
            }
        }
        //DRAW
        Application::draw();
        //STOP DRAW
        SDL_UpdateWindowSurface(window);
    }
}

void Application::draw()
{
    SDL_UpdateWindowSurface(window);
}

main.h
#pragma once

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdio.h>
#include <string>

const int SCREEN_WIDTH = 500;
const int SCREEN_HEIGHT = 500;

class Application
{
    public:
        Application();
        ~Application();

        void update();
        void draw();

    private:
        SDL_Window *window = NULL;
        SDL_Surface *windowSurface = NULL;
        SDL_Event event;
};

Makefile
.PHONY = all clean

CC = g++

SRCS:= $(wildcard src/*.cpp) # Succesfully grabs all source files
BINS := $(SRCS:%.cpp=%)

LINKERFLAG = -lSDL2 -Isrc

all: ${BINS}

%: %.cpp
    ${CC} ${LINKERFLAG} $< -o $@.o

%.o: %.cpp
    ${CC} -o $<.o

clean:
    rm -rvf *.o ${BINS}

The error

g++ -lSDL2 -Isrc src/main.cpp -o src/main.o
/usr/lib64/gcc/x86_64-suse-linux/10/../../../../x86_64-suse-linux/bin/ld:
/tmp/ccp2ZmwE.o: in function main': main.cpp:(.text+0x11): undefined reference to Application::Application()'
/usr/lib64/gcc/x86_64-suse-linux/10/../../../../x86_64-suse-linux/bin/ld:
main.cpp:(.text+0x1d): undefined reference to Application::update()' /usr/lib64/gcc/x86_64-suse-linux/10/../../../../x86_64-suse-linux/bin/ld: main.cpp:(.text+0x29): undefined reference to Application::draw()'
/usr/lib64/gcc/x86_64-suse-linux/10/../../../../x86_64-suse-linux/bin/ld:
main.cpp:(.text+0x35): undefined reference to
Application::~Application()' /usr/lib64/gcc/x86_64-suse-linux/10/../../../../x86_64-suse-linux/bin/ld: main.cpp:(.text+0x4b): undefined reference to Application::~Application()'

What I have tried: using -c to compile all then running again without to link, no success. I'm coming to c++ and Make from a python background so it is fairly new to me. What I think is happening is it's trying to link main.cpp before compiling functions.cpp, but I don't know how to go about that figuring that out.

A: Suppose you have a self-contained source file, foo.cpp.
You could build the executable foo in one step:
g++ foo.cpp -o foo

Or you could build the object file, then build the executable from that:
g++ -c foo.cpp -o foo.o
g++ foo.o -o foo

Now suppose you have two source files, main.cpp and functions.cpp. The code in main.cpp calls a function defined in functions.cpp. If you carelessly try to build the executable from only one file:
g++ main.cpp -o app

the compiler will complain that your code calls a function that has no definition. This is what your makefile does, when it tries to build main:
%: %.cpp
    ${CC} ${LINKERFLAG} $< -o $@.o

The usual way in a case like this is to build the object files first, then link them:
g++ -c main.cpp -o main.o
g++ -c functions.cpp -o functions.o
g++ main.o functions.o -o name_of_executable

You can do that with a makefile that looks like this:
$(EXEC_NAME): main.o functions.o
    ${CC} ${LINKERFLAG} $^ -o $@

%.o: %.cpp
    ${CC} -c $< -o $@

There are some more refinements to make (and you don't even have to write that second rule, Make already knows it), but that should be enough to get you started.


text:
Q: prevent nested for loops in javascript this is my JSON file and i want to create HTML multi level menu without nested loops
[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home"},{"text":"Posts","href":"","icon":"fas fa-bell","target":"_self","title":"","children":[{"text":"Sports","href":"","icon":"empty","target":"_self","title":""},{"text":"IT1","href":"","icon":"empty","target":"_self","title":""},{"text":"Web","href":"","icon":"","target":"_self","title":""},{"text":"About","href":"","icon":"fas fa-chart-bar","target":"_self","title":""}]}]

i wrote this but i think its not the best way to do that
thanks for helping
        function MenuToHTML(JSON) {
            let html = "
";
            for (items in JSON) {
                html += "
";
                //console.log(JSON[items].text);
                html += JSON[items].text;
                if (JSON[items].hasOwnProperty("children")) {
                    var child = JSON[items].children;
                    html += "
";
                    for (subItems in child) {
                        html += "
";
                        html += child[subItems].text;
                        if (child[subItems].hasOwnProperty("children")) {
                            html += "
";
                            var child = child[subItems].children;
                            for (SubsubItems in child) {
                                html += "
";
                                html += child[SubsubItems].text;
                                html += "
";
                            }
                            html += "
";
                        }
                        html += "
";
                    }
                    html += "
";
                }
                html += "
";
            }
            html += "
";
            return html;
        }

A: You donot need to create nested loops like that use recursion and for arrays use for for..of or forEach instead of for..in

let arr = [
 {"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home"},
 {"text":"Posts","href":"","icon":"fas fa-bell","target":"_self","title":"","children":
  [{"text":"Sports","href":"","icon":"empty","target":"_self","title":""},
  {"text":"IT1","href":"","icon":"empty","target":"_self","title":""},
  {"text":"Web","href":"","icon":"","target":"_self","title":""},
  {"text":"About","href":"","icon":"fas fa-chart-bar","target":"_self","title":""}]}
]

/*this function will convert an array to html list. So you can pass the children
array again to the same function and it will to convert children to html list*/
function MenuToHTML(JSON) {
     let html = "
";
  JSON.forEach(item => {
  html += `<li>${item.text}</li>`;
  if(item.children){
   html += MenuToHTML(item.children);
  }
 })
 return html + '
';
}
document.body.innerHTML = MenuToHTML(arr);

A: You could build real elements and use a recursion for nested children.

function getMenu(array) {
    return array.reduce((ul, { text, href, icon, target, title, children }) => {
        var li = document.createElement('li'),
            a;

        if (href) {
            a = document.createElement('a');
            a.href = href;
            a.target = target;
            a.appendChild(document.createTextNode(text));
            a.title = title;
            li.appendChild(a);
        } else {
            li.appendChild(document.createTextNode(text));
        }
        if (children) {
            li.appendChild(getMenu(children));
        }
        ul.appendChild(li);
        return ul;
    }, document.createElement('ul'));
}

var data = [{ text: "Home", href: "http://home.com", icon: "fas fa-home", target: "_top", title: "My Home" }, { text: "Posts", href: "", icon: "fas fa-bell", target: "_self", title: "", children: [{ text: "Sports", href: "", icon: "empty", target: "_self", title: "" }, { text: "IT1", href: "", icon: "empty", target: "_self", title: "" }, { text: "Web", href: "", icon: "", target: "_self", title: "" }, { text: "About", href: "", icon: "fas fa-chart-bar", target: "_self", title: "" }] }];

document.body.appendChild(getMenu(data));


text:
Q: To find the Joint distribution $f(x,y)=(1+x^3\,y^3)/4 \quad \Big[(x,y)\in[-1,1]^2\Big]$
How to find the joint distribution of $f(x^2,y^2)$??
Well this one is completely new for me as I am a begginer. Any help would b appreciated.

A: Double integrate to find $\mathsf P(X^2\leqslant u,Y^2\leqslant v)$, then double differentiate with respect to $u,v$.
Hint: Actually, use the Fundamental Theorem of Calculus to avoid integrating and differentiating back.   It should then simplify greatly in just a few steps.
$\begin{split}\qquad f_{\small X^2,Y^2}(u,v)=~&\begin{vmatrix}\dfrac{\mathsf d^2 \mathsf P(X^2\leqslant u, Y^2\leqslant v)}{\mathsf du~\mathsf d v\hspace{16ex}}\end{vmatrix}\\[1ex]=~& \begin{vmatrix}\displaystyle\dfrac{\mathsf d^2 ~~~~~}{\mathsf d u~\mathsf d v}\int_{-\surd u}^{\surd u}\int_{-\surd v}^{\surd v} \dfrac{1+(xy)^3}{4}~\mathsf d y~\mathsf d x\end{vmatrix}\mathbf 1_{(u,v)\in[0;1]^2}\\[1ex]=~& \phantom{ \dfrac{1}{4\surd(uv)}\left(\dfrac{1+(uv)^{3/2}}{4}+\dfrac{1-(uv)^{3/2}}{4}+\dfrac{1-(uv)^{3/2}}{4}+\dfrac{1+(uv)^{3/2}}{4}\right)\mathbf 1_{(u,v)\in[0;1]^2}}\\ =~&\phantom{\dfrac{1}{4\surd(uv)}\mathbf 1_{(u,v)\in[0;1]^2}}\end{split}$


text:
Q: What's the difference between substitution and equality? Is $2$ a substitution for $1+1$, or equal to $1+1$? In this case both seems true, but I was wondering if there really is a difference. Whenever there is an equality $A=B$, is it also true that $B$ is always a substitution for $A$?

A: In the sense you have defined substitution and equality, they refer to the same thing.
Firstly, in order to shorten long complicated expressions containing $1+1$, we chose to substitute it by $2$. Hence we made the statement that $1+1=2$.
However, one can also claim that we have DEFINED $1+1=2$.

A: It is true that if there's equality, then you can apply substitution. That comes from the definition of equality, as explained in this answer. The opposite is not always true. Let's see some examples.
Non-transitive relations
Here, substitution doesn't work because there's no equivalence relation at all. If you take two real numbers $x$ and $y$, given that $x \ne y$ and $x \ne 7$, it would be a huge mistake to claim that $y \ne 7$.
Transitive relations
Let's add the transitivity. The subset inclusion relation $\subset$ suits well. Knowing, for example, that
$$
\lbrace x \in \mathbb{R} \colon -1 \le x \le 1 \rbrace \subset \lbrace x \in \mathbb{R} \colon 1 + \lvert x \rvert < \pi \rbrace
$$
and that $\mathbb{Q} \cap [0,\frac12]$ is included in the first set, you can safely write that
$$
\mathbb{Q} \cap [0,\frac12] \subset \lbrace x \in \mathbb{R} \colon 1 + \lvert x \rvert < \pi \rbrace
$$
but there's no equality in those sets. Indeed, you would have that
$$
\lbrace x \in \mathbb{R} \colon -1 \le x \le 1 \rbrace \subset \mathbb{Q} \cap [0,\frac12]
$$
which is false.
Substitution derived from equality
That's the case of, say, algebraic substitution. Suppose you are given the system of equations
$$
\begin{cases}
x + y = 6 \\
3x + 2y = -1
\end{cases};
$$
you can rephrase the second equation as
$$
2(x+y) + x = -1
$$
and substitute $x + y$ with $6$ because of their equality, leading to
$$
\begin{cases}
x = -13 \\
y = 19
\end{cases}.
$$
The peculiar feature of equality is that, among the axioms which define it, there is the so-called indiscernibility of identicals.

Given two entities $x$ and $y$ and a predicate $\phi(u, \alpha_1,\dots,\alpha_n)$,
  $$
x = y \implies \phi(x,\alpha_1,\dots,\alpha_n) = \phi(y,\alpha_1,\dots,\alpha_n).
$$

Can you recognise which entities are involved in this example? Which is the predicate?
Then, there is Leibniz's Law, which states that also the opposite implication holds for equality, giving the equivalence
$$
\forall x.\forall y. x = y \iff \phi(x,\alpha_1,\dots,\alpha_n) = \phi(y,\alpha_1,\dots,\alpha_n).
$$
Substitution without equality
If you take the relation
$$
x \equiv 3 \pmod{6} \quad x \in \mathbb{Z}
$$
and thanks to the transitivity of the congruence relation, we can substitute $3$ by $9$, since they are congruent modulo $6$. However, they are not the same integer. As you can see, here substitution is used without the condition of equality.
If you take the set of congruence classes modulo $6$, denoted by $\mathbb{Z}/6\mathbb{Z}$, you have that $[3]$ and $[9]$ are equal. That's a matter of definition of the involved entities.
What about quotients?
As nicely explained here, a necessary condition to have equality and substitutivity is for the considered relation to be compatible with operations. Then, the quotient space w.r.t. the equivalence relation allows you to consider compatible objects as equals.


text:
Q: How can I alphabetically sort the values in my NSDictionary with an NSArray? I have an NSDictionary which contains several arrays with several strings in them. I want to put all strings under each array in one single array. How can I receive all the strings at once? I've tried this:
NSMutableArray *mutarr = [[NSMutableArray alloc] initWithObjects:[self.firstTableView allValues], nil];
NSArray *mySorted = [[NSArray alloc]init];
mySorted = [mutarr sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSLog(@"First table view values: %@", mySorted);

NOTE: self.firsttableview is a NSDictionary like this:
NSString *path = [[NSBundle mainBundle] pathForResource:@"firstTableView" ofType:@"plist"];

self.firstTableView = [NSDictionary dictionaryWithContentsOfFile:path];

EFFECT: This gives me a list in NSLog, but it isn't in alphabetic order.

A: You are initializing your mutarr with one object which is the array returned by allValues on your dictionary. Instead try this:
NSMutableArray* mutarr = [NSMutableArray array];

for (NSArray* array in self.firstTableView.allValues) {
    [mutarr addObjectsFromArray:array];
}

A: Your code is going to mean that mutarr is an array containing an array of arrays, not an array of strings. You should be looping over the array values from the dictionary and adding the items from each one to your mutarr to make it an array of strings that you can sort.

A: If your NSDictionary values are arrays then you are trying to sort the arrays instead of the strings. Try to create a for loop to iterate [self.firstTableView allValues] then add all values in that array to your main to sort array.


text:
Q: Excel VBA Initialize Workbook by Clearing Tables I have some VBA code which I use in another workbook to resize a table to be 1 row and delete the contents of a data table to initialize a workbook. Then a file prompt opens asking the user to select the appropriate file for processing. For some reason, I am getting a

"Run-time error '91': Object variable or With block variable not set"

The code is a copy and paste from the other workbook and I have adjusted the names of the variables, workbooks, worksheets, and table names.
workbook is called "IMD Processing.xlsm" with 2 sheets titled "IMD" and "Raw". The "Raw" sheet has a table with the name "tbl_raw" and the "IMD" sheet has a table with the name "tbl_imd".
Any guidance would be greatly appreciated.
Option Explicit

Sub IMDAutomation()

Dim fileName As String 'Filename string

Dim wb_macro As Workbook 'Macro workbook
Dim ws_macro_imd As Worksheet 'Macro worksheet
Dim ws_macro_raw As Worksheet 'Macro raw worksheet

Dim wb_imd As Workbook 'IMD Workbook for processing
Dim ws_imd As Worksheet 'IMD Worksheet for processing

Dim objTable As ListObject 'Table of raw data

Dim tbl_raw As ListObject 'Raw table in macro workbook
Dim tbl_imd As ListObject 'IMD table in macro workbook

Dim vals As Variant 'Array to store values

Dim lrow As Long 'Variable used to determine number of rows in data table

Set wb_macro = ThisWorkbook
Set ws_macro_imd = Sheets("IMD")
Set ws_macro_raw = Sheets("Raw")

'============ Initialize macro workbook - clearing data ============'
'Clear the raw data in the macro workbook
Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw")
    With tbl_raw.DataBodyRange
           If .Rows.Count > 1 Then
            .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
        End If
    End With
tbl_raw.DataBodyRange.Rows(1).ClearContents

'Clear the IMD data in the macro workbook
Set tbl_imd = ws_macro_imd.ListObjects("tbl_imd")
    With tbl_imd.DataBodyRange
        If .Rows.Count > 1 Then
            .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count).Rows.Delete
        End If
    End With

'============ Locate Raw Data File ============'
'Open file dialog to locate the Workforce Review raw data workbook exported from system
With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .Title = "Select the IMD file"
    .Filters.Clear
    .Filters.Add "Custom Excel Files", "*.xlsx, *xls, *csv"
    .Show
    fileName = .SelectedItems.Item(1)
End With
If InStr(fileName, ".xlsx") = 0 Then
Exit Sub
End If
Workbooks.Open fileName
'Set the Workforce Review raw workbook
Set wb_imd = ActiveWorkbook
'Set the worksheet
Set ws_imd = wb_imd.ActiveSheet

lrow = ws_imd.Cells(ws_imd.Rows.Count, 2).End(xlUp).Row
vals = ws_imd.Range("A2:CU" & lrow)

Application.CutCopyMode = False
Application.CutCopyMode = True

End Sub

UDPATE WITH SOLUTION
Thanks to @Variatus for the solution.
I did not have a data row in my table so I created one and now it's working.
This should work to handle cases where there is no row in the table. If tbl_raw.DataBodyRange Is Nothing Then InsertRowRange Else (Code to clear the table)

A: Probably the object that is being searched for by Set tbl_raw = ws_macro_raw.ListObjects("tbl_raw") does not exist in the new workbook and hence referencing through With tbl_raw returns this error


text:
Q: Show that $F_x(x,y) = P(x,y), \ F_y(x,y) = Q(x,y)$. In Complex Variables and Applications by Brown and Churchill it comes:

When the point $(x_0,y_0)$ is kept fixed and $(x , y)$ is allowed to vary throughout a simply connected domain $D$, the integral represents a single-valued function $$F(x,y) = \int_{(x_0,y_0)}^{(x,y)} P(s,t) ds+ Q(s,t) dt$$ of $x$ and $y$ whose first-order partial derivatives are given by the equations $$F_x(x,y) = P(x,y), \ \ F_y(x,y) = Q(x,y).$$

My question is how $F_x(x,y) = P(x,y), \  F_y(x,y) = Q(x,y)$ hold?
I searched MSE for similar question, but no much similarities with other questions and Leibniz integral rule couldn't be much help: For, there are variables in upper bound (actually two), partial derivative with respect to one variable makes the other function zero!! and confusion of different variables 'inside' the integral.

A: Fix a point $(x,y)$. Since the domain $D$ is open, there is some small disk $\Delta$ centered at $(x,y)$ which is entirely contained in $D$. The line segment $(a,y) \to (x,y)$ is thus contained in $D$ for some constant $a$ sufficiently close to $x$. Since we have independence of the integration path, choose a path which starts by going from $(x_0,y_0)$ to $(a,y)$, followed by the line segment $(a,y) \to (x,y)$. We then have
$$F(x,y)=\int_{(x_0,y_0)}^{(a,y)} P(s,t) \,\mathrm{d} s+ Q(s,t)\, \mathrm{d}t+\int_{(a,y)}^{(x,y)} P(s,t) \,\mathrm{d} s+ Q(s,t)\, \mathrm{d}t . $$
Taking the partial derivative w.r.t. $x$ we notice that the first term vanishes, meaning
$$F_x(x,y)=\frac{\partial}{\partial x} \int_{(a,y)}^{(x,y)} P(s,t) \,\mathrm{d} s+ Q(s,t)\, \mathrm{d}t. $$
This integral can be rewritten using the parameterization $s=u,t=y$, for $a \leqslant u \leqslant x$, giving
$$F_x(x,y)=\frac{\partial}{\partial x} \int_a^x P(u,y) \mathrm{d} u. $$
The Fundamental Theorem of Calculus then gives $F_x=P$. A similar approach gives $F_y=Q$.


text:
Q: ssh Bad configuration option: host Try to set up ssh with this instructions: https://support.atlassian.com/bitbucket-cloud/docs/set-up-an-ssh-key/
get the following error:
user@iMac-user dir % ssh -T git@bitbucket.org
/Users/bitbucket-user/.ssh/config: line 1: Bad configuration option: host
/Users/bitbucket-user/.ssh/config: terminating, 1 bad configuration options

config file contains only 2 rows as described:
Host *
UseKeychain yes

ssh -V:
OpenSSH_8.6p1, LibreSSL 2.8.3

What I missed? It should be pretty simple i think.


text:
Q: Por qué Router Outlet me duplica los componentes? soy iniciante en Angular y en mi componente principal tengo esto
 <app-header>
  </app-header>

ver libros

        <router-outlet></router-outlet>

        <app-footer></app-footer>

En mi localhost veo los componentes duplicado, de esta forma:

HEADER - VER LIBROS - HEADER - VER LIBROS - FOOTER - FOOTER
alguno sabe como hacer para que eso no pase?

A: Y si lo colocas dentro de un section?? Ejemplo:
<app-header>    </app-header>

ver libros

 <router-outlet></router-outlet>

 <app-footer></app-footer>