text:
Q: ggplot2, labels from column 1 but values from column 2 implemented automatically rather than by hand? The problem seemed simple enough. I have three columns of data in a dataframe. Row one is a score, row two is the rank, and row three is the corresponding name. I want to create a graph in ggplot2 that orders the scores by rank.
The issue is that I do not want the x label to be the rank but instead the individuals name. The other problem is that I cannot do this by hand (which would be easy enough).
An example of the data set would look like
    var1 <- c("jon", "jamie", "jessie", "jennifer", "jordan")
    var2 <- c(91, 92, 85, 99, 88)
    var3 <- c(3,2,5,1,4)
    data <- data.frame(var1, var2, var3)

I have been currently trying to use labels but that has not worked out too well. The core issue is how ggplot2 orders things.
ggplot(data, aes(x = var3, y = var2)) +
geom_bar(stat="identity") +
scale_x_discrete(name ="Name", labels = (data$var3 = data$var1))

Currently the labels are the rank. What I would like them to be are the names.
The name order should be jennifer, jamie, jon, jordan, and jessie. Instead, I just get the name order of the row, i.e. jon, jamie, jessie, jennifer, jordan.

A: This is a perhaps inelegant - using both order() and reorder() feels clunky to me - but it gets the job done with limited changes to your original script.
Setup:
library(tidyverse)

var1 <- c('jon', 'jamie', 'jessie', 'jennifer', 'jordan')
var2 <- c(91, 92, 85, 99, 88)
data <- data.frame(var1, var2)

Reorder the levels of var1:
levels(data[,'var1'])
data[,'var1'] <- reorder(data[,'var1'], -data[,'var2'])
levels(data[,'var1'])

Giving:
> levels(data[,'var1'])
[1] "jamie"    "jennifer" "jessie"   "jon"      "jordan"
> data[,'var1'] <- reorder(data[,'var1'], -data[,'var2'])
> levels(data[,'var1'])
[1] "jennifer" "jamie"    "jon"      "jordan"   "jessie"

From which we can plot as desired:
ggplot(data) +
  geom_bar(aes(x = var1, y = var2), stat = 'identity') +
  scale_x_discrete(name = 'Name', labels = levels(data[,'var1']))

A: For me it always works better this way:
library(ggplot2)
library(dplyr)

dat %>%
  arrange(ranks) %>%
  mutate(names = factor(ranks, , names, T), ranks = NULL) %>%
  ggplot(aes(x = names, y = marks)) +
  geom_col(fill = 'salmon', alpha = .5) +
  ggthemes::theme_tufte()

dat <- data.frame(
  names  = c("jon", "jamie", "jessie", "jennifer", "jordan"),
  marks  = c(91, 92, 85, 99, 88),
  ranks  = c(3, 2, 5, 1, 4)
)


text:
Q: Adding and Deleting from Stack, via Text File Data I have an assignment where I am to create a main function that takes in a text file (in this case: test.dat) and it is to interpret the file to either add or delete integers from a stack and queue.
I have the stack and queue functioning properly. However, I am not sure how to read the file and have the program actually interpret what it is saying.
For example: If the first line of the file says "add 3", the program will push 3 into the stack and enqueue 3 into the queue. If the next line of the file says "delete", it is to pop the stack and dequeue the queue.
Like I said, the enqueue/dequeue push/pop functions aren't the issue. I do not know how to get my program to actually interpret and distinguish between the integers, characters, and use this info to perform the functions.
sqjuggler.c: (this is the main function to read the file)
 #include <string.h>
#include <stdio.h>
#include "sqjuggler.h"
#include "stackADT.h"
#include "queueADT.h"

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

   Stack inStack, outStack;
   Queue inQueue;

  inStack = creates();
  outStack = creates();
  inQueue = createq();

   char *filename;
   if(argc < 2)
   {
        printf("Usage: Enter Filename after ./sqjuggler\n");
        exit(EXIT_FAILURE);
   }else if(argc > 2)
   {
        printf("Usage: Entered too many file names.\n");
        exit(EXIT_FAILURE);
   }else {filename = argv[1];}

   printf("You entered the filename: %s\n", argv[1]);

   FILE *fp = fopen(filename, "r+");
   if(fp == NULL)
   {
        printf("Cant open %s\n", filename);
        exit(EXIT_FAILURE);
   }

   char str[1000];
   while(fgets(str, 1000, fp) != NULL)
        printf("%s", str);
   fclose(fp);
}

Right now, it prints out the text file. Thats all.
Text file:
add 3
add 2
delete
add 5
delete
add 10
add 7
delete
add 0
delete
add 11
delete
delete
delete

console:
xxxxxx:~project2$ make j
gcc  -o j queueADT.c queueADT.h stackADT.c stackADT.h sqjuggler.c sqjuggler.h
xxxxxx:~project2$ ./j test.dat
You entered the filename: test.dat
add 3
add 2
delete
add 5
delete
add 10
add 7
delete
add 0
delete
add 11
delete
delete
delete

Any help is greatly appreciated!!!
EDIT
I tried to use the strtok function to split the file into tokens. When I implemented this:
char *pch;

  pch = strtok(str," \n");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok(NULL, " \n");
  }

It only printed an extra "delete"
I am unsure how to get it to split the whole file into tokens and then analyze from there.
EDIT
I added this to my while loop and got the following print out:
while(fgets(str, 1000, fp) != NULL)
   {
        printf("%s", str);
        char *value = strtok(str, " \n");
        printf("%s", value);
   }

console:
You entered the filename: test.dat
add 3
addadd 2
adddelete
deleteadd 5
adddelete
deleteadd 10
addadd 7
adddelete
deleteadd 0
adddelete
deleteadd 11
adddelete
deletedelete
deletedelete

redpajama_set_name: RedPajamaStackExchange


text:
Q: Configure location on VirtualHost I'm new at apache and have a few questions. First of all i'm working on a regional government and I have to set up in my computer a working environment, so I followed a manual they have to do that. But they also have some configuration files preconfigured that I have to copy in a virtual machine running centos which is an application server. Here is the preconfigured apache file:
<VirtualHost *:80>

ServerAdmin sti@guadaltel.es
ServerName sagir.guadaltel.es
ErrorLog logs/sagir.guadaltel.es-error_log
CustomLog logs/sagir.guadaltel.es-access_log common
RewriteEngine on
RewriteRule ^/$ /sagir [R]

<Location /TrewaAdm>
    ProxyPass ajp://localhost:8109/TrewaAdm
    ProxyPassReverse ajp://localhost:8109/TrewaAdm
</Location>

<Location /sagir>
    ProxyPass ajp://localhost:8109/sagir
    ProxyPassReverse ajp://localhost:8109/sagir
</Location>

<Location /sagir2>
    ProxyPass ajp://localhost:8209/sagir2
    ProxyPassReverse ajp://localhost:8209/sagir2
</Location>

</VirtualHost>

Well, my question is about almost everything, what does this file mean? what the tag location is for? Do I have to have a folder named "sagir" or "TrewaAdm". Well any help will be appreciated.

A: You should start by reading the user guides for Virtual Hosting and Mapping URLs to the File System. Then read the documentation for the VirtualHost, Location, ProxyPass, and ProxyPassReverse directives. Take time to read and understand that documentation. You'll come back to it over and over again.
No, you don't need to have "sagir" or "TrewaAdm" directories. If someone requests for example http://example.com/sagir from your site, this configuration will proxy (forward) the request by the AJP protocol to a listener on localhost:8109, if there is one on your server.
Good luck!


text:
Q: Surrogate Keys complicate insertion? I often see people using artifical / surrogate keys in relational databases. Thinking about it, it seems to me that while this simplifies join-Queries, it complicates the insertion of new tuples. Take the following example:
R1(a, b, c)
R2(c, d, e)
c is a surrogate primary key of R2, referenced by R1(c).
If I want to insert data in R1 and R2, I first have to check whether the to-be-inserted R2 tuple already exists in R2, and if so, I have to get its corresponding artifical key so I can reference it in the tuple for R1.
Using natural keys:
R1(a,b,d,e)
R2(d,e)
The attributes d and e are the natural primary key set for R2, referenced by R1(d,e). If I want to insert a new tuple in R1 and R2, I simply can insert them, because for the R1 tuple the foreign key (ie. value of the R2 primary key set) I reference is known.
Am I correct in my assumption or am I missing something?

A: You are correct that additional work is usually needed to process surrogate keys. You might be able to take advantage of some library code or a framework to help you with surrogate key processing but there is always a cost in terms of complexity and processing time. Similar considerations apply to queries as well as inserts. Extensive use of surrogate keys invariably means your queries will be doing more joins on average.
You should evaluate these costs against any potential benefits every time you think you want a surrogate key. Don't overuse surrogates. In many cases, and probably most cases, there is no good reason for using surrogate keys in database tables.


text:
Q: Data structure to handle array with changing indices I have an array with space for say 8 elements. I want to fill this array with numbers 8,7,...,1 at indices indicated by the following array:
7 4 4 2 1 2 0 0

You must've notices that some indices are repeating. This is so because these numbers indicate indices for the remaining array.
I will guide you through the steps of array filling so you get the idea :
Initial Array(with indices)
_ _ _ _ _ _ _ _
0 1 2 3 4 5 6 7

Step 1
_ _ _ _ _ _ _ 8
0 1 2 3 4 5 6 -

Step 2
_ _ _ _ 7 _ _ 8
0 1 2 3 - 4 5 -

Notice how the indices got updated as I filled in "7", so that I can fill "6" at index 4 too, as index 4 is a new position.
Step 3
_ _ _ _ 7 6 _ 8
0 1 2 3 - - 4 -

Step 4
_ _ 5 _ 7 6 _ 8
0 1 - 2 - - 3 -

Step 5
_ 4 5 _ 7 6 _ 8
0 - - 1 - - 2 -

Step 6
_ 4 5 _ 7 6 3 8
0 - - 1 - - - -

Step 7
2 4 5 _ 7 6 3 8
- - - 0 - - - -

and "1" can be filled at the last place.
I have solved the problem directly scanning the array for the ith empty place if I have to fill at index i. It is O(n^2). I need better.
Question: Is there a data structure that can optimize the above algorithm? Or can the algorithm itself be improved?
NOTE: I have tried using BIT, but failed.

A: Store all initial indices in a binary search tree. Also store along with each node the number of total children (all deeper levels).
As soon as you inserted one element in the array, remove its index from the tree in O(log n). At the same time update the child counts.
For the next insert in the array at index i in "new indices" you need to find the ith element in ordering of the search tree which will give you the position in "original" indices. Since the number of childs at each node can be queried, this can be done in O(log n) as well.
So the full average- and worst-case complexity is O(n log n).

A: If you accept to use additional O(n) memory you may do this:

*

*Create a helper array, which at index i stores the index of i'th free place in the original data array. So, if your original array have indexes 0 - 7 and places indexed 1, 3, 5 are free, then your helper array would look like: [1, 3, 5, -1, -1, -1, -1, -1], where -1 indicates there is no such amount of free space in the original array.

*In order to insert an element at i'th free position in the data array you do this:

    int j = helperArray[i];
    if (j > -1){
        dataArray[j] = itemYouWantToInsert;
        while (i < helperArray.size() - 1){
              helperArray[i] = helperArray[i+1];
              i++;
          }
          helperArray[i] = -1;
    }
    else
        cout<<"There are less free places in the dataArray.";

