text:
Q: Using a switch statement to determine GPA result This is the code to determine a GPA from the command line. At the moment, the code is incorrect. I'm hoping to see the corrected code.
public class Main {
  public static void main(String[] args)  {
    double gpa = Integer.parseInt(args [0]);
    switch(gpa)) {
      case (gpa>3.5) :           System.out.println("First class Hons"); break;
      case (3.49=> gpa => 3.0):  System.out.println("upper Second class Hons"); break;
      case (2.99=> gpa >= 2.5):  System.out.println("Lower Second class Hons"); break;
      case (2.99=> gpa >= 2.0):  System.out.println("Pass"); break;
      case (2.0 => gpa):         System.out.println("Fail"); break;
      default:                   System.out.println("Invalied gpa");
    }
  }
}

A: Switch/case statements don't work like that. They're not conditions - they're specific cases. (And, as pointed out by others, you can't switch on double values anyway.) You just want a lot of if/else statements:
String grade;
if (gpa >= 3.5) {
    grade = "First class Hons";
} else if (gpa >= 3.0) {
    grade = "Upper second class Hons";
} else if (gpa >= 2.5) {
    grade = "Lower second class Hons";
} else if (gpa >= 2.0) {
    grade = "Pass";
} else {
    grade = "Fail";
}
System.out.println(grade);

It's important to note that I'm only using one condition for each check here - even if your syntax for switch/case worked, and even if you'd changed => to >= in each case, you'd still have invalid cases such as 3.495 which didn't fall into any buckets. It also means that you only need to specify each boundary once.
Now, when you've got it compiling it's still going to fail if you enter "3.5" as input, because of this line:
double gpa = Integer.parseInt(args [0]);

You actually want
double gpa = Double.parseDouble(args[0]);

... otherwise you'll only parse integer input.
You might also want to consider using BigDecimal instead of double here - for this specific case it may not matter, but if you're really interested in maintaining the exact decimal digits, BigDecimal is more appropriate.

A: Hint: you can't easily use switch here. Use a series of if statements instead.

A: Java clearly states:

A switch works with the byte, short, char, and int primitive data
  types. It also works with enumerated types (discussed in Enum Types),
  the String class, and a few special classes  that wrap certain
  primitive types: Character, Byte, Short, and Integer (discussed in
  Numbers  and String).

More details on switch along with example can be seen at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
So as suggested by others if-else is the way to go.

A: You could use a switch statement if you REALLY want, by using enums to represent the different grades:
public class Main {
    public static void main(String[] args) {
        double gpa = Double.parseDouble(args[0]);
        Grade grade = Grade.getGradeFromGPA(gpa);

        switch (grade) {
            case FIRST_CLASS:   System.out.println("First class Hons"); break;
            case TWO_ONE:       System.out.println("upper Second class Hons"); break;
            case TWO_TWO:       System.out.println("Lower Second class Hons"); break;
            case PASS:          System.out.println("Pass"); break;
            case FAIL:          System.out.println("Fail"); break;
            default:            System.out.println("Invalied gpa");
        }
    }

    private enum Grade {
        FIRST_CLASS(3.5, 4),
        TWO_ONE(3, 3.49),
        TWO_TWO(2.5, 2.99),
        PASS(2.49, 2),
        FAIL(0, 1.99);

        private final double minGPA;
        private final double maxGPA;

        Grade(final double minGPA, final double maxGPA) {
            this.minGPA = minGPA;
            this.maxGPA = maxGPA;
        }

        static Grade getGradeFromGPA(double gpa) {
            for (Grade grade : Grade.values()) {
                if (grade.maxGPA >= gpa && grade.minGPA <= gpa) {
                    return grade;
                }
            }
            //invalid GPA
            return null;
        }
    }
}

Notes:

*

*I've corrected Integer.parseInt to Double.parseDouble

*I have left the logic the way it was in your question, but it does leave a doubt around what happens with inputs like 3.499 - this will return an invalid grade, as it slips between the max of TWO_ONE and the min of FIRST_CLASS

If you really used an enum, you probably wouldn't use a switch to print out the grade.  You'd be better off having a String representing the description of the grade and printing that, i.e.:
public static void main(String[] args) {
    double gpa = Double.parseDouble(args[0]);
    Grade grade = Grade.getGradeFromGPA(gpa);

    if (grade != null) {
        System.out.println(grade.description);
    } else {
        System.out.println("Invalied gpa");
    }
}

private enum Grade {
    FIRST_CLASS(3.5, 4, "First class Hons"),
    TWO_ONE(3, 3.49, "upper Second class Hons"),
    TWO_TWO(2.5, 2.99, "Lower Second class Hons"),
    PASS(2.49, 2, "Pass"),
    FAIL(0, 1.99, "Fail");

    private final double minGPA;
    private final double maxGPA;
    private final String description;

    // remaining code omitted for brevity
}

The moral of this story is that you shouldn't let your programming hammer (in this case, the switch statement) drive your design.  Your code should reflect the problem you're trying to solve, you shouldn't be forcing your problem into the shape of your code.


text:
Q: UIDatePicker not scrolling iOS I do not know what to say but this bug has been haunting me for the last 2 days and I cannot get it to work.
I want to add a UIDatePicker to my view. But for some reason it is not scrolling. I just dragged and dropped the control but without any luck. I checked my view is user-interaction enabled. I even created a dummy view controller which only has a picked in it and made it the initial view controller, still no scrolling happening.
All other interactions are fine.
I created a new project from scratch and simply dropped a picker in its view and tested. It scrolled!!! Not sure why the one in my app is not.
I know you will ask for code, but there is no code here. Jut adding the picker in an initial vc and no action is happening.
Any idea what could be wrong? where i should look?
Cheers

A: Try to use following code
#import "DatePickerViewController.h"

@interface DatePickerViewController ()

@end

@implementation DatePickerViewController

-(void)getSelection:(id)sender
{
   NSLocale *usLocale = [[NSLocale alloc]
       initWithLocaleIdentifier:@"en_US"];

   NSDate *pickerDate = [_datePicker date];
   NSString *selectionString = [[NSString alloc]
       initWithFormat:@"%@",
       [pickerDate descriptionWithLocale:usLocale]];
   _dateLabel.text = selectionString;
}
.
.
.
@end

redpajama_set_name: RedPajamaStackExchange


