Is this dangerous for storing the user_id in the session?

Question: When the user is login success, I will have a user_id to access to the session. But the question is can the user/hacker enable to modify, after I assigned? Because the user_id I will use to query and insert db and use this user_id to do all the query. If this is dangerous and not security, what else can I do? Thank you.
Answer: When you say that you will have a "user_id to access the session", it sounds like you are really talking about a session ID, not a user ID. Basically this is a cookie that you set upon successful login, and the server uses the cookie to look up the right session.
Beware: session hijacking. Using a session ID is a pretty standard scheme (though it's usually called session ID, not user ID), but it really depends how it is implemented. In general you want the app server to handle this for you automatically, rather than having to code it up yourself, because there are more and less secure ways to do it. If the session IDs are guessable, for example, then your app is vulnerable to so-called session hijacking. Obviously you don't want the IDs to be a sequence, but that's not all. You want them to be random, you want them not to have patterns (not always easy to see--but there are tools to determine whether there are patterns), you want there to be sufficiently many bits at play when generating the session ID, etc. Usually this is stuff that app developers would delegate to the supporting infrastructure.
Beware: session fixation. One other risk is session fixation. There are different varieties, but the basic concept is that the attacker tricks somebody into clicking on a link with a known session ID (which can be done when the session ID is passed along in the URL instead of using a cookie). He may for example post the link in a public forum, then the victim clicks on it and subsequently authenticates the session. Now the attacker can take over the session and he's authenticated to boot. One countermeasure is to make sure that the app generates a new session ID when it receives an unrecognized session ID from the client, as opposed to simply accepting the unrecognized session ID and starting a new session with it. If you are using a standard mechanism for generating session IDs then there's a good chance (though no guarantee--look at your documentation) that it already provides this countermeasure, as least as a configuration option. If you write your own then it's something that a nonexpert would almost certainly overlook.
Identifying session and user IDs leads to session hijacking. One other thing. If you are using a single ID to do double-duty as a session ID and a user ID--don't do that. First, sessions and users are conceptually different things (a session has an associated user, but it isn't the same thing as the user), so from a pure modeling perspective, it's not correct. But more importantly, user IDs usually aren't a secret, and they show up in things like URLs (which users can see). Session IDs on the other hand are definitely secret. So if for example every time I log into your app you send me a cookie that says "user_id=14" then all somebody has to do is go look at your app, notice that I'm user 14, and then periodically try to pass a "user_id=14" cookie to your app. Sooner or later they'll do that at the same time that I'm actually logged in, and voila, session hijack.
Comment: nono, I means, I store a user_id in the session. The session_id is only a generate char, but my session also store the user_id in my session.....
Comment: Storing a user ID in the session itself is perfectly normal and fine.
Answer: There are a lot of places you could take that, but on the surface. It sounds fine.
Many sites store the user id in the cookies or session object. You just have to make sure you follow best practice to ensure this is not taken advantage of.
If you are very conserned you could always encrypt it.
Des


Passing char pointer in C

Question: Okay so I am trying to pass a char pointer to another function. I can do this with an array of a char but cannot do with a char pointer. Problem is I don't know the size of it so I cannot declare anything about the size within the main() function.
#include <stdio.h>

void ptrch ( char * point) {
    point = "asd";
}

int main() {
    char * point;
    ptrch(point);
    printf("%s\n", point);
    return 0;
}

This does not work however, these two works:
1)
#include <stdio.h>

int main() {
    char * point;
    point = "asd";
    printf("%s\n", point);
    return 0;
}

2)
#include <stdio.h>
#include <string.h>

void ptrch ( char * point) {
    strcpy(point, "asd");
}

int main() {
    char point[10];
    ptrch(point);
    printf("%s\n", point);
    return 0;
}

So I am trying to understand the reason and a possible solution for my problem
Answer: This should work since pointer to the char pointer is passed. Therefore any changes to the pointer will be seen outside thereafter.
void ptrch ( char ** point) {
    *point = "asd";
}

int main() {
    char * point;
    ptrch(&point);
    printf("%s\n", point);
    return 0;
}

Comment: I would have prefered to return the pointer rather than another level of indirection, but +1 nonetheless
Comment: why it works with integer and doesn't need to pass pointer to pointer? i think because after dereference, char pointer remain is the address of first element of array?
Answer: void ptrch ( char * point) {
    point = "asd";
}

Your pointer is passed by value, and this code copies, then overwrites the copy. So the original pointer is untouched.
P.S. Point to be noted that when you do point = "blah" you are creating a string literal, and any attempt to modify is Undefined behaviour, so it should really be const char *
To Fix - pass a pointer to a pointer as @Hassan TM does, or return the pointer as below.
const char *ptrch () {
    return "asd";
}

...
const char* point = ptrch();

Comment: This will trigger a warning of local variables if you do not hardcode the return value as a string literal.
Comment: Which way is less expensive?
Comment: @SarpKaya both are blazingly fast (difference would be minimal if any), but I would prefer the "return the pointer" method for readability.
Comment: why we need const here?
Answer: Here:
int main() {
char * point;
ptrch(point);
You're passing point by value.  Then, ptrch sets its own local copy of point to point to "asd", leaving the point in main untouched.
A solution would be to pass a pointer to main's point:
void ptrch(char **pp) { *pp = "asd"; return; }
Answer: If you change the value of the pointer in a function, it will remain changed only in that one function call.
Don't mess your head with pointers and try:
void func(int i){
  i=5;
}
int main(){
  int i=0;
  func(i);
  printf("%d\n",i);
  return 0;
}

The same with your pointer. You do not change the address it points to.
If you assign to a variable passed by value, the variable outside the function will remain unchanged.
You could pass it by a pointer (to pointer) and change it by dereferrencing it and it's the same with an int - in this case, it doesn't matter if the type is int or char * .
Answer: first declare funtion......like this
 #include<stdio.h>
 void function_call(char s)

next write main code.....
void main()
{
    void (*pnt)(char);  //  pointer function declaration....
    pnt=&function_call;  //    assign address of function
    (*pnt)('b');   //   call funtion....
}

Passing char pointer in C


XP, single interface, multiple routes out?

Question: I am not in a position to test this and I was curious if anyone knew the answer.
Lets say I have a network 10.0.0.0/24 and I have two routers that go out to the internet, 10.0.0.253 and 10.0.0.254.
Lets say that the default route for each workstation is 10.0.0.254 and each workstation only has a single interface and is running a version of windows, lets say XP.
Now here are the questions:
Lets say I create the route 0.0.0.0 10.0.0.253 with a higher metric than the route to .254. Would the workstations then use this other router to access the internet if there are issues with the first router? Are there any problems or concerns that can occur by doing this?
Next if the above was to work, could I flip on RIP on the routers and install some type of RIP listener on the windows machines and let them find the routers on their own? Would they not assign a cost to each route and pick the better one with this method?
Am I way off track here, is there a better way to go about this? Any advice on the matter is welcome.
Answer: You are going to want to look at doing this at the network layer with HSRP/VRRP instead of trying to mess around with local routing tables.
HSRP is a Cisco proprietary standard, while VRRP is not.
Since you don't say what kind of routers you have I can't give you much more detail than the above wikipedia links. If you let us know the manufactuer and model of the routers then we can give you more detail.
Answer: first question: no, your workstation would not use the second route because it would have no way to know of any status changes on the 10.0.0.254 device.
most versions of Windows do have a RIP listener service, you could enable that and then set both router to use RIP and if the 10.0.0.254 device went off line then, after a bit of time, the 10.0.0.253 would be the only route the PC would have and it should use that


What 1968 Moog synthesizer was used in the Movie Apollo 11?

Question: I was watching the short YouTube video How 'Apollo 11' Gives the Moon Landing New Life | Anatomy of a Scene and near the end the narrator says:

My music composer, Matt Morton decided to do a period score, using only instrumentation that was around pre-1969, most notably, he went out and got a 1968 edition Moog synthesizer.

What 1968 Moog synthesizer is this?

I'm not sure if I should post this question here or in Movies SE. If there are Moog aficionados here they may know it right away, so I thought I would try here first. The only thing I can think of is the cover of Switched On Bach.
Answer: It's a Moog modular Synthesizer IIIc
From Matt Morton - Apollo 11

Matt wrote, orchestrated, performed, recorded, and mixed all of the
  original music for the film, as well as the teaser trailer and the
  theatrical trailer.  Every instrument and effect used in the score
  existed at the time of the mission in 1969 including the Moog modular
  Synthesizer IIIc (see below), the Binson Echorec 2 (tube echo), the
  Mellotron (early keyboard sampler used by The Beatles, Led Zeppelin,
  etc.), and the orchestra.

I had a quick listen to this video & the trailer, and I have to say that all the synth noises I could pick out from this & under the orchestra could be made in VSTi these days (or certainly close enough for those of us without a Hollywood budget;) I have several plugins that can do Moog, ARP, Mellotron & the like, all really quite convincingly, if not as a single 'patch' then at least by layering.
Comment: And interesting comparison between real analog synths and virtual synth plugins is the difference between the *Stranger Things* (real) and *Dark Matter* (virtual) soundtracks.
Comment: Looks like I chose the right site to post, thanks very much!
Comment: I'd have probably struggled to choose too - but I'm on both, so you'd have got the same answer from me on either ;)
Comment: @uhoh and at Tetsujin, we seem to hang out in the same places :-)


Selecionar registros entre duas datas com intervalos de minutos pré-estabelecidos