The insertion time is O(k) then, where k = (n - i). So pesimistic time of insertion is O(n), but optimistic one is O(1). isFree() is just an example method, as I do not know how do you recogize "empty space" in the dataArray.


text:
Q: TextBoxFor does not create correct name attribute for the input element in ASP.NET MVC5? I noticed that my viewmodel properties are being posted back as nulls. Upon further investigation, the problem was found to be that the name attributes of textboxes (textboxes generated via TextBoxFor helper methods) were missing the action's viewmodel variable paramter names in them.
Perhaps the example code will make it clearer -
ViewModel
public class ViewModel {
    public string ID {get;set;}
    public List<ViewModelChild> ViewCustomNames{ get; set; }
}

Controller Action (ViewModel contains a collection property ViewCustomNames)
public ActionResult Create(ViewModel viewModel1) {...}

View (strongly typed with ViewModel)
@Html.TextBoxFor(vc => vc.ID) //This will not be posted back
<input name="viewModel1.ID" type="text" /> //This will be posted back
@for(int i = 0; I < Model.ViewCustomNames.Count;i++)
    @Html.TextBoxFor(m => m.ViewCustomNames[i].SomeProperty)

Generated HTML
<input name="ID"...
<input name="ViewCustomNames[0].SomeProperty" id="ViewCustomNames_0_SomeProperty" type="text" value="">

What the generated HTML should be
<input name="viewModel1.ID"...
<input name="viewModel1.ViewCustomNames[0].SomeProperty" id="doesn't-matter-for-this-example" type="text" value="">

Question
I've fixed it by replacing the TextBoxFor(...) with explicit HTML input elements but I wonder if it's an MVC5 bug or if I'm missing something obvious here. I can't imagine the standard TextBoxFor method that ships with ASP.NET to be not working, it has to be something that I'm doing wrong. Any ideas?
----------------------------------
Adding the actual code being used in my project for reference -
Controller*
public class ViewCustomViewModelsController : Controller {
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ViewCustomId,ViewCustomName,ReconContextId,ViewCustomFieldCollection")] ViewCustomViewModel viewCustomViewModel) { }

}
View
@model AR.UI.MVC.ViewModels.ViewCustomViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

ViewCustomViewModel

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.ViewCustomId)

ViewCustomId

@*@Html.TextBoxFor(vc => vc.ViewCustomId)*@ //Posts back null
                <input name="viewCustomViewModel.ViewCustomId" type="text" value="@Model.ViewCustomId" /> //Posts back the correct value

Name

@Html.TextBoxFor(vc => vc.ViewCustomName) //Posts back null
            <input name="viewCustomViewModel.ViewCustomName" type="text" value="@Model.ViewCustomName" /> //Posts back the correct value

ReconContext

@Html.DropDownList("viewCustomViewModel.ReconContextId", ViewBag.ReconContextList as SelectList)

        Field
        @Html.DropDownList("Field", new SelectList(ViewBag.FieldList, "FieldId", "FieldName"), new { id = "ddlField" })
        Add

