text:
Q: Why function inside while loop does not work? I want to use while loop for looping and activating function 5 times. But I have problems making function myFunction work inside the while loop. The loop works by itself if I remove the function. What's wrong?

var c = 0;
var p = 0;

while (c < 5 && p < 5) {
  function myFunction() { // How to make this function work?
    c++;
    document.write(c);
  }

  if (c == 5) {
    document.write(c);
    document.write('computer win');
  }
  else if (p == 5) {
    document.write('player win');
  }
}

A: You are declaring a function in  the loop but aren't calling it.

function myFunction() { // how to make this function work?
  c++;
  document.write (c);
}

var c = 0;
var p = 0;

while ( c < 5 && p < 5) {
  myFunction();
  if ( c == 5 ) {
    document.write (c);
    document.write ('computer win');
  } else if ( p == 5 ) {
    document.write ('player win');
  }
}

A:     var c = 0;
    var p = 0;

    function myFunction() {

        c++;
        document.write(c);
    }

while (c < 5 && p < 5) {

    myFunction();

    if (c == 5) {
        document.write(c);
        document.write('computer win');
    } else if (p == 5) {
        document.write('player win');
    }

}

In JavaScript or any other language, you have to define the function to invoke it. And defining a function inside a loop is a very bad practice probably gives an error.

A: You didn't invoke the function, merely declared it.


text:
Q: value not display correctly in textbox populate value in second textbox based on the value selected in first textbox by using jquery and ajax in mvc3 I am working on a small form in mvc3 with 2 fields 1 is for account code and second is for account description.
i get data of account code and description from sql server 2008 r2 database in account code field with jquery autocomplete textbox but it does not display values coreectly in text boxes.
below is my code.
$(function () {
        $("#AcCode").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Home/AutocompleteSuggestions", type: "POST", dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.split('-')[0], value: item.split('-')[1] }
                        }))
                    }
                })
            },
            minLength: 1,
            select: function (event, ui) {
                if (ui.item) {
                    alert("You picked" + ui.item.label + "' with a value of " + ui.item.value);
                     $("#AcCode").val(ui.item.label),
                   $("#Descrip").val(ui.item.value);
                }
            }

        });
    });

it display description in account code field and nothing display in description field.
 help me to solve this problem. i want to display descripton in description field and account code in account code field.
function  to get data from database
      public List GetAutoCompDataDAL(string Acode)
        {
        List<string> result = new List<string>();

        using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
        {
            using (SqlCommand cmd = new SqlCommand("select AcCode,Descrip from Account where AcCode like '%'+@AcCode+'%' order by AcCode asc", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@AcCode", Acode);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {

                    result.Add(string.Format("{0}-{1}", dr["AcCode"].ToString(), dr["Descrip"].ToString()));

                }
                con.Close();
                return result;
                //return result1;
            }
        }

    }

A: You can either use a viewmodel (option #1) that can represent AcCode and Descrip or if you don't want that extra code (additional class) then return a list of objects (option #2):
// option #1 if you want a viewmodel
public class AccountModel {
    public string Code {get;set}
    public string Description {get;set;}
}
// then use it just like the following:
//
// instead of this
// List<string> result = new List<string>();
// do this:
// option #1
// var results = new List<AccountModel>();
// option #2
var results = new List<object>();

while (dr.Read())
{
    var code = dr["AcCode"].ToString();
    var desc = dr["Descrip"].ToString();
    results.Add(new { code , desc });
}

Then after your last using clause return the results object as a json:
public ActionResult AutocompleteSuggestions() {
    return Json(results,JsonRequestBehavior.AllowGet);
}

And then instead of doing:
$.ajax({
    url: "/checkout/AutocompleteSuggestions", type: "POST", dataType: "json",
    data: { term: request.term },
    success: function (data) {
        response($.map(data, function (item) {
            return { label: item.split('-')[0], value: item.split('-')[1] }
        }))
    }
})

you can refer to each field:
$.ajax({
    url: "/checkout/AutocompleteSuggestions", type: "POST", dataType: "json",
    data: { term: request.term },
    success: function (data) {
        response($.map(data, function (item) {
            return { label: item.code, value: item.desc }
        }))
    }
})

redpajama_set_name: RedPajamaStackExchange


text:
Q: IBM Worklight - How to push "Disable state event" to the app from the server? When I deploy and use application from Worklight server (Hosted on Apache Tomcat) everything works fine.
Now, When I make the Application State Disabled from Server. I want the client to be notified the same moment. Currently I am getting notified when my client application takes some action. How do I accomplish direct push from server when state is changed from Enable to Disable?
Any Reference guide for That?

A: This ability, or feature, does not exist in Worklight.
IMO it is not needed. Read the below.
Note the actual meaning of Remote Disable: "Remote Disable" is not about disabling the app itself, but rather about preventing the app from connecting to the Worklight Server (fetch data, ...).
That is the default behavior. Once an app is "disabled", the app itself is functional, but any request to the server will be blocked. So there is nothing to "push" to the app...
User documentation:

*

*Remotely disabling application connectivity
If what you want is to disable the app itself, you will need to override the default  behavior. You can accomplish this by updating the app with custom behavior. This way, the next time the app tries to connect to the Worklight Server once it has been disabled, it will be blocked completely - this will depend on how and what you will implement. For example, display another HTML all together.
Blog post:

*

*How to create a customized remote disable behavior


text:
Q: MatLab - Return value of the zero() function I'm trying to implement a very simple transfer function to see its zeroes and poles. For example:
s=tf('s');
H= (s+5)/(s^2+3*s+2);
zeroes_H=zero(H);
poles_H=pole(H);

I can't seem to get the return values from the zero() and from the pole() functions. When I check my previous notes my code seems to work fine. What is a possible reason for the problem? Could it be related to a version difference? ( I was using 2019. Now I switched back to 2014.) If it is, what would be a more suitable way for the implementation?

A: the input of zero must be a system (in fact, a SISO, single-input-single-output system). So go with
% create transfer function
sys = tf([1,5],[1,3,2]);

zeroes_H = zero(sys);
poles_H = pole(sys);


text:
Q: Вопрос о безопасности - подделка POST-запросов, накрутка голосваний Есть система, которая дает возможность проголосовать - вы нажимаете на кнопку "Поддержать", отправляется запрос на сервер, увеличивается счетчик нажатий. Вопрос заключается в следующем - запрос можно подделать... подскажите как в таких ситуация обычно делают? Я имею в виду в глобальном смысле, то есть не именно для этой системы, а как обеспечить безопасность запросов вообще? Какую хитрость нужно использовать? Что нужно отправлять? Какие токены? Чтобы проверять все это на сервере, не подмена ли это. Спасибо.

A: В общем случае - никак. Запрос от настоящего пользователя ничем не отличается от запроса бота. Поэтому все онлайн голосования поддаются накрутке. Можно отбрасывать множественные голоса с одного клиентского IP, но это не слишком поможет если голосование действительно захотят накрутить.

A: Существует много способов от этого защититься (и ещё больше - чтобы обойти :)).
Можно заюзать токен - некая последовательность букаф, которые выдаются только на один запрос. Правда в случае подделки запроса не сильно поможет (но от CSRF вполне годен (тоже обходят)).
Для защиты от голосования можно сделать так (сам никогда голосовалки не делал... что странно, кстати):
В таблице голосования делаешь поле с... ID голосовавших, например. При попытке голосовать (пусть с токеном и вообще - это сам юзер хочет обхитрить систему), вытаскивать это поле, проверять наличие там ID текущего юзера и, если он найден, посылать от ворот поворот.

A: Ответ "в глобальном смысле" уже дали - НИКАК.
Судя по странным ответам, эту простую истину понимают не все. А точнее понимают, но как-то не до конца. В итоге получаются бессмысленные ответы вида "Токены не помогают, но вот как их реализовать...".
Если же говорить о защите голосования, то здесь есть только две стратегии:

*

*Либо вообще никак специально не защищаться, просто ставить куку для
удобства уже проголосовавших, а потом по логам отсекать накрутчиков.

*Либо вводить уже тяжелую артиллерию типа капчи смс-голосования.

Середины - это важно понимать - не существует.
Все эти игру в бирюльки с токенами и IP совсем не затруднят ботоводов, но только затруднят их отлов.

A: Никак, хотя бы потому, что все методы взламываются очень легко:
1. Фильтр по IP: Заведите бота через TOP - новый запрос, новый IP;
2. Фильтр по токену: Бот просто будет делать два запроса;
3. Капча: Зависит от сложности, простая подбирается на ура, сложная плоха для юзабилити.

Так что вы можете только использовать все три метода в надежде, что накрутчик не обработает их все. Так же в качестве усложнения могу предложить вариант, очень похожий на токены.
При заходе на страницу генерируется сессия, в сессии генерируете уникальный ID (можно просто увеличивать на 1 от предыдущего). При запросе без сессии возвращать, что голос успешно отправлен, но на деле не отправлять его. При запросе с сессией проверять ID, было ли голосование с него, если было, то возвращать ошибку.
Но это лишь легкая маскировка работы с токенами.

A: Мне на ум приходит гугловская рекапча. По своим логам не раз видел, что она отрубает некоторых "вредных" посетителей.

A: Самый удобный как вебмастеру, так пользователю способ отличить человека от бота - сделать что-то наподобие скрытого поля в form-е для отправки запроса, заполняемого javascript-ом. Чтобы подделать такой запрос, понадобится полнофункциональный браузер.
К сожалению, боты, способные на эмуляцию джаваскрипта и продвинутое изображение из себя браузера тоже иногда встречаются. От них этот способ не спасет. Как вариант борьбы с такими товарищами можно усилить ограничения по отправке с одного IP-адреса и блокировать прокси, висящие в blacklist-е IP-адреса, соответствие часового пояса IP-адресу, соответствие его IP-адресу, сообщаемому плагинами, соответствие IP-адреса DNS-у... Но даже все это можно обойти. К сожалению, универсальной защиты нет.
Даже CAPTCHA вас полностью не спасет - даже самую сложную капчу сможет расшифровать китаец за четверть цента =)
Другое дело, что если ваш ресурс не особо популярен, то на него, скорее всего, не забредут даже набиватели голосов с ботами, эмулирующими браузер. Так что излишняя паранойя вам тоже ни к чему.

