text:
Q: How can I get the nearest date with given day using date-fns? In my database I have stored a day like "sun", now I am trying to get the nearest day of the week using that day, I got it to work with moment
getActualDate() {
  const days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
  const date = moment.utc().startOf('day')
  const expectedDay = days.indexOf(this.day) // "sun"

  date.days(expectedDay)

  // If later than given day of the week, move to next week
  if (date.days() < moment().days()) {
    date.add(7, 'days')
  }

  return date.toDate()
}

How can I achieve this with date-fns?

A: I fixed this using isSameDay, addDays, startOfWeek and nextDay
const getFirstDateFromDay = () => {
  const dayIndex = days.indexOf(day) as Day

  return isSameDay(date, addDays(startOfWeek(date), dayIndex))
    ? date
    : nextDay(date, dayIndex)
}

A: You can also use POJS. The input value should be tested and perhaps should accept a day number as well.

/* Return next instance of day >= today
 * @param {string} day : 3 letter lower case abbreviation of day name
 * @returns {Date} next instance of day that is >= today
 */
function getDay(day) {
  let days = {sun:0, mon:1, tue:2, wed:3, thu:4, fri:5, sat:6};
  let idx = days[day.toLowerCase().substr(0,3)];
  let today = new Date();
  // Zero time and copy today
  let then = new Date(today.setHours(0,0,0,0));
  // Set then to day in current week
  then.setDate(then.getDate() - then.getDay() + idx);
  // If then is before today, add 7 days. Otherwise, return then
  return then < today ? new Date(then.setDate(then.getDate() + 7)) : then;
}

['sun','mon','tue','wed','thu','fri','sat'].forEach(day =>
  console.log(getDay(day).toString())
);


text:
Q: eclipse disable completion of xml comment Is there a way to disable Eclipse auto-inserting --> after I type <!-- (opening of XML comment)?
I have tried removing a template for "comment" (<!-- ${cursor} -->) in Preferences->XML->XML Files->Editor->Templates, but nothing happens.

A: Go to Preferences -> XML ->XML Files -> Editor -> Typing
Uncheck Comments checkbox in Automatically close section. Click Apply. Should work

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ int wrapper class with different values for comparison not working Why do the following usage give me an error: Undefined referrence to "Environment::self"
So below is my test case and the class is just below it, header and cpp:
Test:
Environment bla;
bla=Environment::CTE;
if(bla==1){
    printf("CTE!");
}else if(bla==Environment::PPE){
    printf("NO: its ppe");
}

Header:
class Environment{
public:
enum{CTE, PTE, PPE, LOCALHOST};
static int self;
bool operator==(const int& rhs)const;
Environment& operator=(const int &rhs);
};

And CPP:
#include "Environment.h"

bool Environment::operator==(const int& rhs)const{
if (this->self ==rhs)
    return true;
return false;
}

Environment& Environment::operator=(const int &rhs) {
  if (this->self != rhs) {
  this->self=rhs;
}

  return *this;
}

A: You've declared self as static. This means:

*

*You must define it somewhere. That is, put int Environment::self; into exactly one .cpp file. This fill fix your "Unresolver reference" linker error.

*Being static means there's just one instance of self for the entire class.  Therefore, accessing it through this->self is not necessary, and is actually confusing. It seems to imply each instance of class Environment has its own copy, but that is in fact not true.
If you want each instance of Enviornment to have its own value of self, simply drop the static keyword from self's declaration.