Id	FieldId	FieldName	DisplayOrder	SortOrder

            @for (int fieldCount = 0; fieldCount < Model.ViewCustomFieldCollection.Count; fieldCount++)
            {

                    <input name="viewCustomViewModel.ViewCustomFieldCollection.Index" type="text" value="@fieldCount" />
                    <input name="viewCustomViewModel.ViewCustomFieldCollection[@fieldCount].ViewCustomFieldId" type="text" value="@Model.ViewCustomFieldCollection[@fieldCount].ViewCustomFieldId" />
                    <input name="viewCustomViewModel.ViewCustomFieldCollection[@fieldCount].FieldId" type="text" value="@Model.ViewCustomFieldCollection[@fieldCount].FieldId" />

ViewModel
namespace AR.UI.MVC.ViewModels
{
public class ViewCustomViewModel
{
    [Key]
    public int ViewCustomId { get; set; }
    public string ViewCustomName { get; set; }
    public int ReconContextId { get; set; }
    public int ReconContextName { get; set; }
    public List<ViewCustomFieldViewModel> ViewCustomFieldCollection { get; set; }
    public ViewCustomViewModel() { ViewCustomFieldCollection = new List<ViewCustomFieldViewModel>(); }
    public ViewCustomViewModel(int viewCustomId, string viewCustomName)
    {
        ViewCustomId = viewCustomId;
        ViewCustomName = viewCustomName;
        ViewCustomFieldCollection = new List<ViewCustomFieldViewModel>();
    }
}

public class ViewCustomFieldViewModel
{
    [Key]
    public int ViewCustomFieldId { get; set; }
    public int ViewCustomId { get; set; }
    public int FieldId { get; set; }
    public string FieldName { get; set; }
    public int DisplayOrder { get; set; }
    public int SortOrder { get; set; }
    public ViewCustomFieldViewModel() { }
    public ViewCustomFieldViewModel(int viewCustomFieldId, int viewCustomId, int fieldId, string fieldName, int displayOrder, int sortOrder)
    {
        ViewCustomFieldId = viewCustomFieldId;
        ViewCustomId = viewCustomId;
        FieldId = fieldId;
        FieldName = fieldName;
        DisplayOrder = displayOrder;
        SortOrder = sortOrder;
    }
}


text:
Q: Why does a PyInstaller executable terminate when the built-in quit function is mentioned (not called)? In the below code, the list of dictionaries named options contains mention of the quit built-in function. The function is not called until it passes a check against user input. Its name is just stored in that list for when it's needed later.
def my_function():
    input("my_function successfully executed, input anything to end program> ")

def choose_from_menu():

    options =   [
                {"description":". Execute my_function.",
            "method":my_function},
                {"description":". Terminate program.",
            "method":quit}
                ]

    for i in options:
        print(str(options.index(i) + 1) + i["description"])

    chosen = input("Choose an option. > ")

    for i in options:
        if chosen == str(options.index(i) + 1):
            # here it gets called
            i["method"]()

choose_from_menu()

Run with the Python interpreter, the script lets the user choose from the printed list, and the correlating method gets picked from options and then called.
But when this script is turned into an executable with PyInstaller (on my machine, on Windows) and run, it seems to terminate the moment it sees mention of the quit function inside the options list, therefore never reaching the input prompt in the first place. (Notably, it did this with quit, but not with my_function.)
Why?
I tried defining my own method that contains a quit call, and storing that name in the dictionary instead. It does bypass this situation. However, doing that doesn't enlighten me as to the reason for this contrast between interpreter and compiler.
When the executable is run with PowerShell's Start-Process commandlet, no error is displayed.


text:
Q: Can $ f\colon \mathbb{R}^k \to \mathbb{R}^n$ such that $ \forall y \in \operatorname{im}(f)$, $f^{-1}(y) = \{a_y,b_y\} $ be continuous? This is the problem we want to solve:

Can $f\colon \mathbb{R}^k \to \mathbb{R}^n$ such that $ \forall y \in \operatorname{im}(f)$,   $ f^{-1}(y) = \{a_y,b_y\}, a_y \neq b_y $ be continuous?

Originally I've seen this question on an exam but it was stated only for the case $ k = n = 1 $ and $f$ surjective, which made it really easy to show $f$ can't be continuous, by using the Weierstrass extreme value theorem. A very similar argument seem to work for any $k$, as long as $n=1$. However, for general $k$ and $n$ this seems much harder. I don't see how surjectivity affects this problem, so I've dropped this assumption for now. Edit:Slup commented below, showing the relevance of surjectivity for this question.
Induction on $n$ and looking at projections of $f$ onto individual coordinates seemed tempting at first, but the composition of $f$ with a projection seems to lose any traces of the property that the inverse image of a point = exactly two points, so I don't see how this could be useful.
Trying to visualise this for $k=n=2$, it intuitively seems that in order to transform the space in this way, we would have to 'tear' it along some curve. For bigger $k = n$, that becomes 'tearing' along some $n-1$ dimensional manifold, but that's obviously completely informal, sort of useless and I completely have no idea how this idea could be translated into a formal proof.
Bonus question: Does the answer or the proof change in a significant way if we limit the domain to $ f:\overline{\mathbb{B}^k} \to \mathbb{R}^n $? We operate on a compact ball now, so that's fairly different from $\mathbb{R}^k$.

A: I did not read the paper of Mioduszewski mentioned in one of the posts. I only
have some partial answers when $f$ is more regular than continuous.
If $k\leq n$ and $f:\overline{B}\rightarrow\mathbb{R}^{n}$ (the bonus
question) is Lipschitz continuous, then using the area formula for Lipschitz
functions (it's in the book of Evans and Gariepy "Measure theory and fine
properties of functions")
$$
\infty>L\mathcal{L}^{k}(\overline{B})\geq\int_{\overline{B}}Jf\,dx=\int
_{\mathbb{R}^{n}}\mathcal{H}^{0}(\overline{B}\cap f^{-1}(\{y\})\,dy=\int
_{\mathbb{R}^{n}}2\,dy=\infty,
$$
which is a contradiction. Here, $Jf$ is the Jacobian of $f$, $L$ is the bound
of $Jf$, and $\mathcal{H}^{0}$ is the counting measure. If $f:\mathbb{R}%
^{k}\rightarrow\mathbb{R}^{n}$ is Lipschitz continuous and $Jf$ has finite
integral, you get the same contradiction.
If $k>n$ and $f\in C^{k+1-n}(\mathbb{R}^{k})$, then using Sard's theorem
https://en.wikipedia.org/wiki/Sard's_theorem the set of points $\{x\in
\mathbb{R}^{k}:\,Jf(x)=0\}\cap f^{-1}(\{y\})$ is empty for $\mathcal{L}^{n}$
a.e. $y\in\mathbb{R}^{n}$. Hence, if $f$ is onto or if $f(\mathbb{R}^{k})$ has
positive measure, then taking $y\in f(\mathbb{R}^{k})$ such that
$\{x\in\mathbb{R}^{k}:\,Jf(x)=0\}\cap f^{-1}(\{y\})=\emptyset$, we get that
$Jf(x)$ has rank $n$ and so we can apply the implicit function theorem to
conclude that $f^{-1}(\{y\}$ is locally the graph of a function. In particular
$f^{-1}(\{y\})$ cannot consists of two points.

A: A negative answer for the case $k>n=1$.
Let $a,b\in\mathbb R^k $ be twin points. Let $c$ and $d $ other points. Take a path from $a $ to $c $ to $d $ to $b $. By the mean value theorem the twin points are extremal on that path. Say they are minima. This remains true even if we change the point $d $ to be any point; therefore $a $and $b $ are global minima. Since this is true for any pair of twins, any such pair are extremal. But this impossible because $ \mathbb R^k$ contains more than 4 points.
The same argument holds for the closed ball.

A: (I'm assuming $f$ is surjective). Let $n=k=2$, $y \in \mathbb{R}^2, a_y=a, b_y=b.$ Consider the line between $a$ and $b$, $r$. This splits $\mathbb{R}^2$ in $2$ connected components, $P_1$ and $P_2$. Since these are connected, if $f$ was continous then their images through $f, Q_1$ and $Q_2$, would be connected as well, and their intersection would be empty. Since $r$ is also connected, its image $s$ is connected as well, and it contains $y$. Furthermore, since $f(a)=f(b)=y, s$ is not injective, in fact it splits $\mathbb{R}^2$ in at least $3$ connected components. Since continous functions can only decrease the number of connected components, we have a contradiction.
For a general case with $k=n$ i think it suffices to take an adequate number of points in order to split the domain and codomain and use a similar reasoning (eg for $k=n=3$ take two points such that their preimages are coplanar and split $\mathbb{R}^3$ using a plane and a weird surface). I also think this reasoning, if a bit modified, works for $k>n$ as well (eg if $k>n=1$, it's even simpler: $\mathbb{R}^k - \{a, b\}$ is connected but its image $\mathbb{R} - \{y\}$ is not, so $f$ is not continous).


text:
Q: Restart and monitor service from Website in IIS I have a console application that monitors a folder for imports and parses them.  I want to convert this to a Windows Service.  What I'm not sure how to do or if it's possible is have an IIS hosted website be able to show the status of that service and manually restart it if necessary. The website and the windows service would be running on the same server.

A: Yes, you can create a website that checks for the status and restarts the Windows Service by using the ServiceController class. You can refer to this answer (or even the official documentation) for sample code on both checking the status and restarting the service.
Just keep in mind that the website will have to run (under IIS settings) with a user identity that has enough privileges (normally administrator) on the server.


text:
Q: A multiple of a characteristic function is the weak limit of a sequence of characteristic functions Consider $f\in L^1(I,I)$ where $I=[0,1]$ and $ \langle f, g\rangle =\int fg $.    For any given   $\frac{m}{n}\chi_{A}$  where $\frac{m}{n}$  rational and $A$ an subinterval in $I$, how would I show that a sequence of characteristic functions $\{\chi_{A_n}\}$
$$\langle \chi_{A_n}, g\rangle \to \langle \frac{m}{n}\chi_{A}, g\rangle$$
for all continuous $g\in L^{\infty}(I,I)$?
Suppose first we divide the interval $A$ into $n$ parts with $m$ parts with values equal to $1$ and do this recursively. Then how could I continue?

A: Recall that $g$ is uniformly continuous; let $\omega$ be its modulus of continuity.
Divide the interval $A$ into $kn$ equal subinterval, where $k$ is large. Let's say the subintervals are $I_1,\dots,I_{kn}$. For $j=1,\dots, n$ define
$$
B_j = \bigcup_{r=0}^{k-1} I_{j+rn}
$$
Simply put, $B_j$ is the union obtained by taking every $n$th interval starting with $I_j$. The key point is for $j,\ell\in \{1,\dots,n\}$
$$
\left|\int_{I_j+rn}g-\int_{I_\ell+rn}g\right| \le \frac{|A|}{kn}\omega(|A|/k)
$$
which follows from the uniform continuity of $g$. (The number $|A|/k$  bounds the offset between the two intervals of integration.) Sum over $r$ to get
$$
\left|\int_{B_{j}}g-\int_{B_{\ell}}g\right| \le \frac{|A|}{n}\omega(|A|/k)
$$
Note that the right-hand side is small when $k$ is large. So, the integral over all sets $B_{j}$ are about the same. In particular, taking
$$A_k=B_1\cup\dots\cup B_m$$
achieves the goal
$$
\int_{A_k}g\to \frac{m}{n}\int_A g
$$


text:
Q: Pulling data from google spanner to BigQuery for Data Data analysis? What's the best way to pull the data from cloud spanner to BigQuery for Data Analysis?
thanks

A: You can use the Google provided dataflow template for pulling data from Spanner to GCS, then run a load job to load it into Bigquery.
Export Spanner database
Cloud Spanner to GCS AVRO

A: check this Link1. you dont need any external service to migrate data. you can directly read all spanner data through Bigquery and load it.


text: Q: How to create a DAX function that will re-calculate when the referencing table is filtered I have created a pivot table which contains measures that calculates values from another pivot table. Everything works correctly, however when I apply a filter to the referencing table, my measures don't reflect the same value, but they will if a slicer is applied. Is there a way to do this without using slicers?


text:
Q: Map Quest POI Markers Text I am working with existing Map Quest code, in that I am showing POIs with Alphabet labels . Like A B C and so on.
I want to replace them with 1 2 3 4 .... so on.
Is there any property that has to set before loading map or initializing.?
Like!

I want to replace A,B with 1,2

A: After a little research < I figured out that, MAP Quest return a image list with link, I manually replaced the last character with my index number that is 1,2,3 or whatever


text:
Q: Azure Pipeline - Why parameter value is required Hi have a pipeline with the below parameter in the .yaml file:
parameters:
- name: Proceed
   displayName: Should we proceed
   type: boolean
   default: Yes
- name: Description
   displayName: Short description
   type: string

trigger: none

stages:
- template: sometemplate.yaml
  parameters:
    Proceed: ${{ parameters.Proceed }}
    CopySomething: ${{ parameters.Description }}

When I run the pipeline, the "Description" appears to be required even thought is not specified in the parameter.  It is asking me to enter a value.  I need this to be a non-required parameter and yet don't have to be set to a default value?
Thanks

A:
Why parameter value is required

For this issue, currently this is by design: "# default value; if no default, then the parameter MUST be given by the user at runtime"

You can refer the document on github. As a workaround, agree with Krzysztof Madej, you need to set default value ''.

A: I think that your only option is default value ' ' like here:
parameters:
- name: Proceed
  displayName: Should we proceed
  type: boolean
  default: true
- name: Description
  displayName: Short description
  type: string
  default: ' '

trigger: none
pr: none

stages:
- template: sometemplate.yaml
  parameters:
    Proceed: ${{ parameters.Proceed }}
    CopySomething: ${{ parameters.Description }}

Be aware that yes is not valid value for boolean type.


text:
Q: How to check if there is any overlapping in array of range object using Joi I have a object with one of key having array of range object.
// this is valid object because startRank and endRank are not overlapping in all object
var object_1 = {
    "prizeDistribution": [
        {
            "startRank": 1,
            "endRank": 4,
            "value": 10
        },
        {
            "startRank": 4,
            "endRank": 11,
            "value": 7
        },
        {
            "startRank": 11,
            "endRank": 21,
            "value": 4
        },
        {
            "startRank": 21,
            "endRank": 51,
            "value": 2
        },
        {
            "startRank": 51,
            "endRank": 101,
            "value": 1
        }
    ]
}

// this is invalid object because startRank and endRank are overlapping
var object_2 = {
    "prizeDistribution": [
        {
            "startRank": 1,
            "endRank": 4,
            "value": 10
        },
        {
            "startRank": 3,
            "endRank": 11,
            "value": 7
        }
    ]
}

var schema = Joi.object({
    "prizeDistribution": Joi.array().items({
        "startRank": Joi.number().integer().required(),
        "endRank": Joi.number().integer().required(),
        "value": Joi.number().integer().required()
    })
})

How can I validate such array of range object using Joi?

A: You can try to achieve this through  Array.unique check in Joi. Basically mark an array item as duplicate if it falls in the range of any  other array item.
Something like below could help.
var schema = Joi.object({
      prizeDistribution: Joi.array()
        .items(
          Joi.object({
            startRank: Joi.number()
              .integer()
              .required(),
            endRank: Joi.number()
              .integer()
              .required(),
            value: Joi.number()
              .integer()
              .required()
          })
        )
        .unique((a, b) => {
          return (
            (a.startRank > b.startRank && a.startRank < b.endRank) ||
            (a.endRank > b.startRank && a.endRank < b.endRank)
          );
        })
    });

Demo

A: little small and better
var schema = Joi.object({
      prizeDistribution: Joi.array()
        .items(
          Joi.object({
            startRank: Joi.number().integer().required(),
            endRank: Joi.number().integer().required(),
            value: Joi.number().integer().required()
          })
        ).unique((a, b) => (b.endRank > a.startRank) && (b.startRank < a.endRank))
    });


text: Q: What's the geometry of the double coset space? Let $G$ be a Lie group and $K$ a compact subgroup. The double closet space $K\backslash G/K$ is important in harmonic analysis of semisimple Lie groups. How should I think about this space? $G/K$ is a nice manifold, and $G\rightarrow G/K$ is a nice principal $K$ bundle. Is there any kind of similar geometry for $G\rightarrow K\backslash G/K$? I know if $K$ is not compact, the double closet space can be quite bad, so clearly compactness would have to play some role.


text:
Q: Add multiple columns to my dataframe (if statement) I have the following Pandas DataFrame:

factor_A
factor_B
factor_C

0.0384
-0.0565
0.0964

-0.0598
0.0967
0.9156

0.8795
0.0254
-0.0853

I now want to create some new columns or a new df (factor_A_signal_A, factor_B_signal_B and so on)  with the following if statement:
If the factor_x is > 0, than 1, otherwise -1.
So far so good. But the problem is, that at the moment I don't know how many factors I will put into my dataframe and I can't do an if/else statement for example 100 columns.
Could you please help me? I need this step to multiply each factor with each signal.

A: You can loop through the columns in your DataFrame like this:
import pandas as pd

data = [
    [0.1,-0.2,0.3],
    [-0.1,0.2,0.3],
    [0.1,0.2,-0.3]
]

df = pd.DataFrame(data, columns=['factor_A', 'factor_B', 'factor_C'])

for col in df:
    new_name = col + '_signal'
    df[new_name] = [1 if x>0 else -1 for x in df[col]]

print(df)

producing the following output
   factor_A  factor_B  factor_C  factor_A_signal  factor_B_signal  factor_C_signal
0       0.1      -0.2       0.3                1               -1                1
1      -0.1       0.2       0.3               -1                1                1
2       0.1       0.2      -0.3                1                1               -1

A: On option would be np.where then join with a rsuffix:
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'factor_A': [0.0384, -0.0598, 0.8795],
    'factor_B': [-0.0565, 0.0967, 0.0254],
    'factor_C': [0.0964, 0.9156, -0.085]
})

signal_cols = pd.DataFrame(np.where(df.gt(0), 1, -1), columns=df.columns)
df = df.join(signal_cols, rsuffix='_signal')

df:
   factor_A  factor_B  factor_C  factor_A_signal  factor_B_signal  factor_C_signal
0    0.0384   -0.0565    0.0964                1               -1                1
1   -0.0598    0.0967    0.9156               -1                1                1
2    0.8795    0.0254   -0.0850                1                1               -1

str.replace can be used if columns need to be exactly as outlined in the OP:
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'factor_A': [0.0384, -0.0598, 0.8795],
    'factor_B': [-0.0565, 0.0967, 0.0254],
    'factor_C': [0.0964, 0.9156, -0.085]
})

signal_cols = pd.DataFrame(np.where(df.gt(0), 1, -1), columns=df.columns)
signal_cols.columns = (
    signal_cols.columns
        .str.replace(r'factor_(.*)', r'factor_\1_signal_\1', regex=True)
)
df = df.join(signal_cols)

df:
   factor_A  factor_B  factor_C  factor_A_signal_A  factor_B_signal_B  factor_C_signal_C
0    0.0384   -0.0565    0.0964                  1                 -1                  1
1   -0.0598    0.0967    0.9156                 -1                  1                  1
2    0.8795    0.0254   -0.0850                  1                  1                 -1

A: Thank you so much for your answer! After these signals I am now able to multiply each factor with each signal with the numpy.einsum method.
def one_one(n_factors):

    i, j = factors_table.iloc[:, 0:n_factors].shift(-1), factors_table.iloc[:, n_factors:5]
    factors_table['return_strategy'] = np.einsum('ij,ij->i', i, j) / n_factors # (i.values * j).sum(axis=1)
    return factors_table

factors_1_1 = one_one(2)
factors_1_1

factors_1_1['return_strategy'] = factors_1_1['return_strategy'].shift(1)
factors_1_1.head()

.. and gives me the following output:
pandas df return strategy


text:
Q: Checking the state of Parse email verification from swift After parse has sent the email to the entered email address, how can I check wether or not that email address has been verified from within swift and only then allow the user to log in to the app? Thanks!

A: Parse User object, has field emailVerified. So when user log in to the app you can check it:
PFUser.logInWithUsernameInBackground(email, password: password) { (user, error) in

  if error == nil{
    if let verified = user["emailVerified"] as? Bool{
      if verified == true{
       // log in
      }else{
       // show that email isn't verified
      }
    }else{
      // show that email isn't verified
    }
  }
}


text:
Q: what happens if we 'put' and new value to an already existing key in the Linkedhashmap I have a fixed set of key value pairs with which I am initializing the LinkedHashMap<String, Double>.
Does the insertion order remain the same when I do a
LinkedHashMap.put(existingKey, newValue);

To be precise my question is, when we update a value for a key using the put method, is the order of initial insertion disturbed??
If so 1) why?
2) How can I prevent this to preserve the initial order of insertion?
I chose LinkedHashMap because, I wanted a collection that supports a key value pair and maintains the the insertion order.
TIA

