text:
Q: Gold tag badge holders can unilaterally re-open a question they asked, closed as duplicate by a moderator. Is this expected? As a moderator on a site, I closed a question as duplicate of another question asked by the same user. It happened that the question was using a tag for which I have a gold tag badge. Since the user who asked the question has the same gold tag badge, the user was able to unilaterally re-open the question.
Is this working as expected? Should not a question closed by a moderator require another moderator, or more users to re-open?

A: If someone else has a gold tag badge that works for that question, they can always override your duplicate decision with the click of a button, whether you also had the badge or not and regardless of your status as a moderator. That's what they're trusted to do - single-handedly close and/or reopen a question using that tag.
However, as a moderator, you do still have slightly more power than they do. You have the ability to close the question again if you truly feel the need to do so. As a regular user though, they are still limited to only casting one reopen vote in the lifetime of that question. They wouldn't be able to reopen it on their own again. The dupehammer may be a useful and powerful tool, but you can only wield it once per question (well, twice since technically you could use it for both a close and a reopen).
As far as a user being able to use the dupehammer on their own question, it has been discussed before but it's not seen as a pressing problem at the moment.


text:
Q: Asymptotic distribution of sample mean of the sum of two poisson distribution I'm trying to calculate the asymptotic distribution of the sample mean of the sum of two Poisson distributions.
Sample 1 is of size N1, and is from a Poisson distribution with expectation $\mu_1$.
Sample 2 is of Size N2, and is from a Poisson distribution with expectation $\mu_2$.
Now, I was able to derive that when $N_1 \uparrow \infty$, and $N_2 \uparrow \infty$ at the same rate, the sample mean of the sum of two samples will be $\frac{(N_1 \cdot \mu_1 + N_2 \cdot \mu_2)}{N_1 + N_2}$.
From here, I'm having trouble deriving the standard deviation of the asymptotic distribution of the sample mean. How would I go about it?

