text:
Q: Cast one of the operands of multiplication operation to a long? I am multiplying two numbers which is int and storing in long. But it displays error as ,
Cast one of the operands of this multiplication operation to a long. How to solve this?
 private int milisecPerSecond = 1000;

/**
 * The update interval in seconds.
 */
// Update frequency in seconds
private int updateIntervalInSec = 5;
 /**
 * The update interval.
 */
// Update frequency in milliseconds
private long updateInterval = milisecPerSecond * updateIntervalInSec;

A: First, this will not result in a compiler error. It's the usual case to multiply to int numbers and store the result in an int.
A signed int if 32 bit wide can take numbers up to approx. 2 billion. If your code does what it says, this will make an update interval of 2 million seconds, or 23 days.
If you really want to force a long-based calculation, just cast one of its factors:
long updateInterval = millisecsPerSecond * (long) updateIntervalInSec;

The second factor will get converted automatically then.
Keep in mind that only casting the result will not be enough:
private long updateInterval = (long) (milisecPerSecond * updateIntervalInSec);
// THIS WON'T DO AS EXPECTED

as it will do the problematic calculation on int and just cast the then maybe wrong result into a long.
Casting is something that's described on the first three pages of every book on Java. If you're serious enough about code quality to run code quality tools, then have someone with knowledge of the language you use sit beside you. A trained pair of fresh eyes for a code review is such a great resource.


text:
Q: How to use regexp to search a list for a string using proc? Trying to dive into TcL Scripting.  I've found that I'm writing a lot of duplicate code & I'd like to figure out how to make it a process, to shorten my scripts.  I may be wrong about the entire idea of the process.  I'm currently copying the foreach loop & changing the names of the variables.  Can I do this with a process so I only type the foreach loop once?
One example, is that I need a process to search a list for strings that "should" be there.  If they're not there, I'd like to output to a report file.
I apologize if this is unclear:
Something like this
        set mandatoryGlobal "{
        ^service tcp-keepalives-in} {
        ^service tcp-keepalives-out} {
        ^service timestamps debug datetime msec}"
    set run "{
    version 12.4}
    {service timestamps debug datetime msec}
    {service timestamps log datetime msec}
    "

    proc mandatory {mandatoryList config} {
        foreach command $mandatoryList {
            set x 1
            foreach line $config {
                if {![regexp $command $line]} {
                    incr x
                }
            }
            if {$x>[llength $config]} {
                append report $command\n
                return $command\n
            }
        }
    }

    mandatory $mandatoryGlobal $run

    puts $report
    #I would expect that report shows
    #^service tcp-keepalives-in
    #^service tcp-keepalives-out

    #But I only have this????
    #^service tcp-keepalives-in

    #If I run the foreach loop without the proc & change the variables,
    #it works as expected

Also, I've edited this to try to be more clear about what I'm trying to do.  Donal Fellows answered perfectly after I re-read my question, but I wasn't clear in my goal.  Donal, I really appreciate your effort & an amazing explanation.

A: OK, you've got a list of words and a string to look in them for. Let's assume the words are all well-behaved (no RE-metacharacters) so we can search simply, and that the string just contains simple words too.
Well, in that case we can use foreach to go over the list of words, and lsearch instead of regexp to see if the word is present:
proc mandatory {string list} {
    set report {}
    foreach word $list {
        if {[lsearch -exact $string $word] < 0} {
            lappend report $word
        }
    }
    return $report
}

Now we need to call this and deal with the results:
set run "this is a test list to check for a string"
set value "string that's not in the list"
set unfound [mandatory $value $run]
if {[llength $unfound] > 0} {
    puts "The following words were not in the string: $unfound"
} else {
    puts "All words present and correct"
}

Note that we're returning the list of unfound words as a value, storing that in a local variable, and then generating the message after that. (The llength check is a good way to see if a list is empty.)

We can shorten the mandatory procedure using the ni (Not In) operator:
proc mandatory {string list} {
    set report {}
    foreach word $list {
        if {$word ni $string} {
            lappend report $word
        }
    }
    return $report
}

But we ought to be more careful about what words are present. This is where we use regexps; for parsing:
proc mandatory {string list} {
    set report {}
    set stringWords [regexp -all -inline {\S+} $string]
    foreach word $list {
        if {$word ni $stringWords} {
            lappend report $word
        }
    }
    return $report
}

In some cases, it can be better to build a hash table of the words that are present so that we don't do linear scans of the string's words over and over. Tcl arrays are really hash tables.
proc mandatory {string list} {
    set report {}
    foreach word [regexp -all -inline {\S+} $string] {
        set present($word) "some dummy value"
    }
    foreach word $list {
        if {![info exists present($word)]} {
            lappend report $word
        }
    }
    return $report
}

(Don't worry about this getting a bit long; it's all bytecode-compiled except for the RE splitter, which frankly doesn't need to be.)
You could write things to use regexps to do the actual searching (lsearch -regexp is the key you're looking for), but I wouldn't advise that unless you really need it: for this sort of "check all these things are present", they're the wrong tool.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preferred Method of debugging a wordpress SQL calls? What is your preferred method of debugging Wordpress Applications when writing custom behind-the-scenes SQL calls, etc. ?
Coming from a Rails background, I usually tail a log file that displays not only all the processes and views that are being seperately loaded into a template, but if there is an error, it will pin point the exact location of the error, with a suggested idea of what went wrong. I noticed that in WordPress, you can set up a debug.log file but it only shows a very barebones version of this, and rarely points to what actually is failing.
Any recommends?

A: Turn on  define( 'WP_DEBUG', true ); and define( 'SAVEQUERIES', true ); .
I prefer the format of the debug bar, http://wordpress.org/extend/plugins/debug-bar/ , which can be combined with the console, http://wordpress.org/extend/plugins/debug-bar-console/ .
This script is great for profiling, Best Collection of Code for your functions.php file
There are some other plugins that might help, like Debug Queries, but you probably going to have to use a debugger like xdebug to get more fine grained details.


text:
Q: Giving input to a Python file and recieving output? I'm pretty new to Python and I'm trying to do something. I'm using a Python IRC bot which let's me build functions that are used as commands on the channel. I have obtained a python version of Cleverbot and would like to link these 2 together. But becuase I'm not good with Python I'm not sure how to do it.
To use the cleverbot python I would simply type in a terminal:
python cleverbot.py

And it would give me a "> " where I can input. Then I say on that line "Hello" and the cleverbot script will print the result using a print command.
So, I've been messing around and have discovered I can use the Python IRC bot commands to print a string, so it will simply print the results string for me. The problem is I can't get it to input anything to the cleverbot script. I was hoping it was possible to do something like:
print python cleverbot.py "hello"

And it would simply print the response from Cleverbot, does that make sense? I could then simply use the IRC commands to print the response to the channel.
Thanks in advance, and I hope it was possible to understand.

A: inside cleverbot.py you can you these statements to print the command line argument provided:
   import sys
   print(sys.argv[1])  #or print(' '.join(sys.argv[1:])) if the arguments are more than one

so now python cleverbot.py hello will print hello

A: Try
echo "hello" | python cleverbot.py


text:
Q: Run script depending on active sheet I'm trying to execute a script based on an active sheet the user is. So, the menu code is the following:
function onOpenInstalledTrigger(){
  app.createMenu('Benefits')
    .addItem('Generate benefits', 'setBenefits')
    .addToUi();
}

And then, to execute the script only when the sheet VT is active I wrote:
function setBenefits(){
  if (SpreadsheetApp.getActiveSpreadsheet().getSheetByName() == 'VT'){
    benefitsValue()
    discountValue()
    netValue()
  } else {
    app.alert('It must be active on sheet VT')
  }
}

But when I add this condition, I get an error:

Exception: The parameters () don't match the method signature for
SpreadsheetApp.Spreadsheet.getSheetByName.

How can I only execute the code when the user is at the right sheet?

A: Use getActiveSheet().getName() to get the name of the current active sheet.
function setBenefits(){
  if (SpreadsheetApp.getActiveSheet().getName() == 'VT'){
    benefitsValue()
    discountValue()
    netValue()
  } else {
    app.alert('It must be active on sheet VT')
  }
}

You have it confused with getSheetByName.
getSheetByName needs a parameter (sheet name) and it returns the sheet.
getName returns the name of the spreadsheet/sheet depending on where you use it.
Output:

Reference:

*

*getName

*getSheetByName
EDIT:

*

*The issue "Exception: The number of rows in the range must be at least 1." is caused by the commands outside the functions trying to access the active sheet's range that isn't available.

FIX:

*

*There are many ways to do this, but the easiest modification you can do is access VT directly. Since you only need to do this in VT sheet, access the VT sheet instead.

Modification:
var spread = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('VT');

Output:

A: try this instead :
function setBenefits(){
  if (SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName() == 'VT'){
    benefitsValue()
    discountValue()
    netValue()
  } else {
    app.alert('It must be active on sheet VT')
  }
}

Your function has two problems :

*

*getSheetByName takes a string as an argument ( cf https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getSheetByName(String) )

*even if getSheetByName had sent you a sheet, you can't compare a sheet with a string

A: You should use the onSelectionChange(e) trigger:
To execute a code when switching between different sheets you can instead use onSelectionChange(e).
The following example will execute some code when you switch from a different sheet to VT:
function onSelectionChange(e) {
   const as = e.source.getActiveSheet();
   if (as.getName() == 'VT'){
          benefitsValue();
          discountValue();
          netValue();
   }
}


text:
Q: Did I change the given (very short) assembler instruction correctly? mov 8[+r1], 1337

Edit, after having read the recommended thread of dwelch I get to (assuming I understood it right):
add #8, r1
mov #1337, r2
mov [r1], [r2]
sub #7, r1

Is this correct or did I do mistakes?
Info we had about the assembler:

*

*n[+rx] register indexed with pre-increment; n is index value and rx is register x

*rx register directly addressing

*[rx] register indirect addressing

*#n immediate addressing
We may only use add, sub, mov. Except for r1 we may additionally modify r2 if necessary.
I hope I did it correctly?

A: add #8, r1
mov #1337, r2
mov [r1], [r2]

This doesn't seem to incorporate the pre-increment on the r1 register.
Just add 9 instead of 8.
add #9, r1
mov #1337, r2
mov [r1], [r2]


text:
Q: What causes "Request was aborted after waiting too long to attempt to service your request"? What causes "Request was aborted after waiting too long to attempt to service your request"?
It seems the result of some sort of internal timeout, but I don't know where this is configured.
We're currently using autoscaling, and that error was the result of a temporary increase in the number of tasks in our taskqueue. Shouldn't autoscaling have created more instances to handle that request?
Also, if a task in Cloud Tasks fails with "Request was aborted after waiting too long to attempt to service your request", is that task retried, or is it removed from the queue?
Edit: I found the problem.
This was the configuration for scailing in our app.yaml:
basic_scaling:
  max_instances: 2

A: I found this when I was proxying to view a munin node with many graphs on an f1-micro backend. Responses will fail with a 529 error if they are waiting for longer than (min|max)_pending_latency - probably it is trying to create a new instance, because the minimum is violated, but finds it cannot.
The default appears to be 5s. You can set it in app.yaml to a max of 15s.
automatic_scaling:
  min_pending_latency: 15s
  max_pending_latency: 15s

Once I did that I stopped getting the errors for requests waiting for 6s. Of course, I'm sure Google would prefer you increase the number of scaling instances, or use a faster node. But maybe you only want to scale to one or two, or 15s is an acceptable latency for what you're trying to do.
For reference, my full app.yaml:
runtime: php73
service: munin
instance_class: F1

automatic_scaling:
  max_instances: 1
  min_instances: 0
  target_cpu_utilization: 0.95
  target_throughput_utilization: 0.95
  max_concurrent_requests: 80
  max_pending_latency: 15s

handlers:
- url: .*
  script: auto
  secure: always


text:
Q: Margin top don't work I am trying to set margin top to the inside div ("main") but it's not working, and sometimes it pushed the outside div ("news_wrapper") instead.
Here is the fiddle link: https://jsfiddle.net/g2a9bpnd/
This is the div that need to get the margin top:
#main {
  margin-top:30px;
  background-color: #FFF;
  padding: 0 30px 0 28px;
  border-radius: 4px;
  text-align: left;
  color: #494949;
  border: 1px solid #d0d1d3;
  background-position: center center;
  background-repeat: no-repeat;
  margin: 0px auto;
  width: 150px;
  padding: 23px;
  min-height: 350px;
  height: auto;
}

A: That's because of collapsing margins.

8.3.1 Collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

One option to fix this would be to add overflow: hidden to the element #news_wrapper. In doing so, this will establish a new block formatting context.
Updated Example
#news_wrapper {
  width: 100%;
  width: 600px;
  height: 100%;
  min-height: 800px;
  margin: 0 auto;
  background-color: #34353A;
  overflow: hidden;
}