A: From the class doc:

Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

A:
This linked list defines the iteration ordering, which is normally
  the order in which keys were inserted into the map (insertion-order).

So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.


text:
Q: Django Debug Toolbar unexpected behaviour I have defined two serializers for a model, ListingSerializer and DetailedSerializer.
Also, there is a static function get_people_count() defined in both serializers as below:
@staticmethod
def get_people_count(obj):
  #some code

When using Django Debug toolbar, get_people_count() of ListingSerializer is called instead of DetailedSerializer's even though DetailedSerializer is returned in overridden get_serializer_class(). However, this problem doesn't occur when using Postman. Debug toolbar is updated to 1.11 version, still this issue is occuring.


text:
Q: NUnit.ConsoleRunner throwing System.ArgumentException : The net-4.5.2 framework is not available error Azure DevOps pipeline failing after updating NUnit.ConsoleRunner nuget package to to 3.15 version.
Command use to run the nunit test:
exec /Library/Frameworks/Mono.framework/Versions/Current/bin/mono --debug /Users/name/Documents/MyProject/packages/NUnit.ConsoleRunner.3.15.0/tools/nunit3-console.exe /Users/name/Documents/MyProject/TestProject.NUnitTest/bin/Release/TestProject.NUnitTest.dll

Which is throwing below error:

System.ArgumentException : The net-4.5.2 framework is not available.
Available frameworks: mono-4.0
--ArgumentException The net-4.5.2 framework is not available. Available frameworks: mono-4.0   at
NUnit.Engine.Services.TestAgency.GetAgent (NUnit.Engine.TestPackage
package) [0x0008e] in <83a050af71a545d186bc8c62a15c3005>:0    at
NUnit.Engine.Runners.ProcessRunner.CreateAgentAndRunnerIfNeeded ()
[0x0003d] in <83a050af71a545d186bc8c62a15c3005>:0    at
NUnit.Engine.Runners.ProcessRunner.RunTests
(NUnit.Engine.ITestEventListener listener, NUnit.Engine.TestFilter
filter) [0x0001f] in <83a050af71a545d186bc8c62a15c3005>:0

This is working fine with NUnit.ConsoleRunner version 3.8.0. and using target .Net framework vresion 4.5.2 able build and run the testcases in visual studio without any issue(in both the versions)
Link suggesting to edit the nunit-agent.exe.config file from package folder to add supported environment which is not possible in my case as CI/CD each time takes the fresh copy of packages.
nunit-agent.exe.configfile located in \packages\NUnit.ConsoleRunner.3.15.0\tools\ path has the following content, where it is mentioned supported runtime version to 4.0 and 2.0
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0.30319" />
    <supportedRuntime version="v2.0.50727" />
  </startup>
  <runtime>
    <legacyUnhandledExceptionPolicy enabled="1" />
    <legacyCorruptedStateExceptionsPolicy enabled="true" />
    <loadFromRemoteSources enabled="true" />
    <AppContextSwitchOverrides value="Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces=false" />
  </runtime>
</configuration>

Where as in config file of version 3.8.0 in startup tag has no exlicit mentioned platform versions.
Any hint or suggestion to resolve this issue?
Thanks

A: Looks like it may be this issue reported last week against nunit-console 3.14: https://github.com/nunit/nunit-console/issues/1130
(If it seems to apply to you, you might comment on the issue.)
Workaround would be to use an earlier console version. The reporter of the issue says 3.12 works.


text:
Q: highlights android syntax after import android gradle based project to intellij idea I decided to switch build system for Android project to Gradle 1.4. I use Intellij Idea IDE. After imported existing project tictactoe based on biuld.gradle file, I can build it but Intellij Idea doesn't highlight any Android syntax, for example: Activity.
I will be very happy if someone tell me how to fix it.

A: The solution of this problem was clean inteliij idea cache - File > Invalidate caches...


text:
Q: How do I find if two strings is isomorphic of not? #include <iostream>
#include <string>
#include <vector>

using namespace std;

bool is_isomorphic(string input1, string input2)
{
    if(input1.length()!= input2.length())
        return  false;

    vector<int> diff_arr(26, -40);//Initialise with some random value.

    for(int  i = 0 ; i < input1.length(); i++){
        if(diff_arr[input1[i]-'a'] == -40)
            diff_arr[input1[i]-'a'] = input1[i] - input2[i];
        else{
            if(diff_arr[input1[i]-'a'] != input1[i] - input2[i])
                return false;
        }
    }

    return true;
}

int main() {
    cout<<is_isomorphic("abcd", "aabb");
    return 0;
}

My logic is that if characaters could be replaced with exact same characters in the second string then the character-wise difference has to be the same throughout.
The logic is failing in the above case.

A: You also need to check if two characters from input1 do not map to same character in input2.
#include <iostream>
#include <string>
#include <map>
#include <set>

using namespace std;

bool is_isomorphic(string input1, string input2)
{
    if(input1.length()!= input2.length())
        return  false;

    set<char> usedLetters;
    map<char, char> transformations;

    for(int i = 0 ; i < input1.length(); i++) {
        auto iter = transformations.find(input1[i]);
        if (iter != transformations.end()) {
            if (iter->second == input2[i]) continue;
            else return false;
        }
        if (usedLetters.count(input2[i])) return false;
        usedLetters.insert(input2[i]);
        transformations[input1[i]] = input2[i];
    }

    return true;
}

int main() {
    cout<<is_isomorphic("abcd", "aabb");
    return 0;
}

A: You need 2 arrays, one to know which character of input2 correspond to a given character of input1, and a second to check if a character of input2 is not already affected to a character of input1.
#include <iostream>
#include <string>

using namespace std;

bool is_isomorphic(const string& input1, const string& input2)
{
    if (input1.length() != input2.length()) {
        return false;
    }

    char map[256]{};
    bool used[256]{};

    for (size_t i = 0; i < input1.length(); i++) {
        unsigned char val1 = input1[i];
        if (!map[val1]) {
            unsigned char val2 = input2[i];
            if (used[val2]) {
                return false;
            }
            map[val1] = input2[i];
            used[val2] = true;
        } else
        if (map[val1] != input2[i]) {
            return false;
        }
    }

    return true;
}

int main() {
    cout << is_isomorphic("abcd", "aabb") << endl;
    cout << is_isomorphic("abcdb", "zerte") << endl;
    return 0;
}


text:
Q: Protégé & Reasoning: Infer sameIndividualAs with enumerated classes So, here is something with OWL / Protégé I can't quite understand:
Let's say I have a class Clazz which is an enumerated class containing only the individuals I1 and I2. I then create a third individual I3 and declare it to be of type Clazz.
If I now start a reasoner, I would expect it to infer a sameIndividualAs between all (or at least some) of the indidivuals. This is not the case, I tested with both Hermit and Pellet reasoners.
If I explicitly state the three individuals to be different from each other, the ontology becomes inconsistent. Can anyone tell me why the individuals are not showing up to be sameIndividualAs in Protégé in the first case?

A: As there is no unique name assumption in OWL, the ontology is consistent until it is explicitly asserted that the manually typed individual is owl:differentFrom all of the individuals defining the class (the set restricted with owl:oneOf). If that's not asserted, in case there is more than one individual, the only inference that can be made is that, in your case, I1and I2 are members of the class Clazz. I3 should  be the same as one of the individuals, but there is no information to decide as which. You can remove this ambiguity by making Clazz defined as owl:oneOf :I1. Then there will be no ambiguity and sufficient information to infer that :I3 owl:sameAs :I1.


text:
Q: Getting All the information from two tables I'm having some issues trying to get all the information from two tables with my query
here is how my tables look
products
http://imgur.com/uI7Z8XG
products_photos
http://imgur.com/l5JSxWx
and here is my SQL query
$id = json_decode(file_get_contents('php://input'), true)["id"];

    $result = mysqli_query($con, "SELECT * FROM products INNER JOIN products_photos ON products.ProductId = products_photos.ProductId");
    $row = mysqli_fetch_object($result);

    $data = '';

    if (!is_null($row)) {
      $data = $row;
    }

    print json_encode($data);

when I do a var_dump($row) this is the result I get
object(stdClass)[3]
  public 'ProductId' => string 'pzhVrLsYXG' (length=10)
  public 'ProductName' => string 'Dell xps' (length=8)
  public 'ProductStatus' => string 'instock' (length=7)
  public 'ProductOverview' => string '' (length=0)
  public 'CategoryId' => string '5' (length=1)
  public 'CharacteristicId' => null
  public 'ReviewId' => null
  public 'ProducerId' => string '1' (length=1)
  public 'PromotionId' => null
  public 'ProductQty' => string '35' (length=2)
  public 'ProductOldPrice' => string '' (length=0)
  public 'ProductPrice' => string '2000' (length=4)
  public 'ProductLink' => string 'dell-xps' (length=8)
  public 'ProductPhoto' => string 'http://ecommerce/uploads/NDgxNzYwLWRlbGwteHBzLTg5MDAuanBn.jpg' (length=61)
  public 'PhotoId' => string '11' (length=2)
  public 'PhotoSrc' => string 'http://ecommerce/uploads/NDM5MDUzNDUzNDUuanBn.jpg' (length=49)

How can I make it so PhotoSrc returns an array of all my photos rather than a string
*Note: I'm not sure if PhotoId in the products table is needed or not