Question: Tenho uma tabela que armazena dados coletados em intervalos de 5 minutos. Gostaria de selecionar os registros entre uma data/hora inicial e data/hora final. Até aí consigo fazer. Só que gostaria de incluir um terceiro parâmetro na query que seria o intervalo de tempo entre coletas. Ex. Registros de 30-01-2018 00:00:00 até 30-01-2018 12:00:00 em intervalos de 10 minutos.
Comment: exemplo de dados ? exemplo de como quer a saída ? estrutura das tabelas ? utilize o SQLFiddle se possível
Comment: A tabela tem somente dois campos: datahora (datetime), tag (varchar(30).
time                                         tag
2016-04-01 00:01:03.580 PDT_1_T13@PV
2016-04-01 00:06:03.580 PDT_1_T13@PV
2016-04-01 00:11:03.580 PDT_1_T13@PV
2016-04-01 00:16:03.580 PDT_1_T13@PV
2016-04-01 00:21:03.580 PDT_1_T13@PV
2016-04-01 00:26:03.580 PDT_1_T13@PV
2016-04-01 00:31:03.580 PDT_1_T13@PV
2016-04-01 00:36:03.580 PDT_1_T13@PV
Comment: Qual é o gerenciador de banco de dados?
Answer: Insira a seguinte clausula no WHERE:
<code>DATEPART(MINUTE,[CAMPO DATA]) % 10 < 5
</code>
Explicando o que esta sendo feito: estou isolando último dígito do minuto de seu campo datetime e verificando se ele está contido em {0,1,2,3,4}.
Com isso acredito que retornará os valores esperados.
Exemplo (serão retornados os itens em negrito:

30/01/2018 08:00
30/01/2018 08:05
30/01/2018 08:11
30/01/2018 08:17
30/01/2018 08:23
30/01/2018 08:28
30/01/2018 08:33
30/01/2018 08:38

A tabela tem somente dois campos:
datahora (datetime) tag (varchar(30)
Conteúdo tabela:
datahora    tag
2016-04-01 00:01:03.580 PDT_1_T13@PV
2016-04-01 00:06:03.580 PDT_1_T13@PV
2016-04-01 00:11:03.580 PDT_1_T13@PV
2016-04-01 00:16:03.580 PDT_1_T13@PV
2016-04-01 00:21:03.580 PDT_1_T13@PV
Caso a seleção seja 01-04-2016 00:00:00 até 01-04-2016 00:35:00
Intervalo de 10 minutos.
Saída Esperada
datahora    tag
2016-04-01 00:01:03.580 PDT_1_T13@PV
2016-04-01 00:11:03.580 PDT_1_T13@PV
2016-04-01 00:21:03.580 PDT_1_T13@PV
Comment: A tabela tem somente dois campos:
datahora (datetime)
tag (varchar(30)
Conteúdo tabela:
datahora                                 tag
2016-04-01 00:01:03.580 PDT_1_T13@PV
2016-04-01 00:06:03.580 PDT_1_T13@PV
2016-04-01 00:11:03.580 PDT_1_T13@PV
2016-04-01 00:16:03.580 PDT_1_T13@PV
2016-04-01 00:21:03.580 PDT_1_T13@PV

Caso a seleção seja 01-04-2016 00:00:00 até 01-04-2016 00:35:00
Intervalo de 10 minutos. Saída Esperada

datahora                                 tag
2016-04-01 00:01:03.580 PDT_1_T13@PV
2016-04-01 00:11:03.580 PDT_1_T13@PV
2016-04-01 00:21:03.580 PDT_1_T13@PV
Comment: @SergioPaiva não consegui entender seu comentário, acredito que seja melhor você editar a pergunta e colocar mais estruturado lá.
Chegou a testar com adicionando a cláusula que coloquei na resposta no where? deu certo?
Comment: Coloquei a resposta no item acima.
Comment: Não entendi se chegou a testar com o código que eu passei acima ou não, pois entendo que você teria o resultado esperado. Ou qual o problema que ocorreu.
Comment: Felipe, como no banco tenho registros nas seguintes horas (hh:mm) em: 00:01, 00:06, 00:11, 00:16 e 00:21. Se minha seleção for de 00:00 a 00:35 com intervalos de 10 minutos, os registros que deveriam retornar são: 00:01, 00:11, 00:21.
Comment: Pelos testes que fiz por aqui, adicionando no seu where " AND DATEPART(MINUTE,datahora) % 10 < 5 " traria exatamente o resultado que você espera.
Comment: Perfeito Felipe. Realmente funcionou! Estava enganado.


Is it possible to end a process nicely in a Java application?

Question: In a Java application:
currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...
currentProcess.destroy();

Calling destroy simply kills the process and doesn't allow any user cleanup or exit code to run. Is it possible to send a process a WM_CLOSE message or similar?
Answer: You could use Process.getOutputStream to send a message to the stdin of your app, eg:
PrintStream ps = new PrintStream(currentProcess.getOutputStream());
ps.println("please_shutdown");
ps.close();

Of course this means you have to contrive to listen on stdin in the Windows app.
Comment: Thanks, of all the solutions, this one seems the best!
Answer: you can try with JNA, importing user32.dll and defining an interface that defines at least CloseWindow
Comment: +1 JNI maybe? I wonder if there's a utility like 'kill -SIGTERM' in Windows
Answer: Using JNA's jna.jar and process.jar (from http://jna.java.net/) you send a WM_CLOSE message as follows:
int WM_CLOSE = 0x10;

HWND hwnd = User32.INSTANCE.FindWindow(null, windowTitle);
User32.INSTANCE.PostMessage(hwnd, WM_CLOSE, new WinDef.WPARAM(), new WinDef.LPARAM());

Answer: Not without resorting to native code. Process.destroy() causes a forced termination. On Windows this is equivalent to calling TerminateProcess(). On Unix it is equivalent to a SIGQUIT and causes the application to core dump.
Comment: SIGKILL doesn't dump core! It's not SIGQUIT (which does dump core by default).
Comment: I stand corrected. I guess Unix versions of Java must send a SIGQUIT (core dumps definitely occur). I'll update this answer. Thank you.
Answer: A dirty solution would be making your MyWindowsApp register its identifier somewhere like file and create another windows app that sends WM_CLOSE (let's name it MyWindowsAppCloser) to another applications.
With this in hand, you would code the following using java 1.6

currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...

// get idMyWindowsApp where MyWindowsApp stored its identifier
killerProcess = new ProcessBuilder("MyWindowsAppCloser.exe", idMyWindowsApp).start();
killerProcess.waitFor();

int status = currentProcess.waitFor();


Pug Templating iterate through multiple arrays in JSON data object?

Question: I am new to pug. I am using JSON files to store my data used in the pug file. This is my data structure:
{
  "nav": {
     "titles": [
      "location",
      "reservations",
      "accomodations",
      "amenities"
    ],
    "icons": [
      "img/sprite.svg#icon-location2",
      "img/sprite.svg#icon-book",
      "img/sprite.svg#icon-key",
      "img/sprite.svg#icon-glass"
    ]
  }
}

I know how to loop through a single array in the JSON. My problem is how to pull data into the template for more then one item off the data object. For instance I want to loop to get both the titles and the icons from my nav.json file. My pug file looks like this
li(class="top-nav__item")
  a(class="top-nav__link")
    svg(class="top-nav__icon")
      use(xlink:href=icon)
        span=title

I've tried nesting the loops
each title in nav.titles
  each icon in nav.icons

and using logical operators
each title in nav.titles && each icon in nav.icons

and pulling off the object directly like
each n in nav

None of those worked. How do I do this in pug? Should I set my data up a differently to be able to do this? Or is there a different way to loop through and grab the data?
Answer: title and icon correspond and should be grouped together. If your data looked like this, you'd have an easier time of it:
{
  "nav": [{
    "title": "location",
    "icon": "img/sprite.svg#icon-location2"
  }, {
    "title": "reservations",
    "icon": "img/sprite.svg#icon-book"
  }, {
    "title": "accommodations",
    "icon": "img/sprite.svg#icon-key"
  }, {
    "title": "amenities",
    "icon": "img/sprite.svg#icon-glass"
  }]
}

Alternatively, you could each i in [0, 1, 2, 3] and use the i value to pull matching titles and icons out of their respective arrays. But relying on data lining up across multiple arrays is a bad idea.
Comment: Thank you! @dmfay That worked. I am iterating over the object w/ each i in nav and assigning the values i.titles i.icons.


File object from Inputstream

Question: I'd like to apply zip4j in my android app. I put a demo zip file into the assets folder (main/assets/test.zip). I'd like to open it with zip4j:
import net.lingala.zip4j.core.ZipFile;
...
ZipFile zipFile = new ZipFile(new File("an/absolute/path/is/required"));

However, the constructor required for applying zip4j requires a String object (the absolute path of the file) or a File object. But the AssetManger of Android only returns an InputStream. Also please not: The AssetManger does not provide an absolute path or something.
So, what do I have to do in order to transform the input stream of InputStream is = getResources().getAssets().open(filename); into a java.io.File object which I then can apply to ZipFile
Comment: `file:///android_asset/` is the absolute path to the asset directory.
Comment: I already tried that. It does not work.
Comment: Any particular reason for the zip file to be located in the assets folder? Is it your intention to eventually bundle one with your app that way? Perhaps downloading/copying the zip file to local storage (from which you can then get a `File`) is an option too? Alternatively, have a look at the [`java.util.zip.ZipInputStream`](http://developer.android.com/reference/java/util/zip/ZipInputStream.html) that comes with the Android SDK: it acts as a wrapper for any `InputStream`, meaning you could use it directly with the result of `getAssets().open(...)`.
Comment: Yes, `ZipInputStream` is exactly what I am currently using. `Zip4j` is probably not recommended for using in Android projects
Comment: Why? What does this package provide beyond `java.util.zip`?
Answer: Quite a a common Task when dealing with assets:

Get a AssetFileDescriptor from the AssetManager : openFD(String fileName).
Get a FileDescriptor from that AssetFileDescriptor  : getFileDescriptor()
Construct a new File from the FileDescriptor.

File object from Inputstream


O que é Malha Digital Inteligente (Digital Mesh)?

Question: De forma simples e objetiva, o que seria esse termo que muitos dizem ser uma tendência na área da tecnologia da informação?
Answer: É uma tendências de software que estão permitindo o entrelaçamento de pessoas, dispositivos, conteúdo e serviços. O resultado é o que o Gartner chama de malha digital inteligente:

Inteligente: como a IA está se infiltrando em praticamente todas as tecnologias e com um foco definido e bem definido pode permitir sistemas mais dinâmicos, flexíveis e potencialmente autônomos.
Digital : mistura os mundos virtual e real para criar um ambiente imersivo e conectado digitalmente.
Malha : as conexões entre um conjunto crescente de pessoas, negócios, dispositivos, conteúdo e serviços para fornecer resultados digitais.

Na minha opinião a junção de todos esses culminará(num futuro breve) no laço neural que a junção de maquina e humano(Olha o projeto da neuralink):D


Error: function crashed out of request scope Function invocation was interrupted

Question: I'm writing a Cloud Function that reads several lines from a .csv file and sends one HTTP request for each line, but I'm getting the error above.
This error has been asked before (here, here and here to list a few), but in all of these cases, the issue was that the function didn't return a promise that would resolve only after every asynchronous operation.
From my understanding of how async works, my code doesn't seem to have this issue. Here's the gist of it, removing some specific details:
const request = require('request-promise-native');
const storage = require('@google-cloud/storage')();

exports.sendData = async (data, context) => {
    const [file] = await storage.bucket(data.bucket).file(data.name).download();
    const [header, ...table] = file.toString('utf8').split('\n').map(row => row.split(','));
    const rows = table.map(
        row => header.reduce((obj, col, i) => {
            obj[col] = row[i];
            return obj;
        }, {})
    );

    const paramList = rows.map(({ csv_field1, csv_field2 }) => ({
        req_field1: csv_field1,
        req_field2: csv_field2,
        // etc.
    }));

    let errors = 0;
    console.log(`Sending ${paramList.length} rows...`);
    await Promise.all(paramList.map(async (param, i) => {
        try {
            await request.get({ url: "", qs: param }); // Endpoint removed
            if ((i + 1) % 10000 == 0) {
                console.log(`${i + 1} rows ${paramList.length} sent.`);
            }
        } catch (e) {
            console.log(`Request failed for row ${i + 1} .\n\n${e}`);
            errors++;
        }
    }));
    console.log(`Done.`);
    if (errors > 0) {
        console.log(`Total errors: ${errors}`);
    }
};

The above code works just fine for a couple of lines (10), but the error begins showing up when trying with bigger numbers (1000). The "Done." message also didn't appear in the logs, so it doesn't seem that the function is reaching the end.
Any clues?
Comment: Rewrote the code to use promises and tried the Node.js 6 runtime and it worked. Not sure if there was anything wrong with the code or if it was an issue with the Node.js 8 runtime.
Comment: I've got exactly the same symptoms, but in quite a big project that I really didn't want to rewrite for Node 6... It works fine until the number of outgoing http requests reaches a few hundred, and then starts crashing with that helpful error.
Comment: sounds like the same problem I have...  any ideas?
Answer: I had the same error on my project.
I resolved it by downgrading runtime from node8 to node6


RecursionError while trying to implement a function recursively

Question: I need to implement a recursion function which will provide the first N elements of a sequence, x_{n+1} = r*x_n*(1-x_n). The code I present below is not running, the error being  if N == 0: RecursionError: maximum recursion depth exceeded in comparison. I will appreciate your help in making the code run.
def sequence(N, x0, r):
    A = [x0]
    if N == 0:
        return x0
    else:
        A.append(r * sequence(N, x0, r) * (1 - sequence(N, x0, r)))
    return [A[i] for i in range(N + 1)]

print(sequence(10, 2, 2))

Comment: You always pass `N` as-is to the recursive calls of `sequence()`, so there's no way you could ever reach `if N == 0` if you originally pass in a non-zero `N`.
Answer: Looks like you might want
def compute_value(N, x0, r):
    if N == 0:
        return x0
    x_n = compute_value(N - 1, x0, r)
    return r * x_n * (1 - x_n)

sequence = [compute_value(n, 2, 2) for n in range(10)]

print(sequence)

This prints out
[2, -4, -40, -3280, -21523360, -926510094425920, -1716841910146256242328924544640, -5895092288869291585760436430706259332839105796137920554548480, -69504226188572366382469893394830651557109425404264568995802412215018036314883217970500884577054804760905832770274449717760, -9661674916144457552727034361009790527700732880801664275092268814451233373207768500008969714893014677195041164647293059752576754550666470442049020239364319771280275066863699741389031161203686169060521699834121138295895752329492941497636218270720]

(boy, those are some big negative numbers...)
Comment: Oh, and also, it is a simple modelisation of a pandemic evolution, r, being the same "R" parameter we always hear about in pandemic talk.
Comment: Yes. That is the logistic sequence. It is supposed to be used with initial values between [0,1]. It has a fascinating behavious, depending on value of r. If r<1, it converges toward 0. If 1<r<3 it converges but not toward 0. If 3<r<3.56 it doesn't converge strictly speaking, but oscillate between 2, 4, 8, ... limits. Over 3.56, it is pure chaos. And in complex space, the area of r for which the sequence is chaotic is (ignoring a simple geometric transformation) Mandelbrot's fractal.
Comment: @user996159 literally add `@cache` before `compute_value`, after importing it from `functools` (ie. `from functools import cache`).
Comment: This is quite inefficient.
Comment: @BlackBeans Yes. It can be made efficient by adding the `@cache` decorator to `compute_value`. ;-)
Comment: Thanks. How you will do that with `@cache` to make it more efficient ?
Comment: Thanks. In what sense makes it the code more efficient  ? I used it, I do not see any difference in the speed of finding the sequence. For `N = 20`, it starts already to get very slow in finding the sequence with or without `@cache`.
Comment: @user996159 With `@cache`, the result for a given computation is memoized, so future calls won't need to recurse at all.
Comment: Also, if `@cache` doesn't seem to make a difference, you've probably applied it wrong somehow. A quick benchmark with `timeit`: `name='nocache' iters=10 time=0.915 iters_per_sec=10.93` / `name='w/cache' iters=10000000 time=0.562 iters_per_sec=17793958.42`
Comment: I simply added `from functools import cache` and `@cache` before the function that you defined. Is it as simple as that?
Comment: Yes. Of course you'll notice the speedup only after the second invocation - there's no way around having to actually do the maths once.
Answer: Staying as close as possible from your initial try, I would do something that also returns a sequence, not a number
def sequence(N, x0, r):
   A=[x0]
   if N==0:
      return A
   else:
      return A + sequence(N-1, r*x0*(1-x0), r)

print(sequence(10, 2, 2))

Explanation: it computes the first element of the sequence, and then the rest of it, recursively.
Just trace it for a few values.
For N=0
Simple, it just returns [x0]
For N=1
For clarity (otherwise, x0 means different things during recursions), let's choose x0 for the initial call=2, and also (even if r stays the same thorough all call), choose r=3. So let's call sequence(1,2,3)

In sequence(1,2,3) call, we starts by A=[2]
Then, since N≠0, we go to else, so we compute A=[2]+sequence(0,3*2*(1-2),3) recursively, that is sequence(0,-6,3)``

In this sequence(0,-6,3) call, we starts with A=[-6]
Since N=0 in this call, we simply return A, aka [-6]

So, back in sequence(1,2,3), we return A+result of recursive call sequence(0,-6,3). That is A+[-6]. That is [2]+[-6]
so final answer is [2, -6]

For N=2
(And still initial x0=2, and r=3)

In sequence(2,2,3) call, we start with A=[2]
Since N=2≠0, we return A+sequence(N-1,r*x0*(1-x0), r), and for that we need to compute sequence(1, -6, 3) recursively

In sequence(1,-6,3) call, we start with A=[-6]
Sine N=1≠0, we return A+sequence(N-1,r*x0*(1-x0),r) that is [-6] + sequence(0, 3*(-6)*7, 3) = [-6] + sequence(0, -126, 3).
so we have to call recursively sequence(0, -126, 3).

In sequence(0, -126, 3), we start we A=[-126]
Since N=0, we just return that [-126]

now back in sequence(1,-6,3) call. Our [-6]+sequence(0,-126,3) computation [-6]+[-126] or [-6, -126], which is what we return

now back in sequence(2, 2, 3) call. Our [2]+sequence(1,-6,3) computation is therefore [2]+[-6,-126] or [2,6,-126]. Which is our final answer

Note that no redundant computation is done here. And it stays as close as possible from your initial answer.
Another, more "functional" recursion, which for the record, was my previous main answer (what is now my main answer was 1st provided as an alternative solution, before I realized it was probably the one your are expected to provide)
def sequence(N, x0, r):
    if N == 0:
        return [x0]
    else:
        prev=sequence(N-1, x0, r)
        prev.append(r * prev[-1] * (1-prev[-1]))
        return prev

It is also recursive, and efficient. But not as elegant. I mean, the recursion here is just a way to repeat N times the prev.append(...) line. We could have achieved the same result by iterating N times that line with a for loop. So recursion brings nothing. Whereas in the first solution, it has the advantage to stick to mathematical recurrent definition of the sequence (that is one advantage of recursion. It may be harder to understand for computer scientist used to imperative programming. But for a mathematician, it is closer to the way we define sequences)


How do I learn this Peruvian technique?

Question: I can't figure out how he is playing the part with the triplets beginning 1:18 :(
would love to learn this technique but how? Is he playing two notes at once, or just semiquavers like in Recuerdos de la Alhambra?
How do I learn the phrasing? Maybe somebody knows a resource that allows me to figure it out, e.g. a simpler example of this technique or a tutorial.
Comment: Tim's comment from your other post: "It's tremolo, played with probably two fingers, in semis. While the counter melody is played with the thumb on lower strings."
Comment: It is played with your 2nd, 3rd, and 4th fingers. https://www.youtube.com/watch?v=I83lanJNze0
Answer: As in my comment - melody played using thumb (p), tremolo played using index, middle and ring (i, m, a), on top string. There appears to be tune note followed by 3 semis, which have manifested themselves to you as triplets.
Comment: Yep - have just tried playing this various different ways and this is the only one that works.
Answer: This seems to be just tremolo played on the 2nd, 3rd and 4th fingers.
Comment: Isn't this what I wrote...  or do you mean middle, ring and pinky, which he doesn't use.
Answer: From just a quick look and listen it seems to be a four (not triplets) 32nd note tremolo on the B (2nd) string using the pinky as well as i, m and a. The camera operator chose exactly the wrong time to change the focus.
Comment: The notes are too high to be played on the 2nd string. His fretting hand would have to be much higher up the fingerboard.

How do I learn this Peruvian technique?


Sum of i.i.d. random variables for which Chebyshev inequalities are tight

Question: Chebyshev's inequalities: Let $X$ be a random variable with finite expected value $\mu$ and finite non-zero variance $\sigma^{2}$. Then for any real number $\delta > 0$,
$$ \Pr[|X - \mu| \geq \delta\sigma] \leq \frac {1}{\delta^{2}}$$
There is a tight example in wiki, $X_c$ is a random variable with $\sigma = 1/c$:
$$
\left\{
\begin{aligned}
&\Pr[X_c = -1] = \frac{1}{2c^{2}}  \\
&\Pr[X_c = 0] = 1 - \frac{1}{c^{2}}  \\
&\Pr[X_c = 1] = \frac{1}{2c^{2}}  \\
\end{aligned}
\right.
$$
If $\delta = c$, then we have
$$ \Pr[|X - \mu| \geq \delta\sigma] = \Pr[|X| \geq 1] = \frac {1}{\delta^{2}}$$
But for $\delta > c$, it is not tight.
Is there another example that is tight for every $\delta$ satisfying $|\delta| > \delta_{0}$? ($\delta_{0}$ is a constant only depending on the distribution.)
In addition, suppose $X_{1}, X_{2}, \ldots, X_{n}$ are i.i.d. random variables with finite expected value $\mu$ and finite non-zero variance $\sigma^{2}$.
According to Chebyshev's inequalities:
$$\Pr\left[\left|\sum_{i}^{n}X_{i} - n\mu\right| \geq \delta n\sigma\right] \leq \frac{1}{n\delta^{2}}$$
Is there also an (asymptotic) tight example for $\{ X_{i} \}_{i = 1}^{n}$?
Comment: Could you explain what an "infinite large $\delta$" means?
Comment: Also [cross-posted to math.SE](https://math.stackexchange.com/q/4541437/15941) where it has also been answered.
Comment: @whuber I have modified the expression.
Comment: When you contemplate the [idea behind Chebyshev's Inequality](https://stats.stackexchange.com/a/562570/919), the answer is immediate.
Answer: No to both.

Suppose $X$ attains the bound for $\delta=\delta_1$.   Construct $\tilde X$ by moving any probability mass of $X$ further than $\delta_1$ from $\mu$ to distance $\delta_1$ from $\mu$. If there is any such mass then
$$P(|\tilde X-\mu|\geq\delta_1)=P(|X-\mu|\geq\delta_1),$$
but
$$\mathrm{var}[\tilde X]<\mathrm{var}[X].$$
Since Chebyshev's inequality is tight for $X$ is it violated for $\tilde X$: a contradiction.  So there must be no probability mass with $X-\mu$ greater than $\delta_1$. But in that case Chebyshev's inequality cannot be sharp for any $\delta>\delta_1$.

Write $\sigma^2_n$ for $\mathrm{var}[X_n]=\mathrm{var}[X]/n$. The Central Limit Theorem says that as $n\to\infty$
$$P[|\bar X_n-\mu|\geq\delta\sigma_n]\to 2\Phi(-\delta)$$
so it is not possible to have
$$P[|\bar X_n-\mu|\geq\delta\sigma_n]=1/\delta^2$$
for any fixed $X$ and arbitrarily large $n$.

[2. Alternative proof sketch: the inequality is only sharp when all the probability mass of $X$ is at $\mu$ or $\mu\pm\delta$, a distribution supported on more than one and no more than three points. A mean of $n$ iid observations supported on more than one point must be supported on at least $n$ points.]


SHS module in drupal 7 views

Question: I am using Simple hierarchical select module and I am having terms lists like below;

India
a) Karnataka

Bangalore

So, I want this filed as exposed filter in my views. Let me give example, assume if 3 nodes are selected "Bangalore".
So, whenever I select the "India" or "Karnataka" means it should shows the content which is selected as "Bangalore" in views.
How should I achieve this process?
Any configuration has to be done?
Can anyone please help me out in this case?
Thanks in advance
Answer: 1) Add filter  "Content: Has taxonomy terms (with depth; Simple hierarchical select)"
2) choose your vocabulary
3) in the selection type choose  "Simple hierarchical select"
4) select Depth 2 and click on save.
5) Tick in the "Expose this filter to visitors,"
Here the trick is in the Depth selection
Comment: Awesome man its cool tricky thing :) Then one more request, have you used https://www.drupal.org/project/cshs ever?
Because I need the same set up for this module also in views. can you please help me out, since I cant see the depth field in views when am using this module.
Comment: Yes i used cshs module, cshs module do not allow you to search in the depth. using cshs you must select the terms to the deepest level otherwise cshs will give you no results.
Comment: Thanks for response. Yeah CSHS wont allow to search through parent term. I hope you have used both of that SHS and CSHS.
CSHS is more speed compare to SHS, is there any chance to increare the speed of SHS module UI? can you please help me out in this case?
Comment: This problem is discussed on the module page, you can use  High-performance JavaScript callback handler
Comment: Thanks, hey as well as I want to take the super parent in drupal 7 views. for example I need to display India as a parent term for Bangalore not karnataka.
Comment: Sorry i didn't get your point, can you explane a little bit?
Comment: Hey thanks for your request, I will explain now what I am exactly looking for. Am using taxonomy with Super parent, parent, child, i.e (2 depth). So, I gave term reference on one content type, while adding content I will select the child (Bangalore). So, in views I want to display the super parent of child term, i.e I dont want to display karnataka, I want to display India as a parent. So, how should I make view to bring this? any idea? please share here. Thanks in advance.
Comment: Edit your view and then click on the shs field from the fields list, then in the Formatter drop down list select "simple hierarchy" and save. in the front end you can hide the child's using css if you do not want the child's to display.
Answer: I presume you already set your Taxonomy and your node has add field (example: you name this field as "Place")for select either Bangalorem, India or Karnataka.
In the views, add FILTER CRITERIA. Select Content: Place. Selection type: You can choose dropbox. Save the view. Last, click on the same CRITERIA again (example: Content: Place (= )) and choose  Bangalorem

SHS module in drupal 7 views


Get Progress in %age with upload speed while uploading file over http using Java?

Question: I was working on some code to upload files on http url. But i don't know how to get %age & upload speed while transfering to make it more verbose.
httpupload.java
<code>   import java.io.File;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.RandomAccessFile;
   import java.io.StringWriter;
   import java.io.UnsupportedEncodingException;
   import java.text.DecimalFormat;

   import javax.xml.ws.spi.http.HttpContext;

   import org.apache.http.HttpEntity;
   import org.apache.http.HttpResponse;
   import org.apache.http.HttpVersion;
   import org.apache.http.client.HttpClient;
   import org.apache.http.client.methods.HttpPost;
   import org.apache.http.client.methods.HttpPut;
   import org.apache.http.entity.mime.MultipartEntity;
   import org.apache.http.entity.mime.content.FileBody;
   import org.apache.http.impl.client.DefaultHttpClient;
   import org.apache.http.params.BasicHttpParams;
   import org.apache.http.params.HttpParams;
   import org.apache.http.params.HttpProtocolParams;
   import org.apache.http.protocol.BasicHttpContext;

   public class httpupload  {
String str;
private int transferedMegaBytes = 0;
int choice;
long size = 0;
static int iter;
DecimalFormat df = new DecimalFormat("#.00");
RandomAccessFile f1;
httpUploadProgress fileEntity;

boolean bo1, bo2, bo3, bo4;// truefalsetruefalse

public httpupload(boolean b1, boolean b2, boolean b3, boolean b4,
        int Iterations) {
    super();

    // TODO Auto-generated constructor stub
    bo1 = b1;
    bo2 = b2;
    bo3 = b3;
    bo4 = b4;
    this.iter = Iterations;
    if(bo1){
        ProgressBar.maxprogress+= iter*250*1024;
    }
    if(bo2){
        ProgressBar.maxprogress+=iter*500*1024;
    }
    if(bo3){
        ProgressBar.maxprogress+=iter*2*1024*1024;
    }
    if(bo4){
        ProgressBar.maxprogress+=iter*10*1024*1024;
    }

    try {
        ProgressBar.status="Uploading File via HTTP";
        this.chooseFiles(bo1, bo2, bo3, bo4);
        //System.out.println(httpUploadProgress.getSpeed());
    } catch (Exception ex) {
        //System.out.println(ex.getLocalizedMessage());
    }
}

public void chooseFiles(boolean b1, boolean b2, boolean b3, boolean b4)
        throws Exception {
    for (int i = 0; i < iter; i++) {
        if (b1) {
            ProgressBar.status="Uploading File Of Size 250KB";
            this.startUpload(1);
        }
        if (b2) {
            ProgressBar.status="Uploading File Of Size 500KB";
            this.startUpload(2);
        }
        if (b3) {
            ProgressBar.status="Uploading File Of Size 2MB";
            this.startUpload(3);
        }
        if (b4) {
            ProgressBar.status="Uploading File Of Size 10MB";
            //this.post();
            this.startUpload(4);
        }
    }
    httpUploadProgress.totalSpeed /= iter;
}

public static void main(String args[]) {
    httpupload av = new httpupload(false, false, false, true, 2);

}

private void startUpload(int choice) throws Exception {
    String str = "";
    switch (choice) {
    case 1:
        str = "250kb.txt";
        size = 250 * 1024;
        break;
    case 2:
        str = "500kb.txt";
        size = 500 * 1024;
        break;
    case 3:
        str = "2MB.txt";
        size = 2 * 1024 * 1024;
        break;
    case 4:
        str = "10MB.txt";
        size = 10 * 1024 * 1024;
        break;
    }

    //str="/sdcard/"+str;
    f1 = new RandomAccessFile(str, "rw");
    f1.setLength(size);
    File file = new File(str);

    String serverResponse = null;
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    HttpPut put = new HttpPut("URL"
            + file.getName());
    //HttpPost httpPost = new HttpPost("URL");

    fileEntity = new httpUploadProgress(file, "binary/octet-stream");
    put.setEntity(fileEntity);
    //httpPost.setEntity(fileEntity);
    HttpResponse response = client.execute(put);
    //HttpResponse response = client.execute(httpPost);

    // HttpEntity entity = response.getEntity();
    /*
     * if (entity != null) { serverResponse = EntityUtils.toString(entity);
     * //System.out.println(serverResponse); }
     */

    File f2 = new File(str);
    f2.delete();

}
</code>
httpuploadProgress.java
<code>        import java.io.File;
         import java.io.FileInputStream;
         import java.io.IOException;
         import java.io.InputStream;
         import java.io.OutputStream;
         import java.text.DecimalFormat;

         import org.apache.http.entity.AbstractHttpEntity;

        /**
        * File entity which supports a progress bar.<br/>
        * Based on "org.apache.http.entity.FileEntity".
        * @author Benny Neugebauer (www.bennyn.de)
        */
        public class httpUploadProgress extends AbstractHttpEntity implements Cloneable
        {

  protected final File file;
 // private final ProgressBarListener listener;
  private long transferredBytes;
  private long transferedMegaBytes = 0;
  long startTime, endTime,totalTime;
  static double speed,totalSpeed;
  static DecimalFormat df = new DecimalFormat("#.00");
  int choice;
  static String metrics;

  public httpUploadProgress(final File file, final String contentType)
  {
    super();
    if (file == null)
    {
      throw new IllegalArgumentException("File may not be null");
    }
    this.file = file;
    this.transferredBytes = 0;
    setContentType(contentType);
  }

  public boolean isRepeatable()
  {
    return true;
  }

  public long getContentLength()
  {
    return this.file.length();
  }

  public InputStream getContent() throws IOException
  {
    return new FileInputStream(this.file);
  }

  public void writeTo(final OutputStream outstream) throws IOException
  {
    if (outstream == null)
    {
      throw new IllegalArgumentException("Output stream may not be null");
    }
    InputStream instream = new FileInputStream(this.file);
    try
    {

        {
        byte[] tmp = new byte[1024];
      int l;
       startTime = System.nanoTime();

      while ((l = instream.read(tmp)) != -1)
      {
        outstream.write(tmp, 0, l);
        this.transferredBytes += l;

        updateTransferred(this.transferredBytes);
      }
      outstream.flush();
      endTime = System.nanoTime();
        System.out.println("End Time of "+"is :"+endTime);
        totalTime = (endTime - startTime)/1000000000;
        speed=(double)(transferredBytes/totalTime);
        System.out.println("Bytes is :"+transferredBytes);
        totalSpeed+=speed;
        System.out.println("Speed is :"+totalSpeed);
        }

    }
    finally
    {
      instream.close();
    }
  }

  public void updateTransferred(long transferedBytes)
  {
    transferedMegaBytes =  (transferedBytes/(1024*1024) );
    ProgressBar.status="Uploading File";
    System.out.println("Transferred: " + transferedMegaBytes + " Megabytes.");
  ProgressBar.progress+=(int)transferedBytes;
  }

  public String getResult(int i) throws NumberFormatException, IOException{

        choice=i;
        switch(choice)
        {
            case 1://System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 2:httpUploadProgress.totalSpeed/=1024;
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 3:httpUploadProgress.totalSpeed/=(1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
            case 4:httpUploadProgress.totalSpeed/=(1024*1024*1024);
                //System.out.println(httpUploadProgress.totalSpeed);
                break;
        }

        return df.format(httpUploadProgress.totalSpeed);
  }
  public static String getSpeedbps(){

      return    df.format(totalSpeed);
      }

  public static String getSpeedkbps(){
      return df.format(totalSpeed/=1024);

  }
      public static String getSpeedmbps(){

      return    df.format(totalSpeed/=(1024*1024));
      }
      public static String getSpeedgbps(){

      return    df.format(totalSpeed/=(1024*1024*1024));
      }

  public boolean isStreaming()
  {
    return false;
  }
  public static String getSpeed(){
    String str2 = "";
    if((totalSpeed<=1024)){
        str2=""+getSpeedbps();
        metrics=" Bps";
    }else if((totalSpeed>=1024)&& ((totalSpeed<(1024*1024 )))){

        str2=""+getSpeedkbps();
        metrics=" KBps";
    }else if((totalSpeed>=1024*1024)&& ((totalSpeed<(1024*1024*1024 )))){

        str2=""+getSpeedmbps();
        metrics=" MBps";
    }else if((totalSpeed>=1024*1024*1024 )){

        str2=""+getSpeedgbps();
        metrics=" GBps";
    }
    return str2;
  }

  public static String showSpeed(){
        String temp=""+getSpeed()+" "+getMetrics();
        return temp;
    }

    public static String getMetrics(){
        return metrics;
    }
  @Override
  public Object clone() throws CloneNotSupportedException
  {
    return super.clone();
  }
}
</code>
Some of the code also get deprecated. I don't know how to upload files using latest apache httpclient? I'm working on my study project, So it's a request to help with this problem. I'm newbie in JAVA.
Thanks
Answer: Seems there is already an answer to this question at file-upload-with-java-with-progress-bar
Mainly HttpClient uses somewhere an outputstream to send the Data to the target. This outputstream has to be wrapped by you to count how many bytes already have been sent/processed.
Also knowing the full filesize by file.size() you should be able to show a percentage.
With the help of a second thread you can monitor the time passed by and determine the bytes/sec.
Comment: can you help me with this code, i'm learner in java. It will be grateful if you can give any example. Thanks


Why did "gradlew assembleDebug" produce more than one apk?

Question: I am working on Mac and I used to use ./gradlew assembleDebug in command line to build my Android app's app-debug.apk for internal distribution. But this time it turned out to be 4 files
app-arm64-v8a-debug.apk
app-armeabi-v7a-debug.apk
app-x86_64-debug.apk
app-x86-debug.apk

I remember a few weeks ago this same command was producing a single file app-debug.apk. Does anyone know how to build one single app-debug.apk as before?
Comment: They are different in CPU architectures, shown by the name. You should have some basic knowledge among them: x86 vs arm, 32 vs 64, etc.
Comment: Sorry about not asking my question clearly. @GenoChen Yes I know they are for different architectures but I don't really care about that. What I am looking for is the single `app-debug.apk` as I had before. I don't want to post 4 download links and let the users try out one by one to find out which one fits their device. I revised my question a bit to clarify.
Answer: app/build.gradle
def enableSeparateBuildPerCPUArchitecture = false


Oauth Causing More permissions problems

Question: I've been working to solve this issue for months and it is just getting worse.
I have a simple program in Google Apps script that grabs email addresses from a sheet and puts them in the appropriate Google Contacts group. It was working fine up until a month or so ago when it stopped working.
Please help me:
1) Understand If I really need to work with API's to do what I'm doing.
2) Check my work below for something I might be missing.
Original Problem:
When I run this code i get the error: "You do not have permission to perform that action."
function testAddEmail(){

ContactsApp.createContact(null, null, "firstname.lastname@example.com");

};

To resolve this issues I've:
-Made sure Contacts API is enabled in my Cloud Console.
-Disabled and reinabled it multiple times.
-Created a new file with the program and enabled new Contacts API.
-Created Credentials for the new program (It worked for one day after this).
-Contacted Google Cloud Support and G Suite Support to make sure settings are correct (they don't support script or contacts.)
Problem 2:
I've tried to add the Oauth 2 code but now it gives me the error "You do not have permission to call getActiveSpreadsheet."
Are their problems in my Oauth 2 code below? (I removed my personal info.)
function getContactsService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  return OAuth2.createService('contacts')

      // Set the endpoint URLs, which are the same for all Google services.
      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      // Set the client ID and secret, from the Google Developers Console.
      .setClientId('blablabla.apps.googleusercontent.com')
      .setClientSecret('blablabla')

      // Set the name of the callback function in the script referenced
      // above that should be invoked to complete the OAuth flow.
      .setCallbackFunction('authCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties())

      // Set the scopes to request (space-separated for Google services).
      .setScope('https://www.google.com/m8/feeds')
      .setScope('https://www.googleapis.com/auth/spreadsheets')

      // Below are Google-specific OAuth2 parameters.

      // Sets the login hint, which will prevent the account chooser screen
      // from being shown to users logged in with multiple accounts.
      .setParam('login_hint', Session.getActiveUser().getEmail())

      // Requests offline access.
      .setParam('access_type', 'offline')

      // Forces the approval prompt every time. This is useful for testing,
      // but not desirable in a production application.
      .setParam('approval_prompt', 'force');
}

Comment: Check your Apps Script manifest file - have you set scopes there? if so, they override any automatic scope detection, and are used as-is. If you don't have any scopes in the manifest file, check File->Project Properties->Scopes
Comment: "oauthScopes": [
     "https://www.googleapis.com/auth/script.container.ui",
     "https://www.googleapis.com/auth/spreadsheets",
     "https://www.google.com/m8/feeds"
     ]
Comment: The above is what I have in there now. it authorizes just fine, but doesn't let me get the job done.
Answer:
Are you logged into multiple Google accounts? That often causes issues with authorization. Try logging out of everything and logging back in to just one account.
Is this running on a trigger or are you manually running the formulas?
Are the owner of the spreadsheet and logged in as the owner? Are you running this test in the spreadsheet's container-bound script?
If you're the owner of the spreadsheet and you're just adding the email addresses from your own spreadsheet to your own Gmail account then there's no reason you need to use the API or OAuth protocol.
As another commenter mentioned, what are the scopes you're requesting? To just set up a simple script from your spreadsheet to add contacts you probably just need the two you listed. You can set them manually by selecting view-->show manifest file. For example:
{
   "timeZone": "America/New_York",
   "dependencies": {
     },
   "oauthScopes": [
     "https://www.googleapis.com/auth/script.container.ui",
     "https://www.googleapis.com/auth/spreadsheets"
     ]
}

Comment: Thanks so much for your help on this!!! 1)I've logged out of everything and am testing with only one account attached.
Comment: 2) No triggers yet. Just trying to run from Menu drop down or from within the script editor. 3) I'm the owner. This is being run on my own domain.  The script isn't shared with anyone. This is container bound. 4) I'm the owner of my domain, working with my own domain account. 5) If I don't need the API's then I don't need to worry about adding scopes.

