text:
Q: Nodejs and Express, use res.send() from a worker thread In Nodejs, using Express as a server, I offload a heavy computation onto a worker thread.
From the main application, I call the worker thread like this:
// file: main.js

const { Worker } = require("worker_threads");

function runService(fileName, workerData) {
    return new Promise((resolve, reject) => {
        const worker = new Worker(fileName, { workerData });
        worker.on("message", resolve);
        worker.on("error", reject);
        worker.on("exit", code => {
            if (code !== 0)
                reject(new Error(`Worker stopped with exit code ${code}`));
        });
    });
}

router.get("/some_url", async function(req, res) {
    const result = await runService(
        "./path/to/worker.js",
        { query: req.query, user: req.user } // using { req } causes an error
    );
});

The worker looks like this:
// file: worker.js

const { workerData, parentPort } = require('worker_threads');
const { query, user } = workerData;

async function run() {
    const result = await generateLotsOfData(query, user);

    parentPort.postMessage(result);

    // What I would like to do here (doesn't work): res.send(result);
}

The worker generates a huge amount of data and "postMessage" causes a server error.
Is there a way to send this data from the worker thread directly to the client, using res.send() or something alike?
(instead of using postMessage and then sending from the main thread)?

A: It seems not possible to send directly from the worker-tread to the client.
In the end, I used child-process (instead of worker-treads), and send the result back to the main tread, and then to the client.
// file: main.js

var child_process = require('child_process');

// Run a worker thread
function runService(fileName, workerData) {
    return new Promise((resolve, reject) => {

        const worker = child_process.fork(fileName);

        worker.on('message', function(message) {
            if (message.ready) {
                // worker is ready to receive data
                worker.send(workerData);
            } else {
                // worker finished it's calculations, send the data to the client
                resolve(message);
            }
        });

        worker.on("error", function(x) {
            console.log('error', x);
            resolve({status: 500});
        });
        worker.on("close", function(y) {
            console.log('close', y);
        });
        worker.on("exit", function(code) {
            if (code == 0) {
                console.log('report ran successfully');
            } else {
                console.log('report FAILED');
                resolve({status: 500});
            }
        });
    });
}

And in the worker:
process.on('message', run);
process.send({ready: true});

async function run(workerData) {
    try {
        const result = doSomeCalculations();

        process.send({
            data: JSON.stringify(result)
        }, null, {}, function() {process.exit(0)});
    } catch(err) {
        console.error(err);
        process.exit(1); // exit the process with a failure
    }
}

// Make sure that this child_process doesn't accidentally stay in memory.
// Kill after 10 minutes. (not sure this is necessary, just to be sure)
setTimeout(function(){
    console.log('Timeout in child-process');
    process.exit(1);
}, 600000);

This actually works quite well.

A: This sample of code works :

*

*create worker

*create event handler

*sendMessage --> wrapperWorkerThreadBigComputing

*sendBack message on our main thread

*emit server response

Api routes :
app.get('/bigComputingWithWorker', (req, res) => {
     const worker = new Worker(`${__dirname}/src/wrapperWorkerThreadBigComputing.js`);
    res.set('Content-Type', 'text/html');
      worker.once("message", count => {
        res.status(200).send(`The final count :${count}`);
    });
    worker.once("error", err => {
        console.error(err);
        res.status(400).send(`error worker thread`);
    });
     worker.postMessage({coucou : 'john'});
});

wrapperWorkerThreadBigComputing
const { parentPort } = require('node:worker_threads');

console.log("* worker created");
parentPort.once('message', (message) => {
      let big = bigComputing();
      parentPort.postMessage(big);
})

function bigComputing() {
    let i = 0;
    console.log("* start big computing")
    for (i = 0; i < 300000000; i++) {
    }
    return i;
}


text:
Q: Firebase onDataChange method is not called even if the data is changed My code is as shown below:
private DatabaseReference mFirebaseDatabase;
    private FirebaseDatabase mFirebaseInstance;
    private static final String TAG = "OrderManagementFragment";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_managment, container, false);

        //get reference to the orders node
        mFirebaseDatabase = mFirebaseInstance.getReference("orders");

        // app_title change listener
        mFirebaseInstance.getReference("58ca237b2e2c211dc0c7ed9b").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Toast.makeText(getActivity(), dataSnapshot.getValue(String.class), Toast.LENGTH_LONG).show();
                Log.d(TAG, "onDataChange: " + dataSnapshot.getValue(String.class));

            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
                Log.d(TAG, "onCancelled: " + error.getMessage());
            }
        });

        return view;
    }

My credentials for firebase is as shown below:

Now, what happens here is , whenever data is changed from backend side , onDatachange method never gets called.So is there anything missing in this method?
I am testing this via android emulator, so is it the problem ?

A: I change your code, u dont need reference inconstructor becouse aplication method will know what u need.
Data is not changed becouse u no have static like textView on your layout. When you got a Toast, its start once so u cant see that its changed
 //get reference to the orders node
            mFirebaseDatabase = mFirebaseInstance.getReference();

            // app_title change listener
            mFirebaseInstance.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Toast.makeText(getActivity(), dataSnapshot.child("YOUR REFERENCE HERE")getValue(String.class), Toast.LENGTH_LONG).show();

                }

I give you example from my application:
 mDatabase = FirebaseDatabase.getInstance().getReference();
        settingsText2.setText("Loading...");
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(final DataSnapshot dataSnapshot) {
                settingsTextWithScrollView.setText(dataSnapshot.child("Youtube1").child("Text").getValue(String.class));
                settingsText2.setText(dataSnapshot.child("Youtube1").child("Information").getValue(String.class));
                settingsTextWithScrollView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openYoutubeIntent(dataSnapshot.child("Youtube1").child("Link").getValue(String.class));
                    }
                });
                settingsText3.setText(dataSnapshot.child("Youtube2").child("Text").getValue(String.class));
                settingsText4.setText(dataSnapshot.child("Youtube2").child("Information").getValue(String.class));
                settingsText3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openYoutubeIntent(dataSnapshot.child("Youtube2").child("Link").getValue(String.class));
                    }
                });
                settingsText5.setText(dataSnapshot.child("Youtube3").child("Text").getValue(String.class));
                settingsText6.setText(dataSnapshot.child("Youtube3").child("Information").getValue(String.class));
                settingsText5.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openYoutubeIntent(dataSnapshot.child("Youtube3").child("Link").getValue(String.class));
                    }
                });
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

A: its a static call like this
FirebaseDatabase database=FirebaseDatabase.getInstance();
DataBaseRefrence dbRef=database.getRefrence("nodeOfData");
DataSnapshot ds=dbRef.getChildren("gettingWhatIsInNodeOfData"); or
better yet chain them DataSnapshot
ds=FirebaseDatabase.getInstance().getRefrence("orders").getChildren();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mind transfer into the body of ape-like aliens Doing a deep dive into unsolved "story identification" questions on another forum, I came across two different people seeking this book about 10 years ago - neither got an answer. I have not been able to figure it out and thought I'd see if the brain trust here can give it a shot.
The novel or novella is from the 70s. The cover is an image of an old man's face merging with that of an ape-like alien. The story: A professor (or scientist) finds that he can send his mind/consciousness out (when asleep or meditating (?)) into the body of a juvenile member of an ape-like species on a distant world. He becomes a leader of these aliens and teaches them to use tools and develop a society. The ape-like aliens that make up his tribe are in competition with another, cro-magnon-like tribe. It is essentially an arms race between the two. The twist at the end: While awake on Earth, our protagonist discovers another human male is sending his mind into the body of the leader of the cro-magnon tribe.

A: SOLVED! After searching for what feels like millennia for this book, I finally stumbled across the cover today. This novel is John Robert Russell's Cabu (1974).
Here is the blurb: "George Piget was only human. A frail history professor with just a few months to live, he dreamed of having the power of a Caesar, the genius of a Napoleon, the ruthless cunning of a Hitler. Then one day he awoke from a deep sleep to find himself in the dark, primitive world of Cabu, where to be 'only human' was to be the highest form of life. At first he was terrified of the huge lizardlike beasts that stalked him on the vast plains, of the hairy subhuman creatures that made him one of their own. But then his memory of human history took hold, and he plotted to make his dream of world domination come true..."
And the cover, as the OPs originally described exactly:

A: Perhaps this is Jack London's short novel Before Adam (1906), with the cover image of this 1970 paperback.
Story is narrated by a modern-day human who has memories of a particular ancestor from before history, and experiences them as dreams.  It does prominently feature competition with another tribe, that of the Fire-People, who are coordinated more effectively by a leader and have more technology than the ancient protagonist's tribe, including fire and arrows.  The tool use that you mention is prominently featured starting from chapter 10: the protagonist and his companion swim on a lake by grabbing onto logs and paddling, and then use this to cross a river that they had no way to cross before that invention.  Not all details match, and in particular it does not have the twist ending that you mention.


text:
Q: Compose two Transform streams in Node.js I have a no-op Transform stream test that outputs the list of all files passed through it. Why does the following code outputs the list of files only once? How do I compose two streams properly?
var composed = test().pipe(test());
gulp.src('source/*').pipe(composed);

A: To compose streams, you pipe() the first to the second, but you also have to modify pipe() and unpipe() so they apply to the second stream.  This way additional calls to pipe() on the composed stream will use the output of the second stream instead of the first.
function compose(s1, s2) {
    s1.pipe(s2);
    s1.pipe = function (dest) {
        return s2.pipe(dest);
    }
    s1.unpipe = function (dest) {
        return s2.unpipe(dest);
    }
    return s1;
}

var composed = compose(test(), test());
gulp.src('source/*')
    .pipe( composed )  // src -> s1 -> s2
    .pipe( ... );      // s2 -> ...

A: pipe() returns the stream being piped to, not from (to allow chaining). So the second line is basically trying to pipe to the second instance of test(). What you need to do instead is:
var first = test();
first.pipe(test());
gulp.src('source/*').pipe(first);

Or:
gulp.src('source/*')
    .pipe(test())
    .pipe(test());


text:
Q: Sumologic integration on Artifactory How do I get past the 401, Unauthorized error from Artifactory when working with Sumologic integration?
I tell Artifactory to:

*

*Create a new client connection, which forwards me to the Sumologic website.

*Agree to the service agreement and click 'Access Dashboard'.

