text:
Q: Observable stream from StackExchange Redis Pub Sub subscription OBJECTIVE:
I am using StackExchange Redis Client. My objective is to create an Observable stream from the Pub Sub Subscriber exposed by the Client, that can then in turn support 1-n subscriptions by Observables, that each have their own filter via LINQ. (Publishing is working as planned, the issue is purely around Subscription to the Event Stream on a specific channel.)
BACKGROUND:
I am using Redis Pub Sub as part of an Event Sourced CQRS application. The specific use case is to publish Events to multiple subscribers that then update the various Read Models, send emails etc.
Each of these Subscribers need to filter the Event Types that they handle, and for this I am looking to use Rx .Net (Reactive Extensions), with LINQ, to
provide a filter criteria on the Event Stream, to efficiently handle reacting only to Events of interest. Using this approach removes the need for registering Handlers with an event bus implementation, and allows me to add new projections to the system by deploying 1-n Microservices that each have 1-n Observables subscribed to the Event Stream with their own specific filters.
WHAT I HAVE TRIED:
1) I have created a class inheriting from ObservableBase, overriding the SubscribeCore method, which receives subscription requests from Observables, stores them in a ConcurrentDictionary, and as each Redis notification arrives from the channel, loops through the registered Observable subscribers and calls their OnNext method passing the RedisValue.
2) I have created a Subject, that also accepts subscriptions from Observables, and calls their OnNext method. Again, the use of Subjects appears to be frowned upon by many.
THE ISSUE:
The approaches I have tried do function (at least superficially), with varying levels of performance, but feel like a hack, and that I am not using Rx in the way it was intended.
I see many comments that the built-in Observable methods should be used where at all possible, for example Observable.FromEvent, but that seems to be impossible to do with the StackExchange Redis Clients Subscription API, at least to my eyes.
I also understand that the preferred method for receiving a stream and forwarding to multiple Observers is to use a ConnectableObservable, which would seem to be designed for the very scenario I face (Each Microservice will internally have 1-n Observables subscribed). At the moment, I cannot get my head around how to connect a ConnectableObservable to the notifications from StackExchange Redis, or if it offers real benefit over an Observable.
UPDATE:
Although completion is not an issue in my scenario (Disposal is fine), error handling is important; e.g. isolating errors detected in one subscriber to prevent all subscriptions terminating.

A: Here is an extension method you can use to create an IObservable<RedisValue> from an ISubscriber and a RedisChannel:
public static IObservable<RedisValue> WhenMessageReceived(this ISubscriber subscriber, RedisChannel channel)
{
    return Observable.Create<RedisValue>(async (obs, ct) =>
    {
        // as the SubscribeAsync callback can be invoked concurrently
        // a thread-safe wrapper for OnNext is needed
        var syncObs = Observer.Synchronize(obs);
        await subscriber.SubscribeAsync(channel, (_, message) =>
        {
            syncObs.OnNext(message);
        }).ConfigureAwait(false);

        return Disposable.Create(() => subscriber.Unsubscribe(channel));
    });
}

As there is no completion of Redis channels the resulting IObservable will never complete, however you may drop the IDisposable subscription to unsubscribe from the Redis channel (this will be done automatically by many Rx operators).
Usage could be like so:
var subscriber = connectionMultiplexer.GetSubscriber();

var gotMessage = await subscriber.WhenMessageReceived("my_channel")
    .AnyAsync(msg => msg == "expected_message")
    .ToTask()
    .ConfigureAwait(false);

Or as per your example:
var subscriber = connectionMultiplexer.GetSubscriber();

var sendEmailEvents = subscriber.WhenMessageReceived("my_channel")
    .Select(msg => ParseEventFromMessage(msg))
    .Where(evt => evt.Type == EventType.SendEmails);

await sendEmailEvents.ForEachAsync(evt =>
{
    SendEmails(evt);
}).ConfigureAwait(false);

Other microservices may filter differently.


text:
Q: How do i convert hdb file? ... believed to be from act! source Any ideas ?
I think the original source was a goldmine database, looking around it appears that the file was likely built using an application called ACT which I gather is a huge product I don't really want to be deploying for a one off file total size less than 5 meg.
So ...
Anyone know of a simple tool that I can run this file through to convert it to a standard CSV or something?
It does appear to be (when looking at it in notepad and excel) in some sort of csv type format but it's like the data is encrypted somehow.

A: I am unaware of any third party tooling for opening these files specifically, although there is an SDK available for C# which could resolve your problem with a little elbow grease.
The SDK can be aquired for free Here
Also there is a developer forum which could provide some valuable resources including training material with sample code Here
Resources will be provided with the SDK
Also, out of interest since ACT is a Sage product have you any Sage software floating about which you could attempt to access the data with? Most offices have!
Failing all of the above there is a trial available for ACT! Here!
Good luck with your problem!

A: Ok this is weird,
I got a little confused because the data looked a complete mess, in actual fact the mess was the data, that's what it was meant to look like.
Simply put, i opened the file in notepad, seemed to have a sort of pattern so i droppped it on excel.
Apparently excel has no issues reading these files ... strange huh !!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: animation based on device orientation with CSS? I've created a page that has content showing & hiding based on the device orientation, however I find that there's somewhat of a jump/lag when you rotate and the content shows/hide.
Is it possible to animate a smoother transition between lelements showing/hiding using just css?

A: For the elements that animate in and out of view, you can use transition-property: all; and transition-duration: 1s; (or whatever duration you'd like) to fade in/slide in said elements.  Of course those CSS properties will need to be prefixed in some browsers.


text: Q: how to put text at random position in xaringan I'm trying to put some text in the slides at certain position on top of other stuffs/plots, is that possible? Here is one scenario, the slide is occupied by pictures and texts, but I like to give one sentence conclusion by a different color on top of them, the text just like a stamp to the slide, it's better if I also can adjust the text orientation, just like in powerpoint or keynote, you can add text at any position and style.


text:
Q: Why does Autoresizing disappear when constraints are added? When you create a new label in the storyboard, the Size Inspector menu looks like this:
But as soon as you add constraints, the Autoresizing disappears:
Why does this happen?
Is it impossible for an item to be resizeable while constrained?

A: No , it's not possible these are 2 separate ways to layout an element you can't have both at the same time , either with the old springs and struts ( Discouraged  now ) or using auto-layout ( Recommended ) and that for pretty a lot of limitations regarding the old way look here discussing some problems


text:
Q: Delete throwing destructor called from destructor I understand that the current rules in C++ say that:

if a destructor throws while already stack unwinding because of a exception then std::terminate is called.

While exploring why the rules are as they are, I came across the situation described in the code below.

*

*The destructor of X throws.

*Y deletes an X in its own destructor.

*Therefore the destructor of Y throws.
It's not clear to me if the fact that Y throws (3.) should trigger std::terminate by the standard rules. I hope it should not, and testing against gcc runs as I hoped.
Can someone familiar with the standard legalese clarify this? Should (3.) trigger std::terminate or not?
#include <iostream>

struct X {
  ~X() noexcept(false) {
    std::cout << "Destroying X\n";
    throw std::runtime_error("Exception");
  }
};

struct Y {
   X * x_;

  explicit Y(X * x) : x_{x} { }

  ~Y() noexcept(false) {
    std::cout << "Destroying Y\n";
    delete x_;
  }
};

int main() {
  try {
    Y y(new X());
    std::cout << "Living\n";
  }
  catch (const std::exception & e) {
    std::cout << "Caught " << e.what() << '\n';
  }
}

With g++ version 5.4.0-6ubuntu1~16.04.9 with --std=c++17 I get:
Living
Destroying Y
Destroying X
Caught Exception

A: The standard says in [except.terminate]p1.4:

*

*when the destruction of an object during stack unwinding terminates by throwing an exception, or

2) happens because y goes out of scope. 1) throws an exception, which starts stack unwinding. During stack unwinding, more specifically while destroying Y - which is 2). It throws an exception, and so the point is satisfied and std::terminate is called.
Which is exactly what you're code is doing, except for an important point: during stack unwinding. Stack unwinding doesn't happen when a scope ends, it only happens when an exception is thrown and goes out of the current scope it was thrown.
Y isn't destroyed because of an exception. Add a throw 1; to see a call to std::terminate in action.
Thus, that clause doesn't apply and your code is indeed valid.


text:
Q: How to add multiple filters to the same document key in mongoose? I currently have an array of objects in a document that looks something like this:
users: [
    {name: "Bob", age: 23},
    {name: "Tom", age: 23),
    {name: "Sam", age: 26),
]

I am trying to find the document that has the name Bob and the age 23. while filtering out any documents that do not match this criteria, or do not yet exist. I was able to find the matching object with:
User.find({users: { $elemMatch: { name: "Bob", age: 23}}})

and I was able to filter out the documents that do not exist with:
User.find({users: {$ne: []}})

but when I try to add the two together, like so, the program stops working:
User.find({users: {$ne: [], $elemMatch: { name: "Bob", age: 23}}})

I want to know how to can add two filters for the same key inside the document.


text:
Q: Progress bar (circle) setVisibility() doesn't exist anymore? (Android Java) I want to turn my progress bar / circle invisible when the images are loaded on the page, but the setVisibilty() doesn't exist anymore. What is the subistute, because I couldn't find anything on the internet.
I wanted to call it after the setAdapter().
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.notes_fragment, container, false);
    BottomNavigationView bottomNav = view.findViewById(R.id.bottomAppBar);
    MaterialToolbar topAppBar = view.findViewById(R.id.topAppBar);
    bottomNav.setSelectedItemId(R.id.notes);
    mProgressCircle = (ProgressBar) view.findViewById(R.id.progress_circle);

    imageList = new ArrayList<>();

    currentUser = mAuth.getCurrentUser();
    mUserRef = storage.getReference().child(currentUser.getEmail());
    gridView = view.findViewById(R.id.gridview);
    mUserRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
        @Override
        public void onSuccess(ListResult listResult) {
            for(StorageReference file:listResult.getItems()){
                Log.w(TAG, file.toString());
                file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        imageList.add(uri.toString());
                        Log.w(TAG,"URI: " + uri.toString());
                    }
                }).addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        adpter = new GridAdapter(getActivity(), imageList);
                        gridView.setAdapter(adpter);
                    }
                });
            }
        }
    });

        android:id="@+id/progress_circle"
        style="@style/Widget.AppCompat.ProgressBar"
        android:layout_width="78dp"
        android:layout_height="83dp"
        android:layout_gravity="center"/>


text:
Q: How can I load test the system for 100 thousand unique users by running Jmeter test on several AWS instances? I want to load test the system for 100 thousand unique users by running Jmeter test on several AWS instances (Master, Slave).
These users are registered in the site that I want to load test and I have them in csv file.
I have to use different set of users from each instance as the test case during load run involves different i.e. unique set of users.

A: JMeter can be executed in distributed mode so you need to have:

*

*1 machine to act as a Master - which will load the Test Plan, orchestrate the test and collect the reusults

*X number of slaves where X depends on:

*