Any other suggestions? Should I reset GSuite Account settings to default?
Comment: I'd start over: Delete the permissions from this app by going to https://myaccount.google.com/permissions and "remove access". Then comment out everything in your code (better yet, delete everything) but the test function, set the scopes explicitly in the manifest file as above, and then try to run the function from the script editor. What happens then...?
Comment: So I removed ALL the permissions from every app I have. Also opened a new sheets file and pasted in the test function above. Got the same exact error. Then I added the spreadsheet and UI scopes above. The error was specifically "You do not have permission to add contacts." So I added the contacts scope. Everything reauthorized fine again. And still got the same "You do not have permission to perform that action." Do I even need scopes though? It seems like in your comments above since it is my contacts and my script under the same email address they shouldn't.
Comment: For this new file I also went in and authorized the Contacts API
Comment: Ah my bad, I copied the wrong one -- yes the first oauthScope in the manifest file should be: "https://www.google.com/m8/feeds". I wasn't able to reproduce your problem -- it worked fine for me, but I bet it's because you have a GSuite account. It looks like you might have to whitelist apps as an admin by going to  admin.google.com. Try following the steps here: https://support.google.com/a/answer/7281227
Comment: Yes, I just got it to work fine in a different gmail account. Thanks for your help. I'll test out this whitelist business.
Comment: I whitelisted everything. Removed access from every single app to my account. removed all sharing with other users. Deleted the content of the oauth json file. removed 2 step verification and removed my 2nd email account from my chrome browser. Also went in and did security check up on this account and the other account that was connected to my browser. reauthorized program. The program is now working...FINGERS CROSSED because it usually only lasts a day when it does work. I very much appreciate your help. Will mark this as the solution if it sticks. feel free to check in to remind me. Thanks!
Comment: It only worked very briefly. It worked for me then sometime between when I fixed it and When my assistant went in there a few hours later it was broken again. assistant had his personal gmail logged into as well.
Comment: Did all the things I could with my assistant and it didn't work. Arg!!! He uses the same login as me to the same account so there shouldn't be anything different.
Comment: Maybe a cookies thing? Try in new incognito session