A: It looks like you're selecting the data with a full join. No. Think about it, there might be a case where you have a product without any photo, we're dealing with multiple photos possibly linked to a single product and SQL does not permit selecting array to column value so we'll have to iterate through your query result for all products and declare Photos manually
$result = mysqli_query($con, "SELECT * FROM products");
$products = array();
if ($result) //sql query was executed successfully
{
    while (($product = mysqli_fetch_object(result)) != null) //iterate through all rows
    {
        $pid = (int)$product->ProductId;
        $photoresult = mysqli_query($con, "SELECT * FROM products_photos where ProductId = $pid");
        $product->Photos = array();
        if ($photoresult) //sql query was executed successfully
        {
            while (($photo = mysqli_fetch_object($photoresult)) != null) //iterate through all rows
            {
                //push the photo into the products photo array
                array_push($product->Photos, $photo);
            }
        }
        //push the product into products array
        array_push($products, $product);
    }
}

var_dump($products);//for debugging purpose (todo: remove)

A: I think you need to first split images and products apart...
$images = array_map(function($element){; return [$element['ProductId'] => $element['PhotoSrc']];}, $products);

And then loop through the array and add push the value into the photosrc array.

A: First of all, in case you'd expect products which do not have photos, you should probably use a left join (use all rows from the first table and join rows from second table if there are any):
SELECT * FROM products LEFT JOIN products_photos ON products.ProductId = products_photos.ProductId

The statement will give you the product along with every photo, in case there is one (be careful, the product will hence be the same in 2 rows, only the latter part with the image will change). The reason you don't get this from the inner join (which would also work in the case every product has at least one photo) is that mysqli_fetch_object returns only the current row (see http://www.w3schools.com/php/func_mysqli_fetch_object.asp for a solution to loop all rows).
The photoId in the products table is not needed for this kind of relationship.


text:
Q: Sum array values depending dates non-singularity Let's say I have 2 same sized arrays filled with values. The dates array contains dates in string format and the costs array contains numeric costs.
For instance:
$dates = array('2001-01-01', '2001-02-01', '2001-02-01', '2001-02-01', '2001-03-01', '2001-04-01', '2001-04-01', '2001-05-01');
$costs = array(5, 10, 20, 4, 30, 14, 2, 0);

What I want is to sum the numbers from the costs array into a new array only when the dates in the $dates array are repeated. When this happens, the new array value must be a sum of its "left siblings".The rest new array value(s) should be 0. In other case (when the date is unique in the array, then the new array value is 0).
This should be the result of the above proccess:
$newarr = array(5, 0, 0, 34, 30, 0, 16, 0);

A: How about this?
$result = $costs;
foreach ($dates as $i => $d) {
    if ($i > 0 && $dates[$i - 1] == $dates[$i]) {
        $result[$i] += $result[$i - 1];
        $result[$i - 1] = 0;
    }
}
print_r($result);

We're starting with our $costs array, and looping through all the dates... every time we detect that the date is the same as the previous entry, we zero out the previous entry and add it's value to our current location.
Alternate Solution
This isn't exactly what you asked for, but I suspect a more useful solution might be this:
$result = array();
foreach ($dates as $i => $d) {
    $result[$d] = (isset($result[$d]) ? $result[$d] : 0) + $costs[$i];
}
print_r($result);

This will produce a result of:
array(
    '2001-01-01' => 5,
    '2001-02-01' => 34,
    '2001-03-01' => 30,
    '2001-04-01' => 16,
    '2001-05-01' => 0
)


text:
Q: generate barcode on android google sheets I have a Google Sheet that we use to generate picking tickets for our warehouse.  There are several columns that have barcodes.  They are generated using the following function call:
=image("http://www.barcodesinc.com/generator/image.php?code=" & E3 & "&style=68&type=C128B&width=200&height=80&xres=1&font=0", 3)
This works perfectly and does exactly what we need it to do, which is using a PC to print the ticket and hand it off to the warehouse guys.
In my attempt to make the process more streamlined I want to replace the tickets with an Android tablet and let them scan from there.  The benefit to that is that they can also manually update the Sheet with exceptions and other items that are not bar coded.  Here is what I have run into:

*

*On the android if I view the Sheet through the Chrome browser it I can see the bar codes fine, but as soon as I hit the edit button, it opens the sheet in the Sheets app and I can no longer see the bar codes.

*If I open the sheet in the Sheets app I can edit the cells but can't see the bar codes.
Note, when using my PC workstation I can see the bar codes and edit the sheet with no problems.

So, not sure if this is actually a programming question or not, but what can I do in order to be able to view the bar codes in the Sheets app or to be able to edit the sheet in the browser like I do on my PC?  Yes, I have requested the desktop site in options for Chrome.
Any help would be appreciated, I would really like to roll this out and save some paper.

A: I am now answering my own question in case anyone runs into this.  You need to request the desktop site (in Chrome options) as soon as you log into Google Drive AND after you open the sheet.  Now the sheet will switch from view only mode to edit mode in the browser.
Bonus question: Is there anyway you can force the browser to always open stuff in the desktop site?  Specifically for Google stuff, but for any other site really since larger tablets can handle the 'full' site and don't need to be redirected to the m.version of the site.


text:
Q: ssh and nodejs application I have a nodejs application which run some shell commands. I want to execute these commands in another machine by using ssh.
I have this:
snapInfo(snapName: string) {
    return `snap info ${snapName}`;
}

I need something like this:
snapInfo(snapName: string) {
    return `ssh user@host snap info ${snapName}`;
}

the file is a .ts file. How can I do it? Any suggestions? It's the first time I see a nodejs app.
Thanks in regard

A: You could use the excellent ssh2 module for Node.js.
npm install ssh2
And then you can connect to your remote system like this by adding a new function execSSHCommand which can be used instead of execCommand in the file shell-commands.ts.
import { Injectable } from '@nestjs/common';
import { promisify } from 'util';
import { exec } from 'child_process';
import { Client } from 'ssh2'

const exec_promise = promisify(exec);

function execute_over_ssh(cmd: string): Promise<{ stdout: string; stderr: string; }> {
  return new Promise<{ stdout: string; stderr: string; }>((resolve, reject) => {
    let conn = new Client();
    conn.on('ready', function () {
      let stdout = "", stderr = "";
      conn.exec(cmd, function (err, stream) {
        if (err) reject(err);
        stream.on('close', function (code, signal) {
          resolve({ stdout, stderr });
          conn.end();
        }).on('data', function (data) {
          stdout += data.toString('utf8');
        }).stderr.on('data', function (data) {
          stderr += data.toString('utf8');
        });
      });

    }).connect({ host: '127.0.0.1', port: 22, username: 'user', password: 'pass' });
  });
}

@Injectable()
export class ShellService {

  async execCommand(cmd: string, password?: string): Promise<string> {
    if (password) {
      // TODO: Possibly remove
      const command = `echo ${password} | sudo -S ${cmd}`;
      const { stdout, stderr } = await exec_promise(command);
      return stdout;
    } else {
      const command = `${cmd}`;
      const { stdout, stderr } = await exec_promise(command);
      return stdout;
    }
  }

  async execSSHCommand(cmd: string): Promise<string> {
    const command = `${cmd}`;
    const { stdout, stderr } = await execute_over_ssh(command);
    return stdout;
  }

}


text:
Q: writing a if-else-then fucntion I am trying to write a function to call a function from a package, snippets as below:
library(optionstrat)

# sameple detla
# do not run
# calldelta(s,x,sigma,t,r)
# putdelta(s,x,sigma,t,r)

x=10
sigma=0.25
t=0.25
r=0.05

delta<-function(option_type,stock_price) {
    if (option_type="c") {
        delta<-calldelta(s,x,sigma,t,r)
    } else {
        delta<-putdelta(s,x,sigma,t,r)
    }
}

both calldelta and putdelta are built in functions from optionstrat package, and I would like to write a function so that if option_type="c", then return with a call delta value based on the stock price input. Likewise, if option_type!="c", then return with a put delta value based on the stock price input.
My end goal here is to come up with a function like delta(c,10) then return with a call delta value based on stock price 10. May I know how should I do from here? Thanks.
Update 1:
Now I try working with the below snippets:
x=10
sigma=0.25
t=0.25
r=0.05

stock_delta<-function(option_type,s) {
    if (option_type="c") {
        delta<-calldelta(s,x,sigma,t,r)
    } else {
        delta<-putdelta(s,x,sigma,t,r)
    }
}

And again, if I define optiontype equals to c & s equals to 10, the same warning msg is returned...
Update 2:
Thanks to @akrun, now the function is created & now I would like to add one more return value from the delta function by adding:
calleval(s,x,sigma,t,r)$Gamma
puteval(s,x,sigma,t,r)$Gamma

The first line will return with the call gamma value & the latter will return with put gamma. May I know how do I string it with the function written previously?

A: There are multiple issues in the function - 1) function arguments passed should match the arguments to the inner function, 2)  = is assignment and == is comparison operator, 3) if the last statement is assigned to an object, it wouldn't print on the console.  We may either need to return(delta) or in this case there is no need to create an object delta inside (when the function name is also the same), 4) Passing unquoted argument (c) checks for object name c and even have an additional issue as c is also a function name.  Instead, pass a string "c" as is expected in the if condition
delta<-function(option_type,stock_price)
{

 if (option_type=="c")
    calldelta(stock_price,x,sigma,t,r)
else
    putdelta(stock_price,x,sigma,t,r)
}

-testing
> delta("c", 10)
[1] 0.5645439


text:
Q: Docker Memory usage and Server stuck We are getting an issue on Ubuntu EC2 instance, we are running 8 docker container on Amazon EC2 instance which is having 30 GB memory and 16 cores. What we observed our EC2 being stuck after 3-4 days of reboot and in the logs we are getting Memory issues. When we monitored to docker stats command it shows every Docker is running on less than 2GB (Total used 16G) on the EC2 when we ran the free –g command it shows the used memory is around 16-17GB and other memory is in buff / cache and Free is having 0.
Please let us know There is any issue or we have to do any configuration. I tried to drop the cache but it got filled in 10 minutes.
Versions –
Ubuntu – 16.04 ( xenial)
Docker -  17.09.0-ce
Please let me know if required more details for troubleshooting.
Thanks,


text:
Q: Safe to use WMI to remotely recycle IIS app pools on production servers? What are the downsides to enabling & using WMI to remotely manage IIS?
I plan to have a specific user account (non-admin) with only Execute Methods, Enable Account, and Remote Enable WMI permissions on the root\MicrosoftIISv2 namespace.  It will be used primarily to recycle various app pools, no changing any settings.
Are there any other security or performance concerns I need to be aware of with this solution?  Accessing WMI can only be done over our VPN, and only either Admins or this heavily restricted account have access to WMI.  Is there anything I'm missing?
Thanks


text:
Q: OperatorNotAllowedInGraphError in fitting modeling in BERT using transformer in tensorflow I just learned tensorflow and I am currently creating a model for fine-tunning a bert model whose pretrained model was recieved via the transformer package
from transformers import BertTokenizerFast, TFAutoModel

model_name = 'ckiplab/bert-base-chinese'
tokenizer = BertTokenizerFast.from_pretrained(model_name)
bert = TFAutoModel.from_pretrained(model_name, from_pt = True)

My code is as below, and most of them refer to this post
def tf_encode(input):
  def encode(input):
      # breakpoint()
      corpus = [c.decode('utf-8') for c in input.numpy()]
      # breakpoint()
      tokened = tokenizer(corpus, return_tensors = 'tf',max_length=128, padding = 'max_length', truncation=True)
      return tokened['input_ids'], tokened['attention_mask']
  return tf.py_function(func = encode, inp = [input], Tout = (tf.int32, tf.int32))