*Nature of your test (number of requests, size of requests/responses, number of pre/post processors/assertions/etc.), see What's the Max Number of Users You Can Test on JMeter? article for guidelines on properly sizing your JMeter test

*Hardware specifications of your AWS instances as there are different AWS EC2 instance types with different number of CPUs, amount of memory, etc.
Remember that you need to divide your "lakh" to the number of the slave machines, for example if you have 10 machines you should define 10k users in the Thread Group, if you have 20 machines - 5k users, etc.

You might also find projects like jmeter-aws or jmeter-ec2 useful


text:
Q: Accessing infinite nested children object Wanted to know how can we access infinitely nested object in JS?
Consider this example given to be my interviewer
You have an object with a Parent and infinitely nested children
[
 {
   name: "Jack",
   age: "98" ,
   profession: "doctor
   children: [
               {
                 name: "Varun",
                 age: "80"
                 profession: "scientist"
                 children: [
                             {
                                name: "Ishan"
                                age: "62",
                                profession: "teacher
                                children: [{....
                                 .....
                                 .....[{
                                       name: "Rahul",
                                       age: "23",
                                       profession: "engineer"
                                      children: [{
                                                  .....

I need to find the name corresponding where profession is "engineer" and how deep that given object is nested.
Note: Number of children to be considered here is infinite.
Question: Can someone help me in figuring out how I can do it with recursion and without recursion
update: He gave me a hint to use divide and conquer
Update: Based on the solution by Bary, I tried something like this
let infiniteArray = [
    {
      name: "Jack",
      age: "98" ,
      profession: "doctor",
      children: [
                  {
                    name: "Varun",
                    age: "80",
                    profession: "scientist",
                    children: [
                                {
                                   name: "Ishan",
                                   age: "62",
                                   profession: "teacher"
                                }
                            ]
                    }
                ]
        }
]

function isTheItem(item) {
   if (item["profession"] === "teacher") return item
    return false
 }

 function walk(collection) {
    return collection.find(item => isTheItem(item) || walk(item.children));
  }

But when I console.log it, i.e console.log(walk(infiniteArray)), it is logging the entire infiniteArray and I understand why but I went it to return just the name corresponding to profession. Any help on how I can achieve it?
  name: "Ishan",
        age: "62",
        profession: "teacher"
    }

A: There's two directions walking through your collection
* sibling
* nested
so you can iterate this sibling items with regular array iterator and recursively walk through the children of each item.
function isTheItem(item) {
   return ...;
}

function walk(collection) {
  return collection.find(item => isTheItem(item) || walk(item.children));
}

A: Divide and conquer algorithms usually have more to do with sorting values in an array (during an interview process). If you were sorting by age or something, I could see that being a hint. But there's no way to really divide and conquer when searching for a key value pair of an infinite number of nested objects. You have to search through n number of values until you find the result. Any dividing of the object doesn't necessarily improve efficiency with a random key value pair stored that you want to find.
More experienced devs correct me if I'm wrong here
Barry Gane has a good start to the code you would write for the actual application of this.


text:
Q: accesing to RGB and depth buffer of fragment shader : GLSL continue to this question :
GLSL : accessing framebuffer to get RGB and change it
Is it possible to develop program based on GLSL as follows?

*

*draw object1

*get depth buffer using shader (also save rgb)

*draw object 1, object 2 simultaneously

*get detph

*check if depths are different (depth 2 vs depth 4)

*draw object 1
: for the range that depth isn't changed -> draw as original RGB
: for the range that depth is changed -> draw with different RGB

I confirmed this algorithm which distinguishes object 1 is hidden by other object using glut functions.
I used glReadbuffer, glDrawbuffer functions. However those are too slow, I want to use GLSL.

A: If the only goal is to render object1 with a different color set when it is hidden behind object2 (which are the pixels of object1 where depth has changed) I would go for a completely different approach.

*

*Draw object2 with depth-write only (glDrawBuffer(GL_NONE) or glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE))

*Draw object1 with depth test set to glDepthFunc(GL_GREATER) and the coloring you want when object1 is behind object2

*Draw object1 with depth test set to glDepthFunc(GL_LESS) and the coloring you want when object1 is in front of object2.

In contrast to the algorithm you described in the question, there is no need for any read-back operations or additional framebuffers


text:
Q: Same code, same compiler and different binary... I am very confused So, my professor gave us code of example bootloader and nasm compiler...
He demonstrated how we should compile it and sent us binary after compiling it.
I came home, compiled code, started it, and... it did not work... (qemu-system-x86_64 -fda BOOT12.SYS just froze after printing "Booting from floppy", and it should have printed NP, for Not Found)
I did diff on binaries and those do seem quite a bit different...
The bottom one is mine and the top one is professors.

Weird thin is that mine looks like it is right, since, there is quite a bit of zeros after "Boot Prog"

What do you think could be cause of something like this?
BTW, compiler is nasm 2.12 (nasm-2.12-dos.zip fea1bf6efe69446f5e6ebfae873073363e340bb6913ff5ce3658e5ea533e0dae)
I wouldn't bother you with this, but, I am very tired.
Code: https://pastebin.com/cpH11iCy
; ---------------------------------------------------------------------------
; FAT12 sistem datoteka
; Ucitava COM ili EXE datoteku, a zatim je izvrsava (opracije LOAD i EXEC)
; Promenljiva "ImePrograma" sadrzi ime datoteke
; Zbog velicine boot sektora, greske tokom ucitavanja date su sa po dva slova:
;     "GC" za "Greska u Citanju"
;     "NP" za "Nije Pronadjeno"

; Radi samo sa prvom MBR particijom koja mora da bude PRI DOS particija
; sa sistemom datoteka FAT12 (ID sistema datoteka: 1)

; Radi sa disketama 360KB 5"25, 1.2MB 5"25 i 1.44MB 3"5

;                              Memorija:        segment
;                 -------------------------------------
;                 Tabela vektora prekida           0000
;                 -------------------------------
;                 BIOS Data Area                   0040
;                 -------------------------------
;                 PrtScr Status / neiskorisceno    0050
;                 -------------------------------
;                 Adresa gde se ucitava program    0060
;                --------------------------------
;                 Raspoloziva memorija             nnnn
;                 -------------------------------
;                 2KB Boot stek                    A000 - 512 - 2KB
;                 -------------------------------
;                 Boot sektor                      A000 - 512
;                 -------------------------------
;                                                  A000  (granica od 640 KB)

;  Vrednosti registara:
;  --------------------
;  DL = broj boot disk jedinice
;  CS:IP = pocetak programa
;  SS:SP = programski stek (ne mesati ga sa stekom boot sektora !)
;  COM program standardne vrednosti: CS = DS = ES = SS = 50h, SP = 0, IP = 100h
;  EXE program standardne vrednosti: zavisi od EXE zaglavlja
; ---------------------------------------------------------------------------------

ImageLoadSeg            equ     60h    ; U ovaj segment ucitava se kompletna slika programa sa diska
                                       ; To ne znaci da pocinje i izvrsavanje u ovom segmentu
;-----------------------
; Pocetak boot sektora
;-----------------------
[ORG 0]
        jmp     short   start
        nop
bsOemName               DB      "BootProg"      ; 0x03

;-----------------------------------
; Pocetak BPB (BIOS Parameter Block)
;-----------------------------------

; Nazivi polja su na engleskom jeziku da bi se lakse poredili sa rezultatima upotrebe raznih alata

bpbBytesPerSector       DW      0               ; 0x0B
bpbSectorsPerCluster    DB      0               ; 0x0D
bpbReservedSectors      DW      0               ; 0x0E
bpbNumberOfFATs         DB      0               ; 0x10
bpbRootEntries          DW      0               ; 0x11
bpbTotalSectors         DW      0               ; 0x13
bpbMedia                DB      0               ; 0x15
bpbSectorsPerFAT        DW      0               ; 0x16
bpbSectorsPerTrack      DW      0               ; 0x18
bpbHeadsPerCylinder     DW      0               ; 0x1A
bpbHiddenSectors        DD      0               ; 0x1C
bpbTotalSectorsBig      DD      0               ; 0x20

;----------
;Kraj BPB
;----------

bsDriveNumber           DB      0               ; 0x24   potrebno nam je za INT 13h, fn.2
bsUnused                DB      0               ; 0x25
bsExtBootSignature      DB      0               ; 0x26
bsSerialNumber          DD      0               ; 0x27
bsVolumeLabel           DB      "NO NAME    "   ; 0x2B
bsFileSystem            DB      "FAT12   "      ; 0x36

;------------------------------
; Pocetak koda iz boot sektora
;------------------------------

start:
        cld                     ; Kopiranje nizova bice od nizih ka visim adresama

;-----------------------------------
; Koliko je RAM-a na raspolaganju?
;-----------------------------------

        int     12h             ; BIOS poziv za velicinu konvencionalne memorije ("top" u KB)
        shl     ax, 6           ; a zatim konvertovanje u paragrafe

;------------------------------------------------
; Reervisati deo memorije za boot sektor i stek
;------------------------------------------------

        sub     ax, 512 / 16    ; Rezervisati 32 paragrafa (512 bajtova) za kod iz boot sektora
        mov     es, ax          ; koji ce biti relociran. ES:0 -> top - 512

        sub     ax, 2048 / 16   ; Rezervisati 128 paragrafa (2048 bajtova) za boot stek
        mov     ss, ax          ; SS:0 -> top - 512 - 2048
        mov     sp, 2048        ; Inicijalizacija SP za boot kod (dno steka je na top - 512)

;-------------------------------------------------------
; Boot kod kopira samog sebe u gornji deo memorije
; da bi u donjoj memoriji mogao da ucita drugi program
;-------------------------------------------------------

        mov     cx, 256          ; Kopira se 256 reci (512 bajtova)
        mov     si, 7C00h
        xor     di, di           ; ES:DI -> pocetak odredisnog niza (ES:0 = top - 512)
        mov     ds, di           ; DS:SI -> pocetak izvornog niza (0:7C00h)
        rep     movsw            ; Kopiraj 512 bajtova

;----------------------------------------
; Predaja kontrole relociranom boot kodu
;----------------------------------------

        push    es               ; Ovaj deo boot koda sada je relociran ali ga jos uvek izvrsavamo
        push    word main        ; u nerelociranom delu. Tekuca vrednost ES (segment gde smo kopirali
        retf                     ; kod sa lokacije 0:7C00h) je buduca vrednost CS.

main:                            ; Sada nastavljamo izvrsavanje u relociranom boot kodu.
        push    cs
        pop     ds               ; DS=CS jer je program svega 512 bajtova

        mov     [bsDriveNumber], dl     ; Sacuvati broj boot diska (npr. floppy A = 00, B = 01, prvi HDD = 080h...)
                                        ; Ovo smo dobili kao zaostatak nakon BIOS INT 19h - load boot sector.
                                        ; INT 19h prekidna rutina cita ovaj podatak iz CMOS RAM-a, Flash-a
                                        ; ili druge vrste memorije gde se cuvaju podaci za BIOS.
                                        ; INT 19h prekidna rutina, nakon upotrebe, broj diska ostavlja u DL.
;------------------------------------------
; Rezervisati memoriju za smestanje FAT12
;------------------------------------------

        mov     ax, [bpbBytesPerSector]
        shr     ax, 4                    ; AX = velicina sektora u paragrafima
        mov     cx, [bpbSectorsPerFAT]   ; CX = velicina FAT u sektorima
        mul     cx                       ; AX = velicina FAT u paragrafima

        mov     di, ss                   ; FAT bafer se nalazi odmah iza steka
        sub     di, ax
        mov     es, di                   ; ES:BX -> bafer za FAT
        xor     bx, bx                   ; Pocetak bafera = ES:0 -> (top - 512 - 2048 - velicina FAT)

        mov     ax, [bpbHiddenSectors]   ; Preskociti sakrivene i rezervisane sektore
        mov     dx, [bpbHiddenSectors+2]
        add     ax, [bpbReservedSectors] ; Boot sektor
        adc     dx, bx                   ; DX:AX = Linear Block Address (LBA) prvog sektora prve FAT

        call    CitajSektor              ; Citati CX sektora prve FAT

;----------------------------------------------------------------
; Rezervisati memoriju za root direktorijum, a zatim ga ucitati
;----------------------------------------------------------------

        mov     bx, ax
        mov     di, dx                   ; Sacuvati LBA prvog sektora prve FAT u DI:BX

        mov     ax, 32                   ; Jedna direktorjumska stavka ima 32 bajta
        mov     si, [bpbRootEntries]     ; Broj direktorijumskih stavki
        mul     si                       ; Broj bajtova za direktorijum
        div     word [bpbBytesPerSector]
        mov     cx, ax                   ; CX = velicina root direktorijuma u sektorima

        mov     al, [bpbNumberOfFATs]    ; Broj FAT tabela (standardno 2)
        cbw                              ; Konverovati sadrzaj AL u AX Word
        mul     word [bpbSectorsPerFAT]  ; Ukupan broj sektora za sve FAT
        add     ax, bx                   ; Dodati na LBA prvog sektora FAT
        adc     dx, di                   ; DX:AX = LBA prvog sektora root direktorijuma

        push    es                       ; Segment FAT bafera na stek (drugi parametar - WORD)
        push    word ImageLoadSeg
        pop     es                       ; Segment pocetka bafera za root direktorijum (060h)
        xor     bx, bx                   ; ES:BX -> bafer za root direktorijum

        call    CitajSektor              ; Citanje CX sektora root direktorijuma

        add     ax, cx                   ; Dodati broj sektora za root direktorijum na LBA
        adc     dx, bx                   ; podesiti LBA na prvi klaster oblasti podataka
                                         ; (LBA_klastera_2)
        push    dx
        push    ax                       ; LBA_klastera_2 na stek (prvi parametar - DWORD)

;--------------------------------------------------------------
; Potraziti COM ili EXE program kojeg treba ucitati i izvrsiti
;--------------------------------------------------------------

        mov     di, bx                  ; ES:DI -> tekuca stavka iz root direktorijuma
        mov     dx, si                  ; DX = broj stavki u direktorijumu
        mov     si, ImePrograma         ; DS:SI -> ime programa

;---------------------------------------------------
; Trazimo datoteku sa zadatim imenom
;---------------------------------------------------
; Ulaz:  DS:SI -> ime datoteke (11 znakova, tj 8+3)
;        ES:DI -> polje root direktorijuma
;        DX = broj stavki u root direktorijumu
; Izlaz: SI = redni broj prvog klastera datoteke
;---------------------------------------------------

        mov     cx, 11                  ; CL = broj znakova u imenu (DOS 8+3). CH = 0.
NadjiIme:                               ; Ime je prvo polje od 11 bajtova u dir. stavci
        cmp     byte [es:di], ch        ; Pocetak tekuce direktorijumske stavke je [ES:DI]
        je      ImeNijeNadjeno          ; Kraj direktorijuma. Prvi bajt imena je 0 (nedodeljeno).
        pusha
        repe    cmpsb                   ; Ova instrikcija poredi [DS:SI] sa [ES:DI]
        popa                            ; Poredi se CX bajtova, pri cemu se CX ne menja
        je      ImeNadjeno              ; Ako je svih CX bajtova medjusobno jednako, ZF=1
        add     di, 32                  ; Sledeca stavka u root direktorijumu
        dec     dx                      ; Da li je u pitanju poslednja stavka direktorijuma?
        jnz     NadjiIme                ; Ako nije, tazi dalje.
ImeNijeNadjeno:
        jmp     GreskaNP
ImeNadjeno:                             ; Pronasli smo trazeno ime datoteke.
        mov     si, [es:di+1Ah]         ; SI = redni broj prvog klastera (start).
                                        ; Ovo je bajt br. 26 u direktorijumskoj stavci.
;----------------------------
; Ucitati kompletni program
;----------------------------

CitajSledeciKlaster:
        call    CitajKlaster
        cmp     si, 0FF8h               ; EOC (End of Chain) moze da bude od 0FF8h do 0FFFh
        jc      CitajSledeciKlaster     ; Ovim se ispituje da li je SI manje od EOC. Ako jeste,
                                        ; ucitava se sledeci klaster.
;--------------------------------
; Ispitivanje tipa (COM ili EXE)
;--------------------------------

        cli                             ; Prlikom raznih podesavanja steka ne sme da dodje do prekida
        mov     ax, ImageLoadSeg
        mov     es, ax
        cmp     word [es:0], 5A4Dh      ; Da li su pva dva bajta "MZ"?
        je      RelocirajEXE            ; Ako jesu, to je EXE program

;-------------------------
; Startovati COM program
;-------------------------

        mov     ax, es
        sub     ax, 10h                ; Treba oduzeti 10h od svih segmentnih registara da bi se
        mov     es, ax                 ; u memoriji napravio prostor za PSP (memorijska struktura velicine 100h
        mov     ds, ax                 ; koju kreira DOS nakon ucitavanja, a pre izvrsavanja programa).
        mov     ss, ax                 ; Mi ne koristimo PSP, ali moramo da uzmemo u obzir memoriju koju zauzima.*
        xor     sp, sp                 ; SP se inicijalizuje na 0000. Zbog osobine 16-bitnog broja (wrap around)
                                       ; prvi PUSH pomera SP na FFFE, tj. na vrh memorijskog segmenta od 64K.
        push    es                     ; Ovaj sadrzaj ES bice vrednost CS nakon izvrsavanja instrukcije RETF.
        push    word 100h              ; Nakon instrukcije RETF, IP se inicijalizuje na 100h.
        jmp     Run                    ; U propratnom materijalu objasnjeno je zasto se ovako predaje kontrola.

; (*) Napomena. Ukoliko ne zelimo kompatibilnost sa MS-DOS-om, mozemo da izostavimo PSP.
;               Tada ne treba za njega rezervisati prostor (treba izbaciti sub ax, 10h),
;               inicijalnu vrednost IP treba posaviti na 0 ('push word 0h' umesto 'push word 100h'),
;               a nasa cista binarna datoteka treba da ima 'ORG 0h' umesto 'ORG 100h'.

;--------------------------------------
; Relocirati i startovati EXE program
;--------------------------------------

RelocirajEXE:
        mov     ds, ax                  ; Segment pocetka EXE slike sa diska (sa zaglavljem): kod nas 60h

        add     ax, [ds:08h]            ; AX = dodaje se velicina zaglavlja u pragrafima (preskacemo zaglavlje)
        mov     cx, [ds:06h]            ; CX = broj relokacionih stavki
        mov     bx, [ds:18h]            ; BX = ofset pocetka RPT (Relocation Pointer Table)

        jcxz    KrajRelokacije          ; Preskoci Relociraj ako je broj relokacionih stavki = 0

Relociraj:
        mov     di, [ds:bx]             ; DI = ofset stavke u RPT       | Svaka stavka predstavlja memorijsku adresu
        mov     dx, [ds:bx+2]           ; DX = segment stavke u RPT     | segmentne adrese koju treba relocirati
        add     dx, ax                  ; DX = na segement stavke dodati segment pocetka programa u memoriji

        push    ds
        mov     ds, dx
        add     [ds:di], ax             ; Izvrsiti promenu adrese segmenta na lokaciji stavke
        pop     ds

        add     bx, 4                   ; Sledeca stavka (stavke su DWORD)
        loop    Relociraj

KrajRelokacije:

        mov     bx, ax                  ; Informacije iz zaglavlja koje je upisao linker
        add     bx, [ds:0Eh]            ; AX sadrzi segment pocetka izvrsnog koda
        mov     ss, bx                  ; Podeseni SS za EXE
        mov     sp, [ds:10h]            ; Inicijalni SP za EXE

        add     ax, [ds:16h]            ; Podeseni CS
        push    ax
        push    word [ds:14h]           ; Inicijalni IP
Run:
        mov     dl, [cs:bsDriveNumber]  ; Posledjujemo broj disk jedinice programu
        sti                             ; koji startujemo, ako mu to zbog necega treba
        retf

; --------------------------------------------------------------------------
; FAT klasteri su deo sistema datoteka i oni ne obuhvataju boot sektor,
; sektore koji sadrze FAT tabele niti sektore koji sadrze root direktorijum.
; Klasteri se odnose samo na oblast podataka, koji mogu da budi bilo koja
; vrsta datoteke ili direktorijuma.
; - FAT klasteri se aresiraju od 2 do n (0 i 1 se ne koriste).
; - LBA trazenog klastera racuna se ovako:
;   (trazeni_klaster - 2) * (broj_sektora_po_klasteru) + LBA_klastera_2
;---------------------------------------------------------------------------

;---------------------------------------------------------------------------
; Zbog istorijskih razloga (efikasnije iskoriscenje tadasnjeg dragocenog
; disk prostora i minimalno pomeranje glave diska), 12-bitne FAT stavke ne
; zauzimaju po 2 bajta (jednu celu 16-bitnu rec), vec se dele medju susednim
; bajtovima na sledeci nacin:
; - Ukoliko je klaster parni, koristiti donjih 12 bitova 16-bitne reci
; - Ukoliko je klaster neparni, koristiti gornjih 12 bitova 16-bitne reci
;
; Zbog toga je velicina FAT tabele 6KB, umesto 8KB
; Racunica: FAT12 ima 2^12 stavki = 4096 = 4K
; --------  - Ako se svaka adresira sa 2 cela bajta
;             (16 bitova od kojih se koristi samo 12 donjih) to je 2B*4K=8KB
;           - Ako se svaka stavka adresira sa tacno 12 bitova (1.5 bajtova)
;             to je onda 1.5B*4K=6KB
;----------------------------------------------------------------------------

;---------------------------------
; Citanje FAT12 klastera
;---------------------------------
; Ulaz:  ES:BX -> bafer
;        SI = broj klastera
; Izlaz: SI = sledeci klaster
;        ES:BX -> sledeca adresa
;---------------------------------

CitajKlaster:
        mov     bp, sp

        lea     ax, [si-2]                 ; trazeni_klaster - 2
        xor     ch, ch
        mov     cl, [bpbSectorsPerCluster] ; CX = broj_sektora_po_klasteru
        mul     cx                         ; (trazeni_klaster - 2) * (broj_sektora_po_klasteru)

        add     ax, [ss:bp+1*2]            ; DX:AX = LBA_trazenog_klastera =
        adc     dx, [ss:bp+2*2]            ; = (trazeni_klaster-2)*(broj_sektora_po_klasteru)+LBA_klastera_2

        call    CitajSektor                ; Kopirati sektor u bafer za datoteku

        mov     ax, [bpbBytesPerSector]
        shr     ax, 4                      ; AX = broj paragrafa po sektoru
        mul     cx                         ; AX = broj procitanih paragrafa za trazeni klaster

        mov     cx, es
        add     cx, ax
        mov     es, cx                     ; ES:BX nova vrednost pointera bafera za datoteku

; --------------------------------------
; Deo karakteristican samo za FAT12
; Izlaz: SI = sledeci klaster datoteke
;---------------------------------------

        mov     ax, 3
        mul     si
        shr     ax, 1
        xchg    ax, si                    ; SI = klaster * 3 / 2 = klaster * 1.5

        push    ds
        mov     ds, [ss:bp+3*2]           ; DS = memorijski segment gde je smestena FAT
        mov     si, [ds:si]               ; SI = broj sledeceg klastera iz FAT
        pop     ds

        jnc     CitajParniKlaster         ; Parni klaster prilikom mnozenja sa 1.5 nije imao ostatak

        shr     si, 4                     ; Postavljanje bitova iz neparnog klastera na pravo mesto (0..11)
                                          ; Sada je sadrzaj SI sa istim vazecim bitovima i za parne i za neparne
CitajParniKlaster:
        and     si, 0FFFh                 ; Osigurati da su vazeci bitovi na pozicijama od 0..11 (FAT12).
        ret

;---------------------------------------------------
; Citanje sektora upotrebom BIOS INT 13h, funkcija 2
;---------------------------------------------------
; Ulaz:  DX:AX = LBA
;        CX = broj sektora koje treba procitati
;        ES:BX -> adresa bafera
; Izlaz: CF = 1 ako je nastala greska
;---------------------------------------------------

;---------------------------------------------------
; Parametri koje zahteva BIOS INT 13h, funkcija 2
;---------------------------------------------------
; AH = 2    (funkcija za citanje sektora)
; AL = broj sektora koje odjednom treba procitati
; CH = cilindar (donjih 8 od 10 bitova)
; CL = preostala dva bita cilindra + 6 bitova za sektor
; DH = glava
; DL = broj disk jedinice
; ES:BX = pointer na bafer gde se smestaju sektori
;----------------------------------------------------

;----------------------------------------------------------
; Konverzija iz LBA u CHS (Cylinder Head Sector):
;----------------------------------------------------------
; S = (LBA mod SPT) + 1
; H = (LBA / SPT) mod HPC
; C = (LBA / SPT) / HPC
; gde su:
;           S - sektor
;           H - glava
;           C - cilindar
;           SPT - broj sektora po stazi
;           HPC - broj glava po cilindru
;
; Neke BIOS verzije (Western Digital, Phoenix Technologies)
; poseduju tzv. INT 13h Extensions koje direktno rade sa LBA
; ----------------------------------------------------------

CitajSektor:
        pusha

SledeciSektor:
        mov     di, 5                   ; 5 pokusaja citanja

PokusajPonovo:
        pusha                           ; Cuvamo sve registre
        div     word [bpbSectorsPerTrack]
                ; AX = LBA / SPT          Operacija div daje rezutat deljenja u AX, a ostatak u DX .
                ; DX = LBA mod SPT  = sektor - 1
        mov     cx, dx
        inc     cx                      ; CX = sektor
        xor     dx, dx
        div     word [bpbHeadsPerCylinder]
                ; AX = (LBA / SPT) / HPC = cilindar
                ; DX = (LBA / SPT) mod HPC = glava
                                        ; Cilindar se koduje sa 10 bitova, sektor sa 6 bitova
        mov     ch, al                  ; CH = LSB 0...7 od broja cilindra
        shl     ah, 6
        or      cl, ah                  ; CL = MSB 8...9 od broja cilindra + redni broj sektora

        mov     dh, dl                  ; DH = broj glave
        mov     dl, [bsDriveNumber]     ; DL = broj diska
        mov     ax, 201h                ; AL = ukupan broj sektora koje treba procitati
                                        ; AH = 2 = funkcija za citanje
        int     13h                     ; Citaj sektor
        jnc     ZavrsenoCitanje         ; CF = 0 ako nema greske
                                        ; Nesto nije u redu. Resetovati disk.
        xor     ah, ah                  ; AH = 0 = reset funkcija
        int     13h

        popa
        dec     di
        jnz     PokusajPonovo
        jmp     short GreskaGC

ZavrsenoCitanje:
        popa
        dec     cx
        jz      KrajCitanja             ; Poslednji sektor

        add     bx, [bpbBytesPerSector] ; Podesiti ofset u baferu za sledeci sektor
        add     ax, 1
        adc     dx, 0                   ; Podesiti LBA za sledeci sektor
        jmp     short SledeciSektor

KrajCitanja:
        popa
        ret

;--------------------
; Poruke o greskama
;--------------------

GreskaGC:
        mov     si, GreskaCitanja
        jmp     short Greska
GreskaNP:
        mov     si, NijePronadjen
Greska:
        mov     ah, 0Eh
        mov     bx, 7

        lodsb
        int     10h                    ; Prvi znak poruke o gresci
        lodsb
        int     10h                    ; Drugi znak poruke o gresci

        jmp     short $                ; Zavrsetak u beskonacnoj petlji :(

;-------------------
; String konstante
;-------------------
 GreskaCitanja      db      "GC"       ; Koristimo skracenice jer nemamo dovoljno prostora
 NijePronadjen      db      "NP"       ; za kompletne poruke unutar 512 bajtova boot sektora.
                                       ; Ovo se resava tako sto boot sektor ucita program "boot loader"
                                       ; koji moze da bude znatno veci od 512 bajtova. Npr., nas STARTUP.BIN
                                       ; moze da bude boot loader!
;------------------------------------------------
; Ispuniti peostali prostor boot sektora nulama
;------------------------------------------------

               times (512-13-($-$$)) db 0

;----------------------------------------------
; Ime programa kojeg treba ucitati i izvrsiti
;----------------------------------------------

ImePrograma     db      "STARTUP BIN"   ; Ime i ekstenzija datoteke moraju da budu dopunjeni
                                        ; praznim mestima (ukupno 11 bajtova, tacka se ne racuna)

;--------------------------
; ID za kraj boot sektora
;--------------------------

                dw      0AA55h

Compiler arguments: nasm -f bin -o BOOT12.SYS boot12.asm
P.S. Am I allowed to upload bins?


text:
Q: Should I use Runtime.exec() to call bash shell script? I have some files to be appended and sorted using unix sort utility. Then we would use Java to process the sorted file.
Initially I would want to use a bash shell script to do the sorting and at the later part of the script file, I call the Java program. But my concern is that shell script doesn't have a mature log library, you can only redirect output stream and error stream.
If I want the log to be better looking, should I use Runtime.exec() to call the bash shell script part in Java so that I can log them?
The following is the shell script file:
    cd /home/app/xyz/data

    echo -n "Total number of files: "
    ls | wc -l

    for file in ls ABC_*.DAT
    do
        echo "Appending" $file "..."
        cat $file >> /home/app/xyz/data/unsorted.DAT
        echo "Moving" $file "to back up folder..."
        mv $file /home/app/xyz/data/backup
    done

    sort -t ',' -k 1,1 -k 5,7 -k 2,2r unsorted.DAT -o sorted.DAT

    CALL JAVA_PROGRAM sorted.DAT

A: IMHO if you want to use Java you should rewrite this script logic to Java to improve portability. It is a short script, so it won't be difficult. You can look here: Optimal way to sort a txt file in Java.
But it depends on a scenario and usecase. It is possible to write script with good logging ;)

A: I dont think "better logging" is a reason to execute shell scripts from java. The java process need only take the name of the file to process as argument. The acutal processing could be done directly on the terminal if possible. This way, your java program is portable too. But need to know the entire use-case to come to the right decision.

A: The shell script simply concatenates all ABC_*.DAT files in the current directory into a single file /home/app/xyz/data/unsorted.DAT, and then it sort the content to /home/app/xyz/data/unsorted.DAT into sorted.DAT. Finally, the script would call a Java program to process sorted.DAT.
You can do file reading, concatenation and sorting from Java. If you need some helper classes to process files from directories etc., then I would recommend Apache Fileutils. So, if I would recommend exploring the possibility of abandoning the shell script, consolidate all the processing into a single Java program, and avoid Runtime.exec() in this (apparently) simple case.


text:
Q: ModelChoiceField initial value from db I tried to find out how to set the initial value of a ModelChoiceField, I found many answers to this question but I don't really get them. I understand that I can set "initial" when calling the form in admin.py but then a model instance is mentioned and I am lost.
This is my models.py
class Articles(models.Model):
    headline = models.CharField('Rubrik', max_length=200)
    category = models.CharField('Kategori', max_length=200, blank=True)
    extract = models.TextField('Utdrag')
    image = ImageField('Bild', upload_to='articles', blank=True, default="")
    text = RichTextUploadingField('Text', blank=True, default="")
    added = models.DateTimeField('Publicerad', default=timezone.now,     blank=True)
    updated = models.DateTimeField('Uppdaterad',auto_now=True)
    frontpage = models.BooleanField('Visa på startsida', default=True)
    active = models.BooleanField('Aktiv', default=False)

    def save(self, *args, **kwargs):
        if self.added is None:
            self.added = timezone.now
        super(Articles, self).save(*args, **kwargs)

    def __unicode__(self):
        return '%s' % (self.headline)

    class Meta:
        verbose_name = "artikel"
        verbose_name_plural = "Artiklar"

This is my forms.py
class ArticleForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Menu.objects.order_by('name').filter(category=True))

This is my admin.py
class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')
admin.site.register(Articles, ArticlesAdmin)

When I edit the article in the admin section I want the stored value of the category to be the initial value for the ModelChoiceField. Do you get what I mean?
In admin.py there should be something like:
form = ArticleForm(initial = {'category':  instance.something})

*EDIT: I added ForeignKey as suggested
category = models.ForeignKey(Menu)

and admin.py looks like this:
class ArticlesAdmin(admin.ModelAdmin):
form = ArticleForm
list_display = ('headline','category', 'extract', 'image', 'added', 'updated', 'frontpage', 'active')

And now it's working as expected!

A: This code should work:
form = ArticleForm(initial = {'category':  pk})

pk is the stored value, pk = primary key


text:
Q: Manipulating List> into List > other format Input :
I want to manipulate List<List<Object>> in another format. Below I am providing input and expected output format
Sample Input:
List<List<Object>> data = new ArrayList<>();
List<Object> list1 = new ArrayList<>();
List<Object> list2 = new ArrayList<>();
List<Object> list3 = new ArrayList<>();
List<Object> list4 = new ArrayList<>();
List<Object> list5 = new ArrayList<>();
List<Object> list6 = new ArrayList<>();

list1.add("Siva");
list1.add("20");
list1.add("Hyd");
list1.add("India");

list2.add("Siva");
list2.add("22");
list2.add("Banglore");
list2.add("India");

list3.add("Ramesh");
list3.add("22");
list3.add("Chennai");
list3.add("India");

list4.add("Ramesh");
list4.add("24");
list4.add("Kochi");
list4.add("US");

list5.add("Suresh");
list5.add("25");
list5.add("Chennai");
list5.add("UK");

list6.add("Suresh");
list6.add("24");
list6.add("Hyd");
list6.add("UK");

data.add(list1);
data.add(list2);
data.add(list3);
data.add(list4);
data.add(list5);
data.add(list6);

I need out put in below format. I need to construct another List of list obejects in below format
Need out put in distinct names, distinct age, distinct city, distinct state
Sample output:
[[Siva,Ramesh,Suresh],[20,22,24,25],[Hyd,Banglore,Chennai,Kochi],[India,US,UK]]

A: *

*Find the number of the sets in the resulting list.

int longest = 0;
for (List<Object> items : data) {
    longest = Math.max(longest, items.size());
}

*Pre-populate the resulting list with set implementation (should be LinkedHashSet as long as the order of insertion is needed).

List<Set<Object>> result = new ArrayList<>();
for (int i = 0; i < longest; i++) {
    result.add(new LinkedHashSet<Object>());
}

*Iterate through the inner lists.  Each entry at the given index in the list is put/added to the set at the related index in the result.

for (List<Object> items : data) {
    for (int i = 0, n = items.size(); i < n; i++) {
        // ... hometask to complete ...
    }
}


text:
Q: How does an amazon ec2 ECU compare to a google app engine MHZ cpu rating? Amazon states that an ECU is approximately equal to a 2007 1200 MHZ opteron.  GAE rates their instance classes(B1,B2,B4,B8,F1,F2,F4) in MHZ.  Does a GAE MHZ approximately equal the MHZ for an ECU? Also does a GAE B8 instance rated at 4800 MHZ have all of that  4800 MHZ available on a single thread or is the 4800 MHZ just a sum of all the cpu capacity across multiple cores?

A: Google had stated in the app engine discussion group that a single thread on the highest class backend (B8) is only able to use 2.4 GHz of CPU, so a B8 backend consist of two threads of 2.4 GHz CPU each. Thus, if your app is not thread-safe, you would not notice any difference in performance between B4 and B8.
Comparing megahertz is tricky due to differences in processors that might be used, and Google does not release details about the specific hardware that they use in their GAE datacenter.
Based on experience, I think Google will migrate your app into a different server when you upgrade your backend instance to a B4/B8 class. For lower-class instances, they probably (purely speculative on my side) did some virtualizations and share a CPU with several instances. Nevertheless, you would be able to use the full CPU power of all the instance classes up to the F4/B4 class.


text:
Q: Going from 3rd to 1st fragment in the backstack: Android I have a sequence of event via which i have added three fragments to the backstack, one by one. Each of these fragments covers the full screen of the activity.
I have stored the is returned from the commit of Frag1.
Now in Frag3, based on a specific click, I want to go back to Frag1 directly and discard/pop all Fragments in between.
So, when this button is clicked i send a message to the activity which does the following:
getSupportFragmentManager().popBackStack(mFrag1Id, FragmentManager.POP_BACK_STACK_INCLUSIVE);

But i just got a blank screen, so i assume no fragment was loaded.
I even tried:
In commit - fragmentTransaction.addToBackStack("Fragment1");
and then
getSupportFragmentManager().popBackStack("Fragment1", FragmentManager.POP_BACK_STACK_INCLUSIVE);

But it doesn't work.
Could someone please help me with this?
Thanks.

A: from third fragment you should call popBackStack();
twice (one to remove third fragment  and the second to remove second fragment )
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.remove(ThirdFragment.this);
transaction.commit();
fm.popBackStack();
fm.popBackStack();

A: When you opened Fragment A and you Navigated to Fragment B and then to Fragment C and then You want to close Fragment C and B and land on Fragment A
Now in some scenario, you want to close Fragment C and Fragment B and you want to land on Fragment A... then use this logic of FragmentManager to do such task.

*

*First get the number of fragment entries in back stack (When we are adding any fragment to addToBackStack("Frag1")) at that time fragment back stack entry will increase.

so get using this
FragmentManager fmManager = activity.getSupportFragmentManager();
Log.e("Total Back stack Entry: ", fmManager.getBackStackEntryCount() + "");

Now assume, you want to close current fragment (Fragment C) and your last fragment (Fragment B) so simple logic is getBackStackEntryCount -2 and at that time your back stack entry count will be 3 (Fragment A, Fragment B and Fragment C)

Here -2 is for because we want to go 2 fragment step back (Fragment C
  and Fragment B)

So simple two line of Code is:
if (fmManager.getBackStackEntryCount() > 0) {
fmManager.popBackStack(fmManager.getBackStackEntryAt(fmManager.getBackStackEntryCount()-2).getId(), FragmentMaanger.POP_BACK_STACK_INCLUSIVE);
}

You can also do it by adding two time "popBackStack()" and will also work, but it not idle way to do this
FragmentManager fmManager = activity.getSupportFragmentManager();
fmManager.popBackStack();
fmManager.popBackStack();

A: OK so I found the issue.
FragmentManager.POP_BACK_STACK_INCLUSIVE pops all the fragments including the one whose id passed as argument.
SO for example:
getSupportFragmentManager().popBackStack(mFrag1Id, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Here it will pop everything on the stack including fragment whose id id mFrag1Id.

A: If you want user to back at the beginning fragment, code snippet below will help you.
public static void popBackStackInclusive(AppCompatActivity activity) {

    FragmentManager fragmentManager = activity.getSupportFragmentManager();

    for (int i = 1; i < fragmentManager.getBackStackEntryCount(); i++){
        try {
            int fragmentId = fragmentManager.getBackStackEntryAt(i).getId();
            fragmentManager.popBackStack(fragmentId, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } catch (Exception e) {
            Timber.d("Fragment Back Stack Error: %s", e.getLocalizedMessage());
        }
    }

}

Also if you want to prevent user to close app when no fragments at back stack, take a look at below.
@Override
public void onBackPressed() {
    FragmentManager fragmentManager = getSupportFragmentManager();

    if(fragmentManager.getBackStackEntryCount() > 1) {
        super.onBackPressed();
    } else {
        // TODO: Show dialog if user wants to exit app or;
        //finish();
    }
}


text:
Q: multiple pagination in django class based view The code below paginates the queryset but how can I paginate context['guser1']
class AuthorList(ListView):
    template_name = 'authorList.html'
    paginate_by = 10
    queryset = Author.objects.order_by('date')

def get_context_data(self, **kwargs):
    context = super(AuthorList, self).get_context_data(**kwargs)
    if int(self.kwargs['user_id']) != self.request.user.id:
        raise PermissionDenied
    if self.request.user.username == 'guest':
        raise PermissionDenied
    context['guser1'] = Author.objects.order_by('date').filter(
                 real_date__lte=datetime.now()).filter(
                 created_by=int(self.kwargs['user_id']))

    context['guser'] = User.objects.filter(pk=int(self.kwargs['user_id']))
    return context


text:
Q: How to fix settimeout memory leak problem in javascript I have a JS function like this
function check() {
    ...do something
}

Now, I want to run it when script start, and at start of everyday (00:00:01 everyday). My code now look like this
function check() {
    ...do something

    let today = new Date();
    let tomorrow = new Date();
        tomorrow.setHours(0,0,1,0);
        tomorrow.setDate(tomorrow.getDate()+1);

    console.log("next check in", tomorrow-today);
    setTimeout(() => { check() }, tomorrow-today);
}
check();

I'm using setTimeout inside check(). I think it's bad code because it will create a loop, and function check() will never been cleanup. How to fix it ?

A: You are right that uncontrolled recursion could cause exhaustion of resources due to the stack growing indefinitely.  For example, the following Javascript program will crash after check() is executed sufficient times without first returning:
function check() {
  check();
}
check();

The following code will not crash in this way:
function check() {
  setTimeout(check, 1000);
}
check();

This code can run indefinitely without exhausting the stack because each time check() is run, it is allowed to run to completion and return before it is run in the future.
This works because the setTimeout() function doesn't directly run check().  Instead, it tells the Javascript runtime to schedule an execution of check() for 1s into the future.  When it and check() have completed, the Javascript stack becomes empty.  1s later, the execution of check() is queued and eventually executed as long as the Javascript stack is clear.
Since the Javascript stack must be clear before check() can run, stack overflows are avoided.

A: You could add the function clearTimeout(timer):
let timer = setTimeout(() => check());

clearTimeout(timer);


text:
Q: How can I delete the row having specific contiditon? I want to delete the row that is column 'revenue' = 0 or 'Budget' = 0 from the movie table
so I tried this code.
movies[(movies['revenue'] == 0) or (movies['Budget'] == 0)]

Then, I got a value error
So I tried this code as well
columns = ['budget', 'revenue']
df = movies.replace(0, pd.np.nan).dropna(axis=0, how='any', subset = columns).fillna(0).astype(int)

also I got an Future warning " The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead.
plus, value error that traceback

A: Try this, and use | bitwise operator (means or):
new = movies[(movies['revenue'] != 0) | (movies['budget'] != 0)]

The code will create a new df with the rows that are not 0 in column or not 0 in budget.
Note that != means not equal. For extra information on operators, I find this link clear: https://www.w3schools.com/python/python_operators.asp

A: You need to change the below line -
drop_idx = movies[(movies['revenue'] == 0) or (movies['Budget'] == 0)].index

to
drop_idx = movies[(movies['revenue'] == 0) | (movies['Budget'] == 0)].index

Once you have the drop indexes you can use drop to delete the indexes
movies = movies.drop(index=drop_idx)

A: You can't use the or operator there, you have to use the logical or | sign:
movies = movies[(movies['revenue'] == 0) & (movies['Budget'] == 0)]

Edit:
If you want to remove the rows with 0, try using the ~ sign:
movies = movies[~(movies['revenue'] == 0) & ~(movies['Budget'] == 0)]

I use & since OP said in the comments that he needs &


text:
Q: Jquery each - Uncaught RangeError: Maximum call stack size exceeded I have a function that uses each but the problem is that I want it runs or loops 14 times, but it loops more than 14 times until gives error
Uncaught RangeError: Maximum call stack size exceeded

As you see in the image below it doesn't stop at 14 and starts over again at 0 , 1 ,2  etc...

I have tried
 if(index = 14){
   return false;
 }

also i have try break;
At the moment my code that gives the error is this:
  var type = [];

  type[1] = $("#type_1").val();
  type[2] = $("#type_2").val();
  type[3] = $("#type_3").val();
  type[4] = $("#type_4").val();
  type[5] = $("#type_5").val();
  type[6] = $("#type_6").val();
  type[7] = $("#type_7").val();
  type[8] = $("#type_8").val();
  type[9] = $("#type_9").val();
  type[10] = $("#type_10").val();
  type[11] = $("#type_11").val();
  type[12] = $("#type_12").val();
  type[13] = $("#type_13").val();
  type[14] = $("#type_14").val();

  $.each(type, function( index, type ) {
    console.log( index + ": " + type );
  });

i hope that i can just loop with each function in the array and nothing more!
Thanks for the help.


text:
Q: Show that the distance between these two sets is not bounded. I have a homework question that asks:
"Consider the curve $\gamma : [1, \infty] \to \mathbb{R}^2$ defined by $\gamma (t) = \langle t \cos (\ln t), t \sin (\ln t) \rangle$.  Show that this curve is not a bounded distance from a geodesic."
It looks a little cryptic, so here is how I decoded the statement.  Say I have two points $p_1 = \gamma (t_1)$ and $p_2 = \gamma (t_2)$ on the curve (say $t_1 < t_2$).  I get the straight line (a.k.a. the geodesic) between them to be
$$ D = \{ (1-t) p_1 + t p_2 : t \in [0, 1] \}. $$
On the other hand, if I follow the curve $\gamma$, I get the set
$$ G = \{ \gamma (t) : t \in [t_1, t_2] \}. $$
Now the question amounts to showing
$$ \sup_{d \in D, g \in G} \{ dist(d, g) \} $$
is not bounded. I think this is the way to go about the question, but I don't know where to go from here.
EDIT:
The supremum will of course be bounded for fixed $p_1$ and $p_2$, but I want it to depend on the choice of points $p_1$ and $p_2$ somehow.  In other words, the curve $\gamma$ gets arbitrarily far away from straight lines connecting points of $\gamma$.

A: (1) Consider a line $\{p+ tv\}$ so that if $w\cdot v=0,\ |w|=1$,
then
$$ (p+tv)\cdot w =p\cdot w $$ for all pt in a line
This line determines two half planes $$ \{ q| w\cdot q \leq\ (or\
\geq )\ p\cdot w \} $$
(2) Assume that the curve $\gamma$ is bounded distance from some
geodesic Then it is in some half plane $$ (\gamma (t)-p)\cdot w \leq
0 $$ for some $p$ and some $w=(w_1,w_2)$
In other words $$w_1t\cos\ \ln\ t+w_2t\sin\ \ln\ t \leq C$$ for some
$C$ By considering $t$ where $ln\ t=2n\pi + \frac{\pi}{2} $ or
$2n\pi + \frac{3\pi}{2}$ we have the term $w_2t\sin\ \ln\ t$ which
is large Hence we have a contradiction.


text:
Q: What is name of the timer/counter overflow interrupt in stm32 I am using timer in input capture mode in STM32 micro with keil compiler, and I want to trigger an interrupt whenever counter register of the dedicated timer overflows.
Could anyone please tell me how i can do that? what is the name of this interrupt?
Note: I am using hal functions.

A: Please check out the (exact) controller type you are using on the STM homepage (you can start from here:
https://www.st.com/en/microcontrollers-microprocessors/stm32-32-bit-arm-cortex-mcus.html
On the product page for your controller, you'll find a useful list of PDFs under "Resources", especially

*

*the Reference Manual (find the register descriptions in the TIM description of the timer you use)

*a list of Application Notes, which are relevant for all STM32 families, especially

*

*AN4776
General-purpose timer cookbook for STM32 microcontrollers
https://www.st.com/resource/en/application_note/dm00236305-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf
and

*AN4013
STM32 cross-series timer overview
https://www.st.com/resource/en/application_note/dm00042534-stm32-crossseries-timer-overview-stmicroelectronics.pdf
Looking for the correct library functions, you can use STM32CubeMX to configure the timers in a GUI and have the correct driver codes generated for you.
Good luck!


text:
Q: How do I launch gnome's print screen dialog without using the PrtScn key in recent versions of Gnome? I use a laptop from linovo where they replaced the Menu key with PrtScn. I restored the menu key through XKB - which fortunately still works with Wayland Gnome - but lost the dedicated print-screen key as a result. See this question for a picture of the problem.
To get around the lack of a PrtScn key, I used to run gnome-screenshot -i from the terminal. Unfortunately, this command was removed in whatever version of Gnome that shipped with Ubuntu 22.04. I tried guessing the command in Gnome's "Run a Command" dialog (i.e Alt+F2`) with little success.
How do access the screenshot functionality in modern versions of gnome without using the dedicated keyboard key?

A: Next to the option you found yourself, there is another way. You can reassign the keybindings to take a screenshot in "Settings", "Keyboard", then "View and Customize shortcuts. You will find a "Screenshots" section there, where you can change the default keybindings to something else.
In Ubuntu 22.04, screenshots is not anymore a separate tool. It is a function integrated in the code of Gnome Shell itself (very much like Gnome Shell extensions also integrate into the Gnome Shell code).

A: Typing "screenshot" in Gnome's Start Menu - the screen that appears when you press the windows keys - did the trick.


text:
Q: "a car of his son" is wrong to use/but/ "a friend of mine" is alright? There's a question asking which answer is correct in "He uses [a car of his son /his son's car]."
While I know the right one is 'his son's car', I also remember that I surely heard of 'a friend of mine' somewhere and it was alright to use the 'of+mine' there. So... what makes the former is wrong to use but the latter is alright?

A: A car of his son is a perfectly good, grammatical, comprehensible, Englsh phrase. It's just not one that any English speaker would use in normal circumstances.
However, a car of his son's is idiomatic, and implies that his son may have more than one car. Note that this is parallel with a friend of mine, in that mine is possessive, like son's.

A: "He uses a car of his son." means the son has more than one car.
"He uses the car of his son". is fine but generally, items that are owned can take the possessive apostrophe s. As in: He uses his son's car. [the son only has one car]

*

*The son owns a garage and the police found a car of his son [or one of his son's cars] near the crime scene.

Whereas: a friend of mine means: not a friend of someone else (for example, a friend of yours) and is one person in the group of people that are "my friends".
A friend of mine=one of my friends.
A car of mine=one of my cars.
My friend [not of mine] is just my friend, not my enemy. There is no idea of group, here.

*

*A car of mine was used in the drag race and I had not given the driver permission to use it!
A car of mine implies I have more than one car.


text:
Q: Remove Dynamic Table row in jQuery isn't working I'm trying to make dynamic table with javascript that elements can be dynamically added and removed with it.
Now, the remove function doesn't work probably.
I've tried .parent().parent().remove();
.parents("tr").remove();
.closest("tr").remove();
but they don't work.
The code to append to table :
$("table tbody").append("
<input type='hidden' name='label[]' value='" + $(".inputTitle").val() + "' /><input type='hidden' name='htmlText[]' value=\"" + html + "\" />" + html + "	" + $(".inputTitle").val() + "	" + typeName + " ( " + crArabic + " )
");
The Removal Code :
$("table tbody tr").on("click", ".deleteRow", function () {
    $(this).parent().parent().remove();
});

The expected results to this is to add and remove table rows dynamically. However, the removing event isn't working.

A: You may have to read this SO answer Difference between $(document).on("click", "selector", function …); and $("selector").on("click", function …) and change your code to:
$(document).on("click", ".deleteRow", function () { $(this).parent().parent().remove(); });


text:
Q: Finding the automorphisms of $S_3$ by looking at the orders of the elements
Show that the symmetric group of degree 3 $S_3$ has 6 automorphisms.

I can understand the argument that each transposition must permute. 3 transpositions gives $3! = 6$.
But the argument given in my textbook says the following.

$S_3$ can be represented as $\{1, \sigma, \sigma ^2, \tau, \tau\sigma, \tau\sigma ^2\}$ (i.e. isomorphic to the dihedral group of order 6), where $o(\sigma)=3$ and $o(\tau)=2$. Here I denote $o(x)$ to mean the order of the element $x$. So if $\theta$ is an automorphism then $o(\theta(\sigma))=o(\sigma)=3$, so $\theta(\sigma)=\sigma \text{ or } \sigma^2$ because $o(\sigma)=o(\sigma ^2)=2$.

I understand the argument up to here, but what follows I don't understand.

Similarly $\theta(\tau)=\tau, \tau\sigma \text{ or } \tau\sigma ^2$

They conclude that there are at most $2\cdot 3=6$ choices for $\theta$, which completes the solution based on a previous observation that $|\text{inn}S_3|=6$ and $\text{inn}S_3\subseteq\text{aut}S_3$.
My confusion is that I computed $o(\tau\sigma)$ and $o(\tau\sigma ^2)$ to be $6$, not $2$, whereas $o(\tau)=2$. Using this logic, there should be $1\cdot2\cdot1\cdot2=4$ automorphisms, where the identity element is sent to itself and $\tau$ is sent to itself.
It would really help me if somebody could list each of the 6 automorphisms so that I can clearly see why there are 6.
I apologize if this question has been answered before; I'm in a rush.

A: Note that $S_3$ is generated by $(1\ 2)$ and $(1\ 2\ 3)$: powers of either $(1\ 2)$ or $(1\ 2\ 3)$ account for $4$ elements of $S_3$ directly, and:
$(1\ 2\ 3)(1\ 2) = (1\ 3)$
$(1\ 2)(1\ 2\ 3) = (2\ 3)$
account for the remaining $2$.
So any homomorphism $\phi:S_3 \to S_3$ is completely determined by $\phi((1\ 2\ 3))$ and $\phi((1\ 2))$.
Now an automorphism, being an isomorphism, must preserve the order of elements. Thus we have only $2$ (at most) possible choices for what $\phi((1\ 2\ 3))$ can be, and only $3$ (at most) possible choices for what $\phi((1\ 2))$ might be. This gives at most $6\ (= 2\cdot 3)$ possible automorphisms. Since the inner automorphisms comprise $6$ distinct automorphisms, this must be all of them. Using $a = (1\ 2\ 3)$ and $b = (1\ 2)$, here are all $6$:
$1.\ \phi(a) = a, \phi(b) = b\\2.\ \phi(a) = a,\phi(b) = ab\\3.\ \phi(a) = a,\phi(b) = a^2b\\4.\ \phi(a) = a^2,\phi(b) = b\\ 5.\ \phi(a) = a^2,\phi(b) = ab\\6.\ \phi(a) = a^2,\phi(b) = a^2b$

A: By definition $S_3=\{f:\{1,2,3\}\to\{1,2,3\}\,|\, f \text{ is invertible}\}$. Let $\sigma:\{1,2,3\}\to\{1,2,3\}$ be the map defined by $\sigma(1)=2$, $\sigma(2)=3$, and $\sigma(3)=1$, and let $\tau:\{1,2,3\}\to\{1,2,3\}$ be map defined by $\tau(1)=2$, $\tau(2)=1$, $\tau(3)=3$. A straightfoward calculation shows that $|S_3|=6$, and hence if we find $6$ destinct maps we know we have found all of them. A tedious (but straightforward) calculation shows that $S_3=\{1,\sigma,\sigma^2,\tau,\tau\sigma,\tau\sigma^2\}$ where $1$ denotes the identity map, and furthermore that $\sigma^3=\tau^2=\sigma\tau\sigma\tau=1$.
Note that from this we can deduce that:
$$\tau\sigma\tau\sigma=\tau\sigma\tau\sigma\tau\tau=\tau^2=1$$
$$\tau\sigma^2\tau\sigma^2=\tau\sigma\sigma\tau\sigma\tau\tau\sigma=\tau\sigma\tau\sigma=1$$
and hence $o(\tau\sigma)=o(\tau\sigma^2)=2$.
The six automorphisms turn out to be conjugation by each element in $S_3$.
i.e
$$x\mapsto x$$
$$x\mapsto \sigma x \sigma^2$$
$$x\mapsto \sigma^2 x \sigma$$
$$x\mapsto \tau x \tau$$
$$x\mapsto \tau \sigma x \tau \sigma$$
$$x\mapsto \tau\sigma^2 x \tau\sigma^2.$$
To understand why this is so note that for any group $G$ the group $G/Z(G)$ is isomorphic to the group of inner automorphisms of $G$, and hence since $S_3$ has trivial center each element determines a different automorphism.


text:
Q: How to perform $near-like queries for array of lat/lng pairs with mongomapper I have a trip model that contains an array of lat/lng pairs
class Trip
  include MongoMapper::Document

  key :route, Array, # example: [[45,-122], [45.5, -122.5], [45, -123]]
  ...
end

I would like to perform $near-type queries on the route array, which should be possible according to the documentation .
I would like to find the route nearest to a certain point.
def self.nearest_to(coords)
  where(:route => {'$near' => coords}).limit(1).first
end

But this does not work, I get an error that says:
Mongo::OperationFailure: can't find special index: 2d for: { route: { $near: [ 32.80909, -117.1537 ] } }
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/mongo-1.3.1/lib/mongo/cursor.rb:101:in `next_document'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/mongo-1.3.1/lib/mongo/cursor.rb:248:in `each'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/mongo-1.3.1/lib/mongo/cursor.rb:267:in `to_a'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/mongo-1.3.1/lib/mongo/cursor.rb:267:in `to_a'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/plucky-0.3.8/lib/plucky/query.rb:76:in `all'
    from /Users/lash/code/rails3projects/rideshare/app/models/trip.rb:20:in `nearest'
    from (irb):10
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
    from /Users/lash/.rvm/gems/ruby-1.9.2-p290@rails3.0.9/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

What is the correct way to query multi-location documents with mongomapper?

A: The correct answer - as of today - is that you can't. The ruby driver does not yet support mongo 1.3.3, so this type of geo-location query simply isn't possible.
Here is one example of how one might work around the issue in the mean time.
class Trip
  include MongoMapper::Document

  key :route, Array # example: [[45,-122], [45.5, -122.5], [45, -123]]
  ...

  scope :passes_near, lambda {|coords| where(:id => {'$in' => Trip.near(coords)}) }

  def self.near(coords, options = {})
    options[:radius] ||= 60
    case coords
      when Array; coords
      when String; coords = Geocoder.coordinates(coords)
    end

    trips = {}
    Trip.all.each do |trip|
      dist = trip.route.map{|point| Geocoder::Calculations::distance_between(point, coords)}.min
      trips[trip.id] = dist
    end
    return trips.select {|k, v| v < options[:radius]}.keys
  end
end

To find all trips that go near Seattle ([47.6062095, -122.3320708]) I would simply type:
Trip.passes_near("Seattle, WA")
=> #<Plucky::Query _id: {"$in"=>[*lots of ids*}, transformer: #...>

Since a plucky object is returned it would be simple to chain queries together.

A: You should find some answers on $near at this nice little tutorial: http://mongly.com/
db.treasures.find({location: {$near: [20, -20]}});


text:
Q: Java ArrayList using in JSTL() i want foreach items add arrays list
<sql:query var="query"  dataSource="${db}">

   select fname, lname from users where fname='ali'

</sql:query>

<c:forEach items="${query.rows}" var="result">

 <%

  ArrayList l= new ArrayList();
  l.add("${result.fname}");
  l.add("${result.lname}");

 for(int i=0; i<l.size(); i++)
   {
   out.println(l.get(i));
   }
 %>

</c:forEach>

output result:
${result.fname} ${result.lname}  ${result.fname} ${result.lname}  ${result.fname} ${result.lname}

what is wrong ?

A: You can't use jstl inside scriptlet..
Save the value of ${result.fname} using <c:set> in page  scope. And use the variable inside the scriptlet.
e.g.
<c:forEach items="${query.rows}" var="result">
     <c:set var="lname" value="${result.lname}"  />
     <c:set var="fname" value="${result.fname}" />

     <%
         ArrayList l= new ArrayList();

         l.add((String)pageContext.getAttribute("fname"));
         l.add((String)pageContext.getAttribute("lname"));

         for(int i=0; i<l.size(); i++)
         {
             out.println(l.get(i));
         }
     %>

</c:forEach>

For more information, http://docs.oracle.com/javaee/1.4/tutorial/doc/JSTL4.html
http://javapapers.com/jsp/jsp-life-cycle-explain/
http://docs.oracle.com/cd/E13222_01/wls/docs81/taglib/handler.html
UPDATE
EL attributes are stored in the scope - page, request, session, application
The <c:set> tag example doesn't specify a scope, so therefore you could get it like this:
 <c:set var="fname" value="${result.fname}" />

  <%
       String fname = (String)pageContext.getAttribute("fname");
       System.out.println(fname);
  %>

alternatively exploit the feature of the useBean tag that creates a scriptlet variable:
<c:set var="fname" value="${result.fname}" />
<jsp:useBean id="fname" type="java.lang.String"/>
<%
  System.out.println(fname);
 %>

Note that the EL variable and the Scriptlet variable are initially pointing at the same String.
But changing the string in scriptlet code will change the value it is pointing at, while leaving the EL variable untouched.

A: As you are adding ${result.fname} using quotes. JVM considers it as string literals. So you are getting result like this.

A: use foreach loop in jstl for eg check out the eg here!
and avoid java code in jsp page check out this link
How to avoid Java code in JSP files?


text:
Q: Finding a 'part' word with RegEx I want to find chapter and find words in a sentence.
sentence1 = 'chapter1'
sentence2 = 'chapter 1'
sentence3 = 'part1'
sentence4 = 'part 1'
sentence5 = 'party'

re.search('((\bchapter\b|\bpart$\b)|[ ^a-z*,0-9]+)+', sentence5)

But I don't want to get some words like 'part(y)'. I mean code should find first 4 sentences but 5th sentence shouldn't be find.

A: $ is end of line, not word boundary.
^((\bchapter)|(\bpart))\s?[0-9]


text:
Q: Efficient treatment of tuples as fixed-size vectors In Chapel, homogeneous tuples can be used as if they were small "vectors" ( e.g., a = b + c * 3.0 + 5.0; ).
However, because various math functions are not provided for tuples, I have tried writing a function for norm() in several ways and compared their performance. My code is something like this:
proc norm_3tuple( x: 3*real ): real
{
    return sqrt( x[1]**2 + x[2]**2 + x[3]**2 );
}

proc norm_loop( x ): real
{
    var tmp = 0.0;
    for i in 1 .. x.size do
        tmp += x[i]**2;
    return sqrt( tmp );
}

proc norm_loop_param( x ): real
{
    var tmp = 0.0;
    for param i in 1 .. x.size do
        tmp += x[i]**2;
    return sqrt( tmp );
}

proc norm_reduce( x ): real
{
    var tmp = ( + reduce x**2 );
    return sqrt( tmp );
}

//.........................................................

var a = ( 1.0, 2.0, 3.0 );

// consistency check
writeln( norm_3tuple(     a ) );
writeln( norm_loop(       a ) );
writeln( norm_loop_param( a ) );
writeln( norm_reduce(     a ) );

config const nloops = 100000000;  // 1E+8

var res = 0.0;
for k in 1 .. nloops
{
    a[ 1 ] = (k % 5): real;

    res += norm_3tuple(     a );
 // res += norm_loop(       a );
 // res += norm_loop_param( a );
 // res += norm_reduce(     a );
}

writeln( "result = ", res );

I compiled the above code with chpl --fast test.chpl (Chapel v1.16 on OSX10.11 with 4 cores, installed via homebrew). Then, norm_3tuple(), norm_loop(), and norm_loop_param() gave almost the same speed (0.45 sec), while norm_reduce() was much slower (about 30 sec). I checked the output of top command, and then norm_reduce() was using all 4 cores, while other functions use only 1 core. So my question is...

*

*Is norm_reduce() slow because reduce works in parallel
and the overhead for parallel execution is much
greater than the net computational cost for this small tuple?

*Given that we want to avoid reduce for 3-tuples, the other three routines run essentially with the same speed. Does this mean that explicit for-loops have negligible cost for 3-tuples (e.g., via loop unrolling enabled by --fast option)?

*In norm_loop_param(), I have also tried using param keyword for the loop variable, but this gave me little or no performance gain. If we are interested in homogeneous tuples only, is it not necessary to attach param at all (for performance)?

I'm sorry for many questions at once, and I would appreciate any advice/suggestions for efficient treatment of small tuples. Thanks very much!

A:
Is norm_reduce() slow because reduce works in parallel and the overhead for parallel execution is much greater than the net computational cost for this small tuple?

I believe you are correct that this is what's going on.  Reductions are executed in parallel, and Chapel currently doesn't attempt to do any intelligent throttling to squash this parallelism when the work may not warrant it (as in this case), so I think you're suffering from too much task overhead to do almost no work other than coordinating with the other tasks (though I am surprised that the magnitude of the difference is so large... but I also find I have little intuition for such things).  In the future, we'd hope that the compiler would serialize such small reductions in order to avoid these overheads.

Given that we want to avoid reduce for 3-tuples, the other three routines run essentially with the same speed. Does this mean that explicit for-loops have negligible cost for 3-tuples (e.g., via loop unrolling enabled by --fast option)?

The Chapel compiler doesn't unroll the explicit for loop in norm_loop() (and you can verify this by inspecting the code generated with the --savec flag), but it could be that the back-end compiler is.  Or that the for-loop really doesn't cost that much compared to the unrolled loop of norm_loop_param().  I suspect you'd need to inspect the generated assembly to determine which is the case.  But I also expect that back-end C compilers would do decently with the code we generate -- e.g., it's easy for it to see that it's a 3-iteration loop.

In norm_loop_param(), I have also tried using param keyword for the loop variable, but this gave me little or no performance gain. If we are interested in homogeneous tuples only, is it not necessary to attach param at all (for performance)?

This is hard to give a definitive answer to since I think it's mostly a question about how good the back-end C compiler is.

A: Ex-post remark: actually there was a third remarkable performance surprise at the end...

Performance? Benchmark! ... always, no exceptions, no excuse
This is what makes chapel so great. Thanks a lot the Chapel team for developing and improving such great computing tool for the HPC over more than the last decade.
With a full love in true-[PARALLEL] efforts, the performance is always a result of both the design practices and underlying system hardware, never a just syntax-constructor granted "bonus".
The norm_reduce() processing systematically spends several milliseconds just to setup all the concurrency-enabled reduce computing facilities to later just generate and return a single x**2 product to the queue of results for a deferred central +-reductor-engine summation. Pretty a lot of overheads for a single 2 CLK CPU uops, isn't it?
For reasons why, one may kindly review the costs of process-scheduling details and my updated criticism of Amdahl's Law original formulation.

Code Benchmarking - has delivered actually two surprises at once:
+++++++++++++++++++++++++++++++++++++++++++++++ <TiO.IDE>.RUN
                                        3.74166
[SEQ]       norm_loop():    0.0 [us] -- 3.74166
[SEQ] norm_loop_param():    0.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 5677.0 [us] -- 3.74166

                                        3.74166
[SEQ]       norm_loop():    0.0 [us] -- 3.74166
[SEQ] norm_loop_param():    1.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 5818.0 [us] -- 3.74166

                                        3.74166
[SEQ]       norm_loop():    1.0 [us] -- 3.74166
[SEQ] norm_loop_param():    2.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 4886.0 [us] -- 3.74166

The first was reported in the original post, the second was observed after the Chapel runs were equipped with a --fast compiler switch:
+++++++++++++++++++++++++++++++++++++++++++++++ <TiO.IDE>.+CompilerFLAG( "--fast" ).RUN
                                        3.74166
[SEQ]       norm_loop():    1.0 [us] -- 3.74166
[SEQ] norm_loop_param():    2.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 7769.0 [us] -- 3.74166

                                        3.74166
[SEQ]       norm_loop():    0.0 [us] -- 3.74166
[SEQ] norm_loop_param():    0.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 9109.0 [us] -- 3.74166

                                        3.74166
[SEQ]       norm_loop():    1.0 [us] -- 3.74166
[SEQ] norm_loop_param():    1.0 [us] -- 3.74166
[PAR]:    norm_reduce(): 8807.0 [us] -- 3.74166

As always, SuperComputing2017 HPC promotes [ Reproducibility ] for every aspect published in Technical Papers or benchmarking tests.
These results were collected on Try-it-Online sponsored chapel online platform, and all interested enthusiasts are welcome to re-run and post their localhost / cluster operated performance details of the Chapel-code, so as to better document the hardware-system dependent variability of the above observed times ( for further experimentation with a ready-to-run timing decorated code, may use this link to a state-full snapshot of the TiO.IDE ).
/* ---------------------------------------SETUP-SECTION-UNDER-TEST--*/ use Time;
/* ---------------------------------------SETUP-SECTION-UNDER-TEST--*/ var aStopWATCH_SEQ: Timer;
/* ---------------------------------------SETUP-SECTION-UNDER-TEST--*/ var aStopWATCH_PAR: Timer;

proc norm_3tuple( x: 3*real ): real
{
    return sqrt( x[1]**2 + x[2]**2 + x[3]**2 );
}

proc norm_loop( x ): real
{
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_SEQ.start();
    var tmp = 0.0;
    for i in 1 .. x.size do
        tmp += x[i]**2;
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_SEQ.stop(); write(                          "[SEQ]       norm_loop(): ",
                                                                       aStopWATCH_SEQ.elapsed( Time.TimeUnits.microseconds ), " [us] -- " );
    return sqrt( tmp );
}

proc norm_loop_param( x ): real
{
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_SEQ.start();
    var tmp = 0.0;
    for param i in 1 .. x.size do
        tmp += x[i]**2;
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_SEQ.stop(); write(                          "[SEQ] norm_loop_param(): ",
                                                                       aStopWATCH_SEQ.elapsed( Time.TimeUnits.microseconds ), " [us] -- " );
    return sqrt( tmp );
}

proc norm_reduce( x ): real
{
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_PAR.start();
    var tmp = ( + reduce x**2 );
/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_PAR.stop(); write(                          "[PAR]:    norm_reduce(): ",
                                                                       aStopWATCH_PAR.elapsed( Time.TimeUnits.microseconds ), " [us] -- " );
    return sqrt( tmp );
}

//.........................................................

var a = ( 1.0, 2.0, 3.0 );

// consistency check
writeln( norm_3tuple(     a ) );
writeln( norm_loop(       a ) );
writeln( norm_loop_param( a ) );
writeln( norm_reduce(     a ) );

Scaling:
 [LOOP] norm_3tuple():       45829.0 [us] -- result = 4.30918e+06 @   1000000 loops.
 [LOOP] norm_3tuple():      241680   [us] -- result = 4.30918e+07 @  10000000 loops.
 [LOOP] norm_3tuple():     2387080   [us] -- result = 4.30918e+08 @ 100000000 loops.

[LOOP]  norm_loop():         72160.0 [us] -- result = 4.30918e+06 @   1000000 loops.
[LOOP]  norm_loop():        755959   [us] -- result = 4.30918e+07 @  10000000 loops.
[LOOP]  norm_loop():       7783740   [us] -- result = 4.30918e+08 @ 100000000 loops.

[LOOP]  norm_loop_param():   34102.0 [us] -- result = 4.30918e+06 @   1000000 loops.
[LOOP]  norm_loop_param():  365510   [us] -- result = 4.30918e+07 @  10000000 loops.
[LOOP]  norm_loop_param(): 3480310   [us] -- result = 4.30918e+08 @ 100000000 loops.

-------------------------------------------------------------------------1000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():     5851380   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     5884600   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6163690   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6029860   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6083730   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6132720   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6012620   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6379020   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     5923550   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     6144660   [us] -- result = 4309.18     @      1000 loops.
[LOOP]  norm_reduce():     8098380   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     6215470   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     5831670   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     6124580   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     6092740   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     5811260   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     5880400   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     5898520   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     6591110   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     5876570   [us] -- result = 4309.18     @      1000 loops. [--fast]
[LOOP]  norm_reduce():     6034180   [us] -- result = 4309.18     @      1000 loops. [--fast]

-------------------------------------------------------------------------2000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    12434700   [us] -- result = 8618.36     @      2000 loops.

-------------------------------------------------------------------------3000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    17807600   [us] -- result = 12927.5     @      3000 loops.

-------------------------------------------------------------------------4000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    23844300   [us] -- result = 17236.7     @      4000 loops.

-------------------------------------------------------------------------5000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    30557700   [us] -- result = 21545.9     @      5000 loops.
[LOOP]  norm_reduce():    30523700   [us] -- result = 21545.9     @      5000 loops.
[LOOP]  norm_reduce():    29404200   [us] -- result = 21545.9     @      5000 loops.
[LOOP]  norm_reduce():    29268600   [us] -- result = 21545.9     @      5000 loops. [--fast]
[LOOP]  norm_reduce():    29009500   [us] -- result = 21545.9     @      5000 loops. [--fast]
[LOOP]  norm_reduce():    30388800   [us] -- result = 21545.9     @      5000 loops. [--fast]

-------------------------------------------------------------------------6000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    37070600   [us] -- result = 25855.1     @      6000 loops.

-------------------------------------------------------------------------7000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    42789200   [us] -- result = 30164.3     @      7000 loops.

---------------------------------------------------------------------8000--------{--fast}---------------------------------------------------------------------
[LOOP]  norm_reduce():    50572700   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    49944300   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    49365600   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():   ~60+                                                                 // exceeded the 60 seconds limit and was terminated [Exit code: 124]
[LOOP]  norm_reduce():    50099900   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    49445500   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    49783800   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    48533400   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    48966600   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    47564700   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    47087400   [us] -- result = 34473.4     @      8000 loops.
[LOOP]  norm_reduce():    47624300   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():   ~60+                                                        [--fast] // exceeded the 60 seconds limit and was terminated [Exit code: 124]
[LOOP]  norm_reduce():   ~60+                                                        [--fast] // exceeded the 60 seconds limit and was terminated [Exit code: 124]
[LOOP]  norm_reduce():    46887700   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():    46571800   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():    46794700   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():    46862600   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():    47348700   [us] -- result = 34473.4     @      8000 loops. [--fast]
[LOOP]  norm_reduce():    46669500   [us] -- result = 34473.4     @      8000 loops. [--fast]

A third surprise appeared - from going into a forall do { ... }:
While the [SEQ]-nloops-ed code was awfully devastated from the associated add-on overheads, a slight problem re-formulation has shown a very different performance levels achievable even on a single-CPU platform ( the more should the performance gain on multi-CPU code-execution ) and the very effect the --fast compiler-switch has generated here:
/* ---------------------------------------SETUP-SECTION-UNDER-TEST--*/ use Time;
/* ---------------------------------------SETUP-SECTION-UNDER-TEST--*/ var aStopWATCH_LOOP: Timer;

config const nloops = 100000000;  // 1E+8
       var   res: atomic real;
             res.write( 0.0 );
//------------------------------------------------------------------// PRE-COMPUTE:
var A1:    [1 .. nloops] real;                                      // pre-compute a tuple-element value
forall k in 1 .. nloops do                                          // pre-compute a tuple-element value
    A1[k] = (k % 5): real;                                          // pre-compute a tuple-element value to a ( k % 5 ), ex-post typecast to real

/* ---------------------------------------------SECTION-UNDER-TEST--*/  aStopWATCH_LOOP.start();
forall i in 1 .. nloops do
{               //  a[1] = (  i % 5 ): real;                        // pre-compute'd
   res.add( norm_reduce( ( A1[i],            a[1], a[2] ) ) );      //     atomic.add()
// res +=   norm_reduce( ( (  i % 5 ): real, a[1], a[2] ) );        // non-atomic
//:49: note: The shadow variable 'res' is constant due to forall intents in this loop

}/* ---------------------------------------------SECTION-UNDER-TEST--*/ aStopWATCH_LOOP.stop(); write(
  "forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }: ",     aStopWATCH_LOOP.elapsed( Time.TimeUnits.microseconds ), " [us] -- " );
/*
   --------------------------------------------------------------------------------------------------------{-nloops-}-------{--fast}-------------
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:     7911.0 [us] -- result =     320.196 @       100 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:     8055.0 [us] -- result =    3201.96  @      1000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:     8002.0 [us] -- result =   32019.6   @     10000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:    80685.0 [us] -- result = 3.20196e+05 @    100000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:   842948   [us] -- result = 3.20196e+06 @   1000000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  8005300   [us] -- result = 3.20196e+07 @  10000000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }: 40358900   [us] -- result = 1.60098e+08 @  50000000 loops.
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }: 40671200   [us] -- result = 1.60098e+08 @  50000000 loops.

   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  2195000   [us] -- result = 1.60098e+08 @  50000000 loops. [--fast]

   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4518790   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  6178440   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4755940   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4405480   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4509170   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4736110   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4653610   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4397990   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
   forall .. do { res.add( norm_reduce( aPreComputedTUPLE ) ) }:  4655240   [us] -- result = 3.20196e+08 @ 100000000 loops. [--fast]
  */