Oauth Causing More permissions problems


Representation of finite group and Classifying finite simple group

Question: My question is quite clear as the title of it. I had studied theory of representation of finite group and I also had known something about the program of classifying finite simple group, and in general, the problems of two subjects is not far different, but in fact, I have not seen any mathematical paragraph that tells us about the connection(of these two subject).
But, I think the two subject both give us the structure of finite group. Could any MSer point it out for me?
Thanks.
Comment: Will this link help, http://www.ams.org/notices/199502/solomon.pdf ? But, there's very little about the connection, but points out to the work of many people in this direction
Comment: Your title does not at all make it clear what you want to ask...
Comment: Sorrry, Mariano. I in my head thought about the title "the bridge between representation theory of finite group and classifying finite simple group, but I did wrote down the other name without awaring.
Answer: Representation theory of finite groups over the complex numbers yields information about groups which can be be determined by group characters. The most important characters in this context are the irreducible characters, and complete information about these can be encoded within the character table, which is a $k \times k$ array, where $k$ is the number of conjugacy classes of the group in question, say $G.$ It can be determined by inspection from the character table whether there are any normal subgroups of $G$ other than the trivial group and $G$ itself, ie whether $G$ is simple or not. However, it is sometimes possible to use remarkably small amounts of character-theoretic information to prove the non-simplicity of $G.$ There is a long tradition of using the embedding of certain subgroups of $G$ to produce enough character-theoretic information to show that $G$ is not simple. Two early examples of such theorems were Burnside's $p^a q^b$-theorem and Frobenius theorem about subgroups of $G$ which have trivial intersection with all their distinct conjugates. This tradition continued until the 1960s and beyond, and was give fresh impetus by the work of Richard Brauer, who showed how to use modular methods to further refine character-theoretic information. These methods were particularly effective when dealing with simple groups of low $2$-rank, that is without elementary Abelian $2$-subgroups of order $8$ or more. In particular, character theory played a prominent role in the proof by Feit and Thompson of the solvability of finite groups of odd order, and in the classification of finite simple groups with dihedral or semi-dihedral Sylow $2$-subgroups (as well as proving that no finite simple group has generalized quaternion Sylow $2$-subgroups). Another high point of the use of character theory was Glauberman's $Z^{*}$-theorem, which proved that if $G$ is a finite non-Abelian simple group, and $t$ is an involution of $G,$ then $t$ commutes with one of its other conjugates, which was used as a starting point for many group-theoretic analyses in the classification programme. It is probably fair to say that in the later stages of the classification programme, ordinary character theory played less of a role, with the honorable exception of the $Z^{*}$-theorem. On the other hand, most of the infinite families of finite simple groups are best described in terms of natural representations over finite fields.