A: Если у вас есть лояльная аудитория, которая совершает какие-то действия на сайте, то можно учитывать голоса разных людей с разным весом.
Например, на IMDB голос только что зарегистрированного будет значить меньше, чем голос старого пользователя с похожей на человеческую активность в течении года. Это сложнее обойти, чем токены и IP.


text:
Q: Galois covering Let $X$ and $Y$ be topological spaces with a free G-action, where $G$ is group. Suppose $p:X\rightarrow Y$ is a Galois covering which is G-equivariant map.
Then will it be true that the induced map $\tilde{p}:X/G\rightarrow Y/G$ is also
a Galois covering?

A: Here is a counter-example. Let $X$ be a (arc-connected) space with a free action of the symmetric group $S_3$ (an example would be a sphere with 8 points removed, or a connected Lie group containing $S_3$ as a subgroup). $S_3$ contains as subgroups $C_3$ (the subgroup of cyclic permutations) and $C_2$ (identity and one transposition). Let $Y=X/C_3$, $G=C_2$. Then $X/G\to Y/G$ is $X/C_2\to X/S_3$ and that covering is not Galois as its monodromy group is $S_3$ (acting on its 3 leaves)


text:
Q: during dynamic linking/loading, how is the base address obtained i am writing my own dynamic linker/loader
my PRIMARY concern is getting the BASE ADDRESS correct and valid, as at the moment it is 0 (nil)
in which i have not worked on in 11 months and will probably need to re-learn most of my linker/loader aswell as ELF spec
which aims to provide the following capabilities:

*

*able to load and execute any libc compiled application including glibc, musl, uclibc, klibc, and others, and thus MUST be independent of such libs,

for example if it can compile with glibc but cannot be compiled with musl than it is broken and is thus dependent on glibc to compile, which if being compiled on a musl based distribution, is obviously not an option

*to be able to redirect shared object loading to $APP_LOCATION/../

provided $APP_LOCATION is for example, app/bin/app, it redirects /lib/blah to app/bin/../lib/blah and if the path does not exists fallsback to /lib/blah
this is something which CANNOT be achieved in the gnu dynamic linker, and cannnot be pre-loaded in ld.so.

*to be able to dlopen any valid symbol from any shared object, including local and nested symbols if known, aswell as C++ symbols (decoded/encoded via libiberty) , something which also cannot be done via hooking dlsym due to how dlsym itself works (eg it is only limited to global link symbols)

an example of this is:
(due to posting the files would result in exceeding 30,000 characters)
test_loader.c :
https://github.com/mgood7123/universal-dynamic-loader/blob/master/loader/test_loader.c
additional_flags="-w"
debug="-g3 -O0 $additional_flags"
share="$debug -fPIC -shared"

void* test = dlopen("./files/test_lib.so") : gcc $share test_lib.c test_lib2.c -o files/test_lib.so : https://github.com/mgood7123/universal-dynamic-loader/blob/master/loader/test_lib.c and https://github.com/mgood7123/universal-dynamic-loader/blob/master/loader/test_lib2.c
void* testCPlusPlus = dlopen("./files/test++_lib.so") : g++ $share test++_lib.cpp test++_lib2.cpp -o files/test++_lib.so : https://github.com/mgood7123/universal-dynamic-loader/blob/master/loader/test%2B%2B_lib.cpp and https://github.com/mgood7123/universal-dynamic-loader/blob/master/loader/test%2B%2B_lib2.cpp
so far this works for almost all libraries (as in all libraries compiled as shared objects, not all libc variants such as musl or klib) except glibc which requires initialization of variables such as stdin/stdout/stderr and others, tho strlen, write(), work fine, have not tested strcmp and others, BUT printf and puts hang upon being executed
musl does not seem to have this problem and all of its functions seem to work find though i have not tested it extensively, strlen, write, puts, and printf work in musl with no problems
(idk which term it is called officially since the ELF spec seems to refer to it as dynamic loader, while gnu refers to it as dynamic linker)
and during dynamic linking, how is the base address obtained in order to initialize shared object files
granted i CANNOT post the full code of my linker as it is
257,903 characters, and the post limit is
30,000 characters
this base address is required for R_x86_64_RELATIVE relocations, which i believe contain the DT_INIT and DT_INIT_ARRAY functions/function arrays pointers among others
when i attempt to figure it out i get... well i get two things

*

*my relocation segfaults when attempting to assign to the computed base address + offset:
R_X86_64_RELATIVE            calculation: B + A (base address + r_addend)
library[library_index].base_address    =          (nil)
reloc->r_offset =          (nil)+0x000000200e78=0x000000200e78
reloc->r_addend =          (nil)+0x000000000590=0x000000000590
((char**)((char*)library[library_index].base_address + reloc->r_offset)) = 0x200e78
Segmentation fault

which brings up problem number 2

*the base address is incorrect
searching indexes for "./DT_INIT.so" incase it has already been loaded
current index 0 holds "./DT_INIT.so"
index 0 holds desired library "./DT_INIT.so"
map succeded with address: 0x7f132f66a000
calling round_up
returning = 0x7f1320000000
memmove: round_up(0x7f131dbe0010, 0x000010000000)+0x000000200000 = 0x7f1320200000
calling round_up
returning = 0x7f1320000000
dest = 0x7f1320200000
dest = 0x7f1320000000
library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_vaddr = 0x000000200e78
library[library_index]._elf_program_header[lowest_idx].p_paddr = 0x000000200e78
library[library_index]._elf_program_header[lowest_idx].p_vaddr = 0x000000200e78
calling round_down
returning = 0x000000200000
calling round_down
returning = 0x000000200000
calling round_nearest
returning = 0x000000201000
base address range = 0x7f1320000000 - 0x7f1320201028
mapping = 0x7f1320000000
base address =          (nil)

which is done via
dlopen(lib) > dlopen_(lib) > init_(lib) > {
                                            > init(lib) // mmaps the lib
                                            > map()
**base address is assigned in the function map(), which aswell
as assigning the base address, also maps the PT_LOADS**
}

int init(char * lib) {
    if (library[library_index].struct_init != "initialized") init_struct();
    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "current index %d holds \"%s\"\nsearching indexes for \"%s\" incase it has already been loaded\n", library_index, library[library_index].last_lib, lib);

    library_index = search(lib);
    library[library_index].last_lib = lib;
    library[library_index].current_lib = lib;
    if (library[library_index].array == NULL) {
        int fd = open(lib, O_RDONLY);
        if (fd < 0) {
            if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "cannot open \"%s\", returned %i\n", lib, fd);
            return -1;
        }
        library[library_index].len = 0;
        library[library_index].len = lseek(fd, 0, SEEK_END);
        lseek(fd, 0, 0);
        library[library_index].array = mmap (NULL, library[library_index].len, PROT_READ, MAP_PRIVATE, fd, 0);
        if (library[library_index].array == MAP_FAILED) {
            if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "map failed\n");
            exit;
        } else {
            if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "map succeded with address: %014p\n", library[library_index].array);
            return 0;
        }
    } else return 0;
    return -1;
}

int prot_from_phdr(const int p_flags)
{
    int prot = 0;
    if (p_flags & PF_R)
    {
        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "PROT_READ|");
        prot |= PROT_READ;
    }
    if (p_flags & PF_W)
    {
        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "PROT_WRITE|");
        prot |= PROT_WRITE;
    }
    if (p_flags & PF_X)
    {
        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "PROT_EXEC|");
        prot |= PROT_EXEC;
    }
    return prot;
}

uintptr_t round_nearest(uintptr_t value, uintptr_t size)
{
    printf("calling %s\n", __func__);
    uintptr_t result = 0;
    uintptr_t remainder = value % size;
    if (remainder < size/2) { result = value - remainder; } else { result = value + size - remainder; }
    printf("returning = %014p\n", result);
    return result;
}

uintptr_t round_down(uintptr_t value, uintptr_t size)
{
    printf("calling %s\n", __func__);
    uintptr_t result = 0;
    result = (value/size)*size;
    printf("returning = %014p\n", result);
    return result;
}

uintptr_t round_up(uintptr_t value, uintptr_t size)
{
    printf("calling %s\n", __func__);
    uintptr_t result = 0;
    result = value ? size * ((value + (size - 1)) / size) : size;
    printf("returning = %014p\n", result);
    return result;
}

// special version specifically for PT_LOAD handling
int read_fast_verifyb(const char *src, int len_of_source, char **dest, int requested_len, Elf64_Phdr PT_LOAD_F, Elf64_Phdr PT_LOAD_L) {
    void * align = 0x10000000;
    *dest = malloc(requested_len+align+PT_LOAD_L.p_align);
    if (len_of_source < requested_len) memcpy(*dest, src, len_of_source);
    else memcpy(*dest, src, requested_len);
    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "memmove: round_up(%014p, %014p)+%014p = %014p\n", *dest, align, PT_LOAD_L.p_align, round_up(*dest, align)+PT_LOAD_L.p_align);
    *dest = memmove(round_up(*dest, align)+PT_LOAD_L.p_align, *dest, requested_len);
    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "dest = %014p\n", *dest);
    *dest = memmove(*dest-PT_LOAD_L.p_align, *dest, PT_LOAD_F.p_memsz);
    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "dest = %014p\n", *dest);
    return requested_len;
}