As a side note, margin: 0px auto was overriding margin-top: 30px.
Either add the margin-top after,
margin: 0 auto;
margin-top: 30px;

..or use the shorthand:
margin: 30px auto 0;

A: You defined margin 2 times
margin-top:30px;

and
margin: 0px auto;

The later definition will override the earlier one so you got no margin
If you need to center do
margin: 30px auto 0 auto;

shorthand
margin: 30px auto 0;

the last auto can be omitted
https://jsfiddle.net/g2a9bpnd/2/
For that pushing issue you are mentioned, that's margin collapsing
http://www.w3.org/TR/CSS2/box.html#collapsing-margins

In CSS, the adjoining margins of two or more boxes (which might or
  might not be siblings) can combine to form a single margin. Margins
  that combine this way are said to collapse, and the resulting combined
  margin is called a collapsed margin.
Adjoining vertical margins collapse, except:
Margins of the root element's box do not collapse.
If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of

following siblings but that resulting margin does not collapse with
  the bottom margin of the parent block.
Horizontal margins never collapse.


text:
Q: Is there a function that gives you index of last char substring in string? The find() function gives you index of first char of substring in string, I need last char.
I tried to get length of substring and sum it to first index but it is going out of bound.
  // if( str2.substr(last char index, str2.find(part3)))

        int sizeOfPart2 = part2.length();
    int sizeOfPart3 = part3.length();
    if(sizeOfPart2 == 1){
        sizeOfPart2 = 0;
    }
    else if(sizeOfPart3 == 1){
        sizeOfPart3 = 0;
    }
   cout<<str2.substr(str2[str2.find(part2) + sizeOfPart2],
   str2.find(part3));

A: You can try to do something like the below helper function I made. It returns the index of the last character of the substring.
Stepwise details:

*

*Find the substring: this gives the index of the first char of the substring.

*If the index is out of bound, return -1 to denote that the substring cannot be found.

*Else if the index is valid, add it to the length of the substring - 1. This is done to get the index of the actual character.

int findLastCharSubstring(std::string text, std::string substring){
    int index = text.find(substring);
    if(index != std::string::npos) // If in bound, return correct index
        return index + substring.length() - 1;
    else // If out of bound return -1, i.e. not found
        return -1;
}

A: You can do something like:
const std::string path = "repeatedstrieang";
std::string mysubstr = "ea";
auto firstCharPos = path.find("ea");
if(firstCharPos!=std::string::npos)
{
    std::cout << firstCharPos + mysubstr.size() -1; //-1 because indexing starts from `0`
}


text:
Q: Images working locally, but not working once deployed on Google App Engine? I have an app.yaml file which looks like this:
application: segmentize
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /css
  static_dir: css

- url: /img(.*\.(gif|png|jpg))
  static_files: img/\1
  upload: img(.*\.(gif|png|jpg))

- url: /
  script: index.app

skip_files:
- ^(.*/)?app\.yaml
- ^(.*/)?app\.yml
- ^(.*/)?index\.yaml
- ^(.*/)?index\.yml
- ^(.*/)?#.*#
- ^(.*/)?.*~
- ^(.*/)?.*\.py[co]
- ^(.*/)?.*/RCS/.*
- ^(.*/)?\..*
- ^(.*/)?dev
- ^(.*/)?old_ver
- ^(.*/)?resources

The images all display fine locally. However, once deployed, they show as broken.
Images in the html are set as follows:
<img src="/img/welcomeimg.png">

Are the images just not uploading when I deploy? What's causing this? The css folder seems to deploy with no issue.

A: Add the slash in the end of the img in the url and in the upload section:
- url: /img/(.*\.(gif|png|jpg))
  static_files: img/\1
  upload: img/(.*\.(gif|png|jpg))


text:
Q: How To Throw customized Block Exception in Java I would like to know that how can i trow customized block exception in java.i will explain it on following example.
@login
//Below code snippet do log in functionality.
mycode goes here

String name="abc";
if name.equals("ABC")
{
  enter to system ...
}

Console Out Put
You have error on log in

@register
//Below code snippet do register functionality.

mycode goes here

let say in @login annotation there is a error from my code.java should  throw it like a good readable way.The exception should be like regular exception and where it generate.i mean code block in this case it is log in.If register it should say u have an error in register code block.
Also i don't declare annotation on top of method.In my case there is no such a method and everything handle the annotations.
as a example
Student Class
class student{
@login
login related codes goes here

@View Result
view result related codes goes here

@logout
logout code goes here

}

As a example you can consider above class as a selenium script.in scripts we don't use any methods.i want to implement back end class(annotations) that gives and meaningful errors on happens in the related code block.(log in,view result,...)
when ever user write a new script he can reuse my annotation.
Actually this is a idea that i wanna implement.Because if i do like that it will be easy for my app users.so I would like to know that can it possible to do and if so how can i do it.If you know another way Please let me know your ideas.Thanks.

A: I'm not convinced I fully understand the question but if you're looking for creating a custom exception, you can do the following:
if name.equals("ABC") {
    // do something
} else {
    throw new CustomException("Name did not equal 'ABC'");
}

where the custom exception is defined as:
public class CustomException extends Exception {

    public CustomException(String msg) {
        super(msg);
    }
}

And then wherever you need to handle the exception, it would look like:
try {
    // do something that might throw a CustomException
} catch (CustomException ce) {
    ce.printStackTrace();
    // or do something more useful to handle the exception
}

And if you go this route, I would call it something other than CustomException, call it something that is relevant to the problem the exception pertains to, for example NameNotEqualException.


text:
Q: flutter add method was called on null using provider Hello I want to add some value to my list. I have already googled for solutions but I can't see any other solutions besides initializing the list which I did.
When I try to add an item to my AutomaticDateList class I get the error:

The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'AutomaticDate')

Here is the class with the list in it.
class AutomaticDateList with ChangeNotifier {
List<AutomaticDate> items = [];  // here I inialize

AutomaticDateList({this.items});

void addToList(AutomaticDate automaticDate) {
items.add(automaticDate);
notifyListeners();
}

 List<AutomaticDate> get getItems => items;
}

This is the item I want to add to the list.
class AutomaticDate with ChangeNotifier {
String date;
String enterDate;
String leaveDate;
String place;

AutomaticDate({this.date, this.enterDate, this.leaveDate, this.place});

Here I call the method using the provider inside a page widget
void onGeofenceStatusChanged(Geofence geofence, GeofenceRadius geofenceRadius,
  GeofenceStatus geofenceStatus) {
geofenceController.sink.add(geofence);
AutomaticDate automaticDateData = AutomaticDate();

automaticDateData.place = geofence.id;
automaticDateData.date = DateFormat("dd-mm-yyyy").format(DateTime.now());
if (geofenceStatus == GeofenceStatus.ENTER) {
  widget.enterDate = DateFormat("HH:mm:ss").format(DateTime.now());
} else {
  automaticDateData.leaveDate =
      DateFormat("HH:mm:ss").format(DateTime.now());
  automaticDateData.enterDate = widget.enterDate;
  widget.list.add(automaticDateData);

  WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    AutomaticDateList automaticDateList =
        Provider.of<AutomaticDateList>(context, listen: false);
    automaticDateList.items.add(automaticDateData); // Here I add the data and get error "add was called on null"
    print(automaticDateList.getItems);
  });
}
}

A: The problem is in the initialization:
List<AutomaticDate> items = [];  // here I inialize

AutomaticDateList({this.items});

You set a default value, but you are using the "auto-assign" sintax in the constructor, saying that items passing in the parameters are going to be assigned in the items property of the class.
You are instantiating the class using this code:
AutomaticDate automaticDateData = AutomaticDate();

So, you are passing "null" implicitly as parameter, then items [] got replaced with null value.
Just change the code to:
List<AutomaticDate> item;

AutomaticDateList({this.items = []}); // Default value


text:
Q: Selective coloration of polynomial parts of rational expressions I'm teaching high school students how to simplify rational expressions by cancelling factors.
The cancelled expressions should be colored red (incl. L /R parenthesis), but not the fraction bar. The image below shows what I've been able to achieve so far and the places where the red color still needs to be applied:

MWE is below. Very much appreciate your assistance (as will my students).
\documentclass[12pt]{exam}

\printanswers
% un-comment to print solutions.
\renewcommand{\solutiontitle}{}

\usepackage{multirow, tabularx}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\usepackage[table]{xcolor}
\usepackage{amsmath}
\usepackage{cancel}
\usepackage{framed}
\usepackage{multicol}
\usepackage{tasks}
\usepackage[a4paper,margin=0.5in,include head]{geometry}