A: I'm going to introduce some notation to hopefully clear things up.
Let $X_1,X_2,\dots,X_{N_1}$ be the samples from the first Poisson distribution, which are independent, and let $S_{N_1}$ be their sum. Let $Y_1,Y_2,\dots,Y_{N_2}$ be the samples from the second Poisson distribution, which are also independent (and independent of the $X_i$'s), and let $T_{N_2}$ be their sum. The $X_i$'s all have mean and variance $\mu_1$ and the $Y_i$'s all have mean and variance $\mu_2$.
The sample mean is then the random variable:
$$\frac{X_1+\cdots+X_{N_1}+Y_1+\cdots+Y_{N_2}}{N_1+N_2} = \frac{S_{N_1}+T_{N_2}}{N_1+N_2}.$$
You have found the mean of the sample mean (not the sample mean, which is again a random variable) to be
$$E\left[\frac{X_1+\cdots+X_{N_1}+Y_1+\cdots+Y_{N_2}}{N_1+N_2}\right]=\frac{E[S_{N_1}]+E[S_{N_2}]}{N_1+N_2}=\frac{N_1 \mu_1+N_2\mu_2}{N_1+N_2}.$$
To find the standard deviation of the sample mean, first find the variance. The two facts you need to use are:

*

*$\text{Var}(aX)=a^2\text{Var}(X)$ for any constant $a$ and random variable $X$.

*If $X$ and $Y$ are independent, then $\text{Var}(X+Y)=\text{Var}(X)+\text{Var}(Y)$.

Thus,
\begin{align*}
\text{Var}\left(\frac{X_1+\cdots+X_{N_1}+Y_1+\cdots+Y_{N_2}}{N_1+N_2}\right) &=\left(\frac{1}{N_1+N_2}\right)^2\text{Var}(X_1+\cdots+X_{N_1}+Y_1+\cdots+Y_{N_2})\\
&=\cdots (\text{use fact 2 now})
\end{align*}
I'll let you finish from here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Animating UIImageView from an array of images - Swift I'm trying to make a ImageView animate from a PNG-Sequence. However, in the line "imageList = UIImage(named: imageName)" I get an error which states the following: Missing argument for parameter 'inBundle' in call.
class ViewController: UIViewController {

@IBOutlet weak var myImageView: UIImageView!
var imageList = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    startAnimation()

    for i in 0...120
    {

        let imageName = "\(i)"
        imageList = UIImage(named: imageName)

    }

}

@IBAction func generate(sender: AnyObject) {

     tabBarController?.selectedIndex = 1

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func startAnimation() -> Void
{
    myImageView.animationImages = imageList
    myImageView.startAnimating()
}
}

Been Googling to fix this for hours, but can't seem to find anything that works. It is the same code as in this tutorial: https://www.youtube.com/watch?v=PSny6un3VUw


text:
Q: How to use Varray or cursor or any other array in decode function to compare the values I want to compare the last_name values in emp_x table, name column for first 3 character if match any of the records then i want to return that value from emp_x table.
Below is my tables and records:
select substr(x.last_name,1,3) from employee x;

Mathews
Smith
Rice
Black
Green
Larry
Cat

select * from emp_x;

Mataaa
Mmitta
Smitta
Riceeeee

Expected Result:
select decode(substr(x.last_name,1,3), substr(x.last_name,1,3), (select name from emp_x y where y.name like substr(x.last_name,1,3)||'%'),x.last_name) from employee x;

Mataaa
Smitta
Riceeeee
NULL
NULL
NULL
NULL

I am getting the exact result but is there any other best way to use it in pl/sql procedure.
say for example, I am taking the 'Mathews' last_name value from employee table and read the first 3 digit and comparing in emp_x table and getting the Mataa value as result in the decode function above.
Instead of selecting values from table can we use any array or cursor to compare and get the values from varaible in pl/SQL Procedure...
Please help to resolve this..

A: I know this code is not the best solution, it's sort of work(ish) in nature. Anyways I wrote it to just pass some time at work, and I hope even if its not the complete solution, you get an idea regarding what you wanna achieve
DECLARE
CURSOR c1 IS select substr(x.last_name,1,3) from employee x;
c1_rec c1%ROWTYPE;
CURSOR c2 IS select * from emp_x;
c2_rec c2%ROWTYPE;
l_name employee.last_name%TYPE;
BEGIN
FOR c1_rec IN c1
LOOP
FOR c2_rec IN c2
LOOP
IF(c1_rec.last_name == c2_rec.name) THEN
SELECT last_name into l_name from EMPLOYEE where substr(last_name,1,3) = c1_rec.last_name;
dbms_output.put_line(l_name);
ELSE
dbms_output.put_line("NULL");
END IF;
END LOOP;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line("exception occured");
END;

A: I would rather stick with this approach:
SQL> with employee as
  2   (select 'Mathews' name from dual
  3    union all
  4    select 'Smith' from dual
  5    union all
  6    select 'Rice' from dual
  7    union all
  8    select 'Black' from dual
  9    union all
10    select 'Green' from dual
11    union all
12    select 'Larry' from dual
13    union all
14    select 'Cat' from dual),
15  emp_x as
16   (select 'Mataaa' pattern from dual
17    union all
18    select 'Mmitta' from dual
19    union all
20    select 'Smitta' from dual
21    union all
22    select 'Riceeeee' from dual)
23  select nvl(ex.pattern, 'NULL') result
24    from employee e
25    left outer join emp_x ex
26      on substr(ex.pattern, 1, 3) = substr(e.name, 1, 3);

RESULT
--------
Mataaa
Smitta
Riceeeee
NULL
NULL
NULL
NULL
7 rows selected

You didn't provide any information about how big are your tables, but anyway hash join in this query would be much faster then any procedural code. Of course if you need to use it in some procedure you could wrap it in cursor:
for c1 in (select ...)
loop
 dbms_output.put_line(c1.result);
end loop;

A: This can be used for comparing collections using cursors:
declare
cursor c1 is
select last_name ls from empc;
type x is table of employees.last_name%type;
x1 x := x();
cnt integer :=0;
begin
for z in c1 loop
cnt := cnt +1;
x1.extend;
x1(cnt) := z.ls;
if x1(cnt) is  NULL then
DBMS_OUTPUT.PUT_LINE('ASHISH');
end if;
dbms_output.put_line(cnt || ' '|| x1(cnt));
end loop;
end;


text:
Q: Recode numeric values in R I want to recode some numeric values into different numeric values and have had a go using the following code:
survey$KY27PHYc <- revalue(survey$KY27PHY1, c(5=3, 4=2,3=2,2=1,1=1))
I get the following error:
## Error: unexpected '=' in "survey$KY27PHYc <- revalue(survey$KY27PHY1, c(5="

Where am I going wrong?

A: This function does not work on numeric vector. If you want to use it, you can do as follows:
 x <- 1:10 # your numeric vector

 as.numeric(revalue(as.character(x), c("2" = "33", "4" = "88")))

 # [1]  1 33  3 88  5  6  7  8  9 10

A: Try this:
#sample data
set.seed(123); x <- sample(1:5, size = 10, replace = TRUE)

x
# [1] 2 4 3 5 5 1 3 5 3 3

#recode
x <- c(1, 1, 2, 2, 3)[ x ]

x
# [1] 1 2 2 3 3 1 2 3 2 2

A: We can recode numeric values by using recode or case_when on dplyr 0.7.0.
library(dplyr)
packageVersion("dplyr")
# [1] '0.7.0'

x <- 1:10

# With recode function using backquotes as arguments
dplyr::recode(x, `2` = 20L, `4` = 40L)
# [1]  1 20  3 40  5  6  7  8  9 10

# Note: it is necessary to add "L" a numerical value.
dplyr::recode(x, `2` = 20, `4` = 40)
# [1] NA 20 NA 40 NA NA NA NA NA NA
# Warning message:
# Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default

# With recode function using characters as arguments
as.numeric(dplyr::recode(as.character(x), "2" = "20", "4" = "40"))
# [1]  1 20  3 40  5  6  7  8  9 10

# With case_when function
dplyr::case_when(
  x %in% 2 ~ 20,
  x %in% 4 ~ 40,
  TRUE ~ as.numeric(x)
)
#  [1]  1 20  3 40  5  6  7  8  9 10


text:
Q: Birthday problem modified: Expected number of birthdays Given there are N people in one room and let us assume that they are born randomly on one of x(=365) days in the year. What is the expected number of different birthdays for N people?
Edit:
I think the solution should be x-x(1-1/x)^n since (1-1/x)^n is the prob. that no-one has their birthday on a specific day and since all days are the same we should be able to multiply this probability with the number of days to get the expected number of "no birthday" days.

A: Hint: Let $X_1, X_2,\dots, X_{365}$ be indicator random variables taking value $1$ if their respective day of the year is the birthday of at least one of the $N$ people and $0$ otherwise.
How can we rephrase the meaning of the random variable $X=X_1+X_2+X_3+\dots+X_{365}$ in more natural language?

 $X$ is the random variable denoting the number of distinct birthdays seen amongst our $N$ people.

If we were to look at $E[X]$, noting its relation to $X_1,X_2,\dots,X_{365}$, how can this help us for our problem?

 $E[X] = E[X_1+X_2+\dots+X_{365}]=E[X_1]+E[X_2]+\dots+E[X_{365}]$ by linearity of expectation.

What more is left to complete the problem?

 Calculate $E[X_i]$, notice the symmetry of the scenario, and complete the necessary arithmetic.


text:
Q: Is "overflow" a historical term, or does physical overflowing really still happen? I believe that during arithmetic overflow (in the context of an integer variable being assigned a value too large for it to hold), bits beyond the end of the variable could be overwritten.
But in the following C++11 program does this really still hold? I don't know whether it's UB, or disallowed, or implementation-specific or what, but when I take the variable past its maximum value, on a modern architecture, will I actually see arithmetic overflow of bits in memory? Or is that really more of a historical thing?
int main() {
   // (not unsigned; unsigned is defined to wrap-around)
   int x = std::numeric_limits<int>::max();
   x++;
}

A:
I don't know whether it's UB

It is undefined, as specified in C++11 5/4:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

(As you say, it is defined for unsigned types, since they are defined by 3.9.1/4 to obey modular arithmetic)

on a modern architecture, will I actually see arithmetic overflow of bits in memory?

On all the modern architectures I know of (x86, ARM, 68000, and various DSPs), arithmetic is modular, with fixed-width 2s-complement results; on those architectures that can write the result to memory rather than registers, it will never overwrite more memory than the result size. For addition and subtraction, there is no difference to the CPU between signed and unsigned arithmetic. Overflow (signed or unsigned) can be detected from the state of CPU flags after the operation.
I could imagine a compiler for, say, a 32-bit DSP that tried to implement arithmetic on 8 or 16-bit values packed into a larger word, where overflow would affect the rest of the word; however, all compilers I've seen for such architectures just defined char, short and int to be 32-bit types.

Or is that really more of a historical thing?

It would have happened on Babbage's Difference Engine, since "memory" is a single number; if you partition it into smaller numbers, and don't insert guard digits, then overflow from one will alter the value of the next. However, you couldn't run any non-trivial C++ program on this architecture.
Historically, I believe some processors would produce an exception on overflow - that would be why the behaviour is undefined.

A: The content of addresses almost never really "overflowed". For example we would expect primitive integers to roll over their values. See http://www.pbm.com/~lindahl/mel.html.
I think overflow is when the pointers move beyond their desired limits so that you have pointers that point to unexpected places.

He had located the data he was working on near the top of memory --
  the largest locations the instructions could address -- so, after the
  last datum was handled, incrementing the instruction address would
  make it overflow. The carry would add one to the operation code,
  changing it to the next one in the instruction set: a jump
  instruction. Sure enough, the next program instruction was in address
  location zero, and the program went happily on its way.

A: Personally, I have never seen an architecture where overflow would cause memory outside the variable to be overwritten.
I think you should read overflow as you leave a domain that is well defined (like the positive values of a signed integer) and enter one that is not well defined.
Concretely, lets take the max short value, 0x7FFF. If you add one to it you get 0x8000. This value has different meaning depending on if you use one-complement or two-complement negative numbers, both of which are allowed by the C standard.

A: It still happens. With floating point arithemitic it is sometimes necessary to ensure that the caluculations are dcarried out in the right order to ensure that this event is unlikely to happen. (also it can reduce rounding errors!)

A: There are two main overflows in Computer buisness
Arithmetic overflow: like in your example which is defined and needed for work
Negativ example:
int a = std::numeric_limits<int>::max()/2;
int b = a + a + 3; // b becomes negativ and the plane crashes

Positiv example:
double a = std::numeric_limits<double>::max()/2;
double b = a + a + 3; // b becomes Inf and it is determined

Thats how the overflow is defined for Processor integer and floatingpoint units and it will not go awayand has to be handled.
Memory Overflow: Still happens if things do not match like

*

*memory size

*calling conventions

*data type size of client server

*memory alignment

*...

A lot of security issues are based on memory overflow.
Read wikipedia for more facets of overflows:
http://en.wikipedia.org/wiki/Overflow


text:
Q: Bash Recursive Function Call on all elements in a directory First post on StackOverflow, first time using Bash.
I'm currently trying to construct a function to read a file, then give me out put depending on the status:

*

*If it's a file, then print the name, size and type

*If it's a symbolic link, then print the name and it's target

*If it's a directory, then recursively call the function on each item.

*Otherwise return 'unknown'

I know the code is rough so far, but all I really need help with is the recursive looping part. How do I loop through the contents of a directory using a While Loop?
Here's my code so far:
#!/bin/bash

function fileChecker f  {

    if [-e $1 ]; then
        if [ -f $1]; then
            SIZE = 'du -k $1 | cut -f1'
            CONTENT = 'file $1 | cut -d':' -f2'
            echo $1 +" " +  $SIZE + " " + $CONTENT
    elif[ -h $1 ]; then
        LINK = get info from $1
        echo $1 + " " + "symbolic link " + $LINK
    elif [ -d $1 ]; then
        while  [ ???? ]; do
            fileChecker n
        do
    else
        echo $1 + "unknown"
    fi
fi
}

Thanks in advance!

A: There's nothing stopping you to call your function recursively, like this:
fileChecker() {
    # ...
    for f in "$1"/*; do
        fileChecker "$f"
    done
}

Here's your script with a few fixes (*), behaving as described:
#!/bin/bash
fileChecker() {
    if [ -f "$1" ]; then
        size=$(du -k "$1" | cut -f1)
        content=$(file "$1" | cut -d':' -f2)
        echo "$1 $size $content"
    elif [ -h "$1" ]; then
        link=$(readlink -f "$1")
        echo "$1 symbolic link $link"
    elif [ -d "$1" ]; then
        for f in "$1"/*; do
            [ -e "$f" ] || [ -h "$f" ] && fileChecker "$f"
        done
    else
        echo "$1 unknown"
    fi
}

(*) Fixes:

*

*correct spacing before and after [ command

*correct quoting of variables ("$1")

*omitted redundant checking of file existence, since -f already checks if file exists (and is regular)

*using command substitution $(cmd ...) instead of backticks (simpler and more readable)

*string concat fixed in echo

*using readlink -f for symlink target

*POSIX-compliance (function definition)

Just note that for f in "$1"/* will not loop over filenames starting with a dot ("hidden files"). Also note the [ -e "$f" ] || [ -h "$f" ] check before a call to fileChecker to prevent calling it on "$1"/* in case the glob does not expand (when there are no files in dir "$1").


text:
Q: Can't Authenticate with Local .NET back-end I've followed the guide:
Getting Started with Authentication with Mobile Services .NET for Windows Store
I'm able to run the service locally as long as I don't need to authenticate the user. I can also authenticate the user if I publish the service to Azure. But I want to be able to test and authenticate the user locally. How can this be done?
I'm using Live ID and I have the correct ClientID and ClientSecret set in the Web.config. When I attempt to call LoginAsync from the client the call fails with The request could not be completed.  (Method Not Allowed)
** Update 2014-03-20 **
Based on the comments of Carlos and Henrik, I've updated my local service to look exactly like my server instance. I followed Scot Hanselmans excellent guide and now I have my service running locally on port 80 and port 443 with a completely valid SSL certificate. It's even running on the exact same https://xxxx.azure-mabile.net hostname.
With these changes, there is now no configuration difference whatsoever between running the app against my local machine or running it against Azure. I can go to https://xxxx.azure-mabile.net in the browser, get redirected to Live login, sign in, and get redirected back to the service successfully. In the browser it all works. However it still doesn't work in the app.
I attached the debugger, set CLR errors to "break when thrown" and I managed to trap the exception in the service. Here's what I see in the immediate window:

The Response property is not helpful. It does not provide any additional information about the problem.
The only thing that stands out to me is that the app is trying to do a POST to /login/microsoftaccount while the browser would normally be doing a GET at this address (then getting redirected).
** Update #2 2014-03-20 **
After following Henriks guide for remote debugging I was able to load symbols and get a tiny bit more information:
"An existing connection was forcibly closed by the remote host"
The error code is 10054 (WSAECONNRESET) Connection reset by peer.
It appears the Live Authentication server may be forcibly terminating the connection, but only when I'm authenticating with the app. Again, authentication within the browser is fine. This, combined with the fact that /login/microsoftaccount is a POST from the app seems to suggest there is a problem with the authentication token I'm getting back from LiveClient.LoginAsync. I'll do some more digging...

A: At the moment, it is set up so that you don't need authentication when running locally and access the service from localhost. In this case, anonymous access is let through (this is of course disabled while running in the cloud).
We don't really have a way for your to authenticate locally as redirect URIs won't work (they can't point to localhost as there is not way that Facebook, say, can resolve "localhost").
One option is that we somehow can mock the authentication locally and give you a token without connecting with the various identity providers. I am not sure exactly what that would look like but it is something we can consider.
Henrik

A: Did you perhaps set Mobile client app: Yes in your Live Connect project? I think that setting is meant to be used with the Live Connect SDK (client) flow, not the browser-based (server) flow. The client flow isn't supported yet with a .NET backend.
You also want to make sure you are using LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount) on the client to trigger the server flow.


text:
Q: ReorderbleList with Draggable Widgets does not work I have a ReorderdableList with 5 Widgets and each of them is Draggable.
The Draggable Widget works great, but it seems that this makes the onReorder function not work.
This is my ReorderableListView:
return Scaffold(
      body: ReorderableListView(
        onReorder: ((oldIndex, newIndex) {
          print('onReorder');
        }),
        onReorderStart: (index) => print('reorder start'),
        scrollDirection: Axis.horizontal,
        children: [
          for (final card in handCards)
            HandCard(key: ValueKey(card), card, player, handOwner),
        ],
      ),
    );

Each Handcard returns a Draggable Widget. Is there a way to make sure both still work?
Handcard Widget:
class HandCard extends ConsumerStatefulWidget {
  HandCard(this.card, this.player, this.handOwner, {Key? key})
      : super(key: key);
  String handOwner;
  dynamic card;
  Player player;
  @override
  _HandCardState createState() => _HandCardState();
}

class _HandCardState extends ConsumerState<HandCard> {
  @override
  void initState() {
    isVisibled = true;
    // TODO: implement initState
    super.initState();
    print(isVisibled);
  }

  void setVisible() {
    setState(() {
      isVisibled = true;
    });
  }

  late bool isVisibled;
  @override
  Widget build(BuildContext context) {
    var handCardPickProvider =
        ref.watch(handCardHighlightProvider(widget.card).notifier);
    var handCardPick = ref.watch(handCardHighlightProvider(widget.card));
    var gameStateProvider = ref.watch(GameStateProvider);
    var handSize = ref.watch(handSizeProvider(widget.handOwner).state);
    return Draggable<HandCard>(
      onDragStarted: () {
        // change state of current cards in hand
        handSize.state = handSize.state - 1;
      },
      onDragEnd: (details) {
        handSize.state = handSize.state + 1;
      },
      onDragCompleted: () {
        setState(() {
          isVisibled = true;
        });
      },
      data: widget,
      childWhenDragging: SizedBox.shrink(),
      feedback: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(widget.card.imageLink),
            fit: BoxFit.fill,
          ),
        ),
        width: 100,
        height: 150,
        child: Stack(children: [
          (widget.card is CharacterCard)
              ? Positioned(
                  right: 0,
                  left: 60,
                  child: Container(
                    color: Colors.white,
                    width: 40,
                    height: 13,
                    child: Center(
                      child: Text(
                        widget.card.power.toString(),
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 10,
                            fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                )
              : const SizedBox.shrink(),
          Positioned(
              left: 2,
              child: Container(
                width: 20,
                height: 20,
                decoration: BoxDecoration(
                  color: Colors.red,
                  shape: BoxShape.circle,
                ),
                child: Center(
                    child: Text(
                  widget.card.cost.toString(),
                  style: TextStyle(color: Colors.white, fontSize: 12),
                )),
              ))
        ]),
      ),
      child: (isVisibled)
          ? InkWell(
              onTap: () {
                print('click');

                // If it is the counter move and the card has a counter effect we can use it
                if (gameStateProvider.gameSession!.moves.length != 0) {
                  Move currentMove = gameStateProvider.gameSession!
                      .moves[gameStateProvider.gameSession!.atMove - 1];
                  print(currentMove.moveType);
                  // Handle on counter effect
                  if (currentMove.moveType == 'on counter effect' &&
                      currentMove.toPlayer.id == widget.player.id) {
                    handCardPickProvider.highlightCard(widget.card);
                  }
                }
              },
              child: Container(
                margin: EdgeInsets.all(1),
                decoration: BoxDecoration(
                  boxShadow: [
                    (handCardPick)
                        ? BoxShadow(
                            color: Colors.white,
                            spreadRadius: 1,
                            blurRadius: 10)
                        : BoxShadow(
                            color: Colors.white,
                            spreadRadius: 0,
                            blurRadius: 0),
                  ],
                  image: DecorationImage(
                    image: AssetImage(widget.card.imageLink),
                    fit: BoxFit.fill,
                  ),
                ),
                width: 100,
                height: 150,
                child: Stack(children: [
                  (widget.card is CharacterCard)
                      ? Positioned(
                          right: 0,
                          left: 60,
                          child: Container(
                            color: Colors.white,
                            width: 40,
                            height: 13,
                            child: Center(
                              child: Text(
                                widget.card.power.toString(),
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 10,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ),
                        )
                      : const SizedBox.shrink(),
                  Positioned(
                      left: 2,
                      child: Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(
                          color: Colors.red,
                          shape: BoxShape.circle,
                        ),
                        child: Center(
                            child: Text(
                          widget.card.cost.toString(),
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        )),
                      ))
                ]),
              ),
            )
          : SizedBox.shrink(),
    );
  }
}


text:
Q: SharePoint feature deployment and scope via PowerShell We use SP2013 and PowerShell to deploy wsps.
When installing the wsp via PowerShell:
CASE 1:
Add-SPSolution -LiteralPath $path
install-spsolution -Identity $solution  -GACDeployment

Above PowerShell will deploy the wsp to the GAC on server and deploy to all URLS.
CASE 2:
Add-SPSolution -LiteralPath $path
install-spsolution -Identity $solution -WebApplication $oURL  -GACDeployment

Above powershell deploys the WSP to the GAC on server and deploy only to 1 specific web application (not in bin folder).
CASE 3:
How to deploy to the URL at bin folder on server?

My questions here are:-

*

*Case 1 makes the wsp (say webpart) available for each webapplication on server, what about Case 2? Since it is deployed at 1 particular webURL, wont it be usable from the other web apps? What is this concept?

*For CASE 3, please provide me powershell code.

*I have read that:-
SharePoint solutions are either deployed globally or targeted to a particular web application. The decision of which is made automatically by the SharePoint Solution framework depending on the contents of the solution manifest.
But, this can be also controlled by PowerShell, no matter what is the setting in the solution manifest, am I right?

A: No, the solution dictates if it's global or per web application.
WebApp Scope
If the solution contains resources that's web application specific like:
- Dll deployed to bin
- Dll with SafeControls
- files to the other hostdir folders
then the solution must be installed to specific web application(s) by either specifying web applications like:
Install-SPSolution -Identity $solution -WebApplication $webApp

or by specifying that you want to deploy to all:
Install-SPSolution -Identity $solution -AllWebApplications

Global Scope
If there is no web application specific resources then it's installed globally using
Install-SPSolution -Identity $solution
How do I control if my dll goes to GAC or bin?
The placement of your dll(s) is controlled by the manifest.xml in the solution and is con trolled by the DeploymentTarget attribute of the <Assembly> element(s).
Here I deploy to GAC:
<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="3086e4c4-aa41-45a4-b2f2-6c0d3fddc99f" SharePointProductVersion="15.0">
  <Assemblies>
    <Assembly Location="Test.dll" DeploymentTarget="GlobalAssemblyCache">
    </Assembly>
  </Assemblies>
  <FeatureManifests>
    <FeatureManifest Location="Test_Feature1\Feature.xml" />
  </FeatureManifests>
</Solution>

And here to bin folder:
<Solution xmlns="http://schemas.microsoft.com/sharepoint/" SolutionId="3086e4c4-aa41-45a4-b2f2-6c0d3fddc99f" SharePointProductVersion="15.0">
  <Assemblies>
    <Assembly Location="Test.dll" DeploymentTarget="WebApplication">
    </Assembly>
  </Assemblies>
  <FeatureManifests>
    <FeatureManifest Location="Test_Feature1\Feature.xml" />
  </FeatureManifests>
</Solution>

As a developer you specify that in VS by selection your SharePoint Project in Solution Explorer and then in properties change Assembly Deployment Target:


text:
Q: How to know which RAM slots are in use in a Macbook Pro? I'd like to upgrade the memory of a 15" Macbook Pro. It came with 4GB out of the box, but I don't know if it came as 1x4GB or 2x2GB.
Is there a way to know that, before unscrewing the computer?

A: Open the Apple menu, select About This Mac. Then click on More Info… and select the Memory tab.

A: It will most likely be 2 slots. Double check your specs depending on model year. Most, if not all, are coming with 2x2GB
 4GB (two 2GB SO-DIMMs) of 1333MHz DDR3 memory;
 two SO-DIMM slots support up to 8GB

Edit - looks like all recent 15" have 2 slots. I just upgraded my early 2011 and it had two, make sure you read the directions before you upgrade. You'll need a #00 head screwdriver to get the bottom off, if you have a recent model macbook.


text:
Q: Difference between WebOperationContext.current and HttpContext.Current I develop web and mobile applications for my customers. In my current architecture, many resources are shared between the web access and mobile access. An aspx page can be shown on web and be called to a web view in a mobile app. My question is :
What is the difference between WebOperationContext.Current and HttpContext.Current object?
From my understanding it is the same object, but I noticed that WebOperationContext.Current is null in some cases and I don't understand why.

A: WebOperationContext is typically used in a WCF REST method so that method can access the incoming request and outgoing response.
HttpContext is typically used in an ASP.NET WebForms page or web method for ASMX Web Service, when incoming request and outgoing response can be accessed.
They are designed for different project types (WCF REST/ASP.NET WebForms) so you should not use them in a wrong project type.
About when the value of .Current is null, that's even more complicated. Even if you are calling this property in the correct project type, you need to make sure the call is made on a proper thread. Only on the thread that handles the request (which also sends out the response) you can access the current context. On any other threads (background threads, or new threads created by you) you get null. This has been known for years but beginners still get it wrong sometimes.


text:
Q: Controling 3 LEDs using only 2 IOs I once saw somewhere that it is possible to control 3 LEDs with 2 IOs and only using LEDs and resistors. The high state is 5v and low state is 0v.
With 2 digital IOs, we can have 4 different possible situations for LEDs.
00 -> all off
01 -> LED1 on, others off
10 -> LED2 on, others off
11 -> LED3 on, others off
So it is logically possible using logical gates and mixing them. but How could it be done only with resistors and LEDs? and I am sure this method exists.
If they were 2 It was so easy. we connected them the in opposite to each other in parallel with a series resistor and 01 would light the first one and 10 would light the other one. like this :

A: If both IO lines have the same logic level then neither of the two LEDs would light so you use this to control a 3rd LED but I think you need two diodes acting as a sort of AND gate: -

simulate this circuit – Schematic created using CircuitLab
If either GPIO line is low then the LED won't light. If both GPIO line is high then the LED lights.

A: if you want to use only resistors you can do it like this.

simulate this circuit – Schematic created using CircuitLab
as VCC is 5V the  bleed resistor parallel with D3 is needed suffifient that it does not light.unless both in0 and in1 are high.


text:
Q: Eclipse Plugin only contains manifest I am attempting to develop an Eclipse plugin. The plugin runs from inside Eclipse (i.e. when I launch a test instance of Eclipse with my plugin from inside Eclipse, I can use the plugin in the test instance.)
However, when I attempt to generate a plugin that could be installed by other systems using File > Expoort > Deployable Plug-ins and fragments, the zip file created, contains a single jar file which itself contains only a manifest file:
$ jar tvf com.foo.bar_1.0.0.d.jar
     0 Wed Feb 10 12:14:12 EST 2016 META-INF/
   863 Wed Feb 10 12:14:10 EST 2016 META-INF/MANIFEST.MF

For example, it does not include my icons or my plugin.xml file.
I am not (yet) using maven-tycho or any other extra-Eclipse means of building the plugin.
Can anyone suggest what I may be doing wrong?

A: You must list everything you want in the plugin in the build.properties file, so check that file. When you run from within Eclipse this file is not checked for accuracy but it must be correct when you export.
For a simple plugin it might look something like:
output.. = bin/
bin.includes = META-INF/,\
               .,\
               plugin.xml,\
               OSGI-INF/
source.. = src/

This is including the 'META-INF' folder, the 'bin' folder (where your class files are), the 'plugin.xml' file and the 'OSGI-INF' folder.
In the plugin.xml editor use the 'Build' tab to set the contents of this file.


text:
Q: Drupal Query builder I quite often use Drupal's Views Module to build SQL that I paste into my code. It understands the Drupal database schema quite well.
Is there a module that would give me this functionality or can I factor this out of Views?

A: Would be cool of the Views module was extended to better support programmatic usage, but until then you might perhaps want to take a look at one of my colleagues attempt at creating something similar to such a thing: http://github.com/hugowetterberg/query_builder
Related to this might be the Services project attempt at providing Views data as a service, an effort that we right now are separating out into it's own module: http://drupal.org/node/709100 Might be worth follow since it's going to need some level of programmatic access to Views.
Another example of a module that's accessing Views programmatically is Development Seeds Litenode: http://developmentseed.org/blog/2009/feb/4/litenode
Update 15/12-2010: The EntityFieldQuery in Drupal 7 is almost like using Views programmatically to build queries - the difference being that EntityQueryBuilder works on only entities and fields and by that also with the bonus that it actually can build queries against any type of field storage in use - eg. a NoSQL database like MongoDB. Example can be found here: http://drupal4hu.com/node/267

A: Although this isn't the ideal way to do things, you can get the results of a view as follows:
$view = views_get_view('search');
$view->set_display('main');
$view->set_items_per_page(0);
$view->execute();

$items = array();
foreach ($view->result as $row) {
  $items[] = $row;
}

This way, whenever you modify your views query, you don't have to re-copy the code. I do agree that Views needs to be split up into a query building api and a UI.

A: Yes, i assume views is the best to know what tables are used for current field, because many modules (and more in views) have hook functions, that provide some information about this field, table, and connection type with other tables.

Also you can read scheme of tables and fields via: http://drupal.org/project/schema

A: I'm curious- why would you use Views to build SQL, and then not use Views?
When it comes to more difficult things like many to many relationships, GROUP BY, COUNT, SUM, subquerying etc whatever the function calls for, it's best to write it yourself (especially if contrib modules have no views support and you need more than the node table).
For me, when Views can't get it done, I write a simple module that invokes hook_menu (to register the paths) with a callback that does the querying I need.


text:
Q: File Upload with Restler v3 Just recently, support for multipart/form-data upload was added to Restler v3 (source) but I can't get it to work. In my index.php file, I've added:
$r->setSupportedFormats('JsonFormat', 'UploadFormat');

When I post a .txt file, I get the following error (which is expected, since the default 'allowed' format is 'image/jpeg', 'image/png':
"error": {
    "code": 403,
    "message": "Forbidden: File type (text/plain) is not supported."
}

But when I post a .jpg file, I get the following error instead:
"error": {
    "code": 404,
    "message": "Not Found"
}

What am I missing?  Here is my function:
function upload() {
    if (empty($request_data)) {
        throw new RestException(412, "requestData is null");
    }
    return array('upload_status'=>'image uploaded successfully');
}

A: I figured it out! All I needed a post() function! For anyone who runs into the same issue I ran into, here is my solution for uploading a file with Restler 3:
index.php
<?php
    require_once '../vendor/restler.php';
    use Luracast\Restler\Restler;

    $r = new Restler();
    $r->addAPIClass('Upload');
    $r->setSupportedFormats('JsonFormat', 'UploadFormat');

    $r->handle();

Upload.php
<?php
    class Upload {
        function get(){
           if (empty($request_data)) {
              throw new RestException(412, "requestData is null");
           }
        }

        function post($request_data=NULL) {
           return array('upload_status'=>'image uploaded successfully!');
        }
    }


text:
Q: vs code python keybindings ignored Steps to reproduce:

*

*Put the following in keybindings.json:

// Place your key bindings in this file to override the defaults
[
    { "key": "shift+enter",
      "command": "jupyter.execSelectionInteractive",
      "when": "editorTextFocus && jupyter.ownsSelection && !findInputFocussed && !notebookEditorFocused && !replaceInputFocussed && editorLangId == 'python'"
    },
    {
        "key": "ctrl+shift+enter",
        "command": "python.execSelectionInTerminal",
        "when": "editorTextFocus && !findInputFocussed && !jupyter.ownsSelection && !replaceInputFocussed && editorLangId == 'python'"
    },
]

*make test.py:

#%%
# move working directory to the script
import os
mydir = os.path.dirname(os.path.abspath(__file__))
os.chdir(mydir)

*select lines 1-5 and hit shift+enter

Expected result (an interactive window opens and runs the script):
# move working directory to the script...
<director path is printed>

*prints out the current directory

Observed result (get the following error in the terminal):
>>> mydir
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'mydir' is not defined

A: VSCode did not ignore the setting of shortcut keys. This is not a problem caused by the shortcut key, but the "__file__" used in the code.
When using __file__, we need to use it as code in the file, referring to the path of the currently opened file; but when using the command "python.execSelectionInTerminal", it will enter the python interactive window and execute the entered content as independent code, (like The interactive window after typing python in the cmd window), it cannot identify what the current file refers to.
We can use other code to test the use of this shortcut:

Reference: Use of "__file__".


text:
Q: How to avoid tainted canvas? I try to save an Canvas as an Image. But it fails always. I was looking up the Internet and Stackoverflow.com but I couldn't find the right answer.
I use the answer in this question to get the context. This works fine, but if I use context.toDataURL I receive error the Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I do not understand why I get this until now, because I added to my canvas and to the videostream the attribute crossorigin="anonymous" and if I check the attribute in the javascript section I still receive that crossorigin is anonymous. Therefore it should work.
function captureimage(){
var canvas = document.getElementById("c");
var video = document.getElementById("v");
var ctx;
if(video.paused) {
    try {
         ctx = canvas.getContext('2d').drawImage(video, 0, 0);
     } catch (e) {
          alert(e);
     }
     var a = ctx.toDataURL();
}
}

How can I solve this security issue? I also added Header set Access-Control-Allow-Origin * to my httpd.conf, but this didn't solve the problem either.

A: I had the same issue, and it was solved by adding crossorigin="*" to the video tag

A: I had this problem when i was trying to draw an image that Chrome had cached into a canvas. I solved my issue by adding a unique cache breaking parameter to the image URL, to ensure that the image was never being cached.


text:
Q: Surjective sheaf homomorphisms induced by morphisms of schemes Let $S$ be a scheme and $X\to Y$ be a morphism over $S$. Then we have an induced homomorphism of sheaves $h_X=\operatorname{Hom}_S({-}, X)\to h_Y=\operatorname{Hom}_S({-}, Y)$ over the small étale site $S_\text{étale}$.
Question: When is $h_X\to h_Y$ a surjective homomorphism between sheaves of sets over $S_\text{étale}$?
I find this result in the comment of Ehsan M. Kermani under Étale Local Sections of a Smooth Surjective Morphism. Is there any proof or reference of this claim?

A: Proposition. Let $f\colon X\to Y$ be a surjective morphism such that $\forall y\in Y$ there exists a point $x\in f^{-1}(y)$ where $f$ is smooth (i.e. every fiber has a non-reduced point). Then $h_X\to h_Y$ is surjective on the (small or big) étale site.
Proof: Take $f\in h_Y(S)$. The property of having a smooth point in every fiber is stable under base change so we may assume $S=Y$. Consider the open subset $X^\circ$ of $X$ where $f$ is smooth. The restriction $f^\circ$ of $f$ to $X^\circ$ is smooth and surjective. Apply EGA IV 4 Cor. 17.16.3 (ii) to $f^\circ$. We find an étale covering $Y'\to Y$ such that $Y'\times_Y X$ admits a section $s\colon Y'\to Y'\times_Y X$ which is what we need.
Remark 1. By EGA IV 4 Cor. 17.16.2 if $f\colon X\to Y$ is locally of finite presentation and faithfully flat then it admits a section after a faithfully flat base change. Therefore, in this case $h_X$ surjects over $h_Y$ on the (small or big) fppf site.
Remark 2. The property in the proposition is equivalent to the surjectivity of $h_X\to h_Y$. Indeed, the surjectivity implies that $f$ admits a section étale locally on $Y$.


text:
Q: Add same form element below by clicking add button. using Angular Js I have a form1 and a add button. The thing I want is to add same form as form2 below form1 on clinking add button. As I am new to Angular Js it will be very helpful if someone can help me out.

HTML

      APPLICANTS
      <input class="btn btn-primary" style="float:right " type="button" value="Add" />

            Name

              <input type="text" class="form-control" id="inputDefault" ng-model="txtFullName">

            Nationality

              <input type="text" class="form-control" id="inputDefault" ng-model="txtNationality">

            Pin Code

              <input type="text" class="form-control" id="inputDefault" ng-model="txtPincode">

            House No.

              <input type="text" class="form-control" id="inputDefault" ng-model="txtHouseNo">

A: You need to create an array of applicants model objects, let's call it applicantsArray, where every object will represent a single applicant form.
You need to initialize this array with one model empty on page load.
Then you need to wrap your form with ng-for and iterate over every applicant model. So the n-th form will be binded with the n-th model in the applicantsArray.
Last step will be to push an empty applicant model to applicantsArray when 'Add' is clicked. Then a new model is added and the DOM will render additional form for the new model.


text:
Q: Como o fim do "for" pode ser uma variável definida pelo usuário? Em um for em C, definimos "início, fim e passo de incremento". Sei que em Python não é assim. Vi que é chamado de foreach. Gostaria que o fim do meu for fosse definido pelo usuário. E que, a  cada iteração até o fim do for, fosse requisitado um valor ao usuário e salvo em um vetor.
Tentei:
num_tracos = raw_input()

tracos_treino = np.arange(100)

for i in num_tracos:
    print "Digite o traco", i+1, " para o treinamento"
    tracos_treino[i] = raw_input()

Também tentei um while, mas não deu certo porque nunca acaba (na verdade dá erro quando chega à entrada 101, porque não cabe mais no vetor, mas se não fosse por isso, seria infinito) :
num_tracos = raw_input()

 tracos_treino = np.arange(100)

i=0
while i < num_tracos :
    print "Digite o traco", i+1, " para o treinamento"
    tracos_treino[i] = raw_input()
    i = i+1

Sempre ouvi que é melhor um for que um while, a não ser que você vá iterar initamente (ou seja, nunca). Li isso no "Learn Python The Hard Way".
De toda forma, nenhum dos dois está funcionando como eu gostaria.

A: Qual é a versão do Python que você está utilizando?
Eu vou dar a minha ideia em cima do Python 3.
De fato o for no Python é um pouco diferente do que em C, mas você pode fazer essas tarefas sem problemas, basta entender a estrutura.
Digamos que você quisesse fazer um for para contar de 0 a 9, em C você faria isso da seguinte forma:
    for(int c=0; c<10; c++) {
        printf("%d\n", c);
    }

Em Python isso ficaria um pouco diferente, vide abaixo:
    for c in range(0, 10):
        print(c)

Repare que no Python, eu utilizo um 'range' de valores a percorrer, neste caso, de 0 a 9, esses valores podem ser substituídos por variáveis.
Você pode também definir o passo da iteração.
    for c in range(0, 10, 2):
        print(c)

Repare no terceiro parâmetro do range, ele faz com que a contagem aconteça de 2 em 2.
Partindo para a sua pergunta...
No Python temos uma coisa que na minha opinião ajuda bastante, são as listas.
    # Definimos uma lista para guardar os valores.
    tracos_treino = []
    # Podemos solicitar ao usuário quantos ítens ele quer inserir na lista.
    tamanho = int(input('Informe a quantidade de ítens desejados:'))
    # Fazemos a iteração.
    # Aqui utilizo a variável 'tamanho' para determinar o fim da contagem.
    for c in range(0, tamanho):
        valor = input('Digite o traco ' + str(c+1) + ' para o treinamento:')
        tracos_treino.append(valor)   # Adiciona ao final da lista.
    # Depois podemos fazer a exibição desses valores.
    for c in range(0, tamanho):
        print(tracos_treino[c])

Espero ter ajudado em algo :D

A: Para conseguir implementar aquilo que tem em vista tem de fazer o seguinte:

*

*criar uma condição para acabar o ciclo while, na definição do mesmo

*criar input na consola para ler uma variável de input

*a partir daí, mapear a variável de input para a condição que dá por encerrado o ciclo while loop
esta definição poderá eventualmente ser algo do género (estrutura de pseudo-código):

*

*continuar enquanto variável de input for diferente de 0

Aí, no final de cada ciclo de iteração deverá colocar o seguinte:

*

*deseja continuar (sim - 1, não - 0) - imprimir na consola

*deverá depois ler o input para uma variável que deverá ser a mesma que se encontra no cabeçalho do ciclo quando diz que continua caso seja diferente de 0


text:
Q: respuesta.forEach is not a function Estoy tratando de obtener valores mediante un json el cual es un arreglo multidimensional

Dicho json estoy tratando de recorrerlo para obtener, por ejemplo, de respuesta_resultado_banca_privada obtener un campo llamado BANCO pero a la hora de obtener dicho campo me sale el siguiente error:

respuesta.forEach is not a function

*

*JSON
resultado_banca_privada:

        0: {BANCO: "BBVA", TOTAL_ACTIVO_1: "25724452", TOTAL_ACTIVO_2: "2542452", ABSOLUTA_TOTAL_ACTIVO: "15415156"....

        1: {BANCO: "SANTANDER", TOTAL_ACTIVO_1: "25424254", TOTAL_ACTIVO_2: "2542452", ABSOLUTA_TOTAL_ACTIVO: "15415156"....

*

*Código
function table(respuesta)
{
    respuesta.forEach(function(element) {
        console.log(element.respuesta_banca_privada.BANCO);
    });
}

A: Tienes que tener en cuenta que un objeto no posee la función forEach() para que puedas recorrerlo ya que los elementos dentro del mismo poseen una clave y un valor. Si deseas algún dato dentro de objeto necesitas acceder a ellos mediante la clave del mismo.
La posible solución a tu caso seria recorrer cada elemento dentro del json cargando la clave a una variable dentro de un  for():

var dato = {
    0: {BANCO: "BBVA", TOTAL_ACTIVO_1: "25724452", TOTAL_ACTIVO_2: "2542452", ABSOLUTA_TOTAL_ACTIVO: "15415156"},
    1: {BANCO: "SANTANDER", TOTAL_ACTIVO_1: "25424254", TOTAL_ACTIVO_2: "2542452", ABSOLUTA_TOTAL_ACTIVO: "15415156"}
        };

    for (var item in dato){
        console.log(dato[item].BANCO);
    }

Y luego accedes a la clave que necesitas(en tu caso, la propiedad BANCO). Suerte
Espero te sirva el ejemplo

A: Como te mencionaron es un objeto que no posee la función foreach
por lo tanto puedes recorrer el objeto por clave y valor teniendo en cuenta de que es multidimencional tienes que recorrer por llaves para este caso usas un for in
que recorre primero respuesta_banca_privada y después accedes a las propiedades de la misma con otro for para mostrar los nombres hache te dejo un ejemplo

var bancos = {
    resultado_banca_privada : {
      0 : {
            BANCO: "BBVA",
            TOTAL_ACTIVO_1: "25724452",
            TOTAL_ACTIVO_2: "2542452",
            ABSOLUTA_TOTAL_ACTIVO: "15415156"
        },
      1 : {
            BANCO: "BBVA 2",
            TOTAL_ACTIVO_1: "33333",
            TOTAL_ACTIVO_2: "44444",
            ABSOLUTA_TOTAL_ACTIVO: "7777"
        }
    },
    resultado_banca_publica : {
        0 : {
          BANCO: "SANTANDER",
          TOTAL_ACTIVO_1: "25424254",
          TOTAL_ACTIVO_2: "2542452",
          ABSOLUTA_TOTAL_ACTIVO: "15415156"
        },
        2 : {
          BANCO: "SANTANDER 2",
          TOTAL_ACTIVO_1: "77777",
          TOTAL_ACTIVO_2: "8888",
          ABSOLUTA_TOTAL_ACTIVO: "99999"
        }

    }
 };

for (var key in bancos){

    for ( keyBanco in bancos[key]  ) {
      console.log(bancos[key][keyBanco].BANCO )
    }
}


text:
Q: in the C++ BLPAPI is there a way to avoid using hasElement or catching errors Generally I do the following:
if (msg.hasElement(BID_SIZE))
{
   bid_sz=msg.getElementAsInt32(BID_SIZE);
}

If I don't use check first using hasElement - then fields that don't exist will throw an error

A: Instead of using getElementAsInt32 use getValueAs:
Element field;
int err=msg.asElement().getElement(&field, BID_SIZE);
if (!err)
{
    int valerr=field.getValueAs(&bid_sz);  // will call getValueAs for the type of bid
}

This will avoid looking for BID_SIZE twice in the message, and will not throw when fields are not found.
Alternatively you can loop through all fields and check which field it is:
Element asElem=msg.asElement();
size_t num=asElem.numElements();
for (size_t i=0; i < num; ++i)
{
   Element field=asElem.getElement(i);
   Name field_name=field.name();
   if (field_name == BID_SIZE)
   {
       bid_sz=field.getValueAsInt32();
   }
   // check other fields
   // put more likely fields at the top
}


text:
Q: Want to use js to add rows onclick I have this code below that pulls up FX data from the Visa website. Each time you tap on a date, it adds another row.
But adding a row seems to cause a reload/refresh of all the iframes ... why? How do I prevent that?
(You can see it live at http://zinclabs.com/eur2)

A: Adding text to an object's innerHTML causes a complete refresh of the object – in this case document.body.  Therefore, all the iframes within it will be reloaded.
Instead, you could create a new DIV element, and append it as a child of document.body:
function addrow(){
  var d = format(date);
  var newRow= document.createElement('div');
  newRow.innerHTML= '

'+d+'

';
  document.body.appendChild(newRow);
  date.setDate(date.getDate() - 1);
}


text:
Q: Testing that Devise is re-sending confirmation instructions email in a background worker I want to send Devise confirmation instructions to users a second time if they haven't confirmed within two days of signing up, however I can't seem to get my success case test to pass.
Background worker (runs once a day):
class ResendConfirmationWorker
  include Sidekiq::Worker
  sidekiq_options queue: :resend_confirmation, retry: false

  def perform
    d = Time.zone.now - 2.days
    users = User.where.not(confirmation_sent_at: nil)
                .where(confirmed_at: nil)
                .where(created_at: d.beginning_of_day..d.end_of_day)

    users.find_each do |user|
      user.send_confirmation_instructions
    end
  end
end

RSpec test:
require 'rails_helper'

describe ResendConfirmationWorker, type: :job do
  before do
    time = Time.zone.now - 2.days
    @user = create :unconfirmed_user,
                    created_at: time,
                    confirmation_sent_at: time
  end

  def run_job
    subject.perform
  end

  it 'resends a confirmation email to people who haven't accepted it within two days' do
    run_job
    expect(Devise::Mailer.deliveries.count).to eq 1
  end
end

I always get 0 instead of 1. I've also tried looking at Sidekiq::Extensions::DelayedMailer.jobs.size and Devise.mailer.deliveries.count but they also return 0.
Lastly, I put a binding in the worker and run user.send_confirmation_instructions manually:
[1] pry(#<ResendConfirmationWorker>)> user.send_confirmation_instructions
=> #<ActionMailer::DeliveryJob:0x007fc53f05c420
 @arguments=
  ["Devise::Mailer",
   "confirmation_instructions",
   "deliver_now",
   #<User id: 1, email: "unconfirmed1@example.com", created_at: "2017-01-05 04:40:13", updated_at: "2017-01-07 04:40:13", company_id: nil, name: "Unconfirmed User", invitation_token: nil, invitation_created_at: nil, invitation_sent_at: nil, invitation_accepted_at: nil, invitation_limit: nil, invited_by_type: nil, invited_by_id: nil, invitations_count: 0>,
   "token1",
   {}],
 @job_id="9b5f6231-3194-4c57-9a6b-a38368cec603",
 @priority=nil,
 @queue_name="mailers">

It looks like it's correctly adding a new confirmation instructions email to the mailer queue, so why can't I see it from my test?


text:
Q: Clearness Scoring Function Hello to the community,
I would love to hear your opinion about a Prediction Model I am currently working on for my thesis, in order to predict the Clearness of a website.
I created a dataset of 5.000 landing page images.
Then I made a web application where users would vote random pairs of images and choose the image that looked more "clear".
As a result, after getting results from more than 1.000 users Ι have a dataset with the following scheme
    "image1"      "image521"   1
    "image3"      "image241"   0
    "image35"      "image12"   1
    :
    :
    :
    "image5"      "image902"   1

where I have tuples of the images that have been displayed and if the third value is 0, then the first image is chosen, if the value is 1 the second image was chosen.
Now, my question comes to how I should structure the (Clearness) Score function.
So far the Clearness Score function is calculated with the following way:
Clearness =  TimesAnImageIsVoted*100/TimesAnImageIsDisplayed

As an example, if an image has been displayed 20 times in 20 unique pairs and has been selected 15 times as the more clear image, then the Clearness would be equal to 75.
Should I take into consideration the pairs, penalize images that are not selected or in general have a more elegant approach?
Thank you in advance.


text:
Q: Share a virtual environment between Windows and Linux I am developing a kivy app in python using vscode with a virtual environment, everything works fine until I try to create an apk for Android.
Buildozer installs fine, but only works in Linux. So I am using the "Windows Terminal" Linux shell to do the apk build steps using buildozer. The problem is I cannot get the Linux shell to activate the virtual environment set up in windows/vscode and which is usually activated by running venv/Scripts/activate.
How do I activate this environment from "Windows Terminal" so vscode and Linux are sharing the same venv.


text:
Q: SQL Server 2005 Auditing Background
I have a production SQL Server 2005 server to which 4 different applications connect and make changes.
There are no foreign keys and in some cases no primary keys.
Unfortunately throwing the whole thing out and starting from scratch is not an option.
So my solution is to start migrating each of the applications to a service layer approach so that there is only one application directly connecting to the database.
However there are problems that need to be fixed before that service layer is written and all the applications are migrated over.
So rather than make changes and hope they don't break any one of the 4 badly written applications (with no way of quickly testing all functionality) my solution is to start auditing the database
Problem
How do I audit what stored procedures, tables, columns, views are being accessed/updated/called by each user on SQL Server 2005.
I can find out which tables are being updated but I have no idea which columns and by what users.
I also don't know if certain tables are being accessed only through stored procedures/views.
I know that SQL Server 2008 has better auditing features but if I could do this without spending money that would be great. That said if the best solution is to upgrade or buy software that's also an option.

A: Check out SQL Server 2008's CDC feature. You can't use this directly in 2005 but you can write a trigger for each table to log all data changes to a new audit table. i.e. you'd have an audit table for each table in your db, with all the same columns plus some additional columns saying what the operation was and when it occurred.
If the nature of your applications means you can get user information and/or application information from CURRENT_USER and APP_NAME() you could include that information in the audit table too.
And check out this answer for more goodness.


text:
Q: Как перейти через браузер по данному мне vps провайдером IP? Мне vps провайдер дал ip, логин и пароль для входа. Через ssh успешно захожу в консоль управления сервером. Но через браузер по данному IP зайти не могу. В чем может быть проблема?

A: Все. Нашёл решение! У меня сервер работает на NodeJS. Программа слушала порт 5000, а браузер отображает на 80 порту. Так что тут 2 решения:
1. Добавить в адресной строке браузера к IP порт.
2. Изменить в настройках программы порт на 80.
Теперь все работает на ура.


text:
Q: Empty body getting sent on using PUT method through android Volley I am using Volley to fetch data from a REST service. So there are two methods , One is POST which creates an object on server and other is PUT which basically updates the same object.I use the same code for making these requests.I just change the Method which is passed in Volley.The app works fine through POST request with the correct data sent in the body, but it encounters a problem with PUT request where it randomly sends no data in the body.
I shifted to a custom Request object as suggested by Google but it is still not working.
    int method = Request.Method.POST;

    String objID = sharedPreferences.getString("objID", null);
    String Url = "/api_url";

    if (objID != null)
    {
        Url += objID + "/";
        method = Request.Method.PUT;
    }

    try
    {
        JSONObject objJSON = new JSONObject();
        objJSON.put("name", "new_name");
    }
    catch (JSONException e)
    {
        // Handle Execption
    }

    GsonRequest request = new GsonRequest<CustomObj>(method, Url, CustomObj.class,null, null, objJSON.toString(),
    new Response.Listener<CustomObj>()
    {
        @Override
        public void onResponse(CartObj cartObj)
        {
            // Handling Logic
        }
    }
    ,
    new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError volleyError)
        {
            // Handle Error
        }
    });

    VolleySingleton.getInstance(this).addToRequestQueue(request);

GsonRequest is my Custom Class Extending Request Object
public class GsonRequest<T> extends Request<T>
{
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;
    private final Map<String, String> params;
    private final String body;
    private ErrorListener mErrorListener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url     URL of the request to make
     * @param clazz   Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */

    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Map<String, String> params, String body, Listener<T> listener, ErrorListener errorListener)
    {
        super(method, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
        this.params = params;
        this.body = body;
        this.mErrorListener = errorListener;
    }

    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Map<String, String> params, Listener<T> listener, ErrorListener errorListener)
    {
        this(method, url, clazz, headers, params, null, listener, errorListener);
    }

    public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> headers, Listener<T> listener, ErrorListener errorListener)
    {
        this(method, url, clazz, headers, null, null, listener, errorListener);
    }

    @Override
    public byte[] getBody() throws AuthFailureError
    {
        return body != null ? body.getBytes() : super.getBody();
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError
    {
        return params != null ? params : super.getParams();
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError
    {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response)
    {
        listener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error)
    {
        mErrorListener.onErrorResponse(error);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response)
    {
        try
        {
            String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        }
        catch (UnsupportedEncodingException e)
        {
            return Response.error(new ParseError(e));
        }
        catch (JsonSyntaxException e)
        {
            return Response.error(new ParseError(e));
        }
    }
}

I am using GSON to parse my Data , and CustomObj is a Mapping Object for volley.

A: First of all all make sure the url you're building (where you check if objID is not null) is correct.
Secondly, you can try to call getBytes() method with a charset.
In the request override getBody() method:
@Override
public byte[] getBody() throws AuthFailureError {
    try {
        return body != null ? body.getBytes(getParamsEncoding()) : super.getBody();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return super.getBody();
}

Hope this will help.
Edit:
You can also try to override getBodyContentType() method:
@Override
public String getBodyContentType() {
    return "application/json; charset=" + getParamsEncoding();
}


text:
Q: Is possible backgroundworker DoWork in main thread? Is possible backgroundworker DoWork in main thread?
I meant if some device only have one CPU , Is it possible to happen?
PS: I'm working on unity , So run Android & IOS & Windows Platform.
    System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
    bool inMainThread = false;
    int mainThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

    bw.DoWork += (object sender, System.ComponentModel.DoWorkEventArgs e) =>
        {   // Is it possible equal true ??
            inMainThread = mainThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId;
        }

A: No it is not possible. A BackgroundWorker will always do its work on an seperate thread.
To the point with an system with only one CPU. An OS runs many programs asynchronous and every program can have many threads. The OS will schedule all this threads to run at somepoint on any available CPU. This is crucial to maintain a smooth running system, especially when a system has only one CPU.
If you want to know more you could look here or here and for a start I would recommend this video.


text:
Q: Apply Row_Number for 3 columns in a table I've a table named as "Temp" like this,
ItemId  JobId   Status
1       11      Yes
1       12      No
1       12      Yes
1       13      Yes
2       12      Yes
2       12      Yes
2       11      No
2       13      Yes
2       13      No
2       13      Yes

My expected output is, Needs to set series for these 3 columns(ItemId, JobId, Status) based on values.
Output should be as,
iID     iSN     JobId   JobSN   Status  statusId
1       1       11      1       Yes     1
1       2       12      1       No      1
1       3       12      2       Yes     1
1       4       13      1       Yes     1
2       1       12      1       Yes     1
2       2       12      2       Yes     2
2       3       11      1       No      1
2       4       13      1       Yes     1
2       5       13      2       No      1
2       6       13      3       Yes     2

Here iSN needs to set based on ItemId
JobSN based on JobId->ItemId
StatusId based on Status->JobId->ItemId

I know to set the series on a column, need to partition over the column by using ROW_NUMBER() OVER(PARTITION [ColumnName])...
But, how can i apply for get expected output. Can anybody help me on this?
Thanks in Advance!!!

A: Assuming you have a column that you can use to sort the rows by, you can do something like this:
Create and populate sample table (Please save us this step in your future questions)
DECLARE @T AS TABLE
(
    id int identity(1,1),
    ItemId int,
    JobId int,
    [Status] varchar(3)
)

INSERT INTO @T VALUES
(1, 11, 'Yes'),
(1, 12, 'No'),
(1, 12, 'Yes'),
(1, 13, 'Yes'),
(2, 12, 'Yes'),
(2, 12, 'Yes'),
(2, 11, 'No'),
(2, 13, 'Yes'),
(2, 13, 'No'),
(2, 13, 'Yes')

The query:
SELECT  ItemId As iID,
        ROW_NUMBER() OVER(PARTITION BY ItemId ORDER BY id) As iSN,
        JobId,
        ROW_NUMBER() OVER(PARTITION BY JobId, ItemId ORDER BY id) As JobSN,
        [Status],
        ROW_NUMBER() OVER(PARTITION BY [Status],JobId, ItemId ORDER BY id) As statusId
FROM @T
ORDER BY id

Results:
iID     iSN     JobId   JobSN   Status  statusId
1       1       11      1       Yes     1
1       2       12      1       No      1
1       3       12      2       Yes     1
1       4       13      1       Yes     1
2       1       12      1       Yes     1
2       2       12      2       Yes     2
2       3       11      1       No      1
2       4       13      1       Yes     1
2       5       13      2       No      1
2       6       13      3       Yes     2

A: Only the statusId column is not clear to me. Hope this can be a start.
SELECT ItemId
    , ROW_NUMBER() OVER (PARTITION BY ItemID ORDER BY ItemID) AS iSN
    , JobId
    , ROW_NUMBER() OVER (PARTITION BY JobId, ItemID ORDER BY ItemId) AS iSN
    , Status
FROM @T
ORDER BY ItemId

Result
+------+----+------+----+-------+
|ItemId|iSN |JobId |iSN |Status |
+------+----+------+----+-------+
|1     |1   |11    |1   |Yes
|1     |2   |12    |1   |No
|1     |3   |12    |2   |Yes
|1     |4   |13    |1   |Yes
|2     |1   |11    |1   |No
|2     |2   |12    |1   |Yes
|2     |3   |12    |2   |Yes
|2     |4   |13    |1   |Yes
|2     |5   |13    |2   |No
|2     |6   |13    |3   |Yes
+------+----+------+----+-------+

A: Try this:
SELECT Itemid AS iID
, ROW_NUMBER() OVER (PARTITION BY ITEMID  ORDER BY JobID, STATUS) AS iSN
, JobID
, ROW_NUMBER() OVER (PARTITION BY ITEMID,JobID  ORDER BY JobID, STATUS) AS iSN
, Status
, ROW_NUMBER() OVER (PARTITION BY ITEMID,JobID,STATUS  ORDER BY JobID, STATUS) AS statusid
FROM TEMP;

but you have to decide ORDER BY rules to obtain always same results: mine are slightly different from yours)
iID         iSN                  JobID       iSN                  Status statusid
----------- -------------------- ----------- -------------------- ------ --------------------
1           1                    11          1                    Yes    1
1           2                    12          1                    No     1
1           3                    12          2                    Yes    1
1           4                    13          1                    Yes    1
2           1                    11          1                    No     1
2           2                    12          1                    Yes    1
2           3                    12          2                    Yes    2
2           4                    13          1                    No     1
2           5                    13          2                    Yes    1
2           6                    13          3                    Yes    2


text:
Q: Minimize "new Email" Dialog I try to modify a new email.
Everything works fine but i want to minimize the "new Email" Dialog in Outlook during the modification and i don't know where to do this.
This is my code so far:
public Outlook.MailItem convertMail()
{
    mail.Subject = "New subject";
    mail.Body =  "This is the test text";
    return mail;
}

I already tried:
mail.Display(false);

This doesnt work and i don't know which function to use.
How can i minimize the Outlook Dialog by code?

A: The window state of the message composer is not a property of the mail item, but of its inspector:
var inspector = mail.GetInspector;
inspector.WindowState = OlWindowState.olMinimized;

This assumes that the window is already shown on screen by the time this code executes. Otherwise, call inspector.Display(false) before you set the window state.

A: From Outlook Interop I believe the nearest you could get is:
outlookApp.Inspector inspect;
inspect = mail.GetInspector;
inspect.Display;
inspect.WindowState = olMinimized; // probably outlookApp.olMinimized

(although I cannot test currently)


text:
Q: user input validation issues Whenever I try this it does not work (input = 6). It sends me to the previous menu and says the input is invalid.
Code in Python that does not work.
def amount_of_Chests () :
    chestCount = 0
    amount_of_Chests_Display ()
    while chestCount <4 :
        chestCount_string = input("Please Make Sure You Enter Enough Chests\nPlease Enter How Many Chests You Would Like (Min.4)")
        chestCount = int(chestCount_string)
        if chestCount < 4 :
            print ("\nThere Are Not Enough Chests, Please Try Again.")
            amount_of_Chests_Display ()
        if chestCount > 3 :
            return chestCount
            amount_of_Bandits ()
        else :
            print ("Sorry that input is not valid. Please try Again.\n")

A: No code after a return statement will be executed, so amount_of_Bandits() will never be called


text:
Q: "grub package failed to install into /target/". Error installing Ubuntu alongside Windows 10 (actually installing Xubuntu but I don't think it makes a difference)
When I attempt to install Ubuntu after setting up the partitions and beginning installation, I end up with a "the 'grub-efi-amd-64-signed' package failed to install into /target/. Without the GRUB bootloader, the installed system will not boot" error and the install cannot continue.
What led to the current situation:
So I previously had Kubuntu installed dualbooting alongside Win10, long story short I formatted the Kubuntu partition, so I've only got Windows installed atm.
Grub then proceeded to break, but with a Win10 iso I managed to 'repair' it (via bootrec /fixmbr, stuff like that).
On boot I now get a grub console, if I 'exit' Windows will then boot.
Windows is installed in legacy mode if it matters, not UEFI.


text:
Q: How can TabNavigator child screen refer to parent StackNavigator? The structure of the application is this.

*

*StackNavigator

*

*StackA-Screen(TabNavigator)

*

*TabChildA-Screen

*TabChildB-Screen

*...

*StackB-Screen

code in App.js
const TabComponent = TabNavigator(
{
    TabChildA-Screen: {
    screen: TabChildA,
    },
    TabChildB-Screen: {
    screen: TabChildB,
    }
},
{
    tabBarPosition: "bottom",
    animationEnabled: false,
    swipeEnabled: false
}
);

const StackComponent = StackNavigator(
{
    StackA-Screen: {
    screen: TabComponent,
    navigationOptions: ({ navigation }) => ({
        headerBackTitle: null,
        headerRight: (
        <TouchableWithoutFeedback
            onPress={() =>
            navigation.navigate("StackB-Screen", { space: "" }) // can't navigate to "StackB-Screen".
            }
        >
            <MaterialIcon
            name="playlist-add"
            size={Sizes.NavigationBar.Icon.Size}
            style={{ padding: 8, color: Colors.White }}
            />
        </TouchableWithoutFeedback>
        )
    })
    },
    StackB-Screen: {
    screen: StackB,
    }
},
{
    initialRouteName: "StackA-Screen",
    mode: "modal"
}
);

export default StackComponent;

I want to navigate TabChildA-Screen to StackB-Screen.
But, TabChildA-Screen can refer to navigator is navigator of TabNavigator.
code in TabChildA-Screen
import React, { Component } from "react";
import { Button, Text, View } from "react-native";

class StackB extends Component {
constructor(props) {
    super(props);
}

render() {
    return (
    <View
        style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center"
        }}
    >
        <Button
        onPress={ () =>
            this.props.navigation.navigate("StackB-Screen") // can't navigate to "StackB-Screen".
        }
        title="move to StackB-Screen"
        />
    </View>
    );
}
}