After a delay, I get 401, Unauthorized from Artifactory (not Sumologic).
I don't find anything in the log, so I turn to the great collective...WTH did I screw up?


text:
Q: understand process memory map in linux I am trying to understand the basic of linux process memory layout and i got this program:
#include <stdio.h> // standard io
#include <stdlib.h> // C standard library
#include <pthread.h> // threading
#include <unistd.h> // unix standard library
#include <sys/types.h> // system types for linux

// getchar basically is like "read"
// it prompts the user for input
// in this case, the input is thrown away
// which makes similar to a "pause" continuation primitive
// but a pause that is resolved through user input, which we promptly throw away!
void * thread_func (void * arg) {

    printf("Before malloc in thread 1\n");
    getchar();
    char * addr = (char *) malloc(1000);
    printf("After malloc and before free in thread 1\n");
    getchar();
    free(addr);
    printf("After free in thread 1\n");
    getchar();

}

int main () {

    char * addr;
    printf("Welcome to per thread arena example::%d\n", getpid());
    printf("Before malloc in the main thread\n");
    getchar();
    addr = (char *) malloc(1000);
    printf("After malloc and before free in main thread\n");
    getchar();
    free(addr);
    printf("After free in main thread\n");
    getchar();

    // pointer to the thread 1
    pthread_t thread_1;
    // pthread_* functions return 0 upon succeeding, and other numbers upon failing
    int pthread_status;

    pthread_status = pthread_create(&thread_1, NULL, thread_func, NULL);

    if (pthread_status != 0) {
        printf("Thread creation error\n");
        return -1;
    }

    // returned status code from thread_1
    void * thread_1_status;

    pthread_status = pthread_join(thread_1, &thread_1_status);

    if (pthread_status != 0) {
        printf("Thread join error\n");
        return -1;
    }

    return 0;
}

When I started the program, the content in /proc/<pid>/maps is:
00400000-00401000 r-xp 00000000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
00600000-00601000 r--p 00000000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
00601000-00602000 rw-p 00001000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
7fcc372d7000-7fcc37491000 r-xp 00000000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37491000-7fcc37691000 ---p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37691000-7fcc37695000 r--p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37695000-7fcc37697000 rw-p 001be000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37697000-7fcc3769c000 rw-p 00000000 00:00 0
7fcc3769c000-7fcc376b5000 r-xp 00000000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc376b5000-7fcc378b4000 ---p 00019000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b4000-7fcc378b5000 r--p 00018000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b5000-7fcc378b6000 rw-p 00019000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b6000-7fcc378ba000 rw-p 00000000 00:00 0
7fcc378ba000-7fcc378dd000 r-xp 00000000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37abe000-7fcc37ac1000 rw-p 00000000 00:00 0
7fcc37ad8000-7fcc37adc000 rw-p 00000000 00:00 0
7fcc37adc000-7fcc37add000 r--p 00022000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37add000-7fcc37ade000 rw-p 00023000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37ade000-7fcc37adf000 rw-p 00000000 00:00 0
7ffdc1cff000-7ffdc1d20000 rw-p 00000000 00:00 0                          [stack]
7ffdc1dd8000-7ffdc1ddb000 r--p 00000000 00:00 0                          [vvar]
7ffdc1ddb000-7ffdc1ddd000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

What are the purposes of these memory regions?
7fcc37491000-7fcc37691000 ---p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
...
7fcc37abe000-7fcc37ac1000 rw-p 00000000 00:00 0
7fcc37ad8000-7fcc37adc000 rw-p 00000000 00:00 0

Then I press enter a few times after running the program. After it prints "Before malloc in thread 1". The memory layout looks like below:
00400000-00401000 r-xp 00000000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
00600000-00601000 r--p 00000000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
00601000-00602000 rw-p 00001000 08:01 1323314                            /home/oscp/xg/c/memory_layout/a.out
00632000-00653000 rw-p 00000000 00:00 0                                  [heap]
7fcc36ad6000-7fcc36ad7000 ---p 00000000 00:00 0
7fcc36ad7000-7fcc372d7000 rw-p 00000000 00:00 0
7fcc372d7000-7fcc37491000 r-xp 00000000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37491000-7fcc37691000 ---p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37691000-7fcc37695000 r--p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37695000-7fcc37697000 rw-p 001be000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37697000-7fcc3769c000 rw-p 00000000 00:00 0
7fcc3769c000-7fcc376b5000 r-xp 00000000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc376b5000-7fcc378b4000 ---p 00019000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b4000-7fcc378b5000 r--p 00018000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b5000-7fcc378b6000 rw-p 00019000 08:01 1053877                    /lib/x86_64-linux-gnu/libpthread-2.19.so
7fcc378b6000-7fcc378ba000 rw-p 00000000 00:00 0
7fcc378ba000-7fcc378dd000 r-xp 00000000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37abe000-7fcc37ac1000 rw-p 00000000 00:00 0
7fcc37ad8000-7fcc37adc000 rw-p 00000000 00:00 0
7fcc37adc000-7fcc37add000 r--p 00022000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37add000-7fcc37ade000 rw-p 00023000 08:01 1053733                    /lib/x86_64-linux-gnu/ld-2.19.so
7fcc37ade000-7fcc37adf000 rw-p 00000000 00:00 0
7ffdc1cff000-7ffdc1d20000 rw-p 00000000 00:00 0                          [stack]
7ffdc1dd8000-7ffdc1ddb000 r--p 00000000 00:00 0                          [vvar]
7ffdc1ddb000-7ffdc1ddd000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

What are the purposes of these two regions?
7fcc36ad6000-7fcc36ad7000 ---p 00000000 00:00 0
7fcc36ad7000-7fcc372d7000 rw-p 00000000 00:00 0

After it prints "After malloc and before free in thread 1", it creates another two regions below:
7fcc30000000-7fcc30021000 rw-p 00000000 00:00 0
7fcc30021000-7fcc34000000 ---p 00000000 00:00 0

What are the purposes of these two regions?

A: Your question covers many completely different things, so the answer will be long.
The first question is the meaning of
7fcc37491000-7fcc37691000 ---p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so

in
7fcc372d7000-7fcc37491000 r-xp 00000000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37491000-7fcc37691000 ---p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37691000-7fcc37695000 r--p 001ba000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so
7fcc37695000-7fcc37697000 rw-p 001be000 08:01 1053757                    /lib/x86_64-linux-gnu/libc-2.19.so

This inaccessible memory region is a gap between adjacent ELF segments of the library (which is supposed to occupy the contiguous chunk of memory). The ---p protection mode forbids using this gap for occasional memory allocation. If you strace(1) the process when it loads the library, you may see something like this:
mmap(NULL, 1848896, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3</usr/lib/libc-2.28.so>, 0) = 0x7f9673d8f000
mprotect(0x7f9673db1000, 1671168, PROT_NONE) = 0
mmap(0x7f9673db1000, 1355776, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3</usr/lib/libc-2.28.so>, 0x22000) = 0x7f9673db1000
mmap(0x7f9673efc000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3</usr/lib/libc-2.28.so>, 0x16d000) = 0x7f9673efc000
mmap(0x7f9673f49000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3</usr/lib/libc-2.28.so>, 0x1b9000) = 0x7f9673f49000

The first mmap() maps the first ELF segment into the memory but reserves the space for whole library. This is done to allow the kernel to choose the location for the library on its discretion. To protect any possible gaps between segments mprotect(..., PROT_NONE) is called; then all remaining segments are mapped into the memory using mmap() - this also changes the protection mode of the appropriate memory pages from ---p to whatever mode the segment requires. You may have some fun by taking a look at how it actually works. If you want to verify how this ---p gap is formed during the loading, you may also use readelf(1) with library's binary and do some hexadecimal math with segments' locations and alignments, collating the results with the output of strace.
The second question are the following anonymous mappings:
7fcc36ad6000-7fcc36ad7000 ---p 00000000 00:00 0
7fcc36ad7000-7fcc372d7000 rw-p 00000000 00:00 0

This looks like a thread stack for thread 1. The second mapping is the stack itself (372d7000 - 36ad7000 = 800000 = 8 MiB, which is a default stack size limit in many distros, which, in turn, is a default stack size for pthread), and the first one is a stack guard page. This page with mode ---p protects the stack from overflowing, and triggers the segfault when the overflow happens (because of a write to this write-protected page).
Note: in older Linux kernels, the thread stacks were annotated with [stack:TID] names in maps file, but this feature was removed, so I cannot guarantee that this mapping is really a thread stack (though it looks like). However, you may use strace to find the exact thread's stack location from child_stack argument of clone() syscall and compare with this mapping.
Going on. The third question is
7fcc30000000-7fcc30021000 rw-p 00000000 00:00 0
7fcc30021000-7fcc34000000 ---p 00000000 00:00 0

Well, this is what malloc() in thread 1 did to allocate the memory you have requested. In short, the whole region 7fcc30000000-7fcc34000000 is a heap, from which allocations are done. The rw-p interval 7fcc30000000-7fcc30021000, allocated from this heap, will grow as you will request more and more memory with malloc(). When this heap will deplete, new one will be requested using mmap().
As you probably noticed, I don't have an explanation for the following mappings in your question:
7fcc37abe000-7fcc37ac1000 rw-p 00000000 00:00 0
7fcc37ad8000-7fcc37adc000 rw-p 00000000 00:00 0

I can't recognize those guys quickly and not sure that these are ordinary allocations. Probably this needs separate investigation, as this topic is already too long.


text:
Q: Is there any way to use attribute for Controller Action to allow specific hostname I has a Customer microservice with 2 Controller Actions:
One used by user with permission, no problem with this
One used by system request from Gateway microservice (a microservice I use for doing complicated action that require multiple actions from multiple microservices), this should not require any permission, but it must be called from Gateway microservice
[HttpPut("{id}/restore")]
[Authorize(Roles = PermissionConstants.RestoreCustomer)]
public async Task<CustomerResModel> RestoreCustomer(int id)
{
    return (await _customerService.RestoreCustomer(id)).ToResModel();
}

[HttpPut("{id}/restore-by-order")]
[AllowHostNames(_sitemapUrl.BaseGatewayUrl, "localhost:44302")] //any way to do this ?
public async Task<CustomerResModel> RestoreCustomerByRestoreOrder(int id)
{
    return (await _customerService.RestoreCustomer(id)).ToResModel();
}