def build_classifier_model():
    input = tf.keras.layers.Input(shape=(1,None), dtype=tf.string)

    input_id, attention_mask = tf_encode(input)
    # breakpoint()
    input_id.set_shape(tf.TensorShape((None, None)))
    attention_mask.set_shape(tf.TensorShape((None, None)))
    output = bert(input_ids = input_id, attention_mask=attention_mask)['pooler_output']
    fine_tune_model = tf.keras.layers.Dropout(0.1)(output)
    fine_tune_model = tf.keras.layers.Dense(1, name = "classifier")(fine_tune_model)
    return tf.keras.Model(inputs = input, outputs = fine_tune_model)

It works perfectly during eager mode,
print(corpus)

build_classifier_model()(corpus)

Out
tf.Tensor(
[b'2.\xe8\x82\x8c\xe8\x82\x89\xe9\x81\x8b\xe5\x8b\x95\xe4\xb8\x8d\xe8\xb6\xb3\xef\xbc\x8c\xe8\x84\x82\xe8\x82\xaa\xe5\xb0\xb1\xe6\x9c\x83\xe5\x9b\xa4\xe7\xa9\x8d'
 b'3.\xe8\x82\x8c\xe8\x82\x89\xe9\x81\x8b\xe5\x8b\x95\xe9\x81\x8e\xe5\xba\xa6\xef\xbc\x8c\xe7\xad\x8b\xe8\x86\x9c\xe5\xb0\xb1\xe6\x9c\x83\xe7\xb7\x8a\xe7\xb9\x83\xe4\xb8\xa6\xe8\xae\x93\xe9\x97\x9c\xe7\xaf\x80\xe8\xae\x8a\xe7\xa1\xac'], shape=(2,), dtype=string)
<tf.Tensor: shape=(2, 1), dtype=float32, numpy=
array([[ 0.01183807],
       [-0.5373523 ]], dtype=float32)>

but
I have this error when fitting the dataset after compiling:
OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

I guess it comes from the part which I turn the byte string into strings so that the tokenizer accepts (line 4 in the second code block).
I did some research and it seems that I have to wrap the function with a for loop with a @tf.function on my tf_encode function. However, this step turns out to be way more tragical and harder for me to debug or even look for solutions.
Therefore I would like to ask if there is a way to substitude the list comprehension that decodes the sentence to utf-8 strings.
I tried something like this
tf.map_fn(lambda c: c.numpy().decode('utf-8'), input)

but it somehow got parsed pack into byte strings:
<tf.Tensor: shape=(2,), dtype=string, numpy=
array([b'2.\xe8\x82\x8c\xe8\x82\x89\xe9\x81\x8b\xe5\x8b\x95\xe4\xb8\x8d\xe8\xb6\xb3\xef\xbc\x8c\xe8\x84\x82\xe8\x82\xaa\xe5\xb0\xb1\xe6\x9c\x83\xe5\x9b\xa4\xe7\xa9\x8d',
       b'3.\xe8\x82\x8c\xe8\x82\x89\xe9\x81\x8b\xe5\x8b\x95\xe9\x81\x8e\xe5\xba\xa6\xef\xbc\x8c\xe7\xad\x8b\xe8\x86\x9c\xe5\xb0\xb1\xe6\x9c\x83\xe7\xb7\x8a\xe7\xb9\x83\xe4\xb8\xa6\xe8\xae\x93\xe9\x97\x9c\xe7\xaf\x80\xe8\xae\x8a\xe7\xa1\xac'],
      dtype=object)>

which can't be accepted in the tokenizer.


text:
Q: How to repeat query on different parts of a dataset in R? I want to repeat a particular query on a large dataset and I am sure the answer to my question is quite basic, but after reading various sources on 'for' loops, repeat and replicate functions for about 2 hours, I still can't find any examples which appear to do what I need to do.
The dataset contains survey data from particular sites which are split into plots and each plot contains multiple species entries so the data looks like this:
SITE    PLOT    SPECIES
1          1    a
1          1    b
1          2    a
1          2    c
1          3    b
1          3    c
1          3    d
1          4    a
1          5    a
1          5    b
2          1    b
2          1    c
2          3    a
2          3    b
2          4    b
2          4    c
2          4    d
2          5    e

The actual data is over 6500 rows as there are hundreds of sites and each should contain 20 plots - the issue is some plots are missing from some sites, so what I need to do is establish how many plots are missing in total. I can use the following code to query how many unique plots are on each site so in the example below I query how many unique plots are in site number 7:
NROW(unique(df$PLOT[df$SITE=="7"]))

   [20]

But I have hundreds of sites, so is there a function that will allow me to query each site automatically without manually changing the site number each time?

A: Here is a base R way with tapply.
x <- '
SITE    PLOT    SPECIES
1          1    a
1          1    b
1          2    a
1          2    c
1          3    b
1          3    c
1          3    d
1          4    a
1          5    a
1          5    b
2          1    b
2          1    c
2          3    a
2          3    b
2          4    b
2          4    c
2          4    d
2          5    e'
df1 <- read.table(textConnection(x), header = TRUE)

num_plots <- with(df1, tapply(PLOT, SITE, \(x) length(unique(x))))
which(num_plots != max(num_plots))
#> 2
#> 2

Created on 2022-05-26 by the reprex package (v2.0.1)

A: Not quite sure what you're going for but does this help?
Using data.table:
df <- read.table(text='SITE    PLOT    SPECIES
1          1    a
1          1    b
1          2    a
1          2    c
1          3    b
1          3    c
1          3    d
1          4    a
1          5    a
1          5    b
2          1    b
2          1    c
2          3    a
2          3    b
2          4    b
2          4    c
2          4    d
2          5    e', header=TRUE)
library(data.table)
setDT(df)[, .(plots=uniqueN(PLOT)), by=.(SITE)]
##    SITE plots
## 1:    1     5
## 2:    2     4


text:
Q: Openlayers: add padding to zoom in on a cluster I need to add a padding to a zoom in on cluster function. I've used a part of this code to do this.
var zoomCluster = function(pixel) {

  var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
    return feature;
  });

  if (feature) {

    var features = feature.get('features');
    if (features.length > 0) {
      var extent = ol.extent.createEmpty();
      features.forEach(function(feature) {
        ol.extent.extend(extent, feature.getGeometry().getExtent());
      });
      map.getView().fit(
        extent,
        [500, 0, 500, 0],
      );

    }

  }

};

map.on('click', function(evt) {
  zoomCluster(evt.pixel);
});

I can click on a cluster and zoom in it without problem but it seams that tha padding is ignored.
What I've wrong?

Edit GeoJSON
{
    "type": "FeatureCollection",
    "features": [
        {
            "id": 1,
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    18.480233975421925,
                    50.937583702324076
                ]
            },
            "properties": {
                "publishing_date": "2020-06-25T15:00:37",
                "livability": "4.00"
            }
        },
        {
            "id": 2,
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    14.25,
                    40.83333
                ]
            },
            "properties": {
                "publishing_date": "2020-06-28T18:27:47",
                "livability": "1.57"
            }
        },
        {
            "id": 3,
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    17.09611,
                    50.69667
                ]
            },
            "properties": {
                "publishing_date": "2020-06-28T18:28:50",
                "livability": "4.14"
            }
        },
        {
            "id": 4,
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    16.00228,
                    50.48138
                ]
            },
            "properties": {
                "publishing_date": "2020-06-28T18:29:17",
                "livability": "2.71"
            }
        }
    ]
}

Cluster code
var clusterDistance = 100;

var clusterSource = new ol.source.Cluster({
  source: new ol.source.Vector({
      url: api_url,
      format: new ol.format.GeoJSON(),
  }),
  distance: clusterDistance,
});

var styleCache = {};
function getStyle (feature, resolution) {
  var size = feature.get('features').length;
  var style = styleCache[size];
  if (!style) {
    var color;
    if ( size>clusterDistance ) {
      color = "rgba(192,0,0,0.75)";
    } else if ( size>clusterDistance/3 ) {
      color = "rgba(255,128,0,0.75)";
    } else if ( size>1 ) {
      color = "rgba(0,128,0,0.75)";
    } else {
      color = "rgba(0,0,255,1.0)";
    }
    var radius = (Math.max(8, Math.min(size*0.75, 20))) * 1.5;
    style = styleCache[size] = new ol.style.Style({
      image: new ol.style.Circle({
        radius: radius,
        stroke: new ol.style.Stroke({
          color: "rgba(255,0,0,1.0)",
          width: 0.75,
          lineDash: [3, 3],
        }),
        fill: new ol.style.Fill({
          color: color
        })
      }),
      text: new ol.style.Text({
        scale: radius/8,
        text: size.toString(),
        fill: new ol.style.Fill({
          color: 'rgba(255,255,255,1.0)'
        })
      })
    });
  }
  return style;
};

var cluster = new ol.layer.Vector({
  source: clusterSource,
  style: getStyle,
});
map.addLayer(cluster);

A: Correct syntax for padding option of OpenLayers view.fit method is:
view.fit(extent, {padding: [topPadding, rightPadding, bottomPadding, leftPadding]});

As @JGH noted, top and bottom padding of 500 is simply too much for most of the monitors/maps.


text:
Q: How to add image to information windows in Google Maps Api v3 android I wanna know how to add an image inside of the information box event from google maps markers.
Hello, guys! I need some help about how to add an image inside of the information box event that shows up when you click in the marker.
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
    //Parking 1 Central Park Rua Arlindo Colaço - SM 216
     LatLng est1 = new LatLng(-23.492668, -46.4419270);
    mMap.addMarker(new MarkerOptions().position(est1).title("Central Park").snippet("Rua Arlindo Colaço, 216"));

This Peace of code is adding one marker into the google maps in my android Project and it shows that information "Central Park" as a title and "Rua Arlingo Colaço, 216" as a line of text.

A: All you have to do is customize the info window.Please have a look at this :
Custom info window for google maps android