text:
Q: Laravel Eloquent - Multiple NOT LIKE queries? I have a changeable output from the database like this:
1,2,3,4 and sometimes 5,4,9
I want to add a not like where clause depending on the user:
For example:
User 1
$products = \App\Product::where('user', '1')
    ->where(['category', 'not like', '1,2,3,4')
    ->get();

User 2
$products = \App\Product::where('user', '2')
    ->where(['category', 'not like', '5,4,9')
    ->get();

A: https://laravel.com/docs/5.8/queries#where-clauses
$products = \App\Product::where('user','2')
  ->whereNotIn('category', [5, 4, 9])
  ->get();

A: If all you need is to change the category them why not make it a variable like this.
$categories = $userId == 1 ? [1,2,3,4] : [5,4,9];

$products = \App\Product::where('user',$userId)
  ->whereNotIn('category', $categories)
  ->get();

So my guess is that you need to have some method to see which categories a user should have that would be more complex than this, but well I hope you get the idea.

A: Another way
 $user_id = $request->input('id');//Put your user id in variable either by request or anyway you want to save
 $category_arr = [];

 if($user_id == 1) {
   $category_arr = [1,2,3,4];
 } elseif ($user_id == 2) {
   $category_arr = [5,4,9];
 } else {
   echo "Error Msg"
 }

$products = \App\Product::where('user',user_id)
   ->whereNotIn('category', $category_arr)
   ->get();

A: This is an answer that extend the Roman Bobrik's an Eli's.
The goal is to let your request to be able to handle a default condition while handling specific request when you need to.
if ($request->input('id') == 1) {$categories = [1,2,3,4];}
if ($request->input('id') == 2) {$categories = [5,4,9];}

$products = \App\Product::where('user', $request->input('id'))
    ->when(isset($categories), function($query) use($categories) { // This will be applied for specified users. In this case, users id = 1 || 2
        return $query->whereNotIn('category', $categories);
    })->when(!isset($categories), function($query) { // This will be applied when users id != 1 || 2
        return $query->whereNotIn('category', [1,2]); //Define your default categories for every users that are not specified at the begining.
    })->get();

You could also save the categories array to the users table and change the when() condition for when(Auth::user()->categories != null) and when(Auth::user()->categories == null).
The only warning is, when you use that kind of query, you must have two when() condition that are the exact opposite. Because if none of the both condition are respected, the final query will be $products = \App\Product::where('user', $request->input('id'))->get(); and I'm sure that you won't that to happen.
Well, you can chain more than two when() condition, but be sure to have one that will catch everything that was not catch by any other.

A: If your changeable output is an array, you can try this:
$categories = [1, 2, 3, 4];

$products = \App\Product::where('user', 1)
   ->whereNotIn('category', $categories)
   ->get();


text:
Q: Multiple Springboot app refer to single git yaml I need to create few springboot applications which have a common piece of functionality which is refer through a yml file over git (using Config server). I can have all applications to have the same property and use it accordingly but its a repetition of same property over multiple ymls. Is there a way where we can refer to a common yml file on git through multiple applications ?
I could not find a solution by myself.


text:
Q: IIS - Access denied to directories and files on the novell network I'm trying, through the action of a button on my website, to open a file that is on my company's network. Running the application only through visual studio, the file opens without problems. But when I register it in IIS, this problem happens. Through IIS I can't access the file, this message appears, as shown below:
Open file print
System.ComponentModel.Win32Exception: 'The specified network password is not correct'
For the network drives to be visible to me on my computer, every time I turn on the computer, I must enter the network username and password novel: Client for Open Enterprise Server 2 SP4 (IR7a). After login, the network drives appear. In one of these units is where I want to access a file through my website.
I believe the problem is in the configuration of IIS.
I configured authentication in IIS to be anonymous. I don't know how to configure it differently.
Would anyone know how to solve this problem?
Thank you very much in advance.

An addendum:
These are the mapped drives. I want to access the file of one of them through IIS:
Mapped drives
Addendum 2:
I found that I can't access local documents through IIS either. I can see the error through debug, with VS configuration in IIS Local. If I configure in visual studio for it to run the application in IIS Local, the document access problem occurs. I can't open the files through the button on my website.
As shown in the picture in the link: IIS configuration
When I open IIS, and I click on the page link, as shown:
Internet Information Service Manager - IIS, access problem occurs.
If I'm running Visual Studio with IIS Local configured, I can debug and see the problem.
If I run Visual Studio in IIS Express, I can access and open the files through the click of the button on my website, normally.
I just don't want to have to do this every time I need to run my site.
I want my site to work without needing to run visual studio.


text:
Q: OpenText Content Server SmartView customization We have a requirement to customize the add document screen. We need to disable the '+' sign on the screen which is used to add categories or classifications. Please let me know if it is possible. Also is it possible to create the "Add Categories" to the screen as one of the field.
Metadata properties View might be the clue


text:
Q: How to use Dropbox Chooser without forcing the user to login to the Dropbox account used I am putting a Dropbox Chooser together. The idea is that site users will have access to the Dropbox button and will be able to download any file they want.
This is working fine when I login to the account in question but I can't ask used to login to this account. I can't figure out what needs to be changed, the domain used is added to the Dropbox app settings, here is my test code:
<!DOCTYPE html>

    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

A: The Chooser is used when your app wants to gain access to a file in the end user's Dropbox. If what you're trying to do is offer users files from your own Dropbox, you should probably use the Core API instead.

A: try this this link
it may help you .
first you have to register your app ,
then Dropbox will provide you some keys:
keep that in authorize.php file of your app e.g
<?php
$access_token = array (
  "oauth_token_secret" => "abcdefghilmnopqr",
  "oauth_token" => "stuvwxyzabcdefgh",
  "uid" => "1234567"
);

The first time your application is run, the following condition in the index.php file will be true:
<?php
if (!isset($access_token)) {
    header("Location: authorize.php");
    exit;
}

the authorize.php will manage automatically for you .

A: Following previous answers I have tried to implement the solution at http://www.sitepoint.com/access-dropbox-using-php/ however this solution allowed me to create a list of files and folders but not create a temporary download link for any files.
I ended going to https://github.com/phpmasterdotcom/AccessDropboxUsingPHP where the codes originated and with a little tailoring was able to create a system showing the folder accessed in a breadcrumb style, have the folders clickable so users can navigate to subfolders and back and have a link generated to a file.
Here is what I have done:

*

*Downloaded the files at https://github.com/phpmasterdotcom/AccessDropboxUsingPHP

*Created a drop box app (there is good instructions on doing so on the first link above)

*I have created a file using sample.php as a base that will list the files and folders, I have called it index.php and here it is, you will need to change the app detail.
Please note that Dropbox request a URL with an https.

*

*DropPHP sample
*

*http://fabi.me/en/php-projects/dropphp-dropbox-api-client/
*

*@author     Fabian Schlieper

*@copyright  Fabian Schlieper 2012

*@version    1.1

*@license    See license.txt
*
*/

// these 2 lines are just to enable error reporting and disable output buffering (don't include this in you application!)
error_reporting(E_ALL);
ini_set('display_errors', 1);
//enable_implicit_flush();
// -- end of unneeded stuff
// if there are many files in your Dropbox it can take some time, so disable the max. execution time
set_time_limit(0);
require_once("DropboxClient.php");
// you have to create an app at https://www.dropbox.com/developers/apps and enter details below:
$dropbox = new DropboxClient(array(
    'app_key' => "xxxxxxxxxxxxxxxxxx",
    'app_secret' => "yyyyyyyyyyyyyyyyyyyyyy",
    'app_full_access' => true,
),'en');
// first try to load existing access token
$access_token = load_token("access");
if(!empty($access_token)) {
    $dropbox->SetAccessToken($access_token);
    //echo "loaded access token:";
    //print_r($access_token);
}
elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page?
{
    // then load our previosly created request token
    $request_token = load_token($_GET['oauth_token']);
    if(empty($request_token)) die('Request token not found!');
// get & store access token, the request token is not needed anymore
$access_token = $dropbox->GetAccessToken($request_token);
store_token($access_token, "access");
delete_token($_GET['oauth_token']);

}
// checks if access token is required
if(!$dropbox->IsAuthorized())
{
    // redirect user to dropbox auth page
    $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1";
    $auth_url = $dropbox->BuildAuthorizeUrl($return_url);
    $request_token = $dropbox->GetRequestToken();
    store_token($request_token, $request_token['t']);
    die("Authentication required. Click here.");
}
//set the current path requested
$path = '';//start on the root folder
    if (isset($_GET['path']))
    {
        $path = $_GET['path'];
}

        $dir = 'Root';

                if (strpos($path,'/')!== false)
                {
                                $rowDir = explode('/',$path);
                        $increment_path = '';

                        if (count($rowDir) !=0)
                        {
                            foreach($rowDir AS $dl)
                            {

                                    if ($dl !='')
                                    {
                                    $increment_path .= '/'. $dl;

                                    $dir .= ' >> '.$dl.'' ;
                                    }

                            }

                        }//end if

                }//end if

            echo '
Current Path: ' . $dir . '
';

$files = $dropbox->GetFiles($path,false);
                //then loop through the files returned separting folders and files
                if (empty($files))
                {
                        echo "Sorry, there is currently no files in the folder selected";

            }
            else
            {

                //loop through the array returned showing the folders first followed by the files
                                            $thisFiles = '';//store files
                                            $thisDir = '';//store directories
                                            foreach($files AS $file)
                                            {

                                                //see if it is a file or directory
                                                //we remove the first slash from the path
                                                $thisPath = $file->path;
                                                $lastMod = $file->modified;
                                                    //take the time out of the last modified date
                                                    $lastMod = substr($lastMod,0,strpos($lastMod,':'));
                                                    $lastMod = substr($lastMod,0,strrpos($lastMod,' '));

                                                //get the files name using the path
                                                $fileName = $thisPath;
                                                    //remove the first /
                                                    if (substr($fileName,0,1) == '/')
                                                    {
                                                    $fileName = substr($fileName,1);

                                                    }

                                                    //then replace the further slashes with >>
                                                    $fileName = str_replace('/', ' >> ', $fileName);

                                                if ($file->is_dir==1)
                                                {
                                                    //this is a directory
                                                    $thisDir .= '
' . $fileName. "
";

                                                }
                                                else
                                                {
                                                    //in order to avoid tool many calls we create the link in a separate file, this could very easily be done as follows:
                                                    //$thisFiles .= '
GetLink($thisPath).'" target="_blank">' . $fileName. '
Modified '.$lastMod.'
';
                                                    $thisFiles .= '
' . $fileName. '
Modified '.$lastMod.'
';
                                                }

                                            }

                                        echo '
'.$thisDir . $thisFiles.'
';

            }//end else

function store_token($token, $name)
{
    if(!file_put_contents("tokens/$name.token", serialize($token)))
        die('Could not store token! Make sure that the directory tokens exists and is writable!');
}
function load_token($name)
{
    if(!file_exists("tokens/$name.token")) return null;
    return @unserialize(@file_get_contents("tokens/$name.token"));
}
function delete_token($name)
{
    @unlink("tokens/$name.token");
}
?>

*finaly I have created a file called download_file which creates the downloadable link:

*

*DropPHP sample
*

*http://fabi.me/en/php-projects/dropphp-dropbox-api-client/
*

*@author     Fabian Schlieper

*@copyright  Fabian Schlieper 2012

*@version    1.1

*@license    See license.txt
*
*/

// these 2 lines are just to enable error reporting and disable output buffering (don't include this in you application!)
error_reporting(E_ALL);
ini_set('display_errors', 1);
//enable_implicit_flush();
// -- end of unneeded stuff
// if there are many files in your Dropbox it can take some time, so disable the max. execution time
set_time_limit(0);
require_once("DropboxClient.php");
// you have to create an app at https://www.dropbox.com/developers/apps and enter details below:
$dropbox = new DropboxClient(array(
    'app_key' => "xxxxxxxxxxxxxxxxxxxxxxx",
    'app_secret' => "yyyyyyyyyyyyyyyyyyyyyy",
    'app_full_access' => true,
),'en');
// first try to load existing access token
$access_token = load_token("access");
if(!empty($access_token)) {
    $dropbox->SetAccessToken($access_token);
    //echo "loaded access token:";
    //print_r($access_token);
}
elseif(!empty($_GET['auth_callback'])) // are we coming from dropbox's auth page?
{
    // then load our previosly created request token
    $request_token = load_token($_GET['oauth_token']);
    if(empty($request_token)) die('Request token not found!');
// get & store access token, the request token is not needed anymore
$access_token = $dropbox->GetAccessToken($request_token);
store_token($access_token, "access");
delete_token($_GET['oauth_token']);

}
// checks if access token is required
if(!$dropbox->IsAuthorized())
{
    // redirect user to dropbox auth page
    $return_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?auth_callback=1";
    $auth_url = $dropbox->BuildAuthorizeUrl($return_url);
    $request_token = $dropbox->GetRequestToken();
    store_token($request_token, $request_token['t']);
    die("Authentication required. Click here.");
}
//set the current path requested
if (isset($_GET['path']))
{
    $path = $_GET['path'];

    header("Location: ". $dropbox->GetLink($path));

}
else
{
    echo "
No path passed on to the script
";

}

function store_token($token, $name)
{
    if(!file_put_contents("tokens/$name.token", serialize($token)))
        die('Could not store token! Make sure that the directory tokens exists and is writable!');
}
function load_token($name)
{
    if(!file_exists("tokens/$name.token")) return null;
    return @unserialize(@file_get_contents("tokens/$name.token"));
}
function delete_token($name)
{
    @unlink("tokens/$name.token");
}


text:
Q: Integrating USB Camera on TI Hercules Evaluation Kit (ARM Cortex R4) I am using a TI Hercules Evaluation Kit, which can act as a USB Host.
Here's the link  [http://www.ti.com/tool/tmdxrm48hdk]. It is a ARM Cortex R4 with 8 MB of SDRAM.
I want to use a Logitech Webcam (specifically the Logitech C200 Webcam). It is UVC compliant, so the UVC driver code for this can be found inside Linux source code.
I want some help on porting this driver code to my Evaluation Kit.
Is it feasible or am I aiming too high?

A: I am answering my own question.
This was not feasible, because I wanted to capture 30 frames per second and for such high rates USB 2.0 is a must. My board does not support USB 2.0
Also there were not many sample USB driver codes available for this board.


text:
Q: How to use openID to login in a site with another site's account? I want to know how does SO registers users if they have only a gmail account and don't ask for any information.
in a word, how it is possible to login with google or facebook account in another website using openID.

A: Stack Overflow allows you to register using your Google account, meaning as long as you're logged in via Google at the time you register/log in you won't need to supply a username/password. Stack Overflow will then get some needed information from your Google account after you authorize it to.
Here's a decent run-down of the process: http://qpleple.com/how-to-make-people-login-into-your-website-with-their-google-account/
And some SO questions that are similar:

*

*Google login in my site

*Login to site using Gmail

*Using Google account as Login... what next?

*https://stackoverflow.com/questions/18593992/how-would-go-about-implementing-a-multiple-account-sign-in-like-google


text:
Q: Error in distance SQL query I have this SQL query:
SELECT
  *,
  6371.04 * acos(cos(pi() / 2 - radians(90 - `Tournament`.`latitude`)) * cos(pi() / 2 - radians(90 - 37.226)) * cos(radians(`Tournament`.`longitude`) - radians(-93.4397)) + sin(pi() / 2 - radians(90 - `Tournament`.`latitude`)) * sin(pi() / 2 - radians(90 - 37.226))) AS `Tournament`.`dist`
FROM `tournaments` AS `Tournament`
WHERE 1 = 1
ORDER BY `Tournament`.`dist` ASC
LIMIT 5

I can't figure out what could be possibly wrong with that statement. Here's the error I'm getting:
1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.`dist` FROM `tournaments` AS `Tournament`   WHERE 1 = 1   ORDER BY `Tournament`' at line 1

Could anyone point me in the right direction?

A: The keyword AS is supposed to be followed by an id, not a compound identifier.
From the manual:

A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses.

http://dev.mysql.com/doc/refman/5.0/en/select.html
More on alias names: http://dev.mysql.com/doc/refman/5.6/en/identifiers.html

A: AS `Tournament`.`dist`

It is probably complaining about the dot.  Try assigning it to just dist.


text:
Q: How to create a fixed, vertical, expandabale navbar? I already read the related questions, which unfortunately do not give an answer to my specific problem:
On the basis of Bootstrap 3.0.3, I am trying to create a fixed navbar on the left with a width of 50px, which should expand to a width of 150px, when you click on the navbar-toogle. When the navbar is not expanded, it should display only the glyphicons for each link. I am able to create the navbar with a fixed width, but I am stuck with the correct incorporation of the navbar-toggle and the the span-text, which is neither displaying nor working correctly. Have a look at the example pictures for the intended result:

HTML:

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

 Link1

 Link2

 Link3

 Link4

 Link5

CSS:
    #sidebar {
    background-color: #16a085;
    color: white;
    height: 100%;
    padding: 0;
    position: fixed;
    left: 0;
    top: 0;
    width: 50px;
    z-index: 2;

}

#sidebar-nav {
    margin-top: 75px;
}

I would appreciate your advice on this.

A: Something like this sort of what you're after? Animations can be done with -webkit-transition on the width. I'll fine tune this when I get the time in half an hour.
#sidebar .link-text {
    visibility: hidden;
}
#sidebar:hover .link-text {
    visibility: visible;
}