so, is there any way to use something like [AllowHostNames(_sitemapUrl.BaseGatewayUrl, "localhost:44302")] to allow only some specific hostnames have the right to call some specific Action Apis


text:
Q: How do I use jQuery to select all children except a filter element I have a main div. I'd like to select all in the main div, except the start div and it's all children element(as blew code, pink block).
.filter() ==> it shows the all children element of star div.
.not()==> it shows the star div,expect the input and button element.

$("*.main,.main *").filter("*.start,.start *").css({
  "backgroundColor": "pink"
});

$("*.main,.main *").filter("*.start,.start *").click((e) => {
  e.stopPropagation();
  alert("filter")
});
.main,
.main * {
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;
}

.start,
.start * {
  color: pink;
  border: 2px solid pink;
}

(main)

div (parent)

start
      <form id="more_form" method="get">
        <input type="text" name="id" id="id">
        <button id="more">Send my greetings</button>
      </form>

div

div

div

div

In this exampl".

As result,when I click star div,it shows alert,too.
I expect when click the non-pink block trigger the function ,
how can I do?thanks a lot.

A: Just click on main and check the target of the event to see if it is start or within start by using closest()

$("*.main,.main *").filter("*.start,.start *").css({
  "backgroundColor": "pink"
});

$('.main').click((e) => {
  if (!$(e.target).closest('.start').length) {
    alert("filter")
  }
});
.main,
.main * {
  display: block;
  border: 2px solid lightgrey;
  color: lightgrey;
  padding: 5px;
  margin: 15px;
}

.start,
.start * {
  color: pink;
  border: 2px solid pink;
}

(main)

div (parent)

start
      <form id="more_form" method="get" onsubmit="return false;">FORM
        <input type="text" name="id" id="id">
        <button id="more">Send my greetings</button>
      </form>

div

div

div

div

In this exampl".

A:

$("*.main,.main *").filter("*.start,.start *").css({"backgroundColor": "pink"});

    // Remove the wildcard after main because it will access all the class after it
     $("*.main,.main").click((e)=>{
         e.stopPropagation();
         alert("filter")
     });
     $(".start").click((e) => {
        e.stopPropagation();
     });
.main, .main * {
            display: block;
            border: 2px solid lightgrey;
            color: lightgrey;
            padding: 5px;
            margin: 15px;
  }

.start,.start * {
            color: pink;
            border: 2px solid pink;
}

(main)

div (parent)

start
                <form  id="more_form" method="get">
                    <input type="text" name="id" id="id">
                    <button id="more">Send my greetings</button>
                </form>

div

div

div

div

In this exampl".


text:
Q: comparing two columns from two mysql tables to find distinct values I have two table as
Employee table
id  username    status
1   user1       retire
2   user2       retire
3   user3       working
4   user4       working
5   user5       working
6   user6       working
7   user7       retire

Report Table
id  username    task    date
1   user3       task1   2018-02-15
2   user3       task2   2018-02-15
3   user3       task3   2018-02-15
4   user4       task1   2018-02-15
5   user4       task2   2018-02-15
6   user4       task3   2018-02-15
7   user4       task1   2018-02-16
8   user5       task1   2018-02-16
9   user5       task2   2018-02-16
10  user5       task3   2018-02-16
11  user5       task4   2018-02-16
12  user3       task2   2018-02-16
13  user3       task3   2018-02-16

What I have to do is, first select username from employee table those have status working and compare them with username from report table for particular date. I used left outer join for the same, it gave me result but not exactly what I intended, my query for outer join is
SELECT DISTINCT employee.username FROM employee LEFT OUTER JOIN report
ON employee.username = report.username WHERE report.username IS null And
employee.status = 'working'

I want to add further condition of dates from report table, but I am not able to get it, can someone suggest me how can I get the required result.

A: SELECT Distinct(employee.username) FROM employee where employee.status = 'working'
and employee.username not in (SELECT report.username from report where
report.date = 'YourDate')

A: Something like this perhaps.
Select * from ReportTable
where taskDate between @minValue and @maxValue
and userName in (select username from Employee where status = 'working')

A: Your question seems to be incomplete, still i try to answer as far as i understand this. It looks you try to add the date filter in the where clause but you had used REPORT TABLE "LEFT OUTER JOIN" with EMPLOYEE TABLE. It is good practice not to use where clause conditions to filter the records from LEFT OUTER JOINed Table, instead you can use that condition in ON clause (where do you use the LEFT OUTER JOIN)
Regards,
Ananda Kumar J.

A: *

*You have used LEFT OUTER JOIN wrong

*Mention the relationship between the tables

SELECT DISTINCT employee.username FROM report
LEFT OUTER JOIN employee ON employee.username = report.username
WHERE report.username IS null And employee.status = 'working'
and taskDate between @minValue and @maxValue


text:
Q: Laravel Storage Cache folders owned by root causes fail in clearing cache I have a laravel 7 application running on a server (Ubuntu 18.04 LTS, apache2 webserver). My problem is, that php artisan cache:clear does return "Failed to clear cache. Make sure you have the appropriate permissions."
I tried the following approaches without success:

*

*chmod -R 775 storage

*php artisan config:cache

*manually deleting "bootstrap/cache/services.php" + "bootstrap/cache/packages.php" + "bootstrap/cache/config.php"

New created cache folders in "storage/framework/cache/data" are sometimes owned by user root, this seems to be the problem.
If I delete these folders manually it works till new root folders are created.
With ps -aux I saw that the laravel process was running from user root. I changed this with sudo -u myusername, but this didnt change the behaviour. I am starting the laravel application (php artisan serve) within the rc.local script on server restart.
The current user "myusername" is in the group www-data.

A: You have to run webserver from the user that is belongs to the same usergroup with your current user. By default rc.local call commands from root user, which is not what you need.
Edit your rc.local this way:
su user01 -c 'php /var/www/artisan serve'

Where user01 is your current user and /var/www/artisan is full path to your artisan file. Also maybe you should specify full path to your php bin file, like /usr/bin/php or else.
More details here

A: The problem should be that you don't have folders in storage path. You should have

*

*storage/framework/sessions

*storage/framework/views

*storage/framework/cache

Try to create empty folders, it should be work.


text:
Q: Set min date in materializecss" date picker Does someone know how to set min date for "materializecss" date picker?
Official web site doesn't content information about it.

A: datepicker in Material Design uses pickadate.js internally. And documentation for this is avaialble here. So this should work:
$('.datepicker').pickadate({
  min: new Date(2015,3,20),
  max: new Date(2015,7,14)
});

As mentioned here.
Here is an working example: https://jsfiddle.net/ashishanexpert/oxdbyk7t/

A: You can use:
$('.datepicker').datepicker({
    onOpen: function () {
        var instance = M.Datepicker.getInstance($('.datepicker'));
        instance.options.minDate = new Date(YOUR_DATE);
    }
});

A: For Materialize version 1 things have changed:

.datepicker::placeholder {
  color: #000;
  text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<input type="text" class="datepicker" placeholder="click and pick: only today available per setting">

<script>
jQuery('.datepicker').datepicker({ // intitiate datepicker for each element with class name "datepicker"
  minDate  : new Date(), // set minimum date to "today"
  maxDate  : new Date(), // set maximum date to "today"
  autoClose: true        // enable date picking on a very small window
})
</script>

References

*

*Materialize Date Picker

*Date


text:
Q: adding multiple views in your app I am working on an app in which the starting point is a map and it has a button too. What i want is that if user clicks the button it will take him to another view which just have two or three buttons or other elements.
Please provide me with detail answer so that i would be able to do it.
Thanks in advance, i would really appreciate it.

A: Assuming your application uses the UINavigationController, this will do the trick. Make sure you #import your other view's controller file in your header. The below example assumes your controller is named ViewSettings.
- (void)gotoOtherview {
    ViewSettings *settings = [[ViewSettings alloc] initWithNibName:@"ViewSettings" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:settings animated:YES];
}


text:
Q: Subtracting a certain number of hours, days, months or years from date I'm trying to create a simple function which returns me a date with a certain number of subtracted days from now, so something like this but I dont know the date classes well:
<?
function get_offset_hours ($hours) {
    return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}

function get_offset_days ($days) {
    return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}

function get_offset_months ($months) {
    return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") /*and now?*/));
}

function get_offset_years ($years) {
    return date ("Y-m-d H:i:s", strtotime (date ("Y-m-d H:i:s") + $years));
}

print get_offset_years (-30);
?>

Is it possible to do something similar to this?
this kind of function works for years, but how to do the same with other time types?

A: For hours:
function get_offset_hours($hours)
{
    return date('Y-m-d H:i:s', time() + 3600 * $hours);
}

Something like that will work well for hours and days (use 86400 for days), but for months and year it's a bit trickier...
Also you can also do it this way:
$date = strtotime(date('Y-m-d H:i:s') . ' +1 day');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 week');
$date = strtotime(date('Y-m-d H:i:s') . ' +2 weeks');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 month');
$date = strtotime(date('Y-m-d H:i:s') . ' +30 days');
$date = strtotime(date('Y-m-d H:i:s') . ' +1 year');

echo(date('Y-m-d H:i:s', $date));

A: Try to use datetime::sub
Example from the docs (linked):
<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'
';

date_sub($date, new DateInterval("P5D"));
echo '
'.$date->format("d-m-Y").' : 5 Days';

date_sub($date, new DateInterval("P5Y5M5D"));
echo '
'.$date->format("d-m-Y").' : 5 Days, 5 Months, 5 Years';

date_sub($date, new DateInterval("P5YT5H"));
echo '
'.$date->format("d-m-Y H:i:s").' : 5 Years, 5 Hours';

?>

A: something like this:
function offset hours($hours) {
    return strtotime("+$hours hours");
}


text:
Q: View pager displaying image only once I have used View pager to display sliding images in my application.The code works just fine but when the user navigates to other fragments and when return back to previous fragment the images are not shown.The images in the view pager are only shown when the app starts,otherwise it is not visible.
Code
public class HomeScreen extends BaseFragment {

    ViewPager viewPager;
    Fragment fragment;
    private int[] images = {R.drawable.ic_launcher, R.drawable.nav_bg};
    private FragmentManager fragmentManager;
    private Timer swipeTimer;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_screen, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        fragmentManager = getFragmentManager();
        viewPager.setAdapter(new pagerAdapter(fragmentManager, images));
        final Handler handler = new Handler();
        final Runnable update = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < images.length; i++) {
                    viewPager.setCurrentItem(i);
                }
            }
        };
        swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(update);
            }
        }, 1000, 5000);

    }

    public class pagerAdapter extends FragmentStatePagerAdapter {

        private int[] images;

        public pagerAdapter(FragmentManager fm, int[] images) {
            super(fm);
            this.images = images;

        }

        @Override
        public Fragment getItem(int i) {
            fragment = ImageSwitcher.newInstance(images[i]);
            return fragment;
        }

        @Override
        public int getCount() {
            return images.length;
        }
    }

}