text:
Q: 403 Forbidden Error : JSON-RPC PHP I tried to implement json-rpc server on local for some test.
But when I send some request, it returns the "Forbidden Error".
I made a clone from git (https://github.com/fguillot/JsonRPC), but for now I wanted to make sure something could be returned. So I used command line, instead of running program named Client.php.
example.php
    <?php

    require 'Server.php';
    use JsonRPC\Server;

    $server = new Server;
    $server->register('addition', function ($a, $b) {

        return $a + $b;
    });
    $server->register('random', function ($start, $end) {

        return mt_rand($start, $end);
    });

    echo $server->execute();

    ?>

Server.php
<?php

namespace JsonRPC;

use Closure;
use BadFunctionCallException;
use Exception;
use InvalidArgumentException;
use LogicException;
use ReflectionFunction;
use ReflectionMethod;

class InvalidJsonRpcFormat extends Exception {};
class InvalidJsonFormat extends Exception {};

/**
 * JsonRPC server class
 *
 * @package JsonRPC
 * @author  Frederic Guillot
 * @license Unlicense http://unlicense.org/
 */
class Server
{
    /**
     * Data received from the client
     *
     * @access private
     * @var string
     */
    private $payload;

    /**
     * List of procedures
     *
     * @static
     * @access private
     * @var array
     */
    private $callbacks = array();

    /**
     * List of classes
     *
     * @static
     * @access private
     * @var array
     */
    private $classes = array();

    /**
     * Constructor
     *
     * @access public
     * @param  string   $payload      Client data
     * @param  array    $callbacks    Callbacks
     * @param  array    $classes      Classes
     */
    public function __construct($payload = '', array $callbacks = array(), array $classes = array())
    {
        $this->payload = $payload;
        $this->callbacks = $callbacks;
        $this->classes = $classes;
    }

    /**
     * IP based client restrictions
     *
     * Return an HTTP error 403 if the client is not allowed
     *
     * @access public
     * @param  array   $hosts   List of hosts
     */
    public function allowHosts(array $hosts) {

        if (! in_array($_SERVER['REMOTE_ADDR'], $hosts)) {

            header('Content-Type: application/json');
            header('HTTP/1.0 403 Forbidden');
            echo '{"error": "Access Forbidden"}';
            exit;
        }
    }

    /**
     * HTTP Basic authentication
     *
     * Return an HTTP error 401 if the client is not allowed
     *
     * @access public
     * @param  array   $users   Map of username/password
     */
    public function authentication(array $users)
    {
        if (! isset($_SERVER['PHP_AUTH_USER']) ||
            ! isset($users[$_SERVER['PHP_AUTH_USER']]) ||
            $users[$_SERVER['PHP_AUTH_USER']] !== $_SERVER['PHP_AUTH_PW']) {

            header('WWW-Authenticate: Basic realm="JsonRPC"');
            header('Content-Type: application/json');
            header('HTTP/1.0 401 Unauthorized');
            echo '{"error": "Authentication failed"}';
            exit;
        }
    }

    /**
     * Register a new procedure
     *
     * @access public
     * @param  string   $procedure       Procedure name
     * @param  closure  $callback        Callback
     */
    public function register($name, Closure $callback)
    {
        $this->callbacks[$name] = $callback;
    }

    /**
     * Bind a procedure to a class
     *
     * @access public
     * @param  string   $procedure    Procedure name
     * @param  mixed    $class        Class name or instance
     * @param  string   $method       Procedure name
     */
    public function bind($procedure, $class, $method)
    {
        $this->classes[$procedure] = array($class, $method);
    }

    /**
     * Return the response to the client
     *
     * @access public
     * @param  array    $data      Data to send to the client
     * @param  array    $payload   Incoming data
     * @return string
     */
    public function getResponse(array $data, array $payload = array())
    {
        if (! array_key_exists('id', $payload)) {
            return '';
        }

        $response = array(
            'jsonrpc' => '2.0',
            'id' => $payload['id']
        );

        $response = array_merge($response, $data);

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

    /**
     * Parse the payload and test if the parsed JSON is ok
     *
     * @access public
     */
    public function checkJsonFormat()
    {
        if (empty($this->payload)) {
            $this->payload = file_get_contents('php://input');
        }

        if (is_string($this->payload)) {
            $this->payload = json_decode($this->payload, true);
        }

        if (! is_array($this->payload)) {
            throw new InvalidJsonFormat('Malformed payload');
        }
    }

    /**
     * Test if all required JSON-RPC parameters are here
     *
     * @access public
     */
    public function checkRpcFormat()
    {
        if (! isset($this->payload['jsonrpc']) ||
            ! isset($this->payload['method']) ||
            ! is_string($this->payload['method']) ||
            $this->payload['jsonrpc'] !== '2.0' ||
            (isset($this->payload['params']) && ! is_array($this->payload['params']))) {

            throw new InvalidJsonRpcFormat('Invalid JSON RPC payload');
        }
    }

    /**
     * Return true if we have a batch request
     *
     * @access public
     * @return boolean
     */
    private function isBatchRequest()
    {
        return array_keys($this->payload) === range(0, count($this->payload) - 1);
    }

    /**
     * Handle batch request
     *
     * @access private
     * @return string
     */
    private function handleBatchRequest()
    {
        $responses = array();

        foreach ($this->payload as $payload) {

            if (! is_array($payload)) {

                $responses[] = $this->getResponse(array(
                    'error' => array(
                        'code' => -32600,
                        'message' => 'Invalid Request'
                    )),
                    array('id' => null)
                );
            }
            else {

                $server = new Server($payload, $this->callbacks, $this->classes);
                $response = $server->execute();

                if ($response) {
                    $responses[] = $response;
                }
            }
        }

        return empty($responses) ? '' : '['.implode(',', $responses).']';
    }

    /**
     * Parse incoming requests
     *
     * @access public
     * @return string
     */
    public function execute()
    {
        try {

            $this->checkJsonFormat();

            if ($this->isBatchRequest()){
                return $this->handleBatchRequest();
            }

            $this->checkRpcFormat();

            $result = $this->executeProcedure(
                $this->payload['method'],
                empty($this->payload['params']) ? array() : $this->payload['params']
            );

            return $this->getResponse(array('result' => $result), $this->payload);
        }
        catch (InvalidJsonFormat $e) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32700,
                    'message' => 'Parse error'
                )),
                array('id' => null)
            );
        }
        catch (InvalidJsonRpcFormat $e) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32600,
                    'message' => 'Invalid Request'
                )),
                array('id' => null)
            );
        }
        catch (BadFunctionCallException $e) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32601,
                    'message' => 'Method not found'
                )),
                $this->payload
            );
        }
        catch (InvalidArgumentException $e) {

            return $this->getResponse(array(
                'error' => array(
                    'code' => -32602,
                    'message' => 'Invalid params'
                )),
                $this->payload
            );
        }
    }

    /**
     * Execute the procedure
     *
     * @access public
     * @param  string   $procedure    Procedure name
     * @param  array    $params       Procedure params
     * @return mixed
     */
    public function executeProcedure($procedure, array $params = array())
    {
        if (isset($this->callbacks[$procedure])) {
            return $this->executeCallback($this->callbacks[$procedure], $params);
        }
        else if (isset($this->classes[$procedure])) {
            return $this->executeMethod($this->classes[$procedure][0], $this->classes[$procedure][1], $params);
        }

        throw new BadFunctionCallException('Unable to find the procedure');
    }

    /**
     * Execute a callback
     *
     * @access public
     * @param  Closure   $callback     Callback
     * @param  array     $params       Procedure params
     * @return mixed
     */
    public function executeCallback(Closure $callback, $params)
    {
        $reflection = new ReflectionFunction($callback);

        $arguments = $this->getArguments(
            $params,
            $reflection->getParameters(),
            $reflection->getNumberOfRequiredParameters(),
            $reflection->getNumberOfParameters()
        );

        return $reflection->invokeArgs($arguments);
    }

    /**
     * Execute a method
     *
     * @access public
     * @param  mixed     $class        Class name or instance
     * @param  string    $method       Method name
     * @param  array     $params       Procedure params
     * @return mixed
     */
    public function executeMethod($class, $method, $params)
    {
        $reflection = new ReflectionMethod($class, $method);

        $arguments = $this->getArguments(
            $params,
            $reflection->getParameters(),
            $reflection->getNumberOfRequiredParameters(),
            $reflection->getNumberOfParameters()
        );

        return $reflection->invokeArgs(
            is_string($class) ? new $class : $class,
            $arguments
        );
    }

    /**
     * Get procedure arguments
     *
     * @access public
     * @param  array    $request_params       Incoming arguments
     * @param  array    $method_params        Procedure arguments
     * @param  integer  $nb_required_params   Number of required parameters
     * @param  integer  $nb_max_params        Maximum number of parameters
     * @return array
     */
    public function getArguments(array $request_params, array $method_params, $nb_required_params, $nb_max_params)
    {
        $nb_params = count($request_params);

        if ($nb_params < $nb_required_params) {
            throw new InvalidArgumentException('Wrong number of arguments');
        }

        if ($nb_params > $nb_max_params) {
            throw new InvalidArgumentException('Too many arguments');
        }

        if ($this->isPositionalArguments($request_params, $method_params)) {
            return $request_params;
        }

        return $this->getNamedArguments($request_params, $method_params);
    }

    /**
     * Return true if we have positional parametes
     *
     * @access public
     * @param  array    $request_params      Incoming arguments
     * @param  array    $method_params       Procedure arguments
     * @return bool
     */
    public function isPositionalArguments(array $request_params, array $method_params)
    {
        return array_keys($request_params) === range(0, count($request_params) - 1);
    }

    /**
     * Get named arguments
     *
     * @access public
     * @param  array    $request_params      Incoming arguments
     * @param  array    $method_params       Procedure arguments
     * @return array
     */
    public function getNamedArguments(array $request_params, array $method_params)
    {
        $params = array();

        foreach ($method_params as $p) {

            $name = $p->getName();

            if (isset($request_params[$name])) {
                $params[$name] = $request_params[$name];
            }
            else if ($p->isDefaultValueAvailable()) {
                $params[$name] = $p->getDefaultValue();
            }
            else {
                throw new InvalidArgumentException('Missing argument: '.$name);
            }
        }

        return $params;
    }
}

Commmand Line (I use macOS)
curl --data-binary '{"jsonrpc": "2.0","id":1, "method":"addition","params":[100,200] }' -H 'content-type: text/plain;' http://127.0.0.1/jsonrpcphp3/example.php

Return Value
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>403 Forbidden</title>

Forbidden

You don't have permission to access /jsonrpcphp3/example.php
on this server.


text:
Q: datatable pagination in laravel I am using laravel 5.0
I am also using datatable jquery plugin to display grid.
Controller mehtod
 public function index() {

    $jobs = \App\Job::orderBy('created_at', 'DESC')->limit(1000)->get();

    return View::make('jobs.index', ['jobs' => $jobs]);
}

The issue:
Right now I hard-coded the ->limit(1000) to 1000 jobs in datatable grid to display
it but i have more then 1000 records to display.
What I want?
I want to display 500 records with grid and then 500 records.
I am not sure if there is any call back data-table plugin function available?
I need a dynamic way to load next 500
NOTE:
I am not willing to us this solution of scrolling
https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html

A: I think above answer should be extended with search feature.
Update the answer;
$filter = $request->get('search');
$search = (isset($filter['value']))? $filter['value'] : false;
where('somecolumnonyourdb','like', '%'.$search.'%')

This works for me

A: You can user ajax data source:
please visit : https://datatables.net/examples/ajax/objects.html
Example PHP Script:
// function will process the ajax request
public function getMembers(Request $request) {

        $draw = $request->get('draw');
        $start = $request->get('start');
        $length = $request->get('length');

        $search = (isset($filter['value']))? $filter['value'] : false;

        $total_members = 1000; // get your total no of data;
        $members = $this->methodToGetMembers($start, $length); //supply start and length of the table data

        $data = array(
            'draw' => $draw,
            'recordsTotal' => $total_members,
            'recordsFiltered' => $total_members,
            'data' => $members,
        );

        echo json_encode($data);
    }

Example JavaScript :
$('#all-member-table').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            url: base_url+"ajax/members"
            },
            "columns": [
            { data: '1' },
            { data: '2' },
            { data: '3' },
            { data: '4' },
            { data: '5' },
        ]
    } );

Example HTML:

                    Column1
                    Column2
                    Column3
                    Column4
                    Column5

A: You can use standard pagination:
$jobs = \App\Job::latest()->paginate(500);

Or create it manually.


text:
Q: Add level and balance in search tree in TiKZ I have the following AVL search tree:
\documentclass[border=10pt]{standalone}
  \usepackage{tikz}
   \begin{document}
    \begin{tikzpicture}[
                > = stealth, % arrow head style
                shorten > = 1pt, % don't touch arrow head to node
                auto,
                node distance = 4cm, % distance between nodes
                semithick % line style
            ]

            \tikzstyle{every state}=[
                draw = black,
                thin,
                fill = blue!50!,
                minimum size = 2mm
            ]

            \node[state] (b){};
             \node[state] (f)[below left=1cm and 1.5cm of b] {};
               \node[state] (g)[below left=1cm and 0.5cm of f] {};
               \node[state] (g2)[below right=1cm and 0.5cm of g] {};
               \node[state] (f2)[below right=1cm and 0.5cm of f] {};
            \node[state] (c)[below right=1cm and 1.5cm of b] {};
            \node[state] (d)[below right=1cm and 0.5cm of c] {};
             \node[state] (d2)[below left=1cm and 0.5cm of c] {};
              \node[state] (d3)[below right=1cm and 0.5cm of d2] {};
               \node[state] (d5)[below left=1cm and 0.5cm of d3] {};
               \node[state] (d4)[below left=1cm and 0.5cm of d2] {};
             \node[state] (h)[below right=1cm and 0.5cm of d] {};

              \path[-] (b) edge node {} (c);
              \path[-] (b) edge node {} (f);
                \path[-] (c) edge node {} (d);
               \path[-] (d) edge node {} (h);
                \path[-] (f) edge node {} (g);
                 \path[-] (f) edge node {} (f2);
                 \path[-] (c) edge node {} (d2);
                 \path[-] (d2) edge node {} (d3);
                 \path[-] (d2) edge node {} (d4);
                 \path[-] (d3) edge node {} (d5);
                   \path[-] (g) edge node {} (g2);

       \end{tikzpicture}