export default StackB;

How to TabChildA-Screenrefer StackNavigator ?


text:
Q: Complex Integration and deduce that function is constant Let $f$ be an entire function, $z_{1}$, $z_{2}$ $\in$ $C$, with $z_{1} \neq z_{2}$ and $R>\max{(|z_{1}|,|z_{2}|)}$. Prove that
  $$2\pi i\dfrac{f(z_{1})-f(z_{2})}{z_{1}-z_{2}} = \oint_{\gamma}{\dfrac{f(z)}{(z-z_{1})(z-z_{2})}},$$
where $\gamma$ is the circle of center $0$ and radius $R$ positively oriented. Deduce that every bounded entire function is constant.
Progress
By Partial fractions, we have   $\dfrac{1}{(z-z_{1})(z-z_{2})} = \dfrac{1}{z_{2}-z_{1}}\left( \dfrac{1}{z-z_{2}} - \dfrac{1}{z-z_{1}}\right)$
$$\oint_{\gamma}{\dfrac{f(z)}{(z-z_{1})(z-z_{2})}}dz=\dfrac{1}{z_{2}-z_{1}}\oint{\left( \dfrac{f(z)}{z-z_{2}}dz - \dfrac{f(z)}{z-z_{1}}dz\right)}$$
Now, applying Cauchy's Theorem $$\oint_{\gamma}{\dfrac{f(z)}{(z-z_{1})(z-z_{2})}}dz=\dfrac{1}{z_{2}-z_{1}}(2\pi if(z_{2})-2\pi if(z_{1}))$$
Then,
$$2\pi i \left(\dfrac{f(z_{2})-f(z_{1})}{z_{2}-z_{1}}\right)=\oint_{\gamma}{\dfrac{f(z)}{(z-z_{1})(z-z_{2})}}dz$$
But, I don't know how determinated the last part of problem (or maybe, my progress isn't than better for the problem. And finally, who knows where is this problem in some book, greetings