Fragment Code
public class ImageSwitcher extends BaseFragment {

    private ImageView imageView;

    public static final ImageSwitcher newInstance(int image) {
        ImageSwitcher imageSwitcher = new ImageSwitcher();
        Bundle bundle = new Bundle();
        bundle.putInt("image", image);
        imageSwitcher.setArguments(bundle);
        return imageSwitcher;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    private void initialize() {
        imageView = (ImageView) view.findViewById(R.id.image_switcher);
        imageView.setBackgroundResource(getArguments().getInt("image"));
    }
}

A: Change
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
        view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
        return view;
 }

to
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)   {
    view = inflater.inflate(R.layout.image_switcher_fragment, container, false);
    initialize();
    return view;
}


text:
Q: Colorbar for lineplot using pgfplots I am doing a lineplot with pgfplots. However, instead of the usual legend, I would prefer a colorbar, as I am basically trying to visualize a transition, and for that I chose colors in a gradient like fashion.
How can I add a colorbar below the following MWE plot with clear steps and one label on the left and one label on the right of the colorbar to indicate that my transition is from A to B:
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage{tikz,pgfplots}

\pgfplotscreateplotcyclelist{TheBlues}{%
    {color=RoyalBlue!50!black},
    {color=RoyalBlue!70!black},
    {color=RoyalBlue!90!black},
    {color=RoyalBlue!90!white},
    {color=RoyalBlue!70!white},
    {color=RoyalBlue!50!white},
}

\pgfplotsset{cycle list name=TheBlues}

\begin{document}
    \begin{tikzpicture}
        \begin{axis}[
            xmin=0,
            xmax=1,
            axis line style={
                very thick,
                gray,
                shorten <=-0.5\pgflinewidth
            },
            tick label style ={gray},
            axis lines*=left,
        ]
            \foreach \n in {1,2,...,6}
                \addplot+[ultra thick,smooth,domain={0:1}] {x^\n};
        \end{axis}
    \end{tikzpicture}
\end{document}


text:
Q: How do I run two or more methods in a class like a chain? I'm trying to learn OOP but I'm getting very confused with how I'm supposed to run the methods or return values. In the following code I want to run read_chapters() first, then sendData() with some string content that comes from read_chapters(). Some of the solutions I found did not use __init__ but I want to use it (just to see/learn how i can use them).
How do I run them? Without using __init__, why do you only return 'self'?
import datetime

class PrinceMail:

    def __init__(self):
        self.date2 = datetime.date(2020, 2, 6)
        self.date1 = datetime.date.today()
        self.days = (self.date1 - self.date2).days
        self.file = 'The_Name.txt'
        self.chapter = '' # Not sure if it would be better if i initialize chapter here-
                           # or if i can just use a normal variable later

    def read_chapters(self):
        with open(self.file, 'r') as book:
            content = book.readlines()
            indexes = [x for x in range(len(content)) if 'CHAPTER' in content[x]]
            indexes = indexes[self.days:]
            heading = content[indexes[0]]
            try:
                for i in (content[indexes[0]:indexes[1]]):
                    self.chapter += i # can i use normal                      var and return that instead?
                    print(self.chapter)
            except IndexError:
                for i in (content[indexes[0]:]):
                    self.chapter += i
                    print(self.chapter)
        return self????? # what am i supposed to return? i want to return chapter
                         # The print works here but returns nothing.

    # sendData has to run after readChapters automatically
    def sendData(self):
         pass
         #i want to get the chapter into this and do something with it

    def run(self):
        self.read_chapters().sendData()
        # I tried this method but it doesn't work for sendData
        # Is there anyother way to run the two methods?

obj = PrinceMail()
print(obj.run())
#This is kinda confusing as well

A: Chaining methods is just a way to shorten this code:
temp = self.read_chapters()
temp.sendData()

So, whatever is returned by read_chapters has to have the method sendData. You should put whatever you want to return in read_chapters in a field of the object itself (aka self) in order to use it after chaining.