void map() {
    if (library[library_index].is_mapped == 0) {
        library[library_index]._elf_header = (Elf64_Ehdr *) library[library_index].array;
        library[library_index]._elf_program_header = (Elf64_Phdr *)((unsigned long)library[library_index]._elf_header + library[library_index]._elf_header->e_phoff);

/*
the very first thing we do is obtain the base address

Base Address
The virtual addresses in the program headers might not represent the actual virtual addresses
of the program's memory image. Executable files typically contain absolute code. To let the
process execute correctly, the segments must reside at the virtual addresses used to build the
executable file. On the other hand, shared object segments typically contain
position-independent code. This lets a segment's virtual address change from one process to
another, without invalidating execution behavior. Though the system chooses virtual addresses
for individual processes, it maintains the segments' relative positions. Because
position-independent code uses relative addressing between segments, the difference between
virtual addresses in memory must match the difference between virtual addresses in the file.

The difference between the virtual address of any segment in memory and the corresponding
virtual address in the file is thus a single constant value for any one executable or shared object
in a given process. This difference is the base address. One use of the base address is to relocate
the memory image of the program during dynamic linking.

An executable or shared object file's base address is calculated during execution from three
values: the virtual memory load address, the maximum page size, and the lowest virtual address
of a program's loadable segment. To compute the base address, one determines the memory
address associated with the lowest p_vaddr value for a PT_LOAD segment. This address is
truncated to the nearest multiple of the maximum page size. The corresponding p_vaddr value
itself is also truncated to the nearest multiple of the maximum page size. The base address is
the difference between the truncated memory address and the truncated p_vaddr value.
*/

        // aquire the first and last PT_LOAD'S
        int PT_LOADS=0;
        for (int i = 0; i < library[library_index]._elf_header->e_phnum; ++i) {
            switch(library[library_index]._elf_program_header[i].p_type)
            {
                case PT_LOAD:
//                         if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "i = %d\n", i);
//                         if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "PT_LOADS = %d\n", PT_LOADS);
                    if (!PT_LOADS)  {
//                             if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "saving first load\n");
                        library[library_index].First_Load_Header_index = i;
                    }
                    if (PT_LOADS) {
//                             if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "saving last load\n");
                        library[library_index].Last_Load_Header_index = i;
                    }
                    PT_LOADS=PT_LOADS+1;
                    break;
            }
        }
        size_t span = library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_vaddr + library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_memsz - library[library_index]._elf_program_header[library[library_index].First_Load_Header_index].p_vaddr;

        read_fast_verifyb(library[library_index].array, library[library_index].len, &library[library_index].mapping_start, span, library[library_index]._elf_program_header[library[library_index].First_Load_Header_index], library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index]);

        fprintf(stderr, "library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_vaddr = %014p\n", library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_vaddr);

        // aquire the lowest PT_LOAD'S
        Elf64_Addr lowest_p_vaddr = 0;
        int lowest_idx = -1;
        for (int i = 0; i < library[library_index]._elf_header->e_phnum; ++i) {
            switch(library[library_index]._elf_program_header[i].p_type)
            {
                case PT_LOAD:
                    if (!lowest_p_vaddr) {
                        lowest_p_vaddr = library[library_index]._elf_program_header[i].p_vaddr;
                        lowest_idx = i;
                    }
                    if (lowest_p_vaddr < library[library_index]._elf_program_header[i].p_memsz) {
                        lowest_p_vaddr = library[library_index]._elf_program_header[i].p_vaddr;
                        lowest_idx = i;
                    }
                    break;
            }
        }
        size_t pagesize = 0x1000;
        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "library[library_index]._elf_program_header[lowest_idx].p_paddr = %014p\nlibrary[library_index]._elf_program_header[lowest_idx].p_vaddr = %014p\n",library[library_index]._elf_program_header[lowest_idx].p_paddr, library[library_index]._elf_program_header[lowest_idx].p_vaddr);
        Elf64_Addr truncated_physical_address = round_down(library[library_index]._elf_program_header[lowest_idx].p_paddr, pagesize);
        Elf64_Addr truncated_virtual_address = round_down(library[library_index]._elf_program_header[lowest_idx].p_vaddr, pagesize);
        library[library_index].base_address = truncated_physical_address - truncated_virtual_address;
//      library[library_index].base_address = library[library_index].mapping_start;

        library[library_index].align = round_nearest(library[library_index]._elf_program_header[library[library_index].Last_Load_Header_index].p_vaddr, pagesize);
//      library[library_index].base_address = library[library_index].mapping_start - library[library_index].align;
        library[library_index].mapping_end = library[library_index].mapping_start+span;

        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "base address range = %014p - %014p\nmapping = %014p\nbase address = %014p\n", library[library_index].mapping_start, library[library_index].mapping_end, library[library_index].mapping_start, library[library_index].base_address);

//      abort_();
        // base address aquired, map all PT_LOAD segments adjusting by base address then continue with the rest
        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\n\n\nfind %014p, %014p, (int) 1239\n\n\n\n", library[library_index].mapping_start, library[library_index].mapping_end);

        if (library[library_index].mapping_start == 0x00000000) abort_();
        int PT_LOADS_CURRENT = 0;
        for (int i = 0; i < library[library_index]._elf_header->e_phnum; ++i) {
            switch(library[library_index]._elf_program_header[i].p_type)
            {
                case PT_LOAD:
                    PT_LOADS_CURRENT = PT_LOADS_CURRENT + 1;
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "mapping PT_LOAD number %d\n", PT_LOADS_CURRENT);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_flags:  %014p\n", library[library_index]._elf_program_header[i].p_flags);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_offset: %014p\n", library[library_index]._elf_program_header[i].p_offset);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_vaddr:  %014p\n", library[library_index]._elf_program_header[i].p_vaddr);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_paddr:  %014p\n", library[library_index]._elf_program_header[i].p_paddr);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_filesz: %014p\n", library[library_index]._elf_program_header[i].p_filesz);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_memsz:  %014p\n", library[library_index]._elf_program_header[i].p_memsz);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\t\tp_align:  %014p\n\n", library[library_index]._elf_program_header[i].p_align);

                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "\tp_flags: %014p", library[library_index]._elf_program_header[i].p_flags);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_offset: %014p", library[library_index]._elf_program_header[i].p_offset);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_vaddr: %014p", library[library_index]._elf_program_header[i].p_vaddr);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_paddr: %014p", library[library_index]._elf_program_header[i].p_paddr);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_filesz: %014p", library[library_index]._elf_program_header[i].p_filesz);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_memsz: %014p", library[library_index]._elf_program_header[i].p_memsz);
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, " p_align: %014p\n\n\n", library[library_index]._elf_program_header[i].p_align);

                    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "mprotect(%014p+round_down(%014p, %014p), %014p, ", library[library_index].mapping_start, library[library_index]._elf_program_header[i].p_vaddr, library[library_index]._elf_program_header[i].p_align, library[library_index]._elf_program_header[i].p_memsz);
                    prot_from_phdr(library[library_index]._elf_program_header[i].p_flags);
                    if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, ");\n");
                    errno = 0;
                    int check_mprotect_success = mprotect(library[library_index].mapping_start+round_down(library[library_index]._elf_program_header[i].p_vaddr, library[library_index]._elf_program_header[i].p_align), round_up(library[library_index]._elf_program_header[i].p_memsz, library[library_index]._elf_program_header[i].p_align), library[library_index]._elf_program_header[i].p_flags);
                    if (errno == 0)
                    {
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "mprotect on %014p succeded with size: %014p\n", library[library_index].mapping_start+round_down(library[library_index]._elf_program_header[i].p_vaddr, library[library_index]._elf_program_header[i].p_align), round_up(library[library_index]._elf_program_header[i].p_memsz, library[library_index]._elf_program_header[i].p_align));
                        print_maps();
                    }
                    else
                    {
                        if (bytecmpq(global_quiet, "no") == 0) fprintf(stderr, "mprotect failed with: %s (errno: %d, check_mprotect_success = %d)\n", strerror(errno), errno, check_mprotect_success);
                        print_maps();
                        abort_();
                    }
                    break;
            }
        }
        library[library_index].is_mapped = 1;
    }
}

int
init_(const char * filename) {
    init(filename);
    if (library[library_index].init__ == 1) return 0;
    library[library_index]._elf_header = (Elf64_Ehdr *) library[library_index].array;
    read_section_header_table_(library[library_index].array, library[library_index]._elf_header, &library[library_index]._elf_symbol_table);
    obtain_rela_plt_size(library[library_index].array, library[library_index]._elf_header, library[library_index]._elf_symbol_table);
    if(!strncmp((char*)library[library_index]._elf_header->e_ident, "\177ELF", 4)) {
        map();
        ...
    }
    ...
}

void *
dlopen_(const char * cc)
{
    if (library[library_index].init_lock == 1) {
        if (bytecmpq(ldd_quiet, "no") == 0) fprintf(stderr, "dlopen: LOCKED\n");
        return "-1";
    };
    if ( if_valid(cc) == -1) {
        fprintf(stderr, "\"%s\" not found\n", cc);
        errno = 0;
        return "-1";
    }
    init_(cc);
    ...
}

void *
dlopen(const char * cc) {
    get_needed(cc);
    return dlopen_(cc);
}