\end{document}

I want to write down the lovels of the search tree as well as the balance of every node like this:

A: Here's an example using Forest. Labelling the levels is straightforward. Labelling the nodes can be automated, almost certainly, but I don't know what the 'balance' depends on. Hence, it is not automated here. Instead, I show how to label a node manually by labelling the root as an example.
\documentclass[tikz,border=10pt]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
  for tree={
    draw,
    circle,
    inner sep=1.5pt,
    fill=pink!75!black!20,
    l sep'+=2.5mm,
    s sep'+=3.5mm,
  },
  before drawing tree={
    tikz+={
      \coordinate (a) at (current bounding box.east);
    },
    for nodewalk={
      r,
      while nodewalk valid={l}{l}
    }{
      tikz+/.process={
        Ow {level}{
          \node [anchor=west, font=\sffamily, magenta] at (.center -| a) {#1};
        }
      }
    }
  }
  [, label={[blue!50!cyan, font=\sffamily]right:1}
    [
      [
        [, phantom]
        []
      ]
      []
    ]
    [
      [
        []
        [
          []
          [, phantom]
        ]
      ]
      [
        [, phantom]
        [
          [, phantom]
          []
        ]
      ]
    ]
  ]
\end{forest}
\end{document}


text:
Q: How to plot multiple variables with means as y values for multiple groups in r? I have already researched the webs on how to do this but nothing has worked - there is an element missing always. I am trying to plot histogram for mean fish condition (y axis) for males and females(colour/legend) for each age group(x axis). What complicates it more is that I have multiple sites so I am not sure how to go about it. I have attached what is kind of close to what I had like to plot(note how a factor is missing-sites). There is a lot of code I have tried but I will provide a sample below. My data is saved as a csv with different columns that have sex, site, fish condition, etc.
F8 is the csv sheet that has multiple sites from one year
K is the fish condition column that I want means calculated for
gender.mean <- t(tapply(F8$K,
                        list(F8$Age1, F8$Sex), mean))

^I am not sure how to factor in the site as well.
I plotted this (code below) which gives me mean condition for both males and females for each age group but its all of sites combined.
barplot(gender.mean, col=c("darkblue","red"), beside=TRUE, legend=c("F","M"))

^for some reason, the x axis line (not numbers) is missing though and the legend is on top of the bars?
In addition, I had like the bars to have standard error bars but
geom_errorbar( aes(x=name, ymin=value-sd, ymax=value+sd), width=0.4, colour="orange", alpha=0.9, size=1.3)

the above code has not worked.


text:
Q: Micronaut data jdbc: saving an existing entity creates a new entity instead of updating the existing one I have the following Kotlin code:
val book = bookRepository
        .findById(1)
        .orElseThrow { DoesNotExistException("Book with ID 1 does not exist") }

bookRepository.save(book)

I would expect that this code just saves the same entity again. However, it actually generates a new entity by copying all the fields and changing the ID.
The Entity itself is here:
@Entity
data class Book(@Id
                @GeneratedValue
                var id: Long?,
                val status: Book.Status
)

I am using micronaut-data (previously named Micronaut Predator) with JDBC, I am not using JPA.
How could I update the existing entity without creating a new one?

A: That is how it works by design. From the documentation: https://micronaut-projects.github.io/micronaut-data/snapshot/guide/#jdbcQuickStart, scroll down to "Updating an Instance (Update)" section:

With Micronaut Data JDBC, you must manually implement an update method since the JDBC implementation doesn't include any dirty checking or persistence session notion. So you have to define explicit update methods for updates in your repository.


text:
Q: Radgridview visual issue I have problem displaying the columns correctly,
some columns have some gap in between
I wanted to attach a picture but I need 10 reputation points to post image
See picture link below!!
Here is my code:
private void UpdateProducts()
    {
        MyPharmacyDataContext db = new MyPharmacyDataContext();
        int tabid = Convert.ToInt32(radRibbonBar1.SelectedCommandTab.Name);
        var list = from g in db.OutOfStocks
                   where g.ListID == tabid
                   select new { g.ID, g.Product.CName, g.Required, g.Product.Price, g.Product.Disscount, g.Product.BuyPrice, g.TotalBuy, Stock = g.Product.Available + "," + g.Product.AvailableMid + "," + g.Product.AvailableSmall,g.Product.Supplier.Title };
        if (list.Count() > 0)
        {
            radGridView1.SummaryRowsBottom.Clear();
            radGridView1.Columns.Clear();

            radGridView1.Visible = true;
            radGridView1.TableElement.TableHeaderHeight = 60;
            GridViewTextBoxColumn num = new GridViewTextBoxColumn();
            num.MaxWidth = 50;
            num.Name = "num";
            num.HeaderText = "م";
            num.DataType = typeof(int);
            radGridView1.Columns.Add(num);

            radGridView1.DataSource = list;

            radGridView1.Columns[1].IsVisible = false;

            radGridView1.Columns[2].Width = 350;
            radGridView1.Columns[2].HeaderText = "اسم المنتج";
            radGridView1.Columns[2].Name = "Name";
            radGridView1.Columns[2].TextAlignment = ContentAlignment.MiddleCenter;

            radGridView1.Columns[3].MaxWidth = 60;
            radGridView1.Columns[3].HeaderText = "عدد";
            radGridView1.Columns[3].TextAlignment = ContentAlignment.MiddleCenter;
            radGridView1.Columns[3].Name = "Q";

            radGridView1.Columns[4].MaxWidth = 90;
            radGridView1.Columns[4].HeaderText = "السعر";
            radGridView1.Columns[4].Name = "Price";
            radGridView1.Columns[4].TextAlignment = ContentAlignment.MiddleCenter;
            radGridView1.Columns[4].FormatString = "{0:G29}";

            radGridView1.Columns[5].MaxWidth = 80;
            radGridView1.Columns[5].HeaderText = "الخصم";
            radGridView1.Columns[5].TextAlignment = ContentAlignment.MiddleCenter;
            radGridView1.Columns[5].FormatString = "{0:G29}";

            radGridView1.Columns[6].MaxWidth = 100;
            radGridView1.Columns[6].HeaderText = "سعر\nالشراء";
            radGridView1.Columns[6].Name = "BuyPice";
            radGridView1.Columns[6].TextAlignment = ContentAlignment.MiddleCenter;
            radGridView1.Columns[6].FormatString = "{0:G29}";

            radGridView1.Columns[7].MaxWidth = 100;
            radGridView1.Columns[7].HeaderText = "اجمالي\nالشراء";
            radGridView1.Columns[7].Name = "TotalBuyPice";
            radGridView1.Columns[7].TextAlignment = ContentAlignment.MiddleCenter;
            radGridView1.Columns[7].FormatString = "{0:G29}";

            radGridView1.Columns[8].MaxWidth = 80;
            radGridView1.Columns[8].MinWidth = 80;
            radGridView1.Columns[8].Name = "Stock";
            radGridView1.Columns[8].HeaderText = "الرصيد";
            radGridView1.Columns[8].TextAlignment = ContentAlignment.MiddleCenter;

            radGridView1.Columns[9].MaxWidth = 100;
            radGridView1.Columns[9].MinWidth = 100;
            radGridView1.Columns[9].Name = "Supplier";
            radGridView1.Columns[9].HeaderText = "افضل\nمورد";
            radGridView1.Columns[9].TextAlignment = ContentAlignment.MiddleCenter;

            GridViewCheckBoxColumn checkbox = new GridViewCheckBoxColumn();
            checkbox.MaxWidth = 30;
            checkbox.HeaderText = "";
            checkbox.DataType = typeof(bool);
            checkbox.Name = "Ordered";
            radGridView1.Columns.Add(checkbox);

            var allpro = from g in db.OutOfStocks
                         where g.ListID == tabid
                         select g;
            foreach (OutOfStock p in allpro)
            {
                foreach (GridViewRowInfo row in radGridView1.Rows)
                {
                    if ((int)row.Cells[1].Value == p.ID)
                    {
                        if (p.Ordered == 'y')
                            row.Cells["Ordered"].Value = true;
                        else
                            row.Cells["Ordered"].Value = false;
                    }
                }
            }

            GridViewSummaryItem total = new GridViewSummaryItem("Name", "الاجمالي", GridAggregateFunction.Avg);
            GridViewSummaryItem price = new GridViewSummaryItem();
            price.Name = "Price";
            price.AggregateExpression = "(Sum(Q*Price))";
            price.FormatString = "{0:G29}";
            // GridViewSummaryItem price = new GridViewSummaryItem("Price", "{0}", GridAggregateFunction.Sum);
            GridViewSummaryItem buypice = new GridViewSummaryItem("TotalBuyPice", "{0:G29}", GridAggregateFunction.Sum);
            GridViewSummaryRowItem summaryRowItem = new GridViewSummaryRowItem(new GridViewSummaryItem[] { total, price, buypice });

            radGridView1.SummaryRowsBottom.Add(summaryRowItem);
            radGridView1.Focus();
        }
        else
        {
            radGridView1.Visible = false;
        }

        if (radGridView1.Rows.Count() > 0)
            radGridView1.ChildRows.Last().IsCurrent = true;
    }

Here is the pic
https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpa1/v/t34.0-12/10893575_742987025776952_423788280_n.jpg?efg=eyJpIjoidCJ9&oh=c69f42a8f47d6529f2b9d89ab2782711&oe=54A71C8A&gda=1420210517_66e1b08ccf9c00fd3dcff31e1854b3cc


text:
Q: How to update an object in React? My React app retrieves a list of Items from a database and stores them in state, like this:
Client.getListOfItems(url)
.then((itemList) => {        // itemList is an array of Items
    setItemList(itemList);   // Declared as [itemList, setItemList] = useState([]);
});

Now I want to modify each Item in itemList by adding in some sub-data.  Each Item has the key 'userID'; I want to loop over each item to get the corresponding userID, and then copy that into the Item object.  Then the saved itemList should contain a list of Items, each of which has the property 'user'.
So far I have:
Client.getListOfItems()
.then((itemList) => {        // itemList is an array of Items

  const newItemList = itemList.forEach((item) => {
    Client.getUser(item.userID)
    .then((user) => {
       let newItem = {...item, users: user};
       return newItem;
    })
  })

  setItemList(newItemList);

});

but newItemList is undefined at the point when I'm trying to call setItemList.  How do I achieve what I need here?

A: You need to map your list into array of promises, and then use Promise.all to wait for all promises to resolve, and then use one  more then to set the state:
Client.getListOfItems()
  .then((itemList) => {
    const newItemListPromises = itemList.map((item) => {
      return Client.getUser(item.userID).then((user) => {
        let newItem = { ...item, users: user };
        return newItem;
      });
    });
    return Promise.all(newItemsListPromises);
  })
  .then((list) => setItemList(list));

Use with caution, since if at least one promise will fail, Promise.all will also fail. Don't forget to catch your errors


text:
Q: Calculate probability given dependent events I'm having some trouble finding out how to calculate the probability of the following problem:

I'm confused as to how I should be calculating the probability of B. I'm not sure how to factor in the possibility of A winning in one state but B winning in another.

A: The answer your instructor or book is looking for is that there is a 50% chance that B wins Kentucky, and if he does not, then there is a 28% chance that he wins Tennessee.  The total probability that B wins at least one is then 50% plus (1 - 50%) times  28%, for a total of 64%.
There are some subtleties for the purist; for example, the conditions given are not unabiguously consistent.  But it is clear you are not meant to overthink the matter.

A: Let $K$ be the event that party A wins in Kentucky.  Let $T$ be the event that party A wins in Tennessee.  The events of B winning in each state is the complementary events $K^c, T^c$
We are given: $\mathsf P(K)=0.50,\, \mathsf P(T)=0.50,\, \mathsf P(T\mid K)=0.72$
We wish to find the probability that party B wins in at least one of the states.  This event is the complement of party A winning in both states.  We can then apply the product rule for the conjunction of conditionally dependent events.
$$\begin{align}\mathsf P(K^c\cup T^c) & = 1-\mathsf P(K\cap T) \\ & = 1 - \mathsf P(K)\cdot\mathsf P(T\mid K)\\ & = 1-0.5\cdot 0.72 \\ & = 0.64\end{align}$$


text:
Q: how to refer another page element using javascript I have a LocationInfo.jsp in which i am calling AddCities.jsp using AJAX
Now the Problem is when i am validating addCities.jsp fields like isEmpty and setting focus on  element if it is empty, javascript function searching the element on locationinfo.jsp and it is not setting focus on desired element.
I am new to javascript so plese help me.
here is my code:
function isEmptyField(obj)
{
if((obj.value==null)||(obj.value.length==0))
    {
    alert("Please Enter Value");
    document.getElementById(obj.id).focus();
    }
}

and textbox within the AddCities.jsp is like this:
<input class="combo" type="text" name="city" id="ctname" onBlur="isEmptyField(this);">

enter code here

A: 2 comments
1. check that your "if" condition returns true?
2. if yes, try this.focus() instead of document.getElementById(obj.id).focus();


text:
Q: Flask-SQLAlchemy Unittest Runs Twice I've set up my project up like this:
- proj/
  - proj.py
  - views.py
  - tests.py
  - models.py
  - settings.py
- setup.py

In proj.py I defined app and db:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

from proj import settings

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE
db = SQLAlchemy(app)

views just contains the hooks for the app. models contains the SQLAlchemy models. The relevant portions of test:
from flask import Flask
from flask_testing import (
        TestCase,
        LiveServerTestCase,
        )

class SqlalchemyUnittest(TestCase):

    SQLALCHEMY_DATABASE_URI = "sqlite://"
    TESTING = True

    def create_app(self):
        proj.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
        proj.app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
        proj.app.config['TESTING'] = True
        proj.app.config['DEBUG'] = True
        proj.app.testing = True
        proj.app.debug = True
        return proj.app

    def setUp(self):
        proj.db.create_all()

    def tearDown(self):
        proj.db.session.remove()
        proj.db.drop_all()

class TestSomething(SqlalchemyUnittest):

    def test_something(self):
        self.assertEqual(1, 1)

And then in the actual execution...
test_something (proj.tests.TestSomething) ... ok
test_something (proj.tests.TestSomething) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.010s

OK

The odd thing is that on some of the tests they pass one one of the runs, but fail on another, though the tests are independent of the environment (e.g. the database state). It almost seems as though there are .pyc files hanging around, but I've deleted all the .pyc files and __pycache__ directories and still get the same result.
Any ideas why? Thanks.
tl;dr Python unit tests run twice, and sometimes give varying results.

A: I think the issue was that old pyc files and pycache directories were hanging around.
Removing them seemed to solve the issue.


text:
Q: Initializing python object using different object types as arguments I'v read how to overload... and multiple constructors in python and a few more on this topic, however I'm looking for something more specific.
I'm given a list of Content objects and a list of Data objects:
class Content:
    def __init__(self):
        self._title = 'movie title'
        self._url = 'http://movie-url'

    @property
    def title(self):
        return self._title

    @property
    def url(self):
        return self._url

class Data:
    def __init__(self):
        self._title = 'movie title'
        self._year = 2021
        self._rating = 7.6

    @property
    def title(self):
        return self._title

    @property
    def year(self):
        return self._year

    @property
    def rating(self):
        return self._rating

I want to match each Content with it's corresponding Data by the title property and combine everything under one class Movie, by passing one of the other objects to Movie's init argument:
movie_content = Movie(Content())
movie_data = Movie(Data())

From what I'v read so far my options are:

*

*Default arguments: Doesn't seem to fit here (correct me if I'm wrong) since I want to pass only one argument anyway.