A: First of all, __init__ has nothing to do with what you want to achieve here. You can consider it as a constructor for other languages, this is the first function that is called when you create an object of the class.
Now to answer your question, if I am correct you just want to use the output of read_chapters in sendData. One of the way you can do that is by making the read_chapters a private method (that is if you don't want it to use through the object) using __ in the starting of the name like __read_chapters then make a call to the function inside the sendData function.
Another point to consider here is, when you are using self and don't intend to use the function through the object you don't need to return anything. self assigns the value to the attribute of the current instance. So, you can leave the function read_chapters at self.chapter = i and access the same in sendData.
Ex -
def sendData(self):
    print(self.chapter)

A: I'm not an expert but, the reason to return self is because it is the instance of the class you're working with and that's what allows you to chain methods.
For what you're trying to do, method chaining doesn't seem to be the best approach. You want to sendData() for each iteration of the loop in read_chapters()? (you have self.chapter = i which is always overwritten)
Instead, you can store the chapters in a list and send it after all the processing.
Also, and I don't know if this is a good practice but, you can have a getter to return the data if you want to do something different with (return self.chapter instead of self)
I'd change your code for:
import datetime

class PrinceMail:

    def __init__(self):
        self.date2 = datetime.date(2020, 2, 6)
        self.date1 = datetime.date.today()
        self.days = (self.date1 - self.date2).days
        self.file = 'The_Name.txt'
        self.chapter = []

    def read_chapters(self):
        with open(self.file, 'r') as book:
            content = book.readlines()
            indexes = [x for x in range(len(content)) if 'CHAPTER' in content[x]]
            indexes = indexes[self.days:]
            heading = content[indexes[0]]
            try:
                for i in (content[indexes[0]:indexes[1]]):
                    self.chapter.append(i)
            except IndexError:
                #not shure what you want to do here
                for i in (content[indexes[0]:]):
                    self.chapter.append(i)

        return self

    # sendData has to run after readChapters automatically
    def sendData(self):
        pass
        #do what ever with self.chapter

    def get_raw_chapters(self):
        return self.chapter

Also, check PEP 8 Style Guide for naming conventions (https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)
More reading in
Method chaining - why is it a good practice, or not?
What __init__ and self do on Python?


text:
Q: non drawn Sprite still active xna I am making a 2D space Shooting game and I have ran into an issue with a shield power up. The shield makes the player invincible to collision from the enemy ships for a certain amount of time. When the player collides with the power up the player is invincible for a set period of time when the player moves away from the position of the power up and the power up gets removed from the screen which all works fine. However, the issue i am having is the player can still collide with it even after it's being removed from the screen in the draw method, meaning the player could simply stay in that spot and be invincible forever. So once the player has collided with the shield, I would like it so the player cannot collide with it again. I have tried searching online but I haven't found anything that was particularly useful.
I would also like to use this power up again. in the future I plan on adding them 'randomly' throughout my scrolling background. Not sure if this add anything to the post just thought I would include it.
game1.cs
    public double counterPower = 0;

    public bool powerUpCollision = false;
    public bool invincibility = false;
    Sprite shieldPower;
    bool isVisible = true;

    protected override void Initialize()
    {
      shieldPower = new Sprite();
    }

    protected override void LoadContent()
    {
        if (isVisible == true)
        {
            shieldPower.LoadContent(this.Content, "powerUpShield");
            shieldPower.Position.X = 300;
            shieldPower.Position.Y = 300;
        }
    }

    protected override void Update(GameTime theGameTime)
    {
        powerUps(theGameTime);
    }

     public void powerUps (GameTime theGameTime)
    {
        if (mPlayer.boundingBox.Intersects(shieldPower.boundingBoxShieldPower))
        {
            if (shieldPower.isVisible == true)
            {
                Console.WriteLine("collision working");
                powerUpCollision = true;
                invincibility = true;
                isVisible = false;
                if (powerUpCollision == true && invincibility == true)
                {
                    lives = lives - 0;
                }

                counterPower = 0;
            }
        }
        counterPower += theGameTime.ElapsedGameTime.TotalSeconds;
        {
            Console.WriteLine(counterPower);
            if (counterPower > 7)
            {
                powerUpCollision = false;
                invincibility = false;

            }
        }

       protected override void Draw(GameTime theGameTime)
       {
           spriteBatch.Begin();

           if (isVisible == true)
             {
                shieldPower.Draw(this.spriteBatch);
             }
       }
       spriteBatch.End();

In the sprite class is the bounding box for the power up, this works fine.
I have a lot more code and classes but I'm fairly sure a lot of it isn't relevant for this issue and I also don't want to waste your time.
Any help would be greatly appreciated.
Thank you.

A: What I would first suggest is setting the bounding box to null or to somewhere it cannot possibly be collided with. It sounds like the player ship is colliding with the object because even though it isn't displayed, all of it's attributes still exist to the system. So, making it invisible and hiding it offscreen is one option, although that's for if you set the location with other code when it is supposed to be called.
Second thing, set a flag for if the powerup exists in the game. Basically nest all of your "Do this when the ship hits it" within a if statement so that it will only apply while you want it to and will skip that code when the conditions aren't met. You could actually do this instead of the first part if the bounding box wouldn't affect anything else.
edit: To clarify, something like this:
if(ship.hitsPowerup)
{
   if(powerup.isActive)
   {
       doTheThing;
       powerup.isActive = false;
   }
}


text:
Q: python: create list from list returns less items I have a list of files, which I create with:
files=[f for f in os.listdir(source) if f.endswith('.tif')]
print(len(files))
264

This list contains 264 files, i.e.
 ...,'NL-HnWFA_2244_157.tif', 'NL-HnWFA_2244_158-001.tif', 'NL-HnWFA_2244_158-002.tif', 'NL-HnWFA_2244_159.tif', ...

From this list of files I want to substract the inventory (the "157" part) by doing:
inventories = []
for file in files:
  inventories.append(file.split('_')[2].split('-')[0].split('.')[0])
print(len(inventories))
264

Then I have 264 items in the list
However, if I issue the command:
inventories = {fn.split('_')[2].split('-')[0].split('.')[0] for fn in files}
print(len(inventories))
263

The double values have been omitted and there are only 263 items.  Why are the double values been omitted in the second statement?
Can I still (somehow) get the double values in the first statement?

A: It's because set (as you're doing {...}), always makes the sequence non-duplicate valued.
Nothing you can do about that.
So you gotta use the list comprehension one.
Demo:
>>> a=[1,2,3,3]
>>> set(a)
{1, 2, 3}
>>> {i for i in a}
{1, 2, 3}
>>> {*a}
{1, 2, 3}
>>>

As in this docs:

Sets are mutable unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.


text:
Q: iOS icon resolution/management "within" application i am completely new to this, but i was not able to find anything about it.
In order to make my applications main icon use the native resolution of a specific iOS device, a lot of different image resolutions are required and need to be loaded. This is also applicable for LaunchImages.
What I am missing is:
What about the icons used within the application?
How do i handle the resolution of this icons and how are they set properly?
Thank you in advance!

A: When you are exporting images you created, export 3 different sizes, one is for non-retina screens like iPhone 3GS (it's unnecessary nowadays), one with 2x the width and height with a surfix of "@2x", another with 3x the width and height with a surfix of "@3x".
Then you put these three images in Xcode image.xcassets file, so when you access these images, iOS will automatically match the right image with the right device.
I'm both a programmer and a designer, Xcode makes doing this a breeze. Have fun!


text:
Q: How to Get All Custom Category Attribute Values? I have created module that add custom attribute in Manage Categories section. Say My custom category attribute is category_sku, and it is a text field.
I see that the value of my custom attribute is stored in catalog_category_entity_text table.
But how to populate all the values of it?
I tried using the below code, but it return NULL.
Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_sku')->getValue();

A: I'm doing it in phtml file like this way
<?php $categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*'); ?>

<?php foreach ($categories as $category): ?>
   <?php $categorySku = $category->getCategory_sku(); ?>
   <?php print_r ($categorySku); ?>
<?php endforeach; ?>

That way I can populate all my custom category attribute values which is category_sku :).
And this will make it to a select option list.
    <?php $categories = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*'); ?>

        <select id="my-id" name="my-name">
            <option value="">Select</option>
            <?php foreach ($categories as $category): ?>
<?php /*magento fetch data by using get and attibute name like banner_id change to getBannerId*/   ?>
                <?php $categorySku = $category->getCategorySku(); ?>
                <option value="<?php echo $categorySku; ?>"><?php echo $categorySku; ?></option>
            <?php endforeach; ?>
        </select>

A: I need to the something very similar to this but I can't get it to work.
I hope get some answers from the wise guys out her.
I need to get a attribute collection of the current category for example.
I have 4 custom attributes (images) that I would like to use for category slider
<?php $category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
      $categories =$category->getCollection()
      ->addAttributeToSelect(array('sliderimg1','sliderimg2','sliderimg3','sliderimg4'))
    ->addAttributeToFilter('is_active', 1)
    ->addIdFilter($category->getChildren())
    ->addAttributeToSort('position', ASC);?>

with this code I can get the attributes to show but, how can I add it to my slider?
please help.
I tried

     <?php foreach ($categories as $category): ?>

<img class="imgl" style="width:100%; height:100%; object-fit: cover;  object-position: 69% 37%;" src="<?php echo Mage::getBaseUrl('media') . 'catalog' . '/' . 'category' . '/' . $category->getSliderimg1() ?>">

 <?php echo $category->getName() ?>

<?php echo $category->getF_title1() ?>

MSRP <?php echo $category->getMsrp() ?>

                <button type="button" class="btn btn1 menu-btn-brp-default" onClick="location.href='<?php echo $category->getUrl(); ?>'">VIEW DETAILS </button>

    <?php endforeach; ?>

This gets the attribute image for each category...
but I need to create a slider for each category how can I get the other 3 attributes
(sliderimg2,sliderimg3,sliderimg4 ) in to my category slider for the current category only.


text:
Q: What is the purpose of 'Number()' in indexedDB get() method According to the documentation linked below, get() has a single parameter: key. In the description is:

Key identifying the record to be retrieved. This can also be an
  IDBKeyRange in which case the function retreives the first existing
  value in that range.

In the example code below, using get(Number("1")), will find the record. Using only get("1"), result is empty. (The primary/only key is 'num' and is auto-increment.)
function removeRecord(num) {
    var transaction = db.transaction(['queueStore'], 'readwrite');
    var store = transaction.objectStore('queueStore');

    // Check if the record exists & to identify the record
    store.get(Number(num)).onsuccess = function(event) {
        /*      ^ here     this works  */
        var result = event.target.result;
        if(result) {
            number = result.number;
        }
    };
}

I have not been able to find the answer in the Indexed Database API or by search.
What does Number accomplish?

A: The Number constructor when called as a function (that is, without new) converts the parameter to a number and returns that value. So, Number("1") returns the number 1.
There's no point to coding Number("1") explicitly; you'd simply use 1. It's useful if you know you might get a string value. In your case, the API is performing an exact comparison against your key, and if the real key is a number then it will never === any string.
The unary + operator does essentially the same thing, so +"1" is also 1. Some people prefer to call Number() explicitly because it's a little more explicit.
The parseFloat() function also will convert a string to a number, but unlike the Number() constructor or unary +, parseFloat() will allow for non-numeric content at the end of the input string:
console.log(parseFloat("123hello world")); // 123
console.log(+"123hello world"); // NaN


text:
Q: how to use Query.limit and Query.skip? I've spent about 13hrs/day for the past week but I can't seem to figure it out. I've scrolled to the ends of the web but I can't seem to implement 'query.skip' and 'query.limit' to my table correctly.
The 'user' is following people and each person has a lot of posts. I want to load the first 5, then load the next 5 as the user scrolls down the table.
I have a total of 19 posts by the users we are following.
PROBLEM:  when this runs the first time, everything works, but as i scroll past the 4th row, it SHOULD run, skip = 5 and limit = 10, so on so fourth. But when it runs the 'loadFollowersImages()' function it starts to load 15, objects, then 30, 46...everything repeats and doubles.
What am I doing wrong? why does it not skip to the limit and add 5 to the new limit.
my viewDidLoad:
override func viewDidAppear(animated: Bool) {

    if resultsHasNameArray.count == 0 {

        // to start download 5 posts

        skip = resultsHasNameArray.count
        limit = resultsHasNameArray.count + 5

        getFollowingData() {

    }

}

Gets the list of people the user is following: In this case it's Two Users
func getFollowingData() {

    var followQuery = PFQuery(className: "follow")
    followQuery.whereKey("user", equalTo: PFUser.currentUser()!.username!)

    var objects = followQuery.findObjects()

    for object in objects! {

        self.followArray.append(object.objectForKey("userToFollow") as! String) // stores all the usernames Current user is following
    }

    loadFollowersImages() // once we know who we are following, start to download their "posts"

}

returns Two Users: James & Amy
Now to download their posts: which is total of 19
First downloads 5 posts.
func loadFollowersImages(){

    var photoQuery = PFQuery(className: "PostPhoto")

    photoQuery.skip = skip!      // oringally to 0
    photoQuery.limit = limit!    // oringally to 5

    photoQuery.whereKey("username", containedIn: followArray)
    photoQuery.addDescendingOrder("createdAt")

    photoQuery.findObjectsInBackgroundWithBlock {
        (objects:[AnyObject]?, error: NSError?) -> Void in

        if error == nil {

            for object in objects!{

                self.resultsHasNameArray.append(object.objectForKey("username") as! String)
                self.resultsHasUserImageFile.append(object.objectForKey("userImageFile") as! PFFile)

                self.resultsTable.reloadData()

            }

        }
    }

returns 5 posts successfully.
Now, when the users scrolls down to the 5, row, it should run the above (loadFollowersImages()) method and add 5 to skip and 5 to limit (5, 10, respectively).
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    if indexPath.row  == limit! - 1{   // when scrolling down, if our limit meets index path run

        skip = skip! + 5               // adds '5' to skip
        limit = limit! + 5             // adds '5' to limit

        loadFollowersImages()          // runs above method
    }

}

A: You don't want to change the limit, you just want to download the next 5 so the limit still 5 during all the interactions, the only number you should alter is the number of rows to skip, however this will require adjustments in the if condition as now you want to run the loadFollowersImages function when the row displayed is equal to the limit plus the number of rows already skipped, as below:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

        if indexPath.row  == limit! + skip! - 1{
        // when scrolling down, if our limit + rows skiped meets index path run
            skip = skip! + 5               // adds '5' to skip and limit is constante
            loadFollowersImages()          // runs above method
        }

    }


text:
Q: Android Hide Sliding Drawer After Some Time I have a slidingdrawer in my activity, i open sliding drawer on swipe gesture from bottom to top what i want is to close that opened drawer after some second or delay let say after 5 seconds. How can i do that?
private class GestureDetector extends SimpleOnGestureListener {
   SlidingDrawer drawer;
   Timer timer;

   public GestureDetector(SlidingDrawer drawer) {
        this.drawer = drawer;
        timer = new Timer();
   }

   TimerTask timerTask = new TimerTask() {

       @Override
       public void run() {
         closeSlider();
       }
    };

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        if(e1.getY() > e2.getY()) {
             this.drawer.animateOpen();
             timer.scheduleAtFixedRate( timerTask , 0, 3000);
         } else {
            //this.drawer.animateClose();
         }
    }

       public void closeSlider() {
            this.drawer.animateClose();
         }
   }

   //i call it on activity onCreate()
   SlidingDrawer slidingDrawer = (SlidingDrawer) findViewById(R.id.slidingDrawer);
   new GestureDetector(slidingDrawer);

Thanking you

A: new Handler().postDelayed(new Runnable() {

   @Override
        public void run() {
        // TODO call closeSlider method here.

        }
}, 5000);