in which this is the structure of the library[]
struct lib
{
    char * rootlib;
    char * rootusrlib;
    int init_lock;
    char * struct_init;
    char * library_name;
    char ** NEEDED;
    int NEEDED_COUNT;
    char library_first_character;
    char * library_len;
    char * library_symbol;
    Elf64_Ehdr * _elf_header;
    Elf64_Phdr * _elf_program_header;
    Elf64_Shdr * _elf_symbol_table;
    char *strtab;
    size_t len;
    char * array;
    char * current_lib;
    char * last_lib;
    int is_mapped;
    size_t align;
    Elf64_Addr mapping_start;
    Elf64_Addr base_address;
    Elf64_Addr mapping_end;
    int init__;
    int PT_DYNAMIC_;
    char * tmp99D;
    Elf64_Dyn * dynamic;
    int First_Load_Header_index;
    int Last_Load_Header_index;
    size_t RELA_PLT_SIZE;
    int _R_X86_64_NONE;
    int _R_X86_64_64;
    int _R_X86_64_PC32;
    int _R_X86_64_GOT32;
    int _R_X86_64_PLT32;
    int _R_X86_64_COPY;
    int _R_X86_64_GLOB_DAT;
    int _R_X86_64_JUMP_SLOT;
    int _R_X86_64_RELATIVE;
    int _R_X86_64_GOTPCREL;
    int _R_X86_64_32;
    int _R_X86_64_32S;
    int _R_X86_64_16;
    int _R_X86_64_PC16;
    int _R_X86_64_8;
    int _R_X86_64_PC8;
    int _R_X86_64_DTPMOD64;
    int _R_X86_64_DTPOFF64;
    int _R_X86_64_TPOFF64;
    int _R_X86_64_TLSGD;
    int _R_X86_64_TLSLD;
    int _R_X86_64_DTPOFF32;
    int _R_X86_64_GOTTPOFF;
    int _R_X86_64_TPOFF32;
    int _R_X86_64_PC64;
    int _R_X86_64_GOTOFF64;
    int _R_X86_64_GOTPC32;
    int _R_X86_64_GOT64;
    int _R_X86_64_GOTPCREL64;
    int _R_X86_64_GOTPC64;
    int _Deprecated1;
    int _R_X86_64_PLTOFF64;
    int _R_X86_64_SIZE32;
    int _R_X86_64_SIZE64;
    int _R_X86_64_GOTPC32_TLSDESC;
    int _R_X86_64_TLSDESC_CALL;
    int _R_X86_64_TLSDESC;
    int _R_X86_64_IRELATIVE;
    int _R_X86_64_RELATIVE64;
    int _Deprecated2;
    int _Deprecated3;
    int _R_X86_64_GOTPLT64;
    int _R_X86_64_GOTPCRELX;
    int _R_X86_64_REX_GOTPCRELX;
    int _R_X86_64_NUM;
    int _R_X86_64_UNKNOWN;
    Elf64_Addr * GOT;
    Elf64_Addr * GOT2;
    Elf64_Addr * PLT;
} library[512];
extern struct lib library[512];

as i am not entirely sure what "truncated to the nearest multiple" means buts since p_paddr and p_vaddr are the same any calulation done on each will yeild 0 when "The base address is the difference between the truncated memory address and the truncated p_vaddr value."  unless i im interperating this incorrectly:
An executable or shared object file's base address is calculated during execution from three
values: the virtual memory load address, the maximum page size, and the lowest virtual address
of a program's loadable segment. To compute the base address, one determines the memory
address associated with the lowest p_vaddr value for a PT_LOAD segment. This address is
truncated to the nearest multiple of the maximum page size. The corresponding p_vaddr value
itself is also truncated to the nearest multiple of the maximum page size. The base address is
the difference between the truncated memory address and the truncated p_vaddr value.


text:
Q: greasemonkey throws SecurityError for a simple script I'm new to greasemonkey and trying to understand how greasemonkey is different from the embedded web console. A simple script which works perfectly on web console does not work on greasemonkey, and I have no idea why.
Environments

*

*Firefox 74.0 on Arch Linux

*Greasemonkey 4.9
Web Console
Here is the test script I use:
(function() {
    "use strict";

    const w = window.open('https://www.google.com/', 'w');

    console.log("Hello");

    w.onload = () => {
        console.log("World");
    };

})();

When I access https://www.google.com/webhp?gl=us&hl=en&gws_rd=cr&pws=0 (Google US top page), copy and paste the script into web console, and then execute it,

*

*A new window w loading https://www.google.com/ is opened.

*The string Hello is printed.

*The string World is printed.
Everything is as expected.
Greasemonkey
On greasemonkey, I use the script below. The header part is the only difference.
// ==UserScript==
// @name     test
// @namespace n
// @match https://www.google.com/webhp?gl=us&hl=en&gws_rd=cr&pws=0
// ==/UserScript==

(function() {
    "use strict";

    const w = window.open('https://www.google.com/', 'w');

    console.log("Hello");

    w.onload = () => {
        console.log("World");
    };

})();

When I access https://www.google.com/webhp?gl=us&hl=en&gws_rd=cr&pws=0 (Google US top page),

*

*A new window w loading https://www.google.com/ is opened.

*The string Hello is printed.

*SecurityError is thrown saying

Script error in [Greasemonkey script n/test]:
  SecurityError: Permission denied to access property "onload" on cross-origin object test:42:19
      user-script:n/test:42

When I use unsafeWindow instead of window,

*

*A new window w loading https://www.google.com/ is opened.

*The string Hello is printed.

*And nothing else happens. (No error, no World)
Question
How should I modify the script so that is can be executed on greasemonkey?

Update
According to this comment, the script works on Tampermonkey or Violentmonkey under Chrome.
I haven't confirmed this but have confirmed that the script works on Tampermonkey 4.10.6105 or Violentmonkey 2.12.7 under Firefox.

A: Web Console is part of browser scope while a GreaseMonkey script is injected into a page content and its scope it limited to that page only.
You can open a new tab/window from page content with GM but that window/tab will have its own page content scope which is separate from the first one. Therefore, you can not access properties belonging to another tab/window from a page content of different tab.
This separation is for all content scripts and not only for GM. Otherwise, it would have created a great security risk if JS in one tab/page could access data on other tabs.
Update:
As pointed out by wOxxOm, the CSP and cross-origin policy prevents Cross-Origin Resource Sharing (CORS).
In your example, in Firefox, the first issue is that Firefox will "Block pop-up windows" from the content script.
Testing Firefox dedicated userScripts API on FireMonkey, after allowing popup, still causes an error:

SecurityError: Permission denied to access property "onload" on
  cross-origin object

In this case, I believe it is due to the sandboxing of userScripts for security.
GM/TM/VM do not use the userScripts API and use other means to inject userSripts which results in different outcome.


text:
Q: Understanding the difference between FHIR String_ vs String I'm trying to understand the different between the uses of setText()/setLabel Vs. setTextSimple / setLabelSimple in the FHIR Reference implementation.
What use cases would require the use of the String_ primitive type instead of the plain old setLabelSimple() approach? I've tried looking at several examples of use, and I cant really see why i'd favor one over the other. As far as I can see, both perform exactly the same, and the String_ object's value gets assigned to a plain old Java String object anyway...
Is there a preferred mode of use that anyone would recommend ? and if so, why ?

A: The FHIR string type has extensions and an xml id:
 <text value="[text value]" id="[id]">
   <extension url="[url]">
     <value[x] ... />
   </extension>
 </text>