Data disappear after refreshing the page when using browserHistory locally

Question: I had this issue where I was testing the react-router browserHistory on a webpack-dev-server and when I refresh any of the routes I get something like this Cannot GET /pageurl
In the production case it's a server configuration case as mentioned here, but it's a test and I'm using a development server!
Answer: So the solution was so simple! as mentioned in this article all I have to do is to add the following to webpack.config.js file
devServer: {
    port: 8080,
    historyApiFallback: true
}

and BAM it works!, alright I just wanted so share this because it wasn't easy to find the solution. bbye.


Adding hive jdbc dependency breaks Glassfish deployment

Question: I'm building a Java webapp that needs to access Hive through JDBC, deployed on a Glassfish.
Once the hive jdbc maven dependency
<code><dependency>
    <groupId>org.apache.hive</groupId>
    <artifactId>hive-jdbc</artifactId>
    <version>2.1.0</version>
</dependency>
</code>
is added, deployment breaks and Glassfish gives the following exception:
Error occurred during deployment: Exception while loading the app : CDI deployment failure:WELD-001408: Unsatisfied dependencies for type Injector with qualifiers @Default at injection point [BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] @Inject public org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter(Injector) at org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.(RMWebAppFilter.java:0) . Please see server.log for more details.
Comment: Which version of Glassfish do you use?
Comment: I'm using GlassFish Server Open Source Edition 4.1.1 (build 1). The issue seems to have something to do with guava version having to be updated. I tried excluding them from my project, but I think I'll have to upgrade it on Glassfish itself
Answer: This seems to be a dependency issue with the libs provived by Glassfish 4.1.1 (1).
It works in Glassfish 4.1 (13). If possible, you should use this version. You can download it here: https://glassfish.java.net/download-archive.html
Comment: Will try upgrading to (13) and get back to this asap.
Comment: Updated to Glassfish 4.1 (13) and still have the same issue. I take out the hive jdbc dependency and it deploys with no issues instantly.
Answer: Solved the issue by