text:
Q: How to safely return objects from DLL calls I am fairly new to C++ and working with DLLs. I have a main application that aggregates results from different measurements. As the measurements are different from case to case I decided to put them into external DLLs so they can be loaded at runtime (they simply all export the same function). The idea is to just load them like this so the aggregator can be extended depending on the runtime needs:
typedef int (*measure)(measurement &dataHolder);

int callM() {
  [...]
  measurement dataHolder;
  lib = LoadLibraryA("measureDeviceTypeA.dll");
  measure measureFunc = (measure)GetProcAddress(lib, "measureFunc");
  pluginFunc(dataHolder);
  [...] // close the lib and load the next one depending on found Devices
}

This works pretty well for simple datatypes (depending on the actual definition of the struct "measurement") such as this:
typedef struct measurement {
    DWORD realPBS;
    DWORD imaginaryPBS;
    int a;
} measurement;

Now there also may be a string of arbitrary length (char representations of results). I would like to put them into the measurement struct as well and fill them inside the actual worker function inside the DLL. My first assumption was that it would be easy to just use std::string, which works sometimes and sometimes not (as it will reallocate memory on std::string().append() and this might break (access violation) depending on the actual runtime environment of the program and the dll). I read here and here that returning a string from a function is a bad idea.
So what would be the "proper" C++ way of returning arbitrary length strings from such a call? Is it helpful at all to pass a struct to the DLL or should I split it into separate calls? I don't want to have pointers dangling around or unfreed memory when I close the DLL again.

A: This won't work with std::string, as noted by Dani in the comments. The problem is that std::string is a type that belongs to your implementation, and different C++ implementations have different std::strings.
For DLL's specifically (Microsoft), you do have another alternative. COM is an ancient technology, but it still works today and is unlikely to go away ever. And it has its own string type, BSTR. Visual Studio provides a helper C++ class bstr_t for your own code, but on the interface you'd use the plain BSTR from _bstr_t::GetBSTR.
BSTR relies on the Windows allocator SysAllocString from OleAut32.dll

A: The problem is, that the string data is often allocated on the heap, so it has to be freed / managed somehow.
You could think, hey std::string is returned by value - so why I need to care about memory management. The problem is that usually only very small strings are stored "inside" the class. For larger strings the string class contains a pointer to some "heap-storage".
Dlls can be used from and with different programming languages - which is the reason that dlls do not share a "memory manager", freeing in the dll would fail.
To solve this you need to have two function calls, one which returns a pointer / handle to the data and one to free it. Or the caller could give the callee some pointer where it wants the data to be stored. You need for that a maximum-byte-count, too.
As you can see, there are some reasons why you should avoid these APIs - but it is not always possible. See for example the Windows API (there you can find both approaches).
Another approach would be to ensure a shared memory manager, but this is tricky somehow because it must be done really early!


text:
Q: state of multitouch gestures in 14.04 / Unity This seems like one of the most-asked items around here, but the Ubuntu dev team has been making changes fast in this area, so recent information is important.
I'm on a macbook pro 9,2.
When I installed Ubuntu Saucy, I got the new and exciting mtrack driver for my touchpad.  It seems to work well for all the basic functions and two and three finger gestures seem to be picked up by my applications, at least (ie firefox 3 button "back", scrolling). I would like to customize the gestures though, and maybe add one or two of my own to manage my workspaces/windows. I updated to 14.04 last night to see if multitouch support in the GUI was improved (it doesn't look like it).

*

*I have tried touchegg, but it seems like it relied on utouch which no longer exists in 13 or 14. It can't detect anything from my touchpad, even when I recompiled unity without multitouch, per http://ineed.coffee/1068/os-x-like-multitouch-gestures-for-macbook-pro-running-ubuntu-12-10/ . Most of the doco I've seen on it assumes you're using synaptics, so maybe that's the problem.

*I have tried ginn, but encountered the same problem - it can't detect any input from my trackpad gestures.

*I have tried easystroke, but it wants me to have a "gesture button" which enables gestures. I just want to do them without a special button.
This is driving me crazy. I understand that if I switch to Ubuntu Gnome touchegg should "just work". But do I REALLY have to change my whole shell interface to configure mouse gestures? Does Unity REALLY hijack the entire multitouch stack without exposing any of it in a configuration tool?
I feel like this is so ridiculous I must be missing something obvious. Any advice would be welcome.

A: On the latest ubuntu, all the advanced multi-touch only work from the touchscreen, not from the touchpad.
So what is left is:

*

*scroll (two fingers drag up or down),

*list of running software (3 fingers double tap)

*launcher (4 fingers tap)

all the other advanced multitouch gestures are only available from the screen. I'm still puzzled by that design choice.
Touchégg seems to work with 14.04 (I'm on 14.10, can't confirm/deny)
https://code.google.com/p/touchegg/

A: According to the Unity Gesture UI Guidelines only the "4 finger" and "1 finger edge" are hard-coded into Unity. I can attest to the fact that most gestures on Wacom tablets can be easily disabled without recompiling Unity (using xsetwacom), however the "4 finger" gesture that opens the dash (which is inadvertently triggered often by my knuckles while writing on the Wacom) is annoyingly persistent.
Update: Recompiling Unity to remove the offending code which pertains to the four finger touches was pretty painless and well outlined in another thread.

A: I have written a guide to do this. Basically, in order for this to work, you must use a forked syndaemon driver. You will also use a program called xswipe. Follow this link.

A: Actually, all of these features still function on the touchpad. The only thing they did was add support for touch screen laptops/monitors. When they did this though, most of the default multi-finger gestures were moved to the touch screen. So if you want them on the touchpad, then all you have to do is set up the shortcut and the command, similarly to that which you would do for a keyboard shortcut. (and yes, I know that this does work, I am currently using Ubuntu 15.04 Vivid Vervent.)


text:
Q: Theano compile fails in composer My calculations using PyMC3 fail after pushing my operators to Google Cloud Composer. Errors provided below.
We've tried updating the PyPI packages of the compute environment and looked at the logs. This shows some clear errors, which seem to indicate that a compile job is failing on the cloud.
This is happens when airflow tries to parse our files - it is a fail on import.
Traceback (most recent call last):

File "/opt/python3.6/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 81, in <module>
    actual_version, force_compile, _need_reload))

ImportError: Version check of the existing lazylinker compiled file. Looking for version 0.211, but found None.

Extra debug information: force_compile=False, _need_reload=True

Traceback (most recent call last):
File "/usr/local/lib/airflow/airflow/models.py", line 374, in
    process_file m = imp.load_source(mod_name, filepath)

File "/opt/python3.6/lib/python3.6/imp.py", line 172, in
    load_source module = _load(spec)

File "<frozen importlib._bootstrap>", line 684, in
    _load

File "<frozen importlib._bootstrap>", line 665, in
    _load_unlocked

File "<frozen importlib._bootstrap_external>", line 678, in
    exec_module

File "<frozen importlib._bootstrap>", line 219, in
    _call_with_frames_removed

File "/home/airflow/gcs/dags/dag_abtesting/abtesting_orchestration.py", line 10, in <module>
    from dag_abtesting.abtesting_tasks import task_analysis

File "/home/airflow/gcs/dags/dag_abtesting/abtesting_tasks.py", line 16, in <module>
    from dag_abtesting.task_bernoulli import task_analyse_bernoulli

File "/home/airflow/gcs/dags/dag_abtesting/task_bernoulli.py", line 3, in <module>
    from dag_abtesting.template_distributions import abstract_template_distribution, bernoulli_distribution

File "/home/airflow/gcs/dags/dag_abtesting/template_distributions/bernoulli_distribution.py", line 6, in <module>
    import pymc3 as pm

File "/opt/python3.6/lib/python3.6/site-packages/pymc3/__init__.py", line 5, in <module>
    from .distributions import *

File "/opt/python3.6/lib/python3.6/site-packages/pymc3/distributions/__init__.py", line 1, in <module>
    from . import timeseries

File "/opt/python3.6/lib/python3.6/site-packages/pymc3/distributions/timeseries.py", line 1, in <module>
    import theano.tensor as tt

File "/opt/python3.6/lib/python3.6/site-packages/theano/__init__.py", line 110, in <module>
    from theano.compile import (

File "/opt/python3.6/lib/python3.6/site-packages/theano/compile/__init__.py", line 12, in <module>
    from theano.compile.mode import *

File "/opt/python3.6/lib/python3.6/site-packages/theano/compile/mode.py", line 11, in <module>
    import theano.gof.vm

File "/opt/python3.6/lib/python3.6/site-packages/theano/gof/vm.py", line 674, in <module>
    from . import lazylinker_c

File "/opt/python3.6/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 140, in <module>
    preargs=args)

File "/opt/python3.6/lib/python3.6/site-packages/theano/gof/cmodule.py", line 2396, in
    compile_str (status, compile_stderr.replace('\n', '. ')))

Exception: Compilation failed (return status=1): /usr/bin/ld: cannot find -lpython3.6m. collect2: error: ld returned 1 exit status.

It looks to me as if I'm missing something -likely a compiler - on my hosted environment? Can someone advise on a next action to take?


text:
Q: cascading dropdown in dynamic row angular? I have cascading dropdown list which works alone, but when I generate a new row and change one of my dropdowns its affects my entire dropdown list.
Here is my html code.

       <select class="form-control" formControlName="province_id"
           (change)="onChangeProvince($event)">
          <option >Select Province</option>
          <option *ngFor="let province of provinces; let i = index"
              [value]="province.id">{{province.province_name}}</option>
       </select>

       <select  class="form-control" formControlName="district_id">
          <option >Select District</option>
          <option *ngFor="let district of districts" [value]="district.id">
               {{district.district_name}}</option>
       </select>

       <button class="btn btn-danger"  type="button"
           (click)="deleteMyRelation(i)">Delete</button>
       <button class="btn btn-primary" type="button"
           (click)="addItem()">Add</button>

Here is my component code.
      createItem(): FormGroup {
            return this.fb.group({
              province_id: '',
              district_id: ''
            });
          }

       addItem(): void {
            this.itemRows = this.contactForm.get('itemRows') as FormArray;
            this.itemRows.push(this.createItem());
          }

       ngOnInit() {
            this.contactForm = this.fb.group({
              province_id: '',
              district_id: '',
              itemRows: this.fb.array([ this.createItem() ])
            });
            this.getProvinces();
          }

          provinces = <any>[];
          districts = <any>[];

          getProvinces(){
            this.contactService.getProvinces().subscribe(
              data => {
                this.provinces = data;
                console.log(data);
              },
              error => {
                console.log(error);
              });
          }
          onChangeProvince(event:any){

            this.contactService.getDistrict(event.target.value).subscribe(
              data => {
                this.districts = data;
              },
              error => {
                console.log(error);
              });
          }