text:
Q: How to put text at rightmost position of an underline?
\documentclass{article}
\usepackage{booktabs}
\usepackage[a4paper,left=0cm,top=0.2cm,bottom=0cm,right=0cm]{geometry}
\usepackage{polyglossia}
\setmainlanguage[numerals=Devanagari]{bengali}
\setmainlanguage{bengali}
\setotherlanguage{english}
%\newfontfamily\englishfont[Scale=MatchLowercase]{Linux Biolinum O}
\newfontfamily\bengalifont[Script=Bengali]{Akaash}
\usepackage{pgffor}
\newcommand{\ListItem}[1]{\underline{\makebox[5cm][l]{#1}}}
\begin{document}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\\

\vspace{2cm}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\\

\vspace{2cm}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\begin{minipage}{0.33\textwidth}
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া}
{
\ListItem{\x}\par\bigskip}
\end{minipage}
\end{document}

I want to add text "40 taka" in the last line(রিক্সা ভাড়া) of the list in the right side of the underline.

A: At least for the simple case you describe, it's sufficient to add \hfill 40 taka to the last element of each list.
\foreach \x in {চাল,ডাল,লবণ,তেল,মরিচ,পেঁয়াজ,রসুন,আদা,মুরগী,মশলা,রিক্সা ভাড়া\hfill 40 taka}


text:
Q: function equalHeight , set a minimum Height to apply? I have tried everything, but without javascript I cannot achieve the bad layout my designer gave to me!!

As you can see I have the div #backgr-box that has to be absolute positioned with z-index to be properly behind the #contenuto (which holds the page content!!)
    Now to solve the extensibilty trouble of #backgr-box I have the below code that works if the content of #contenuto is longer than the sidebar #barra-laterale  , but it is not ok in opposite case, see page: http://demo.liquidfactory.it/secondopolo/per-informarti

So how can I tell javascript to apply that calculation only over a minimum height of div sidebar #barra-laterale ??
Need help.. please!
function equalHeight(group) {
           tallest = 0;
           group.each(function() {
              thisHeight = $(this).height();
              if(thisHeight > tallest) {
                 tallest = thisHeight = $("#contenuto").height() - 380;
              }
           });
           group.height(tallest);
        }
        $(document).ready(function() {
           equalHeight($(".column"));
        });

A: The problem is likely with this line:
tallest = thisHeight = $("#contenuto").height() - 380;

Currently it is  setting both the variables tallest and thisHeight to the height of the content region minus 380 pixels. Change it to:
tallest = thisHeight;

And it will resize all the columns to the height of the tallest one.
Edit: It looks like your right-hand column actually consists of multiple columns  with a class of .barra-laterale in this case you may want to take another tack altogether:
// calculate the total height of the content are and sidebar
var contentHeight = $("#contenuto").height();
var sidebarHeight = 0;
$(".barra-laterale").each(function() { sidebarHeight += $(this).height(); })

if (sidebarHeight > contentHeight) {
    $("#contenuto").height(sidebarHeight);
} else {
    // extend the last sidebar column to cover the difference between the
    // height of the content and the sum of the sidebar heights
    var lastSideBarHeight = $(".barra-laterale").last().height();
    var heightDifference = contentHeight - sidebarHeight;
    $(".barra-laterale").last().height(lastSideBarHeight + heightDifference)
}


text:
Q: Multiple assignments in filtered datasets Trying to do multiple assigments with a filtered dataset I encountered a strange behavior I cannot explaim myself. My Testdata:
import pandas as pd
wert = 2.5
df = pd.DataFrame([['Test', 12, None, None], ['Test2', 15, None, None]], columns=['A','B','C','D'])

My first question occured executing this line of code:
df.loc[(df['A'] == 'Test'), ['D']] = df['B'] * wert

the filter is only on the left side so how does df['B'] knows where to assign the values? I thought df['B'] should be filtered as well but this is obviously not neccessary. So I stepped forward doing multiple assignment with condition and tried to execute this line:
df.loc[(df['A'] == 'Test'), ['C', 'D']] = [1, df['B'] * wert]

Now I get an error ValueError: cannot set using a list-like indexer with a different length than the value. My explanation would be that the array df['B'] is longerthan df.loc[df['A']=='Test) but since this worked fine in example 1 this cannot be the exlanation. Could anyone tell me why this is not working and giving me this error?

A: Why does this happen?
Because pandas will raise a ValueError when:

the indexer is an ndarray or list and the lengths don't match.
An special-case is allowed for when the indexer is a boolean array and
  the number of true values equals the length of value. In this
  case, no exception is raised.
source

You can use df.assign() if you don't want to filter df['B'] to match:
df.loc[(df['A'] == 'Test')].assign(C=1, D=df['B'] * wert)

A: Your solution working, if filter column B by same mask - is necessary same index values of filtered rows for alignment of data (not only length):
mask = (df['A'] == 'Test')
df.loc[mask, ['C', 'D']] = [1, df.loc[mask, 'B'] * wert]
print (df)
       A   B     C     D
0   Test  12     1    30
1  Test2  15  None  None

So if filter by another value:
mask = (df['A'] == 'Test2')
df.loc[mask, ['C', 'D']] = [1, df.loc[mask, 'B'] * wert]
print (df)
       A   B  C     D
0   Test  12  1   NaN
1  Test2  15  1  37.5

What means:

ValueError: cannot set using a list-like indexer with a different length than the value

Honestly, not understand error, so ask in pandas github.
And add answer from pandas devs later.


text:
Q: How to bind or combine two objects in SceneKit I have a bow and arrow. The arrow needs to look like it's on the bow and move with the bow until the arrow get shot forward. So how do I make an object always stay with the bow and move as the bow does, in other words temporarily combining the two? I'm currently using SceneKit. Thanks

A: the easiest way is to make the arrow a child node of the bow. Or you can have a look at SCNTransformConstraint.


text:
Q: Bing Geocode API, SSIS, C# Script I'm trying to replicate what I found here to use bing's geocode API: https://sqlmd.wordpress.com/2012/03/27/using-the-ssis-scripting-task-to-geocode-addresses/
When I run what I have I get this error:

Error: 0xFFFFFFFF at Get Lat Long Bing, Error:: Could not find default
  endpoint element that references contract
  'bing.geocode.IGeocodeService' in the ServiceModel client
  configuration section. This might be because no configuration file was
  found for your application, or because no endpoint element matching
  this contract could be found in the client element.

The script that I'm using is C#.
Public Sub Main()
    If Dts.Variables.Contains("Address") And Dts.Variables.Contains("Lat") And Dts.Variables.Contains("Long") Then
        Try
            ' Set a Bing Maps key before making a request

            Dim key As String = "Bing Key goes here"

            Dim geocodeRequest As New bing.geocode.GeocodeRequest

            Dim SearchAddress As String
            SearchAddress = Dts.Variables("Address").Value.ToString
            Dts.Events.FireInformation(0, "Address:", SearchAddress, "", 0, True)

            ' Set the credentials using a valid Bing Maps Key

            geocodeRequest.Credentials = New bing.geocode.Credentials()
            geocodeRequest.Credentials.ApplicationId = key

            ' Set the full address query

            geocodeRequest.Query = SearchAddress

            ' Set the options to only return high confidence results
            Dim filters As bing.geocode.ConfidenceFilter() = New bing.geocode.ConfidenceFilter(0) {}
            filters(0) = New bing.geocode.ConfidenceFilter()
            filters(0).MinimumConfidence = bing.geocode.Confidence.High

            Dim geocodeOptions As New bing.geocode.GeocodeOptions()
            geocodeOptions.Filters = filters

            geocodeRequest.Options = geocodeOptions

            ' Make the geocode request
            Dim geocodeService As New bing.geocode.GeocodeServiceClient
            Dim geocodeResponse As bing.geocode.GeocodeResponse = geocodeService.Geocode(geocodeRequest)

            If geocodeResponse.Results.Length > 0 AndAlso geocodeResponse.Results(0).Locations.Length > 0 Then
                Dts.Events.FireInformation(0, "Lat:", geocodeResponse.Results(0).Locations(0).Latitude.ToString(), "", 0, False)
                Dts.Variables("Lat").Value = geocodeResponse.Results(0).Locations(0).Latitude
                Dts.Events.FireInformation(0, "Long:", geocodeResponse.Results(0).Locations(0).Longitude.ToString(), "", 0, True)
                Dts.Variables("Long").Value = geocodeResponse.Results(0).Locations(0).Longitude
            End If

        Catch ex As Exception
            Dts.Events.FireError(-1, "Error:", ex.Message, "", 0)
            Dts.TaskResult = ScriptResults.Success
        End Try
    Else
        Dts.Events.FireError(-1, "Error:", "Missing vairable in Task Component Definition.", "", 0)
    End If

End Sub

Enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum

End Class
And this is my app.config:
<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for           My.Application.Log -->
        <source name="DefaultSource" switchName="DefaultSwitch">
            <listeners>
                <add name="FileLog"/>
                <!-- Uncomment the below section to write to the Application Event Log -->
                <!--<add name="EventLog"/>-->
            </listeners>
        </source>
    </sources>
    <switches>
        <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
        <add name="FileLog"
             type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
             initializeData="FileLogWriter"/>
        <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
        <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
    </sharedListeners>
</system.diagnostics>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="basicHttpBinding_IGeocodeService" />
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://dev.virtualearth.net/webservices/v1/geocodeservice/GeocodeService.svc"
            binding="basicHttpBinding_IGeocodeService" bindingConfiguration="basicHttpBinding_IGeocodeService"
            contract="basicHttpBinding_IGeocodeService" name="basicHttpBinding_IGeocodeService" />
    </client>
</system.serviceModel>

A: I would suspect that you need to check if your configuration file is setup properly
<configuration>
    ...
    <client>
        <endpoint address="http://localhost:9999/"
            binding="yoursetting" bindingConfiguration="yoursetting"
            contract="yoursetting" name="yoursetting">
        </endpoint>
    </client>
    ...
</configuration>

Alternatively, it may be that the configuration needs to be restored. Which in that case you should remove the custom bindings from the configuration and rebuild the solution.

A: It looks like you are using the old legacy Bing Maps SOAP services. These are nearing end of life and will be turned off at the end of June. Use the Bing Maps REST services instead which are faster, and have more features. The Bing Maps team created an open source toolkit for using the Bing Maps REST services in .NET. It's actually easier than using the SOAP services: https://github.com/Microsoft/BingMapsRESTToolkit/
That said, if you have a lot of data to geocode in your database on a regular basis, you may want to use the batch geocoding service that is in Bing Maps. Its a bit more work to setup but will be much faster for large data sets, will use less bandwidth. As an added bonus, if you license Bing Maps, the first 1M batch geocoded addresses a year are free customers. You can find documentation about this service here: https://msdn.microsoft.com/en-us/library/ff701733.aspx


text:
Q: How to round $ 0.03446$ to three decimal places?
What is $ 0.03446 $ rounded to three decimal places?

I think it is $0.035$ but someone told me that it should be $0.034$.
I think $0.035$ because the $6$ would change the $4$ into a $5$, which would change the other $4$ into a $5$, but the other person said you only need to look at the next digit along.

A: The other person is correct. To round to the third decimal place, you look strictly at the the digit immediately to the right: $4$ in this case, and $4/10$ rounds to zero.
So you need to round $0.03446$ to $0.034$

A: The other person is correct. Rounding is saying what number it is closer to. So which value is smaller: $|0.03446-0.034|$ or $|0.03446-0.035|$? The smaller value tells us which one we want to round to.

A: The correct question for rounding is - is it closer to $0.034$ or $0.035$? - the tiebreak for equals applies at this level.
NOTE: there has been some recent discussion in the UK suggesting that the incorrect method you exemplify in your question has been widely taught in schools. What we are first taught has a powerful grip on our instinct - but sometimes it is just wrong, and we have to get over it.
See this link for example.
I have also seen primary school teachers effectively defining a trapezium to be what I would call an isosceles trapezium (i.e. symmetrical trapezium). There is a lot of poor basic knowledge.


text:
Q: How to model stored procedure records in Grails? I need to call some stored procedures that return their own kinds of records, that are not directly mapped to tables or views.
I have used stored procedures in the past with groovy.sql.Sql and plain (unmodelled) Maps, but for this application I would like to model those records with something akin to domain classes, in order to define data types, data binding, validation, associations to other entities, and so on.
What is the best way to do so?
Should I model the stored procedure records as proper domain classes (entities) and then try to disable (or redefine) their database persistence? How?
Should I use non-domain POJOs where I selectively enable the features I need? (such as validation with @Validatable) How can I handle associations then? (Associations arise when the record returned from the SP contains a foreign key to some other persisted entity.)

A: If you want data binding, validation and associations to be maintained in an easy way then you should go with the Domain approach.
To disable database persistence for a domain class you can add static mapWith = "none" to a domain class and a table won't be created for that domain class.
Sample Entity class:
@ToString
public class SPTest {

    Long idField

    User user

    GroupIntegrationKey integrationKey

    static constraints = {
    }

    static mapWith = "none"
}

Stored Procedure statement:

SELECT id AS idField, user_id AS user, key AS integrationKey FROM
  my_domain;

In order to map the result of the SP to the entity you can use result transformers.
Query query = session.createSQLQuery("CALL getSPData()");

List<Map> results = query.with {
    resultTransformer = AliasToEntityMapResultTransformer.INSTANCE
    list()
}

Now iterate over list and create a new entity object
List<MyDomain> list = results.collect {
    new MyDomain(it)
}

System.err.println(list)

Drawbacks:

*

*You can not map identifier field

*You would have to iterate over result again to create entity objects

*You can not map hasMany relationships

If you want to go with pojo, then in that case you would have to create your own version of getters to get associated objects.


text:
Q: iOS , UIActivityIndicator never get displayed in pushed web view controller I am trying to display and start an UIActivityIndicator into a webView before loading the requested url... and stopping it after loading
but it never get displayed....
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSDictionary *dict = [self.arrNewsData objectAtIndex:indexPath.row];

     NSString *newsLink = [dict objectForKey:@"link"];

     // setup the controller to be pushed
     UIViewController *webViewController = [[UIViewController alloc] init];
     webViewController.title = @"Article";

     // setu p the web view
     UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
     webView.delegate = self;
    [webViewController.view addSubview:webView];

     // setup and start the indicator
    _webViewLoadingIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(roundf((self.view.frame.size.width - 50) / 2), roundf((self.view.frame.size.height - 50) / 2),50,50)];
    [webView addSubview:_webViewLoadingIndicator];
    [_webViewLoadingIndicator startAnimating];

     // send the request
     NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:newsLink]];
    [webView loadRequest:request];

     // push the controller
    [self.navigationController pushViewController:webViewController animated:YES];

}