text:
Q: Firebase Crashlytics console not showing crashes After following the instructions to integrate Firebase / Crashlytics into an iOS project in Xcode 10.3, I am using Crashlytics.sharedInstance().crash() to test, but the crashes are not showing up in the Crashlytics console (I've waited up to 24 hours and see nothing).
I see this in the log
[Crashlytics:Crash] report submission successful

But nothing shows up in the console.  It does show "I have 50% crash free users", but there is no stack trace and the Crashes show 0 as well.
From my Podfile:
pod 'Firebase/Analytics'
pod 'Fabric', '~> 1.10.2'
pod 'Crashlytics', '~> 3.13.4'

From my logs
[Crashlytics] Version 3.13.4 (143)
2019-08-29 12:13:08.435079-0500 App[58538:12666639]

[Crashlytics] Running on iPhone11,8, 12.4.0 (16G77)
2019-08-29 12:13:08.443235-0500 App[58538:12766639]

[Crashlytics:Crash:Reports:Event] Registered Firebase Analytics event listener

[Fabric] Initialized with kit versions: {
    "com.twitter.answers.ios" = "1.4.1";
    "com.twitter.crashlytics.ios" = "3.13.4";
    "io.fabric.sdk.ios" = "1.10.2";
}

In my build phases I have this code:
"${PODS_ROOT}/Fabric/run

and Input Files (I've tried many variations of this path, not sure if it's working correctly):
${BUILT_PRODUCTS_DIR}/GoogleService-Info.plist

also tried the original instructions path, trying to troubleshoot, but nothing changed.
Also, when I enable debug view, when it crashes I see app_exception come across the stream.

A: User reached out to Firebase customer support. The issue had to do with illegal characters in the form of whitespace being present in the version name of the app. Removing the white space seemed to restore proper crash reporting on the users Firebase Dashboard.


text:
Q: Disable mongoldb health indicator Micronaut i want to disable health indicator for Micronaut, mi application cannot check the health for db. Im using Micronaut framework.
disable health indicator im getting the
Path Taken: new HealthMonitorTask(CurrentHealthStatus currentHealthStatus,[List healthIndicators]) --> new MongoHealthIndicator(BeanContext beanContext,[HealthAggregator healthAggregator],MongoClient[] mongoClients)````

Do you know how to disable health but without getting this error?

A: The easiest way is probably just to replace the implementation with one that always returns UP:
@Singleton
@Requires(beans = MongoClient.class)
@Replaces(MongoHealthIndicator.class)
public class MyMongoHealthIndicator implements HealthIndicator {

    @Override
    public Publisher<HealthResult> getResult() {
        return Publishers.just(buildStatus("mongodb"));
    }

    private HealthResult buildStatusUp(String name) {
        HealthResult.Builder builder = HealthResult.builder(name);
        builder.status(HealthStatus.UP);
        return builder.build();
    }
}


text:
Q: Android drawing to the canvas a large bitmap, while keeping ratio and fill screen centered i am loading a bitmap to be drawn but it is about 25px off from the right of the screen. I am not sure why this is happening.
   scaleWallpaperBitmap(R.drawable.board2);
   canvas.drawBitmap(board, 0, topOffset, null);

   private void scaleWallpaperBitmap(int res) {
      // read bitmap in project
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeResource(getResources(), res, options);
      int imgH = options.outHeight;
      int imgW = options.outWidth;

    // get new bitmap and find how to center it
    if (imgH == imgW) {
        // easy case of a square wallpaper
        if (screenH > screenW) {
            board = decodeSampledBitmapFromResource(getResources(), res,
                    screenW, screenW);
            verticalBitmapOffset = true;
            horizontalBitmapOffset = false;
            topOffset = (screenH - board.getHeight()) / 2;
        } else {
            board = decodeSampledBitmapFromResource(getResources(), res,
                    screenH, screenH);
            horizontalBitmapOffset = true;
            verticalBitmapOffset = false;
            leftOffset = (screenW - board.getWidth()) / 2;
        }
    } else {
        // ratio is now involved
    }
}

the rest of the methods are from the android docs here...
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
the image is almost perfectly scales and centered with it centered vertically, but it's not the full
screen width it should be. There is about 25 px of free space on the right margin.
any feedback would be great!
thanks


text:
Q: chat room whit gif and emoji and image Java I want to build a chat room whit java swing.
I want to have a component to show text, image, gif and emoji.
please help me to select a good component.
In first I choose JtextPane for this.Is it good?

A:
In first I choose JtextPane for this.Is it good?

Yes, I would use a JTextPane, with normal text (not HTML). With a JTextPane you can:

*

*text with attributes.

*align text to the right/left of the text pane

*display icons using the insertIcon(...) method.

Read the section from the Swing tutorial on Text Component Features for some examples that use attributes when adding text.


text:
Q: how to get scala string split to match python I am using spark-shell and pyspark to do word count on one article. scala flatmap on line.split(" ") and python split() get different word counts (scala has more). I tried split(" +") and split("\W+") in the scala code, but can not get the count to come down to the same as the python one.
Anyone knows what pattern would match python exactly?

A: Python's str.split() has some special behaviour for default separator:

runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
For example, ' 1  2   3  '.split() returns ['1', '2', '3']

The easiest way to fully match this in Scala is probably like this:
scala> """\S+""".r.findAllIn(" 1  2   3  ").toList
res0: List[String] = List(1, 2, 3)

scala> """\S+""".r.findAllIn("   ").toList
res1: List[String] = List()

scala> """\S+""".r.findAllIn("").toList
res2: List[String] = List()

Another way is to trim() the string beforehand:
scala> " 1  2   3  ".trim().split("""\s+""")
res3: Array[String] = Array(1, 2, 3)

But that doesn't have the same behaviour as Python for empty strings:
scala> "".trim().split("""\s+""")
res4: Array[String] = Array("")

In Scala split() of an empty string returns an array with one element, but in Python the result is a list with zero elements.


text:
Q: What is the purpose of "uber mode" in hadoop? Hi I am a big data newbie. I searched all over the internet to find what exactly uber mode is. The more I searched the more I got confused. Can anybody please help me by answering my questions?

*

*What does uber mode do?

*Does it works differently in mapred 1.x and 2.x?

*And where can I find the setting for it?

A: What is UBER mode in Hadoop2?
Normally mappers and reducers will run by ResourceManager (RM), RM will create separate container for mapper and reducer.
  Uber configuration, will allow to run mapper and reducers in the same process as the ApplicationMaster (AM).
Uber jobs :
Uber jobs are jobs that are executed within the MapReduce ApplicationMaster. Rather then communicate with RM to create the mapper and reducer containers.
   The AM runs the map and reduce tasks within its own process and avoided the overhead of launching and communicate with remote containers.
Why
If you have a small dataset or you want to run MapReduce on small amount of data, Uber configuration will help you out, by reducing additional time that MapReduce normally spends in mapper and reducers phase.
Can I configure an Uber for all MapReduce job?
As of now,
map-only jobs and
jobs with one reducer are supported.

A: In terms of hadoop2.x, Uber jobs are the jobs which are launched in mapreduce ApplicationMaster itself i.e. no separate containers are created for map and reduce jobs and hence the overhead of creating containers and communicating with them is saved.
As far as working (with hadoop 1.x and 2.x) is concerned, I suppose the difference is only observable when it comes to terminologies of 1.x and 2.x, no difference in working.
Configuration params are same as those mentioned by Navneet Kumar in his answer.

PS: Use it only with small dataset.

A: Pretty good answers are given for "What is Uber Mode?"
Just to add some more information for "Why?"
The application master decides how to run the tasks that make
up the MapReduce job. If the job is small, the application master may choose to run the tasks in the same JVM as itself. This happens when it judges the overhead of allocating and running tasks in new containers outweighs the gain in running them in parallel, when compared to running them sequentially on one node.
Now, the questions could be raised as "What qualifies as a small job?
By default, a small job is one that has less than 10 mappers, only one reducer, and an input size that is less than the size of one HDFS block.

A: Uber Job occurs when multiple mapper and reducers are combined to use a single container. There are four core settings around the configuration of Uber Jobs in the mapred-site.xml. Configuration options for Uber Jobs:

*

*mapreduce.job.ubertask.enable

*mapreduce.job.ubertask.maxmaps

*mapreduce.job.ubertask.maxreduces

*mapreduce.job.ubertask.maxbytes
You can find more details here: http://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.1.15/bk_using-apache-hadoop/content/uber_jobs.html


text:
Q: Closure of category of sheaves under inverse limits. How do I show that the category of sheaves on a space $X$ taking values in , a category $K$ admitting inverse limits, admits inverse limits?
The limit is a presheaf, I tried to show that it is also a sheaf but I cannot establish the existence of the morphisim from any given object $T$ in $K$ to $F(U)$ satisfying the definition of a sheaf (as in the stacks project for example).


text:
Q: how can i modify attributes without adding the component in Wicket? I have to add a class to a component. I can't add the component via ajax because this is a problem with the input. My code is:
private ListView<Opzioni> setListOpzioni(boolean b) {

    return new ListView<Opzioni>("list_opzioni", opzioniDao.findAll()) {

        @Override
        protected void populateItem(ListItem<Opzioni> item) {
            erroriAssociatiAlTextField = new HashMap<>();
            List<Opzioni> opzioniCron = opzioniDao.getOpzioniFormatore();

            final Opzioni o = item.getModelObject();

            final WebMarkupContainer errorContainer = new WebMarkupContainer("errorContainer");
            errorContainer.setOutputMarkupId(true);
            errorContainer.setOutputMarkupPlaceholderTag(true);

            Boolean isSelected = false;
            Boolean isAzienda = o.getAzienda() != null ? o.getAzienda().equals(getAziendaLogged()) : false;
            if (isAdminFormatore(getUserLogged())) {
                isSelected = o.getControlFormatore() || isAzienda;
            } else {
                isSelected = isAzienda;
            }

            Boolean visibile = isSa || isSelected;

            Label name_op = new Label("name_op", o.getName());
            item.add(name_op.setVisible(visibile));

            TextField val_op = new TextField("val_op", new PropertyModel(o, "val"));
            val_op.add(new OnChangeAjaxBehavior() {
                @Override
                protected void onUpdate(AjaxRequestTarget art) {
                    if (opzioniCron.contains(o)) {
                        controllaStringa(o);
                    }
                    if (valoriScorretti == true) {
                        contatore++;
                    } else {
                         contatore = 0;
                    }
                    if (contatore > 0) {
                         ciSonoErrori = true;
                         String error = "Valori inseriti nel box " + o.getName() + " non corretti";

                    if (!erroriAssociatiAlTextField.containsKey(o)) {
                         erroriAssociatiAlTextField.put(o, error);
                    }

                    for (Map.Entry<Opzioni, String> map : erroriAssociatiAlTextField.entrySet()) {
                        val_op.error(map.getValue());
                    }
                    art.add(errorContainer.setVisible(true));
                    refreshFp(art);
                    art.add(save_btn.setVisible(false));
                    } else {
                        ciSonoErrori = false;

                        if (!erroriAssociatiAlTextField.isEmpty()) {

                            art.add(save_btn.setVisible(false));

                            if (erroriAssociatiAlTextField.containsKey(o)) {
                                    erroriAssociatiAlTextField.remove(o);

                            }

                            for (Map.Entry<Opzioni, String> map : erroriAssociatiAlTextField.entrySet()) {
                                 val_op.error(map.getValue());
                            }
                        }
                        if (erroriAssociatiAlTextField.isEmpty()) {
                            art.add(save_btn.setVisible(true));
                        }
                        art.add(errorContainer.setVisible(false));

                        refreshFp(art);

                        }
                    }
                });
                item.add(val_op.setEnabled(b).setVisible(visibile));

                item.add(errorContainer.setVisible(false));

                if (visibile) {
                    o.setModificato(true);
                } else {
                    o.setModificato(false);
                }
            }
        };
    }

With this code every time a user insert a letter inside the field the cursor go to the first position and it's impossible to use it. Is there an alternative mode to add the class dynamically?

A:
With this code every time a user insert a letter inside the field the
  cursor go to the first position and it's impossible to use it.

That is because of the OnChangeAjaxBehavior you are using.
This behavior checks after every user input if the FormComponent validates correct and if it does it will call the onUpdate method.
For a TextField without an IValidator added that means onUpdate is called after every input. If you then reprint the TextField via AjaxRequestTarget you get the behaviour of an input field where you type "backwards" as you currently do.

how can i modify attributes without adding the component in Wicket?

If you want you're changes to be visible in the browser then you need to update the component with ajax at some point. There is no way around it.
You probably have to rethink you're aproach because what you are currently doing doesn't make much sense.
At the moment you have a TextField and when the user enters something that is valid you add the css class "field-error" to the html input.

*

*Shouldn't it be the other way around and the " field-error" should get added when the users enters something that is invalid?

*Do you really want to validate and do an ajax update while the user enters something? Why not validate the input when the form/textfield actually gets submitted, or when the user is done typing into the field?

Edit
Instead of updating the input with the AjaxRequestTarget you could use the AjaxRequestTarget to send the jQuery command to add the css class to the input:
val_op.setOutputMarkupId(true);
val_op.add(new OnChangeAjaxBehavior() {
     @Override
     protected void onUpdate(AjaxRequestTarget art) {
          art.appendJavaScript("$('#"+val_op.getMarkupId()+"').addClass('field-error');");
    }
}

Instead of updating the whole input via ajax, this will just send a jQuery Javascript to be executed in the AjaxResponse. You can then just do the Javascript call in the page you linked and the adding of the css class will be done on client side.
The only thing you need is the id of your input so that jquery can find it. So setOutputMarkupId must be set to true and you can then get the id that wicket created by calling getMarkupId() and insert it into the javascript command.
As I already said it seems strange to me that you add the error-class in the onUpdate method. The correct way would seem to me to add the error class in the onError method (called when input is invalid) and remove it in the onUpdate (when input is valid).
val_op.setOutputMarkupId(true);
val_op.add(new OnChangeAjaxBehavior() {
     @Override
     protected void onUpdate(AjaxRequestTarget art) {
          art.appendJavaScript("$('#"+val_op.getMarkupId()+"').removeClass('field-error');");
    }

     @Override
     protected void onError(AjaxRequestTarget art, RuntimeException e) {
          art.appendJavaScript("$('#"+val_op.getMarkupId()+"').addClass('field-error');");
    }
}


text:
Q: Deserializing json array using gson? I have my json as:
{
   "status": 200,
   "data": [
       {
            "catId": 638,
            "catName": "Helena Bonham Carter",
            "catUniqueName": "helena-bonham-carter",
            "catSlug": ""
       },
       {
        ...
       }
   ]
}

My Category model as:
public class Category {

    private double catId;
    private String catName;
    private String catUniqueName;
    private String catSlug;
}

And my gson custom deserializer is as follows:
Type listType = new TypeToken<ArrayList<Category>>(){}.getType();

Gson gson = new GsonBuilder()
            .registerTypeAdapter(listType, new CategoryDeserializer())
            .create();

private class CategoryDeserializer implements JsonDeserializer {
    @Override
    public Category deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        Gson gson = new Gson();
        return gson.fromJson(((JsonObject) json).get("data"), typeOfT);
    }
}

I am using Retrofit library which uses gson to serialize/deserialize json objects. I pass this custom gson deserializer to retrofit but it gives me an error. Can you tell me where I am going wrong while desrializing?
Error:
java.util.ArrayList cannot be cast to com.compzets.app.models.Category

Expected Result:
I want ArrayList of Category from json.

A: Changing the return type of deserialize() from Category to ArrayList<Category> solved the issue. Rest of the code is correct.

A: It would appear you're just trying to only extract a List of your Category objects from the JSON. You need your deserializer to do that, and use TypeToken accordingly to register your deserializer.
Here's a complete working example. Obviously you can change the class scoping as needed; I changed them to make it a single file example.
public class App
{
    public static void main( String[] args )
    {
        String json = "{\n" +
            "   \"status\": 200,\n" +
            "   \"data\": [\n" +
            "       {\n" +
            "            \"catId\": 638,\n" +
            "            \"catName\": \"Helena Bonham Carter\",\n" +
            "            \"catUniqueName\": \"helena-bonham-carter\",\n" +
            "            \"catSlug\": \"\"\n" +
            "       }\n" +
            "   ]\n" +
            "}";

        Type listType = new TypeToken<List<Category>>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(listType, new CategoryDeserializer()).create();

        List<Category> list = gson.fromJson(json, listType);

        for (Category c : list)
        {
            System.out.println("CatId: " + c.catId);
        }

    }

    public static class CategoryDeserializer implements JsonDeserializer<List<Category>>
    {

        public List<Category> deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
        {
            JsonArray data = je.getAsJsonObject().getAsJsonArray("data");
            ArrayList<Category> myList = new ArrayList<Category>();

            for (JsonElement e : data)
            {
                myList.add((Category)jdc.deserialize(e, Category.class));
            }

            return myList;

        }

    }

    public static class Category
    {
        public double catId;
        public String catName;
        public String catUniqueName;
        public String catSlug;
    }

}

Output:

CatId: 638.0


text:
Q: How to know Who's online on Facebook I am making an iphone app in which i required the functionality to get notify when the particular users get online. There is an app on itune's Who's online, that uses this functionality, but i don't know how can i achieve this. Is there any API provided for it by Facebook developers or what. Does anyone know anything about this.
Thanks in advance.

A: Simply use the official Facebook iOS SDK:
Facebook iOS SDK


text:
Q: Audio Processing - Num Chunking & Forward Fourier Transform? I'm having trouble understanding a concept my teacher taught me and getting pretty inconsistent answers between classmates. I was wondering if anyone could help clarify this idea or concept?
It's known as num chunking in audio processing. We have to deal with WAV files only. So we assume our audio data is uncompressed.
The numChunking has to do with Fourier Transform on an audio sine wave.
To determine the # of numChunks we do something like
method1:
int numChunks = totalNumOfSamples/chunkSize

but few others I've spoken with have also said
method2:
int numChunks = totalNumOfSamples/binSize

The difference is that chunkSize is just some number specified or hardcoded in like 1024 or 2000 or something. binSize on the other hand is the number of frequencies we draw after applying Fourier Transform to our samples. The number of bins(bars/frequency bars on our panel) we generally draw is about 50-100 to display on screen any more and it'll just take forever.
In method 1 we get a number of numchunks from for example like 47988 samples / 2000 = 23 numChunks. then we send these chunks in to a for loop and add each sample of the sound data into each chunk, so if we put all the 23 numChunks together we have pretty much our entire sound data with some loss of precision due to being unable to accommodate every sample from the division. We then add them into an array or ArrayList to be later sent to Discrete Fourier Transform(Forward Fourier function) and we get our results and place them in our bins and plot/draw the results as bars.
One last detail that I'm unsure of is if the fourier transform  divides by TOTAL samples in the entire sound or just the TOTAL # of samples in a numChunk.
In method 2 the way this one works is numChunks = total samples / binSize for example we'll use the same example. 47988/ 30bins = 1599 numChunks. In this idea my classmate explained to me that numChunks is a number of subArrays. So I made a 2D array, 1599 arrays each array with a length of a binSize so when we process each subArray through forward fourier transform we get our resulting amplitude value or frequency We then run each subArray through forward fourier dividing the value by the TOTAL sample size of the entire sound.
the results from both ideas are erratically different. Method 1 yields about 37.5 for the first value and the method 2 yields 3689 as a value. Their following values all seem generically correct so I'm not sure which method is correct or if any is correct at all.
This is being coded in Java
This question is quite confusing as you can tell I'm very bewildered myself. I hope someone can help clarify which is correct or incorrect or explain the concept.

A: Wow, you are a bit confused. I'll do my best to try and help explain a little.
What you're doing with a DFT (Discrete Fourier Transform) is taking a number of samples N and converting them from the time domain to the frequency domain. The size of the array you get out in the frequency domain is the same size as the array you put in in the time domain. So, you can set your numChunks to be whatever you want depending on what frequency resolution you want in the output arrays because the frequency resolution is going to be sampleRate/numChunks. So, if you want, say 80 frequency values out, use a chunk size of 80. Divide your sound file into totalNumSamples/80 chunks and you'll get the frequency content of each chunk in turn.
To answer your other question, the total number of samples in the entire sound doesn't matter - each DFT you do is entirely independent so all that matter is the number of samples you've put into each DFT.
I hope that helps a little.


text:
Q: Confusion about plurality used in conventions in Caliburn.Micro I have used a Caliburn.Micro convention many places that says if you have a collection called Apples, you can add a property with the name SelectedApple, and this will be called whenever you select something in a ComboBox with the name Apples.
All of this is well. Now however, I have a list of different type of Statuses, but I cannot get this to work, maybe because Caliburn and I do not agree upon the proper plural form of the word status.
I have a collection called Statuses, and a property called SelectedStatus. The ComboBox is filled with all the statuses, but nothing happens when I select one of them in the list.
I have tried both Statuses, Status, Stati but to no avail.
Can anyone see why this isn't working?

A: I'd never heard of Caliburn.Micro, but I found the documentation online and decided to search it. And the answer is in there.

Singularize – Turns a word from its plural form to its singular form. The default implementation is really basic and just strips the trailing 's'.

A: I believe it's expecting a property called SelectedStatuse, since it is just lopping off the trailing 's' in 'Statuses' and prepending the word 'Selected.'


text:
Q: SwiftUI: How to select items in a menu using the Picker View? I was wondering how to create a menu with selectable items in SwiftUI. Since I couldn't find any example on the web, see my answer below... :)
Cheers

A: It is actually quite easy and requires Xcode 12 and macOS 11 or iOS 14:
@State var sortKey = 0

...

Menu(content: {
    Picker("Sort by", selection: $sortKey) {
        Text("Date").tag(0)
        Text("Name").tag(1)
        Text("Love").tag(2)
    }
}

If you add .pickerStyle(MenuPickerStyle()) the menu will become a submenu called "Sort by", otherwise it is just part of the other items of your menu.


text:
Q: How to multiply two lists of variables I have two sets of 8 variables each. I want to multiply the first(second, third etc.) element of each list and sum up the products. So far my attempt is this:
DO REPEAT
  set1 = var1 to var8.
  set2 = varA to VarH.
  compute sum_of_products = SUM(set1 * set2).
END REPEAT.
EXECUTE.

The Error I get is (roughly translated from german):

Error code 4285 in row 38. String: set2
Wrong variable name: either name is longer than 64 chars or he is not defined by a previous command.
Execution of this command has been stopped.

I assume the problem is, that my DO REPEAT does not properly wrap around the commands, but I was not able to manage the right solution with the documentary, as well as with google search. These DO REPEATS and LOOPS really give me a headache.

A: See correct syntax for the DO REPEAT command:
compute sum_of_products=0.
DO REPEAT set1 = var1 to var8 /set2 = varA to VarH.
  compute sum_of_products = sum(sum_of_products , (set1 * set2)).
END REPEAT.
EXECUTE.

A: You are very close. Below is mock example dataset with solution:
* Generate mock data*.
INPUT PROGRAM.
NUMERIC ID S1_1 TO S1_8 S2_1 TO S2_8 (F3.1).
LOOP ID=1 TO 10.
  DO REPEAT S1=S1_1 TO S1_8 /S2=S2_1 TO S2_8.
    COMPUTE S1=RND(RV.F(3,10)).
    COMPUTE S2=RND(RV.F(3,10)).
  END REPEAT.
END CASE.
END LOOP.
END FILE.
END INPUT PROGRAM.

DO REPEAT S1=S1_1 TO S1_8 /S2=S2_1 TO S2_8 /S=#S_1 TO #S_8.
    COMPUTE S=(S1*S2).
END REPEAT.
COMPUTE PS=SUM(#S_1 TO #S_8).