**args: I prefer to avoid passing a long line of arguments (there will be at least 12).

*@classmethod: This approach is the most appealing to me, but I'm struggling with the implementation:

class Movie:
    def __init__(self, object):
        self.object = object

    @classmethod
    def by_content(cls, content):
        _title = content.title
        _url = content.url

        return cls( # what goes here?)

    @classmethod
    def by_data(cls, data):
        _title = data.title
        _year = data.year
        _rating = data.rating

        return cls( # what goes here?)

*

*Using methods as multi-setters, which I'm currently using (not the most pythonic from my understanding):

class Movie:
    def __init__(self):
        self._title = ''
        self._url = ''
        self._year = 0
        self._rating = 0.0

    def by_content(self, content):
        self._title = content.title
        self._url = content.url

    def by_data(self, data):
        self._title = data.title
        self._year = data.year
        self._rating = data.rating

Any thoughts or suggestions would be greatly appreciated.

A: You can use the classmethods as secondary constructors - where you will use the values from the second parameter in the function to fill out the attributes in your Movie class's constructor.
I have made the example using dataclasses since that makes the code shorter, with the same functionality. (or more)
from dataclasses import dataclass

@dataclass
class Content:
    title: str
    url: str

@dataclass
class Data:
    title: str
    year: str
    rating: float

@dataclass
class Movie:
    title: str
    year: str
    rating: float
    url: str

    @classmethod
    def by_content(cls, content: Content): return cls(
        title = content.title,
        url = content.url,
        rating = 0,
        year = 0,
    )

    @classmethod
    def by_content(cls, data: Data): return cls(
        title = data.title,
        url = 'https://null.com',
        rating = data.rating,
        year = data.year,
    )


text:
Q: Reading and IO port configured as a UART on a PIC16F916 Is it possible to read the input on a PIC (in this case a PIC16F916) when it is configured as UART RX?
RC7 is the RX pin on the PIC16F916, and I would like to be able to read the state of the pin while the UART is receiving data.


text:
Q: psycopg2 connecting to postgresql database - error I have problem to connect to my postgreSQL database.
I have databasename, password, hostname, port and I use this:
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"

But I got error like this:

Is the server running on host "...." and accepting TCP/IP connections on port 5432

I don't know if I used correctly host, I insert the value of hostname.
What is the difference between hostname and host? Anyone could help me?

A: psycopg2.connect(dbname=dbname, user=user, password=password, host=postgres_address, port=postgres_port)

This is working example to connect, you must define early dbname, user, password, postgres_address. If you have connection error, you can use ping for testing connection and telnet for testing openning port. Or you can use Beaver for test connection to postgres server.

A: Most likely your database has a firewall, be sure to whitelist the IP you are trying to connect from.

A: Difference of host and hostname
The difference of host and hostname really depends on the context. In your context of psycopg2 and PostgreSQL connection, the host normally means the IP address of the PostgreSQL server or the resolvable name of the PostgreSQL server such as DNS name if it has. If you are running linux server, the output of command hostname is unlikely to work in your case.
psycopg2 connection
Your connection string looks OK. But I will suggest you to use below connection format:
import psycopg2
try:
    connection = psycopg2.connect(user = "sysadmin",
                                  password = "pynative@#29",
                                  host = "127.0.0.1",
                                  port = "5432",
                                  database = "postgres_db")
except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)

You should use the IP address as the host value.
Troubleshooting
In the case of connection error, you should use other tools to test the connection of PostgreSQL server such as psql, pgAdmin4 or DBeaver.
You can also use telnet or netcat tools to test the network connection of PostgreSQL server, such as
telnet PostgreSQL_ip_address 5432

nc -v PostgreSQL_ip_address 5432


text:
Q: Remove parent and sub directory sample_dir2
`-- sample_dir
    |-- cambridge
    |   `-- security
    |       |-- annex
    |       `-- parking
    |-- history.exe
    |-- markham
    |   |-- annex
    |   |-- building1
    |   `-- parking
    `-- stenton
        |-- admin
        |   `-- accounting
        |       `-- payroll
        |-- gen_ed
        |   `-- Holidays
        `-- lib_arts
            `-- english.txt

Your current directory is stenton. Remove the accounting directory:
You entered: rm -r /admin/accounting
Please try again.
Your current directory is stenton. Remove the accounting directory:
Shouldn't rm -rf /admin/accounting work?

A: Paths that start with / are from the root of the entire filesystem.  Leave off the slash to specify a file relative to the current directory.  You can also say ./admin/accounting to refer to a path relative to ., which is the current directory.


text:
Q: Spring WARNING: Custom isolation level specified but no actual transaction initiated After updating spring libraries in our project from version 4.1.6.RELEASE to the latest 4.3.8.RELEASE, a strange WARNING began to pop up. I couldn't find any explanation online so far.
Nothing else but the spring version has changed in the project.
What exactly does this warning mean and why is it popping up? Do we miss some configuration? Our logs are full of it.
Full log message:
WARN  2017-04-27 07:59:15 : Custom isolation level specified but no actual transaction initiated; isolation level will effectively be ignored: PROPAGATION_NOT_SUPPORTED,ISOLATION_READ_COMMITTED; '' --- o.s.j.d.DataSourceTransactionManager:389 --- [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-93]

If you need some specific parts of our configuration, please ask for it.
We are using mybatis as dat alayer (version 3.2.7, and mybatis-spring version 1.2.2)


text:
Q: Minimal OpenGL example in Java As an Java developer, I recently had idea of learning OpenGL. I fully understand, that Java isn't best language for computer graphics, but as I just want to learn basics and concepts (and not writting Minecraft 2), I think it will do just fine.
I have started by searching in google and github for some "hello worlds" that uses JOGL (Java OpenGL). I was extremly supprised, that well above 85% of those "hello worlds" had about 100-500 lines of code (that I mostly do not understand just yet) and also, nearly none of them used Maven/Gradle dependency, which caused me must trouble with setting libraries (including native) properly (Using Linux, not sure if this is important).
I am really looking for some trivial example, like just add Maven/Gradle dependency, write simple JavaFX window, that displays OpenGL sphere, so I could focus on OpenGL instead of configuring everything.
There were few examples for Android, but I would like to run it on laptop (easier development).
Am I missing something? Where should I look for it?

A:
I fully understand, that Java isn't best language for computer graphics

Well, it depends, each language has its pros and vs.
For example Java allows you to get a running program very quick, but you don't have full control on the memory like c/c++.
It doesn't take time to compile and can be run even when some part of the code are full of errors.
But is getting somehow verbose compared to some newer jvm languages, such as kotlin, scala or groovy.

I have started by searching in google and github for some "hello worlds" that uses JOGL (Java OpenGL). I was extremly supprised, that well above 85% of those "hello worlds" had about 100-500 lines of code

Well, that is because rendering is not as trivial as you thought.
However if you like to have core classes very compact you can eliminate a lot of boilerplate code  by delegating laborious and manual work to util classes and get an hello triangle below a hundred lines.
For example in this hello triangle of mine. you can:

*

*avoid many default calls to glWindow  in the main method

*save all the constant variables in a static class

*avoid initDebug()

*cut down in half initBuffers()

*init your shader programs in one line by movind initProgram() to utils

nearly none of them used Maven/Gradle dependency, which caused me must trouble with setting libraries (including native)

I feel you, I really do.
And exactly because of this, I started two organization on github, one called java-graphic to be API neutral and another one called java-opengl-labs for everything related to jogamp, in order to address some major problems of us java devs and converge all our single effort into a unified place.
I wish also to have available plenty of modern tutorials, tools, libraries and whatever, all of them under Maven/Gradle dependency, one click and I get everything set it up and ready to be used.
When I started learning OpenGL the situation was much worse, I am trying to change it, but it is an huge effort.
There are a lot of things to do:

*

*writing new counterparts tools (major are assimp and bullet)

*improving existing code

*implementing Maven/Gradle

*writing wikis

*improving channels communications

*...

If you (or anyone who is reading) can contribute then please, do not hesitate do that, you are very welcome :)