Updating from Glassfish 4.1(1) to Glassfish 4.1(13). However this did not on itself solve the issue.
On Glassfish's deploy screen in the admin console I disabled Implicit CDI Discovery.
Comment: where we can find CDI Discovery in admin console?
Answer: Hive-jdbc has some unfortunate dependencies (javax.*, jetty etc).
Your error comes from a transitively included YARN webapp.
Try to slim down the Maven dependencies of hive-jdbc,
as some dependencies like YARN do not belong in a JDBC driver.,


PDO drivers missing on Ubuntu 16.04 with PHP 7.2.4

Question: I wanted to try the latest version of PHP on Kubuntu 16.04, since then, it seems I can't use pdo with mysql.
When I launch php, I have the following warning:
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_mysql' (tried: /usr/lib/php/20170718/pdo_mysql (/usr/lib/php/20170718/pdo_mysql: cannot open shared object file: No such file or directory), /usr/lib/php/20170718/pdo_mysql.so (/usr/lib/php/20170718/pdo_mysql.so: undefined symbol: pdo_parse_params)) in Unknown on line 0

I'm running
PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr  5 2018 08:53:57) ( NTS )

I tried to fix with this solution : https://askubuntu.com/a/824505, but I've the same problem.
However, in the phpinfo, there's a driver found for PDO (mysql).
When I check a php -m, PDO and pdo_mysql are found.
In the /usr/lib/php/20170718 and /usr/lib/php/20151012 folder, there is a pdo_mysql.so.
I don't really know what else to try. Thanks in advance for your help.
Comment: Check whether the line enabling `pdo.so` is above the line enabling `pdo_mysql.so`
Comment: I added pdo in the php.ini (extension=pdo), but nothing changed,
Comment: Do you use any included config files that might get parsed first?
Comment: Nothing that I'm aware of, Idk how I can assure this tho.
Comment: Same issue with 18.04 LTS
Comment: I think this is related to https://askubuntu.com/questions/999999/php-with-pdo-mysql-in-ubuntu-16-04 where there is a solution
Answer: sudo apt-get update
sudo apt-get install php7.2-pdo

Comment: Hello, it tries to install php7.2-common when I run it. Since it's already installed, it does nothing.
Comment: I updated to Ubuntu 18.04 LTS today, same issue. Tried installing plenty of PHP DB related extensions, none satisfied PDO.
Answer: In my case I had updated from Ubuntu 16.04 to 18.04, thus PHP 7.0 to 7.2.
Turns out PHP 7.0 was still (partly) installed, and was the active PHP-FPM handler for Apache.
Commands I used to resolve this: (as root or via sudo)
service php7.0-fpm stop
apt-get remove php7.0*
service php7.2-fpm restart
service apache2 restart

Be sure to copy any INI changes you made from /etc/php/7.0 to /etc/php/7.2 though.
Comment: I did an upgrade from 16.04 to 18.04 and did not find this was the case, but the issue prevails.


What is my current octave range, can it go much farther, and how can I increase it?