A: You need define each control with a [formGroupName]='i'. Now Angular will assign the values to each group properly, something like

  <ng-container formArrayName='itemRows'>

        <select class="form-control" formControlName="province_id"
           (change)="onChangeProvince(i)">
          <option  value=''>Select Province</option>
          <option *ngFor="let province of provinces; let i = index"
              [value]="province.id">{{province.province_name}}</option>
       </select>

        <select  class="form-control" formControlName="district_id">
          <option value=''>Select District</option>
          <option *ngFor="let district of districts[i]" [value]="district.id">
               {{district.district_name}}</option>
       </select>

        <button class="btn btn-danger"  type="button"
           (click)="deleteMyRelation(i)">Delete</button>
        <button class="btn btn-primary" type="button"
           (click)="addItem()">Add</button>

  </ng-container>

We can now define below functions to enable adding and removing of items
  get itemRows() {
    return this.contactForm.get("itemRows") as FormArray;
  }
  deleteMyRelation(i) {
    this.itemRows.removeAt(i)
  }
  addItem(): void {
    this.itemRows.push(this.createItem());
  }
  onChangeProvince(i) {
    this.contactService
      .getDistrict(this.itemRows.get(i + ".province_id").value)
      .subscribe(
        data => {
          this.districts[i] = data;
        },
        error => {
          console.log(error);
        }
      );
  }

Now your form should work as expected
See Demo

A: Complementary the answer, when the only we need in a subscription use the values in the .html you can use pipe async.
You define
//It's usually way, named a variable that was an observable adding a "$" to the variable
province$=this.contactService.getProvinces()
district$=[]

As always we has a formArray is good has a getter
  get array(){
     return this.contactForm.get('itemRows') as FormArray;
  }

Your (change) becomes like
  change(index)
  {
    const value=+(this.array.at(index) as FormGroup).get('province_id').value;
    this.array.at(index).get('district_id').setValue(null)
    this.district$[index]=this.dataService.getDistrict(value)
  }

You can use
   <select class="form-control" formControlName="province_id"
                  (change)="change(index)"  >

      <option [value]="null" hidden>Select Province</option>
      <option *ngFor="let province of province$|async; let i = index"
          [value]="province.id">{{province.province_name}}</option>
   </select>
   <select  class="form-control" formControlName="district_id">
      <option [value]="null" hidden>Select District</option>
      <option *ngFor="let district of district$[index]|async"
           [value]="district.id">
           {{district.district_name}}</option>
   </select>

I write a fool example in this stackblitz (not has your models, but I hope can help for inspiration)


text:
Q: MOXy on OSGi error (property "eclipselink-oxm-xml" is not supported) I'm using MOXy under fuse ESB (based on karaf). When trying to create new instance of JAXBContext i get error : property "eclipselink-oxm-xml" is not supported.
I have placed jaxb.properties file with content : javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory in same package as domain classes. And xml-bindings file is loaded succesfully.
Map<String, Object> properties = new Hashmap<>(1);
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, Utils.class.getResource("xml-bindings.xml").getPath());
JAXBContext jc = JAXBContext.newInstance(clazz, properties);

The main problem is that, when i run the function which uses this xml-bindings.xml properties from eclipse with JUnit tests, everything works fine, but when i run it in OSGi environment and call this function, i receive error : property "eclipselink-oxm-xml" is not supported.
So maybe somebody could give me the clue, what is wrong, why it fails to create new jaxbcontext in OSGi?
EDIT:
System.getProperty("javax.xml.bind.context.factory") returns org.eclipse.persistance.jaxb.JAXBContextFactory, so i guess jaxb properties file is loaded.


text:
Q: Reverse range over a string How can I "reverse range" in Go over individual characters of a string?
For example, given s := "some string \u1222 whatever" - I want to do something like:
for i, v := ~reverse~ range s {
}

Please note, that I'm interested in a solution via standard library without having to write a function myself. I'm aware of tons of existing libraries which can do that, but that's irrelevant. Moreover - I can't use len(s) and do:
for i := len(s) - 1; i >= 0; i-- {
}

since in Go built-in len function returns only number of bytes in a string (won't work for non-ASCII strings). I also can't do len(s) - k - 1 where k is an index provided by range instruction due to aforementioned reason.

UPD1:
It is possible to do a reverse (right to left) lookup of utf-8 runes, because we can easily identify runes by high order bits of each byte or groups of bytes. From The Go Programming Language book:

As you can see, we can start from the last byte and we will need to scan to the left at most 4 bytes to get a rune.

A: The easiest solution would be to convert the string to []rune, so you can iterate over it, but index "backward" (or use a downward loop):
rs := []rune(s)
max := len(rs) - 1
for i := range rs {
    r := rs[max-i]
    fmt.Printf("%c ", r)
}

This will output (try it on the Go Playground):
r e v e t a h w   ሢ   g n i r t s   e m o s

If you want to avoid the []rune conversion, you may use utf8.DecodeLastRuneInString() like this:
for {
    r, size := utf8.DecodeLastRuneInString(s)
    if r == utf8.RuneError {
        break
    }
    fmt.Printf("%c ", r)
    s = s[:len(s)-size]
}

This outputs the same, try this one on the Go Playground.

A: You can do:
runes:=[]rune(str)
for x:=len(runes)-1; x>=0; x-- {
   // work with runes[x]
}


text:
Q: Update generic property of generic class? I'm quite new at C# Generic Classes so I don't know if we can update the generic property of a generic class dynamically?
Let say I have a class
A { long id; long count; }

Can we write an extension that update the given property by 1 so
A.AddOne(a => a.id); will change A {id=1, count=1} to A {id=2, count=1}

and

A.AddOne(a => a.count); will change A {id=1, count=1} to A {id=1, count=2}

Any helps would be appreciated!

A: If I understand your question correctly, you want to be able to declare which property to update by giving the AddOne method a lambda expression. In this case, it's possible -- you can write an extension method that takes an Expression<T>, retrieves from this expression the property access expression, and uses Reflection to update that property on the A object.
The following is a very rough prototype of the above:
public static void AddOne<S,T>(this S x, Expression<Func<S,T>> expr)
{
    if (expr.Body.NodeType != ExpressionType.MemberAccess)
        throw new InvalidOperationException();

    MemberExpression memberExpr = expr.Body as MemberExpression;
    switch (memberExpr.Member.MemberType)
    {
        case MemberTypes.Field:
            {
                FieldInfo field = memberExpr.Member as FieldInfo;
                ulong value = Convert.ToUInt64(field.GetValue(x));
                ++value;
                field.SetValue(x, Convert.ChangeType(value, field.FieldType));
                break;
            }
        case MemberTypes.Property:
            {
                PropertyInfo prop = memberExpr.Member as PropertyInfo;
                ulong value = Convert.ToUInt64(prop.GetValue(x, null));
                ++value;
                prop.SetValue(x, Convert.ChangeType(value, prop.PropertyType), null);
                break;
            }
        default:
            throw new InvalidOperationException();
    }
}


text:
Q: OpenSSL certificate validation caching I make a HTTPS request with CURL. CURL uses SSL and checks the server certificate. This works fine.
It is possible to simulate a web browser behavior, that means that the certificate is checked if the first HTTPS connection is made, but the following HTTPS connections to the same server don't check the certificate again. The certificate check is cached by the web browser.


text:
Q: I'm looking to stab someone. What weapon should I pick? The weapons, shiv, screwdriver and scalpel are all of the stabbing category and all take the same weapon slot (you can only have one of them at any given time).
What are the differences between them? Which is the best stabbing weapon?

A: There's a weapons FAQ that covers the differences between shivs. The listings give identical speed/strength ratings to all shivs, but notes differences in the description anyway. I couldn't tell whether those differences are real or perceived, since they're not explained well, but here they are anyway (bold is my emphasis):

Carved Bone

*

*This looks like a bone, that was carved into a Shiv. It looks pretty cool, and it can only be got at one point in the game: When you kill Alonzo.

Shiv (Chisel-Like)

*

*This is the first type of Shiv you'll be able to get your hands on, and you will find it on several prisoners in the Aquilla territory. This model of Shiv looks like a chizel.

Shiv (Curved Blade)

*

*This is a pretty good Shiv - kind of big, compared to some of the other models. It's definitely worth the buy, if you have the UDs to pay for it. This is the Shiv shown on the box of the game, and is likely the best one you'll find.

Shiv (Thick Metal Blade)

*

*You'll find this Shiv early in the game, but when you get it you'll also have the [Chisel] Shiv and the Thin Shiv to get. This has [the] shortest reach of the three, so pass on it if you see anything better. This shiv looks like a knife with no handle.

Shiv (Thin Metal Blade)

*

*You'll find this Shiv early in the game, along with the [Chizel] Shiv and the Thick Shiv. It's the longest of them so you may want to choose it. This shiv looks like a knife with no handle.

Scalpel

*

*You'll find this when you're [in] the Infirmary, so don't pass up on the chance to get it. It's a surgeon's tool, so you can picture what it looks like, but it works great in a fight. This is the second best shiv that you'll be able to find.

Screwdriver

*

*This is just the average [screwdriver] that you'd expect to see in your tool chest. However, anything can be used as a weapon, if you're Riddick. I'd [recommend] avoiding this one unless you don't have any other shivs.


text:
Q: Integer polynomial on integer values: dense mod $\pi$? I was trying to answer the question at How to show that $\lim_{n \to \infty} \sin(n^2)$ does not exist?
I was able to show that $\sin(n^2)$ does not tend to a limit, but am still unable to show that $n^2$ itself is dense mod $\pi$. Can this be deduced in a straightforward way from the famous theorem that the integers are dense mod $\pi$?
Also, are all integer polynomials dense modulus an irrational number? I struggle to find the relevant literature online.

A: Yes, I think so. Answering loosely: say we want an integer $n$ so that $n^2$ is "close to" a certain value $r$ mod $\pi$. Let $s = \sqrt{r}$. Because the integers are dense mod $\pi$, there is an integer $k$ so that $k$ is "close to" $s$. Let $n = k$. $n^2 \mathrm{mod} \pi = k^2 \mathrm{mod} \pi = (k \mathrm{mod} \pi)^2$. So $n^2$ is "close to" $s^2 = r$ mod $\pi$.


text:
Q: get array of number of days of specified day with moment.js there is a way to obtain an array with day numbers of a specified month (current month) of a specified day name?
E.g. I want to obtain all Saturdays of June 2016.
I would like to have the array with [4,11,18,25] values. (4th June is Saturday, 11 too, and so on...).
Regards

A: Solved. Suppose that I want to obtain all Sundeys (so call function with 0 that is the number for Sundays)
function getDays(num){
    var dArray = new Array();
    var cMonth = moment().get('month');
    dArray.push(moment().day(num));
    if (moment().day(num-7).get('month') == cMonth) {dArray.push(moment().day(num-7));}
    if (moment().day(num-14).get('month') == cMonth) {dArray.push(moment().day(num-14));}
    if (moment().day(num-21).get('month') == cMonth) {dArray.push(moment().day(num-21));}
    if (moment().day(num-28).get('month') == cMonth) {dArray.push(moment().day(num-28));}
    if (moment().day(num+7).get('month') == cMonth) {dArray.push(moment().day(num+7));}
    if (moment().day(num+14).get('month') == cMonth) {dArray.push(moment().day(num+14));}
    if (moment().day(num+21).get('month') == cMonth) {dArray.push(moment().day(num+21));}
    if (moment().day(num+28).get('month') == cMonth) {dArray.push(moment().day(num+28));}
    return dArray;
};


text:
Q: llncs: Upright text in theorems and lemmas By default the llncs class defines a host of theorem-like environments, without my loading amsthm. Some of them, such as Theorem, Lemma, Corollary, set their text in italics.
I think this is not very good, typographically, and I would like to change it. Besides manually writing \normalfont after each \begin{theorem}, what can I do?
In a similar vein, I would also like to put a \qed before the end of each \end{proof}. Maybe there is a similar solution?

A: Preface (personal opinion): llncs.cls is not particularly pretty, so I would only use it if I had to (because of submitting to a Springer venue). In this case, I would not change the predefined settings, because this is the way the elements (like theorems) are supposed to look like. It's up to the editor to define a common appearance.
Regarding your questions: You can define your own environments, like
\spnewtheorem{thm}{Theorem}{\bfseries}{}

If you want/have to reuse the theorem environment, you can redefine it:
\let\theorem\relax
\spnewtheorem{theorem}{Theorem}{\bfseries}{}

To obtain a square at the end of proofs, llncs.cls defines  the command \qed.

\documentclass{llncs}
\let\theorem\relax
\spnewtheorem{theorem}{Theorem}{\bfseries}{}
\begin{document}
\begin{theorem}
  The theorem I worked on all my life.
\end{theorem}
\begin{proof}
  The result is obvious.\qed
\end{proof}
\end{document}


text:
Q: intersection Observer doesn't work in Edge I have a problem, where I need to fetch data when user scrolls to the bottom of the page. To solve this problem I use intersection Observer. And it works in Chrome, Firefox, Opera and Safari, but it doesn't work in Edge for a reason that I don't understand (and there is no error as well).
Here is what it is supposed to be

And here is Edge (no Loading...)

*

*I put console.log inside handleObserver function (inside if (this.state.prevY > y) {} statement) --> in Edge it didn't trigger

*And I've tried to reference the target by id instead of this.loadingRef - the result was the same.
Here is my react component:
/**
 * App main react component
 */
export default class Main extends Component {
  state = {
    cards: [],
    isFetching: false,
    page: 1,
    prevY: 0,
    sortValue: 'name',
    searchValue: '',
    prevSearchValue: '',
    numberLoaded: null,
  };

  /**
   * Initial data fetch
   */
  componentDidMount() {
    this.getCards(this.state.page);

    // Options
    const options = {
      root: null, // Page as root
      rootMargin: '0px',
      threshold: 1.0,
    };
    // Create an observer
    this.observer = new IntersectionObserver(
        this.handleObserver.bind(this), // callback
        options
    );
    // Observe the `loadingRef`
    this.observer.observe(this.loadingRef);
  }

  /**
   * Callback for Intersection Observer
   */
  handleObserver(entities, observer) {
    const y = entities[0].boundingClientRect.y;
    if (this.state.prevY > y) {
      const curPage = this.state.page + 1;
      this.getCards(curPage, this.state.sortValue, this.state.searchValue);
      this.setState({page: curPage});
    }
    this.setState({prevY: y});
  }

  /**
   * Data fetch
   */
  getCards(page, sortValue = 'name', searchValue = '') {
   //... code
  }

  /**
   * Renders component
   */
  render() {
    const loadingCSS = {
      height: '10px',
      marginTop: '0',
      width: '1px',
    };
    const {cards, isFetching, numberLoaded} = this.state;
    return (

          MTG Creatures{numberLoaded && ` (${numberLoaded} loaded)`}

        {!isFetching && cards.length === 0 && (

No cards have been found

        )}

        {/* code */}

        {cards.length !== 0 && <Cards cards={cards} />}

 (this.loadingRef = loadingRef)}
          style={loadingCSS}
        >
          {isFetching && <Loader />}

    );
  }
}