I am really looking for some trivial example, like just add Maven/Gradle dependency, write simple JavaFX window, that displays OpenGL sphere, so I could focus on OpenGL instead of configuring everything.

The simplest you get, it that hello triangle I linked you. Unfortunately it has no Maven/Gradle dependency yet, but it relies only on pure jogl.

There were few examples for Android, but I would like to run it on laptop (easier development)

Since you are also mentioning Android (and somehow also verbosity previously), let me suggest you to take a look to Kotlin... I recently started digging into it and it is a whole new level compared to java, I also wrote a small hello triangle just as a pure style exercise

A: Try taking a look at the JogAmp wiki, and the demos with available source code.
JogAmp Wiki: http://jogamp.org/wiki/index.php/Main_Page
JogAmp Demos: http://jogamp.org/jogl-demos/www/
I would also suggest reading the OpenGL Redbook, this will introduce a lot of core OpenGL concepts, but is made for Version 1.1 of OpenGL, still a good read, but some practices will be outdated.
Lastly I'd recommend reading The OpenGL Programming Guide - 8th Edition. It's basically like the redbook but for modern OpenGL. Here's a link for it on Amazon
Code from the redbook and the OpenGL programming guide are going to be in pseudo code or C/C++, but the concepts and API calls are all the same between Java and C/C++. The only major differences will be in window creation, but that should be covered in the JogAmp demos and wiki.
EDIT: I just noticed there's a 9th edition of The OpenGL Programming Guide, you may want to read that instead, the 8th edition covers OpenGL 4.3, and the 9th edition covers 4.5.
Unfortunately you won't find any simple or trivial example. Learning OpenGL is a very large undertaking, and it won't happen overnight. Learning to configure your libraries, and the core concepts of the OpenGL API will help you a lot in the long run.


text:
Q: No lazy loading for Resource Dictionaries is there a possibility in WPF / XAML to eager load resource dictionaries? I have a resource dictionary defined in my XAML:
<s:SurfaceWindow.Resources>
    <local:SomeConverter x:Key="SomeConverter"/>
    <local:SomeView x:Key="SomeView" />
</s:SurfaceWindow.Resources>

I need these resources before the loaded event occurs - is there any way to do that?
Thanks

A: If you place you ResourceDictionaries BEFORE you create the control then you should be fine. If you are REALLY eager then put your Resources in the App.xaml file


text:
Q: Something I could not figure out in my exam today How can you use this class to print "foo" but not "foobar"? You cannot edit the class.
class Test

    def foo
        puts "foo"
        foobar
    end

    def foobar
        puts "foobar"
    end

end

Edit: I just came up with a solution where you create a subclass to Test and override foo so that it just prints "foo".

A: You could do the following.
class Test
  def foo
    puts "foo"
    foobar
  end
  def foobar
    puts "foobar"
  end
end

Test.instance_methods(false)
  #=> [:foo, :foobar]
Test.new.foo
  # foo
  # foobar

Create an alias of :foobar
Test.class_eval { alias_method :old_foobar, :foobar }
  #=> Test
Test.instance_methods(false)
  #=> [:foo, :foobar, :old_foobar]
Test.new.old_foobar
  # foobar
Test.new.foobar
  # foobar

Create a stub method :foobar.
Test.class_eval { define_method(:foobar) {} }
  #=> :foobar

Try it.
Test.new.foo
  # foo

Clean-up
Restore the original :foobar.
Test.class_eval { alias_method :foobar, :old_foobar }
  #=> Test
Test.new.foo
  # foo
  # foobar

Remove :old_foobar.
Test.instance_methods(false)
  #=> [:foo, :foobar, :old_foobar]
Test.class_eval { remove_method(:old_foobar) }
  #=> Test
Test.instance_methods(false)
  #=> [:foo, :foobar]

Note
Test.class_eval { alias_method :old_foobar, :foobar }

produces the same alias :old_foobar as does
class Test
  alias_method :old_foobar, :foobar
end

but it does it dynamically.
Alternatively, one can write
Test.send(:alias_method, :old_foobar, :foobar)

but not
Test.alias_method :old_foobar, :foobar

because :alias_method is private.
These comments also apply to the other two uses of class_eval.

A: You cannot edit the class.
test = Test.new
test.foo
# => foo
# => foobar

But you can edit the object instantiated from the Test class
class << test
  def foobar
  end
end
test.foo
# foo

for more information, you can google "singleton methods".