A: Note that equality holds for sufficiently large $R>0$.
Consider $|f(z)|\le M$
$\displaystyle \left|\int_{\gamma}\frac{f(z)}{(z-z_1)(z-z_2)}dz\right|\le \frac{M}{(R-|z_1|)(R-|z_2|)}\cdot 2\pi R\longrightarrow 0$ , $R\longrightarrow \infty$ (ML-Inequality)
Therefore   $\;2\pi i\dfrac{f(z_{1})-f(z_{2})}{z_{1}-z_{2}}=0$.


text:
Q: Openmp's unexpected unspecified behavior when testing values after parallel block Consider the following:
// compile with
// gcc -fopenmp test.c

#include <stdio.h>    // to display on the screen
#include <stdlib.h>   // to access EXIT_SUCCESS
#include <omp.h>      // OpenMP library.

int main() {
  unsigned long long input = 100;
  unsigned long long b = 0, c = 0;
  #pragma omp parallel
  {
    #pragma omp for
    for(unsigned long long a = 0 ;  a < input ; a++) {
      b++;
      c++;
    }
  } // <= There should be a barrier here.
  // Check
  if (b != c || b != input){
      fprintf(stdout, "\"Error\" : %llu and %llu are different from %llu", b, c, input);
      return EXIT_FAILURE;
  }
  else{
    return EXIT_SUCCESS;
  }
}