Per suggestion in MS Edge: IntersectionObserver. Does it work for you? I've tried to add min-width, min-height and a border --> it didn't work for me


text:
Q: Dataset Crashes Information and Definition functions Bug in 11.0.1 fixed in 11.1.0

Has anyone else noticed this odd function crash with Datasets.  Try the following in a clean kernel.
ds = ExampleData[{"Dataset", "Planets"}]

?`*

Repeated $RecursionLimit errors.

Have to abort evaluation.
??`*

Repeated $RecursionLimit errors.

Have to abort evaluation.
Add a second symbol.
x = 1

Now both ?`* and ??`* complete. However if you select ds the  $RecursionLimit errors return and you must abort evaluation.
Version 11.0.1 Win 7 Ent

CASE:3861310


text:
Q: Fallback Font Weights in CSS My font stylesheets are hosted on Fonts.com and out of my control. On the stylesheet, different weights of Avenir are implemented as different font families, each with a weight of 400. If the weight is anything but the default normal (400), the font renders oddly. So how do I make my fallback fonts bold while keeping the primary font weight as normal?

I tried to accomplish this by using the font CSS shorthand, thinking I could define different weights for each comma-separated value, like so:
font:   normal 400 18px 'Avenir 85 Heavy',
        normal 800 18px 'Calbri',
        normal 800 18px sans-serif;

But the browser doesn't recognize this structure, unfortunately, unless I eliminate all properties besides  on the fallbacks. Any suggestions, even inelegant ones?

A: When using @font-face, you typically want to apply a different font variant (= different font file), depending on whether your font is (1) normal, (2) italic, (3) bold or (4) italic + bold.
If you use the same font-family name for each variant along with their corresponding font-style and font-weight in your @font-face definitions, the correct font file will automatically be chosen depending on the font-style and font-weight of your elements.
Do this for all fonts defined with @font-face, and behavior should be as expected.

Demo

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 400;
  src: local('Droid Serif'),
       local('DroidSerif'),
       url(https://fonts.gstatic.com/s/droidserif/v6/0AKsP294HTD-nvJgucYTaI4P5ICox8Kq3LLUNMylGO4.woff2)
       format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 700;
  src : local('Droid Serif Bold'),
        local('DroidSerif-Bold'),
        url(https://fonts.gstatic.com/s/droidserif/v6/QQt14e8dY39u-eYBZmppwYlIZu-HDpmDIZMigmsroc4.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 400;
  src : local('Droid Serif Italic'),
        local('DroidSerif-Italic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/cj2hUnSRBhwmSPr9kS5898u2Q0OS-KeTAWjgkS85mDg.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 700;
  src : local('Droid Serif Bold Italic'),
        local('DroidSerif-BoldItalic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/c92rD_x0V1LslSFt3-QEpo9ObOXPY1wUIXqKtDjSdsY.woff2)
        format('woff2');
}

body {
  font-family : "Droid Serif", Georgia, serif;
}

.bold, .both {
  font-weight : 700;
}

.italics, .both {
  font-style : italic;
}

Title

This is a paragraph with some bold text, some text in italics  and some text that is both bold and in italics!

Depending on whether your text is bold, in italics or both, a different font will be used for the same font family!


text:
Q: if there are two regions enclosed by two lines how do I find area Equations
$y=x^3$ and $y=x$
obviously when graphing this, it would spit two areas formed.
Thus the "regular" way to set up the integral would be the following: $\int_{-1}^0(x^3-x)+\int_0^1(x-x^3)$ which gives me 0.5
But
how do I write this within one integral?

A: $$\int_{-1}^1 |x^3 - x|\text{d}x$$
Note that in order to actually solve this integral you'd still split the integral into the two pieces you originally had.

A: Absolute values.  You only care about the distance between $x$ and $x^3$, so use the "distance between" operator (a.k.a. absolute value).

A: Alternatively, a change of variable (y=-x) yields
$$
\int_{-1}^0 x^3-x\,dx
=-\int_{1}^0 y-y^3\,dy
=\int_{0}^1 y-y^3\,dy
$$
So,
$$
\int_{-1}^0(x^3-x)\,dx+\int_0^1(x-x^3)\,dx = 2\int_0^1(x-x^3)\,dx
$$


text:
Q: Can't download files from global area codeigniter I have these structure in my codeigniter app:
application
|
 --- some other folders
|
system
|
 --- some other folders
|
global
|
 --- docs
     |
      --- target folder
          |
           --- MY FILE

Now, I want my users download a file from  http://test.com/global/docs/targetfolder/MYFile
but codeigniter behave with download address as http:://test.com/controller/method/variable and I'll get 404 error.
Would you please let me know how can I fix this situation?
This is my main .htaccess file
# Turn on URL rewriting
RewriteEngine On

# Installation directory
#RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Protect application and system files from being viewed
RewriteRule ^(?:application|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

<ifModule mod_headers.c>
 Header set Connection keep-alive
 </ifModule>

RewriteCond %{HTTP_USER_AGENT} libwww-perl.*
RewriteRule .* ? [F,L]

<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>