text:
Q: Accessing R from QGIS? I have been unable to run R from within QGIS on my computer. I have R version 3.03 installed and QGIS 2.4 on Windows 7. R is located at C:\Program Files\R\R-3.0.3\bin\and this is the path e specified in Processing Options -> Providers -> R Scripts -> R Folder in QGIS.
The error message I receive is
Missing dependency.This algorithm cannot be run :-(
This algorithm requires R to be run.Unfortunately, it seems that R is not installed
in your system, or it is not correctly configured to be used from QGIS
Click here to know more about how to install and configure R to be used with QGIS

I have tried changing the R folder to other R executables, but nothing works.

A: The issue is that R is installed under Program Files by default, which is write-protected. Install R into another folder such as C:\R\R-3.1.3 and the problem goes away when you set it as the R path in QGIS. The solution is described here: http://wiki.awf.forst.uni-goettingen.de/wiki/index.php/R_installation
This worked running QGIS 2.8.1 Wien on Windows 7 64-bit.


text:
Q: tinymce custom implementation - their docAPI could be better i'm just trying user to be able to insert,
,
 &
 and , how can i do it?
their webiste it's too confusing for me...
anyone can help me?

A: You want to adjust the theme_advanced_buttons settings:
tinyMCE.init({
    //...
    theme_advanced_buttons1: 'bullist,numlist,image',
    theme_advanced_buttons2: '',
    theme_advanced_buttons3: '',
    theme_advanced_buttons4: '',
    //...
});

AFAIK, you always get paragraphs.
Have a look at these examples for more, there are various examples listed in the right sidebar.

A: Here is your answer...
var Editor = tinyMCE.get('YourEditorID');
Editor.focus();
Editor.selection.setContent('Hello World');

Note: focus() may not be needed, depending on situation.


text:
Q: ida начало функции в графе Когда ida преобразует функцию в графы, то в большинстве функции начинаются примерно так:
var_230= byte ptr -230h
var_210= qword ptr -210h
var_1FC= dword ptr -1FCh
var_1D8= byte ptr -1D8h
var_E8= byte ptr -0E8h
var_BC= byte ptr -0BCh
var_98= byte ptr -98h
var_68= byte ptr -68h
var_38= qword ptr -38h
var_28= qword ptr -28h
var_20= qword ptr -20h
var_18= qword ptr -18h
arg_0= qword ptr  10h
arg_8= qword ptr  18h
arg_10= qword ptr  20h
arg_18= dword ptr  28h
arg_20= qword ptr  30h
mov     [rsp-8+arg_18], r9d
mov     [rsp-8+arg_10], r8
mov     [rsp-8+arg_8], rdx
mov     [rsp-8+arg_0], rcx
push    rbp
push    rdi
mov     eax, 1048h
call    j__alloca_probe
sub     rsp, rax
lea     rbp, [rsp+60h]
mov     rdi, rsp
mov     ecx, 412h
mov     eax, 0CCCCCCCCh
rep stosd
mov     rcx, [rsp+1050h+arg_8]
mov     [rbp+0FF0h+var_A8], 0FFFFFFFFFFFFFFFEh
mov     rax, cs:__security_cookie
xor     rax, rbp

кроме того что var_число это локальные переменные, ну и arg это аргументы я понимаю, но как мне понять где из этих аргументов this ? Почему вхождение аргументов идет прям в функции, а не  перед ней? Как понять почему именно в эти регистрах находятся аргументы? И кто нибудь сможет прокомментировать по строчно что здесь происходит?

A: В ассемблере 64 бита, когда вызывется функция, стек выглядит следующим образом:
...
parameter 5      [rsp+40]   (optional)
r9 home          [rsp+32]
r8 home          [rsp+24]
rdx home         [rsp+16]
rcx home         [rsp+8]
return address   [rsp]

Код:
mov     [rsp-8+arg_18], r9d
mov     [rsp-8+arg_10], r8
mov     [rsp-8+arg_8], rdx
mov     [rsp-8+arg_0], rcx

сохраняет первые 4 параметра функции (rcx, rdx, r8, r9) в home area. Это освобождает регистры для текущего пользования, параметры могут быть считаны из home area.
Почему в коде используется [rsp-8+...], в данном контексте непонятно. Но адреса получаются правильные. Возможно, дальше в функции устанавливается rbp = rsp - 8 (rsp на момент вызова), и все адреса пишутся относительно rbp.
Если это не статический метод класса, то this в регистре rcx.


text:
Q: Loading multiple View controller in UIPageViewController - Swiping shows blank screen I am loading multiple UIViewControllers in UIPageViewController with each UIViewController having their own navigation bar. I have implemented all the required data source and delegate methods for UIPageViewController and it showing up correctly.
But when I scroll my view controller horizontally, more often, I see a white blank screen instead of my view controller. Below is my code.
Any clue what could be wrong here.
PS: I tried by removing the IF condition in my viewControllerForRequestID method and returning a new controller every time. This works but then I end up with one view controller showing up twice in pagination.
- (UIViewController *)pageViewController:(UIPageViewController *)iPageViewController viewControllerBeforeViewController:(UIViewController *)iViewController {
    [self.pageControl setCurrentPage:self.selectedRequestIndex];

    if (self.selectedRequestIndex == 0) {
        return nil;
    }

    NSUInteger aNewSelectedRequestIndex = self.selectedRequestIndex - 1;
    NSString *aPreviousRequestID = [self.paginationRequestIDList[aNewSelectedRequestIndex] stringValue];

    self.selectedRequestIndex = aNewSelectedRequestIndex;
    self.selectedRequestID = aPreviousRequestID;

    return [self viewControllerForRequestID:self.selectedRequestID];
}

- (UIViewController *)pageViewController:(UIPageViewController *)iPageViewController viewControllerAfterViewController:(UIViewController *)iViewController {
    [self.pageControl setCurrentPage:self.selectedRequestIndex];

    if (self.selectedRequestIndex == NSNotFound || self.selectedRequestIndex >= self.paginationRequestIDList.count - 1) {
        return nil;
    }

    NSUInteger aNewSelectedRequestIndex = self.selectedRequestIndex + 1;
    NSString *aNextRequestID = self.paginationRequestIDList[aNewSelectedRequestIndex];

    self.selectedRequestIndex = aNewSelectedRequestIndex;
    self.selectedRequestID = aNextRequestID;

    return [self viewControllerForRequestID:self.selectedRequestID];
}

- (MyNavigationViewController *)viewControllerForRequestID:(id)iRequestID {
    NSString *aRequestID = iRequestID;

    // Safe check to avoid numbers in request ID
    if (![iRequestID isKindOfClass:[NSString class]]) {
        aRequestID = [iRequestID stringValue];
    }

    @synchronized (self) {
        if ([self.viewControllers containsObjectForKey:iRequestID]) {
            MyNavigationViewController *aNavigationController = self.viewControllers[iRequestID];
            return aNavigationController;
        }

        MyDataModel *aRequestData = self.savedRequestData[iRequestID];
        MyDataModelController *aRequestInfoController = [[MyDataModelController alloc] initWithRequestData:aRequestData];
        aRequestInfoController.delegate = self;
        MyNavigationViewController *aNavigationController = [[MyNavigationViewController alloc] initWithRootViewController:aRequestInfoController];

        [self.viewControllers setObject:aNavigationController forKey:iRequestID];

        return aNavigationController;
    }
}


text:
Q: Changing the background color of a table cell in matlab using html content we know that uitable supports html content
for an example similar to what I want see here
to solve the problem I asked before I used this code in the callback of a button in matlab:
color = uisetcolor;
numberOfClasses = str2num(get(handles.edtNumClass,'String'));
if handles.index == 0
    handles.tableData = cell(numberOfClasses,2);
    guidata(hObject,handles);
end
handles.index = handles.index+1;
handles.tableData(handles.index,1)=cellstr(get(handles.edtNameClass,'String'));
handles.tableData(handles.index,2)=cellstr('');
set(handles.uitable2,'data',handles.tableData);

my problem is this line doesn't work:
handles.tableData(handles.index,2)=cellstr('');

I mean when I open the workspace in matlab I see that handles.tableData(handles.indexes,2) is set to the string.
but the background color does not change
even this html code is not shown as a simple string.
no change happens for the cell!!!
and matlab gives no error message!!!
Note that I even used this code but there was no change.
handles.tableData(handles.index,2)=cellstr('');

A: @Floris is correct, the string is not "evaluated" as MATLAB code, you need to explicitly write the colors. Here is a small example:
%# data
X = {
    'Alice'   1
    'Bob'     2
    'Charlie' 3
    'Dave'    4
};

%# get color from user
c = uisetcolor();

%# format color as: rgb(255,255,255)
%#clr = sprintf('rgb(%d,%d,%d)', round(c*255));

%# format color as: #FFFFFF
clr = dec2hex(round(c*255),2)'; clr = ['#';clr(:)]';

%# apply formatting to third row first column
X(3,1) = strcat(...
    [''], ...
    X(3,1));

%# display table
f = figure('Position',[100 100 350 150]);
h = uitable('Parent',f, 'ColumnWidth',{100 'auto'}, ...
    'Units','normalized', 'Position',[0.05 0.05 0.9 0.9], ...
    'Data',X, 'ColumnName',{'Name','Rank'}, 'RowName',[]);

Note: I tried a few variations of the HTML code. The issue was that the background color was only applied to the text but did not fill the entire table cell:

The last one worked, but its not better than the previous code I showed. I tried other CSS tricks to fill the entire cell space, but failed. I think that the subset of HTML/CSS supported in Java Swing components is limited.

The above HTML approach works fine for small tables. For larger tables or when you want to enable editing, there is a better approach. It requires Java Swing familiarity.

A: Comparing your code (I added line breaks for readability - consider these "on one line"):
handles.tableData(handles.index,2)=  ...
  cellstr('

           ');

With the code from your link
XX(idx,1) = strcat(...
  '', ...
  XX(idx,1), ...
  '');

There is a Very Important Difference. In the original code, the color is defined as a hex number (which can be interpreted when the HTML is rendered). In your code, the color variable is known to Matlab - but it is treated as a string when you create the tableData. And the HTML interpreter doesn't know what to do when it comes across color(1,1) so it silently ignores the whole command. To fix this, you need to make sure that the string you end up with "makes sense" - i.e. convert color to a string. Note - when I looked at the output of uisetcolor it appeared that the value returned was between 0 and 1, not between 0 and 255; so you want to multiply the color value by 255 first:
c255 = color(1,1:3)*255;
colorString = sprintf('rgb(%d,%d,%d)', c255);

At this point, colorString is rgb(173,235,255) (for example).
Now you can create your entire formatstring as
formatString = [''];

And you can set it:
handles.tableData(handles.index,2) = cellstr(formatString);


text:
Q: Passing a struct into a generic function in C I declare a new struct with the name of "Struct"
I have a generic function that takes in an argument "void *data".
void Foo(void *data)

I pass an instance of "Struct" into the generic function.
Struct s;
Foo(&s);

I want to access one of the properties of the struct in the function.
void Foo(void *data) {
    char *word = (char*) data.word;
}

It's not allowed because it doesn't recognize data as a valid struct.
I even try to declare the data as the struct type first, and I get an error.
void Foo(void *data) {
    Struct s = (Struct) data;
    char *word = s.word;
}

I get "conversion to non-scalar type requested".

A: First of all, you should turn on your compiler's warning flags (all of them). Then you should pass a pointer to your Struct and use something other than struct as a variable name:
Struct s;
Foo(&s);

Then, in Foo:
void Foo(void *data) {
    Struct *s    = data;
    char   *word = s->word;
}

You can't convert non-pointer types to and from void* like you're trying to, converting pointer types to and from void* is, on the other hand, valid.

A: You need to pass a pointer to you struct and get a pointer to the struct inside the function:
Struct struct;
Foo(&struct);

void Foo(void *data) {
    Struct* struct = (Struct*) data;
    char *word = struct->word;
}

A: You have to use -> operator when requesting structure member via pointer.
This should work: char *word = (char*) data->word;
You also have to pass the address of the structure to the function. Like this: Foo(&struct);.

A: Firstly you need to call the function correctly:
Struct s;
Foo(&s);

Notice you're now passing a pointer to the structure.
Now, the function has to know that you're using a Struct (as opposed to something else) - perhaps because of another parameter, or a global variable, or some other reason. Then inside the function you can do:
void Foo(void *data) {
    Struct *structpointer = p; /* Note - no need for a cast here */

    /* (determine whether data does refer to a pointer then...) */
    char *word = structpointer->word;
    /* ... then use 'word'... */
}

A: Data is pointer, so whatever you cast it to must also be a pointer. If you said Struct* myStruct = (Struct*) data, all would be well with the world.

A: You are mixing pointers and data.
Struct struct defines a data object
void *data expects data to be a pointer.
Call Foo with a pointer to a Struct, and make other necessary changes

A: Struct struct;
Foo((void*)&struct);

void Foo(void *data) {
    Struct *struct = (Struct*)data;
    char *word = struct->word;
}

or the more compact form:
Struct struct;
Foo((void*)&struct);

void Foo(void *data) {
    char *word = ((Struct*)data)->word;
}


text:
Q: Emberjs project and Visual Studio / Visual Studio Code I'm trying to develop my Ember.js application (created with ember-cli) using Visual Studio however each time, after a few seconds IDE crashes. The same happens with Visual Studio Code. Does anybody know how to solve this problem?

A: This because ember has long folder names but in windows it has limit. Therefore most of the times visual studio will crash. Currently we are using inteliJ on linux. Intelij will never crash because linux doesn't have limitation for the folder name


text:
Q: Unable to Force Resolve in Unity 2022.1.0b2 with Firebase sdk version 10.3 I am getting this error when I do force resolve for android:
stderr:
FAILURE: Build failed with an exception.

*

*What went wrong:
Could not create an instance of type org.gradle.initialization.DefaultSettings_Decorated.

Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 1s
(I am on Macbook Air 2017)


text:
Q: Can't login to new Sandbox accounts I've just created a new Paypal developer account and associated a new sandbox buyer account to it. A facilitator account was automatically created.
However, I cannot login to the sandbox using the sandbox buyer's credentials. I've tried changing the password and clearing my cookies and cache but still not luck.
The credentials for the facilitator account also do not work in the sandbox.
Can anyone help?

A: If you've used the "old" version of sandbox you'll need to clear your cache and cookies before being able to log in.
If you do not, you'll be receiving the error message below.
"This Sandbox email address is not available. Please enter another email address."
If you continue receiving a password error, trying resetting the password to the accounts by following the steps below:
Log into https://developer.paypal.com
Click Applications
Click Sandbox accounts
Expand the account in question
Click "Profile"
Click "Change Password"


text:
Q: Firestore Security Rules - Nested Collection i am trying to create security rules for my firestore instance. here is the data structure and requirements of the collections.
User Collection
/users/{userId}
{
 id:userId
 isAdmin:bool
},

News Collection
/news/{docId}
{
 id:docId,
 userId:uid,
 viewCount:number,
 commentsCount:number,
 upVotes: number,
 comments: collection
}

Comments Collection
/news/comments/{commentId}
    {
     id:commentId,
     userId:uid,
    }

Requirements for news Collection:
Only Users with isAdmin flag set to true can create,update and delete this document except for the viewCount and commentsCount which can be updated if any of the following conditions meet.

*

*any user authenticated or un authenticated view the document

*if only authenticated user posted a comment

Requirement for /news/{docId}/comments Collection:
All Users authenticated or un authenticated can view the comments
Only Authenticated users can create comments.
Only User with uid == userId can delete or update the document
my effort so far.
  match /news/{docId}{
    allow read;
    //we need to improve the below statement
    allow write: if Authenticated() && request.auth.uid == 'adminUserId';
    match /comments/{commentId}{
        allow read;
        allow create: if Authenticated() && request.auth.uid == request.resource.data.userId;
        allow update,delete: if Authenticated() && request.auth.uid == resource.data.userId;
    }
  }


text:
Q: Regular Expressions - Match Character Not Between Two Strings I've read many questions that ask about finding a regular expression to match characters between two strings, but my problem is the inverse.  I'm attempting to create an expression that will match characters NOT between two strings.
Consider the following string.
This is short & [tag]fun & interesting[/tag].

I want to replace any ampersand character that is NOT inside the tag elements with the symbol @.  The result should be as shown below.
This is short @ [tag]fun & interesting[/tag].

I tried the following regular expression, but unfortunately, it matches the ampersand inside the tag elements.
/(?<!\[tag\])&(?!\[\/tag\])/g

I understand that it matches that ampersand because it's surrounded by characters on either side in the string.  But I can't add a random number of characters to check because the lookbehind and lookahead must be fixed length.
Is there a regular expression that will accomplish what I want here?

A: This does the job even with nested tag:

*

*Find: \[(\w+)\].+?\[/\1\](*SKIP)(*FAIL)|&

*Replace: @
Demo & explanation
How it works:

*

*\[(\w+)\].+?\[/\1\] is trying to match opening and closing tag with some data inside

*(*SKIP)(*FAIL) if tag is found, then discard it

*| else

*& match an ampersand. At this point, we are sure it is not inside a tag.

Unfortunately this doesn't work with Java, but this requirement was only added after I answered.


text:
Q: Multiple hash assignments in perl - translated to python? Why equal 1 always? If I had the line in perl
$cds_score{$score}{$id} = 1;

where cds score is a hash, would the best python equivalent be
cds_score = {}
cds_score[score] = id

And in a more general sense, I am confused why I often see the =1 at the end of hashes in perl. In python, it seems more sense to make these list appending instead of a dict like in the case of {NC} -> {$id} =1 where in python I would write NC.append(id). Is the idea just that in perl storing long lists as a hash is better than as an array, if you are trying to look up arbitrary members?

A: A dict/hash where all of the values are 1 (or some other truthy constant) is a standard way to simulate sets in a language that doesn't have them, like perl. (Of course this being perl, it's only one of many standard ways to do it.)
Python does have sets, so you can just use them. For example:
cds_score[score].add(id)

However, Python doesn't have automatic multilevel/recursive dicts, so if you want that, you need to do it explicitly with defaultdict or dict.setdefault:
cds_score.setdefault(score, set()).add(id)

This structure—a dict of sets (or a hash of hashes whose values are always 1)—is sometimes known as a "multidict", because it's a value of representing a dictionary mapping a single key to 0 or more values, instead of to 0 or 1 value. Both languages have third-party modules that implement multidicts more directly, but neither language really needs them, because it's so simple to do on your own.

What you're doing here:
cds_score[score] = id

… is not an equivalent to the perl code; you're storing just the last id for each score, instead of storing all of them.

Finally:

In python, it seems more sense to make these list appending instead of a dict

No. A list is a way to simulate a set, but it has some significant tradeoffs. In particular, lists allow duplicate entries, and take O(N) instead of O(1) time to search. Those tradeoffs are nearly identical in perl and in python, so if it's not appropriate in perl, it's not appropriate in python either.
If you're just keeping a few values and will never have duplicates, go ahead and use a list, in either language. If you're potentially going to have large sets, or may have the same values showing up many times, you need a real set, in either language (which, in perl, you have to fake with a hash).

A:
Is the idea just that in perl storing long lists as a hash is better than as an array, if you are trying to look up arbitrary members?

Yes, that's exactly it. Searching an array by value is O(N). Searching an hash by key is O(1).
The code for searching is also much more concise when using a HoH instead of an HoA. Where as you can use the following with an HoH:
if ($h{$k1}{$k2})

An HoA would require the following:
if (grep $_ eq $key2, @{ $h{$k1} })

Why equal 1 always?

Personally, I use
++$h{$k1}{$k2};

But many people actually use the following to conserve memory: (16 bytes per entry on a 32-bit build)
undef $h{$k1}{$k2};

The check becomes
if (exists($h{$k1}{$k2}))


text:
Q: How to make my switch button center it self I am not sure whether its possible to do this, but look at this switch button:
Switch button location
So what I am trying to do is to move it at the exact center, where it should be on the red square location: Center location
Just to let you know that I have tried:
android:gravity="center" // didn't work
android:layout_gravity="center"// didn't work
android:foregroundGravity="center"// didn't work

this is my full xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="25">

        </android.support.constraint.ConstraintLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="50"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.37">

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="30"
                app:srcCompat="@drawable/ubersign" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="10"
                android:gravity="center"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="40"
                    android:text="Driver"
                    android:textAlignment="center" />

                <Switch
                    android:id="@+id/switch3"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="20"
                    android:onClick="switchOnOf" />

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="40"
                    android:text="Rider"
                    android:textAlignment="center" />
            </LinearLayout>

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="0"
                android:text="Get Started" />

        </LinearLayout>

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="25">

        </android.support.constraint.ConstraintLayout>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

So is there any possible way to do what I want?

A: Replace LinearLayout with RelativeLayout.
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_toLeftOf="@+id/switch3"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="Driver"
        android:textAlignment="center" />

    <Switch
        android:id="@+id/switch3"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:onClick="switchOnOf" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/switch3"
        android:text="Rider"
        android:textAlignment="center" />
</RelativeLayout>

A: Or you can keep the LinearLayour and do the following:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="10"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:text="Driver"
        android:textAlignment="center" />

    <Switch
        android:id="@+id/switch3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="switchOnOf" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="50"
        android:text="Rider"
        android:textAlignment="center" />
</LinearLayout>

A: Just change the value of android:layout_weight="20" to android:layout_weight="10"
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="10"
    android:gravity="center"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="40"
        android:text="Driver"
        android:textAlignment="center" />

    <Switch
        android:id="@+id/switch3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="10"
        android:onClick="switchOnOf" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="40"
        android:text="Rider"
        android:textAlignment="center" />
</LinearLayout>


text:
Q: How do i prove this? ( about permutation) Let $n>1$.
Let $\tau \in S_{n+1}$ and $1≦l≦n+1$.
Assume that $\tau(l)=l$.
Now, define a permutation $\mu\in S_n$ as $\mu(i)=\tau(i)$ if $i<l$ and $\mu(i)=\tau(i+1)$ if $l≦i≦n$. (If $l=n+1$, then define $\mu$ as the restricton of $\tau$ on $\{1,...,n\}$.)
How do I show that $sgn(\mu)=sgn(\tau)$?
===
Below is what I have proved, so you can use these if you need:

$sgn(\tau\sigma)=sgn(\tau)sgn(\sigma)$
$sgn(\tau)=\prod_{1≦i<j≦n}\frac{\tau(j)-\tau(i)}{j-i}$

A: There are a few equivalent definitions of the signature of a permutation. One of them is $$sgn(\tau)=(-1)^k,$$where $\tau$ can be represented as the product of $k$ transpositions. In the above case, given a representation of $\tau$ as a product of transpositions, $$\tau=t_1\cdot\ldots\cdot t_k,$$we may assume that each one of these transpositions fixes $l$, and so it is easy to adjust these transpositions and represent $\mu$ as $$\mu=t'_1\cdot\ldots\cdot t'_k,$$thus both permutations have the same signature.
As a matter of fact, this is only a consequence of a more general claim. Set$$P_l:=\{\sigma\in S_{n+1}|\sigma(l)=l\},$$ then $P_l$ is obviously a subgroup, and the map $\tau\mapsto\mu$ which is described in the question is an isomorphism of $P_l$ onto $S_n$.


text:
Q: waitForNavigation hanging, even though page was loaded I'm trying to automatically login to a website using puppeteer, with the following script:
const puppeteer = require('puppeteer');
async function logIn(userName, password) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://foo.com'); //anonymized host
    await page.type('[name="Email"]', userName);
    await page.type('[name="Pass"]', password);
    page.click('[type=submit]');
    await page.waitForNavigation({waitUntil: 'load'});
}