My current understanding is that there should be an implicit barrier at the end of the #pragma omp parallel { block, so that all threads should have completed when the code reach the if statement.
However, I get inconsistent results:
gcc -fopenmp test.c
./a.out
"Error" : 70 and 69 are different from 100
./a.out
"Error" : 75 and 78 are different from 100
./a.out
"Error" : 83 and 81 are different from 100
./a.out
"Error" : 91 and 86 are different from 100
./a.out  <= Nothing, which means it "worked"
./a.out
"Error" : 88 and 86 are different from 100

What is flawed in my understanding?


text:
Q: Terminal - Application behaves differently when launched as terminal argument vs terminal command I use key shortcuts to launch commonly used applications in i3. Some of these applications are text-based (vim, calcurse) and require me to pass them as arguments to a terminal emulator (st, termite). The problem I'm seeing is that my configs are not being used when launching them this way.
Opening a terminal window first then typing in the application name starts it using the config files in my ~/.config directory.
Launching an application as an argument seems to ignore my configuration files and lockfiles. For example, calcurse typically allows only one active session and will warn you that it is already running if you try to run a second instance. However, when launching one instance of calcurse from the commandline and the other with something like "st calcurse" both instances will run concurrently (with different calendar data and theming).
The solution I'm looking for would have st <application> behave the same as just running <application> from the commandline of a running terminal. It seems like there might be some environment variables that aren't being respected somewhere but I'm not sure. Any ideas on how to fix this?