The String_ getText() returns a type that has a getValue(), and a getXmlId(), and a getExtension() which returns a list of the extensions.
The java.lang.String getTextSimple() ignores the id and the extension, and returns the @value - it's a convenience short cut.
When would you use getText() instead of getTextSimple()? - when you want to deal with extensions or internal cross references. Otherwise, just use ...Simple().
(In fact, it's on my list of todos to flip them over, and have java.lang.String getText(), and String_ getTextObject() or something, as the .Net reference implementation does)


text:
Q: How to addition on bit with loop? For example, I have a number 104 and I want to change to a bit then add one bit every time.
String str = "h";
            String binary = new BigInteger(str.getBytes()).toString(2);
            int decimal = 0;
            int y =  Integer.valueOf(binary);
            System.out.println(y);
            System.out.println(y);
            y = y + 0x00000001;

            String z = String.valueOf(y);
            System.out.println("V  " + z);
            //byte[] bytes1 = z.getBytes("US-ASCII");
            decimal = Integer.parseInt(z, 2);
            System.out.println(decimal);

I get an error that "xception in thread "main" java.lang.NumberFormatException: For input string: "2" under radix 2"

A: Not sure what you mean by "add one bit".
Did you mean to add 1 to the binary number, i.e. simply increment the number like this?
char ch = 'h';
int num = ch;
print(num);
for (int i = 0; i < 10; i++) {
    num++;
    print(num);
}

static void print(int num) {
    System.out.println("Decimal: " + Integer.toString(num) +
                       "  Hex: " + Integer.toHexString(num) +
                       "  Binary: " + Integer.toBinaryString(num));
}

Output
Decimal: 104  Hex: 68  Binary: 1101000
Decimal: 105  Hex: 69  Binary: 1101001
Decimal: 106  Hex: 6a  Binary: 1101010
Decimal: 107  Hex: 6b  Binary: 1101011
Decimal: 108  Hex: 6c  Binary: 1101100
Decimal: 109  Hex: 6d  Binary: 1101101
Decimal: 110  Hex: 6e  Binary: 1101110
Decimal: 111  Hex: 6f  Binary: 1101111
Decimal: 112  Hex: 70  Binary: 1110000
Decimal: 113  Hex: 71  Binary: 1110001
Decimal: 114  Hex: 72  Binary: 1110010

Or did you perhaps mean to add a 1-bit at the end, like this?
char ch = 'h';
int num = ch;
print(num);
for (int i = 0; i < 10; i++) {
    num = (num << 1) | 1;
    print(num);
}

Output
Decimal: 104  Hex: 68  Binary: 1101000
Decimal: 209  Hex: d1  Binary: 11010001
Decimal: 419  Hex: 1a3  Binary: 110100011
Decimal: 839  Hex: 347  Binary: 1101000111
Decimal: 1679  Hex: 68f  Binary: 11010001111
Decimal: 3359  Hex: d1f  Binary: 110100011111
Decimal: 6719  Hex: 1a3f  Binary: 1101000111111
Decimal: 13439  Hex: 347f  Binary: 11010001111111
Decimal: 26879  Hex: 68ff  Binary: 110100011111111
Decimal: 53759  Hex: d1ff  Binary: 1101000111111111
Decimal: 107519  Hex: 1a3ff  Binary: 11010001111111111


text:
Q: Google Chart draws nothing using PHP array to send data I'm trying to take a array from PHP code returned from my CodeIgniter model/controllers and display at my page view. But, the chart is not generated, maybe because it's not getting the right data.
Here's my code:
<?php
$data = array(
    $generateChart['A'],
    $generateChart['B']
);
json_encode($data);
?>

If I send this:  I receive the data everything fine!
Created a new question more specific about my problem: Google Charts won't work if passing JSON data but works with fixed data

A: couple things...

*

*see the data format for PieChart
first column should be 'string'
second a 'number'
'date' column is invalid

*the array format from the comment won't work
you need an array for each row, which should have a value for each column
something like...
Array(
  [0] => Array(
           [0] => 10 - TATUÍ
           [1] => 12
         )
  [1] => Array(
           [0] => 1 - CONCÓRDIA
           [1] => 13
         )
  [2] => Array(
           [0] => 928 - PONTA GROSSA
           [1] => 14
         )
)


text:
Q: Cannot use GoogleSignInClient.silentSignIn() to retrieve an id token in an OkHttpClient Authenticator In my Android app written in Kotlin, I use Google Sign-In for authorization, and JWT tokens for authentication with my back end API. Both my JWT tokens and Google Sign-In's JWT token expire after 1 hour.
I want my app to re-authorise with Google Sign-In and re-authenticate with my API when a request to my back end API fails with a 401 error, so I added an authenticator to the OkHttpClient.
However, when I run the code below, the silentSignIn task locks up permanently and does not respond on the line val result = Tasks.await(task).
Am I missing something obvious? I can't find any reason as to why silentSignIn() would lock up in when called from the authenticator.
Elsewhere, I do not use Tasks.await(task), as there I use an OnCompleteListener to update the UI, update the apiToken and googleToken variables, however in the code below I wanted to update the apiToken and googleToken when the request failed, without requiring the other code in my project to re-fire the request to the back end API.
TLDR: I want to call GoogleSignIn.silentSignIn() in an OkHttpClient Authenticator, get the token, and retry the request immediately, but my app freezes on Tasks.await.
    val RC_SIGN_IN = 9001
    var apiToken: String? = null
    var googleToken: String? = null

    val client: OkHttpClient = OkHttpClient
        .Builder()
        .authenticator(object : Authenticator {
            override fun authenticate(route: Route?, response: Response): Request? {
                return if (response.code == 401) {
                    // Configure sign-in to request the user's ID, email address, and basic
                    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
                    val gso =
                        GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .requestEmail()
                            .requestIdToken("token_goes_here")
                            .build()

                    // Build a GoogleApiClient with access to the Google Sign-In API and the
                    // options specified by gso.
                    val googleSignInClient = GoogleSignIn.getClient(this@MainActivity, gso)
                    val task = googleSignInClient.silentSignIn().addOnCompleteListener {
                        val result = it.getResult(ApiException::class.java)
                        googleToken = result?.idToken
                    }.addOnFailureListener {
                        val signInIntent = googleSignInClient.signInIntent
                        startActivityForResult(signInIntent, RC_SIGN_IN)
                    }

                    if (task.isSuccessful) {
                        googleToken = task.result?.idToken
                    } else {
                        try {
                            /**** The following line is where the routine locks up: ****/
                            val result = Tasks.await(task)
                            googleToken = result?.idToken
                        } catch (ex: ExecutionException) {
                            // task failed
                            Log.e(TAG, "authenticate error:{ex}")
                        } catch (ex: InterruptedException) {
                            // an interrupt occurred while waiting for the task to finish
                            Log.e(TAG, "authenticate error:{ex}")
                        }
                    }
                    apiToken = getApiToken(googleToken)
                    response.request
                        .newBuilder()
                        .header("Authorization", "Bearer $apiToken")
                        .build()
                } else {
                    null
                }
            }
        }
        )
        .build()

A: After some digging I have found the answer. For the sake of anyone else in a similar boat, I will document the problem and solution below:
My suspicions grew when I was starting to have a similar bug with the Google Play Billing Library locking up in a similar manner. An investigation showed that I was calling my API get() code from a runBlocking { } context. Google used the same thread as OkHTTP was using, and so runBlocking caused all network I/O outside of OkHTTP to be blocked until OkHTTP was finished.
The solution was to remove runBlocking wherever possible, loading the data via launch {} asynchronously, and use notifyDataSetChanged() to update the RecyclerView when that is done. I haven't been able to remove runBlocking completely, but it is used so little now, and I have reworked the Task.await() block so that it times out, and calls the intent on timeout:
try {
    val result = Tasks.await(task, 5, TimeUnit.SECONDS)
    googleToken = result?.idToken
} catch (ex: ExecutionException) {
    // task failed
    Log.e(TAG, "authenticate error:{ex}")
    val signInIntent = googleSignInClient.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
} catch (ex: InterruptedException) {
    // an interrupt occurred while waiting for the task to finish
    Log.e(TAG, "authenticate error:{ex}")
    val signInIntent = googleSignInClient.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
} catch (ex: TimeoutException) {
    // an timeout occurred while waiting for the task to finish
    Log.e(TAG, "authenticate error:{ex}")
    val signInIntent = googleSignInClient.signInIntent
    startActivityForResult(signInIntent, RC_SIGN_IN)
}

A better solution would be to implement ViewModels (https://developer.android.com/topic/libraries/architecture/viewmodel), which I recommend for a new project, but because of a tight deadline, I have not been able to do that in this release.


text:
Q: Feeding a Sparse Data into Tensorflow Estimator's Fit I converted a label into sparse a sparse label tuple (indices, values, shape). However, when I feed it to the classifier, I encounter this error:
Traceback (most recent call last):
  File ..., line 23, in <module>
    classifier.fit(x=x_train, y=sparse_y_train, batch_size=128, steps=10)
  File "...tensorflow\python\util\deprecation.py", line 316, in new_func
    return func(*args, **kwargs)
  File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 464, in fit
    SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors)
  File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1429, in fit
    epochs=None)
  File "...tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 139, in _get_input_fn
    epochs=epochs)
  File "...tensorflow\contrib\learn\python\learn\learn_io\data_feeder.py", line 151, in setup_train_data_feeder
    x, y, n_classes, batch_size, shuffle=shuffle, epochs=epochs)
  File "...tensorflow\contrib\learn\python\learn\learn_io\data_feeder.py", line 326, in __init__
    if y_is_dict else check_array(y, y.dtype))
AttributeError: 'tuple' object has no attribute 'dtype'

How do I feed a sparse tuple into the classifier?

A: The error message is quite clear says 'tuple' has no attribute of 'dtype'. You probably want convert your label as a numpy array (with just values)?


text:
Q: Not Able to Set "divId.Visible = false" in Code Behind I have tried following code. But it shows:

The name 'commonMessage' does not exist in the current context

Index.cshtml

Controller:
commonMessage.Visible = false;

A: Mvc does not have the same "code behind" consept as asp.net webforms. You can not reach your frontend-code in that way.
You have to show us all the code in the controller so we can help you.

A: That code would work if you were using WebForms Asp.Net and not using MVC.
What you need to do is have a variable in the controller ,to set the style Display=none or Display=block, eg
var DivIsVisible = false;

Then in the cshtml you would write, something like:

Some links

Another way:
@if(Model.DivIsVisible)
{

Some link

}


text:
Q: Can't access Azure services through Curity I have recently started to use Curity and I am still learning, I have managed to create an authenticator that requires access to a secret in Azure.
        ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId("").tenantId("").clientSecret("").build();

        TokenCredential credential = new ClientSecretCredentialBuilder()
                .clientId("").tenantId("").clientSecret("").build();

When I then try to fetch the actual secret I get the following messages.
 io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: General OpenSslEngine problem
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:478) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[?:?]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[?:?]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[?:?]
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[?:?]
        at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[?:?]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[?:?]
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[?:?]
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[?:?]
        at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[?:?]
        at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe$1.run(AbstractEpollChannel.java:425) ~[?:?]
        at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) ~[?:?]
        at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) ~[?:?]
        at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:384) ~[?:?]
        at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[?:?]
        at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[?:?]
        at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[?:?]
        at java.lang.Thread.run(Thread.java:748) [?:1.8.0_282]
Caused by: javax.net.ssl.SSLHandshakeException: General OpenSslEngine problem
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.handshakeException(ReferenceCountedOpenSslEngine.java:1860) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.wrap(ReferenceCountedOpenSslEngine.java:815) ~[?:?]
        at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:514) ~[?:1.8.0_282]
        at io.netty.handler.ssl.SslHandler.wrap(SslHandler.java:1059) ~[?:?]
        at io.netty.handler.ssl.SslHandler.wrapNonAppData(SslHandler.java:944) ~[?:?]
        at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1421) ~[?:?]
        at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1265) ~[?:?]
        at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1302) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447) ~[?:?]
        ... 17 more
Caused by: java.lang.ClassCastException: io.netty.handler.ssl.OpenSslEngine cannot be cast to org.openjsse.javax.net.ssl.SSLEngine
        at org.openjsse.sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:273) ~[openjsse.jar:1.1.5]
        at org.openjsse.sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:147) ~[openjsse.jar:1.1.5]
        at io.netty.handler.ssl.ReferenceCountedOpenSslClientContext$ExtendedTrustManagerVerifyCallback.verify(ReferenceCountedOpenSslClientContext.java:234) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslContext$AbstractCertificateVerifier.verify(ReferenceCountedOpenSslContext.java:717) ~[?:?]
        at io.netty.internal.tcnative.SSL.readFromSSL(Native Method) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.readPlaintextData(ReferenceCountedOpenSslEngine.java:634) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1258) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1384) ~[?:?]
        at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1427) ~[?:?]
        at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:208) ~[?:?]
        at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1358) ~[?:?]
        at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1265) ~[?:?]
        at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1302) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508) ~[?:?]
        at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447) ~[?:?]
        ... 17 more
        Suppressed: javax.net.ssl.SSLHandshakeException: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
                at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.sslReadErrorResult(ReferenceCountedOpenSslEngine.java:1347) ~[?:?]
                at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1308) ~[?:?]
                at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1384) ~[?:?]
                at io.netty.handler.ssl.ReferenceCountedOpenSslEngine.unwrap(ReferenceCountedOpenSslEngine.java:1427) ~[?:?]
                at io.netty.handler.ssl.SslHandler$SslEngineType$1.unwrap(SslHandler.java:208) ~[?:?]
                at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1358) ~[?:?]
                at io.netty.handler.ssl.SslHandler.decodeNonJdkCompatible(SslHandler.java:1265) ~[?:?]
                at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1302) ~[?:?]
                at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:508) ~[?:?]
                at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:447) ~[?:?]
                at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[?:?]
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[?:?]
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[?:?]
                at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[?:?]
                at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[?:?]
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[?:?]
                at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[?:?]
                at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[?:?]
                at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[?:?]
                at io.netty.channel.epoll.AbstractEpollChannel$AbstractEpollUnsafe$1.run(AbstractEpollChannel.java:425) ~[?:?]
                at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) ~[?:?]
                at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) ~[?:?]
                at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:384) ~[?:?]
                at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[?:?]
                at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[?:?]
                at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[?:?]
                at java.lang.Thread.run(Thread.java:748) [?:1.8.0_282]