logIn('user@domain.com')

The awaitfor waitForNavigation eventually times out at 30 seconds. Launching puppeteer with {headless: false} on the same script, I can check in chromium's devtools that document.readyState evals to "complete" way before the timeout thresold interval. Am I doing something wrong?

A: Adding to the answer of Everettss, I would like to present a more modern code. Basically instead of doing any operation and calling waitFornavigation, the motive is to do the other way around. Something like this:
//Get the promise which isn't resolved yet
const navigationPromise = page.waitForNavigation();

//Perform the activity (Click, Goto etc). Note that the link is any valid url
await page.goto(link);

//wait until the navigationPromise resolves
await navigationPromise;

This helps to avoid race condition as per this discussion
This code makes use of async/await which is much more readable than promise-based code

A: According to Puppeteer documentation proper pattern for clicking on submit and waiting for navigation is like this:
await Promise.all([
  page.waitForNavigation({ waitUntil: 'load' }),
  page.click('[type=submit]'),
]);


text:
Q: What does the Alignment clause in Ada do? I'm not clear what the Alignment clause in Ada does.  See an example below.  I have a 40 bit sized record, and I'm not sure what happens when I use the clause.
    type Knots_Status_Record is
      record
        Value  : Knots;
        Status : Statuses;
      end record;

    for Knots_Status_Record use
      record
        Value  at 0 range  0 .. 31; -- 32
        Status at 0 range 32 .. 39; -- 8
      end record;

    for Knots_Status_Record'Alignment use 1;