Question: My lowest note is a D3, and my highest note is an F6. I am a 14 year old female. I play clarinet, so I am often exercising my lungs even when I am not singing. My dad has more of an average range, but my mom used to have a range of 4-5 octaves. I think I am a mezzo soprano, I am just not certain about how many octaves I have.
Could anyone tell me what my range is and how I can improve it?
P.S. I have had a cough for almost 2 years now that seems asthmatic and may be influenced by allergies. If I could get rid of it, how would that affect my range?
Comment: There are a lot of questions with good answers about extending your range. Here's a few. http://music.stackexchange.com/questions/15947/how-to-extend-the-range-of-your-voice?rq=1, http://music.stackexchange.com/questions/14247/finding-and-improving-singing-range-and-power?rq=1. Good luck.
Comment: Does this answer your question? [How can I safely extend my vocal range?](https://music.stackexchange.com/questions/804/how-can-i-safely-extend-my-vocal-range)
Answer: The best way to answer all your questions is to take some singing lessons from a qualified voice teacher, or at least to do some singing for your school or church or community choir director. There is absolutely no way that anybody can properly answer these questions of yours by reading your short written description of your voice.
In addition, if you are interested in pursuing some singing lessons, your voice and your range will probably "open up" and you may develop the ability to sing in different, wider registers than what you can do now. However, you are quite young; serious singing lessons are sometimes best left until you are older. You would need to consult with a qualified teacher about that.
As far as your chronic cough or asthma symptoms, your singing would certainly improve if your cough went away, so you may need some medical help there.
Answer: As you said, you've already made a lot of progress in the breath support training.
Of course a private voice teacher would be ideal.  If that's not feasible for you at this point, find a choir to sing in (church, school, community center, etc.).  You can learn a lot from a good choir director.  Also, the director may be willing to coach you, even if it's only once every month or two.
One's range might expand through the right sort of singing practice.
It sounds like you've got quite a large range -- slightly over three octaves.
It would be a very good idea to clear up your respiratory problems.  You could start with your primary care doctor.  You might find it helpful to see a specialist, but you might be able to make some good progress with just the primary.
Untreated respiratory problems can result in permanent damage to the voice.


Does the order of elements in app.config matter?

Question: I have seen and experienced problems with app.config/web.config where I had changed the order of elements and the app stopped working.
I believe I fixed the problem by looking at machine.config and following the order in there.
One example is the following question: Common.Logging config exception
The issue was resolved by changing the order the elements appear in the file.
So, the question is, does the order of elements matter?
It appears to me it does.
If it does, is it documented anywhere, an xsd schema maybe?
Answer: It appears that at least for the configSections element order does matter.
Document http://msdn.microsoft.com/en-us/library/ms228256.aspx states the following:
"If the configSections element is in a configuration file, the configSections element must be the first child element of the configuration element."
I got this from here: http://social.msdn.microsoft.com/Forums/en-US/clr/thread/60c7b502-f7fc-49e9-b4b0-771b4fb4134e
Answer: here you have the entire explanation of the web config. the order and the requiered tag.
http://msdn.microsoft.com/en-us/library/ackhksh7(vs.71).aspx


How to create shaded mesh in opengles on android

Question: In my application I'm trying to create a mesh that is shaded by a single directional light. The problem I'm facing is that I can't seem to get the light to take my normals into account at all.
It works fine if I set the normals on a per-triangle-strip basis, but if I try to render a series of triangles with normals set using the glNormalPointer method the entire mesh is rendered using the same color (which is identical to the result I'm getting if I skip calling glNormalPointer all together).
My mesh render method looks like this:
public void render(GL10 gl) {
  gl.glFrontFace(GL10.GL_CW);
  gl.glNormalPointer(GL10.GL_FLOAT, 0, normalBuffer);
  gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
  gl.glDrawElements(GL10.GL_TRIANGLES, indexBuffer.capacity(), GL10.GL_UNSIGNED_BYTE, indexBuffer);
 }
Answer: You should call
glEnableClientState(GL_NORMAL_ARRAY);

Comment: Thank you! That was driving me nuts.


What is the derivative of $\ln\left(x^2 + (3/4)x\right)$?

Question:
What is the derivative of $\ln\left(x^2 + (3/4)x\right)$?

I did $\dfrac{1}{\left(x^2 + (3/4)x\right)}$ and multiplied it by $(2x + 3/4)$
Is this right? Should I have flipped $3/4$ instead because it was being multiplied to the numerator which is $1$?
Comment: Yes, it is right. No, you need no flipping
Answer: Yes you are correct.It's $$\frac {2x+\frac {3}{4}}{x^2+\frac {3x}{4}}$$
Comment: Thanks for the verification. I can never seem to format my texts like that. lol
Answer: Instead of doing pattern matching in your head in applying the chain rule, you can use the property of the logarithms:
$$\log\left(x^2 + \tfrac{3}{4}x\right)=\log\left(x\cdot\left(x + \tfrac{3}{4}\right)\right)=\log(x)+\log\left(x + \tfrac{3}{4}\right)$$
And then
$$\frac{\mathrm d}{\mathrm dx}\left(\log(x)+\log\left(x + \tfrac{3}{4}\right)\right)=\frac{1}{x}+\frac{1}{x\ +\tfrac{3}{4}}$$
which you might rewrite by introducing the common denominator $x\cdot\left(x + \tfrac{3}{4}\right)$.
Answer: The derivative is the product of $\frac{d}{dy}\ln(y)*\frac{d}{dx}y$ where $y=x^2+\frac{3}{4}x$, which is
$$\frac{1}{x^2+\frac{3}{4}x}\left(2x+\frac{3}{4}\right)$$


Spring MVC RestTemplate POST using JSON

Question: I have a Spring MVC Rest Controller that simply adds a customer record. My Rest Service passes around JSON and works fine when I call it from a web client or a test bed like Soap-UI. However, when I try to POST using RestTemplate I get a JacksonMappingException: Can not construct instance of CustomerObject, problem: no suitable creator method found.
It's clearly something to do with the way I am creating the JSON request so to add some meat to the bones here is what I'm doing:
My Test posts using RestTemplate
 @Test
 public void postCustomerIntegrationTest() throws Exception{

    String JSONInput = ("{" +
          "  \"firstName\": \"Anouska\"," +
          "  \"lastName\": \"Williams\"," +
          "  \"email\": \"firstname.lastname@example.com\"," +
          "  \"cardBin1\": 123456768," +
          "  \"cardBin2\": 123456789," +
          "  \"language\": \"Spanish\"," +
          "  \"country\": \"Mexico\"," +
          "  \"product\": \"shit\"," +
          "  \"telephoneNumber\": 447869995262," +
          "  \"termsAndConditions\": \"true\"" +
          "}");

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);

  HttpEntity request= new HttpEntity(JSONInput, headers);

Registration output = restTemplate.postForObject(BASE_URL, request, CustomerObject.class);

assertNotNull("no person",output);
assertNotNull(output.getId());
assertEquals("Bob", output.getFirstName());

}

My RestTemplate is wired through Spring as follows:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
    <list>
        <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="supportedMediaTypes" value="application/json" />
        </bean>
    </list>
</property>
</bean>

The test JSON I'm using here is the same as the test JSON I use in Soap-UI. Having debuged the code it looks like it is treating my JSON as a String and Jackson is trying to convert the entire thing because it can't find an assiciated field (which of course it can't).
I guess I need to know how to pass JSON to my RestTemplate in such a way that the request will be picked up in the correct JSON format. I've spent all morning trying to find an example and can't find one anywhere.
Many Thanks for your help.
Answer: There is at least one problem, last parameter should be class of response
Registration output = restTemplate.postForObject(BASE_URL, request, Registration.class);

Answer: This is my way to post josn:
CustomerObject object = template.postForObject(
            BASE_URL, request, CustomerObject.class);

And CustomerObject class must have fields: firstName, lastName...

Spring MVC RestTemplate POST using JSON


Fitch system, or alternatives?

Question: Is there a good resource for how to understand the rules of a Fitch proof system, or an alternative? I'm currently trying to get a sense or how things are proved in natural deduction, which differs in that context changes are allowed / assumptions can be introduced and discharged, and so on.
Can you still make a proof using the line-by-line approach like you could in a Hilbert system? I don't really understand the usefulness of the Fitch system when it's hard to type and present outside of a handwritten diagram. Is there an "equivalent" way we can represent what's going on, perhaps, so that the Fitch system is easier to understand?
I get that an indentation level is a "new context" or an "introduced assumption" but I don't know what we're allowed to write on which lines in general, when we're allowed to discharge an assumption, when we know when we've proven something, when we are finished, etc.
Comment: Frederic Brenton Fitch, [Symbolic Logic: An introduction](https://books.google.it/books?id=x4lIuAEACAAJ).
Comment: Jon Barwise and John Etchemendy, [Language, Proof and Logic](https://books.google.it/books?id=beKNZwEACAAJ).
Comment: I suppose I have answered some of this in chat, but there is an additional point to be made. Hilbert-style is to Fitch-style what assembly language is to C/Java/Python. In Hilbert-style, you have just line-by-line in the same way that assembly code has no concept of `if` or `for` structures/loops. In Fitch-style, you have the concept of subcontexts, such as `if` or `forall` contexts, which simply make everything user-friendly. Sure, it is harder to explain, but it is way easier to come up with and write down than a Hilbert-style proof.
Comment: [Online](http://www.proofmood.com/index_en.php) (but many others).
Comment: @MauroALLEGRANZA: Thank you very very much for posting that. I had been trying in vain to find that website for a long time now. I suspect they had changed the website name, because I do not recognize the name, but the rabbit is exactly the same!
Comment: @user21820 - you are welcome :-)
Comment: You can see also [Lean](https://leanprover.github.io/about/) as well as [Natural deduction](http://proofs.openlogicproject.org/). And [forall x](http://forallx.openlogicproject.org/).
Comment: May I remind you of the link https://www.iep.utm.edu/nat-ded/ that I recommended to you yesterday? It compares several ways of presenting natural deduction proofs.
Comment: @MauroALLEGRANZA: I used to recommend forallx but stopped after at least two students got the same misunderstanding from it; page 156 of [forallxyyc](http://forallx.openlogicproject.org/forallxyyc.pdf) says "First, we have names. In FOL, we indicate these with lowercase italic letters. For instance, we might let 'b' stand for Bertie, or let 'i' stand for Willard." and so page 245 to 256 give an incorrect ∀-Intro rule, because it did not exclude names in axioms.
Comment: If your motivation for learning logic is to be able to write mathematical proofs, you might consider my DC Proof 2.0 freeware and accompanying tutorial. It is based on a simplified version of FOL, more like that typically used in say real analysis or abstract algebra. Download at http://www.dcproof.com
Comment: @DanChristensen I've seen that before but I don't have Windows at my disposal (I'm on a Mac)
Comment: It is possible to run it on a Mac if it has a Windows emulator. I have sat with a Mac user as he downloaded, installed and ran my program on his machine all within a minute or two. It might be worth your while to get a Windows emulator. You might be able to get one free from https://www.winehq.org/  If you want to write mathematical proofs, my program may be best place to start learning the required logic and basic methods of proof.
Answer: A reference that might rapidly get you past concerns with using Fitch-style natural deduction is the forallx Calgary Remix: An Introduction to Formal Logic text and the corresponding general-use, Fitch-style proof checker. See links below.
For example, consider a proof of disjunctive syllogism: $¬A, A ∨ B ∴ B$.
Here is how the proof checker might allow you to prove this:

There are two options: TFL (Truth Functional Logic) and FOL (First Order Logic). They work for general purpose questions and not only the problems in the text. The software resolves formatting issues with the indented subordinate proofs and provides an ability to check along the way to make sure mistakes have not been made.
The text provides a slightly different proof in section 19.2 as well as providing an introduction to the other rules available in natural deduction along with an introduction to formal logic.

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/
P. D. Magnus, Tim Button with additions by J. Robert Loftis remixed and revised by Aaron Thomas-Bolduc, Richard Zach, forallx Calgary Remix: An Introduction to Formal Logic, Winter 2018. http://forallx.openlogicproject.org/

Fitch system, or alternatives?


JAXB cannot locate a file from a relative path

Question: I'm trying to use Jaxb in order to unamrshal an xml file. for some reason that I don't understand, I cannot refer to any other location then a full path on my specific computer. In the code below, the commented line doesn't work, but only the one above it. the file does exist (in two locations) and the commented line does work on a diffrent class.
JAXBContext jc = JAXBContext.newInstance(Monopoly.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
//unmarshaller.unmarshal(new File("resources/monopoly_config.xml" ));
unmarshaller.unmarshal(new File( "C:\\Users\\Lior\\Documents\\NetBeansProjects\\Monopoly curr\\MonopolyServer\\src\\BoardInfoResources\\monopoly_config.xml"));

Answer: UPDATE
Since you are deploying to a server (from your comments), why not load your XML using a ClassLoader?  In a server environment you wouldn't be able to count on the File object in the way that you want to (as you have already discovered):
ClassLoader cl = Monopoly.class.getClassLoader();
InputStream xml =
 cl.getResourceAsStream("resources/monopoly_config.xml");
JAXBContext jc = JAXBContext.newInstance(Monopoly.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Monopoly monopoly = (Monopoly) unmarshaller.unmarshal(xml);

JAXB will allow you to unmarshal any valid file object.  And it will definitely unmarshal files created with relative paths (see answer below for an example):

How to unmarshal xml message with bad parent/child model

In your example you will need to make sure that your working directory is set correctly.  Based that your full path is:
"C:\\Users\\Lior\\Documents\\NetBeansProjects\\Monopoly curr\\MonopolyServer\\src\\BoardInfoResources\\monopoly_config.xml"

Assuming your working directory is:
"C:\\Users\\Lior\\Documents\\NetBeansProjects\\Monopoly curr\\MonopolyServer\\src\\"

Your relative path appears to be wrong (since there is no resources directory):
"resources/monopoly_config.xml"

You may have meant it to be:
"BoardInfoResources/monopoly_config.xml"

Comment: This is the answer. Just to add to it, though, is you can check your current working directory by doing: System.out.println(System.getProperty("user.dir"));
Comment: Thank you for that. unfortunately, this doesn't solve it. Sorry if I wasn't clear earlier - both resources and BoardInfoResources exist and contain the xml, however, it will simply not work unless it's a full path.
Comment: @Lior - Did you check your working directory as suggested by Alvin?
Comment: yap, it is C:\Users\Lior\Documents\NetBeansProjects\Monopoly curr\MonopolyServer. I was able to make it run "on it's own", but when I try to deploy it to my server I get "java.io.FileNotFoundException: C:\apache-tomcat-6.0.32\bin\src\BoardInfoResources\monopoly_config.xml (The system cannot find the path specified)]"
Comment: @Lior why don't you load it from the ClassLoader instead?  See my updated answer for details.
Comment: Any tips on how to avoid the need to restart netbeans, re install axis and rebooting so often? I keep getting to a point that I have to take these actions because deploy doesn't seem to effect..
Comment: @Lior - You may want to start a new question about this last issue, that may bring in the NetBeans and Axis people.


Telerik RadGrid inside modalpopup?

Question: So, as the title suggests ;)  I'm trying to place a databound RadGrid inside a modal popup.  I've fiddled with Telerik's examples without luck. I seem to be having two principal problems, likely because of my inexperience.  One is that I need to trigger it from an already extant itemcontrol in the grid. The other is that it doesn't seem like the popup extender plays nicely with the Telerik script manager and if I try to add an ASP script manager I get an exception.
As always, I'm very grateful for any suggestions!
Thanks!
Comment: Is your popup content on the page already, or does it contain a separate window?  Are you loading the RadGrid based on an argument from the parent page?
Comment: @Seano666 At the moment I have the grid within a placeholder that I show/hide when the databinding is triggered by an item command.  I'd like to trigger the modal popup the same way... thanks for any input!
Comment: After your databinding you could use the VisibleOnPageLoad property of the RadWindow.  Hopefully I am understanding your requirement correctly.  http://www.telerik.com/forums/how-to-open-rad-window-from-codebehind-in-c
Comment: Try this approach http://demos.telerik.com/aspnet-ajax/controls/examples/integration/gridandwindow/defaultcs.aspx?product=window
Comment: @Seano666 Thank you... that's exactly what I wound up doing.  Seems to work fine.  Thank you!
Comment: @PaulBinCT2 Great, I'll make an official answer then, glad I could help!
Answer: After your databinding you could use the VisibleOnPageLoad property of the RadWindow.
<code>Control.DataBind()
RadWindow1.VisibleOnPageLoad = true;
</code>

Telerik RadGrid inside modalpopup?


JavaScript & PayPal Checkout Button Question

Question: I am currently testing out the sandbox for the PayPal checkout integration using Javascript.
I see how to use the "Sandbox" mode versus using the "Live" mode when testing our buttons out in Javascript.
What I'm asking is how do I set the product's title so that the buyer can see exactly what they're about to purchase prior to clicking the "Pay Now" button to finalize the transaction?
Here is the code that I'm currently working with as shown below:
//HTML GOES HERE TO CONTAIN THE PAYPAL BUTTON

paypal.Buttons({
    style: {
        layout:  'vertical',
        color:   'gold',
        shape:   'pill',
        label:   'buynow'
    },

    // Sets up the transaction when a payment button is clicked
    createOrder: function(data, actions) {
      return actions.order.create({

        purchase_units: [{
          amount: {
            value: 50, // Can reference variables or functions. Example: `value: document.getElementById('...').value`
            currency: 'USD'
          },

        }]

      });

    },

    // Finalize the transaction after payer approval
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(orderData) {
        // Successful capture! For dev/demo purposes:
            console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
            var transaction = orderData.purchase_units[0].payments.captures[0];
            alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

        // When ready to go live, remove the alert and show a success message within this page. For example:
        // var element = document.getElementById('paypal-button-container');
        // element.innerHTML = '';
        // element.innerHTML = '
Thank you for your payment!
';

        actions.redirect('https://SomeWebsiteURLiWillForwardThemTo.com');
      });
    }
  }).render('#paypal-button-container');

Answer: In paypals docs you can see the purchase unit object. https://developer.paypal.com/docs/api/orders/v2/#definition-purchase_unit inside that object you can see that you can pass an items array. This is an array of objects that you can view here https://developer.paypal.com/docs/api/orders/v2/#definition-item. You can define the parameters of each product including the name. So in your case I think you can try something like the following:
purchase_units: [{
  amount: {
    value: 50,
    currency: 'USD',
    breakdown: {
      item_total: {
        currency_code: 'USD',
        value: 50
      },
    }
  },
  items: [
   {
     name: 'Product Name',
     unit_amount: {
       currency_code: 'USD',
       value: 50
      },
      quantity: '1'
    }
  ]
}]

Here is a working fiddle just pop in your client id to test. Fiddle Demo
NOTE: Look at the docs and see what are required fields. I also think that you need to apply a breakdown to the amount for this to work.
Comment: Yes, I've tried this before, but when I try to test the "items:" option in sandbox (haven't tried "live" yet), the new PayPal window tries to open up and load, but then it quickly just crashes and closes right back down immediately.

Here's what I just tried a couple of minutes ago, then it keeps crashing:
Comment: // Sets up the transaction when a payment button is clicked
    createOrder: function(data, actions) {
      return actions.order.create({

        purchase_units: [{
          amount: {
            value: paypal_price, // Can reference variables or functions. Example: `value: document.getElementById('...').value`
            currency: 'USD'
          },
          items: [
            {
              name: 'Product Name'
            },
          ]

        }]

      });

    },
Comment: Yes, I've tried this before, but when I try to test the "items:" option in sandbox (haven't tried "live" yet), the new PayPal window tries to open up and load, but then it quickly just crashes and closes right back down immediately.
@Steve K

Here's what I just tried a couple of minutes ago, then it keeps crashing:
Comment: `// Sets up the transaction when a payment button is clicked
    createOrder: function(data, actions) {
      return actions.order.create({

        purchase_units: [{
          amount: {
            value: paypal_price, // Can reference variables or functions. Example: value: document.getElementById('...').value
            currency: "USD"
          },
          items: [
            {
              name: "Product Name"
            },
          ]

        }]

      });

    },
         `
Comment: You need to add a breakdown to the amount I think for this to work. Like I said in the note before you need to look and see what fields are required. Unfortunately Paypals docs are a mess and its like following the breadcrumbs and is really easy to miss something. I updated the answer with working code and a fiddle demo. You can see the product and total breakdown if you click the down arrow by the price in the checkout now.
Comment: Thanks again Steve! Seems to be working now. I think it would be even nicer if PayPal gave the option to already have that drop down already set to dropped down in case the buyer doesn't see it to click it and see exactly what the product or service title is that they're about to purchase. Anyhow, thanks again.
Comment: Hi , can any one say me how to add tax value in its ...
Comment: @user3209031 https://developer.paypal.com/docs/api/orders/v2/#definition-item in the item object you can see the definition for the tax value.
Comment: Thanks, steve do u have  php server side full demo , can u please share ? means after transaction is completed , i need to send that data in my database


Add different types of the same probe in Smokeping

Question: How do you add different probes of the same type in Smokeping?
My initial attempt:
<code>+ FPing
binary=/usr/sbin/fping

+ FPing2
binary=/usr/sbin/fping
sourceaddress=192.168.1.2
</code>
Yielded:
<code>$ smokeping check
require Smokeping::probes::FPing2 failed: Can't locate Smokeping/probes/FPing2.pm in @INC (@INC contains: .. /usr/share/smokeping /root/perl5/lib/perl5 /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at (eval 22) line 2, <$fh> line 111.
</code>
I'm sure I'm overlooking something obvious!
I have consulted the Probe documentation here https://oss.oetiker.ch/smokeping/probe/index.en.html, to no avail and I'm sure that something so trivial shouldn't require a new module.
Answer: Yes, I was overlooking something obvious - the "Probe" section of the "Config" page in the documentation here: https://oss.oetiker.ch/smokeping/doc/smokeping_config.en.html#___top
<code>+ FPing
binary = /usr/sbin/fping

++ FPingA
sourceaddress = 192.168.1.2

++ FPingB
sourceaddress = 192.168.1.3

# Further down under Targets:
probe=FPingA
</code>
SImple as that!
Comment: The BIG thing missing here, and in the documentation is:  "if you want two FPing probes, *both* must be Children of FPing ..."  - https://lists.oetiker.ch/pipermail/smokeping-users/2016-September/005903.html   So in the example Config given in the answer here, only FPingA and FPingB can be specified as a probe= value.
Answer: Copy the probe file under another name, in the same direcotory (/SMOLKEDIR/lib/Smokeping/probes)
eg: cp EchoPing.pm EhoPing2.pm
open EchoPing2.pm with any text editor,
make obvious changes
(eg: at the first line change Smokeping::probes:EchoPing whit Smokeping::probes:EchoPing2
and so on.
Use both EchoPing and EchoPing2 in the same mannner in the RTT file
Comment: Thanks for the attempt - and this was my first thought too - but this is not portable - as you'd have to ship changes with any config files... also, the existing configuration files support this quite elegantly.


Why would a custom Node.js CLI work with npm link, but not when installed on Windows?

Question: I've created a Node.js command line tool on Mac. I've tested it using npm link and there don't seem to be any problems. Others have installed it on Mac, and it seems to work. When installed on Windows, the CLI will run up until it gets to the point where it needs to create files. At that point, the CLI exits with no errors. Using npm link on Windows does result in a working solution, however.
The CLI itself uses Node 4.x and has no external dependencies. All file operations are done using the fs module. If you would like to investigate further, the full source code is available here: https://github.com/aurelia/cli It's also published on npm under the name aurelia-cli.
Comment: It sounds like you need to see what is causing it to exit, probably an exception being thrown.  That would be your biggest clue.
Comment: have any output do give us ? You may also want to spin up windows via vagrant or testing purpose, i can give you example if you d like to. Try also npm i -g on your box instead of npm link.
Answer: We finally figured it out. I'm still not sure why the exception was being swallowed but we were able to track it down by installing on windows, going to the install location and manually tracking progress with console logs and strategic try/catch blocks. Interestingly, it was caused by a require of a file which was missing. This caused execution to halt. We still haven't figured out why this only happened on windows, because the missing file was due to a gitignore, which seems like it should have affected all installs. However, we were able to easily solve the problem and publish the fix.


How to test React with hooks and PubSub-js with Jest Enzyme

Question: hello I have a simple app that connects with a topic and then updating he's state, seems to be working when playing around, but I have a problem with how to properly write a test for it
There is a library I using https://www.npmjs.com/package/pubsub-js
import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'

const App = () => {

 const [data, setData] = useState([])

 const mySub = (msg, pubData) => {
  setData(pubData)
 }

 useEffect(() => {
  const token = PubSub.subscribe('TOPIC', mySub);

  return () => {
   PubSub.unsubscribe(token)
  };
 },[]);

 return (
  <input onChange={() => {}} value={data && data[0]?.value}
 )
};

import React from 'react'
import PubSub from 'pubsub-js'
import { mount } from 'enzyme'
import App from '.'

const mocked = [{ value: 1}]
describe('should receive some date', () => {
 it('xx', () => {
  const app = mount(<App />)
  PubSub.publish('TOPIC', mocked);
  PubSub.publishSync('TOPIC', mocked);
  // WHAT NEXT?
 })
})

I've tried some
spies, finding input and checking values, but nothing change... why?
How should I test this Function component?
Comment: Where does `mount` function come from?
Comment: @slideshowp2 I added imports
Answer: Since the PubSub.publishSync() operation will trigger mySub event handler that updates the state of the component. Make sure you wrap the code that causes React state updates into act(), otherwise, you will get a warning:

Warning: An update to App inside a test was not wrapped in act(...).

E.g.
index.jsx:
import React, { useState, useEffect } from 'react';
import PubSub from 'pubsub-js';

export const App = () => {
  const [data, setData] = useState('a');

  const mySub = (msg, pubData) => {
    setData(pubData);
  };

  useEffect(() => {
    const token = PubSub.subscribe('TOPIC', mySub);

    return () => {
      PubSub.unsubscribe(token);
    };
  }, []);

  return
{data}
;
};

index.test.jsx:
import React from 'react';
import PubSub from 'pubsub-js';
import { mount } from 'enzyme';
import { App } from './';
import { act } from 'react-dom/test-utils';

describe('67422968', () => {
  it('should receive data and update the state', () => {
    const wrapper = mount(<App />);
    expect(wrapper.text()).toBe('a');
    act(() => {
      PubSub.publishSync('TOPIC', 'b');
    });
    expect(wrapper.text()).toBe('b');
  });
});

test result:
 PASS  examples/67422968/index.test.tsx (7.254 s)
  67422968
    ✓ should receive data and update the state (28 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |   91.67 |      100 |      75 |   90.91 |
 index.tsx |   91.67 |      100 |      75 |   90.91 | 15
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.902 s, estimated 8 s

package versions:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"pubsub-js": "^1.9.3"

Comment: unfortunately not updating state for me...
I have empty array as starting state, and its not changing at all,


Has the Block Cache Settings from Drupal 8 been back-ported to Drupal 7?

Question: I noticed in Drupal 8 there are options to cache a block:

I was wondering if these options exist in Drupal 7 with a module? Has the feature been back ported? or was it a contrib module to begin with?
Comment: The D7 version is [Block Cache Alter](https://www.drupal.org/project/blockcache_alter) I think. It doesn't have contextual caching, I believe that's very new
Comment: @David Barratt Where, in the Drupal Web Admin UI, are the Drupal 8 Block Cache settings shown in the screen - i.e what would the general URL path be, please?
Comment: Question about location of your screenshot of block caching asked here: https://drupal.stackexchange.com/questions/274874/block-caching-in-drupal-8-is-there-a-setting-to-turn-this-off-per-block-block
Answer: No, it's impossible to backport. See https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7's DRUPAL_CACHE_CUSTOM and https://www.drupal.org/developing/api/8/cache/contexts.