I have tried to add all Certificate authorities by Azure into Curity's server truststore without any success. Any ideas on how I can make any progress from here?
https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/certificate-authorities
https://www.microsoft.com/pkiops/Docs/Repository.htm
https://learn.microsoft.com/en-us/azure/security/fundamentals/tls-certificate-changes

A: This is caused by a bug in the JSSE provider. https://github.com/openjsse/openjsse/issues/22
The upcoming 6.3 version upgrades the JRE to a version that includes this fix.


text:
Q: DatePicker not working in JavaScript Spreasheet The DatePicker for Date Of Birth in this example is not working.
https://ej2.syncfusion.com/javascript/documentation/spreadsheet/template/

*

*I want to Bind the date picker with DataSource.

*Instead of showing date picker all the time, I want to show Date picker when user clicks on the cell.
How can I achieve these two?

A: Query #1: I want to Bind the date picker with DataSource.
Your requirement can be achieved by using our template property. For your convenience, we have prepared the sample that renders the Date picker for date value applied cells in created and beforeCellRender event.  You can find the sample link below.
Sample link: https://stackblitz.com/edit/zykkem?file=index.js
Reference Links:
Demo Link: https://ej2.syncfusion.com/javascript/demos/#/bootstrap5/spreadsheet/cell-template.html
Documentation Link: https://ej2.syncfusion.com/javascript/documentation/spreadsheet/template/
KB Link:  https://www.syncfusion.com/kb/12834/how-to-dynamically-add-cell-template-in-javascript-spreadsheet
Query #2: Instead of showing date picker all the time, I want to show Date picker when user clicks on the cell.
Once the data picker is rendered in the cell, it will add this input element to the DOM, and it will display all the time. If you need to show only when you click that cell, you need to destroy and re-render the template again and again, which is a tedious process and complex to implement.


text:
Q: Find Meeting Times returns AttendeesUnavailable with bigger timeslot I am using graph explorer to test my queries. I am invoking findMeetingTimes POST request.
Firstly, I am running it with these time constraints:
"timeConstraint": {
    "timeslots": [
      {
        "start": {
          "dateTime": "2017-05-23T09:00:00",
          "timeZone": "UTC"
        },
        "end": {
          "dateTime": "2017-05-23T12:00:00",
          "timeZone": "UTC"
        }
      }
    ]

This returns me correctly several meeting options.
However, if I change the start time from 9 o'clock to 8 o'clock (which should increase the number of options available) I get the AttendeesUnavailable as the emptySuggestionsReason instead of at least the same amount of meeting proposals like in the former request.
What could be a cause of this? Is it a bug?
The remaining parameters of the query were simple two attendees, one location, and a duration of one hour.
Many thanks!

A: Thanks for your message. There are a couple of reasons the API could've returned AttendeesUnavailable on the second request.  Attendee's could have created or accepted new events on their calendars, making them busy for the desired dates or maybe the list of attendees was different between requests?
If you have confirmed none of this is true, then I could look at the logs to see if there is a problem with the API.  For this though I would need you to go to the "Response Headers" tab in graph explorer and send me the value of the "request-id" header.


text:
Q: Returned json unexpected, has "links" spelled as "_links" and structure different, in Spring hateoas As the title says, I have a resource object Product extending ResourceSupport. However, the responses I receive have the property "_links" instead of "links" and have a different structure.
{
  "productId" : 1,
  "name" : "2",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/products/1"
    }
  }
}

Based on the HATEOAS Reference, the expected is:
{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}

Was this intended? Is there a way to change it, or at leas the "link" if not the structure?
I added the selfLink through the following snippet:
product.add(linkTo(ProductController.class).slash(product.getProductId()).withSelfRel());

I am using spring boot with the following build file:
dependencies {
    compile ("org.springframework.boot:spring-boot-starter-data-rest") {
        exclude module: "spring-boot-starter-tomcat"
    }

    compile "org.springframework.boot:spring-boot-starter-data-jpa"
    compile "org.springframework.boot:spring-boot-starter-jetty"
    compile "org.springframework.boot:spring-boot-starter-actuator"

    runtime "org.hsqldb:hsqldb:2.3.2"

    testCompile "junit:junit"
}