A: Attribute Alignment
Alignment of x ensure the address is divisible by x
Data'Aligment = x  <=>  Data'Address mod x = 0
Implication

*

*Some processors requires data address to be aligned to a specific alignment.

*Some processors accesses data faster if the data address is aligned
to a specific alignment.

Example address behavior
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with System.Storage_Elements; use System.Storage_Elements;
with Ada.Assertions; use Ada.Assertions;
with Ada.Command_Line; use Ada.Command_Line;

procedure Main is

   function Get_Argument_1 return Natural is
   begin
      return Natural'Value (Argument (1));
   exception
      when others => raise Program_Error with "Missing natural argument(1)";
   end;

   -- Change this size to see what happens for every address aligment under 64.
   Float_Array_Size : Natural := Get_Argument_1;
   type Float_Array is array (Integer range 1 .. Float_Array_Size) of Float;

   F4 : Float_Array;
   for F4'Alignment use 4;
   F8 : Float_Array;
   for F8'Alignment use 8;
   F16 : Float_Array;
   for F16'Alignment use 16;
   F32 : Float_Array;
   for F32'Alignment use 32;
   F64 : Float_Array;
   for F64'Alignment use 64;

begin

   -- Check if a 4 aligned address could be a 64 aligned.
   Put (Integer(To_Integer(F4'Address) mod 64));
   -- Sometimes it is, sometimes not, depends partly of Float_Array_Size.
   New_Line;
   Put (Integer(To_Integer(F8'Address) mod 64));
   New_Line;
   Put (Integer(To_Integer(F16'Address) mod 64));
   New_Line;
   Put (Integer(To_Integer(F32'Address) mod 64));
   New_Line;
   Put (Integer(To_Integer(F64'Address) mod 64));

   -- Lets see if the address is aligned to 64 storage units.
   Assert (Integer(To_Integer(F64'Address) mod 64) = 0);

end;

External resources
http://www.adaic.org/resources/add_content/standards/05rm/html/RM-13-3.html
http://www.adaic.org/resources/add_content/standards/05rm/html/RM-K.html

The value of this attribute is of type universal_integer, and nonnegative; zero means that the object is not necessarily aligned on a storage element boundary. If X'Alignment is not zero, then X is aligned on a storage unit boundary and X'Address is an integral multiple of X'Alignment (that is, the Address modulo the Alignment is zero).

https://docs.adacore.com/gnat_rm-docs/html/gnat_rm/gnat_rm/representation_clauses_and_pragmas.html
https://gcc.gnu.org/onlinedocs/gnat_rm/Alignment-Clauses.html

GNAT requires that all alignment clauses specify a power of 2, and all default alignments are always a power of 2. The default alignment values are as follows:

https://en.wikibooks.org/wiki/Ada_Programming/Attributes/'Alignment

X'Alignment is an Ada attribute where X is any memory-allocated object or type. This attribute controls the address values used for objects. The alignment must be non-negative. A value of zero means that the object need not be allocated at the boundary of a storage units. Otherwise the address is a multiple of X's alignment.
  The alignment of an object may be set.


text:
Q: Material UI grid items overflow their grid container on Safari I ran into a problem on Safari browser where my Material UI Grid container does not hold its Grid item elements within it's boundaries. This seems to be a problem only for Safari browsers.

And here is my code for the page.
<Grid
      item
      container
      direction="column"
      justify="space-between"
      className={classes.questionContainer}
    >
      <Grid item>
        <Typography component="h1" variant="h1">
          {question.text}
        </Typography>
      </Grid>

      <Grid
        item
        container
        xs={12}
        justify="flex-start"
        className={classes.btnBlock}
      >
        <Grid item xs={3} className={classes.btnContainer}>
          <Button
            variant="outlined"
            color="primary"
            className={classes.btn}
          >
            {customButtonTitle1 || 'Yes'}
          </Button>
        </Grid>
        <Grid item xs={3} className={classes.btnContainer}>
          <Button
            variant="outlined"
            color="primary"
            className={classes.btn}
          >
            {customButtonTitle2 || 'No'}
          </Button>
        </Grid>
          <Grid item xs={3} className={classes.btnContainer}>
            <Button
              variant="outlined"
              color="primary"
              className={classes.btn}
            >
              {customButtonTitle3}
            </Button>
          </Grid>
      </Grid>
    </Grid>

const useStyles = makeStyles((theme: Theme) => ({
  questionContainer: {
    padding: theme.spacing(6, 6),
    minHeight: '340px',
  },

  btnBlock: {
    flexBasis: 0,
  },
  btnContainer: {
    marginRight: '12px',
  },
  btn: {
    fontSize: '16px',
    lineHeight: '24px',
    color: theme.palette.text.secondary,
    padding: '10px 0',
    width: '100%',
    margin: '0 12px',
  },
}))

Why is this happening and how can I fix that for Safari and not break for other browser?
Unfortunately, I do not have access to a Mac OS to test it myself properly

A: Can you try remove "item" in your Grid container?
<Grid
      container
      direction="column"
      justify="space-between"
      className={classes.questionContainer}
    >


text:
Q: Set  volume to 0 and hide it using CSS I want to know if it is possible to "block" a Flash embed, namely Hypster Audio Player, using CSS. This is its code:
<embed quality="high" style="width:56px;visibility:visible;height:13px;" type="application/x-shockwave-flash" height="56" width="13" pluginspage="http://www.macromedia.com/go/getflashplayer" border="0" src="http://www.hypster.com/flash/player.swf?id=3738427:6841383:0&autoplay=true" FlashVars="color_bg=0xffffff&color_border=0x9A0000&color_box=transparent&color_songbg=0xffffff&color_song_clicked=0xffffff&color_Title=0x000000&color_btns=0x000000&color_title=0x000000" />

I have tried everything, the latest of which is:
[src*="hypster"] {
    visibility: invisible!important;
    volume: 0!important;
    box-shadow: 4px 4px aqua;
}

which succeeded to select the embed (I had added the box-shadow attribute to test that) but did jack squat to disable it.

A: simply do this:
[src*="hypster"] {
 display:none;
}

A: One simple line, give it a class and do this:
.yourclass {
    display:none;
}