text:
Q: Fast and elegant one-way mapping of known integer values I have to map a set of known integers to another set of known integers, 1-to-1 relationship, all predefined and so on. So, suppose I have something like this (c++, simplified, but you'll get the idea):
struct s { int a; int b; };

s theMap[] = { {2, 5}, {79, 12958 } };

Now given an input integer, say 79, I'd need to find the corresponding result from theMap (obviously 12958). Any nice and fast method of doing this, instead of your run-of-the-mill for loop? Other data structure suggestions are also welcome, but the map should be easy to write in the source by hand.
The values in both sets are in the range of 0 to 2^16, and there are only about 130 pairs. What I also am after is a very simple way of statically initializing the data.

A: Sort the array by the key and do the binary search.

A: If you need compile time mapping you could use the following template:
// template to specialize
template<int T> struct int2int {};

// macro for simplifying declaration of specializations
#define I2I_DEF(x, v) template<> struct int2int<x> { static const int value = v; };

// definitions
I2I_DEF(2, 5) I2I_DEF(79, 12958) I2I_DEF(55, 100) // etc.

// use
#include <iostream>
int main()
{
  std::cout << int2int<2>::value << " " << int2int<79>::value << std::endl;

  return 0;
}

A: If the number of your source integers i is relatively high (so that a direct search becomes inefficient) but still manageable, you can relatively easily build a perfect hash function hash(i) for your input integers (using Pearson hashing, for example) and then use the hashed value as the entry into the output table map
output = map[hash(i)];

Of course, if the range of the input values is relatively small, you can use the identity function in place of hash and just turn the whole thing into a straghforward remapping
output = map[i];

(although if that was the case you wouldn't probably even ask.)

A: std::map<int, int> theMap;
theMap[2] = 5;
std::map<int, int>::const_iterator iter = theMap.find(2);
if (iter != theMap.end())
   iter->second; // found it

Insert pairs of ints, retrieve value by key, logarithmic complexity. If you have a really large data set and need faster retrieval use std::tr1::unordered_map or boost::unordered_map (in case your standard library doesn't have TR1 implementation).

A: std::map or std::unordered_map is probably the cleanest you'll get. Unfortunately C++ has no built-in associative arrays.
std::map<int,int> mymap; // the same with unordered map

// one way of inserting
mymap.insert ( std::make_pair(2,5) );
mymap.insert ( std::make_pair(79,12958) );

// another
mymap[2] = 5;
mymap[79] = 12958;

To check
std::map<int,int>::const_iterator iter = mymap.find(2);
if ( iter != mymap.end() )
{
   // found
   int value = iter->second;
}

unordered_map has the advantage of O(1) amortized lookup time as opposed to O(log n) of map.

A: As a supplementary, if you need a binary search implementation, don't overlook the C++ Standard Library. The following does one on an array of your structure type using the equal_range algorithm (apologies for the somewhat hacky quality of the code)
#include <algorithm>
#include <iostream>
using namespace std;

struct S {
    int k, v;
};

bool operator <( const S & a, const S & b ) {
    return a.k < b.k;
};

// must be sorted in key order
S values[] = {{42,123},{666,27}};

int main() {

    S t;
    cin >> t.k;

    S * valend = &values[0] + sizeof(values) / sizeof(S);
    pair <S*,S*> pos = equal_range( &values[0], valend , t);

    if ( pos.first != pos.second ) {
        cout << pos.first->v << endl;
    }
    else {
        cout << "no" << endl;
    }
}

A: Use a map
#include <map>
#include <iostream>

int main() {
   std::map <int, int> m;
   m[79] = 12958;
   std::cout << m[79] << std::endl;
}

Using a map is the most general solution and  the most portable (the C++ standard does not yet support hash tables, but they are  a very common extension). It isn't necessariily the fastest though. Both the binary search and the hashmap solutions suggested by others may (but not will) out-perform it. This probably won't matter for most applications, however.

A: Why not a hashed map? It will give you more or less constant retrieval times for any key.

A: You had the right idea, it's a map. Use std::map.

A: Jump table. A switch will likely set this up if you are able to use that, otherwise you may need some assembly but that's probably the fastest way.

A: You can use boost::assign.
#include <iostream>
#include <boost/assign.hpp>

int main()
{
    typedef std::map< int, int > int2int_t;
    typedef int2int_t::const_iterator int2int_cit;

    const int2int_t theMap
        = boost::assign::map_list_of
            ( 2, 5 )
            ( 79, 12958 )
            ;

    int2int_cit it = theMap.find( 2 );
    if ( it != theMap.end() )
    {
        const int result = it->second;
        std::cout << result << std::endl;
    }
}

A: If you are 100% certain theMap won't grow to over 1,000 entries (profile!), it's probably faster to do a binary search.
If the the value of a has a reasonable bound (e.g. below 1,000), you can just make a simple array with a as the index for guaranteed O(1) complexity. If you're using gcc you can use this syntax (http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html#Designated-Inits):
int theMap[256] = { [2] = 5, [79] = 12958 };

(This is not supported by g++, unfortunately)
In any other cases, use std::unordered_map as shown in the other answers.

A: Your pseudocode is almost valid C++0x code — but C++0x requires less!
map<int, int> theMap = { {2, 5}, {79, 12958 } };
assert ( theMap[ 2 ] == 5 );

In "normal" C++, you have to initialize the map like this, still quite elegant:
pair< int, int > map_array[2] = { make_pair(2, 5), make_pair(79, 12958) };
map< int, int > theMap( &map_array[0], &map_array[2] ); // sorts the array
assert ( theMap[ 2 ] == 5 );

This is fast to write and fast to run!
Edit: Just don't make the map a global variable. (Although that is safe in C++0x.) If you do, it will only be initialized properly if the compiler chooses to initialize it after map_array, which is VERY not guaranteed. If you want to to be a global, initialize it with theMap.assign( &map_array[0], &map_array[2] );.

A: There is also a technique known as "xmacros" which is a nice way to do exactly what you are talking about as well.  However, it is easy to abuse the technique so I always recommend using it with care.  Check out: http://en.wikipedia.org/wiki/C_preprocessor#X-Macros
The basic gist is, you have a file where you list out your mappings say foo.txt which looks like this:
MAP(2,5)
MAP(79,12958)
...
Then you define a macro MAP(A,B) that takes those two arguments and does your initialization for you.  Then #include the file (foo.txt).  You can even do it in multiple passes if you like by redefining the macro between each #include of the file.  Then to add more mappings you simply add them to foo.txt and recompile.  It is very powerful and can be used for many different things.

A: If you don't want to use a map for whatever reason, (for example, you just want to use the array you set up at compile time), you can also use a functor in combination with <algorithm>:
#include <windows.h>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;

struct s { int a; int b; };

s theMap[] = { {2, 5}, {79, 12958 } };

struct match_key : public unary_function<s, bool>
{
    match_key(int key) : key_(key) {};
    bool operator()(const s& rhs) const
    {
        return rhs.a == key_;
    }
private:
    int key_;
};

int main()
{
    size_t mapSize = sizeof(theMap)/sizeof(theMap[0]);
    s* it = find_if(&theMap[0], &theMap[mapSize], match_key(79));
    cout << it->b;

    return 0;
}


text:
Q: Azure Function - Pandas dataframe to Excel, write to outputBlob stream Am trying to write a DataFrame to an outputBlob from an Azure Function. I'm having trouble figuring out which io stream to use.
My function looks like this:
    import io
    import xlrd
    import pandas as pd

    def main(myblob: func.InputStream, outputBlob: func.Out[func.InputStream]):
        logging.info(f"Python blob trigger function processed blob \n"
                     f"Name: {myblob.name}\n"
                     f"Blob Size: {myblob.length} bytes")

        input_file = xlrd.open_workbook(file_contents = myblob.read())
        df = pd.read_excel(input_file)
        if not df.empty:
            output = io.BytesIO()
            outputBlob.set(runway1.to_excel(output))

How do we save the DataFrame to a stream that is recognisable by the Azure Function to write the excel to a Storage Container?

A: If you want to save DataFrame as excel to Azure blob storage, please refer to the following example

*

*SDK

azure-functions==1.3.0
numpy==1.19.0
pandas==1.0.5
python-dateutil==2.8.1
pytz==2020.1
six==1.15.0
xlrd==1.2.0
XlsxWriter==1.2.9

*Code

import logging
import io
import xlrd
import pandas as pd
import xlsxwriter
import azure.functions as func

async def main(myblob: func.InputStream,outputblob: func.Out[func.InputStream]):

    logging.info(f"Python blob trigger function processed blob \n"
                 f"Name: {myblob.name}\n")
    input_file = xlrd.open_workbook(file_contents = myblob.read())
    df = pd.read_excel(input_file)
    if not df.empty:
            xlb=io.BytesIO()
            writer = pd.ExcelWriter(xlb, engine= 'xlsxwriter')
            df.to_excel(writer,index=False)
            writer.save()
            xlb.seek(0)
            outputblob.set(xlb)
            logging.info("OK")

redpajama_set_name: RedPajamaStackExchange


text:
Q: dismissViewController for navigationController Right now I have a cancel button and when i click the cancel button i don't want the name to be displayed on the tableview cell. So if I do [self.navigaitonController popViewControllerAnimated:YES] it works properly but adds the name to the tableviewcontroller which i don't want if i do [self.navigationController dimissViewControllerAnimated:NO completion:nil] the cancel button doesn't do anything. My problem is that, if I press the cancel button it still adds the name to the tableviewcell. What is the best workaround this?
- (void)cancelButtonPressed:(id)sender
{

    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
    //[self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

A: popViewController is to pop a view off of the UINavigationController's stack, whereas dismissViewController is only for modal views. So if you want to present your tableview without a navigation bar (which is what I'm assuming you're trying to do?), use the navigation controller to present it modally instead of pushing it onto the stack. This is do by using presentViewController instead of pushViewController. Then it should respond to dismissViewController.


text:
Q: WM_DESTROY message not being received by WndProc in x64 Windows Assembly Program I'm trying to recreate using MASM /w Visual Studio 2019 something similar to the following C++ code which works. Essentially at this stage just want the window to be movable and the close button to work.
#include <iostream>
#include <Windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM
    lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

int main()
{
    wchar_t windowclass[] = L"MyWinTest";

    HINSTANCE hInstance = GetModuleHandleW(NULL);
    MSG msg;
    WNDCLASSEXW wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hbrBackground = 0;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
    wc.hIconSm = NULL;
    wc.hInstance = hInstance;
    wc.lpfnWndProc = WndProc;
    wc.lpszClassName = windowclass;
    wc.lpszMenuName = nullptr;
    wc.style = CS_HREDRAW | CS_VREDRAW;

    RegisterClassExW(&wc);

    HWND hWnd = CreateWindowExW(
        0,
        windowclass,
        L"MyWindow",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        800,
        600,
        NULL,
        NULL,
        hInstance,
        NULL);

        ShowWindow(hWnd, SW_SHOW);
        UpdateWindow(hWnd);

        while (GetMessage(&msg, NULL, 0, 0))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

}

In my version of x64 assembly using MASM the Window is created and displayed, also WndProc is being hit, can see it get message WM_CREATE and WM_PAINT but the Window can't be moved and can't be closed. I did compile the C++ version as x64 and output assembly listing for comparison, but it looks very similar as far as I can tell to the assembly version.
WSTR MACRO lbl:req,qstr:VARARG
LOCAL arg,unq,qot,q
    lbl LABEL WORD
    FOR arg,<qstr>
        qot SubStr <arg>,1,1
        q = 0
        IFIDNI qot,<!'>;'
            q = 1
        ELSEIFIDNI qot,<!">;"
            q = 1
        ELSE
            DW arg
        ENDIF
        IF q EQ 1
            unq SubStr <arg>,2,@SizeStr(<arg>)-2
        %   FORC c,<unq>
                DW "&c"
            ENDM
        ENDIF
    ENDM
    DW 0
ENDM

L MACRO qstr:VARARG
LOCAL sym,seg
    seg EQU <.code>
    %IFIDNI <@CurSeg>,<_DATA>
        seg EQU <.data>
    ENDIF
    .CONST
        ALIGN 4
        WSTR sym,qstr
    seg
    EXITM <OFFSET sym>
ENDM

extrn   LoadCursorW: PROC
extrn   MessageBoxW: PROC
extrn   ExitProcess: PROC
extrn   GetModuleHandleW: PROC
extrn   RegisterClassExW: PROC
extrn   CreateWindowExW: PROC
extrn   GetLastError: PROC
extrn   DefWindowProcW: PROC
extrn   ShowWindow: PROC
extrn   Sleep: PROC
extrn   GetMessageW: PROC
extrn   TranslateMessage: PROC
extrn   DispatchMessageW: PROC
extrn   DestroyWindow: PROC
extrn   UpdateWindow: PROC
extrn   PostQuitMessage: PROC
extrn   BeginPaint: PROC
extrn   EndPaint: PROC
.data
wstr windowClassName,"AsmTestClass",0,0
wstr windowTitle,"AsmTest",0,0

HWND_DESKTOP        textequ <0h>
MB_OK           textequ <0h>

INFINITE            textequ <0ffffffffh>
WM_CREATE       textequ <0001h>
WM_DESTROY      textequ <0002h>
WM_SIZE         textequ <0005h>
WM_PAINT        textequ <000fh>
WM_CLOSE            textequ <0010h>
WM_QUIT         textequ <0012h>
SW_HIDE         textequ <0000h>
SW_SHOW         textequ <0005h>

CS_VREDRAW      textequ <0001h>
CS_HREDRAW      textequ <0002h>

WS_OVERLAPPED   textequ <00000000h>
WS_CAPTION      textequ <00c00000h>
WS_SYSMENU      textequ <00080000h>
WS_MINIMIZEBOX  textequ <00020000h>

CW_USEDEFAULT   textequ <80000000h>

IDI_APPLICATION textequ <00007f00h>

WINDOW_WIDTH        DWORD   800
WINDOW_HEIGHT   DWORD   600

WNDCLASSEX STRUCT DWORD
    cbSize          DWORD   ?
    style           DWORD   ?
    lpfnWndProc     QWORD   ?
    cbClsExtra      DWORD   ?
    cbWndExtra      DWORD   ?
    hInstance       QWORD   ?
    hIcon           QWORD   ?
    hCursor         QWORD   ?
    hbrBackground   QWORD   ?
    lpszMenuName    QWORD   ?
    lpszClassName   QWORD   ?
    hIconSm         QWORD   ?
WNDCLASSEX ENDS

MSG STRUCT
    hwnd                QWORD   ?
    message         DWORD   ?
    wParam          QWORD   ?
    lParam          QWORD   ?
    time                DWORD   ?
    x               DWORD   ?
    y               DWORD   ?
MSG ENDS

PAINTSTRUCT STRUCT 8
    hdc             QWORD   ?
    fErase          DWORD   ?
    left                DWORD   ?
    top             DWORD   ?
    right           DWORD   ?
    bottom          DWORD   ?
    fRestore            DWORD   ?
    fIncUpdate      DWORD   ?
    rgbReserved     BYTE        32 DUP (?)
PAINTSTRUCT ENDS

.code
main proc

LOCAL wc:WNDCLASSEX
LOCAL hWnd:QWORD
LOCAL hInstance:QWORD
LOCAL hCursor:QWORD
LOCAL ATOM:WORD
LOCAL message:MSG

    sub     rsp, 8

    ; hInstance = GetModuleHandle(NULL)
    mov     rcx, 0
    call        GetModuleHandleW
    mov     hInstance, rax

    ; hCursor = LoadCursor(NULL,IDI_APPLICATION)
    mov     edx, IDI_APPLICATION
    xor     ecx, ecx
    call        LoadCursorW
    mov     hCursor, rax

    ; Setup Window Class
    mov     wc.cbSize, SIZEOF WNDCLASSEX
    mov     wc.style, CS_VREDRAW or CS_HREDRAW
    lea     rax, OFFSET WndProc
    mov     wc.lpfnWndProc, rax
    mov     wc.cbClsExtra, 0
    mov     wc.cbWndExtra, 0
    lea     rax, hInstance
    mov     wc.hInstance, rax
    mov     wc.hbrBackground, 0
    mov     wc.lpszMenuName, 0
    lea     rax, hCursor
    mov     wc.hCursor, rax
    lea     rax, windowClassName
    mov     wc.lpszClassName, rax
    mov     wc.hIconSm, 0
    lea     rcx, wc
    call        RegisterClassExW
    mov     ATOM, ax

    ; CreateWindowExW
    mov     QWORD PTR [rsp+88], 0               ;   lpParam
    lea     rax, hInstance
    mov     QWORD PTR [rsp+80], rax             ;   hInstance
    mov     QWORD PTR [rsp+72], 0               ;   hMenu
    mov     QWORD PTR [rsp+64], 0               ;   hWndParent
    mov     edx, WINDOW_HEIGHT
    mov     DWORD PTR [rsp+56], edx             ;   nHeight
    mov     edx, WINDOW_WIDTH
    mov     DWORD PTR [rsp+48], edx             ;   nWidth
    mov     DWORD PTR [rsp+40], CW_USEDEFAULT   ;   Y
    mov     DWORD PTR [rsp+32], CW_USEDEFAULT   ;   X
    mov     r9d, WS_OVERLAPPED or WS_CAPTION or WS_SYSMENU or WS_MINIMIZEBOX        ; dwStyle
    lea     r8, windowTitle                     ;   lpWindowName
    lea     rdx, windowClassName                    ;   lpClassName
    xor     ecx,ecx                             ;   dwExStyle
    call        CreateWindowExW

    cmp     rax,  0
    je      WindowFailed
    jmp     WindowSuccess

WindowFailed:
    call        GetLastError
    ; to-do check error ?

WindowSuccess:
    mov     hWnd, rax

    mov     rcx, hWnd       ; hWnd
    mov     edx, SW_SHOW        ; nCmdShow
    call        ShowWindow

    mov     rcx, hWnd       ; hWnd
    call        UpdateWindow

MessageLoop:
    xor     r9d, r9d            ; wMsgFilterMax
    xor     r8d, r8d            ; wMsgFilterMin
    xor     edx, edx            ; hWnd
    lea     rcx, message        ; lpMsg
    call        GetMessageW

    test        eax, eax
    je      QuitMessageLoop

    lea     rcx, message            ; lpMsg
    call    TranslateMessage

    lea     rcx, message            ; lpMsg
    call        DispatchMessageW

    jmp     MessageLoop

QuitMessageLoop:
    mov     ecx, eax                            ; uExitCode
    call        ExitProcess

main endp

WndProc proc
    LOCAL hWnd:QWORD
    LOCAL uMsg:DWORD
    LOCAL wParam:QWORD
    LOCAL lParam:QWORD
    LOCAL result:QWORD
    LOCAL ps:PAINTSTRUCT
    LOCAL hdc:QWORD

    sub     rsp, 8
    mov     lParam, r9
    mov     wParam, r8
    mov     uMsg, edx
    mov     hWnd, rcx

    ; msg handler
    cmp     uMsg,WM_CREATE
    je      create
    cmp     uMsg,WM_PAINT
    je      paint
    cmp     uMsg,WM_DESTROY
    je      destroy

    ; default
    mov     r9, lParam
    mov     r8, wParam
    mov     edx, uMsg
    mov     rcx, hWnd
    call        DefWindowProcW
    mov     result,rax
    jmp     finish

create:
    mov     result, 0
    jmp     finish

paint:
    mov     rcx, hWnd
    lea     rdx, ps
    call        BeginPaint
    mov     hdc, rax

    ; to-do HDC paint stuff here

    mov     rcx, hWnd
    lea     rdx, ps
    call        EndPaint

    mov     result, 0
    jmp     finish

destroy:
    xor     ecx, ecx            ; nExitCode
    call        PostQuitMessage
    mov     result, 0
    jmp     finish

finish:
    mov     rax, result

    ret

WndProc endp
End

Note due to local statement masm is automatically adding to my main before the sub rsp,8: (-152 + -8 = -160 )
push    rbp
mov     rbp, rsp
add     rsp, 0FFFFFFFFFFFFFF68h

and adding to wndproc routine (-120 + -8  = -128)
    push    rbp
mov     rbp, rsp
add     rsp, 0FFFFFFFFFFFFFF88h

...

leave

A: error in code - in both procs -
sub rsp, 8
when from x64 calling convention

The caller is responsible for allocating space for the callee's parameters. The caller must always allocate sufficient space to store
four register parameters, even if the callee doesn't take that many
parameters.

so need - to store four register parameters - 4*8 and +8 for 16-byte align, so
sub rsp, 40

in concrete case calls to DispatchMessageW and TranslateMessage can corrupt (overwrite) message because it located in callee's parameters space. if test under debugger - i view that DispatchMessageW overwrite message in prolog and than already use wrong message


text:
Q: How does a 40 Gbit/s Ethernet interface process packets in silicon? A 40 Gbit/s Ethernet interface should have a 40 GHz signal on it. How does common silicon IC technology handle such an exotic beast?
My best guess is that internally various parallel busses are used, but I haven't found much on the internals of these things.

A: 40G Ethernet is really four physical 10G links running in parallel. Modern FPGAs have SERDES hardware that can run at well over 10 Gbps, and it's common to use four 32-bit buses running at 312.5 MHz inside the FPGA. That gives you a data rate of exactly 40.000 Gbps.

A: There are several ways how you can make a data link faster:

*

*make more transmissions per second

*send more bits per transmission

*run several links in parallel

40G Ethernet does all of this: according to Wikipedia, it uses 4 channels, running at 1.6GHz each and transmitting 6.25 bits per clock cycle, which results in 40Gbit/s of total bandwidth.
Here's a picture that shows you how it relates to other Ethernet technologies (it stops at 10G; 40G uses better cables and/or shorter distances to achieve 4 times the spectral bandwidth):

A: Check out the IEEE red-rag, the Journal of Solid State Circuits, in the library.
Almost every issue has 40GigaBit receiver discussions.


text:
Q: How can I pass module parameters for bonding driver when compiled into kernel 2.4? I have an old 2.4 kernel based linux device using NIC Bonding. Instead of having the NIC Bonding module build as a module and modprobe'ed into the system, its compiled directly into the kernel. I'd like to modify the module parameters to add mode=1 miimon=100 in order to get it to not use round-robbin packet sending, but all of the examples I'm finding seem to assume the module is not compiled into the kernel, or just don't seem to work for me.
So far I've tried modifying my /etc/modules.conf file to try adding
alias bond0 bonding
options bond0 mode=1 miimon=100
options bonding mode=1 miimon=100

Based on something else I found on line I've tried adding bond0.mode=1 and bonding.mode=1 to my kernel commandline in grub, but regardless, when I boot up and check 'cat /proc/net/bonding/bond0' I always see staring back at me this line:
Bonding Mode: load balancing (round-robin)

I've tried looking for a setting to change in sysctl or /proc but am coming up empty.

A: I found it - but it's bad news, unfortunately. Here's what Documentation/networking/bonding.txt file for 2.4.37.11 says:

It is recommended
to configure the driver as module sinceit is currently the only way to
pass parameters to the driverand configure more than one bonding device.

So no module = no changing of parameters in this case. Sorry.


text:
Q: eclipse plugin: is it possible to "listen" and interpret double-clicks on text editor? The big picture is that we need to implement a remote debugger as an eclipse plugin. The code that will be passed by during debugging will be shown in an text editor.
I am thinking how can we deal with the issue of placing breakpoints on a file. Is there any way that I can listen for a double-click event and then get the specific line on which the double click was issued?
Many thanks for reading and giving it a thought.

A: Have a look at the Eclipse Debug project - they have the complete infrastructure for a new debugger. Including interfaces to breakpoints, editors, etc..


text:
Q: How to use chm in Delphi 7? How call help from chm files in Delphi 7 program?
Application.HelpFile := 'd:\help.chm';
Application.HelpCommand(HELP_CONTEXT, 10);

result is

Why can't I get Help from this program?
The Help for this program was created in Windows Help format, which
  depends on a feature that isn't included in this version of Windows.
  However, you can download a program that will allow you to view Help
  created in the Windows Help format.
For more information, go to the Microsoft Help and Support website.

A: The problem is that Delphi 7, by default, assumes that help files use the old WinHelp format that was not shipped with Vista. Even though your help file has the .chm extension, Delphi tries to show it using WinHelp commands. And since WinHelp isn't there, you get the error message that you reported.
There are various ways to get the help system to show HTML help. For example, a common technique is to implement an OnHelp handler for the Application object and route the help to calls to the HtmlHelp API. I gave a very simple example of that in a recent answer.

A: To open CHM file I use the following code:
    ShellExecute(Handle, 'open', PChar(ExtractFilePath(Application.ExeName) + 'help.chm'), nil, nil, SW_SHOW);


text:
Q: Conventions for R, G, B and A arrangement in RGBA byte buffers Are there any conventions when representing an image as an RGBA byte buffer? There are multiple ways to do so, for example

*

*Grouped (4 pixel image, 16 byte array)

RGBA, RGBA, RGBA, RGBA

*

*Separated (4 pixel image, 16 byte array)

RRRR, GGGG, BBBB, AAAA


text:
Q: Inter-fragment communication applied to Nested Fragments? The Android developers site has a great article on how to use interfaces to communicate between:

*

*A Fragment and its hosting Activity

*Two Fragments hosted by the same Activity
I am struggling to apply this concept to nested fragments. In particular, getActivity() or Fragment#onAttach(Activity) tell you what Activity is hosting a Fragment.
What is the equivalent in case of nested fragments? How does a "child" Fragment know what "parent" Fragment it is included in? And without knowing this, how can a child Fragment pass events up to its parent Fragment?
An obvious way is to broadcast intents from the child Fragment and have the parent Fragment listen for the broadcast, but I'd rather use the interface-based approach.

A: It turns out there is a getParentFragment() method introduced to cater to nested fragments. It is available on android.app.Fragment from API 17, but can be used on older versions using android.support.v4.app.Fragment.
I can't believe I overlooked this API!
EDIT:
I came across this gist that makes this process of figuring out the parent component (whether Fragment or Activity) easy, elegant and safe!


text:
Q: Cell Value Accessing Of Telerik RadGrid in asp.net I want to loop through all the columns of Telerik RadGrid and store the value in the SQL DataBase . I have tried this approach but the value i am getting is '&nbsp' for every column .
Any Little help will be appreciated as i am new to asp.net
   for (int i = 0; i < this.RadGridDetails.Items.Count; i++)
                    {
                        new SqlCommand("insert into tbl1(col1,col2,col3,col4) " +
                         "values('" + this.RadGridDetails.Items[i].Cells[0].Text.Trim().ToString() + "','" + this.RadGridDetails.Items[i].Cells[1].Text + "',case when '" + this.RadGridDetails.Items[i].Cells[2].Text + "' = 'Block' then 0 else 1 end " +
                         ",'" + this.t1.SelectedValue.ToString() + "' ) ", con).ExecuteNonQuery();
                    }

A: TRY:
  foreach (GridDataItem item in RadGridDetails.MasterTableView.Items)
          {
                    new SqlCommand("insert into tbl1(col1,col2,col3,col4) " +
                     "values('" + item[ColumnUniqueName1].Text + "','" + item[ColumnUniqueName2].Text +  "',case when '" + item[ColumnUniqueName3].Text + "' = 'Block' then 0 else 1 end " +
                     ",'" + this.t1.SelectedValue.ToString() + "' ) ", con).ExecuteNonQuery();
          }

and of course declare in each column its UniqueName


text:
Q: Help with understanding of the solution to the following ODEs. I am not particularly well-versed with ODEs, and the issue that I have encountered is rather a basic one, which I am hoping someone could help me understand (the intuition at least, as I am solving these using numerical solvers on Python; however, I still need to understand this properly in order to code it). I have the following system of ODEs:
\begin{align}
\dot{\psi}_{ yt}&=\beta-K_1'\psi_{y t}\label{eq: ODE1}\\
\dot{\psi}_{0 t}&=\alpha-K_0.\psi_{y t}-\frac{1}{2}\psi_{y t}'H_0\psi_{y t}\label{eq: ODE2}
\end{align}
where $(\psi_{0t},\psi_{yt})\in\mathbb{R}\times\mathbb{R}^{n\times 1}$, $(\alpha,\beta)\in\mathbb{R}\times\mathbb{R}^{n\times 1}$, and $(K_0,K_1)\in\mathbb{R}^{n\times 1}\times\mathbb{R}^{n\times n}$ and $H_0\in\mathbb{R}^{n\times n}$, and where $t$ is the time subscript with terminal time $T$, and with the terminal boundaries $\psi_{y T}=0$ and $\psi_{0 T}=0$. Suppose, I first integrate the first line (i.e., $\dot{\psi}_{yt}$) and evaluate $\psi_{yt}$ at $t=0,\cdots,T$. Does solving the second line then entail just substituting the solutions of $\psi_{yt}$ evaluated for each $t$ and THEN integrating? (essentially integrating a constant?)

A: Your first equation is a constant non-homogeneous linear $n$-dimensional system, which you can solve exactly if you can find the eigenvalues and eigenvectors of $K_1'$. Consider the homogeneous system
$$
\dot{\psi}_{ yt}=-K_1'\psi_{y t}.\;\;\;(1)
$$
Let $\Psi$ be a fundamental matrix solution of (1), that is an $n$ by $n$ matrix solution of (1) whose columns are $n$ linear independent solutions to (1). We also add the condition $\Psi(0)=I_n$, the identity matrix. The fundamental matrix solution $\Psi$ can be constructed with the eigenvalues and eigenvectors of $k_1'$ or it can be written formally as
$$
\Psi=\exp\left(-K_1' t\right).\;\;(2)
$$
In the case where $K_1'$ is diagonalizable to a diagonal matrix $D=\mbox{diag}(d_{11},d_{22},d_{33},\dots,d_{nn})$:
$$
K_1'=S^{-1}DS,
$$
for an invertible matrix $S$, then the exponential in (2) is given by
$$
\exp\left(-K_1' t\right)=S^{-1} \exp(-Dt) S
$$
where  $\exp(Dt)$ is a diagonal matrix with diagonal entries $e^{d_{ii}t}$. Thus $\Psi$ can be computed by an eigenvalue/eigenvector computation.
Then the general solution to
$$
\dot{\psi}_{ yt}=\beta-K_1'\psi_{y t}\;\;\;
$$
is
$$
{\psi}_{ ytg}=\Psi\int_0^t\left(\Psi^{-1}\beta\right)dt+\Psi x_0,
$$
where $x_0$ is the initial condition of ${\psi}_{ yt}$ at $t=0$. In your case, $x_0=0$, so
$$
{\psi}_{ yt}=\Psi\int_0^t\left(\Psi^{-1}\beta\right)dt\;\;(3).
$$
Now, you have that second condition, ${\psi}_{ yT}$, which means
$$
\int_0^T\left(\Psi^{-1}\beta\right)dt=0.\;\;(4)
$$
This condition entirely depend on $K_1$. In other words, you cannot impose it. Given $T$ and $K_1$, the condition above is satisfied or not. There are no free constants to play with in the equation above. In fact, in the case where the matrix $K_1'$ is diagonalizable, the solution (3) can be written explicitly as
$$
{\psi}_{ yt}=S^{-1}D^{-1}\left(I_n-\exp\left(-Dt\right)\right)S\beta.
$$
Thus Condition (4) becomes
$$
\exp\left(DT\right)=I_n.\;\;(5)
$$
Condition (5) means in effect that the eigenvalues of $K_1'$ must all be purely imaginary and of the form
$$
\lambda_k=i \frac{n_k\pi}{T},\;\;k=1,2,3,\dots n,
$$
where $n_k$ are integers. In other words, their imaginary part must be an integer multiple of $\pi$ divided by $T$.
Then, like you say, solving the second line entails just substituting the solutions of $\psi_{yt}$ evaluated for each $t$ and then integrating. The function $\psi_{yt}$ is not a constant so it's not like integrating a constant but perhaps you meant that in the sense that the RHS does not depend on $\psi_{0t}$.


text:
Q: How to localize iOS settings bundle? I added English string to title, what about other languages? Also how to auto generate Root strings files for current titles?

A: fount out..
Apple/Xcode developers just didn't really implement anything in Xcode to automate this process
we have to manually create the next structure using Finder:
Settings.bundle:
    Root.plist
    en.lproj:
        Root.strings
    ru.lproj:
        Root.strings

en.lproj, ru.lproj folders
Root.strings - file
p.s. you won't see Root.strings in Xcode, you need to find it in Finder and edit it using TextEdit


text:
Q: split character columns and get names of field in string I need to split a column that contains information into several columns.
I'd use tstrsplit but the same kind of information is not in the same order among the rows and I need to extract the name of the new column within the variable. Important to know: there can be many pieces of information (fields to become new variables) and I don't know all of them, so I don't want a "field by field" solution.
Below is an example of what I have:
library(data.table)

myDT <- structure(list(chr = c("chr1", "chr2", "chr4"), pos = c(123L,
                  435L, 120L), info = c("type=3;end=4", "end=6", "end=5;pos=TRUE;type=2"
                  )), class = c("data.table", "data.frame"), row.names = c(NA,-3L))

#    chr pos                  info
#1: chr1 123          type=3;end=4
#2: chr2 435                 end=6
#3: chr4 120 end=5;pos=TRUE;type=2

And I'd like to get:
#    chr pos end  pos type
#1: chr1 123   4 <NA>    3
#2: chr2 435   6 <NA> <NA>
#3: chr4 120   5 TRUE    2

A most straightforward way to get that would be much appreciated! (Note: I'm not willing to go with a dplyr/tidyr way)

A: Using regex and the stringi packages:
setDT(myDT) # After creating data.table from structure()

library(stringi)

fields <- unique(unlist(stri_extract_all(regex = "[a-z]+(?==)", myDT$info)))
patterns <- sprintf("(?<=%s=)[^;]+", fields)
myDT[, (fields) := lapply(patterns, function(x) stri_extract(regex = x, info))]
myDT[, !"info"]

    chr  pos type end
1: chr1 <NA>    3   4
2: chr2 <NA> <NA>   6
3: chr4 TRUE    2   5

Edit: To get the correct type it seems (?) type.convert() can be used:
myDT[, (fields) := lapply(patterns, function(x) type.convert(stri_extract(regex = x, info), as.is = TRUE))]

A: I am guessing your data is coming from a VCF file, if so there is a dedicated tool for such problems - bcftools.
Let's create example VCF file for testing:
# subset some data from 1000genomes data
tabix -h ftp://ftp-trace.ncbi.nih.gov/1000genomes/ftp/release/20100804/ALL.2of4intersection.20100804.genotypes.vcf.gz 17:1471000-1472000 > myFile.vcf
# zip it and index:
bgzip -c myFile.vcf > myFile.vcf.gz
tabix -p vcf myFile.vcf.gz

Now we can use bcftools. Here as an example we are subsetting AF and DP from INFO column:
bcftools query -f '%CHROM %POS %INFO/AF %INFO/DP \n' myFile.vcf.gz
17  1471199  1916 0.088
17  1471538  2445 0.016
17  1471611  2733 0.239
17  1471623  2815 0.003
17  1471946  1608 0.007
17  1471959  1612 0.014
17  1471975  1610 0.179

See the manual for more query options.

A: For now, I managed to get what I want with the following code:
newDT <- reshape(splitstackshape::cSplit(myDT, "info", sep=";", "long")[,
                  c(.SD, tstrsplit(info, "="))],
                 idvar=c("chr", "pos"), direction="wide", timevar="V4", drop="info")
setnames(newDT, sub("V5\\.", "", names(newDT)))

newDT
#    chr pos type end  pos
#1: chr1 123    3   4 <NA>
#2: chr2 435 <NA>   6 <NA>
#3: chr4 120    2   5 TRUE

Two options to improve the lines above, thanks to @A5C1D2H2I1M1N2O1R2T1 (who gave them in comments) :
. with a double cSplit prior to dcast:
cSplit(cSplit(myDT, "info", ";", "long"), "info", "=")[, dcast(.SD, chr + pos ~ info_1, value.var = "info_2")]

. with cSplit/trstrplit and dcast instead of reshape:
cSplit(myDT, "info", ";", "long")[, c("t1", "t2") := tstrsplit(info, "=", fixed = TRUE)][, dcast(.SD, chr + pos ~ t1, value.var = "t2")]

A: We could split on ";" then reshape wide-to-long, then split again on "=", then reshape back to long-to-wide:
dcast(
  melt(dt[,  paste0("col", 1:3) := tstrsplit(info, split = ";") ],
       id.vars = c("chr", "pos", "info"))[, -c("info", "variable")][
         ,c("x1", "x2") := tstrsplit(value, split = "=")][
           ,value := NULL][ !is.na(x1), ],
  chr + pos ~ x1, value.var = "x2")

#     chr pos end  pos type
# 1: chr1 123   4 <NA>    3
# 2: chr2 435   6 <NA> <NA>
# 3: chr4 120   5 TRUE    2

An improved / more readible version:
dt[, paste0("col", 1:3) := tstrsplit(info, split = ";")
   ][, melt(.SD, id.vars = c("chr", "pos", "info"), na.rm = TRUE)
     ][, -c("info", "variable")
       ][, c("x1", "x2") := tstrsplit(value, split = "=")
         ][, dcast(.SD, chr + pos ~ x1, value.var = "x2")]

A: Here's how I'd do it :
library(data.table)

myDT <- structure(list(chr = c("chr1", "chr2", "chr4"), pos = c(123L,
                                                                435L, 120L), info = c("type=3;end=4", "end=6", "end=5;pos=TRUE;type=2"
                                                                )), class = c("data.table", "data.frame"), row.names = c(NA,-3L))

R_strings <- paste0("list(", chartr(";", ",", myDT$info),")")
lists <- lapply(parse(text=R_strings),eval)
myDT[,info:=NULL]
myDT <- cbind(myDT,rbindlist(lists, fill = TRUE))
myDT
#>     chr pos type end  pos
#> 1: chr1 123    3   4   NA
#> 2: chr2 435   NA   6   NA
#> 3: chr4 120    2   5 TRUE

Created on 2019-11-29 by the reprex package (v0.3.0)

A: You could use separate calls to sub for each desired extracted field, e.g. for type:
myDT$type <- sub("^.*\\btype=([^;]+)\\b.*$", "\\1", myDT$info)


text:
Q: Resolve symbolic link to local CSS file I am viewing some webpages I have generated on my local computer. I have a file called "style.css" in each directly which is symbolically linked to a global CSS file (Windows 10 - I use the MINGW command ln -svf to generate it). It is called by each html file like this:
<link rel="stylesheet" type="text/css" href="style.css">

Firefox browser recognizes this and applies this style but Chrome does not. Is there a setting in Chrome which enables this?


text:
Q: magento2 soap web service error I created script like this.and I have created token also from admin side.
ini_set('display_errors',1);
require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');
$token = "e3wcugwhdhqoxccwdli8yxepaih5lm3b";
$opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
$context = stream_context_create($opts);

$wsdlUrl = "http://192.168.11.175/magento2/soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1";
$serviceArgs = array("customerId" => 1);

$soapClient = new \Zend\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
$soapResponse = $soapClient->customerCustomerRepositoryV1GetById($serviceArgs);
var_dump($soapResponse);

and I'm getting following error when i run the script.
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://192.168.11.175/magento2/soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1' : failed to load external entity "http://192.168.11.175/magento2/soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1" in /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client/Common.php:37 Stack trace: #0 /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client/Common.php(37): SoapClient->SoapClient('http://192.168....', Array) #1 /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client.php(1023): Zend\Soap\Client\Common->__construct(Array, 'http://192.168....', Array) #2 /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client.php(1195): Zend\Soap\Client->_initSoapClientObject() #3 /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client.php(1106): Zend\Soap\Client->getSoapClient() #4 /var/www/html/magento2/soapcall.php(16): Zend\Soap\Client->__call('cus in /var/www/html/magento2/vendor/zendframework/zend-soap/src/Client/Common.php on line 37

A: @sivakumar :

*

*$token must be the 'Access Token' in System->Integration->YourApiUserDetail. NOT the 'Access Token Secret'.

*Check your Magento's base_url. Is it "http://192.168.11.175/magento2/"?

*If domain gives the error, then u can set it in your host file.


text:
Q: Unable to install Swirl Courses in RStudio I'm trying to install Swirl courses in RStudio on 64-bit Ubuntu 15.10, and I am running across an error. I tried to install a course using the command install_from_swirl("Data_Analysis"), but the system either just hangs (R needs to be interrupted to recover from this), or I get the following error:
Error in unzip(path, list = TRUE) :
  zip file '/home/xxxxx/R/x86_64-pc-linux-gnu-library/3.2/swirl/Courses
 /temp.zip' cannot be opened

The temp.zip doesn't appear to be a zip archive (I'm unable to open in on the command line).

A: You actually helped me with the command! I used
    install_course("Data Analysis")

but it didn't work, then I used
    install_from_swirl("Data_Analysis")

and it worked! Try running the swirl library first:
    library("swirl")
    install_from_swirl("Data_Analysis")    # CASE SENSITIVE!
    swirl()

I wish you luck!


text:
Q: Concurrent release versions on Repos + ClickOnce, what to anticipate? I publish COM addins for Office via ClickOnce.
At the moment, I have only one main branch on the Repos tree (using Azure DevOps), and each time I publish, all the users are automatically updated.
Now, what if I release a substantial update - which would involve a change in a work flow - and one of the teams wishes not to roll the update? (could be for many reasons such as "we are in the middle to sending something out and no time for learning curve right now", to "the new update does not provide a feature we loved")
I can implement this, but what if then I have to undertake a critical-compulsory fix?
I am thinking of allowing several major versions to be available in parallel, whilst within each of them a minor version update would be compulsory.
That is, going from 1.2 to 2.0 would be optional, but going from either 1.2 to 1.3 or 2.0 to 2.1 would be compulsory. This way, everyone is happy.
Well, I hope.. Because I never worked on distinct Repos branches. Also, not sure how ClickOnce might like this..
Any tips or warnings for potential challenges would be much appreciated.
Thanks!


text:
Q: Visual Studio said my variables are useless in a private method I have simple scenario where I started to repeat same code multiple times, so I decided to move it in a private method, depending on a if/else it's being edited and my variables that are listed below might overwrite it's value which is perfectly fine:
ProductResponse identificationResults = new ProductResponse(); // I understand this assignment gets overridden in private method below but that is goal
long? productIdentificationRecordId = null; // I understand this assignment gets overridden in private method below but that is goal

I'm invoking my method on a few places in a code that's reason why I created private method to avoid code repetition in same file:
await SetProductStatusAndPerformDbActions(productCompany, userId );

private async Task SetProductStatusAndPerformDbActions(Company productCompany, long userId, ProductType productType, ProductStatus status, long? productIdentificationRecordId, ProductResponse identificationResults, CancellationToken cancellationToken)
{
    status = GetCompanyProductStatus(productCompany.Id, identificationResults);

    productIdentificationRecordId = await PerformDbAction(status, productType, userId, cancellationToken); // underlined this code

    identificationResults = await IdentifyCompanyProduct(productCompany, cancellationToken); // underlined this code
}

Visual Studio says 'Remove this useless assignment to a local variable
productIdentificationRecordId'
Visual Studio says 'Remove this useless assignment to a local variable
identificationResults'

I understand this assignments gets overridden in private method below but that is point of private method because I want to use for example productIdentificationRecordId and its new value right after I call this private method because goal of private method is to modify it and that is it..
I'm not using vars which might cause this warning so I don't know what to do here.
How this could be written to avoid this scenarios ?
Edit:
Added screenshot from the private method, variables are grayed as they are not used:

A: Because these parameters are not being passed by reference, setting them to any value will only change the value of the parameter variables local to your helper method: it will not impact the values that were passed in to those parameters.
Since you don't use the new values you're assigning to those parameters inside the method, Visual Studio is smart enough to recognize that setting values to them has no effect. It's warning you about that, which is good because in this case you might think your code is doing something that it's not really doing.


text: Q: Do I need to upgrade android SDK from 11 to 12 to implement latest release requirement I have written an android App back in 2021. And I need to do a software updrade on my Apo. I used SDK 11 and SDKtarget = 30 in gradle. So app store requires SDKtarget = 31 for latest releases. So I need to know if I need to ugrade my SDK in build tools to 12 as well? I am using bluetooth scan and connect in app as well. So I need to impliment the runtime permission also in my code.


text:
Q: First Json Array is not parsing using Retrofit and Kotlin Coroutine in kotlin I get Village,City, Dist using ZipPostal code Api.Retrofit Network library and kotlin coroutines. I used https://api.postalpincode.in/pincode/{PINCODE}. Give Error is "com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $"
[{"Message":"Number of pincode(s) found:3","Status":"Success","PostOffice":
[{"Name":"Baroda House","Description":null,"BranchType":"Sub Post Office","DeliveryStatus":"Non-Delivery","Circle":"Delhi","District":"Central Delhi","Division":"New Delhi Central","Region":"Delhi","Block":"New Delhi","State":"Delhi","Country":"India","Pincode":"110001"},
{"Name":"Bengali Market","Description":null,"BranchType":"Sub Post Office","DeliveryStatus":"Non-Delivery","Circle":"Delhi","District":"Central Delhi","Division":"New Delhi Central","Region":"Delhi","Block":"New Delhi","State":"Delhi","Country":"India","Pincode":"110001"},
{"Name":"Supreme Court","Description":null,"BranchType":"Sub Post Office","DeliveryStatus":"Non-Delivery","Circle":"Delhi","District":"Central Delhi","Division":"New Delhi Central","Region":"Delhi","Block":"New Delhi","State":"Delhi","Country":"India","Pincode":"110001"}]}]

Above, Json Data have first fall Json Array after that Json Object so, its give above error.
Pincode.kt
data class Pincode(
    @SerializedName("Message")
    val Message : String,
    @SerializedName("Status")
    val Status : String,
    @SerializedName("PostOffice")
    val PostOffice : List<PostOffice>
)

PostOffice.kt
data class PostOffice(
    @SerializedName("Name")
    val Name : String,
    @SerializedName("BranchType")
    val BranchType : String,
    @SerializedName("DeliveryStatus")
    val DeliveryStatus : String,
    @SerializedName("Circle")
    val Circle : String,
    @SerializedName("District")
    val District : String,
    @SerializedName("Division")
    val Division : String,
    @SerializedName("Region")
    val Region : String,
    @SerializedName("Block")
    val Block : String,
    @SerializedName("State")
    val State : String,
    @SerializedName("Country")
    val Country : String,
    @SerializedName("Pincode")
    val Pincode : String,

)

ApiClient .kt
object ApiClient {

  val apiInterfce: ApiInterface = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(getClient())
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(ApiInterface::class.java)

}

fun getClient() : OkHttpClient {

    val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.MINUTES)
        .readTimeout(10, TimeUnit.MINUTES)
        .build()

    return client
}

ApiInterface.kt
interface ApiInterface {

    @GET("pincode/{PINCODE}")
    suspend fun pinCode(@Path("PINCODE") pinCode: String?): Response<Pincode>
}

MainActivity.kt
  private lateinit var binding : ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPinCodeVerificationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val etPinCode = binding.etPinCode.text.toString()

        GlobalScope.launch (Dispatchers.IO){
            val api  = ApiClient.apiInterfce.pinCode(etPinCode)
             if (api.isSuccessful && api.body() != null){
                val data = api.body()!!

                data.Status.let {
                    binding.etAddress.setText(it)
                }
                data.PostOffice.let {
                    binding.etVillage.setText(it?.component1()?.Name)
                    binding.etTaluka.setText(it?.component2()?.Block)
                    binding.etDist.setText(it?.component3()?.District)
                    binding.etState.setText(it?.component4()?.State)
                    binding.etCountry.setText(it?.component5()?.Country)
                }
            }

        }
    }

when application run after crash its give this error com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $.
how to its error fix and pincode verified this Api  and after show data village, city, Dist and state. Any other postlpincode api available suggeste me.

A: This is because of in your response you have Array and while you receive that response you access that response using object.
You have to do line below when you receive response.
interface ApiInterface {

    @GET("pincode/{PINCODE}")
    suspend fun pinCode(@Path("PINCODE") pinCode: String?): Response<List<Pincode>>
}


text:
Q: Java Set - how to sort based on a list of names I have a java Set and I can't change it to a TreeSet although i could copy it over.  Here is the issue:
I have names , tower, car, building , office , basement.   I have a POJO which has a string label variable containing one of these for each instance.
how can i sort these to be the EXACT order of  tower, car, building , office , basement.  There will be no duplicates allowed of course(its a set).
public class Places{

String label;
int moreinfo;
}

so imagine I have 10 Places objects with labels that could be any of  tower, car, building , office , basement: how can I sort these in a set to ensure that they are in the exact order of  "tower, car, building , office , basement" ?

A: You could turn field 'label' into enum in which enum values are ordered by your custom order.
public enum Label {
    TOWER, CAR, BUILDING, OFFICE, BASEMENT
}

Then, you can implement a comparable in order to sort the set.
class Places implements Comparable<Places>{

    Label label;
    int moreinfo;
    @Override
    public int compareTo(Places o) {
        return label.compareTo(o.label);
    }
}

You can then use Collections.sort method for your sorting.

A: You can use a Map to define an order for an arbitrary set of Strings:
private static Map<String, Integer> ordering;
static {
    ordering = new HashMap<>();
    ordering.add("tower", 1);
    ordering.add("car", 2");
    ...add your other strings with increasing values...
}

Collections.sort(yourCollection, new Comparator<Places>() {
    public int compare(Places p1, Places p2) {
        return ordering.get(p1.label) - ordering.get(p2.label);
    }
});

Be careful, however... you can't sort a Set. If it's a SortedSet (like a TreeSet) it will sort itself, if it's not it has no defined order.


text:
Q: Mockito: Is validation of framework usage enabled without @RunWith(MockitoJUnitRunner.class) We are using Testng 6.8.8 + Mockito 1.10.19 and, obviously we can't use MockitoJUnitRunner, but the validation framework still works!
In this thread I read that it should not be the case. Can someone explain? Is this because we still have @Before* callbacks and MockitoAnnotations.initMocks(this)?
My code:
public class MealTransformerTest {

MealTransformer mealTransformer = new MealTransformer();

@Test(expectedExceptions = NotImplementedException.class)
public void shouldThrowException() throws NotImplementedException {
    mealTransformer.transform(any(),
            any(),
            any(),
            any());
}

}
Nothing fails in this specific test, but when I run the suite, Mockito will tell me about incorrect use of matchers.
I can also do something like:
public class MealTransformerTest {

MealTransformer mealTransformer = new MealTransformer();

//I don't need it in the tests. But I need at least 1 @Mock or @Spy to trigger framework validation
@Mock
private CloneUtils cloneUtils;

@BeforeMethod
void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test(expectedExceptions = NotImplementedException.class)
public void shouldThrowException() throws NotImplementedException {
    mealTransformer.transform(any(),
            any(),
            any(),
            any());
}

@Test(expectedExceptions = NotImplementedException.class)
public void shouldThrowException123() throws NotImplementedException {
    mealTransformer.transform(any(),
            any(),
            any(),
            any());
}
}

I receive:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
....

Don't get me wrong, I really like how it works, but I was surprised to see it without @RunWith(MockitoJUnitRunner.class).

A: Matchers work via side-effects and static global state, so you can break this call into pieces to see what's happening.
MockitoAnnotations.initMocks(this);
// in @Before [1]

mealTransformer.transform(any(), any(), any(), any());
//              [6]       [2]    [3]    [4]    [5]

After init [1], Java sees four calls to any [2-5] and one call to transform [6]. Mockito, however, only sees the four calls to any; Because mealTransformer is not a mock, Mockito can't see its calls. If you ran that test in isolation, Mockito would be left with four recorded matchers that are not consumed. The JVM would tear down the test framework, and the test would pass—unless you have a call to validateMockitoUsage in an @After method, which would catch exactly that case.
When you have two tests, however, they stack up like this:
MockitoAnnotations.initMocks(this);
// [1]
mealTransformer.transform(any(), any(), any(), any());
//              [6]       [2]    [3]    [4]    [5]
// test passes! now the next test
MockitoAnnotations.initMocks(this);
// [7]
mealTransformer.transform(any(), any(), any(), any());
//              [12]      [8]    [9]    [10]   [11]

Here, step 7 happens in the same test execution in the same JVM as steps 1-6, which means that initMocks is called when there are 4 unconsumed matchers on the stack. This should never happen, so initMocks takes its first opportunity to catch that error. One symptom would be if the misused matcher exception corresponds to a matcher outside of the test that fails: testB failing due to the misuse of a matcher in testA. With the use of validateMockitoUsage in an @After message, you'd have the appropriate test fail instead.


text:
Q: Eclipse plugin to give guided tour? Guided tour libraries are quite common in web-based applications.
A small wizard pops up on first usage, and leads the new user through parts of the user interface.
Has anyone heard of a similar library for Eclipse/RCP?
(I've Google'd but can't find one)

A: I have never heard of such a library for Eclipse RCP but a viable alternative could be achieved by providing a custom welcome menu and dedicated cheat sheets (in an Eclipse-based product).
1. Providing a custom welcome dialog
When Eclipse IDE opens for the first time it shows a Welcome Dialog. You can enhance it or provide your own that could, for instance, present the different features available and provide quick access to your different wizards.
2. Providing dedicated cheat sheets
Cheat sheets can be used to provide step-by-step tutorials. A user can access them through the Help > Cheat Sheets... menu but you can also link them in the welcome dialog.


text: Q: Should wifi work after Server install? I just installed Ubuntu Server.  When installing, it asked for the SSID and password.  I provided both.  Following the install and reboot, I appear to not have network connectivity.  A wget to http://www.yahoo.com fails.  Is there something needed to get wifi networking running each boot, or should it have started - and I have a problem?


text:
Q: MySql PREPARE stmt FROM [function argument] and CURSORs I have a MySql function, which takes in 3 arguments. The last argument is a query itself, which I can execute with PREPARE(?), at least if it does not have multiple results. I want to loop through all results returned from the PREPARED statement.
How can I do that? I was thinking of a CURSOR, but all I can find is that it is impossible to use CURSORs on a PREPARED variable statement.
What I want to achieve is the following:
1. I have a view of results in my application. The results are paged.
2. I want to search for a particular row, find the page it belongs on, and put it into view.
3. The view of results can be filtered and ordered in several ways, so therefore the third argument of the MySql function is the query the view of results is filled with.
Hopefully I made myself clear, otherwise let me know.
So far I have the following:
    DELIMITER $$ # Otherwise you cannot use semicolons to end a line
/*
The bar graph (clsBarGraph) shows cows in pages.
If you wish to search for a page with a certain Cow ID you need to do alot of things.
Therefore this function is created, to do the heavy lifting all in the database engine.accessible
@param LongCowID The long cow ID of the cow you wish to get the page for
@param ItemsPerPage To determine on what page a cow comes, it is necessary to known how many cows will fit into a page
@param SelectQuery The query that was used to view the data in the BarGraph. This determines ordering, which cows to have in the resultset to limit on, etc.
        This should be without the limit
@return The page number to set the view to, or -1 if the cow does not exist.
*/
CREATE FUNCTION `GetPageForCowID`(LongCowID INT, ItemsPerPage INT, SelectQuery VARCHAR(255))
RETURNS INT
BEGIN
DECLARE `page` INT;

/* Prepares queries to execute */
PREPARE stmt_CheckIfCowExists FROM 'SELECT COUNT(`Long_Cow_ID`) as `rows` FROM `cow_data` INTO @NumberOfRows';
EXECUTE stmt_CheckIfCowExists;
IF @NumberOfRows = 1 THEN
    /* The cow does nto exist */
    SET `page` = -1;
ELSE
    /* The cow does exist */
    /* Get all the cows used in the view of the data, without a limit and put it into a variable */
    SET @SelectQuery = CONCAT(@SelectQuery, ' INTO @CowsForDataView');
    PREPARE stmt_SelectDataForView FROM @SelectQuery;
    EXECUTE stmt_SelectDataForView;
    SELECT COUNT(*) FROM stmt_SelectDataForView;

    DEALLOCATE PREPARE stmt_SelectDataForView;
END if;

/* Clean Up */
deallocate PREPARE stmt_CheckIfCowExists;
return `page`;
END

thanks in advance.

A: Put the results into a temporary table:
SET @sql := CONCAT('CREATE TEMPORARY TABLE tmp_GetPageForCowID ', SelectQuery);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Then one can iterate a cursor over the content of the temporary table.


text:
Q: How to set this Firebase rules? I am stuck on how to solve the security for my app here.
I have this structure:

Users shouldn't be able to write to points, but able to write to nickname.
Is this possible?
I tried this rule but it doesn't work
"Users" :{
  "$user_id" :{
    "Points" :{
      ".read" : true,
      ".write" : false
    },
    "nickname" :{
      ".read": true,
      ".write": "$user_id==auth.uid"
    }

UPDATE
Splitting the data to two node is a solution to one part of the problem, leaving the other part of the problem which is writing the nickname.
Writing the nickname should only be possible by the user whom the nickname belong to, but in my code, I am asking the user to put email, pass and nickname.
When the user is registring, the auth.uid is not available yet, I considered registering the user under temporary name and they change it later after they log in, but I am looking for a shorter solution where they get to pick the name when registering
This is my bit of code when they register:
Ref.createUser(email, pass,
  new Firebase.ValueResultHandler<Map<String, Object>>() {
    @Override
    public void onSuccess(Map<String, Object> result) {
      Ref2 = new Firebase(firebase_users_path + result.get("uid").toString());
      HashMap<String, String> names = new HashMap<String, String>();
      names.put("nickname", nickname);
      Ref2.setValue(names, new Firebase.CompletionListener() {
        @Override
        public void onComplete(FirebaseError firebaseError, Firebase firebase) {
          if (firebaseError != null) {
            Toast.makeText(MainActivity.this, "Done!", Toast.LENGTH_SHORT).show();
          } else {
            Toast.makeText(MainActivity.this, "Error!", Toast.LENGTH_SHORT).show();
          }
        }
      });

My code is returning Done! indicating registering is complete, I do find a new user but the nickname doesn't get written in users/uid because the auth.uid is not available yet

A: A broad guess (since the code that fails is missing) is that you're trying to write a user record:
 ref.child('Users').child(auth.uid).set({ 'nickname': 'masood' });

This operation will fail, since the user doesn't have write access to the user node.
For this reason (and quite some others) it's better to split the data into separate nodes that the user has different access types to. In your case:
User_names
    0a88b...
        nickname: "First_user"
User_scores
    0a88b...
        Points: 35

Now you can secure it easily and one level higher:
"User_names" :{
  "$user_id" :{
    "nickname" :{
      ".read": true,
      ".write": "$user_id==auth.uid"
    }
  }
},
"User_points" :{
  "$user_id" :{
    "Points" :{
      ".read" : true,
      ".write" : false
    }
  }
}

You might even want to pull the .read up to a higher level, so that anyone can list user names and scores:
"User_names" :{
  ".read": true,
  "$user_id" :{
    "nickname" :{
      ".write": "$user_id==auth.uid"
    }
  }
},
"User_points" :{
  ".read" : true,
  "$user_id" :{
    "Points" :{
      ".write" : false
    }
  }
}

There's a pretty good section in the Firebase docs on how rules cannot be used to filter data.


text:
Q: Where does Laverna stored my local notes? I have downloaded Laverna, disabled any clouds and got the following directory

I ran laverna was able to create a note and it persists after application closed then reopened.
Where did it stored this note?

A: If you are on Linux, check in ~/.config/laverna.


text:
Q: Transformar uma lista em um csv pandas em python Tenho o seguinte código que faz raspagem de dados de um site de leilão:
lista = []
for pagina in range(1,34):
    url = 'https://www.lance24h.com.br/DetalhesLances.php?Codigo=45919&Pagina={0}'.format(pagina)
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html,'lxml')
    lista = []
    for corpo in soup.find_all('tr'):
      lista.append(corpo.text.strip())

novo = []
for x in lista:
    item = x
    for y in ['\n', '\t','\r', '/', '.', '-', '(', ')']:
        item = item.replace(y, "")
    novo.append(item)

Então com retorno eu tendo o seguinte:
['DataValorUsuário',
 '13012021 22:03:02                    R$ 0,59                    Daniel de Santi',
 '13012021 22:03:02                    R$ 0,58                    lordschug',
 '13012021 22:02:50                    R$ 0,57                    socialdomarcos',
 '13012021 22:02:48                    R$ 0,56                    deiaxabs',
 '13012021 22:02:47                    R$ 0,55                    Daniel de Santi',
 '13012021 22:02:35                    R$ 0,54                    lordschug',
 '13012021 22:02:33                    R$ 0,53                    Daniel de Santi',
 '13012021 22:02:27                    R$ 0,52                    socialdomarcos',
 '13012021 22:02:23                    R$ 0,51                    Daniel de Santi',
 '13012021 22:02:11                    R$ 0,50                    lordschug',
 '13012021 22:02:04                    R$ 0,49                    socialdomarcos',
 '13012021 22:02:03                    R$ 0,48                    lordschug',
 '13012021 22:01:54                    R$ 0,47                    Daniel de Santi',
 '13012021 22:01:53                    R$ 0,46                    socialdomarcos',
 '13012021 22:01:42                    R$ 0,45                    lordschug',
 '13012021 22:01:32                    R$ 0,44                    socialdomarcos',
 '13012021 22:01:23                    R$ 0,43                    lordschug',...,]

Agora estou tentando transformar em um arquivo csv que tenha três colunas uma para a data outra para o lance e a última para o nome de quem deu o lance. Já tentei os seguinte códigos:
with open("lances.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(lista)

E tive o seguinte retorno
D,a,t,a,"
",V,a,l,o,r,"
",U,s,u,á,r,i,o
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,3,:,0,2, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,9, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,D,a,n,i,e,l, ,d,e, ,S,a,n,t,i
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,3,:,0,2, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,8, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,l,o,r,d,s,c,h,u,g
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,2,:,5,0, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,R,$, ,0,",",5,7, , , , , , , , ,"
","
","
", , , , , , , , , , , , ,s,o,c,i,a,l,d,o,m,a,r,c,o,s
1,3,/,0,1,/,2,0,2,1, ,2,2,:,0,2,:,4,8, , , , , , , , ,"
","
","

Acredito que o problema está quando eu formato a lista para tirar caracteres indesejados, porém não sei como arrumar isso.

A: Defina os parametros na escrita que vai formatar da maneira que deseja
arquivo = open('novoarquivo.csv', 'w', newline='')
#parametros de acordo com os caracteres de escape
escrever= csv.writer(arquivo, delimiter='\t', lineterminator='\n\n')
escrever.writerow(list(range(1,20)) ) #exemplo de escrita
arquivo.close()


text:
Q: 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message app.module.ts
As you can see that I am lazy loading the MainModule so I have added CUSTOM_ELEMENTS_SCHEMA and imported MainModule also. Added RouterModule.forRoot and exported RouterModule.
import { BrowserModule } from '@angular/platform-browser';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MainModule } from './main/main.module';

export const appRoutes: Routes = [
  {
    path: '',
    loadChildren: () => import('./main/main.module').then(m => m.MainModule),
  },
  {
    path: '**',
    redirectTo: '',
    pathMatch: 'full',
  }
]

@NgModule({
  schemas: [
    CUSTOM_ELEMENTS_SCHEMA
  ],
  imports: [
    BrowserModule,
    NgbModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes, {
      anchorScrolling: 'enabled',
      enableTracing: false,
      preloadingStrategy: PreloadAllModules,
      relativeLinkResolution: 'corrected',
      scrollPositionRestoration: 'disabled',
    }),
    MainModule
  ],
  declarations: [
    AppComponent,
  ],
  exports: [
    RouterModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

main.module.ts
When I come to MainModule , I did all the Routing and added RouterModule.forChild(mainRoutes)
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';

import { MainComponent } from './main.component';
import { VerifyEmailComponent } from './verify-email/verify-email.component';
import { SignupComponent } from './signup/signup.component';
import { EnterEmailComponent } from './enter-email/enter-email.component';

export const mainRoutes: Routes = [
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        redirectTo: 'enter-email',
        pathMatch: 'full'
      },
      {
        path: 'enter-email',
        component: EnterEmailComponent
      },
      {
        path: 'sign-up',
        component: SignupComponent
      },
      {
        path: 'verify-email',
        component: VerifyEmailComponent
      }
    ]
  }
]

@NgModule({
  declarations: [
    VerifyEmailComponent,
    SignupComponent,
    EnterEmailComponent
  ],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forChild(mainRoutes),
  ]
})
export class MainModule { }

mai.component.html
But in main.component.html file when I do <router-outlet></router-outlet> . It shows errors:

*

*If 'router-outlet' is an Angular component, then verify that it is part of this module.

*If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the
'@NgModule.schemas' of this component to suppress this message.

              ...

              <router-outlet></router-outlet>    // errors come here

A: <router-outlet></router-outlet> tag is declared in the RouterModule. Just import RouterModule in your main.module.ts
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule, // <--- Add this line
    RouterModule.forChild(mainRoutes),
  ]


text:
Q: how to know if an ec2 instance is being utilize by a glue job I have two prod glue jobs, how can I know what ec2 instances are being utilized by these glue jobs?
I have a glue policy that need to be separated. how can I know how the resources from this policy are being utilize by glue.
For example, I have 2 glue jobs that use some ec2 instances, how do i identify the ec2 instances being used


text:
Q: how to get latitude and longitude of a circle's border to create that marker? this is my map factory
I draw a circle with multiple markers but I want to add a one marker at the end of circle(/outline of circle) for  to  change the radius dynamically. but I am unable to set the position (latitude and longitude) of that marker
sidemenu.factory('Map', function( $rootScope , $compile,$location,mapPlacesGeocoder,centerCoordinatesForMap,getMapObject){
  //  alert($location.path());

    var canvas   = document.getElementById('map'),
        defaults = {
            center:    new google.maps.LatLng(0,0),
            zoom:      4,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

    return {
        init:function(properties , scope) {
            mapPlacesGeocoder.getCoOrdinates(scope.address,function (coOrdinates) {
                var map=getMapObject.mapEntity();
             centerCoordinatesForMap.setMapObject(map);
            var center = new google.maps.LatLng(coOrdinates.lat, coOrdinates.lng);
           centerCoordinatesForMap.setMapcenter(center);
              var circle=getMapObject.circleEntity();
              centerCoordinatesForMap.setCircleObject(circle);
                  var bounds = getMapObject.boundsEntity();
             centerCoordinatesForMap.setBoundObject(bounds);

                var infoWindow = new google.maps.InfoWindow({
                    boxStyle: {
                        width: "0%",
                        backgroundColor:'#ccc'
                         }});

                 var icon = {
                           url: "../img/square.png", // url
                           scaledSize: new google.maps.Size(10, 10), // scaled size
                           origin: new google.maps.Point(0, 0), // origin
                          anchor: new google.maps.Point(0, 0) // anchor
                            };

                var markerCenter = new google.maps.Marker({
                     draggable: true,
                     title: 'Drag me!',
                      map: map,
                      position:center
                     });

       var sizer = new google.maps.Marker({
           draggable: true,
            title: 'Drag me!',
            position:circle.getBounds(),
            map: map
            });

               circle.bindTo('center', markerCenter, 'position');

        google.maps.event.addListener(markerCenter, 'dragend', function() {
        latLngCenter = new google.maps.LatLng(markerCenter.position.lat(), markerCenter.position.lng());
        bounds = circle.getBounds();

        console.log(markerCenter.position.lat());
                console.log(markerCenter.position.lng());
        console.log(circle.getRadius());

             });

                for (var i = 0, length = properties.length; i < length; i++) {

                    var latLng = new google.maps.LatLng(properties[i].property_latitude, properties[i].property_longitude);

                    // Creating a marker and putting it on the map
                    scope.marker = new google.maps.Marker({
                        position:latLng,
                        map: map,
                      /*  icon:{
                             url:"/img/marker.jpg",
                            size: new google.maps.Size(80,80),
                            origin: new google.maps.Point(0, 0),
                            anchor: new google.maps.Point(24 / 2,24 / 2),
                            scaledSize: new google.maps.Size(40, 80)
                            }*/
                           });

                    bounds.extend(scope.marker.position);

                    google.maps.event.addListener(
                        scope.marker,
                        'mouseover',
                        (function( marker , scope, property,compile,location){
                            return function(){
                                var content = '
' +
                                    '
' +property.hp_location.location_name +'
'+
                                    '
' + property.hp_city.city_name +'
'+
                                    '' + property.property_name +'' + '
';

                                var compiled = compile(content)(scope);
                                scope.$apply();
                                infoWindow.setContent(compiled[0].innerHTML);
                                infoWindow.open( Map , marker );
                             };
                        })(scope.marker,scope,properties[i],$compile,$location)
                     );

                     if(scope.city==true) {
                         circle.setMap(null);
                         map.fitBounds(bounds);
                        }
                      else if(scope.city==false) {
                         map.fitBounds(circle.getBounds());

                        }

                    var listener = google.maps.event.addListener(map, "idle", function() {
                        google.maps.event.removeListener(listener);

                     });

                    var listenerdragstart = google.maps.event.addListener(map, "zoom_changed", function() {

                        google.maps.event.clearListeners(map, 'idle');
                        google.maps.event.removeListener(listenerdragstart);
                    });

                    }

           })
        }//init
    };//return

});//

So how to create this marker?
 var sizer = new google.maps.Marker({
      draggable: true,
      title: 'Drag me!',
      position:circle.getBounds(),
      map: map
 });

What I have to set this position of this marker to create at outline of this circle?

A: The position attribute of google.maps.Marker should be of type google.maps.LatLng not google.maps.LatLngBounds which circle.getBounds() returns.
However, you can get the coordinates of north-east and south-west corner of the bounds. What you could do in your case is to get the longitude of north-east corner, to get the right-most point of the circle and set it to the circle's center latitude. That way the resulting position will be on the border of the circle on right side.
So, you would do something like this:
position: new google.maps.LatLng(circle.getCenter().lat(), circle.getBounds().getNorthEast().lng()),


text:
Q: Training GAN on small dataset of images I have created a DCGAN and already trained it for CIFAR-10 dataset. Now, i would like to train it for custom dataset.
I have already gathered around 1200 images, it is practicly impossible to gather more. What should i do?

A: We are going to post a paper in a coming week(s) about stochastic deconvolutions for generator, that can improve stability and variety for such a problem. If you are interested, I can send a current version of a paper right now. But generally speaking, the idea is simple:

*

*Build a classic GAN

*For deep layers of generator (let's say for a half of them) use stochastic deconvolutions (sdeconv)

*sdeconv is just a normal deconv layer, but filters are being selected on a fly randomly from a bank of filters. So your filter bank shape can be, for instance, (16, 128, 3, 3) where 16 - number of banks, 128 - number of filters in each, 3x3 - size. Your selection of a filter set at each training step is [random uniform 0-16, :, :, :]. Unselected filters remain untrained. In tensorflow you want to select different filter sets for a different images in batch as well as tf keeps training variables even if it is not asked for (we believe it is a bug, tf uses last known gradients for all variables even if they are not being used in a current dynamic sub-graph, so you have to utilize as much variables as you can).

That's it. Having 3 layers with sdeconv of 16 sets in each bank, practically you'll have 16x16x16 = 4096 combinations of different internal routes to produce an output.
How is it helping on a small dataset? - Usually small datasets have relative large "topics" variance, but generally dataset is of one nature (photos of cats: all are realistc photos, but with different types of cats). In such datasets GAN collapses very quickly, however with sdeconv:

*

*Upper normal deconv layers learns how to reconstruct a style "realistic photo"

*Lower sdevond learns sub-distributions: "dark cat", "white cat", "red cat" and so on.

*Model can be seen as ensemble of weak-generators, each sub-generator is weak and can collapse, but will be "supported" by another sub-generator that temorarily outperforms discriminator.

MNIST is a great example of such a dataset: high "topics" variance, but the same style of digits.
GAN+weight norm+prelu (collapsed after 1000 steps, died after 2000, can only describe one "topic"):

GAN+weight norm+prelu+sdeconv, 4388 steps (local variety degradation of sub-topics is seen, however not collapsed globally, global visual variety preserved):


text:
Q: How to avoid duplication of NuGet packages Is there anyway to have a central location for local copies of various NuGet packages AND have different Visual Studio solution POINT at the single copy in the central location rather than copying the NuGet package(s) into each VS solutions \packages directory ?
I know disk space is cheap, but having multiple copies of NUnit, EF, etc. just seems wasteful

A: What happens when there is an update to a package?  Are you going to test every project with the new version of the package?
What happens when a package has a breaking change?
Having separate copies of a package per solution allows you to test and update one at a time.  This is a good thing.
Also, most packages are so small that you would need hundreds, if not thousands of copies of them to notice the "waste".
A few examples
EF 4.3.1 is 2.84 MB.
NUnit 2.3.012054 is 795 KB.
Unity 2.1.505 is 1.45 MB.
Stop worrying about this.  It isn't worth your time.

A: No you can't. See http://nuget.codeplex.com/workitem/215

A: Yes, this is entirely possible now since NuGet 2.1.

*

*You need to move your NuGet.config file to a central location.

*Change the repositoryPath configuration value to specify the central location for all your packages (NuGet docs).

*Do some hacking in the targets file to remove the solutionDir option from the restore command.

*Update all your project references to point to the new location.

To avoid duplication, I've gone into a little more detail on exactly what to do in this answer: https://stackoverflow.com/a/19466173/564726


text:
Q: Make a jar that has a classifier by default We have a project called core-services. This builds three jars:

*

*core-services-client Contains all client classes

*core-services-server: Contains all server and client classes

*core-services-test: Contains all junit classes

Right now, I build the core-services-server jar by default, and then use assemblies to build the client and test jars. If a developer wants to use the client or test jars, they must specify a classifier. However, when they want to depend upon the server jar, they don't specify a classifier.
This will lead to developers just using the server jar when they really should be using the client jar. I'd like to build all three jars to require a classifier when using them as a dependency. However, I can't do this when specifying the project:
<groupId>com.vegicorp</groupId>
<artifactId>core-services</artifactId>
<version>1.0.0</version>
<classifier>server</classifier>
<packaging>jar</packaging>

I know I can use <finalName> to call the default jar core-services-server, but I want to make sure that if a developer depends upon the core-services, they must say whether they want the server, the client, or the testing classes. If I merely rename it, they will get the server jar by default.
How can I specify that the default jar has a classifier of server?

A: I figured it out. I can put the default classifier into the maven-jar-plugin configuration in my pom.xml:
<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <!-- All other configuration information is in the parent pom -->
    <configuration>
        <classifier>server</classifier>
    </configuration>
</plugin>

When I do mvn deploy, I get a warning that No primary artifact to deploy, deploying attached artifacts instead, and all three jars deploy with classifiers.


text:
Q: Benefits of MVVM over MVC Finally getting to do some Silverlight development and I came across MVVM. I am familiar with MVC and the article I was reading said because of XAML, MVC would not work out. Not having too much experience in XAML clearly is the reason I did not get this point.
Can someone explain why MVC is not suited and why MVVM is better for Silverlight development?
Thanks
JD

A: Its a very slim distinction, which I can explain best by comparing MVC in ASP.NET and MVVM in WPF.
In ASP.NET MVC the request comes in from the web server and is handled directly by the Controller.  The Controller determines the appropriate View and populates it with Models.  The Controller then releases these instances to the underlying system which renders a result to the client.  You can see that the Controller is first and last to act.
In MVVM, the UI (the View), faces the user and takes user input directly.  Within the View, Commands within the ViewModel (which is the DataContext of the View) are triggered by this activity.  Control flows to the ViewModel which interprets what the View has sent it and prepares its Models.  After control flows back to the View it updates itself according to changes in the Models.  If a new View is required, the ViewModel communicates this with the NavigationService (or whatever method of navigation your application uses), which is the purview of the Window or Frame--UI components.  You can see that the ViewModel isn't first and last to act; the View plays a much greater role than in MVC.
The architecture of WPF/Silverlight is the reason why things are done this way.  The command, binding and navigation infrastructures can't be controlled/replaced by the Controller; they are tightly integrated with the UI.  So the Controller must sit below the View and take a more passive role.

A: I think the idea is that MVVM is better suited to XAML than MVC. Saying MVC 'is not suited' is a bit exaggerated.
And why is MVVM better? Mainly because of the superb data-binding and command-binding in XAML. See this article.

A: I think the other benefit is learning curve. As most of the developers in frontend technologies have used MVVM kind of coding style it is easier for them to adopt the same than going with a controller model where they need to pass every request from view to controller and have it communicate with Model.

A: Decoupling Components
In MVC, you have a triangular relationship between the components.  That is:  The Controller owns the View and the Model.  The View relies on the definition of the Model.  The Model needs to fulfill the requirements of the View.  Think of a Hub (controller) and spoke architecture (view and model)
In MVVM, think of that triangle flattening out with each component only knowing about one other in the chain.  That is:  View->ViewModel->Model
The Model is unaware of anything up the stack.
The ViewModel is only aware of the Model
The View is only aware of the View Model - it is unaware of the Model.
Why is this important?
This is the core of the original question.
The main purpose is further abstraction of your architecture.  This will typically lead to a bit more code, but fewer points of contact between objects.  Fewer points of contact are important because this leads to more agile code.  The more coupling/contact Class A has with Class B, the more impact a change in Class A will have.  Reducing the impact of change is one of the key benefits of good architecture.
To fully understand this, it's helpful to ponder about what the components really represent.  What is a View, a Controller, a ViewModel, or a Model?  Are they literal definitions, or more of an abstract concept?
In my experience, it has been more beneficial to consider the Model to be a cluster of classes/objects which deal with the construction and persistence of data.  It's not just a plain-old-object with properties.  It's a class which performs data fetches, data saves, a factory which constructs plain-old-objects.  It's a facade layer which provides a clear API into the data.  Should this facade layer be referenced directly from the View?
In my opinion, it should not.  In MVC, that answer is also "no".  The Controller fetches data from the Model.  In that regard, MVC and MVVM achieve the same goal.  Where the two architectures differ is how the data and the view are linked.
Like the Model, the View can be a collection of classes which in coordination with one another, render a presentation view.  This could consist of a View Controller + View in the case of mobile platforms (View Controller on iOS, Activity on Android).  In a lot of cases, you need a class to load a view document into memory and update view properties.  There's a lot of work to do here.  In MVC, the Controller quickly becomes a 'kitchen sink' class - a sort of dumping grounds for anything related to the current user context.
When you multiply this over dozens of potential views within your application, you end up with a lot of deep dependancies between your back-end Model code and your front-end View code.  With large Controller classes, these dependencies aren't immediately apparent.
Flattening out your dependencies
MVVM flattens out the dependencies.  This creates focus.  What is focus?  The ability to work on a single piece of functionality without the distraction of all other dependencies. Now you can start writing unit tests on code that was previously deemed untestable.
The View Model acts as a facade between the View and the Model.  The View Model caters to the needs of the View - technically the View should own the View Model.  If the View requires data from multiple sources, the View Model encapsulates the composition of separate data sources into a single, unified, de-normalized object.  If the view needs to call back into the Model or other destinations, the View Model provides hooks and routes the appropriate call.
Consider how a networking patch-panel works.  At first glance, this seems redundant - why not simply wire your ethernet from point A to point B.  But with experience, you'll understand that a patch panel provides you with a key piece of abstraction which allows you to alter the routes of Point B without affecting Point A.  This is what your View Model is doing.
Now that you have a clean abstraction between your View and Model, the consequence should be that your View/Controller is only concerned with presentation.  This means it shouldn't be dealing with localization or formatting - it gets data and presents data.  Your View Model is an ideal place to put these sort of pre-view data massaging.  Let's say you need to filter data based on a criteria.  Again, the View Model is knowledgable about the Model data (your View is not) and is a great place to put this sort of code.
Once you start organizing your application requirements in this fashion, your View/Controller code becomes cleaner, and when something needs to change, the implications are more obvious, which leads to fewer bugs.
Testability
One final note on testability:  By flattening out dependencies, it makes it easier to inject mock dependencies into your tests.  It makes testing easier and more concise.  Your View Model becomes something that you can define clear test cases against.

A: MVVM was designed mainly because of XAML and to make data binding even simpler, it's very similar to MVP. The main benefits are simpler way of manipulating the user interface (the ViewModel or Presenter takes care of that task rather than the Model having to fire events to the View after it's been manipulated by the Controller).
The best two articles I've come across that helped me understand the principles are MVC vs MVP vs MVVM and MVVM for Tarded Folks Like Me or MVVM and What it Means to Me