text:
Q: onMessageReceived is Never Called when FCM Notification Received, API 19 above Update
onMessageReceived called in API 19 but not on 23 and 24.
Update
I am sending FCM notifications from a server, I can receive notifications but onMessageReceived is not called(foreground, background), even with data messages. This is the code I'm using.
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import uk.co.socktchat.socketchat.MainActivity;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

 private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be:
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]

        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

    }
}

My Manifest file
<service
    android:name=".fcm.MyFirebaseMessagingService"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
    android:name=".fcm.MyFirebaseInstanceIDService">
    <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
</service>

json im posting from server
{
    "data": {
    "title": "5x1",
    "body": "15:10"
  },
    "to" : "d6IJZlXAUZ4:APA91bF8kB_jBn_N93otIdRFsu89ZDhrFsL--i0I4TmS-LO_h3QQ79lu6VlTQe0poNpuUni7N45_jw2XMli",
    "priority" : "high",
    "content_available" : true

 }

I don't see anything wrong, I tried different versions of Android, thinking android version could be any reason, but didn't seem the find any problem. Any ideas?  Thank you.

A: Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Payload: " + remoteMessage.getNotification().getBody());
            //handleNotification(remoteMessage.getNotification().getBody());
        }

Check if message contains a data payload.
if (remoteMessage.getData().size() > 0){
   Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
   handleNotification(remoteMessage.getData());
}