\everymath{\displaystyle}
\setlength\parindent{1em}

\pagestyle{head}
\header{Algebra II Review Ch 3.2: Operations Rational Expressions and Equations: K E Y}
       {}
       {01/13-14/21}

\newcommand{\pagetop}{%
\noindent
  \fbox{\fbox{\parbox{\dimexpr\textwidth-4\fboxsep-4\fboxrule}{
    \textbf {Obj. 3.2.a: I can simplify factored rational expressions and find their restrictions.
    \bigskip
    \bigskipSimplify expression and state the excluded values (+1 pt numerator, +1 pt denominator, +1 pt restrictions.) each equation. Show all work/steps on this page.}
  }}}
  \bigskip
  \vspace{0.5mm}
}

\settasks{after-item-skip=1em,
          after-skip=2cm,
          label-width=2em,
          item-indent=3em,
          label=(\arabic*),
          column-sep=2em
          }
% ------------ DOCUMENT STARTS HERE---------- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

%definition for bigskip = 1 line to replace all \bigskip
\def\bigskip{\vskip\bigskipamount}

\begin{tasks}
[style=enumerate](2)
% Prob #1
\task $\dfrac{10k^2+32k+24}{15k+18}$
\begin{solutionorbox}[5cm]
Factor 2 out of the numerator.\bigskip

$\dfrac{2(5k^2+16k+12)} {15k+18}$\bigskip

The 5 in front of $5k^2$ means this is a non-monic quadratic trinomial. So use the box method to complete the factorization.