text:
Q: faild to build Libyuv library (PJSIP) for android I'm developing a chat android application. I want to use also the call functionality. I have successfully built the pjsua2.so library for SIP call VoIP but I failed to build Libyuv.so Library for video call
I followed the instructions in thows to links
libyuv building libyuv 1776
After running ndk-build command in step 2 from the second link, I do not have this lib libyuv. So I don't have also [libyuv_dir]/libs/armeabi
Also for openH264, after runnig this command /configure-android --with-openh264=/home/ubuntu/openh264-1.0.0/android  I got that :

Using OpenH264 prefix... /home/ubuntu/PJSIPTOOLS/openh264-1.0.0/openlib/
checking OpenH264 usability... no

Can anybody help me please
(sorry for bad english)

A: Download and build libyuv from here:
https://github.com/illuspas/libyuv-android


text:
Q: Rails Active storage "identify -format %[orientation]" issue on .heic format while updating the metadata I am using Rails(5.2) Active Storage for saving attachments directly in S3.
While uploading the attachment using direct uploads, Blob will be created first and the attachments will be created in Active storage. Then background job will be enqueued for saving the metadata using analyze_blob method.
I am facing the below issue in background job while updating the metadata for .heic image formats in ActiveStorage::Blob table

MiniMagick::Error: identify -format %[orientation] /tmp/ActiveStorage20201125-18095-1ccc7me.heic[0] failed with error:
identify: no decode delegate for this image format `HEIC' @
error/constitute.c/ReadImage/564.

Can somebody help on this issue? Thanks in Advance.

A: HEIC is a newer format, I would guess that the version of minimagick or imagemagick you're using isn't aware of that format.  You might have luck upgrading to a newer version of imagemagick on the system and/or a newer version of the minimagick gem.


text:
Q: Logical operation between all elements in array I want to compare all items in my array using a boolean operator in the most efficient way. Currently, I have something like this :
bool myFunction(int i)
{

    bool *myArray = {true, true, false, false, true};
    //suppose we know that i = 5 and that i is the length of the array...
    return myArray[0] && myArray[1] && myArray[2] && myArray[3] && myArray[4];
}

Since the size of the array is not fixed, the value of 'i' can change and my return statement would no longer be working, so I would have to implement something like this
bool myFunction(int i)
{
    bool *myArray = //some other array of bools
    //should work with any value of i
    bool result = myArray[0];
    for (int a = 1; a < i; ++a)
    {
        result &= myArray[i];
    }
    return result;
}

I was wondering if there was a better way to do this other than making a for loop and going through each elements and comparing the value of the next item in list with the stored result from the previous two items. Like some bitwise operators that would make this easy or something, anything to take out the loop.

A: You probably need to know that &= is not a logical operator; it is the "bitwise and" operator.  As long as you only use it on booleans, I guess it will work ok; but C won't stop a value other than 1 or 0 from slipping into the array, so you should probably not make that assumption.  Semantically if you're doing a logical or you want && instead of &.
That said, you can certainly use short-circuiting to refine what you're doing.  Once you've found a single 0 (false), nothing from then on is going to make your aggregate go back to 1 (true), so you might as well stop.
for (int a = 1; result && a < i; ++a)
{
    result &= myArray[i];
}

Other than that, there's not much you can improve.  Not sure why you're averse to a loop, but if you want to combine an unknown number of values you're going to have to iterate.  You might find (or write) some utility function to do it, but it'll be using a loop internally anyway.  (Unless it tries to leverage a vector processor that natively does what you want, maybe... but that would be rather pointless and, if you truly don't have a limit on number of values, will still involve a loop.)

A: You can use all_of (replacestd::begin(myArray) + i with std::end(myArray) if you want to check entire array and not first i elements):
#include <vector>
#include <algorithm>
bool myFunction(int i)
{
    std::vector<bool> myArray = { true, true, false, false, true };
    return std::all_of(std::begin(myArray), std::begin(myArray) + i, [](bool elem) { return elem; });
}

A: You can use a boost::dynamic_bitset, it has a member fuction any() that will return true if any bits in this bitset are set. And none() will return true if no bits are set.
But the implementation of any() is:
template <typename Block, typename Allocator>
bool dynamic_bitset<Block, Allocator>::any() const
{
    for (size_type i = 0; i < num_blocks(); ++i)
        if (m_bits[i])
            return true;
    return false;
}

So you have inside a for loop!
But if you are searching for something like parallel computing, you may want to use arrayfire:
For example it has an algorithm     that do it.
template<typename T >
T af::allTrue(  const array &   in  )
//C++ Interface for checking if all values in an array are true.

A: You can exit the loop as soon as you encounter false:
for (int a = 0; a < i; a++)
{
    if (!myArray[i])
        return false;
}
return true;

If you're allowed to change the last value in the array, then here's a trick for optimizing it:

*

*If the last value in the array is false, then return false

*Write false into the last entry in the array

*Iterate the array until you encounter false

*Write true into the last entry in the array

*If you stopped before the last entry, then return false

*Return true
The code:
int a;
if (!myArray[i-1])
    return false;
myArray[i-1] = false;
for (a = 0; a < i; a++)
{
    if (!myArray[i])
        break;
}
myArray[i-1] = true;
return a != i-1;

This yields one branch per iteration instead of two branches per iteration.

If you're allowed to allocate i+1 entries, then you can get rid of the "last entry swapping" part:
int a;
myArray[i] = false;
for (a = 0; myArray[i]; i++);
return a != i;

You can also get rid of the additional arithmetic embedded in myArray[i]:
bool *arrayPtr;
myArray[i] = false;
for (arrayPtr = myArray; *arrayPtr; arrayPtr++);
return arrayPtr != myArray+i;

If the compiler doesn't already apply it, then this function will do so for sure. On the other hand, it might make it harder on the optimizer to unroll the loop, so you will have to verify that in the generated assembly code...

A: I would change the condition of your for-loop so you won't continue if you encounter a false value and use an iterator instead of an index.
bool myFunction(int i) {
    bool myArray[i] = //some other array of bools
    //should workwith any value of i

    bool result;
    bool * a;
    for (a = myArray, result = *a; a < myArray+i && result; result=*(++i)) {}
    //no need to use the AND operator since we stop if we meet one false

    return result;
}

Or if you really prefer with index:
bool myFunction(int i) {
    bool myArray[i] = //some other array of bools
    //should workwith any value of i

    bool result;
    unsigned int a;
    for (a = 0, result = myArray[a]; a < i && result; result=myArray[++i]) {}
    //no need to use the AND operator since we stop if we meet one false

    return result;
}

Maybe I'm wrong, but I wouldn't use the bitwise AND assignment (&=) if it's not on bit range operation, it's not really relevant on the bool type though.


text:
Q: Confusion about canonical rational section of the sheaf of a divisor In Vakil's "The Rising Sea", remark 14.2.3 says that the sheaf $O_X(D)$ for divisor $D$ comes along with a canonical rational section, namely the section corresponding to function $1$ defined in the complement of support of $D$.  My question is what if the scheme under consideration has only finitely many points and hence possibly the complement of the support is empty, e.g., we can consider a DVR.
Here our schemes are taken to be integral and normal.

A: A divisor $D$ is defined to be a formal sum of codimension-one subvarieties. No codimension-one subvariety contains the generic point of an integral scheme, so it cannot be the case that the complement of the support of $D$ is empty.


text:
Q: How to change the height and width of button and add buttons through drawable canvas in android studio? I made the snake and ladder game in android studio. I want to change the height and width of the buttons, and I want to add one more button for exit. Right now I am using only one .png file for all buttons. So, How to change it? When i add the fourth button my application crash and its shows the error.
Check this image
Error
    FATAL EXCEPTION: main
    Process: com.sixtinbyte.snakeandladder, PID: 25115
 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.sixtinbyte.snakeandladder.components.GameButton.onDraw(android.graphics.Canvas)' on a null object reference
 at com.sixtinbyte.snakeandladder.HomeView.onDraw(HomeView.java:151)

HomeView. java (This are the java file where i want to change because this is the homescreen of the game)
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;

import com.sixtinbyte.snakeandladder.components.GameButton;
import com.sixtinbyte.snakeandladder.constant.Sound;

public class HomeView extends View {
 public Context ctx;
 private Resources res;
 private String refText ="Snakes and Ladders";
 private GameButton gButton, sButton, hButton,eButton;
 private Bitmap logo, play, settings, help, exit;
    private int hWidth, hHeight;
 private Point touchCoordinate = new Point();

 public HomeView(Context ctx) {
    super(ctx);
    this.ctx = ctx;
    res = getResources();
    logo = BitmapFactory.decodeResource(res, R.drawable.snakes_n_ladders);

 }

 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // TODO: Implement this method
    super.onSizeChanged(w, h, oldw, oldh);
    hWidth = w;
    hHeight = h;
    preparePlayButton();
    prepareSettingsButton();
    prepareHelpButton();
//   prepareExitButton();
 }

    private void preparePlayButton() {
    String text =" ";
    int textSize = 40;
    Point po = getBmpMeasureFrom(text, refText, textSize);
    play = getBitmap(R.drawable.play, po.x, po.y);
    gButton = new GameButton(play, text, textSize);
    gButton.setLocation((hWidth - po.x) / 2, (int)(hHeight * 0.6f));
    gButton.setTextColor(Color.CYAN);
 }
 private void prepareSettingsButton() {
    String text =" ";
    int textSize = 40;
    Point po = getBmpMeasureFrom(text, refText, textSize);
    settings = getBitmap(R.drawable.play, po.x, po.y);
    sButton = new GameButton(settings, text, textSize);
    sButton.setLocation((hWidth - po.x) / 2, (int)(hHeight * 0.7f));
    sButton.setTextColor(Color.CYAN);
 }
//
//
 private void prepareHelpButton() {
    String text =" ";
    int textSize = 40;
    Point po = getBmpMeasureFrom(text, refText, textSize);
    help = getBitmap(R.drawable.play, po.x, po.y);
    hButton = new GameButton(help, text, textSize);
    hButton.setLocation((hWidth - po.x) / 2, (int)(hHeight * 0.8f));
    hButton.setTextColor(Color.CYAN);
 }
//  private void prepareExitButton() {
//      String text =" ";
//      int textSize = 40;
//      Point po = getBmpMeasureFrom(text, refText, textSize);
//      help = getBitmap(R.drawable.play, po.x, po.y);
//      hButton = new GameButton(help, text, textSize);
//      hButton.setLocation((hWidth - po.x) / 2, (int)(hHeight * 0.8f));
//      hButton.setTextColor(Color.CYAN);
//
//  }

 private Point getBmpMeasureFrom(String text, String refText, int textSize) {
    Point p = new Point();
    Paint pa = new Paint();
    pa.setTextSize(textSize);
    p.y = (int)(pa.getTextSize() * 2.2f);
    String tt = refText.length() > text.length() ?refText: text;
    p.x = (int) (pa.measureText(tt) * 1.2f);
    return p;
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
    // TODO: Implement this method
    int evt = event.getAction();
    touchCoordinate.x = (int)event.getX();
    touchCoordinate.y = (int)event.getY();
    switch (evt) {
     case MotionEvent.ACTION_DOWN:
 MainActivity.playSound(Sound.BUTTON_CLICK_1, false);
        break;
     case MotionEvent.ACTION_MOVE:

        break;
     case MotionEvent.ACTION_UP:
//      MainActivity.stopSound();
        if (gButton.contains(touchCoordinate)) {
         Intent intent = new Intent(ctx, GameActivity.class);
         ctx. startActivity(intent);
        }
        if (sButton.contains(touchCoordinate)) {

         Intent intent = new Intent(ctx, Playing.class);
            ctx.startActivity(intent);
        }
        if (hButton.contains(touchCoordinate)) {

         Intent intent = new Intent(ctx, Aboutus.class);
         ctx. startActivity(intent);
        }
//       if(eButton.contains(touchCoordinate)){
//           Intent intent = new Intent(ctx, Exit.class);
//           ctx.startActivity(intent);
//       }

        break;
    }
    return true;
 }

 @Override
 protected void onDraw(Canvas canvas) {
    // TODO: Implement this method
    super.onDraw(canvas);
    canvas.drawColor(Color.CYAN);

    canvas.drawBitmap(logo, (hWidth - logo.getWidth()) / 2, (int)((hHeight - logo.getHeight()) * 0.1), null);
    gButton.onDraw(canvas);
    sButton.onDraw(canvas);
    hButton.onDraw(canvas);
//  eButton.onDraw(canvas);
//  Paint p= new Paint();
//  p.setColor(Color.RED);
//  canvas.drawRect(100, 200, 400, 500, p);
    invalidate();
 }

 private Bitmap getBitmap(int drawableRes, int width, int height) {
    Drawable d = res.getDrawable(drawableRes);
    Canvas c = new Canvas();
    Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    c.setBitmap(b);
    d.setBounds(0, 0,width, height);
    d.draw(c);
    return b;
 }

}

A: The prepareExitButton method is assigning hButton, I think it should be assigning eButton. That's why you're getting a NullPointerException there. Also, you're setting the y-coordinate to (int)(hHeight * 0.8f)) which means it will overlap with the help-button.
You may need to alter the GameButton class to get the ability to adjust the button's size. In particular, you'll want to change onDraw to draw the button in the specified size.


text:
Q: Go websocket, nginx proxy is this correct? I have a RESTful server in go, and it's behind nginx. everything is fine and we are happy with this setup (nginx and go) but now we have a websocket route for this application. (Its currently works ok with nginx in our staging server, not real load yet.)
The questions :

*

*Is this good for my websocket route to be behind nginx too? is there any good reason for/against this?

*Is there any way to bypass this route from nginx proxy and serve it directly with go? not in another subdomain or another binary.
Thanks!

A: I am no nginx expert but given that nobody else has answered I will present some of my research.
1) Yes, nginx is definitely a good choice for that. You can find some benchmarks here. Possible caveats are mentioned in this (older) post. The most important point to consider is the timeout aspect. These two answers give helpful information in that regard.
2) Not exactly sure what you want to achieve by that but you could simply use a different port, as websockets are not subject to the same origin policy, or use the tcp forwarding module that is described in one of the answers above.


text:
Q: How to get actual file type if it is renamed to something different file extension in android? I want to upload images on the server, unfortunately, my server supports only jpg/jpeg file formats. If I will upload a png file I will get an error. So before uploading to the server, I want to make sure the file type is only jpg/ jpeg. But I am afraid that some users can change a png file type to jpg just by renaming it. For eg- myfile.png can be renamed easily with myfile.jpg. I used below approach to check file type in Android/ Kotlin -
fun getMimeType(context: Context, uri: Uri): String {
        var mimeType = ""
        mimeType = if (uri.scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            val cr = context.contentResolver
            cr.getType(uri) ?: ""
        } else {
            val fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                    .toString())
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                    fileExtension.toLowerCase(Locale.getDefault())) ?: ""
        }
        return mimeType
    }

But it returns only jpg/jpeg even in case of png file renamed to jpg. I think it's checking by file extension only. So my question is - Is there any way to check the original file type (in our case it is a png file)?
Happy Coding :-)

A: You have to check file's Header and verify if it respects JPEG formats (this procedure is valid for many type of files) https://wiki.fileformat.com/image/jpeg/


text:
Q: radiobutton hovering bug that cannot be solved by preventing it from garbage collection tkinter I was going through some code and came across this one, where while hovering the mouse over the radiobuttons, the Checkbutton gets selected, I have tried keeping a reference to variable(shouldn't be needed as is already global), but it fails.
Here is the code:
from tkinter import *

root = Tk()

text_colors = ['1','2','3','4','5','6','7','8']
rads = []
for i in range(4):
    for j in range(2):
        col = text_colors.pop()
        val = IntVar()
        root.garbage_saver = val
        rads.append(Radiobutton(root,text=col,fg='red',variable=val))
        rads[-1].grid(row=i,column=j)

root.mainloop()

This bug is reproducible on my Windows 10, Python 3.9

A: This is the code without the bug:
from tkinter import *

root = Tk()

text_colors = ['1', '2', '3', '4', '5', '6', '7', '8']
rads = []

val = IntVar(root)
val.set(-1)

for i in range(4):
    for j in range(2):
        col = text_colors.pop()
        rbutton = Radiobutton(root, text=col, fg="red", variable=val, value=i*2+j)
        rbutton.grid(row=i, column=j)
        rads.append(rbutton)

root.mainloop()

Basically you keep over writing the variables root.garbage_saver and var with the last IntVar object so it destroys the previous one. The behaviour is caused by tkinter unsetting the variable when it gets garbage collected.
tkinter.__init__.py:
class Variable:
    """Class to define value holders for e.g. buttons.

    Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
    that constrain the type of the value returned from get()."""
    _default = ""
    _tk = None
    _tclCommands = None
    def __del__(self):
        """Unset the variable in Tcl."""
        if self._tk is None:
            return
        if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
            self._tk.globalunsetvar(self._name)
        if self._tclCommands is not None:
            for name in self._tclCommands:
                #print '- Tkinter: deleted command', name
                self._tk.deletecommand(name)
            self._tclCommands = None

Note tkinter calls self._tk.globalunsetvar(self._name) which tells tcl/tk to unset the variable.
Tcl/Tk docs:
"The widget sets the alternate state whenever the linked -variable is unset."


text:
Q: Prove that if $\sqrt[n]{\prod\limits_{i\leq n}a_i}$ converges to a finite limit then $a_n$ converges Prove that if $$\lim_{n\to\infty} \sqrt[n]{\prod_{i\leq n}a_i} < \infty$$
then $\lim_{n\to\infty} a_n$ exists.
Given that $\{a_i\}$ is bounded and positive.
So I used Cesaro means to show that $\lim_{n\to\infty} \sqrt[n]{\prod_{i\leq n}a_i}  = \lim_{n\to\infty} a_n$ if the limit exists, but how to prove that the limit exists?

A: The existence of $\lim_{n\to\infty}\Big[\prod_{i\leq n}a_i\Big]^{\frac{1}{n}}$ does not imply the existence of $\lim_{n\to\infty}a_n$, even if we assume that all the $a_n$ are positive.
For instance, if we let $a_n=2$ if $n$ is odd and $a_n=\frac{1}{2}$ if $n$ is even, then $(a_1\cdots a_n)^{\frac{1}{n}}\to 1$ as $n\to\infty$, but $\lim_{n\to\infty}a_n$ does not exist.
Essentially $(a_1\cdots a_n)^{\frac{1}{n}}$ makes the sequence more regular in a manner very similar to Cesaro means, as can be seen by taking logarithms.


text:
Q: How should I takcle the following problem? How should I takcle the following problem?
$x$, $y$ and $a$ are integers
$a$ is known
$$
\left\{
\begin{array}{l}
y \leq x \\
y =  \frac a x \\
y > 0, x > 0, a > 0 \\
x - y \rightarrow min
\end{array}
\right.
$$
It was easy to draw the respective graphic in Desmos:

Now I think I need to find the minimum of the $x - y$ in the highlighted on the screenshot area. I was thinking about taking a derivative and setting it to $0$, but I do not know how to proceed further.
I remember from the university that there are methods to solve such min/max problems. Could someone direct me towards a solution for the problem, please?


text:
Q: How to add a web elements to an ArrayList? I have a method in which I am trying to add 12 web elements:
private List<WebElement> iphoneSnippetList = new ArrayList<>();
@Test
public void test(){

    chromeDriver.get("https://market.yandex.ru/catalog--smartfony/54726/list?hid=91491&glfilter=7893318%3A153043&onstock=1&local-offers-first=0");

        new WebDriverWait(chromeDriver, 15).until(ExpectedConditions.elementToBeClickable(By.xpath("//article[@data-autotest-id='product-snippet'][1]")));

        for (int i = 0; i <= 12; i++) {
            iphoneSnippetList.add((WebElement) By.xpath("//article[@data-autotest-id='product-snippet'][" + i + "]"));
        }
        System.out.println(iphoneSnippetList);
    }

Simplified DOM elements in which I only need to get the text :
<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"

<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"

<article class="_2vCnw cia-vs cia-cs" data-autotest-id="product-snippet"

I need to add all 12 web elements to my array and then make sure that the received elements contain the name "Iphone", but when adding elements, there is exception:
java.lang.ClassCastException: class org.openqa.selenium.By$ByXPath cannot be cast to class org.openqa.selenium.WebElement (org.openqa.selenium.By$ByXPath and org.openqa.selenium.WebElement are in unnamed module of loader 'app')

A: iphoneSnippetList  is a List of WebElement in Java-Selenium bindings.
I am not sure why you want to add 12 web elements using the loop, instead a findElements with right xpath would have been a good choice. Anyway, there's a problem with you code related to casting.
See below, driver.findElement will return the web element, and we are storing that into a variable called Webelement e, and adding the same into  iphoneSnippetList
for (int i = 0; i <= 12; i++) {
    WebElement e = driver.findElement(By.xpath("//article[@data-autotest-id='product-snippet'][" + i + "]"));
    iphoneSnippetList.add(e);
}
    System.out.println(iphoneSnippetList);

Also, this loop will run for 13 times not 12 times. In case you want this to run for 12 times, initialize i = 1 not i = 0
I think you will have issue with xpath also, cause you are not using xpath indexing correctly.
try this instead :
for (int i = 1; i <= 12; i++) {
     WebElement e = driver.findElement(By.xpath("(//article[@data-autotest-id='product-snippet'])['" +i+ "']"));
     iphoneSnippetList.add(e);
}
System.out.println(iphoneSnippetList);


text:
Q: Real solution of equation cantaining exponential and cosine function
If $\ln(2\pi)<\log_{2}(2+\sqrt{3}),$ Then number of real roots of the equation $4\cos(e^x)=2^x+2^{-x}$

$\bf{My\; Try::}$ Let $$f(x)=2^x+2^{-x}-4\cos(e^x)$$
Then $$f'(x) = 2^{x}\ln(2)-2^{-x}\ln(2)+4\sin(e^x)\cdot e^x$$
and $$f''(x)=2^{x}(\ln(2))^2+2^{-x}(\ln(2))^2+4\sin(e^x)e^x+4\cos(e^x)e^x$$
Now how can i solve after that, Help required, Thanks


text:
Q: Can I use R attributes to save physical units? Can I (should I) use R attributes to save physical units and similar information as hint for the user?
epsilon0 <- 8.854188e-12
# name <- "electric constant"
# source <- "CODATA"
# unit <- "F m-1"

A: You can, with this code:
attributes(epsilon0) <- list(name = "electric constant", source = "CODATA", unit="F m-1")

A: In addition to @MatthewLundberg's answer, you can set and get individual attributes like:
> attr(epsilon0,"name") <- "electric constant"
> epsilon0
[1] 8.854188e-12
attr(,"name")
[1] "electric constant"

> attr(epsilon0,"name")
[1] "electric constant"


text:
Q: Searching for two integers root**pwr = integer(user's input) A question from a book I have found.

Write a program that asks the user to input an integer and prints two
  integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal
  to the integer user entered. If no such pair exists, print that it is
  impossible to find such a pair.

integer = 3 #there will be raw_input but I use it as an example
root = 0

for pwr in range(1,6):

    if root**pwr != integer:
        pwr += 1
        print pwr

    else:
        print root, pwr

    if pwr > 5:
        pwr = 1
        root += 1

I did not complete program yet because I cannot get loop right. The problem is that I receive output 2, 3, 4, 5, 6 and then loop terminates. However, I did use restart on pwr variable in the last if statement code block you see. However, it stops to execute anyway. What is the problem here?

A: As others have noted, this is the finger exercise for section 3.1 (on exhaustive enumeration) of Introduction to Computation and Programming Using Python by John Guttag, which is the textbook for the massive open online course MITx: 6.00.1x Introduction to Computer Science and Programming Using Python. The textbook and the course use Python 2.7.
I do not yet have a high enough reputation to comment on other answers, so allow me to preface my answer by saying that at the time I am posting this, all of the previously posted answers are incorrect or incomplete, as far as I can see. A common mistake in the other answers is that they do not consider all integers. A correct program should solve the problem for all integers, including positive integers and negative integers and zero (zero is also an integer).
Prior to this exercise in Guttag's book, we have been introduced to while loops but not for loops nor the range function, both of which are introduced in the next section. Here is my answer, using only the concepts that have been introduced in the book prior to this exercise:
num = int(raw_input("Enter an integer: "))
pwr = 1
root = 0
found = False
if num < 0:
    neg = True
else:
    neg = False
while pwr < 6:
    while abs(root**pwr) <= abs(num):
        if root**pwr == num:
            print(str(root) + "**" + str(pwr) + " = " + str(num))
            found = True
        if abs(root) > abs(num):
            root = 0
        elif neg:
            root -= 1
        else:
            root +=1
    pwr += 1
    root = 0
if not found:
    print("No pair of integers, 'root' and 'pwr', exists such that 0 < pwr < 6 and root**pwr = " + str(num))

I have tested this code with the integers 0, 1, -1, 2, -2, 8, -8, and some other integers, and it appears to work.

A: Another option, with "simple math".
integer = 3

for power in range(1,6):
    a = (integer ** (1.0/power))
    if math.ceil(a) == a:
        print a, power

>> 3.0 1

A: In general, it's not a good idea to modify what you are looping over inside of the loop. There is no reason to fiddle with pwr when you are using it to iterate over range(1,6).
What your code is trying to do is test root ** pwr == integer for successive values of pwr and a fixed value of root until pwr reaches 6. Then you want it to add one to root and repeat. This is most naturally phrased as two nested for loops:
for root in range(0,integer):
    for pwr in range(1,6):
        if root ** pwr == integer:
            print root, pwr

In any case, this is a fairly expensive way to go about it and so I would recommend looking into some of the other solutions here. However, you should keep this in mind because it's a good example of how to use for loops.
To answer your question about why the loop was terminating you have to consider how python treats iterators. When the code block inside of a for loop terminates, python sets pwr to the value returned by the iterators next() method (which does exactly what you would think). When there are no more values left in the iterator next() will raise a StopIteration exception and Python will exit the loop. The key is that Python doesn't modify the value of pwr by adding 1 each iteration, it overwrites the value. So you loop will run exactly 5 times because that's how many items there are in range(1,6)
For clarification run the following code:
for i in range(0,9):
    print i
    i += 5
    print i

A: integer ** 1 always suffices the condition.
An alternative (assuming you actually want 1 < pwr < 6):
Check if for a certain base a and a number n: ceil(a ** log_a(n)) == n. If so - then a ** log_a(n) is your answer.
Repeat for all possible a's in range.
(In here log_a(n) is the logarithm with the base a, which can be computed as log(n)/log(a))

A: As others have mentioned, this is a finger exercise from Introduction to Computation and Programm Using Python by John Guttag.
While some of the above responses may work (to be honest, I haven't tested), a simpler approach will produce the desired results as well as accommodate negative integers, e.g.:
x = int(input("Enter an integer: "))
root = 0

while root < abs(x):
    root += 1
    for pwr in range(1,6):
        if root ** pwr == abs(x):
            if x < 0:
                print(-root, "to the power of", pwr, "=", x)
            else:
                print(root, "to the power of", pwr, "=", x)

A: I had a logical error, while trying to figure out what it might be, I wasted a lot of time, and I think this might be a common mistake. I forgot to reset the value of pwr in the outer loop.
Here is the current version:
root=0
pwr=1
check=0
integer=int(input('Enter the number:'))
while(root**pwr<abs(integer)):
    while(pwr<6):
        if root**pwr==abs(integer):
            check=1
            print('Root =',root,'or -'+ str(root),'and Power =',pwr)
        pwr+=1
    root+=1
    pwr=1    #<--------------Resetting pwr to 1 inside the outer loop
if check!=1:
    print('No such combination exists')

I hope this helps in saving some time.

A: This is what I came up with. As was mentioned in a previous post, the range should have been 2-6 for the pwr because there will always be an answer for a integer to a pwr of one, and the exercise states that there will be integers where no such pair exists.
x = int(input('Enter an integer: '))
root = 0
pwr = 2
while pwr > 1 and pwr < 7:
    while root**pwr < x:
        root = root + 1
    if root**pwr == x:
        print(str(root) + '**' + str(pwr), '==', str(x))
        break
    else:
        root = 1
        pwr = pwr + 1
else:
    print('no such pair exists')

A: Long version answer that prints the decrementing function - use it only for small numbers
x = int(input('Enter an integer:'))

pwr = [1,2,3,4,5]
mypairs = []

for p in pwr:
    root = 0
    while root**p < abs(x):
        print('Value of decrementing function abs(x) - root**p is',\
              abs(x)-root**p)
        root = root + 1
    if root**p == abs(x) and p%2 !=0:
        print('For the power %s there exists such a pair, shown in final list.'%p)

    if root**p != abs(x):
        print('For the power %s there does not exist any such pairs.'%p)
    else:
        if x < 0:
            if p%2 == 0 :
                print('For the power %s there does not exist any such pairs'%p)
            else:
                root = -root
                mypairs.append([root,p])
        else:
            mypairs.append([root,p])
print(mypairs)

Faster answer without decrementing function
x = int(input('Enter an integer:'))

pwr = [1,2,3,4,5]
mypairs = []

for p in pwr:
    root = 0
    while root**p < abs(x):
        root = root + 1
    if root**p != abs(x):
        print('For the power %s there does not exist any such pairs.'%p)
    else:
        if x < 0:
            if p%2 == 0 :
                print('For the power %s there does not exist any such pairs'%p)
            else:
                root = -root
                mypairs.append([root,p])
        else:
            mypairs.append([root,p])
print(mypairs)

A: Here is my answer for finger exercise, I added another if statement after the inner loop and it works fine now for positive integers.
inum= int(input('Enter an integer '))
    root = 0
    pwr = 1
    found = 0

    while root**pwr < inum:

        while 0<pwr<6:

            if root**pwr == inum:
                found = 1

                print('The power is ',pwr,'& root is ',root)
                break
            else:
                found = 0
                pwr = pwr+1
        if root** pwr == inum:
            break
        else:
            root = root+1
            pwr = 1

    if found ==0:
        print('Power and root pair doesnot exist')

A: This is the finger exercise from Chapter 3 of 'Introduction to Computation and Programming Using Python' by John Guttag and reads:
Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer entered by the user. If no such pairs exists, it should print a message to that effect.
Given the author indicates that there may be no pairs that exist, I've assumed that the conditions for pwr should be 1 < pwr < 6 otherwise there will always be a solution (integer**1). My answer, using only the concepts that have been introduced in the book to that point, is:
num = int(raw_input('Enter a positive integer: '))
pwr = 2
root = 1
ans = ''
while pwr < 6:
    while root**pwr <= num:
        if root**pwr == num:
            print 'the root is ',root,
            print 'the power is ', pwr
            ans = True
        root += 1
    pwr += 1
    root = 1
if ans != True:
    print'No such pair of integers exist'

A: First, if we enter an integer, e.g 1024, then we have 1024^1 = 1024. So there will always be a solution to the problem:
n = int(input('Enter an integer: '))
pwr = 1
root = 1
found = False

while root <= n:
    if root**pwr == n:
        print('root =',root, 'pwr =', pwr)
        found = True
    pwr = pwr + 1
    if pwr == 6:
        pwr = 1
        root = root + 1

if not found:
    print('No such pair exist.')

A: This is an answer based on the submission by archery1234. Thanks to archery1234 a I am so new to this I could not get started without the help. I liked the answer provided because it only used the concepts explained up to that point in the book so I felt it was close to what Dr. Guttag probably wanted us to learn (while loop within a while loop). The following code meets the condition that 0 < pwr < 6 without always just terminating at the integer entered as the root and pwr = 1.
integer = abs(int(raw_input("Enter an integer: ")))
pwr = 1
root = 2
ans = ' '
if abs(integer) == 1:
    print "No such pair of integers exists"
else:
    while root < abs(integer):
        while root**pwr <= integer:
            if root**pwr == integer:
                print "The root is ",root,";"
                print "The power is ",pwr,"."
                ans = True
            pwr += 1
        root += 1
        pwr = 1
    if ans != True:
        print "No such pair of integers exist"

A: I was working on this problem, my answer works:
number = int(raw_input("Enter a number: "))
    i = 1

    pwr = 1
    test = 0
    while i <= number/2:
        while pwr < 6:
            if i ** pwr == number:
                print i
                test = 1
            pwr = pwr + 1
        i = i + 1
        pwr = 1
    if test == 0:
        print 'No such pair of integers exist.'

A: This is my answer:
usr = int(raw_input("Enter an integer > "))
paired = False
for pwr in range(1,6):
    root = 0
    while (usr - root**pwr > 0):
        root += 1
    if usr == root**pwr:
        paired = True
        print "root is " + str(root) + " and ",
        print "power is " + str(pwr)
        break
if paired == False:
    print "No pair"

A: I have managed to solve this problem  with the knowledge you gain  from chapter 1 up until  3.1  in the book by Gattug. This finger exercise  took me two weeks to do. I am also just started coding.
here is my solution:
num = int(raw_input('Enter an integer: '))
root = num
power = 1

if root**power == abs(num):
   print ' First pair of integers which equal the integer:', num, 'is root = ', root, 'power = ', power
   root -= 1
while root**power != abs(num) and root > 0:
while power < 6 and root**power != abs(num):
      if not(root**power == abs(num)):
         power +=1
      if not(root**power == abs(num)):
         power +=1
if power >= 6 and root**power != abs(num):
    power = 1
    root -= 1
if root**power == abs(num):
print 'Second pair of integers which equal the integer:', num, 'is root = ', root, 'power = ', power
elif root**power != abs(num) and root == 0:
print ' there is no other pair of integers that equal', num

I have done it and it is the best book to teach  teaching you coding

A: Tried to do this without reframing the spec of the finger exercise, only using what the book introduced so far -  this works for positive and negative integers, and, as far as I could tell, it will list all possible pairs, including root=number, pwr=1.  One of the keys seems the use of abs in the right places, and to make sure to set root to negative if the user integer was negative. Hope this helps someone like all the other thoughtful contributions helped me.
num = int(raw_input('Enter an integer: '))
pwr = 1
root = 1
ans = ''
while pwr < 6:
    while root**pwr <= abs(num):
        if root**pwr == abs(num):
            if num<0:
                root=-root
        print 'the root is ',root, 'the power is ', pwr
        ans = True
        root= abs(root)+1
    pwr += 1
    root = 1
if ans != True:
    print'No such pair of integers exist'

A: I am self-studying python and my solution is following.
num = int(input('Please enter integer: '))
list= []
list1=[]
for root in range (0,num):
    for pwr in range (1,6):
        if root**pwr == num:
            list.append([root,pwr])
        else:
            list1.append(0)
if list ==[]:
    print ('No root exist')
else:
    print (list)

I created list to save all roots and pwrs in it.

A: I enjoyed Pragu's solution but improved it a bit I think. I stop it if the solution is found that way you wind up with the lowest value for instance in Pragu's solution, 16 will return both 2^3 and 4^2 which are true answers. I had already put in the nonzero parts myself and solved it using for but realized, as Pragu, so eloquently stated, that we hadn't gotten there in the book yet. Here's what I did.
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 12:03:09 2018

@author: chief
"""

import random #this imports the random function
mysteryNumber = int(input('Please enter a non-zero positive integer: ')) #give me input Seymour!
if mysteryNumber <= 0: #did they give me a non-zero positive integer?
    print("that wasn't a non-zero positive integer doofenshmirtz!! I'll fix that for you") #Carl would understand
    if mysteryNumber < 0: #make it a positive integer
        mysteryNumber = -mysteryNumber
    if mysteryNumber == 0: #make it a non zero integer by generating random number
        mysteryNumber = random.randint(1,100)
print ('Your number is', mysteryNumber)
root=0 #set the variables or clear the pallet if you will
pwr=1
check=0

while(root**pwr<abs(mysteryNumber)): #first while loop
    while(pwr<6) and check == 0: # this and logical stops it at the earliest answer otherwise 16 will give you two answers as will 81
        if root**pwr == abs(mysteryNumber): #if then loop checks did you find the answer, if yes then next 2 lines are active, if no then to the else line
            check=1
            print('The root =',root,'or -'+ str(root),'and Power =',pwr, 'will yield', mysteryNumber)
        pwr+=1 #else line, adds 1 to the pwr and moves back to the while statement of while<6
    root+=1 #While pwr <6 is done so we go onto the next root
    pwr=1    #<--------------Resetting pwr to 1 inside the outer loop
if check!=1: #the first while is done now, if we found an answer this argument returns false and the line below doesn't get executed
    print('No rational combination of root and power exists for', mysteryNumber)

A: number = int(raw_input("Enter a number: "))
pwr = 1
root = 2

while root < number:
    pwr = 1
    while pwr < 6:
        if root*pwr == number:
            print'Numbers are', (root, pwr)
        pwr += 1
    root += 1
    print('No such numbers')

A: I think that this question was already answered, but hopefully this expands on the current working state. Any feedback is appreciated!
I am currently working through this on MIT OpenCourseWare. I wanted to come up with a solution that would print all possible root/pwr combinations for a given integer, while limiting the exhaustive guesses to it's minimum amount. This is my answer:
intNum = int(input("Please enter an integer: "));
neg = False;

if intNum < 0:
    neg = True;

root = 0;
pwr = 2;

print("The integer is: ", intNum);
# Will always have at least one root/pwr such that intNum=root and pwr = 1
print ("rootFOUND: ", intNum, " pwrFOUND : ", 1);

while 0 < pwr < 6:
    while root**pwr <= abs(intNum):
#        print ("root: ", root, " pwr: ", pwr);
        if root**pwr == abs(intNum):
            if neg and pwr%2 != 0:
                print ("rootFOUND: ", -root, " pwrFOUND : ", pwr);
            elif not neg:
                print ("rootFOUND: ", root, " pwrFOUND : ", pwr);
        root += 1;
    pwr += 1;
    root = 0;

Boundaries that I wanted to account for were:

*

*If the integer was positive

*If the integer was negative

*If the integer was zero

Thought process:

*

*A positive integer was accomplished by setting the initial root value to zero and incrementing up while root**pwr was less than the integer that was inputted.

*A negative integer was accomplished by First, always checking if the integer was negative to begin with. Second, as the root was being incremented, the root**pwr was checked against the absolute value of integer. The last thing that had to be accounted for was the fact that negative integers could only be found by exponential statements if the exponential was odd. This was accomplished by checking if the integer was negative and the exponential was odd.

*A zero integer check was accomplished by setting the initial root to zero and always resetting the root back to zero when breaking out of the inner while loop.
Here are some outputs:
Please enter an integer: -4096
The integer is:  -4096
rootFOUND:  -4096  pwrFOUND :  1
rootFOUND:  -16  pwrFOUND :  3

Please enter an integer: 4096
The integer is:  4096
rootFOUND:  4096  pwrFOUND :  1
rootFOUND:  64  pwrFOUND :  2
rootFOUND:  16  pwrFOUND :  3
rootFOUND:  8  pwrFOUND :  4

Please enter an integer: 0
The integer is:  0
rootFOUND:  0  pwrFOUND :  1
rootFOUND:  0  pwrFOUND :  2
rootFOUND:  0  pwrFOUND :  3
rootFOUND:  0  pwrFOUND :  4
rootFOUND:  0  pwrFOUND :  5

A: I believe this may be a more elegant solution as it provides all the possible roots with minimal initializations and uses only the while loop as per the Guttag text. Please give it a try. I believe it works for all uses cases.
I used the root equals integer to break the loop so that I could reset the power on each iteration. This prevents any overload of the while loop. (Root == integer is the same as the case where power is equal to 1)
integer = int(input("Enter an integer please: "))
root = 0
pwr = 0
while root**pwr < abs(integer):
    root = root + 1
    while pwr < 6:
        pwr = pwr + 1
        if root**pwr == integer:
            print("Root:", root, ", Power:", pwr)
    if root == integer:
        break
    pwr = 0

Outputs for Integer = 343:
Root: 7, Power: 3
Root: 343, Power: 1

A: This is what I have by using two while loops
x = int(input('Enter an integer'))
root = 0
pwr = 0

while(root**pwr < abs(x)):

    while(root**pwr < abs(x) and pwr < 6):
        pwr += 1
        #print('root',root, ' power', pwr, 'result', root**pwr)
        if(root**pwr == abs(x)):
            if(x<=0):
                print('root', -root, 'power', pwr)
            else:
                print('root', root, 'power', pwr)
            break

    if(root**pwr == abs(x)):
        break
    else:
        root+=1
        pwr = 0

if(root**pwr!=x):
    print('no result found')

A: #instead of asking for input, i input random so you could test faster
#and greater range of integers

input = randint(-10000,10000)
root = 0
power = 1

while root <= abs(input):
  if root**power == abs(input):
      break
  # if power is within bounds, increment, else reset it to 1 and increment
  # root to loop through
  if power < 6:
      power = power + 1
  else:
      power = 1
      root = root + 1

if root**power != abs(input):
    print("There are no perfect integers")
else:
    if input < 0:
        root = -root
    print("Root:",root,"; Power:",power)

A: Here is the answer up to date (June 2020) using Python 3.7.6 for the Second Editon of Introduction to Computation and Programming using Python by John Guttag.
As Big Mac wrote

As others have noted, this is the finger exercise for section 3.1 (on
  exhaustive enumeration) of Introduction to Computation and Programming
  Using Python by John Guttag, which is the textbook for the massive
  open online course MITx: 6.00.1x Introduction to Computer Science and
  Programming Using Python. The textbook and the course use Python 2.7.
  ... A common mistake in the other answers is that they do not consider
  all integers. A correct program should solve the problem for all
  integers, including positive integers and negative integers and zero
  (zero is also an integer).
Prior to this exercise in Guttag's book, we have been introduced to
  while loops but not for loops nor the range function, both of which
  are introduced in the next section.

Finger exercise: Write a program that asks the user to enter an integer
and prints two integers, root and pwr, such that 0 < pwr < 6
and root**pwr is equal to the integer entered by the user.
If no such pair of integers exists, it should print a message to that effect.
x = int(input('Enter an integer to analyze '))
root = 0
pwr = 1
while pwr < 6:
    while root**pwr < abs(x):
        root += 1
    if abs(root**pwr) != abs(x):
        print('no root at the power', pwr, 'for', x)
    else:
        if x < 0:
            root = -root
            if pwr%2 != 0:
                print (root, "**", pwr, '=', x)
            else:
                print('no root at the power', pwr, 'for', x)
        else:
            print (root, "**", pwr, '=', x)
    root = 0
    pwr += 1

This solution is valid for all integers, is using Python 3, is slightly shorter ( in respect to the knowledge acquired thus far in the Second Editon of the reference book) and slightly more complete (to my understanding) by printing an answer for each power even when no such pair exists.
It will return results like
Enter an integer to analyze -8
-8 ** 1 = -8
no root at the power 2 for -8
-2 ** 3 = -8
no root at the power 4 for -8
no root at the power 5 for -8

A: x = int(input("Enter an Integer :"))
root = 1
pwr = 0

while root**pwr != abs(x) and x != 0 :
    if pwr == 6 :
        pwr = 0
        root = root + 1
    else :
        pwr = pwr + 1
if x > 0 :
    print(root,"**",pwr,"==",x)
elif x < 0 :
    if pwr%2 == 0 :
        print ("no solution")
    else :
        print(-1*root,"**",pwr,"==",x)
else :
    print("no solution")

Hi guys, I think there will be lot of approach to solve the question. Currently I also just learning phyton from the book.
Since this is the question from iteration part using "while"  , I think the solution expected also using "while".

A: integer = int(input('Enter an integer: '))

root = 0
ans=0
isTrue=False
while (root < integer):
    for pwr in range(1,6):
       ans=root**pwr

       if ans==integer:
           print(root, 'to the power', pwr, '=', ans)
           isTrue= True
   root = root+1

if isTrue != True:
    print('No such pair of integers exists')

A: Here is my take on the problem using only the functions that were introduced in the book up to the exercise in question. I believe this is the only program among the pre-existing answers here that takes into account ALL possible pairs of roots and powers (including both positive and negative roots for even powers).
num = int(raw_input('Enter an integer: '))
pwr = 1
root = 0
found = False

while pwr < 6:
    while root**pwr <= abs(num):
        if root**pwr == abs(num):
            if num < 0:
                root = -root
            print '(' + str(root) + ')**' + str(pwr) + ' = ' + str(num)
            if pwr%2 == 0:
                root = -root
                print '(' + str(root) + ')**' + str(pwr) + ' = ' + str(num)
                root = -root
            if num < 0:
                root = -root
            found = True
        root = root + 1
    root = 0
    pwr = pwr + 1

if not found:
    print 'No pairs of integers exist'


text:
Q: How do I make the button value an object, not a string? This is my current code. I want the value of the button to be childData and for it to be the original object, not a string so that I can use it appropriately.
var childData = childSnapshot.val();

                document.getElementById("displayChores").innerHTML += (String(childData["clocation"] + " " +
                childData["cname"] + " " +
                childData["cdescription"] + " " +
                childData["ccredits"] + " " +
                childData["cexp"]) + "
" +
                "<button class='chorebtn' value= '"+childData+"' onclick=\"choreDone();\">Mission Complete</button>
")};

A: could you just make a the value of the button a JSON.stringify() of the object and then when you want to use it just JSON.parse() it back?


text:
Q: Tikz: Curly brace incorrectly positioned I'm trying to draw a curly brace to the right of some nodes. It is currently appearing to the left of a completely different node.
Here is my code:
\documentclass[]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,positioning,calc,decorations.pathreplacing}
\begin{document}
\tikzstyle{block} = [rectangle, draw, fill=blue!20,
    text width=5em, text centered, rounded corners, minimum height=4em]
\tikzstyle{line} = [draw, -latex']
\tikzstyle{brace} = [decorate]
\tikzstyle{bracenode} = [midway, right=2pt, rotate=90, anchor=north]

\begin{tikzpicture}[node distance = 3cm, auto]
    \node [block, label=left:1st Stroke] (recognise) {Recognise};
    \node [block, right of=recognise] (anchor) {Anchor};
    \node [block, right of=anchor] (store) {Store};
    \node [text width=5em, below of=recognise, node distance = 3cm, label=left:2nd Stroke] (recognise2) {};
    \node [block, right of=recognise2] (group2) {Group};
    \node [block, right of=group2] (store2) {Store};

    \path [line] (recognise) -- (anchor);
    \path [line] (anchor) -- (store);
    \path [line, dashed] (store) to [out=270,in=90] (group2);
    \path [line] (group2) -- (store2);

    \draw[brace, decoration={brace}] let \p1=(store.north), \p2=(store2.south) in
        ($(2, \y1)$) -- ($(2, \y2)$) node[bracenode] {1st Annotation};
\end{tikzpicture}
\end{document}

The picture I get is:

What am I doing wrong? I thought using the .south and .north notation would position to the correct node.

A: I would do something like this:
\draw [brace] (store.north east) ++(5pt,0) coordinate (s) -- (store2.south east -| s)  node [bracenode] {1st Annotation};

which produces

Complete code (updated to avoid deprecated syntax and to remove unneeded library):
\documentclass[border=10pt,tikz,multi]{standalone}
\usetikzlibrary{arrows.meta,positioning,decorations.pathreplacing}
\begin{document}
\tikzset{% \tikzstyle is deprecated
  block/.style={rectangle, draw, fill=blue!20, text width=5em, text centered, rounded corners, minimum height=4em},
  line/.style={draw, -LaTeX},
  brace/.style={decorate, decoration={brace}},
  bracenode/.style={midway, right=2pt, rotate=90, anchor=north},
}
\begin{tikzpicture}[node distance = 2cm, auto]
  \node [block, label=left:1st Stroke] (recognise) {Recognise};
  \node [block, right=of recognise] (anchor) {Anchor};
  \node [block, right=of anchor] (store) {Store};
  \node [text width=5em, below=of recognise, node distance = 3cm, label=left:2nd Stroke] (recognise2) {};
  \node [block, right=of recognise2] (group2) {Group};
  \node [block, right=of group2] (store2) {Store};

  \path [line] (recognise) -- (anchor);
  \path [line] (anchor) -- (store);
  \path [line, dashed] (store) to [out=270,in=90] (group2);
  \path [line] (group2) -- (store2);

  \draw [brace] (store.north east) ++(5pt,0) coordinate (s) -- (store2.south east -| s)  node [bracenode] {1st Annotation};
\end{tikzpicture}
\end{document}