A: As per FCM document

Notification messages contain a predefined set of user-visible keys.
  Data messages, by contrast, contain only your user-defined custom
  key-value pairs. Notification messages can contain an optional data
  payload. Maximum payload for both message types is 4KB, except when
  sending messages from the Firebase console, which enforces a 1024
  character limit.

check that your message size is within limit.

A: In fact onMessageReceived is being called the whole time, it is just that Logcat didn't show any messages, weird enough it happened only with devices of API 19 above, on a device with API 19 Logcat is showing the messages, I can't explain why this happened but my problem was solved.


text:
Q: How do I a conditional build through a make file? How can we create selective objects by passing command line options to a make file?
My project structure is as follows.
Makefile
src/
include/
test/

The main file is under test dir & other C++ test code files, like abc1.cc abc2.cc, etc. also under test.
I want to build selective abcX.cc files into abcX.o files by passing appropriate argument to the make file.
I don't want to use my make as,
$ make ABC1=1 ABC2=1,

and put that ABC variable in ifeq in the make file.
Like,
ifeq ($(ABC1), 1)
  $(TESTPATH)/abc1.o
endif

Is there a practical approach?

A: If I understand the question correctly, you want to create the same binary but use a different source for it by providing an option to make.
For this specific scenario, just use a pattern phony/pseudo-target to make the final target:
# Create a pattern target, let's give it a name such that
# the pattern is obvious, such as ABC/<num>
.PHONY: ABC/%
ABC/%: main.cc $(TESTPATH)/abc%.cc
     g++ -o modtest $< # etc...