\newcommand\mcc[1]{\multicolumn{1}{c}{#1}}
\hspace{1cm}
\renewcommand\arraystretch{2}
\begin{tabular}{ c | c | c | }
  \mcc{} & \mcc{\textcolor{red}{$5k$}} & \mcc{\textcolor{red}{$+6$}} \\
    \cline{2-3}
 \textcolor{red}{$k$} & $5k^2$ & $6$ \\
    \cline{2-3}
 \textcolor{red}{$+2$} & $10k$ & $12$ \\
    \cline{2-3}
\end{tabular}

\vspace{0.2cm}
Numerator factors to $\color{red}\dfrac{(5k+6)(k+2)}{\color{black} 15k+18}$

Now factor the bottom:

\hspace{2cm}$3(5k+6)$
\vspace{0.25cm}

Cancel common factors (this creates a HOLE in the graph):

\hspace{2cm}
$\dfrac{\cancel{(5k+6)}(k+2)}{3\cancel{(5k+6)}}$
\vspace{0.25cm}

Simplified form: $\dfrac{(k+2)}{3}$

\textcolor{blue}{\textbf {Reminder:}}

\textbf{Zeros occur on top} (in the numerator).

\textbf{VA's (vertical asymptotes) are restrictions in the denominator}...to prevent division by $0$.

\textcolor{red}
{Zeros: $k=-2$}

\textcolor{red}
{Holes: $k=-6/5$}

\textcolor{red}
{VA: $none$}

\end{solutionorbox}

\vspace{0.25cm}
% Prob #1
\task $\dfrac{5k^2+10k+24}{6k+12}$
\begin{solutionorbox}[5cm]
step-by-step solution goes here
\end{solutionorbox}
\end{tasks}
\end{document}

A: You mainly need \textcolor{red}{<stuff>} to highlight individual components in red if there is no other scoping available:

\documentclass{article}

\usepackage[table]{xcolor}
\usepackage{amsmath}
\usepackage{cancel}

\begin{document}

Numerator factors to
\[
  \dfrac{\color{red}(5k + 6)(k + 2)}{15k + 18}
\]
Cancel common factors (this creates a HOLE in the graph):
\[
  \dfrac{\textcolor{red}{\cancel{(5k + 6)}}(k + 2)}{3 \textcolor{red}{\cancel{(5k + 6)}}}
\]

\end{document}


text:
Q: Help with installation of ROOT, PATH variable is getting deleted I am trying to install ROOT which I need for work. I run Ubuntu 10.04 64 bit on virtualbox on my laptop. After extracting the tarball, I try to source the .sh file using the command as suggested in the README
$  . pathname/root/bin/thisroot.sh
It shows me the following error:
$ . /home/username/Downloads/root/bin/thisroot.sh

bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash:/home/username/Downloads/root/bin/drop_from_path: No such file or directory
bash: man: No such file or directory
Command 'dirname' is available in '/usr/bin/dirname'
The command could not be located because '/usr/bin' is not included in
the PATH environment variable.
dirname: command not found
/usr/bin/env: bash: No such file or directory
Command 'grep' is available in '/bin/grep'
The command could not be located because '/bin' is not included in the
PATH environment variable.
grep: command not found
Command 'grep' is available in '/bin/grep'
The command could not be located because '/bin' is not included in the
PATH environment variable.
grep: command not found

The result of this is that it somehow deleted the PATH, because now I cannot do anything else from the command line. For example:
$ vi README
Command 'vi' is available in '/usr/bin/vi'
The command could not be located because '/usr/bin' is not included in
the PATH environment variable.
vi: command not found

$ clear
Command 'clear' is available in '/usr/bin/clear'
The command could not be located because '/usr/bin' is not included in
the PATH environment variable.
clear: command not found

I have an Ubuntu 11.04 on my desktop at home, where this installation went smoothly. I also tried this on my office mac, but I don't know what is happening here.

A: If you start a script by sourcing it:
. script

or
source script

its commands are executed in the context of this shell. You don't have to worry about disappearing paths, aliases and such; if you later start another shell, that one will not be affected.


text:
Q: Efficient way to group objects in an Array I have an Array of user defined Objects. Lets say the classy, dogs.
Now I need a way to only look at all brown dogs with spots (both attributes of the Object).
I could create a new array "brown dogs" go through the original array take each dog that has brown fur and pack him in the new array. Then do another array "brown, spotted dogs" and so on you get the idea...
Works but isnt really great.
But I actually need to look at all dogs with each possible color, so all brown dogs in a group, all white dogs etc. And then create further sub groups based on further attributes.
It would be easy in an excel sheet, just filter for brown, and the other attribute, then ran the macro you want, then (by hand) filter to another color, ran code again...
I have a construct in mind that could do that in theory (take value of first attribute, create "already done colors" array, put it in their, go through whole original array, find all with the same color and then do this over and over again for all subsequent attributes) But this would be just very complexe, and hard to maintain. Isnt their an easier and quicker option to only a specific subset of values of the array (brown dogs) and repeat it for all permutations of that attribute?
Maybe this picture helps to illustrate the idea:

The basic challange is: find if the the combination of b-z (in column 2 and 3) exists for each group of column 1.
A human sees quiet quickly that for group "1" (blue) in column 1 there are 2 cases of b-z (Rows 5 and 7) but none for group "2" (green).
A programm would need to find all instances where column one is of the first value ("2") and then find all other rows with this value (rows 2,5 and 6) then for this list check column 2 and 3.
Go to the next row and check if attribute 1 was already used (it wasnt, its "1" in line two and was "2" in line one) and then compare again.
This may be doable for the given example but gets burdensome when you have several stages of grouping. So first group for Attribute one, then for ( a hyphotetical) attribute 4 and attribute 5 and then for this sub group check columns 2 an d 3 values.
Iam now looking for a way to do this "grouping" in a more managable way, is there any option for this?
Code example for what I think is a not so great version for grouping/filtering this:
dim ArrayofObjectInstances() as SpecificObject
dim ArrAlreadyUsedIds() as integer
dim ArrayOfObjectsWithSameID() as SpecificObject

For each element in ArrayofObjectInstances
If not IsinArray(elemnt.ID, ArrAlreadyUsedIds) then

For i = 1 to LenghtOfArray
if ArrayofObjectInstances(i).ID Like element.ID then
'In here I would start the for each and the for loop again for a second Attribute I want to group by, and then again for a third, each time needing more arrays

'fill the "ArrayOfObjectsWithSameID" with the current element (and the first one), then lopp through this array and check 2 Attributes if they are spevific values,
'just to then be able to say, yes the grouping for this ID has at least one instance where the reuirment is meet
end if
next

end if
next element

A: One way to go:
Test class clsTest:
Option Explicit

Public Id As Long
Public Color As String
Public Weight As String
Public Attitude As String

'added this for Debug output
Public Property Get AsString()
    AsString = Join(Array(Me.Id, Me.Color, Me.Weight, Me.Attitude), "~")
End Property

Test code:
Option Explicit

Sub Tester()

    Dim i As Long, obj As clsTest, col As New Collection

    'create a collection of test objects with randomized property values
    For i = 1 To 10
        Set obj = New clsTest
        obj.Id = i
        obj.Color = Array("Blue", "Brown", "Yellow") _
                         (Application.RandBetween(0, 2))
        obj.Weight = Array("Heavy", "Light")(Application.RandBetween(0, 1))

        obj.Attitude = Array("Good", "Bad")(Application.RandBetween(0, 1))

        col.Add obj
    Next i

    DumpNestedDict Classify(col, Array("Color"))

    DumpNestedDict Classify(col, Array("Color", "Weight"))

    DumpNestedDict Classify(col, Array("Weight", "Color", "Attitude"))

End Sub

'Classify a collection of objects according to an array of property names
'Returns a scripting dictionary (nested if >1 property) with objects
'   contained in one or more collections
Function Classify(col, arrProps)

    Dim dict As Object, pv, i As Long, curr As Object, obj As Object

    Set dict = CreateObject("scripting.dictionary")

    For Each obj In col
        Set curr = dict 'start at the top level...
        For i = LBound(arrProps) To UBound(arrProps)
            pv = CallByName(obj, arrProps(i), VbGet) 'get the property value
            If Not curr.exists(pv) Then
                If i < UBound(arrProps) Then 'at the last property?
                    'not at last property, so create a nested dictionary
                    curr.Add pv, CreateObject("scripting.dictionary")
                Else
                    'end of the road is a collection of objects
                    curr.Add pv, New Collection 'end of the road is a collection of objects
                End If
            End If
            If i < UBound(arrProps) Then Set curr = curr(pv) 'one level down in the nesting

            'last property, so add the object itself
            If i = UBound(arrProps) Then
                curr(pv).Add obj
            End If
        Next i
    Next obj

    Set Classify = dict
End Function

'create a text output from a nested dictionary containing collections of objects
'  object must have an "AsString" property
Sub DumpNestedDict(d As Object, Optional level As Long = 0)
    Dim k, v, s, obj
    s = String(level * 3, " ")
    For Each k In d.Keys
        Debug.Print s & "Key:" & k
        If TypeName(d(k)) = "Dictionary" Then
            DumpNestedDict d(k), level + 1
        ElseIf TypeName(d(k)) = "Collection" Then
            For Each obj In d(k)
                Debug.Print String((level + 1) * 3, " ") & obj.AsString
            Next obj
        End If
    Next k
    If level = 0 Then Debug.Print "---------------------------", vbLf
End Sub

Example output:
Key:Yellow
   1~Yellow~Light~Good
   3~Yellow~Light~Bad
   4~Yellow~Heavy~Good
   6~Yellow~Light~Bad
   10~Yellow~Heavy~Good
Key:Brown
   2~Brown~Light~Bad
   7~Brown~Heavy~Bad
   8~Brown~Heavy~Bad
Key:Blue
   5~Blue~Heavy~Bad
   9~Blue~Light~Good
---------------------------

Key:Yellow
   Key:Light
      1~Yellow~Light~Good
      3~Yellow~Light~Bad
      6~Yellow~Light~Bad
   Key:Heavy
      4~Yellow~Heavy~Good
      10~Yellow~Heavy~Good
Key:Brown
   Key:Light
      2~Brown~Light~Bad
   Key:Heavy
      7~Brown~Heavy~Bad
      8~Brown~Heavy~Bad
Key:Blue
   Key:Heavy
      5~Blue~Heavy~Bad
   Key:Light
      9~Blue~Light~Good
---------------------------

Key:Light
   Key:Yellow
      Key:Good
         1~Yellow~Light~Good
      Key:Bad
         3~Yellow~Light~Bad
         6~Yellow~Light~Bad
   Key:Brown
      Key:Bad
         2~Brown~Light~Bad
   Key:Blue
      Key:Good
         9~Blue~Light~Good
Key:Heavy
   Key:Yellow
      Key:Good
         4~Yellow~Heavy~Good
         10~Yellow~Heavy~Good
   Key:Blue
      Key:Bad
         5~Blue~Heavy~Bad
   Key:Brown
      Key:Bad
         7~Brown~Heavy~Bad
         8~Brown~Heavy~Bad
---------------------------

A: Please, test the next code. I tried commenting it in a way to be understandable for somebody not familiar with dictionaries handling:
Sub testDictionariyWay()
 'it needs a reference to 'Microsoft Scripting Runtime'
 'The code may use late binding, but not being experienced in dictionary using, adding this reference
 'you will have access to intellisense suggestions. I will also place a piece of code able to put it automatically...
 Dim sh As Worksheet, arr, arrOb, dict As New Scripting.Dictionary
 Dim i As Long, j As Long, boolExisting As Boolean

 Set sh = ActiveSheet
 arr = sh.Range("A2:C7").value      'put the range to be processed in an array (only to make the code faster and more compact)
 For i = 1 To UBound(arr)
    If Not dict.Exists(arr(i, 2)) Then 'if the attribute does not exist like a dictionary key:
        dict.Add arr(i, 2), Array(arr(i, 1))            'a key is created and an array of one element is placed like its value
    Else
       ReDim arrOb(UBound(dict(arr(i, 2))) + 1) 'redim an array able to keep all precedent array elements, plus one to be added
       For j = 0 To UBound(arrOb) - 1              'iterate between the existing array elements:
            If dict(arr(i, 2))(j) <> arr(i, 1) Then    'check if the object is not already in the array:
                arrOb(j) = dict(arr(i, 2))(j)            'if not, it will be placed in the new array
            Else
                boolExisting = True: Exit For         'if the object already exists, the loop is exited and a boolean variable becomes True
            End If
       Next j
       If Not boolExisting Then                        'if not the object already exist:
            arrOb(j) = arr(i, 1)                           'place the new object in the last array element
            dict(arr(i, 2)) = arrOb                       'add the array as dictionary key value
       End If
       boolExisting = False                              'reinitialize he boolean variable
    End If
    'do the same for the third column:
    If Not dict.Exists(arr(i, 3)) Then
        dict.Add arr(i, 3), Array(arr(i, 1))
    Else
       ReDim arrOb(UBound(dict(arr(i, 3))) + 1)
       For j = 0 To UBound(arrOb) - 1
            If dict(arr(i, 3))(j) <> arr(i, 1) Then
                arrOb(j) = dict(arr(i, 3))(j)
            Else
                boolExisting = True: Exit For
            End If
       Next j
       If Not boolExisting Then
            arrOb(j) = arr(i, 1)
            dict(arr(i, 3)) = arrOb
       End If
       boolExisting = False
    End If
 Next i
'testing the dictionary content. Now, being a strings array, Debug.Print can be used.
'Otherwise, an object will be returned and it should be Set and use one of its attributes to check the code:
 Dim El As Variant
 For Each El In dict("a")
    Debug.Print "a: " & El
 Next El
 For Each El In dict("x")
    Debug.Print "x: " & El
 Next El
End Sub

The next piece of code will automatically add the necessary reference. Please, first run the following code, save the workbook (to keep the reference) and then run the above one:
Sub addScrRunTimeRef()
  'Add a reference to 'Microsoft Scripting Runtime':
  'In case of error ('Programmatic access to Visual Basic Project not trusted'):
  'Options->Trust Center->Trust Center Settings->Macro Settings->Developer Macro Settings->
  '         check "Trust access to the VBA project object model"
  Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\SysWOW64\scrrun.dll"
End Sub

Edited to add a variant involving a class and its instances, to be more elocvent (at least, this is what I hope):

*

*Create a class module, named 'clsFoo' and paste the next code:

Option Explicit

Private pmyName As String
Private pmyColor As String
Private pmyTag As String 'to identify the class Object instance (string) name...

Public Property Get myName() As String
    myName = pmyName
End Property
Public Property Let myName(value As String)
    pmyName = value
End Property
Public Property Get myColor() As String
    myColor = pmyColor
End Property
Public Property Let myColor(value As String)
    pmyColor = value
End Property
Public Property Get myTag() As String
    myTag = pmyTag
End Property
Public Property Let myTag(value As String)
    pmyTag = value
End Property

*Try the next code showing how to create dictionaries for both class properties:

Sub testClassInstancesInDict()
  Dim arrFoo(4), Foo1 As New clsFoo, Foo2 As New clsFoo, Foo3 As New clsFoo, Foo4 As New clsFoo, Foo5 As New clsFoo
  Dim El As Variant, dictName As New Scripting.Dictionary, dictColor As New Scripting.Dictionary, arrClss() As clsFoo, i As Long

  Foo1.myName = "Name1": Foo1.myColor = "red": Foo1.myTag = "Foo1": Set arrFoo(0) = Foo1
  Foo2.myName = "Name2": Foo2.myColor = "black": Foo2.myTag = "Foo2": Set arrFoo(1) = Foo2
  Foo3.myName = "Name1": Foo3.myColor = "green": Foo3.myTag = "Foo3": Set arrFoo(2) = Foo3
  Foo4.myName = "Name4": Foo4.myColor = "black": Foo4.myTag = "Foo4": Set arrFoo(3) = Foo4
  Foo5.myName = "Name1": Foo5.myColor = "white": Foo5.myTag = "Foo5": Set arrFoo(4) = Foo5
  For Each El In arrFoo
    'process dictName dictionary:
    If Not dictName.Exists(El.myName) Then
        dictName.Add El.myName, Array(El)
    Else
        ReDim arrClss(UBound(dictName(El.myName)) + 1)
        For i = 0 To UBound(dictName(El.myName))
            Set arrClss(i) = dictName(El.myName)(i)
        Next i
        Set arrClss(i) = El: dictName(El.myName) = arrClss
    End If
    'process dictColor dictionary:
    If Not dictColor.Exists(El.myColor) Then
        dictColor.Add El.myColor, Array(El)
    Else
        ReDim arrClss(UBound(dictColor(El.myColor)) + 1)
        For i = 0 To UBound(dictColor(El.myColor))
            Set arrClss(i) = dictColor(El.myColor)(i)
        Next i
        Set arrClss(i) = El: dictColor(El.myColor) = arrClss
    End If
  Next

  'test the resulted dictionaries:
  Debug.Print "DictName Name1 key has " & UBound(dictName("Name1")) & " clsFoo objects"
  Debug.Print "DictColor black key has " & UBound(dictColor("black")) & " clsFoo objects"
  Dim j As Long

  'all dictName keys/items. myTag returns the object string name:
  Debug.Print "dictName _________________________"
  For j = 0 To dictName.count - 1
        For i = 0 To UBound(dictName.items(j))
            Debug.Print "KeyName: " & dictName.Keys(j) & vbTab & dictName.items(j)(i).myName & _
                             vbTab & dictName.items(j)(i).myColor & vbTab & dictName.items(j)(i).myTag
        Next i
  Next

  'all dictColor keys/items:
  Debug.Print: Debug.Print "dictColor ________________________"
  For j = 0 To dictColor.count - 1
        For i = 0 To UBound(dictColor.items(j))
            Debug.Print "KeyColor: " & dictColor.Keys(j) & vbTab & dictColor.items(j)(i).myName & _
                          vbTab & dictColor.items(j)(i).myColor & vbTab & dictColor.items(j)(i).myTag
        Next i
  Next
End Sub


text:
Q: best way to use context in fragment i m using fragments in my application. i created one Parent Class called BaseFragment and all other fragment extends this Basefrgment below is the snippet of this Basefragment
BaseFragment.java
public class BaseFragment extends Fragment {
    public MainActivity activity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (activity == null && context instanceof  MainActivity) {
            activity = (MainActivity) context;
        }
    }
}

public void replaceFragment(Fragment fragment, FragmentDetail last) {

    fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    boolean push = true;
    if (Validator.isNotNull(last)) {
        push = false;
    }
    /*if(Validator.isNull(last)){
        transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right);
    }else{
        transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
    }*/
    transaction.add(R.id.frame_container, fragment, fragment.getClass().getName());
    if (Validator.isNull(last) && preferences.getFragmentStack().size() > 0) {
        last = preferences.getFragmentStack().lastElement();
    }
    if (Validator.isNotNull(last)) {
        Fragment f = fragmentManager.findFragmentByTag(last.className);
        if (Validator.isNotNull(f)) {
            f.onPause();
            transaction.remove(f);
        }
    }
    last = new FragmentDetail(fragment.getClass().getName(), getTitle().toString(), preferences.isBack());
    if (preferences.isBack() || preferences.getFragmentStack().size() == 0) {
        if (push) {
            preferences.getFragmentStack().push(last);
        }
    } else {
        while (preferences.getFragmentStack().size() > 1) {
            preferences.getFragmentStack().pop();
        }
        if (!preferences.getFragmentStack().lastElement().className.equals(last.className)) {
            preferences.getFragmentStack().push(last);
        }
    }
    transaction.commitAllowingStateLoss();
    changeNavigationIcon();

//        HWUtil.showToast(this, fragmentManager.getBackStackEntryCount() + "");
    }
and in all other fragment i m using activity as a context,my question is whether it is bad way to access context in this way or whether it creates memory leak.or any other approach for accessing context..any help is appriciated.

A: I think the way you are storing the context is really optimal as with that you will be able to use it within each of your sub fragment instances. Because MainActivity is an instance variable in your fragment, it will be garbage collected when your fragment gets destroyed. And if I'm not mistaken about Activity-Fragment lifecycle, when your activity gets rotated, new fragments will be created and the older fragment instances will get destroyed. So, we're good there too. However, you need to be careful with your context variable declaration:
public MainActivity activity;

This makes it accessible from anywhere. Any class can call something like context = fragIns.activity and save it there. This will be really bad for you because now it holds a reference to that context variable. Now, when your fragment is no longer needed it will not be garbage collected because some other class is holding a reference to one of its variable. You'd find yourself in "memory leak town".
Make sure you hold this variable dearly and its reference is not passed to other classes. Since, its in a super class, you may define it as:
protected MainActivity activity;

This should do the job.

A: the best way is to use getActivity() function inside fragment to access context,
because it will return the instance of the activity  on which fragment is attached.

A: using getActivity() is easy and quick way to get parent activity's context but problem comes when that fragment is detached.
So using it like this inside fragment , imo, will suffice the need of doing it better way....
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mContext=activity;
}

A: To avoid memory problems it's recommended that whenever you use onAttach(Context context) you should use onDetach() as well:
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (activity == null && context instanceof  MainActivity) {
        activity = (MainActivity) context;
    }
}