A: Another option would be to disable the whole hypermedia auto-configuration feature (this is how it's done in one of the spring-boot + REST examples here):
@EnableAutoConfiguration(exclude = HypermediaAutoConfiguration.class)

As far as I know, HypermediaAutoConfiguration doesn't really do much except for configuring HAL, so it should be perfectly fine to disable it.

A: Spring Boot now (version=1.3.3.RELEASE) has a property that controls the output JSON format of the PagedResources.
Just add the following config to your application.yml file:
spring.hateoas.use-hal-as-default-json-media-type: false

if you need the output to be like (based on question):
{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}

Edited:
By the way, you only need @EnableSpringDataWebSupport annotation in this way.

A: If you have HAL available it will be selected for you by spring boot (and "_links" is what you get with HAL). You should be able to @EnableHypermediaSupport manually to override the defaults.

A: I have notice the problem appears at least when you trying to return an object extends ResourseSupport vs object containing object extends ResourseSupport.
You may return even List or Array of object(s) extends ResourseSupport and have the same effect.
See the example :
@RequestMapping(method = GET, value = "/read")
public NfcCommand statusPayOrder() {
    return generateNfcCommand();
}

have response:
{
    "field": "123",
    "_links": {
        "self": {
            "href": "http://bla_bla_bla_url"
        }
    }
}

When try to wrap as List:
@RequestMapping(method = GET, value = "/read")
public List<NfcCommand> statusPayOrder() {
    return Arrays.asList(generateNfcCommand());
}

getting:
[
    {
        "field": 123
        "links": [
            {
                "rel": "self",
                "href": "http://bla_bla_bla_url"
            }
        ]
    }
]

Changing structure of an answer is not the right decision, but we can try to think further this way.

A: I've recently had the opposite issue, expected the HAL form (i.e. _links) but always got links, although using @EnableAutoConfiguration.
The solution to my issue might help here as well. Due to copying&pasting from an example I found, I had two mediatypes in my RestController's @RequestMappingannotation
@RequestMapping(path="/example", produces = {MediaType.APPLICATION_JSON_VALUE, "application/hal+json"})

With @EnableAutoConfiguration Spring HATEOAS registers an ObjectMapper for application/hal+json only and in my application there was another one responsible for MediaType.APPLICATION_JSON_VALUE which won the selection and rendered standard JSON.
So my solution to only set produces="application/hal+json" so that the Spring HATEOAS object mapper is choosen. In your case you should try to keep MediaType.APPLICATION_JSON_VALUE

A: I am sure you are using Spring data with @RepositoryRestResource annotation
@RepositoryRestResource
public interface XX extends CrudRepository<AA, String>

If you want to remove default HAL behavior you can add following annotaion param
@RepositoryRestResource(exported = false)
public interface XX extends CrudRepository<AA, String>

Above configurition Spring Data REST to only expose rest endpoints for resources in the parent project, without having to explicitly annotate every repository in the dependency project.
As per doc
Hiding certain repositories, query methods, or fields
You may not want a certain repository, a query method on a repository, or a field of your entity to be exported at all. Examples include hiding fields like password on a User object or similar sensitive data. To tell the exporter to not export these items, annotate them with @RestResource and set exported = false.
For example, to skip exporting a Repository:
@RepositoryRestResource(exported = false)
interface PersonRepository extends CrudRepository<Person, Long> {}

A: I was also getting the '_links' thing... I found that in my @RequestMapping I mistakenly had:
@RequestMapping("id") when I should have had:
@RequestMapping("{id}")
When I fixed that, the '_links' thing went away.


text:
Q: HTML5 canvas how to save full image not the part of the image I have image bigger than canvas size. How  to save full image not the part of image.
i try: getImageData(), toDataURL methods but it save's only part of image in visible canvas frame.
Full image:

The visible part of image:

The visible part of image in canvas:


text:
Q: Embedding the value from one cell within text in another cell Here's an image of what I want to accomplish.

The "function" is shown as pseudo-code in column E, and the desired result in column F.  I want to include the values from columns B and D within the text in column F.  How would I do that?

A: You actually don't need anything fancy.  You can concatenate text and values with an ampersand.  So, for example, F2 would be:
="This item for sale is "&B2&", item number "&D2


text:
Q: VueJS data doesnt change on URL change My problem is that when I go from one user page to another user page the info in component still remains from first user. So if I go from /user/username1 to /user/username2 info remains from username1. How can I fix this ? This is my code:
UserProfile.vue
mounted() {
    this.$store.dispatch('getUserProfile').then(data => {
        if(data.success = true) {
        this.username = data.user.username;
        this.positive = data.user.positiverep;
        this.negative = data.user.negativerep;
        this.createdAt = data.user.createdAt;
        this.lastLogin = data.user.lastLogin;
        data.invites.forEach(element => {
            this.invites.push(element);
        });
        }
    });
},

And this is from actions.js file to get user:
const getUserProfile = async ({
  commit
}) => {
  try {
    const response = await API.get('/user/' + router.currentRoute.params.username);
    if (response.status === 200 && response.data.user) {
      const data = {
        success: true,
        user: response.data.user,
        invites: response.data.invites
      }
      return data;
    } else {
      return console.log('Something went wrong.');
    }
  } catch (error) {
    console.log(error);
  }
};

Should I add watch maybe instead of mounted to keep track of username change in url ?

A: You can use watch with the immediate property, you can then remove the code in mounted as the watch handler will be called instead.
watch: {
    '$route.params.username': {
      handler: function() {
          this.$store.dispatch('getUserProfile').then(data => {
              if(data.success = true) {
                  this.username = data.user.username;
                  this.positive = data.user.positiverep;
                  this.negative = data.user.negativerep;
                  this.createdAt = data.user.createdAt;
                  this.lastLogin = data.user.lastLogin;
                  data.invites.forEach(element => {
                      this.invites.push(element);
                  });
             }
          });
      },
      deep: true,
      immediate: true,
    },
}

A: Your page is loaded before the data is retrieved it seems, you need put a "loading" property in the data and have a v-if="!loading" for your component then it will only render once the display is updated. Personally I would avoid watch if I can it is not great for performance of for fine grained handling.

A: Yes you should add wach on statement that contain user info.(you may have a problem to watch on object, so you can save user info in json, but im not sure). When user changing - call action, after recived response call mutation that should change a state, then watch this state.
And you might use better syntax to receive data from store. That is really bad idea call dispatch directly from your mouted hook, use vuex documentation to make your code better.


text:
Q: Can't resize the form by dragging its borders Form's AutoSize: False.
Form's AutoSizeMode:  Grow and Shrink.
Issue: I cant resize my form by dragging its borders, I can only do that by dragging that grip thing on the bottom right side of the form.
Is there any other property on the form that I sohlud change to fix this problem?
Here is also a screen shot of the hierarchy of controls on the form...maybe setting on lower level controls on the form is causing this?

A: I have the same problem if maximum size was set. Please set it to 0 or to bigger than now. After that you can move the border wherever you want. Change  FormBorderStyle or  SizeGripStyle can't help if maximum size is too small to new settings.

A: Because this is not in the answers, I'll write this here.
The problem seems to be caused by the form's AutoSizeMode being on GrowAndShrink, and not GrowOnly, which is the default setting. Resetting to GrowOnly fixed the issue.
(confirmed on MSVS2013 with .net 4.5 on Win7)

A: Tried everything in the above (and Microsoft's forums) couldn't get it to resize.  Finally just opened another instance with a form I hadn't dorked up and compared.  Here's what needed set.  All are mentioned above but not as a combination.
In the form's property window (or in the code).
Autosize:  False = allows resizing both dimensions (True = only width adjusted).
AutosizeMode:  GrowOnly = allows both growing and shrinking.
FormBorderStyle:  Sizeable.

A: I have the same problem, I can not manually change the size of form or controls in manual mode.  Tried all the above, checked prior forms in the project, I could resize them.
Then, closed VS 2010, reopened the project, and I can resize the form and controls ....
" Did you try the  power switch ...  ;)"

A: Make sure the FormBorderStyle is set to Sizable, and that the SizeGripStyle property is set to Auto or Hide.

A: int height = 960;
int width = 1280;
this.ClientSize = new System.Drawing.Size(width, height);

this way you can get a fixed form size...otherwise visual studio automatically changes it

A: I finally figured out what was causing this for me. This had been a problem for years! None of the things listed here helped, and indeed, all of them were already set as suggested.
It turned out that I couldn't make a window smaller in width if any control was anchored to the right edge, or smaller in height if any control was anchored to the bottom edge.


text:
Q: pass a HashMap by reference I have a multiple-multi-dimensional HashMap() instances, I am using them to store hierarchical data from a database;
HashMap<String, HashMap<String, ArrayList<String>>>

I add to them with 3 primary methods that we'll refer to as addTop(), addMid() and addLow(). The methods all accept parameters that match their data group and a string, each method returns the next dimension of the HashMap();
public static HashMap<String, ArrayList<String>> addTop(HashMap<String, HashMap<String, ArrayList<String>>> data, String val) { ... };
public static ArrayList<String> addMid(HashMap<String, ArrayList<String>> data, String val) { ... };
public static String addLow(ArrayList<String> data, String val) { ... };

I call these, usually, in sequence in between a few checks and perform additional checks inside the methods. Essentially all these methods do is add val to data then return an empty HashMap();
out = new HashMap();
data.put(val, out);
return out;

When I check at the end of the loop/data-population all of the data from addMid() & addLow() is missing. Why is this?
I thought Java worked by reference when dealing with complex objects, such as HashMap().
What can I do to ensure that addMid() and addLow() update the master HashMap()?
EDIT: Included code. It compiles and runs but there are other problems, I have stripped out as much as I can to demonstrate whats happening, except the SQL stuff, that won't compile, sorry. the method that is run at start is sqlToArray();
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

public class Av2 {
    protected class AvailLookup {
        private Integer key;
        private String value;
        public AvailLookup(Integer inKey, String inValue) {
            key = inKey;
            value = inValue;
        }
        public void updateName(String name) {
            value = name;
        }
        public Integer getKey() {
            return key;
        }
        public String getValue() {
            return value;
        }
        public String toString() {
            return value;
        }
    }
    private static HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> data = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
    private static Sql sql = new Sql("PlantAvail");
    public static HashMap<AvailLookup,  ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
        HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
        if (inArray != null ) {
            for (AvailLookup lookup : inArray.keySet()) {
                if (lookup.getKey() == channel) {
                    out = inArray.get(lookup);
                    System.out.println("Channel: " + channel + " found");
                    break;
                }
            }
            if (out == null) {
                System.out.println("Channel: " + channel + " not found");
            }
        }
        return out;
    }
    public static HashMap<AvailLookup,  ArrayList<AvailLookup>> getChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, String channel) {
        HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
        if (inArray != null ) {
            for (AvailLookup lookup : inArray.keySet()) {
                if (lookup.getValue() != null) {
                    if (lookup.getValue().equalsIgnoreCase(channel)) {
                        out = inArray.get(lookup);
                        System.out.println("Channel: " + channel + " found");
                        break;
                    }
                }
            }
            if (out == null) {
                System.out.println("Channel: " + channel + " not found");
            }
        }
        return out;
    }
    public static HashMap<AvailLookup, ArrayList<AvailLookup>> addChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer id, String name) {
        HashMap<AvailLookup, ArrayList<AvailLookup>> out = null;
        if (inArray != null ) {
            if (getChannel(inArray, id) == null) {
                out = new HashMap<AvailLookup, ArrayList<AvailLookup>>();
                inArray.put(new AvailLookup(id, name), new HashMap<AvailLookup, ArrayList<AvailLookup>>());
                System.out.println("Channel: added " + id);
            } else {
                System.out.println("Channel: " + id + " already exists");
            }
        } else {
            System.out.println("Channel: " + id + " already exists");
        }
        return out;
    }
    public static void removeChannel(HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> inArray, Integer channel) {
        boolean pass = false;
        HashMap<AvailLookup,  ArrayList<AvailLookup>> channelLookup = getChannel(inArray, channel);
        for (AvailLookup lookup : channelLookup.keySet()) {
            if (lookup.getKey() == channel) {
                inArray.remove(channel);
                System.out.println("Channel: " + channel + " removed");
                pass = true;
                break;
            }
        }
        if (!pass) {
            System.out.println("Channel: " + channel + " cannot be removed");
        }
    }
    public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
        ArrayList<AvailLookup> out = null;
        for(AvailLookup lookup : channel.keySet()) {
            if (lookup.getKey() == device) {
                out = channel.get(device);
                System.out.println("Device: " + device + " found");
                break;
            }
        }
        if (out == null) {
            System.out.println("Device: " + device + " not found");
        }
        return out;
    }
    public static ArrayList<AvailLookup> getDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, String device) {
        ArrayList<AvailLookup> out = null;
        for(AvailLookup lookup : channel.keySet()) {
            if (lookup.getValue() == device) {
                out = channel.get(device);
                System.out.println("Device: " + device + " found");
                break;
            }
        }
        if (out == null) {
            System.out.println("Device: " + device + " not found");
        }
        return out;
    }
    public static ArrayList<AvailLookup> addDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer id, String value) {
        ArrayList<AvailLookup> out = null;
        if (getDevice(channel, id) == null) {
            out = new ArrayList<AvailLookup>();
            channel.put(new AvailLookup(id, value), new ArrayList<AvailLookup>());
            System.out.println("Device: added " + id);
        } else {
            System.out.println("Device: " + id + " already exists");
        }
        return out;
    }
    public static void removeDevice(HashMap<AvailLookup, ArrayList<AvailLookup>> channel, Integer device) {
        boolean pass = false;
        ArrayList<AvailLookup> deviceLookup = getDevice(channel,device);
        for (AvailLookup lookup : deviceLookup) {
            if (lookup.getKey() == device) {
                channel.remove(device);
                System.out.println("Device: " + device + " removed");
                pass = true;
                break;
            }
        }
        if (!pass) {
            System.out.println("Device: " + device + " cannot be removed");
        }
    }
    public static AvailLookup getHost(ArrayList<AvailLookup> hosts, Integer host) {
        AvailLookup out = null;
        for (AvailLookup hostLookup : hosts) {
            if (hostLookup.getKey() == host) {
                out = hostLookup;
                System.out.println("Host: " + host + " found");
            }
        }
        if (hosts.contains(host)) {
        } else {
            System.out.println("Host: " + host + " not found");
        }
        return out;
    }
    public static AvailLookup getHost(ArrayList<AvailLookup> hosts, String host) {
        AvailLookup out = null;
        for (AvailLookup hostLookup : hosts) {
            if (hostLookup.getValue() == host) {
                out = hostLookup;
                System.out.println("Host: " + host + " found");
            }
        }
        if (hosts.contains(host)) {
        } else {
            System.out.println("Host: " + host + " not found");
        }
        return out;
    }
    public static AvailLookup addHost(ArrayList<AvailLookup> hosts, Integer id, String value) {
        AvailLookup out = null;
        for (AvailLookup hostLookup : hosts) {
            if (hostLookup.getKey() == id) {
                out = hosts.set(id, new AvailLookup(id, value));
                System.out.println("Host: " + id + " found");
                break;
            }
        }
        if (out == null) {
            System.out.println("Host: " + id + " not found");
        }
        return out;
    }
    public static void removeHost(ArrayList<AvailLookup> hosts, Integer host) {
        boolean pass = false;
        for (AvailLookup hostLookup : hosts) {
            if (hostLookup.getKey() == host) {
                hosts.remove(hostLookup);
                System.out.println("Host: " + host + " removed");
                pass = true;
            }
        }
        if (!pass) {
            System.out.println("Host: " + host + " cannot be removed");
        }
    }
    public static ArrayList<AvailLookup> otherHosts(ArrayList<AvailLookup> hosts, Integer key, String value) {
        ArrayList<AvailLookup> out = null;
        for (AvailLookup host : hosts) {
            if (host.getKey() != key) {
                if (out == null) {
                    out = new ArrayList<AvailLookup>();
                }
                out.add(new AvailLookup(key, value));
            }
        }
        if (out != null) {
            if (out.size() > 1) {
                System.out.println("Host: generated other hosts");
            }
        }
        return out;
    }
    public static AvailLookup nextHost(ArrayList<AvailLookup> otherHosts) {
        AvailLookup out = null;
        if (otherHosts != null) {
            out = otherHosts.get(0);
            System.out.println("Host: getting next host");
        } else {
            System.out.println("Host: no other host");
        }
        return out;
    }
    public static void sqlToArray() {
        HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>> tempData = new HashMap<AvailLookup, HashMap<AvailLookup, ArrayList<AvailLookup>>>();
        Integer iHost = null;
        Integer iDevice = null;
        Integer iChannel = null;
        String sHost = null;
        String sDevice = null;
        String sChannel = null;
        HashMap<AvailLookup, ArrayList<AvailLookup>> channel = null;
        ArrayList<AvailLookup> device = null;
        Sql obj = new Sql("plantavail");
        obj.query("select j_channel.id as channelid, j_channel.name as channelname, j_device.id as deviceid, j_device.name as devicename, j_io.id as hostid, j_io.host as hostname, alias"
                + " from j_io"
                + " left join j_channel on j_io.id = j_channel.iofk"
                + " left join j_device on j_channel.iofk = j_device.id");
        try {
            while(obj.getResult().next()) {
                sChannel = obj.getResult().getString("channelname");
                sDevice = obj.getResult().getString("devicename");
                sHost = obj.getResult().getString("hostname");
                iChannel = obj.getResult().getInt("channelid");
                iDevice = obj.getResult().getInt("deviceid");
                iHost = obj.getResult().getInt("hostid");
                channel = addChannel(tempData, iChannel, sChannel);
                if (channel != null) {
                    device = addDevice(channel, iDevice, sDevice);
                    if (device != null) {
                        addHost(device, iHost, sHost);
                    }
                }
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        data = tempData;
    }
}

A: Be careful with accidentally overriding your existing map values. If you use java 8 you can use:
map.computeIfAbsent("entry", s -> new ArrayList<>());

Before Java 8 you need to check if the value is null:
List<String> list = map.get("entry");

if(list == null){
   list = map.put("entry", new ArrayList<String>());
}

Also you need to make sure that you update your map correctly:
A little example:
Map<String, String> map = new HashMap<>();

String a = "a";
String b = "b";

map.put(a, b);

System.out.println(map.get(a));

b = "c";

System.out.println(map.get(a));
System.out.println(b);

The output is:
b
b
c

So you see if you update b the map does not get updated. Now the same thing with a map in a map:
final String a = "a";
final String b = "b";

Map<String, Map<String, String>> topMap = new HashMap<>();
Map<String, String> middleMap = topMap.getOrDefault(a, new HashMap<>());

middleMap.put(b, "c");

topMap.put("a", middleMap);

System.out.println(topMap.get(a).get(b));

middleMap.replace(b, "d");

System.out.println(topMap.get(a).get(b));

topMap.put("a", middleMap);

System.out.println(topMap.get(a).get(b));

The output is:
c
d
d

But why? Shouldn't it be 'c c d'? NO! Because a String in Java is immutable, but a Map is not. If you consider this you should be able to solve your problem.

A: You need to check if there is already a map for this key:
Map<...> result = data.get(val);
if(null == result) {
    result = new HashMap();
    data.put(val, result);
}
return out;

Without this, the second attempt to add values to the same key will overwrite the existing map instead of appending to it.


text:
Q: Using between correctly Well, anyone could help me with that? I have the following form :

    {{Form::label('nrEmpenho', 'Nº Empenho')}}

        Inicial
            {{Form::text('nrEmpenho', null, ['class' => 'form-control', 'min' => 1])}}
            Final
            {{Form::text('nrEmpenhooo', null, ['class' => 'form-control', 'min' => 1])}}

So I have this query doing the search of data in the database :
$query = DB::table('empenho as emp')
        ->join('despesa', 'emp.fichaOrcId', '=', 'despesa.id')
        ->join('pessoa', 'emp.fornecedorId', '=', 'pessoa.id')
        ->join('fonte', 'emp.fonteId', '=', 'fonte.id')
        ->select('emp.nrEmpenho as a', 'emp.date as b', 'emp.tipo as c', 'pessoa.nome as d', 'emp.valor as e',
                'emp.id as f', 'despesa.ficha as g', 'emp.ano as h', 'fonte.id as i')
        ->orderby('emp.nrEmpenho');

Then do an if to catch the data in the database :
if ($request->nrEmpenho) $query->where('emp.id', $request->nrEmpenho);

Thus works perfectly , only taking the field passed as the identifier "nrEmpenho" but I would like to make a range selection , taking the value between "nrEmpenho" and "nrEmpenhooo" as I do that with between? It would be something like this?/
if ($request->nrEmpenho and $request->nrEmpenhooo) $query->where('emp.id', $request->between, $request->nrEmpenho and $request->nrEmpenhooo);

PS: When I create 2 text fields , only one filter , even through different identifiers . can anybody help me? Any questions about the code I put everything it takes to become clearer .
PSs: My english is very bad, i'm using translater, forgive me, i need much this help.

A: use whereBetween() function:
$query->whereBetween('emp.id', [$request->nrEmpenho, $request->nrEmpenhooo]);

but if there will be performance problem with between then try to use this example:
$query
->where('emp.id', '>=', $request->nrEmpenho)
->where('emp.id', '<=', $request->nrEmpenhooo);

or maybe a set of ids?
so:
$query->whereIn('emp.id', [$request->nrEmpenho, $request->nrEmpenhooo]);


text:
Q: LENGTH Equivalent in Report Builder 3.0 I am building a report in Report Builder 3.0 and require spacing that is conditional on the length of a parameter. Because Report Builder 3.0 does not have the LENGTH function that it did in 1.0, is there a workaround? I want to avoid solutions that white-out text.

A: You can measure the lenght of a string using the LEN function
e.g.
= Len(Parameters!ReportParameter1.Value)

An alternative is to use the string length property
= Parameters!ReportParameter1.value.Length


text:
Q: SWIG: How to wrap boost::shared_ptr to std::vector? I have some C++ code that returns a boost::shared_ptr to a std::vector, however I am unable to get SWIG to wrap this correctly to make the object iterable in Python.  Without the boost::shared_ptr it works fine.  Does anyone know how to wrap a vector when it's inside a shared_ptr?
Here is an example demonstrating the problem:
%module example

%include <std_vector.i>
%include <boost_shared_ptr.i>

%shared_ptr(Inner)
%shared_ptr(InnerVector)

%inline %{
#include <boost/shared_ptr.hpp>
#include <vector>

struct Inner {
  int dummy;
};
typedef std::vector< boost::shared_ptr<Inner> > InnerVector;
typedef boost::shared_ptr<InnerVector> InnerVectorPtr;

InnerVectorPtr getVectorPtr()
{
  InnerVectorPtr v(new InnerVector());
  boost::shared_ptr<Inner> i(new Inner);
  i->dummy = 222;
  v->push_back(i);
  return v;
}

%}

%template(InnerVector) ::std::vector< boost::shared_ptr<Inner> >;

And an example Python script:
import example

v = example.getVectorPtr()
print 'Vector is:', v
for i in v:
     print 'Instance is:', i
     print 'Value is:', i.dummy

Which for me, says this:
Vector is: <Swig Object of type 'InnerVectorPtr *' at 0x1127270>
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    for i in v:
TypeError: 'SwigPyObject' object is not iterable

Any suggestions?

A: You might want to try Boost.Python and Py++.  If you already using Boost it provides a very nice wrapping (and pretty much automatic wrapping) of complex C++ constructs.  I have used it in several projects.
Also you should take a look at this question it looks related but not exactly your issue.

A: Did you solve your problem?
I was thinking that it might be a problem with name manging, since you use the same name InnerVector twice:
%template(InnerVector) ::std::vector< boost::shared_ptr<Inner> >;
typedef std::vector< boost::shared_ptr<Inner> > InnerVector;
The error TypeError: 'SwigPyObject' object is not iterable usually means that SWIG does not understand that the object is e.g. a vector and should be converted into a Python list.


text:
Q: Why is Cantor step function not a counter example to Sard's Theorem I recently learned about Sard's theorem: Let $f:[a,b]\to\mathbb{R}$ and denote $E_f=\{x\in(a,b)|f'(x)\mbox{ exists and }f'(x)=0\}$, then $m(f(E_f))=0$.
Now, Cantor's step function is almost everywhere differentiable and $f'(x)=0$ for every point of differentiability. The image of this set is $[0,1]$ from continuity and the fact that $f(\mathcal{C})=[0,1]$ and therefore the measure is not null.
I note that this is also the statement in Frank Jones Lebesgue Integration on Euclidean Space. (unless I am mistaken).
What am I missing?