Then pass whatever number you wish to build to make with make ABC/<num>
$ make ABC/1

If, on the other hand you wish to produce individual binaries it's the same deal, but let the phony target depend on the final binary instead. It may look like this if the pattern is the same:
# Trigger the build for modtest-<num> with the target ABC/%
.PHONY: ABC/%
ABC/%: modtest-%

If you have more advanced dependencies from the pattern to the actual target you can specify variables that maps the pattern to whatever you need by e.g. using target or pattern specific variables:
# Set target specific variables to customize what to be built
ABC/1: OBJECTS=abc1 foo bar
ABC/2: OBJECTS=abc2
ABC/%: OBJECTS=% main


text:
Q: How do I enter Unicode characters in TeX? I need to write a few Unicode characters (e.g. Л) into a text without using e.g. XeTeX, LuaTeX or inputencoding with UTF-8 (please assume as little as possible about the typesetting system).
I have read other questions regarding this problem, but did not find an answer without
XeTeX/LuaTeX/UTF-8/... (therefore the explicit TeX in the question).
EDIT (because it is way too long for a comment and comments do not provide code markup):
Egreg's answer works perfect with TeXlive 2011 (as expected for an answer of egreg and for TeXlive; +1 for that). Also as expected, with "Old-TeX" (SWP5.5 @ http://www.mackichan.com, which is the recent version) it does not work. Additionally it is necessary to install the cyrillic and lh packages and to change the code to
\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T2A,T1]{fontenc}
\begin{document}
{\fontencoding{T2A}\selectfont\CYRL\cyra\CYRT\cyre\CYRK\CYRS}%
\end{document}

(There must be an empty line before \documentclass, which SE does not show.)
Then the document does compile even with SWP, but Л still is not shown. The reason (as found by Ulrike Fischer) for this is that
the needed tfm font file (larm1000.mf) cannot be generated by the "Old-TeX".
When generating it with TeXlive and copying it to SWP, it is still not used.
Thus: With the current version of SWP it is not possible. :-(
Nevertheless, it is possible to do this:
\documentclass{article}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage[T2A,T1]{fontenc}

\def\cylatex{%
%TCIMACRO{LaTeX}%
%BeginExpansion
{\fontencoding{T2A}\selectfont\CYRL\cyra\CYRT\cyre\CYRK\CYRS}%
%EndExpansion
}

\begin{document}

Text\cylatex{}Text

\end{document}

(There must be an empty line before \documentclass again, which SE does not show.)
When compiled with modern LaTeX, it writes TextЛаТеКСText
(I'm not sure about КС for X - anyone speaking a language using cyrillic signs here to help?),
and when compiled with SWP it writes TextLaTeXText (which is better than having just TextText).
Caveat: When the document is opened with SWP and saved, the definition will be changed to
\def\cylatex{LaTeX}

therefore the main document may never be saved by SWP (using subdocuments and editing those is possible).
Placing the
\def\cylatex{%
%TCIMACRO
...
}

into a style file will result in SWP reading the {\fontencoding{T2A}\selectfont\CYRL\cyra\CYRT\cyre\CYRK\CYRS}
part and again creating an error instead of ЛаТеКС or LaTeX.

A: Every character in one of the standard output encoding has a LaTeX Internal Character Representation (LICR). The LICR for л is \cyrl and the character belongs to the output encoding T2A (cyrillic). So
\documentclass{article}
\usepackage[T2A,T1]{fontenc} % T1 can also be OT1
\usepackage[unicode=true,bookmarks=true]{hyperref}
\begin{document}
\section{{\fontencoding{T2A}\selectfont\cyrl} is the cyrillic letter ``ell''}

{\fontencoding{T2A}\selectfont\cyrl}l

\end{document}

will do. Of course you'll want to define a more handy command for choosing a different output encoding.


text:
Q: How to apply colors that are stored in mongodb to ejs templates? I am storing colors codes as a input from user into mongodb through mongoose. I tried to apply those codes into ejs template parts for styling. Can't figure it how can i do  that.
I tried this way but it is showing error mark here :
Please my image :
colors are applying but the problems is  error mark. I should remove that error mark.How can i do that?

A: Please don't send code as screenshot. It appears that you're being warned by the VSCode that you have syntax error but it appears ok, unless you have misspelled the variable name Primarycolor
<button style="background-color: <%= Primarycolor %>!important">Send a free request</button>

Have you tried to render that page?


text:
Q: update function (AddWithValue parameter included) won't work Im trying to loop over some array, and through that , update with new parameters..
this is my code :
for (int i = 0; i < wholeArr.Length - 1; i++)
    {
        string[] temp = wholeArr[i].Split('-');
        UpdateQuery(int.Parse(temp[1]), int.Parse(temp[0]));

    }

and this is my update function :
public void UpdateQuery(int id, int newOrder)
{
    string sql = "update Tama38News set [OrderingNumber] = @OrderingNumber where [ID] = @ID";

    con = new SqlConnection(connection);
    con.Open();
    adapter = new SqlDataAdapter();
    command = new SqlCommand(sql, con);
    command.Parameters.AddWithValue("@ID", id);
    command.Parameters.AddWithValue("@OrderingNumber", newOrder);

    command.ExecuteNonQuery();
    con.Close();
}

the thing is, Im not getting any exception, but for some reason the DB doesnt get affected..
any idea why ?

A: Are you sure that you want to omit the last item in the array?
Change wholeArr.Length - 1 to wholeArr.Length
for (int i = 0; i < wholeArr.Length; i++)
{
    string[] temp = wholeArr[i].Split('-');
    UpdateQuery(int.Parse(temp[1]), int.Parse(temp[0]));
}

Maybe there was only one item, hence the method UpdateQuery was never called. You can use the debugger to check what's going on. Set a breakpoint in the loop and press F10 to go to the next line. Inspect values in the quick-watch-window.
Apart from that, you should always dispose anything that implements IDisposable especially connections best with using-statement.
public void UpdateQuery(int id, int newOrder)
{
    string sql = "update Tama38News set [OrderingNumber] = @OrderingNumber where [ID] = @ID";
    using(var con = new SqlConnection(connection))
    {
        using(var command = new SqlCommand(sql, con))
        {
            con.Open();
            command.Parameters.AddWithValue("@ID", id);
            command.Parameters.AddWithValue("@OrderingNumber", newOrder);
            command.ExecuteNonQuery();
        }
    }
}

A: Make sure that temp[1] is actually the ID you want and temp[0] is the newOrder id and that you are not mixing them up.