@Override
public void onDetach() {
    this.activity = null;
    super.onDetach();
}

A: My way:
public class AppManager extends Application {

    private static AppManager mApp;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
    }

    public static Context getContext() {
        return mApp.getApplicationContext();
    }
}

so, anyone wants to get a Context, just using the AppManager.getContext(), except starting a Activity. It is very simple.
In your way,  if the activity restarted, the fragment will automatically create again. In you dont' handle the action of Activty restarted, it is posssible that the Activity have two same Fragment, and one who automatically creating didn't call OnAttch(), will causing NullPointerException.
My solution:
public abstract class BaseTabActivity extends BaseActivity {

    @CallSuper
    protected void initTabs(boolean isRestarted) {
        if (isRestarted) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            if (manager.getFragments() == null)
                return;
            Stream.of(manager.getFragments())
                    .forEach((fragment) -> {
                        if (fragment != null)
                            transaction.remove(fragment);
                    });
            transaction.commit();
            manager.executePendingTransactions();
        }
    }

    public FragmentTransaction getSlideAnimTransaction() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_out_left);
        return transaction;
    }

}


text:
Q: Possible to make flask login system which doesn't use client-side session/cookie? I'm working on a Flask app to be used by a medical client. Their IT dept is so up tight about security that they disable cookies and scripting network-wide.
Luckly, wtf-forms was able to address one of these issues with server-side validation of form input.
However, I'm getting hung up on the login system. I've implemented flask-login, but this apparently requires client-side data as I'm unable to log in when testing in a browser with these features disabled.
Is there any way to create a login with zero client-side data?
Thanks for the help.

A: You can of course do it without cookies. You just have to get the auth on every request.
Here is an example in flask using only Basic HTTP Auth. If you are not using 100% of the time HTTPS, then you should use Digest Auth which is secure.
Update: All links are broken. :(
Just use Flask-HTTPAuth which implements Basic Auth and others: https://flask-httpauth.readthedocs.io/en/latest/
From the website:
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": generate_password_hash("hello"),
    "susan": generate_password_hash("bye")
}

@auth.verify_password
def verify_password(username, password):
    # Or access the DB.
    if username in users check_password_hash(users.get(username), password):
        return username

@app.route('/')
@auth.login_required
def index():
    return "Hello, {}!".format(auth.current_user())

if __name__ == '__main__':
    app.run()

A: With such restrictions as not having zero client side data, you could pass a session token in the GET parameters of every link rendered in the html page.
Or you could create only POST views with a hidden token input (may be more secure indeed).

A: Another approach, which reminds me back to the good-old-days in PHP using trans-sid, would be to pass the session_id in the url and store the session on the backend to prevent the url parameters from getting to large (in case of large session stores).
You can implement this using a combination of the @app.url_defaults and @app.url_value_preprocessor signals, also known as Flask's URL preprocessors.
This depends on your correct use of url_for, because that's where the session id will get appended. Let's do a short proof-of-concept:
@app.url_defaults
def add_session_id(endpoint, values):
    if 'session_id' in values:
        # Allows to manually override the session_id, might not be wanted.
        return
    if g.session_id:
        values['session_id'] = g.session_id

@app.url_value_preprocessor
def pull_session_id(endpoint, values):
    g.session_id = values.pop('session_id', None)

Now, all you need to do is store the session somewhere useful (using for example a DB, or Redis, and set the session_id using g.session_id = session_id_here.
On each subsequent request, g.session_id should be the same session id, because url_for should append ?session_id=yoursessionid to the url. Your authentication should check for the existence of g.session_id and act accordingly.
Note that if your session stays small, you could probably store the whole session in the url parameter instead of an id.

A: Nope.  That's literally impossible over pure HTTP.  HTTP is a stateless protocol, which means that in order to preserve state, the client has to be able to identify itself on every request.
What you might be able to do is HTTP Basic Authentication over HTTPS, then access that Authentication on the server side.


text:
Q: How to retrieve full value as its(big integer value with decimals) as in json format by using java (spring boot)? I am created a rest API in spring boot which consumes third party API response and return the response.
Challenges : Third party API response {"price":123456789123456789123456789.05}
I want to get the "price" from the single object ,So it will return 123456789123456789123456789.05 as expected
Expected Output : 123456789123456789123456789.05
Actual Output : 1.2345678912345679e+26
Note:
The actual output will given as exponential format but i want actual data without exponential.
Code:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- tag::actuator[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- end::actuator[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SampleApplication.java
package com.example.sample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

HelloController.java
package com.example.sample;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloController {
 @Autowired
 RestTemplate restTemplate;

 @RequestMapping("/")
 public double index() throws Exception {
  HttpHeaders headers = new HttpHeaders();
  headers.set("token", "rtp");
  HttpEntity entity = new HttpEntity < String > ("parameters", headers);
  String END_Point_Test_API = "http://localhost:8080/api/test";
  ResponseEntity < String > responseData = restTemplate.exchange(END_Point_Test_API, HttpMethod.GET, entity, String.class);
  //Third party response {"price":123456789123456789123456789.05}
  System.out.println(responseData.getBody());
  String data = responseData.getBody();

  JSONParser parser = new JSONParser();
  JSONObject jsobj = (JSONObject) parser.parse(data);
  //double price =(double)jsobj.get("price");
  double price = Double.parseDouble(String.valueOf(jsobj.get("price")));
  return price;

 }

}

A: The correct way to convert BigDecimal to double is:
((BigDecimal) jsobj.get("price")).doubleValue()
However, you are converting BigDecimal to double. Double has a vast range, but even this range has limits. When you exceed it you will run into conversion problems.
My suggested answer is, do not convert it to double use BigDecimal for your price.

A: To make it clear: as soon as double is used, you have an approximation of the actual value, without defined precision and everything will just be some imperfect repair.
BigDecimal price = (BigDecimal) jsobj.get("price");
System.out.println(price.toPlainString());

This is probably also mentioned in the provided links. toPlainString will avoid using the scientific E-notation.


text:
Q: Limit for a quadratic form in Hilbert Space I was wondering how can I show that given any bilinear form $b$ in an Hilbert space
$$
\lim_{\mathbf{x}\to 0} \frac{b(\mathbf{x}, \mathbf{x})}{||\mathbf{x}||} = 0
$$
I came up with a few ideas in finite dimensions or with non-negative bilinear forms (Cauchy-Schwarz inequality) but I don't know how to tackle the general case yet I'm pretty sure it's easy.
Thank you in advance

A: Consider the operator defined on an orthonormal basis $\{ \mathbf{e}_n \}$ by $N \mathbf{e}_n = n \mathbf{e}_n$. $(\mathbf{x}
,N\mathbf{x})$ is a form on the linear span of $\{ \mathbf{e}_n \}$ but if you take $\mathbf{x}_k = \frac{1}{\sqrt k} \mathbf{e}_k$ then $ \lim_{k \to \infty} \Vert \mathbf{x}_k \Vert = 0$ but $(\mathbf{x}_k,N \mathbf{x}_k)=1$.


text:
Q: How to get order details in paid membership pro wordpress plugin? How to get order details like

invoice number,
Membership Date Of Purchase,
Payment Method,
Card Number Details

In Paid Membership Pro Wordpress Plugin
Here is documentation.
I have tried Following Code.
<?php
 echo "<pre>";
if (is_user_logged_in() && function_exists('pmpro_hasMembershipLevel') && pmpro_hasMembershipLevel()) {
    global $current_user;
    global $wpdb, $pmpro_invoice, $pmpro_msg, $pmpro_msgt;

    $current_user->membership_level = pmpro_getMembershipLevelForUser($current_user->ID);

    echo "<pre>";
    print_r($current_user);

}
echo "</pre>";

?>


text:
Q: When will the iPad get threaded email messages? I use my iPhone and iPad to check emails, and would really like to have the threaded email functionality on my iPad the same as it is on my iPhone? Will this be available in iOS?

A: That's one of the features of iOS 4.2, which will be released in November.


text:
Q: Does EC2 Memory include Memory for OS? Do EC2  instances include the OS memory?
For example a t3.micro is 1 GB memory but a Windows Server OS will use 2GB just sitting there.
The AWS website will let you have t3.micro using Windows server but there would seem to be no point, unless the memory they are charging for doesn't include the memory for the  OS itself.
However, I've been unable to find any documentation to tell me either way.

A: An Amazon EC2 instance is a normal virtual machine.
All the stated resources (CPU, Memory) will be assigned to the VM for use by the operating system and applications running on the operating system.


text:
Q: ffmpeg decode gif got an error: "[gif @ 0000017ea4d9d1c0] cannot decode frame without keyframe" I want to decode gif when pts is greater than a certain period of time.
This is my code:
for(;;){
  ret = av_read_frame(in_ctx, pkt);

  if (ret != 0) {
      printf("av_read_frame errorcode %d \n", ret);
      break;
  }

  if (pkt->pts < av_rescale_q(3.0*AV_TIME_BASE, AV_TIME_BASE_Q, st->time_base)) {
       av_packet_unref(pkt);
       continue;
  }

  if(pkt->stream_index == video_index){
     if (pkt) {
        ret = avcodec_send_packet(codec_ctx, pkt);
        if (ret < 0 && ret != AVERROR_EOF) break;
        while (avcodec_receive_frame(codec_ctx, frame) >= 0) {
             //do something
        }
     }
  }
}

Is there any way to realize this function?
FFmpeg version is 4.3.3.


text:
Q: How to get data from Wordpress website (LAMP stack) to Android app in nearly realtime? I have a Wordpress website with a working order system. Now I want to make an Android app which displays every new order in a list view as soon as the order was made.
The last two days I thought about the following solutions:

*

*Simple HTTP GET requests every 10 seconds

*Websockets

*MySQL binary log + Pusher Link

*Server Sent Events

My thoughts (working with a LAMP stack):

*

*Simple HTTP requests are obviously the most ineffective solution.

*I figured out that websockets and Apache aren't working well together.

*Feels quite hacky and I want to avoid any 3rd party service if I can.

4. Looks like this is the optimal way for me, however there are some problems with Apache/php and Server Sent Events from what I experienced.
I tried to implement a simple demo script but I don't understand why some of them are using an infinite while loop to keep the connection open and others don't.
Here is an example without a loop and here with an infinite loop, also here
In addition to that, when I tested the variant with the infinite loop, my whole page won't load because of that sleep() function. It looks like the whole server freezes whenever I use it.
Does anyone have an idea how to fix that? Or do you have other suggestions?
That is the code that causes trouble (copied from here) and added a missing curly bracket:
<?php

    // make session read-only
    session_start();
    session_write_close();

    // disable default disconnect checks
    ignore_user_abort(true);

    // set headers for stream
    header("Content-Type: text/event-stream");
    header("Cache-Control: no-cache");
    header("Access-Control-Allow-Origin: *");

    // Is this a new stream or an existing one?
    $lastEventId = floatval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
    if ($lastEventId == 0) {
        $lastEventId = floatval(isset($_GET["lastEventId"]) ? $_GET["lastEventId"] : 0);
    }

    echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE
    echo "retry: 2000\n";

    // start stream
    while(true){

        if(connection_aborted()){
            exit();
        }

        else{

            // here you will want to get the latest event id you have created on the server, but for now we will increment and force an update
            $latestEventId = $lastEventId+1;

            if($lastEventId < $latestEventId){

                echo "id: " . $latestEventId . "\n";
                echo "data: Howdy (".$latestEventId.") \n\n";
                $lastEventId = $latestEventId;
                ob_flush();
                flush();

            }

            else{

                // no new data to send
                echo ": heartbeat\n\n";
                ob_flush();
                flush();

            }

        }

        // 2 second sleep then carry on
        sleep(2);

    }
?>

I'm thankful for every advice I can get! :)
EDIT:
The main idea is to frequently check my MySQL database for new entries and if there is a new order present, format the data nicely and send the information over SSE to my android application.
I already found libraries to receive SSEs on android, the main problem is on the server side.

A: Based on your question I think you could implement SSE - Server sent events, which is part of HTML5 standard. It is a one-way communication from server to client. It needs html/javascript and a backend language, e.g PHP.
The client will subscribe on events and when subscription is up and running the server will send any updates from the input data. As standard the update will be visible each 3 seconds. This can be adjusted though.
I would recommend you to first create a basic functioning web-browser-client as a start. When and if it is working as you expect, only then you would judge about the effort of building the client as an app.
You would probably need to add functions on the client-side, such as start/stop the subscription.
My understanding of users not recommending the combination of (server sent events) and Apache is the lack of control how many open connections there are and what would control the continuously need of closing of connections. This could lead to sever server performance problems.
Seems using for example node.js would not cause that problem.
Here are some start link:
MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
Stream Updates with Server-Sent Events:
https://www.html5rocks.com/en/tutorials/eventsource/basics/


text:
Q: How to send image in html formatted email in android? I want to send a html formatted email though my application,
but styles for all tags are not supported while sending email.
here is my Java code:
Intent emailIntent = new Intent(android.content.Intent.ACTION_SENDTO, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Look What I Found!");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
      Html.fromHtml(mMessage)
);
startActivity(emailIntent);`

Here is my html, What I want to send:

"<!DOCTYPE html>   <meta charset="UTF-8"> <title>Document</title>

View this shared article from the Churchill Downs Incorporated Magazine $title. Download the official lifestyle app of Churchill Downs – "Club 1875" to access the elegant world of Thoroughbred racing and the Kentucky Derby. Stay up to date on fashion, food, celebrities and some of the most recognizable names in the industry. Club 1875 is your behind the scenes guide to the most exciting two minutes in sports – whether you're at the track or far away!

  <img src="https://www.twinspires.com/sites/twinspires.com/files/footer-558x278.jpg" style="display: block;width: 558px;height: 278px;" a"

And here is output while I send email:

A: Try this one.
String mailId="yourmail@gmail.com";
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",mailId, null));
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject text here");
// you can use simple text like this
// emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,"Body text here");
// or get fancy with HTML like this
emailIntent.putExtra(
         Intent.EXTRA_TEXT,
         Html.fromHtml(new StringBuilder()
             .append("
Some Content
")
         .append("http://www.google.com")
         .append("
More content
")
         .toString())
     );
startActivity(Intent.createChooser(emailIntent, "Send email..."));


text:
Q: Why is my view not using my EditorTemplates folder for my create action? In my MedicalProductController, I am trying to make my Create and Delete actions able to create and delete multiple objects on one page by passing IEnumerable<ViewModel> to the view. The approach I am using with my Create action worked with my Edit Action in this stack overflow question.  But it is not working with my create action, so I suspect something isn't right.
The problem is that no fields appear on the page.  The page simply says: "Create", "Save" (button), "Back to list" (a clickable link) on that page.  In-between "Create" and "Save" there should be the html editor fields and labels created by MedicalProductViewModel.cshtml shown below.
Here is what my setup looks like.
Create.cshtml
@model IEnumerable<MvcMedicalStore.Models.MedicalProductViewModel>

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>MedicalProduct</legend>
        @Html.EditorFor(m => m)

            <input type="submit" value="Save" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Views\MedicalProduct\EditorTemplates\MedicalProductViewModel.cshtml
@model MvcMedicalStore.Models.MedicalProductViewModel

@Html.HiddenFor(item => Model.ID)

    @Html.LabelFor(item => Model.Name)

    @Html.EditorFor(item => Model.Name)
    @Html.ValidationMessageFor(item => Model.Name)

    @Html.LabelFor(item => Model.Price)

    @Html.EditorFor(item => Model.Price)
    @Html.ValidationMessageFor(item => Model.Price)

    @Html.LabelFor(item => Model.ID)

    @Html.DropDownListFor(item => Model.BrandID, Model.BrandSelectListItem)
    @Html.ValidationMessageFor(item => Model.BrandID)

MedicalProductController.cs
public class MedicalProductController : Controller
{
    private MvcMedicalStoreDb _db = new MvcMedicalStoreDb();

    public ActionResult Index()
    {
        var productList = _db.Products.ToArray();

        var viewModelList = GetMedicalProductViewModelList(productList);
        return View(viewModelList);
    }

    public IEnumerable<MedicalProductViewModel> GetMedicalProductViewModelList(IEnumerable<MedicalProduct> productList)
    {
        var brandList = _db.Brands.ToArray();

        var mapper = new MedicalProductMapper();

        return mapper.MapMedicalProductViewModel(productList, brandList);
    }
    public IEnumerable<MedicalProduct> GetMedicalProductList(IEnumerable<MedicalProductViewModel> viewModelList)
    {
        var mapper = new MedicalProductMapper();

        return mapper.MapMedicalProductList(viewModelList);
    }

    //
    // GET: /MedicalSupply/Create

    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /MedicalSupply/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    //public ActionResult Create(MedicalProduct medicalProduct)
    public ActionResult Create(IEnumerable<MedicalProductViewModel> productViewModelList)
    {
        var productList = GetMedicalProductList(productViewModelList);

        if (ModelState.IsValid)
        {
            foreach (MedicalProduct product in productList)
                _db.Products.Add(product);

            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(productViewModelList);
    }
}

MedicalProductMapper.cs
public class MedicalProductMapper
{

    public IEnumerable<MedicalProductViewModel> MapMedicalProductViewModel(IEnumerable<MedicalProduct> productList, IEnumerable<Brand> brandList)
    {
        var brandSelectListItem = brandList.Select(b => new SelectListItem()
                                                {
                                                    Text = b.Name,
                                                    Value = b.ID.ToString()
                                                });

        var viewModelList = productList.Select(p => new MedicalProductViewModel()
                                {
                                    BrandID = p.BrandID,
                                    //BrandName = brandList.SingleOrDefault(b => b.ID == p.BrandID).Name,
                                    BrandSelectListItem = brandSelectListItem,
                                    ID = p.ID,
                                    Price = p.Price,
                                    Name = p.Name
                                });

        return viewModelList;
    }

    public IEnumerable<MedicalProduct> MapMedicalProductList(IEnumerable<MedicalProductViewModel> viewModelList)
    {
        var modelList = viewModelList.ToArray().Select( viewModel => new MedicalProduct()
        {
            Name = viewModel.Name,
            Price = viewModel.Price,
            BrandID = viewModel.BrandID
        });

        return modelList;
    }
}

EDIT
My edit view is very similar to my create view:
EDIT.cshtml
@model IEnumerable<MvcMedicalStore.Models.MedicalProductViewModel>

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>MedicalProduct</legend>
        @Html.EditorFor(m => m)

            <input type="submit" value="Save" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

A: Your Create() controller method is passing a null to your view, hence the editortemplate doesn't fire.
public ActionResult Create()
{
    return View();
}

If you pass in a new List<>, then it will work like your editor.
public ActionResult Create()
{
    return View(new List<MedicalProductViewModel>() { new MedicalProductViewModel() });
}

Is there a reason why you aren't just passing in a single viewmodel instead of a list? You will be able to use your editor template the same way.
Another thing to note is that it is probably not a good idea to pass in IEnumerable<> as your viewmodel. What if you need to pass other non-MedicalProduct properties to your view?
I would advocate a composite viewmodel instead, like so.
public class EditMedicalProductViewModel
{
    public IEnumerable<MedicalProductViewModel> MedicalProducts { get; set; }
}

public class CreateMedicalProductViewModel
{
    public MedicalProductViewModel MedicalProduct { get; set; }
}

In your edit view you'd do this instead
@Html.EditorFor(m => m.MedicalProducts)

And for your create view you'd do this
@Html.EditorFor(m=> m.MedicalProduct)

In your create method you should create a new medical product
return View(new CreateMEdicalProductViewModel() { MedicalProduct = new MedicalProductViewModel() } );

A: It's not working because your model is a IEnumerable<MedicalProductViewModel>, but your editor template is for a MedicalProductViewModel
You could try this:
<fieldset>
    <legend>MedicalProduct</legend>
    @foreach(var item in Model)
    {
        Html.EditorFor(model => item)
    }

        <input type="submit" value="Save" />

</fieldset>

But this will probably not format the fields quite the way you want, since it will create numerous editors. The easiest method would be to refactor your controller so that it allows editing one record at a time.


text:
Q: FILE is constant or struct or both FILE is

*

*Is a constant?  (think from, it is upper-case) (but I read, FILE is struct type in stdio.h )

*(or) is a structure? If it is structure why it is upper case?

A: FILE is an opaque type. It's typically a struct containing the file descriptor, error flags etc. But C standard says nothing about its internals.
Why do you need to know? You are going to use the standard interfaces and don't need to worry about how it's implemented.
The definition of FILE from C11 standard, §7.21.1 (N1548 draft):

which is an object type capable of recording all the information
  needed to control a stream, including its file position indicator, a
  pointer to its associated buffer (if any), an error indicator that
  records whether a read/write error has occurred, and an end-of-file
  indicator that records whether the end of the file has been reached;

and doesn't provide any further information. So, implementations are free to implement it in any way they see fit.
As an example, this is what the glibc implementation has. But - as I said before - it's an implementation detail and as such you can't rely on it:
struct _IO_FILE {
  int _flags;       /* High-order word is _IO_MAGIC; rest is flags. */
#define _IO_file_flags _flags

  /* The following pointers correspond to the C++ streambuf protocol. */
  /* Note:  Tk uses the _IO_read_ptr and _IO_read_end fields directly. */
  char* _IO_read_ptr;   /* Current read pointer */
  char* _IO_read_end;   /* End of get area. */
  char* _IO_read_base;  /* Start of putback+get area. */
  char* _IO_write_base; /* Start of put area. */
  char* _IO_write_ptr;  /* Current put pointer. */
  char* _IO_write_end;  /* End of put area. */
  char* _IO_buf_base;   /* Start of reserve area. */
  char* _IO_buf_end;    /* End of reserve area. */
  /* The following fields are used to support backing up and undo. */
  char *_IO_save_base; /* Pointer to start of non-current get area. */
  char *_IO_backup_base;  /* Pointer to first valid character of backup area */
  char *_IO_save_end; /* Pointer to end of non-current get area. */

  struct _IO_marker *_markers;

  struct _IO_FILE *_chain;

  int _fileno;
#if 0
  int _blksize;
#else
  int _flags2;
#endif
  _IO_off_t _old_offset; /* This used to be _offset but it's too small.  */

#define __HAVE_COLUMN /* temporary */
  /* 1+column number of pbase(); 0 is unknown. */
  unsigned short _cur_column;
  signed char _vtable_offset;
  char _shortbuf[1];

  /*  char* _save_gptr;  char* _save_egptr; */

  _IO_lock_t *_lock;
#ifdef _IO_USE_OLD_IO_FILE
};

struct _IO_FILE_complete
{
  struct _IO_FILE _file;
#endif
#if defined _G_IO_IO_FILE_VERSION && _G_IO_IO_FILE_VERSION == 0x20001
  _IO_off64_t _offset;
# if defined _LIBC || defined _GLIBCPP_USE_WCHAR_T
  /* Wide character stream stuff.  */
  struct _IO_codecvt *_codecvt;
  struct _IO_wide_data *_wide_data;
  struct _IO_FILE *_freeres_list;
  void *_freeres_buf;
# else
  void *__pad1;
  void *__pad2;
  void *__pad3;
  void *__pad4;
# endif
  size_t __pad5;
  int _mode;
  /* Make sure we don't get into trouble again.  */
  char _unused2[15 * sizeof (int) - 4 * sizeof (void *) - sizeof (size_t)];
#endif
};

A: The C standard is intentionally vague about the exact composition of FILE.
It, or a pointer to it, is merely something that can be passed to and from the various input / output functions of the C standard library.
Occasionally it can be helpful to think of FILE* as a "pointer to a file", but it doesn't have to be that.
(I think the upper-case convention arose back in the 1970s when it was a macro in many early implementations of pre-standardised C).


text:
Q: Sending CSRF Tokens via Postman I'm trying to test my web server's login with Postman. First, I send a GET request to my login url, and I get a CSRF token as a cookie. Then, I make a POST request to that login page, with my username, password, and CSRF token.
My problem is, when I do this in Postman, I get a 403 forbidden error when I try to make that POST request to login. I'm copying the CSRF token received and putting it as one of the POST parameters, and I'm using a valid username and password. Is there anything I'm overlooking here?

A: You need to set it as a header in the request, not in the body. X-CSRFToken is the key and the value is CSRF token from the cookie. This will work if you are using an API framework like Tastypie or Django Rest Framework.
If you are authenticating without an API layer you would need to actually attach the cookie or create one with the CSRF token. This post explains it.

A: Try installing the Postman Interceptor Extension on GoogleChrome. It worked for me.

A: Works for me :
Set in Postman Header :
KEY : Authorization
Value : Token "Your token"


text:
Q: ElasticSearch - multi_match with AND/OR I want to use multi_match across multiple fields in my index.
For example, I have this users index.
Users
id
real_name
contact_name
user_name

These fields are all using the standard analyzer. So I want to search these 3 fields (real_name, contact_name, user_name) and look for users who have both "John" and "Peter" in at least one of those fields.
I know I can use multi_match if I don't need the AND part. Example: only search for John:
{
  "multi_match" : {
    "query":    "john",
    "fields": [ "real_name", "contact_name", "user_name" ]
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#query-dsl-multi-match-query
But how do I do it if I want additional and conditions. Is it possible to do this with multi_match?

A: Use "operator" : "AND":
{
  "query": {
    "bool": {
      "should": [
        {
          "multi_match": {
            "query": "john",
            "fields": [
              "real_name",
              "contact_name",
              "user_name"
            ],
            "type": "cross_fields",
            "operator": "AND"
          }
        }
      ]
    }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#operator-min

A: Try this. John must be present in the real_name or contact_name or user_name.
{
"bool": {
    "should": [
        {
          "multi_match" : {
            "query":      "john",
            "type":       "cross_fields",
            "fields":     [ "real_name", "contact_name", "user_name" ],
            "minimum_should_match": "50%"
          }
        }
    ]
  }
}


text:
Q: Angularjs: not found the form fetched through the ajax call from the server I have a problem to deal with fetching the html through the ajax call. It fetches the template of the add form; but I couldn't find the form fetched from html through the ajax call. So, how can I submit the form with angularJS? Please help me!

And the add.html is:
<form method="post" name="storeEntryForm" class="form-horizontal" data-ng-submit="create(store)" novalidate>

Create Store

                        Name
                        <input type="text" placeholder="Enter name of the store" class="form-control" ng-model="store.name" name="name" required ng-maxlength="50" />

                        Address
                        <textarea placeholder="Enter address" class="form-control" ng-model="store.address" name="address" ng-maxlength="100"></textarea>

                        ISO No.
                        <input type="text" class="form-control" ng-model="store.iso_no" name="iso_no" ng-maxlength="50" />

                <button type="submit" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-default" data-ng-click="cancel()">Cancel</button>

</form>

A: You can find the solution from https://stackoverflow.com/a/23701325. Very similar problem and I guess that is causing reasonably. For further study you can read Javascript prototype chaining from Why form undefined inside ng-include when checking $pristine or $setDirty()? . Hope this will work.
Thanks

A: I've just written a piece of code. You need to surrond the html with from tag and ng-submit directive. The ng-submit will call the function to post the data.
Please check my jsFiddle: http://jsfiddle.net/v9djntf2/
<form ng-submit="sendPost()">
    <input ng-model="NewPerson.Name"/>
    <button type="submit">Send</button>
</form>


text:
Q: Why failed to compile pentaho-kettle-9.0.0.2-R? Why dose the release build fail? Pentaho-kettle-9.0.0.3-R is same problem.
Environmental information:

*

*maven version 3

*jdk 11

*mvn clean install -Dmaven.test.skip=true
 [INFO]
 [INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ kettle-core ---
 [INFO]
 [INFO] --- build-helper-maven-plugin:3.0.0:parse-version (set-doc-version-property) @ kettle-core ---
 [INFO]
 [INFO] --- build-helper-maven-plugin:3.0.0:rootlocation (set-root-dir-property) @ kettle-core ---
 [INFO]
 [INFO] --- license-helper-maven-plugin:1.27:check-license (check-license) @ kettle-core ---
 [INFO] Effective license file is [/usr/src/app/src/pentaho-kettle-9.0.0.2-R/LICENSE.txt]
 [INFO]
 [INFO] --- iterator-maven-plugin:0.5.1:iterator (javascript-dependencies_unpack-dependencies) @ kettle-core ---
 [INFO] ------ (dummy) org.apache.maven.plugins:maven-dependency-plugin:3.1.0:unpack-dependencies
 [INFO]
 [INFO] --- build-helper-maven-plugin:3.0.0:add-resource (add-filtered-resources) @ kettle-core ---
 [INFO]
 [INFO] --- license-helper-maven-plugin:1.27:bundle (bundle-license) @ kettle-core ---
 [INFO] License file [/usr/src/app/src/pentaho-kettle-9.0.0.2-R/LICENSE.txt] will be added to [META-INF/LICENSE.txt]
 [INFO]
 [INFO] --- maven-resources-plugin:3.0.2:resources (default-resources) @ kettle-core ---
 [INFO] Using 'UTF-8' encoding to copy filtered resources.
 [INFO] Copying 90 resources
 [INFO] Copying 1 resource
 [INFO] Copying 1 resource
 [INFO]
 [INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ kettle-core ---
 [INFO] Changes detected - recompiling the module!
 [INFO] Compiling 398 source files to /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/target/classes
 [INFO] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/version/BuildVersion.java: Some input files use or override a deprecated API.
 [INFO] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/version/BuildVersion.java: Recompile with -Xlint:deprecation for details.
 [INFO] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/core/plugins/SupplementalPlugin.java: Some input files use unchecked or unsafe operations.
 [INFO] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/core/plugins/SupplementalPlugin.java: Recompile with -Xlint:unchecked for details.
 [INFO] -------------------------------------------------------------
 [ERROR] COMPILATION ERROR :
 [INFO] -------------------------------------------------------------
 [ERROR] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/core/Result.java:[32,33] package javax.xml.bind.annotation does not exist
 [ERROR] /usr/src/app/src/pentaho-kettle-9.0.0.2-R/core/src/main/java/org/pentaho/di/core/Result.java:[65,2] cannot find symbol
   symbol: class XmlRootElement
 [INFO] 2 errors

Who can help me?

A: Look at main pom.xml like
https://github.com/pentaho/pentaho-kettle/blob/master/pom.xml
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

Use jdk8.
package javax.xml.bind.annotation does not exist because if I ain't mistaken, it is moved to jee with removal from jdk core since jdk9


text:
Q: Why is my python code running twice? Whenever I type "no" for "Would you like to find the area of another shape?" it asks me the question again. Here is my code:-
def calculate_area():
  print "Welcome to the area calculator"
  user= raw_input("Enter the shape you would like to calculate the area of:").lower()

  def restart():
    answer= raw_input( "Would you like to find the area of another shape?('yes' or 'no')")
    if answer=="yes":
      calculate_area()
  def rerun():
    restart()

  if user== "rectangle":
    def calculate_rectangle():
      rect1= int(raw_input("Enter the length of the first side:"))
      rect2= int(raw_input("Enter the length of the second side:"))
      print "The area is:",float(rect1*rect2)
    calculate_rectangle()
    rerun()

  elif user== "square":
    def calculate_square():
      square=int(raw_input("Enter the length of the side:"))
      print "The area is:",float(square**2)
    calculate_square()
    rerun()

  elif user== "triangle":
    def calculate_triangle():
      triangle=int(raw_input("Enter the length of the base:"))
      triangle2=int(raw_input("Enter the height of the triangle:"))
      print "The area is:", float((0.5*triangle)*triangle2)
    calculate_triangle()
    rerun()

  elif user== "trapezoid":
    def calculate_trap():
      trapezoid=int(raw_input("Enter the length of base 1:"))
      trapezoid2=int(raw_input("Enter the length of base 2:"))
      trapezoid3=int(raw_input("Enter the height:"))
      print "The area is:", (float(trapezoid+trapezoid2)/2*float(trapezoid3))
    calculate_trap()
    rerun()

  elif user== "circle":
    def calculate_circle():
      circle=int(raw_input("Enter the radius:"))
      print "The area is:", (float((circle**2)*3.14))
    calculate_circle()
    rerun()

  elif user== "rhombus":
    def calculate_rhombus():
      rhombus1=int(raw_input("Enter the length of diagonal 1:"))
      rhombus2=int(raw_input("Enter the length of diagonal 2:"))
      print "The area is:", (float((rhombus1*rhombus2)/2))
    calculate_rhombus()
    rerun()

  else:
    print "Shape not recognized"
  rerun()

This code is under "def restart" and runs twice whenever I type "no." Why is this happening?

A: You call rerun() twice for every question:
if user== "rectangle":
    # ...
    rerun()

elif user== "square":
    # ...
    rerun()

# all other elif branches each have rerun()

else:
    print "Shape not recognized"
rerun()

You are relying on recursion here, but recursive functions return; when you type in "No", restart() returns to rerun() which returns control to the point where it was called, so in one of your if ... elif ... branches. And after those branches you call rerun() again.
You should not be using recursion in the first place. Use an infinite loop instead:
print "Welcome to the area calculator"

while True:
    user = raw_input("Enter the shape you would like to calculate the area of:").lower()
    # execute their choice
    if user== "rectangle":
        # ...
    # etc.

    else:
        print "Shape not recognized"

    answer = raw_input( "Would you like to find the area of another shape?('yes' or 'no')")
    if answer != "yes":
        break

The break at the end ends the while True loop. If yes is entered, the while loop continues from the top, re-running the whole block.

A: You have a rerun() at the end of your method.
Snippet:
  ...removed...
  else:
    print "Shape not recognized"
  rerun()

A: The last rerun()  should be inside the else statement:
  print ("Welcome to the area calculator")
  user = raw_input("Enter the shape you would like to calculate the area of:").lower()

  def restart():
    answer = raw_input( "Would you like to find the area of another shape?('yes' or 'no')")
    if answer == "yes":
      calculate_area()
  def rerun():
    restart()

  if user == "rectangle":
    def calculate_rectangle():
      rect1 = int(raw_input("Enter the length of the first side:"))
      rect2 = int(raw_input("Enter the length of the second side:"))
      print "The area is: ",float(rect1 * rect2)
    calculate_rectangle()
    rerun()

  elif user == "square":
    def calculate_square():
      square=int(raw_input("Enter the length of the side:"))
      print "The area is: ",float(square ** 2)
    calculate_square()
    rerun()

  elif user == "triangle":
    def calculate_triangle():
      triangle = int(raw_input("Enter the length of the base:"))
      triangle2 = int(raw_input("Enter the height of the triangle:"))
      print "The area is: ", float((0.5 * triangle) * triangle2)
    calculate_triangle()
    rerun()

  elif user == "trapezoid":
    def calculate_trap():
      trapezoid = int(raw_input("Enter the length of base 1:"))
      trapezoid2 = int(raw_input("Enter the length of base 2:"))
      trapezoid3 = int(raw_input("Enter the height:"))
      print "The area is: ", (float(trapezoid + trapezoid2) / 2 * float(trapezoid3))
    calculate_trap()
    rerun()

  elif user == "circle":
    def calculate_circle():
      circle = int(raw_input("Enter the radius:"))
      print "The area is: ", (float((circle ** 2)*3.14))
    calculate_circle()
    rerun()

  elif user == "rhombus":
    def calculate_rhombus():
      rhombus1 = int(raw_input("Enter the length of diagonal 1:"))
      rhombus2 = int(raw_input("Enter the length of diagonal 2:"))
      print "The area is: ", (float((rhombus1 * rhombus2) / 2))
    calculate_rhombus()
    rerun()

  else:
    print "Shape not recognized"
    rerun()


text:
Q: import timboudreau netty-http-client into eclipse? I start working on the open source project netty-http-client(https://github.com/timboudreau/netty-http-client)
and I have cloned netty-http-client and mastfrog-parent, however, when I import those to eclipse, eclipse told me the pom.xml of netty-http-client was wrong for "Non-resolveable parent POM", I have no idea about this, anyone help!

A: You need to add the repositories in which Tim has the mastfrog parent pom artifact.
From the readme:

To use with Maven, add the Maven repo to your project as described here. Then add groupId com.mastfrog artifactId netty-http-client to your POM file.

Just add
<repositories>
<repository>
    <id>timboudreau-builds</id>
    <name>timboudreau.com builds</name>
    <url>http://timboudreau.com/builds/plugin/repository/everything/</url>
    <releases>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
    </releases>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
    </snapshots>
</repository>

to your project's pom.xml
(I'd actually change that "updatePolicy=never" to something more sensible, however).

A: I  have worked it out.
It should install(mvn install) the parent pom in this url https://github.com/timboudreau/mastfrog-parent


text:
Q: How to check ajax return value I have an ajax call and it retunrs some value. Now i need to check the value in javascript. How  can i do it
$('#cm').blur(function () {
     var cmnumber = document.forms['myform']['cm'].value;
     $.ajax({
         type: 'get',
         url: "/validatecm/" + cmnumber,
         cache: false,
         asyn: false,
         data: cmnumber,
         success: function (data) {
             alert(data)

         },
         error: function (data) {
             alert(data)

         }
     })

 });

Now i need to access the "data" in my javascript submitformfunction. Any help wil be appreciated

A:  success: function(data) {
      console.log(data);
     useInAnotherFunction(data);

 }

 function useInAnotherFunction(data)
 {
  ...use here
 }

If you use  console.log(data); you can view clearly data what you have

A: You are already accessing the data here
alert(data)

If you still want to access it outside your success callback then make it like this
success: function(data) {
         YourFunctionCall(data)

    }


text:
Q: Javascript Date Object Assignment My Javascript assignment this week involves the Date Object. So far i have the following done and it works:
var monthArray = new Array("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December");
var weekDaysArray =new Array("Sun", "Mon", "Tues", "Weds", "Thurs", "Fri");
var reqMonth = prompt("Please enter the number of the month you want to display");
reqMonth = parseInt(reqMonth);

var todaysDate = new Date();
var currYr = todaysDate.getFullYear();
var currMon = todaysDate.getMonth();
var currDate = todaysDate.getDate();
var currDay = todaysDate.getDay();

while((reqMonth == null)||(reqMonth > 12))
{
    reqMonth =  prompt("Please enter a number between 1 and 12, corresponding with the month you want to display");
    reqMonth = parseInt(reqMonth);
}

document.write((currMon + 1) + "/" + currDate + "/" + currYr +
"
" + "
" + monthArray[reqMonth-1] + " " + currYr);

This is where things get difficult, at least for me the rest of the assignment is:

*For each week, use a document.write statement to display this message above the days of the
week and date: "Week x of month:" where x is a variable used to keep track of the weeks
processed, starting at 1 and month is the name of the month that is extracted from the
monthArray using the month number in the variable reqMon.

*Determine the name of the first day of the requested month.
a. Using the correct Date Object method, get the integer for the day of the week for the first
day of the current month.
(hint 1: you will need to pass the year, month and the day value of 1 to the Date Object
to get this number
hint 2:you will use this number to start extracting the names of the day from the array of
day names, then you will reset it to 0 before starting the next week. )

*Use a document.write statement to display every day of the current month on a new line in the
format of the name of the day followed by the integer for the date. See example on page 1.
a. Use loops to keep track of the number of days written for the month
b. Use loops to write out the days of the week from the array created in step 2 under the
name of the requested month and year. (hint: you will need to execute this loop once for
each week in the month)

The end output hast to be like this:
    11/21/2014 (Current Date)
    November 2014 (Month selected from prompt)
Week 1 of November
Sat 1
Week 2 of November
Sun 2
Mon 3
Tue 4

etc….until all days in the month are displayed.
Would I use the Date object I have already instructed to do step 6? Or a whole other one?


text:
Q: Divergence theorem: 2 different results Given the vector field  $\vec a(r, \theta, \phi) = \frac3r \vec e_r = \frac3r \begin{pmatrix} \cos(\phi) \sin(\theta) \\ \sin(\phi) \sin(\theta) \\ \cos(\theta)\end{pmatrix}$, I have to calculcate the flux through a sphere with radius R.
To do this, I want to apply divergence theorem:
$ \int_V\nabla \cdot \vec a = \int_A \vec a \cdot d\vec f  $
Applying the right side of the equation above gives me $12\pi R$, but the left side gives me $0$.
$\nabla \cdot \vec a = \frac{3}{r^2}\cos(\phi)\sin(\theta) + \frac{6}{r^2}\sin(\phi)\cos(\theta)$
Thus, if you calculate $\int_0^{2\pi}d\phi$ in the volume integral you receive $0$ since $\int_0^{2\pi} \sin(x) dx= \int_0^{2\pi} \cos(x) dx = 0 $
Where is my mistake?