text:
Q: Do all threads share the same instance of a heap variable, or have different instances of a heap variable? Computer Systems: a Programmer's Perspective says:

12.4.2 Mapping Variables to Memory
Variables in threaded C programs are mapped to virtual memory
according to their storage classes:
Global variables. A global variable is any variable declared outside
of a func- tion. At run time, the read/write area of virtual memory
contains exactly one instance of each global variable that can be
referenced by any thread. For example, the global ptr variable
declared in line 5 has one run-time instance in the read/write area of
virtual memory. When there is only one instance of a variable, we will
denote the instance by simply using the variable name—in this case,
ptr.
Local automatic variables. A local automatic variable is one that is
declared inside a function without the static attribute. At run time,
each thread's stack contains its own instances of any local automatic
variables. This is true even if multiple threads execute the same
thread routine. For example, there is one instance of the local
variable tid, and it resides on the stack of the main thread. We will
denote this instance as tid.m. As another example, there are two
instances of the local variable myid, one instance on the stack of
peer thread 0 and the other on the stack of peer thread 1. We will
denote these instances as myid.p0 and myid.p1, respectively.
Local static variables. A local static variable is one that is
declared inside a function with the static attribute. As with global
variables, the read/write area of virtual memory contains exactly one
instance of each local static variable declared in a program. For example, even though each peer
thread in our example program declares cnt in line 25, at run time there is
only one instance of cnt residing in the read/write area of virtual memory.
Each peer thread reads and writes this instance.

What about heap variables created by malloc() inside a thread function executed by multiple threads?
Do all the threads share one instance of the heap variable, or have different instances of the heap variable?
For comparison, different threads have different thread stacks, and a local automatic variable declared inside the thread function (executed by all the threads) has different instances in different thread stack.
Is it correct that different threads share the same heap? Does that imply that a heap variable declared in the thread function has the same instance in the heap?

A: There is no such thing like a "heap variable".
You have invented a new term, so expecting others to explain you the threading behaviour of this new thing does not make much sense to me.
There is, of course, "heap memory", and malloc returns a block of such memory. The start the adress of that memory can be stored in a pointer variable, and the latter can be either a global variable, a local automatic variable, or a local static variable - one of the types explained in your text book.
If two threads have a shared access to the same block of memory allocated by malloc depends - usually - on whether each of those threads calls malloc by itself (and keeps the returned adress in its own scope, without trying to reach other thread's memory by some bogus "random memory peeking" technique), or whether malloc is called just once and the adress is stored in a pointer acessible by both threads.

A: Initially I cannot understand your question, because the phrase "heap variable" is not described with sufficient detail and clarity, such that its meaning is a bit ambiguous.
Each call to malloc gets assigned a different address. That address assignment happens during the call to malloc, not before, not after.
When a thread function is executed on multiple threads, the malloc call made by thread #1 and the malloc call made by thread #2 generally do not return the same address. In other words, they are different.
However, threads can access memory data that is "owned" by other threads, provided that they somehow obtain the address of that data. This may occur via thread-to-thread communication.
In C, there are many types of thread-to-thread communication. For example, the first thread may store a heap pointer in a global variable A; the second thread may store a different heap pointer in a different global variable B. (Here, it is implied that A and B are of a pointer type, meaning that each is capable of holding a pointer value.)
Being global variables, both threads can read from both A and B.  Thus, the first thread can read the heap variable via B (the memory of which is allocated through the second thread); and vice versa.

A:
What about heap variables created by malloc() inside a thread function executed by multiple threads? Do all the threads share one instance of the heap variable, or have different instances of the heap variable?

All thread share all instances. It's like my wife and I each having a car. We each have our own car, but each of those two cars is jointly owned by both of us. I can use my wife's car if I want to, and she can use my car if she wants to. But generally, we each use "our" car for convenience and to avoid getting in each other's way. If I want to use "her" car without making arrangements with her, things can get inconvenient.
It's precisely the same with these variables. It's precisely the same if a single thread calls such a function recursively. There are multiple instances, but nothing steps any bit of code from accessing any instance if it can get a pointer to it somehow.

A: A variable has:

*

*an identifier, like the x in int x;,

*some memory* where the value is stored, and

*a scope, the rules for which parts of the program can "see" the variable.

Globals and static locals are stored at a location predetermined by the compiler in the data segment of the program. Automatic variables are stored on the stack.
And then there's malloc(), which allows the program to allocate heap memory, where values can be stored. So naturally, a variable with its value stored on the heap would be a "heap variable", right?
Except, there is no such thing. Recall that malloc returns a pointer. The pointer is a value, which can be stored in a variable. But there is no way to create a variable which refers to the value stored in heap memory. The only way to access heap memory is to dereference a pointer.
This is by design: malloc() and free() exist to create memory allocations which exist independently from the language rules about variables and scope. When you need a value which exists for the lifetime of the program, a global works well for that. And when you need a value that exists for the execution of a function, a local automatic variable will allocate memory (on the stack) at the start of the function, and free that memory when the function returns.
But what if you are implementing a server which can receive network requests to "create a widget" or "destroy a widget", and you require memory to store the state of the widget as long as it exists? The lifetime of the widget doesn't map to the scope of any kind of variable you can create in C: it's for these kinds of use cases the heap is used.
With that out of the way, how does the heap work with multiple threads? The answer is simple: all threads in C share the same address space. This means all memory, the heap included, is shared between all threads.
This is true even for local automatic variables. For example:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

int *ptr;

void *thread_a(void *arg) {
  int i;
  ptr = &i;
  i = 42;
  while(1) {
    printf("thread_a sees i as: %i\n", i);
    sleep(1);
  }
}

void *thread_b(void *arg) {
  while(1) {
    if(ptr == NULL) continue;
    printf("thread_b is incrementing i\n");
    *ptr += 1;
    sleep(1);
  }
}

int main() {
  pthread_t thread_a_id;
  pthread_create(&thread_a_id, NULL, thread_a, NULL);
  thread_b(NULL);
  return 1;
}

This produces:
$ gcc -o test test.c -lpthread && ./test
thread_b is incrementing i
thread_a sees i as: 42
thread_b is incrementing i
thread_a sees i as: 44
thread_b is incrementing i
thread_a sees i as: 45
thread_b is incrementing i
thread_a sees i as: 46
thread_b is incrementing i
thread_a sees i as: 47
thread_b is incrementing i
thread_a sees i as: 48
thread_b is incrementing i
thread_a sees i as: 48
thread_b is incrementing i
thread_a sees i as: 49
^C

This works because the value of i is stored at some address, and we put that address in ptr, and thus thread_b can discover the address where i is stored and increment the integer stored there.
This shared-memory model is notoriously difficult to get right. Did you notice first 42 was printed, then 44, skipping 43? This is because we have no control over when each thread executes. The OS can interrupt a running thread at any time, at which point it might start executing the other thread, or some other program entirely. Or both threads might be executing concurrently on a multi-CPU computer, and the CPU itself might reorder the memory accesses.
Also notice in thread_b we must check if ptr == NULL, because we can't be sure that thread_a has had a chance to set it yet.
It gets worse. Try compiling this with optimization:
$ gcc -o test test.c -lpthread -Wall -O3 && ./test
thread_a sees i as: 42
thread_a sees i as: 42
thread_a sees i as: 42
^C

Now the program is entirely broken! To figure it out, we have to disassemble the program, which I did with objdump -d -M intel test, and added comments:
0000000000001220 <thread_b>:
    1220:   48 83 3d 28 2e 00 00    cmp    QWORD PTR [rip+0x2e28],0x0  # compare ptr to 0 (NULL)
    1227:   00
    1228:   74 36                   je     1260  # if ptr was 0, jump to address 1260 (below)
    122a:   53                      push   rbx
    122b:   48 8d 1d ea 0d 00 00    lea    rbx,[rip+0xdea]        # 201c <_IO_stdin_used+0x1c>
    1232:   66 0f 1f 44 00 00       nop    WORD PTR [rax+rax*1+0x0]
    1238:   48 89 df                mov    rdi,rbx
    123b:   e8 00 fe ff ff          call   1040 <puts@plt>
    1240:   48 8b 05 09 2e 00 00    mov    rax,QWORD PTR [rip+0x2e09]        # 4050 <ptr>
    1247:   bf 01 00 00 00          mov    edi,0x1
    124c:   83 00 01                add    DWORD PTR [rax],0x1
    124f:   e8 0c fe ff ff          call   1060 <sleep@plt>
    1254:   48 83 3d f4 2d 00 00    cmp    QWORD PTR [rip+0x2df4],0x0        # 4050 <ptr>
    125b:   00
    125c:   75 da                   jne    1238 <thread_b+0x18>
    125e:   eb fe                   jmp    125e <thread_b+0x3e>
    1260:   eb fe                   jmp    1260 <thread_b+0x40>  # jump unconditionally to address 1260 (that is this instruction, creating an endless loop)
    1262:   66 2e 0f 1f 84 00 00    nop    WORD PTR cs:[rax+rax*1+0x0]
    1269:   00 00 00
    126c:   0f 1f 40 00             nop    DWORD PTR [rax+0x0]

Essentially, the compiler has "optimized" this bit of code:
while(1) {
  if(ptr == NULL) continue;
  # ...
}

The compiler knows that if ptr == NULL, this reduces to an endless loop doing nothing. So it looks at ptr just once, finds it to be null, and dutifully enters and endless loop, doing nothing.
The compiler can do this because the C specification doesn't require that the program actually "look" in memory on each iteration.
There are things you might do to "fix" this issue. For example, if you change the loop to:
while(1) {
  if(ptr == NULL) {
    printf("ptr is null; skipping\n");
    continue;
  }
  # ...
}

Now the program works for me. But this is an "accident", just as before there's no requirement that the compiled program actually look in memory on each access. It just happens that on my system, with my compiler, on this particular day, the generated program does.
Closer to a solution is to declare ptr as int * volatile ptr;. This tells the compiler it must look in memory every time, and the program will reliably work.
Or will it? While the volatile keyword guarantees the compiled program will look it memory every time, it doesn't guarantee that reads or writes to that memory are atomic. A pointer is typically 4 or 8 bytes wide. Let's say &i happens to be 0x12345678, and this is the value thread_a is going to write when it does ptr = &i;. But because C does not guarantee reads or writes on volatile variables are atomic, thread_b might read ptr when thread_a is half-way through writing it, and end up reading 0x12340000 or some other half-baked value. Then thread_a would end up incrementing something other than the value of i, which might corrupt some other variable, or crash the program. The corruption may not be discovered until the program has been running a while. These kinds of errors very difficult to debug, because the root cause of the problem happens long before the program crashes, and reproducing the failure condition, which depends on stochastic ordering of threads, is very difficult (especially when you don't even yet know what you're trying to find).
To make this program rigorously correct, you'd want to use some threading library which can either lock access to the variable such that it's never being read while it's being written, or which provides a data type which is guaranteed to be atomic.
This is just scratching the surface of threads, but hopefully I've given you a taste of how unpredictable they can be. When you sprinkle these subtle gotchas into a nontrivial program you can very easily end up with horrible, intractable bugs. Threads seem simple but their correct use requires great care. It's for these reasons that some programming languages (for example, Erlang) eschew shared, mutable state between threads ("processes", in Erlang) entirely.
So in summary:

*

*There is no such thing as a "heap variable".

*All threads "see" the same memory.

*Shared memory between threads is very difficult to get right.

* the compiler, as an optimization, might be able to store some values only in CPU registers, or not at all if the calculations involving the variable can be done at compile-time. But this has no effect on the semantics of the program. Except when it does, because you are using shared memory to communicate between threads!

A:
What about heap variables created by malloc() inside a thread function executed by multiple threads? Do all the threads share one instance of the heap variable, or have different instances of the heap variable?

In the sense in which I think you're asking - no. malloc is a function call. Each thread is independent. When two independent threads call malloc, two calls to malloc are made, and two distinct allocations are made. So, each thread that calls malloc gets a different storage region, and each will have its own object.
The thing that perhaps causes some confusion is that all the threads do have access to the other threads' allocations - they just need some mechanism to communicate with each other if they want to share dynamically-allocated objects. (Or, as per Doc Brown's answer, they can accidentally share due to a bug).

For comparison, different threads have different thread stacks, and a local automatic variable declared inside the thread function (executed by all the threads) has different instances in different thread stack.

Correct.

Is it correct that different threads share the same heap?

Yes, with the caveat that while "the heap" is the usual name for the free store managed by malloc, free etc. - it's not in the standard. It is an implementation detail. I shamelessly refer you to this answer and suggest we just talk about dynamic allocation instead.
Anyway, the free store is shared in the sense above that threads can look at memory allocated in other threads, and it is "the same" free store in that one thread can free memory malloc'd by another.

Does that imply that a heap variable declared in the thread function has the same instance in the heap?

No, because you still call malloc multiple times (once per thread), and each call must return a distinct allocation. If this didn't work for multiple threads, it wouldn't work for a single thread either.
int* x = malloc(sizeof(*x));
int* y = malloc(sizeof(*y));

It doesn't make sense for *x and *y to be the same object here, does it? And malloc wouldn't be at all useful if it behaved completely differently in single-threaded versus multi-threaded code.
At this point, I encourage you to note that you can just test this really easily. Why not find out for yourself what actually happens? You only need two threads, two calls to malloc and some print statements.


text:
Q: Adding a new line to existing txt file in c++ As a tutorial I've been a question to add new line to an existing file with a list of items. i've tried numerous ways to add it. no luck yet
            ofstream outdata;
            ifstream indata;

            indata.open("fruits.txt");
            outdata.open("fruits.txt");

            if(indata.is_open()){
             std::string fruit;
             std::cout << "enter a fruit to list "<<endl;
             std::cin >> fruit;
             outdata << "\n" << fruit << "\n" << endl;

             indata.close();
             outdata.close();

            return 0;

            }

This part of the code is supposed to ask the user to enter a value. Its supposed to be stored as new line without deleting the existing line. But here I'm. I've seen a few answers here. but can't find anything understandable.

A: When you open a file for writing its contents are immediately removed, if the file already exists.
       outdata.open("fruits.txt");

You opened the same file for writing here. This is before your code tries to read anything from the same file (I don't actually see anything in your code that tries to read it, I presume you left that part out). And by the time you get to the file it's already empty and there's nothing to read any more from it.
You have three choices:

*

*Read the entire contents of the file into your program, and only then open it for writing and write out the new contents.

*Open a different file for writing. After finishing reading and writing both files, and closing them, rename the new file to the original file.

*Open the file for appending:
 outdata.open("fruits.txt", std::ios::app);

It's not necessary to open it for reading, this will add to the end of the file, instead of overwriting it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Count movies with specific score, per actor I have movies and actors tables. Movies have a rating from 0 to 10. Each actor belongs to a group (table groups). Movies and actors are linked through movies_actors table.
For analytics purposes, I need the number of movies with rating between 0 and 1 (the upper bound excluded, named count0), between 1 and 2 (count1), ..., for every actor in a specific group.
Example of expected result:
actor_id | count0 | count1 | count2 | count3 | count4 | count5 | count6 | count7 | count8 | count9 |
---------|--------|--------|--------|--------|--------|--------|--------|--------|--------|--------|
       1 |      0 |      1 |      0 |      0 |      1 |      0 |      1 |      0 |      0 |      0 |
       3 |      1 |      0 |      0 |      0 |      1 |      0 |      0 |      0 |      0 |      0 |

sqlfiddle here
As you can see in the sqlfiddle, I achieved to get count0, count1, ... for a specific actor whose id is hardcoded into the query.
How do I get this information for every actor in a specific group?
Note: I use Postgres 9.4.1 with Ruby on Rails 5.

A: You can group by actor_id to get the desired results. You might want to join groups in as well if you want to filter by a column in there. (sqlfiddle)
SELECT
    actor_id,
    COUNT(CASE WHEN score >= 0 and score <= 1 THEN 1 END) count0,
    COUNT(CASE WHEN score > 1 and score  <= 2 THEN 1 END) count1,
    COUNT(CASE WHEN score > 2 and score  <= 3 THEN 1 END) count2,
    COUNT(CASE WHEN score > 3 and score  <= 4 THEN 1 END) count3,
    COUNT(CASE WHEN score > 4 and score  <= 5 THEN 1 END) count4,
    COUNT(CASE WHEN score > 5 and score  <= 6 THEN 1 END) count5,
    COUNT(CASE WHEN score > 6 and score  <= 7 THEN 1 END) count6,
    COUNT(CASE WHEN score > 7 and score  <= 8 THEN 1 END) count7,
    COUNT(CASE WHEN score > 8 and score  <= 9 THEN 1 END) count8,
    COUNT(CASE WHEN score > 9 and score  <= 10 THEN 1 END) count9
FROM movies
 INNER JOIN movies_actors ON movies_actors.movie_id = movies.id
 INNER JOIN actors ON movies_actors.actor_id = actors.id
WHERE actors.group_id = 1
GROUP BY actor_id


text:
Q: OSX Cocoa NSSearchField clear button not responding to click I place an NSSearchField and set its border to none and I found that the clear button is not clickable a.k.a. not responding when clicked. If I set the border again it's working fine.

I've been debugging this for a few hours, and found out that when I set the border to none, the text editor width will expand and shadow (cover) the clear button.
Screenshot

View hierarchy debug screenshot

Steps to reproduce:

*

*Create an empty cocoa project/app

*Place an NSSearchField

*Set border to none

*Run the app, fill the search field and try to click the clear button

Is this a bug? Or is it intended to behave that way?
Note: Newbie in cocoa development

A: I faced with this problem and deemed it as a bug in Cocoa. But it is easy to fix in custom control or in a view controller. Just keep text field bordered in interface builder and then kill the border by having new CALayer. For example:
class ViewController: NSViewController {

@IBOutlet weak var searchField: NSSearchField!

override func viewDidLoad() {
    super.viewDidLoad()

    let maskLayer = CALayer()
    searchField.layer = maskLayer
    maskLayer.backgroundColor = searchField.backgroundColor?.CGColor
}
}

As you see, I am just restoring control color in new layer not preserving anything else. It is not perfect, but at least gives good start.

A: julia_v's answer is almost correct. You should also remove searchButtonWidth from rect.origin.x to offset rect back.
And also I've added some more logic to make these "tricks" only, when it needed.
override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) {

    var newRect = rect

    if !isBordered || isBezeled {
        let cancelButtonWidth = NSWidth(cancelButtonRect(forBounds: rect))
        let searchButtonWidth = NSWidth(searchButtonRect(forBounds: rect))

        newRect.size.width -= (cancelButtonWidth + searchButtonWidth)
        newRect.origin.x += searchButtonWidth
    }
    super.select(withFrame: newRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength)
}

After creating subclass simply set it to NSSearchFieldCell instance in IB identity inspector.

A: Had the same problem in NSSearchField, created in code. Solved it by overriding the NSSearchFieldCell method in a subclass:
 - (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
{
    NSRect newRect = aRect;
    newRect.size.width -= (NSWidth([self searchButtonRectForBounds:aRect]) + NSWidth([self cancelButtonRectForBounds:aRect]));
    [super selectWithFrame:newRect inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
}

This method is called after the mouse click on the text area of the field. It also appeared to be a nice place to set the color of the insertion point.


text:
Q: Generate blob data from json object in node/express How can I create blob data from json object ?
I tried few approaches as shown below but front-end always receives empty blob.

Approach: 1
const buffer = require("buffer");

const myJsonFileData = { "id": 1, "name":"abc"};

const str = JSON.stringify(myJsonFileData );

const bytes = new TextEncoder().encode(str);

const blobForJsonFile = new buffer.Blob([bytes], {
    type: "application/json;charset=utf-8"
});

return res.send({filename:'xxx.json', blob: blobForJsonFile });

But front-end always receives
blob: {}
filename: "xxx.json"

If I get proper blob data, at FE, I want create xxx.json file.

Approach: 2
const Blob = require("buffer").Blob;

const myJsonFileData = { "id": 1, "name":"abc"};

const blob1 = new Blob([JSON.stringify(myJsonFileData , null, 2)], {
                        type: 'application/json',
              });

return res.send({filename:'xxx.json', blob: blobForJsonFile });

But it does give same empty result.


text:
Q: sp_Blitz Error on Azure SQL Database Getting the following error when trying to install sp_Blitz on a Azure SQL Database

Msg 40515, Level 15, State 1, Procedure sp_Blitz, Line 16 [Batch Start
  Line 15] Reference to database and/or server name in
  'master.sys.all_objects' is not supported in this version of SQL
  Server.

I can't see anything in the comments on the SP to suggest that Azure SQL Database isn't supported

A: In the readme of the first responder kit there is a statement on Azure SQL DB

Azure SQL DB - It's a dice roll. Microsoft changes DMV contents in
here without warning, so no guarantees.

There is another explanation by Scott Hodgin and a possible workaround by Henrik Staun Poulsen in this question.
Per Henrik's words

I've tried to make a version of sp_blitz that works on Azure SQL DB.
See here  Now, I'm looking for people that will test it.

You could test his version of sp_blitz and give him some feedback.


text:
Q: Update datagrid row by row from a big data table (Progress database), using a task or thread, but keeping the UI responsive during the update There is a datatable containing 40-50.000 records in it. I'm connecting to it via ODBC because that's the only way I'm allowed to.
The code below is a little project in which I want to test out a solution for viewing the records row by row, but in a way that the UI isn't frozen during the query. The code now works, more or less. The program opens, and when I click on the button, the UI freezes and at every record, updates itself, so that the user can see the articles. Though, they cannot controls the UI until the query is finished.
Can somebody help to solve it? I had a hard time reading documentations and listening to videos about tasks.
using System;
using System.Data.Odbc;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncSQLtest
{
    public partial class MainFrom : Form
    {
        DataPresenter presenter;

        public MainFrom()
        {
            InitializeComponent();
            presenter = new DataPresenter(this);
        }

        private async void LoadData(object sender, EventArgs e)
             => await presenter.QueryDataAsync(this.dataGridView1);
    }

    internal class DataPresenter
    {
        private MainFrom mainFrom;

        public DataPresenter(MainFrom mainFrom)
               => this.mainFrom = mainFrom;

        internal async Task QueryDataAsync(DataGridView dgv)
        {
            OdbcConnection con = new OdbcConnection("DSN=PA;UID=XXX;PWD=YYYYYYYYY");
            OdbcCommand cmd = new OdbcCommand("select Artikel from Table", con);

            dgv.Columns.Clear();
            dgv.Columns.Add("artikel", "artikel");

            try
            {
                con.Open();
                var reader = await cmd.ExecuteReaderAsync();
                while (await reader.ReadAsync())
                {
                    dgv.Invoke(new Action(
                        () =>
                        {
                            dgv.Rows.Add(reader.GetString(0));
                            dgv.Refresh();
                        }
                        ));
                }

                reader.Close();
                con.Close();
                cmd.Dispose();
            }
            catch (Exception e)
            {
                reader.Close();
                con.Close();
                if (cmd != null) cmd.Dispose();
                MessageBox.Show(e.Message);
            }
        }
    }
}

A: You do not need to use Invoke, since the insertion in the DataGridView occurs in the main thread. Only the query to the database occurs asynchronously.
The code can be simplified as follows
internal async Task QueryDataAsync(DataGridView dgv)
{
    try
    {
        dgv.Columns.Clear();
        dgv.Columns.Add("artikel", "artikel");

        using (var con = new OdbcConnection("..."))
        using (var cmd = new OdbcCommand("select Artikel from Table", con))
        {
            await con.OpenAsync();

            using (var reader = await cmd.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    dgv.Rows.Add(reader.GetString(0));
                }
            }
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

It will be much better to use virtual mode: walkthrough

A: The ExecuteReaderAsync of the OdbcCommand class most probably has the default synchronous implementation provided by the DbCommand base class. This means that also the await reader.ReadAsync() is most probably 100% synchronous. You could fix this problem by offloading the synchronous call to a background thread, using the Task.Run method:
var reader = await Task.Run(() => cmd.ExecuteReader());
while (await Task.Run(() => reader.Read()))
{

The dgv.Invoke(new Action( is probably redundant, because the QueryDataAsync is called from the UI thread.
Mixing data retrieval code with UI manipulation code is probably not a good idea, because it results to tight coupling between the application layers. If you are using C# 8 or later you could consider exposing the data in the form of an asynchronous stream (IAsyncEnumerable<string>):
internal async IAsyncEnumerable<string> QueryDataAsync()
{
    //...
    con.Open();
    var reader = await Task.Run(() => cmd.ExecuteReader());
    while (await Task.Run(() => reader.Read()))
    {
        yield return reader.GetString(0);
    }
    //...
}

...and consume it from the presentation layer like this:
private async void LoadData(object sender, EventArgs e)
{
    await foreach (string value in presenter.QueryDataAsync())
    {
        dgv.Rows.Add(value);
    }
}

It would still be tricky because of the compile error:

Error CS1626 Cannot yield a value in the body of a try block with a catch clause

You would probably have to replace the catch with a finally, and have the consumer handle the errors.


text:
Q: Minimist array of strings argument How can add an array-of-strings argument in Minimist?
I want to parse, say, foos with a CLI like this:
$ program foo bar baz
And have the result be ['foo', 'bar', 'baz'].
The equivalent in Python's argparse, for people that are familiar with that, would be nargs='+' (or nargs='*').


text:
Q: Am I better off splitting an elaborate mongoose model? Assuming the case of a /login API, where, for a matching set of credentials, a user object from the collection should be returned, which approach would be more performant:
1) One model with projection queries:
var UserSchema = new Schema({
  name        : String,
  email       : String,
  dob         : Number,
  phone       : Number,
  gender      : String,
  location    : Object, // GeoJSON format {type: 'Point', geometry: { lat: '23.00', lng: '102.23' }}
  followers   : [UserSchema],
  following   : [UserSchema],
  posts       : [PostSchema],
  groups      : [GroupSchema]
  // ... and so on
});

2) Split models:
var UserMinimalSchema = new Schema({
  name        : String,
  email       : String,
  phone       : Number,
  location    : Object,
});

var UserDetailSchema = new Schema({
  dob         : Number,
  gender      : String,
  followers   : [UserSchema],
  following   : [UserSchema],
  posts       : [PostSchema],
  groups      : [GroupSchema]
  // ... and so on
});

Let's say:

*

*For a logged-in user, only id, name, email, phone and location are to be returned.

*The first model will use a projection query to return the properties in (1).

*In the second case, only the UserMinimalSchema would be used to query the entire document.

*Essentially both queries return exactly the same amount of data as mentioned in (1).

*Assume that average user object is ~16MB limit and there are 1 Million records.
If someone performed such a test/links to documentation, it would be of great help to see how much it will matter to split or not.

A: I would not use split models:

*

*You'll have to perform a population query everytime you want to look all of the user's data

*You're increasing your data storage (you now will have to reference the user in your user details schema.

*When Mongo will go do a lookup, it will find references to model instances and only extract data that you've specified in your projection query anyways. It will not load the entire object into memory unless you specify that in your query.


text:
Q: Button function not handling the event properly when pressed? struct Question {
    var Question : String!
    var Answers : [String]!
    var AnswerNumber : Int!
}

class LevelOne: SKScene {

    var button = Button()

    var buttons = [Button]()
    let Question_met = UILabel(frame: CGRect(x: 0.3, y: 0.3, width: 40, height: 21))

    var Questions = [Question]()

    var QNumber = Int()

    var buttonNames = [""]

    var AnsNumber = Int()

    let selectors:[Selector] = [#selector(handleButton1), #selector(handleButton2), #selector(handleButton3),#selector(handleButton4)]

    override func didMove(to view: SKView) {

        let background = SKSpriteNode(imageNamed: "background")
        background.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
        background.zPosition = 0
        self.addChild(background)

        QuestionFunction()

        ButtonFuction()

        PickQuestion()

    }

    @objc func QuestionFunction(){

        Questions = [Question(Question: "What is a BMW ?", Answers: ["Bat","Cat","Vehicle","Pat"], AnswerNumber: 2),
        Question(Question: "What is a Boeing ?", Answers: ["Bat","Aircraft","Cat","Pat"], AnswerNumber: 1),
        Question(Question: "What is a Ant ?", Answers: ["Insect","Cat","Insect","Nate"], AnswerNumber: 2),
        Question(Question: "What is a Apple ?", Answers: ["Fruit","Cat","bat","Pat"], AnswerNumber: 0),
        Question(Question: "Where is london ?", Answers: ["UK","USA","France","Germany"], AnswerNumber: 0),
        Question(Question: "Where is New York ?", Answers: ["Canada","USA","France","Germany"], AnswerNumber: 2),
        Question(Question: "where is Berlin ?", Answers: ["UK","USA","Italy","Germany "], AnswerNumber: 3),
        Question(Question: "Where is Toronto ?", Answers: ["India","Africa","Canada","Norway"], AnswerNumber: 2),
        Question(Question: "Where is Rome ?", Answers: ["Japan","China","Italy","Ireland"], AnswerNumber: 2),
        Question(Question: "where is Chennai ?", Answers: ["India","Brazil","Swiss","Germany"], AnswerNumber: 0),]

        Question_met.frame = CGRect(x: 330, y: 70, width: 200, height: 21)
        Question_met.backgroundColor = UIColor.orange
        Question_met.textColor = UIColor.white
        Question_met.textAlignment = NSTextAlignment.center
        Question_met.text = "What caused Global Warming ?"
        self.view?.addSubview(Question_met)

    }

    @objc func ButtonFuction(){

        let stacView = UIStackView()
        stacView.spacing = 12
        stacView.distribution = .fillEqually
        stacView.axis = .horizontal
        stacView.translatesAutoresizingMaskIntoConstraints = false
        view!.addSubview(stacView)

        buttonNames = ["One","Two","Three","Four"]

        for name in buttonNames {
            button = Button()
            button.setTitle(name, for: .normal)
            stacView.addArrangedSubview(button)
            buttons.append(button)
        }

        for i in 0..<4{

            button.addTarget(self, action: selectors[i], for: .touchUpInside)

        }

        NSLayoutConstraint.activate([stacView.centerXAnchor.constraint(equalTo: view!.centerXAnchor),stacView.centerYAnchor.constraint(equalTo: view!.centerYAnchor),stacView.widthAnchor.constraint(equalToConstant: 350),stacView.heightAnchor.constraint(equalToConstant:70)])

    }

    @objc func PickQuestion(){

        if Questions.count > 0{
            QNumber = 0
            Question_met.text = Questions[QNumber].Question

            AnsNumber = Questions[QNumber].AnswerNumber

            for i in 0..<buttons.count{
                buttons[i].setTitle(Questions[QNumber].Answers[i], for: .normal)
            }
            Questions.remove(at: QNumber)
        }
        else {
            print("Done!")
        }
    }

    @objc func handleButton1() {

        if AnsNumber == 0 {
            PickQuestion()
            print("Correct!")
        }

        else {
            print("You are Wrong!!!")
        }
    }

    @objc func handleButton2(){

        if AnsNumber == 1 {
            PickQuestion()
            print("Correct!")
        }

        else {
            print("You are Wrong!!!")
        }

    }

    @objc func handleButton3(){

        if AnsNumber == 2 {
            PickQuestion()
            print("Correct!")
        }

        else {
            print("You are Wrong!!!")

        }

    }

    @objc func handleButton4(){

        if AnsNumber == 3 {
            PickQuestion()
            print("Correct!")
        }

        else {
            print("You are Wrong!!!")
        }

    }
}

The button action methods don't seem to be accurate in knowing which right answer button is being pressed while different number is assigned as answer for each question the methods seems to only move forward when pressing the last button.
Thank you in advance much appreciate the help.

A: Your problem is located in your ButtonFunction():
for name in buttonNames {
    button = Button()
    button.setTitle(name, for: .normal)
    stacView.addArrangedSubview(button)
    buttons.append(button)
}

for i in 0..<4{

    button.addTarget(self, action: selectors[i], for: .touchUpInside)

}

In the second loop, you do not initialize the button variable, so this is always the fourth button..
Better join this code in only one loop like so:
for i in 0..<4{
    button = Button()
    button.setTitle(buttonNames[i], for: .normal)
    stacView.addArrangedSubview(button)
    buttons.append(button)
    button.addTarget(self, action: selectors[i], for: .touchUpInside)
}

Beyond this solution some advices to your coding style:

*

*for convenience and better readability, function names and variable names should start with a lower letter

*declare your variables in the smallest possible scope.

*

*button, buttonNames and selectors are only used in ButtonFunction(), so these should be declared there.

*declaration of button should in fact be in the for loop only. This way, the compiler would have told you, that button is unknown in your second loop and you would have seen the problem on your own ;)


text:
Q: XML Divide by 1000 I'm having trouble when I try to divide a text field by 1000. Currently it's set to Millimetres but I need it to be set to metres. I thought by dividing the text field by 1000 it would do this but it throws the following error.
There was an exception while running the report
An exception occurred while creating a report.
root-cause=class groovy.lang.MissingMethodException/No signature of method: java.lang.String.div()
is applicable for argument types: (java.lang.Integer) values: [1000]"

The code for XML is as following:
<textFieldExpression><![CDATA[$F{EquipmentLengthMm} /1000]]></textFieldExpression>

I think I may require a variable expression to complete this?

A: Are you writing this in iReport or creating the jrxml manually? If the field is of type integer then EquipmentLengthMm/1000 should be a valid expression.
You can change the report default scripting language from groovy to java or javascript so use what you are most comfortable with. If you select the report at the top level of the tree and look into properties you can see language there.
Edit - the following works fine for me in Groovy but not in Java, I guess due to a type conversion error. Here is my xml if you are interested. Note number fields would be big decimal by default not integer (with oracle at least):
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test_UTC_conv" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="d86eb2f0-88fe-4b24-8f1e-3de8dc4116a4">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <queryString>
        <![CDATA[select 1 as col1
from dual
]]>
    </queryString>
    <field name="COL1" class="java.math.BigDecimal"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="79" splitType="Stretch"/>
    </title>
    <detail>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement uuid="9c3a86a8-43d4-45df-bbcf-9877cc60f8d1" x="23" y="0" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[COL1]]></text>
            </staticText>
            <textField>
                <reportElement uuid="12b0d8a4-78a6-44ca-ad0a-a663e00a4e45" x="123" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{COL1}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement uuid="10f0849d-bf16-48b0-b7c9-a1ef3c141638" x="223" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{COL1}/1000]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement uuid="49e2363e-a693-4f4e-aa77-3b168df302e5" x="307" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{COL1}/1000]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>


text:
Q: How to move nested divs containers to the left if content increases I have a div that has a dropdown menu and a label with a button on it.like follows

              hello : hi
              Availablility :
              helloooo :

tessssttt tessssssssssst

<button id="btnLogout" name="btnLogout">Log out</button>

https://jsfiddle.net/g9tdcrxh/2/
The problem I am having is when the text tessssst grows it moves to the left which I want.but it's blocking the triangle dropdown. How do I get the BtnUser div to expand and the triangle to move left when the text grows?
This is what it's doing

I need the position of the triangle to stay where it is, only when the text grows then can it move. The logout button should also stay where it is.
I want it to grow like this

What am I doing wrong? Your guidance will be highly appreciated, can you do it in jQuery?

A: I made a lot of changes. If you right-click elements in your browser, you should be able to select "inspect element" and hovering them in the list that appears, you can see their sizes/margins/paddings..

    <button id="btnLogout" name="btnLogout">Log out</button>

teshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijklteshrthrtrthrthtrhtrhabcdefghijkl

                        hello : hi
                        Availablility :
                        helloooo :

body {
    margin: 5px;
}

.container {
    overflow: hidden;
}

.user {
    overflow: hidden;

    margin-right: 95px;

    min-width: 500px;
    max-width: calc(100% - 100px);
    float: right;

    height: 30px;
    background-color: rgba(0,0,0,.75);
    text-align: center;
    color: #fff !important;
    cursor: pointer;
    right: 0;
    border-bottom-left-radius: .5em;
    display: block;
    box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
    padding-top: 0;
    border-radius: 1px;
    background-color: #1c1c1c;
    box-shadow: inset 0 10px 20px #333;
}

#btnLogout {
    width: 90px;
    background: linear-gradient(to bottom, #74be43 0%,#3a953e 64%,#3a953e 64%,#0f773b 100%);
    border: 1px solid #BFE1A7;
    box-shadow: none;
    border-radius: 4px;
    color: #FFF;
    border-left: 1px solid #ECF5EC;
    border-right: 1px solid #ECF5EC;
    line-height: 20px;

    position: absolute;
    top: 9px;
    right: 5px;
}

.dropMe {
    width: 10px;
    /*margin-top: -26px;*/
    /*margin-left: 110px;*/
    float:right;
    margin-left:10px;
}

.userDetails {
    /*margin-top: -20px;*/
    /*margin-left: -220px;*/
    text-transform: uppercase;
    font-size: 10px;
    color: #cecece;

    text-align: left;
    height: 22px;
    line-height: 22px;
    float:right;
    min-width: 376px; /* 600px - 110px (left margin) - 20px (arrow) - 90px (button) - 4px (button margin) */
    max-width: calc(100% - 20px); /* 20px (arrow) */
    overflow: hidden;
}

https://jsfiddle.net/g9tdcrxh/9/


text:
Q: E_ACCESSDENIED on CoCreateInstance Here is a code snippet
#include "stdafx.h"
#include <tchar.h>
#include <windows.h>
#include <dshow.h>
#include <ExDisp.h>
int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(NULL);
    HRESULT hr = S_OK;
    DWORD err = 0;

    // Try to create graph builder
    IGraphBuilder* pGraph = 0;
    hr = CoCreateInstance(CLSID_FilterGraph, NULL,
    CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&pGraph );
    err = GetLastError();

    // Here, hr is E_ACCESSDENIED
    // err is 5 (ERROR_ACCESS_DENIED)
    // Try to create capture graph builder (succeeds)
    ICaptureGraphBuilder2* pBuild = 0;
    hr = CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC_SERVER, IID_ICaptureGraphBuilder2, (void **)&pBuild );
    err = GetLastError();

    // Here, hr is S_OK
    // err is 0 (ERROR_SUCCESS)
    // Try to create IWebBrowser (succeeds)
    IWebBrowser2* pBrowser = 0;
    hr = CoCreateInstance (CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER, IID_IWebBrowser2, (LPVOID *)&pBrowser);

    err = GetLastError();

    // Here, hr is S_OK
    // err is 0 (ERROR_SUCCESS)
    return 0;
}

I'm trying to create IFilterGraph, which fails with E_ACCESSDENIED. On the other hand, creating other directshow objects works ok. The same with some other COM objects (tried with IWebBrowser2 as an example). Any idea what can be the problem? Thanks!

A: Well, that doesn't look good.  It is the result of a Windows security problem.  This would not normally fail, the coclass lives in c:\windows\system32\quartz.dll.  There are many possible operations that could cause the failure, including having trouble reading the registry and loading the DLL.
Perhaps the best way to troubleshoot it is to use SysInternals' ProcMon and observe your program's actions.  Pay attention to the Result column, you should see the error there.  This ought to get you closer to finding out what security configuration problem might be the source.


text:
Q: Ansible task to strip out data from a file A file has the following contents
com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

I need to fetch a43019cc-d4a4-4acb-83dd-defd76443c6a and write it to a variable using an Ansible task. This value need to be passed to other tasks in the same Ansible file.
Can someone show me the required task to achieve this.

A: If your file is on the controller, you can use the file lookup to get its content.
If the file is on the node, you will have to use something like the slurp module.
Then, when you have the file content, you can use the regex_search filter to extract your required text.

*

*With the file on the controller:
- set_fact:
     com_dkr_container_id: >-
       {{
         lookup('file', '/path/to/file')
           | regex_search('com\.dkr\.container\.id=(.*)', '\1')
           | first
       }}

*With the file on the node(s):
- slurp:
     src: /path/to/file
   register: file_content

- set_fact:
     com_dkr_container_id: >-
       {{
         file_content.content
           | b64decode
           | regex_search('com\.dkr\.container\.id=(.*)', '\1')
           | first
       }}

A: This is the job for the ini lookup plugin. See
shell> ansible-doc -t lookup ini

For example, given the file
shell> cat container.properties
com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

The playbook
- hosts: localhost
  tasks:
    - set_fact:
        id: "{{ lookup('ini', 'com.dkr.container.id
                type=properties
                file=container.properties') }}"
    - debug:
        var: id

gives
  id: a43019cc-d4a4-4acb-83dd-defd76443c6a

The lookup plugins work on the controller only. If the file is at the remote host fetch it, e.g. given the file
shell> ssh admin@test_11 cat container.properties
com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

The playbook
- hosts: test_11
  tasks:
    - fetch:
        src: container.properties
        dest: /tmp/fetched
    - set_fact:
        id: "{{ lookup('ini', 'com.dkr.container.id
                type=properties
                file=/tmp/fetched/{{ inventory_hostname }}/container.properties') }}"
    - debug:
        var: id

gives the same result
  id: a43019cc-d4a4-4acb-83dd-defd76443c6a

The playbook above is idempotent. The file will be stored at the controller
shell> tree /tmp/fetched/
/tmp/fetched/
└── test_11
    └── container.properties


text:
Q: PyQt - subclassing the QMainWindow to access Gui elements I use a QStackedWidget and switch between different views.  Each pane is basically a class and should reside in it's own file.
The problem is I want to access a QTableView from the other file without passing it's reference into the constructor.
Main File:
class MyApp(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        self.setupUi(self)

2nd File
from ui_MainWindow import Ui_MainWindow

class LimitsEditor(QMainWindow):
    def __init__(self, session):
        QMainWindow.__init__(self)
        self.tblCommonLimits_horizheader = QHeaderView(Qt.Horizontal)
        self.tblCommonLimits_horizheader = QMainWindow.tblLimits.horizontalHeader()

I get this error:
AttributeError: type object 'QMainWindow' has no attribute 'tblLimits'

As you can see, I want to access a table called "tblLimits" that I created in QtDesigner, but I'm unable to get access to it in my second file.
Any suggestions?
(edit for formatting)
I am editing this to show what I am doing that works:
In the main, when instantiating the class:
self.LimitsEditor = LimitsEditor(self.ui.tblLimits)

In the LimitsEditor file:
class LimitsEditor():
    def __init__(self, tblLimits):
        self.tblLimits = tblLimits

Now in the main I can access the table as either 'self.ui.tlbLimits' OR 'self.LimitsEditor.tblLimits'
This is how I have been doing it, and it works fine.  It just didn't seem quite right to me, so I was wondering if there was a way to just inherit the knowledge of all the UI elements into another class/subclass.

A: If what you are trying to do is to have LimitsEditor be able to access the exact same table instance being used by MyApp, then this approach you are trying is impossible. The .ui file is a description of a layout of widgets which you apply to your class. When you call setupUi() inside your QMainWindow class, it creates instances. The actual UI module does not contain any references to these instances that you can then access in another file.
You must share a reference to the instance from MyApp to LimitsEditor. This comes down to a design decision. Here are a few suggestions (since I don't know how your app is really organized)

*

*Wherever you are managing your stacked widget, you can pass a reference of the table instance to your LimitsEditor

*Let your LimitsEditor be unaware of the table widget, and emit signals, to which your parent objects will listen and manage the table instance in response

*Set up your LimitsEditor  with an eventsFilter for the table (in your parent object). Your LimitsEditor wont directly have a reference to the table, but rather will receive events for it that it can handle.

Referring to the exception that you are seeing, QMainWindow is the PyQt4 class and does not contain your custom child widgets. Those are located on the instance of your custom class which contains the setupUi() call. You would then need to access it via self.tblLimits, but again this would be only for the class that actually used the Ui file, not other random classes.

A: When working with the QtDesigner in PyQt you usually follow the same patter:

*

*Create the designer .ui file.

*Create a class to use it.

*Ensure that the ui file sets the widgets of your class.

For example:
class MyApp(QMainWindow):

    def __init__(self, parent=None):
        super(MyApp, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

class LimitsEditor(QMainWindow):
    def __init__(self, session):
        super(QMainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.tblCommonLimits_horizheader = QHeaderView(Qt.Horizontal)
        self.tblCommonLimits_horizheader = self.ui.tblLimits.horizontalHeader()

Make sure you do access the widget through the instance ui element.


text:
Q: File Not Found: Java I/O Issue I cannot get my file to read in my program... Why will the program not find the file? Am I not importing the file correctly?
Any feedback is much appreciated! Thank you
import java.util.Scanner;
import java.io.*;

public class ArraysIO {

    public static void main(String[] args) throws IOException {

        //local variables
        //create array
        String[] data = new String[100];
        //set up counter
        int count = 0;

        // Create File and Scanner objects inside main
        File file = new File("sampledata1.txt");
        Scanner inputFile = new Scanner(file);

        // Read in the names from the file
        while (inputFile.hasNext() && count < data.length) {
           data[count] = inputFile.nextLine();
           count++;
        }

        // Remember to close the file ASAP
        inputFile.close();

        // TODO Auto-generated method stub

    }

}

A: File file = new File("sampledata1.txt");

Is asking java to refer for a file located in current directory with name sampledata1.txt
now current directory is from where you launched your program generally, if you want to know where the current working directory points to you can check it by
System.out.println(System.getProperty("user.dir"));

A: Seems that I did not have the file in the correct location and I was not printing the scanner. Here is the working code that I had! Thank you for the help everyone!
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class ArraysIO2 {

        public static void main(String[] args) throws FileNotFoundException {

            // Create File and Scanner objects inside main
            File file = new File("sampledata1.txt");
            Scanner inputFile = new Scanner(file);

            for (int i = 0; i < 10; i++) {
                System.out.println(inputFile.next());
            }
            inputFile.close();
        }

    }


text:
Q: Java ScheduledExecutorService stopped some time after servlet initialization A function is implemented in my Tomcat server: basically a ScheduledExecutorService will be setup to run a task periodically upon the initialization of a HttpServlet. The code is like below:
@Override
public void init() throws ServletException {
    HttpsTool.setupUncheckedHttps();
    LOGGER.info("DeploymentInfoScheduler Initialized successfully....");
    System.out.println("DeploymentInfoScheduler Initialized successfully....");
    this.retrieveServiceDeploymentsInfo();
}

private void retrieveServiceDeploymentsInfo() {
    final Runnable deploymentsDataHandler = new DeploymentsDataHandler();
    final ScheduledFuture<?> beeperHandle = deploymentsInfoRetrieverScheduler
            .scheduleAtFixedRate(deploymentsDataHandler, 0, 5, TimeUnit.MINUTES);

}

If the servlet is initialized successfully, the task will keep running every 5 seconds forever. In the DeploymentsDataHandler's run method, A message is logged like below at the very beginning:
@Override
public void run() {
    LOGGER.info("Now begin a new round of refreshing deployment data...");
    this.doWorkFlow();
}

Correct me if I am wrong: no matter whether there is any exception unhandled in the doWorkFlow method, that message should always be logged every 5 minutes. But the fact is this scheduler runs well for some time and suddenly stops working, and even the message is stopped to be logged. Any possible explanation? How could I handle such an situation since I want to make sure this scheduler service is always running. Or is there any way to debug this issue?
I assume the following code will make sure the Scheduler will never stop executing even an exception occurs in the doworkFlow.
@Override
public void run() {
    try{
        LOGGER.info("Now begin a new round of refreshing deployment data...");
        this.doWorkFlow();
    }catch(Exception e){
        return;
    }

}

A:
Correct me if I am wrong: no matter whether there is any exception unhandled in the doWorkFlow method, that message should always be logged every 5 minutes

No, since the javadoc explicitly says:

If any execution of the task encounters an exception, subsequent executions are suppressed


text:
Q: Custom Button or Link in List View Rows In a Lightning Experience app, in a list view, can I add a custom action button/link to the action menu (highlighted below):

This button/link will provide a sort of checkout mechanism that changes the owner id from the object to the current user, then opens a custom LWC for them to edit details related to the item.
Alternatively, a separate link/button in its own column (not underneath the Actions dropdown menu) would be even better.

A: You cannot customize the list view item's actions. Actions in Lightning Experience mention this:

List view items support only specific standard actions, like Edit,
Delete, or Change Owner.

There's a couple lowly voted ideas asking for this ability:

*

*Custom actions on List view items

*Actions on List View Items for custom buttons
You can customize the buttons that display on the list view itself. This would allow you to select one (or multiple) records from the list view and perform an update action on them (quick action) or pass the record ids to a flow (through URL button) or VF page.

*

*Create a quick action of the type Update Record.

*Add it to the list view layout

Setup --> Object Manager --> Your Object --> Search layouts for Salesforce Classic --> Edit "List View" layout

If you need more complex logic to be initiated by the button (multiple screens) or to leverage a LWC, you'd have to look at utilizing it within a Flow or a VF page in a List Button that has Display Checkboxes (for Multi-Record Selection enabled.


text:
Q: How to pass docker arguments during docker run command or docker-compose up command i have to create a docker container from an docker image. When the container is started using docker run or docker compose up command, i want to pass some arguments to it and those argument values need to be replaced in a property file that will be available inside the container when it is started. I have tried to use entrypoint or CMD commmand, but it doesnt seems to work. Any idea to resolve this problem?

A: You can copy arguments in a file and then copy that file inside container. This can be achieved adding similar lines in Docker file
FROM jboss/wildfly

COPY Jberet-postgresql-configds.ddl /tmp/

Now, this file will be inside container at /tmp and ready to be used by programs inside container.


text:
Q: Ionic 2 (3) does not add os specific classes I have external module which I use in my app.
The shared module header
import {Component, OnDestroy, OnInit, Input} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import {Nav} from 'ionic-angular';

@Component({
    selector: 'hg-page-header',
    template: `
        <ion-header>
            <ion-navbar [class]="navbarClass">
                <button ion-button menuToggle end *ngIf="menuToggleRight">
                    <ion-icon [name]="iconName"></ion-icon>
                </button>
                <button ion-button menuToggle *ngIf="!menuToggleRight">
                    <ion-icon [name]="iconName"></ion-icon>
                </button>
                <ion-title [class]="navbarTitleClass">{{ title | translate}}</ion-title>
            </ion-navbar>
        </ion-header>
    `
})
export class PageHeaderComponent implements OnInit, OnDestroy {

    private ngUnSubscribe: Subject<void> = new Subject<void>();
    @Input() navbarClass: string;
    @Input() navbarTitleClass: string;
    @Input() title: string;
    @Input() iconName: string;
    @Input() menuToggleRight: boolean;

    constructor() {
    }

    private setListeners(): void {
    }

    ngOnInit() {
        this.setListeners();
    }

    ngOnDestroy() {
        this.ngUnSubscribe.next();
        this.ngUnSubscribe.complete();
    }
}

The external module.ts file
import {NgModule, ModuleWithProviders, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';
import {IonicModule} from 'ionic-angular';

import {ISharedModuleConfig} from './models/shared-config.model';
import {PageHeaderComponent} from './components/page-header/page-header.component';
import {MenuComponent} from './components/menu/menu.component';

@NgModule({
    declarations: [
        //Component
        PageHeaderComponent,
        MenuComponent
    ],
    imports: [
        IonicModule,
        TranslateModule.forRoot()
    ],
    exports: [
        //Component
        PageHeaderComponent,
        MenuComponent
    ],
    providers: [],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

export class SharedModule {
    static forRoot(sharedModuleConfig: ISharedModuleConfig): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [
                {provide: 'ISharedModuleConfig', useValue: sharedModuleConfig}
            ]
        };
    }
}

How I use it
<hg-page-header *ngIf="findMenuItemByComponent(nav?.getActive()?.component)?.showMainMenu" [iconName]="'menu'"
                [navbarClass]="'toolbar toolbar-ios toolbar-md'" [navbarTitleClass]="'title title-ios title-md'"
                [title]="nav?.getActive()?.component.name" [menuToggleRight]="true"></hg-page-header>

When I pass the classes as the example above, it works and everything is styled and all the ionic styling is in palce.
But when I remove the classes from the html and the [class]="variable" - ionic does not add it by itself.
The problematic items are ion-navbar and ion-title.

A: I found the problem with help from a friend
The [class] directive WILL OVERRIDE the default classes which are added by ionic


text:
Q: Oracle Creating ER Diagrams and Data Dictionaries I am new to Oracle Databases and would like to develop a data dictionary and ER Diagrams for our existing databases. Do you have any tips, scripts, tools for doing so?

A: We're using Sybase's PowerDesigner though I admit, its quite overkill for what you want.  We're using to support our full software engineering effort, from diagraming use-cases for requirements gathering, capturing those requirements, conceptual and physical models (database, object oriented code, infrastructure, etc), requirements/functionality verification matrices...
Basically anything UML-oriented that helps us to discover, architect, track and implement business solutions from an IT perspective.
Don't be fooled by the "Sybase" name - it supports MANY major RDBMS's and UML diagram formats and has templates for them all.  Its a very cool tool.

A: The free oracle sql developer data modeller works well. note that this is a seperate download than the one bundled with sql developer. The data model tool in sql developer does not have as many features.
http://www.oracle.com/technetwork/developer-tools/datamodeler/overview/index.html
It has some video walkthroughs.
file-> import -> data dictionary. You add a connection to a database and decide what you want to reverse engineer.
Note that the model part will be a mess and will take you time to make it neat enough to read. When oracle reverse engineers, it gives you a physical model and not an ERD. You can change the Physical Model into an ERD. However, most people do  not know what an ERD is and think an ERD is a physical model. ERDs have minimal value at the stage where your data model exists. There is no good reason to keep a physical model (which is easier for developers to read) and an ERD.
As far as data dictionary... This usually means documentation about your data model. The best way to do that is to use the tool and to use the "comment" command. Oracle allows you to create comments for all tables, columns and objects and store them in the database. This way you can have documentation in the database that is queriable. Sql Developer data modeller can query this.
You can do this in the GUI, but I find it faster to use "comment" commands and put it in the database from sql scripts, then pull it, instead of clicking on each object. Google "oracle sql comment" for details on how this works.

A: I know that SQLServer works with Visio; I'm not sure if Oracle does or not, never tried it, but Visio has a LOT of tricks up its sleeves.
Also, if you're in a reasonably large business, Visio isn't that hard to scrape up a copy of, albeit the license can be a little rich. But professional teams in reasonably large businesses usually already have Visio so it's not that big of a deal.
If anyone can deny or confirm that Visio will do this for Oracle as it does for SqlServer that would be awesome.

A: Oracle's Data Modeller can reverse-engineer from an existing database. They were charging for it at one time, but it is now free to use.

A: I answered same question in https://stackoverflow.com/questions/8140387/oracle-extract-graphical-database-representation/8149947#8149947
See below.
For a free tool I recommend schema spy, http://schemaspy.sourceforge.net/.
It needs Java Runtime.
Look to http://schemaspy.sourceforge.net/sample/relationships.html to see diagrams it generate.
simple usage with oracle hr template is given below.
SET JDBC_ORACLE_JAR=C:\oracle\product\10.2.0\client_1\jdbc\lib\ojdbc14.jar
SET CONNECTION_USERNAME=hr
SET CONNECTION_PASSWORD=hr
SET TNS_DATABASE_NAME=orcl
SET SCHEMA_NAME=HR
SET TABLE_NAME='EMP'
SET OUTPUT_NAME=HR_EMP

java -jar schemaSpy_5.0.0.jar -dp %JDBC_ORACLE_JAR% -db %TNS_DATABASE_NAME% -o     schemaOutput%OUTPUT_NAME% -u %CONNECTION_USERNAME% -p %CONNECTION_PASSWORD% -i %TABLE_NAME%.* -schemas %SCHEMA_NAME% -hq -noviews -loglevel severe

java -jar schemaSpy_5.0.0.jar -dp %JDBC_ORACLE_JAR% -db %TNS_DATABASE_NAME% -o     schemaOutput%OUTPUT_NAME% -u %CONNECTION_USERNAME% -p %CONNECTION_PASSWORD%  -schemas %SCHEMA_NAME% -hq -noviews -loglevel severe

First one will give you diagram with tables starting with EMP .
Second one will give you diagram with all tables in hr schema .

A: We use Dataedo for generating data dictionaries and ERDs for all our databases - Oralce & SQL Servers. You just connect to a database, schema is imported into repository and you can describe each element with UI. Tool enables splitting large databases into logical modules, defining missing FKs and UKs, use rich text and paste images. Using physical and logical FKs tool creates simple ERDs.
Each time database schema changes you can import those changes and they are automatically reflected in repository.
Data dictionary with ERDs are exported to PDF or interactive HTML.
I'm the product manager of Dataedo.


text:
Q: Comparing text field and Selection List value and alert I have a text field in which value gets populated when screen loads and also have a selection list.
My question is when user selects a value in Selection List and compares with the text field and trigger an alert message if its not equal.
Please help!
    JS:
function doType()
{
    if (document.getElementById("Text1").value != document.getElementById("Select1").value)
    alert(document.getElementById("Select1").value)
}

HTML:

        Select 1:

           <select name="Select1" onChange="doType();"></select>

         Text 1:

            <input name="Text1" type="text" size="10" maxlength="10">

A: JS:
function doType()
    {
      if(document.getElementById("Select1").value === document.getElementById("Text1").value){
        alert("Equal");
       }

      else{
       alert(" Not Equal");
      }
    }

HTML:
<select id="Select1"onChange="doType();">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>

<input id="Text1" type="text" value="Apple"/>


text:
Q: How can I make routing work for a Svelte app using nginx I have a Svelte app deployed in a docker image with a Nginx as reverse proxy in front of it. My problem is, that the routing is not working. I looked at the following link to resolve it: https://github.com/EmilTholin/svelte-routing/issues/144
I opted to server all requests with my index.html and changed the nginx config as follows:
location / {
 proxy_pass http://127.0.0.1:5000;
 try_files $uri $uri/ /index.html;
}

By doing this I am not getting a 404 anymore on my routes, but the page is blank because now my css, js, ... is not loaded correctly:
The stylesheet https://test.com/global.css was not loaded because its MIME type, "text/html", is not "text/css".
The stylesheet https://test.com/build/bundle.css was not loaded because its MIME type, "text/html", is not "text/css".
The script from "https://test.com/build/bundle.js" was loaded even though its MIME type ("text/html") is not a valid JavaScript MIME type.

As a next step I thought I need an exception for css, js, ... files so that only non css, js, ... files are served through the index.html and I added the following content to my nginx config file: (Source: Send all requests to index.html except certain extensions)
location ~ \.(js|css|png|jpg)$ {
}

Unfortunately this did not solve the issue and I am still having the same issues.
Does someone have another solution for this?


text:
Q: $18 \sec^2θ − 16 \tan θ \sec θ − 15 = 0$ Find all solutions in the interval $0° ≤ θ < 360°$. Find all solutions in the interval $0° ≤ θ < 360°$. If rounding is necessary, round to the nearest tenth of a degree.
$$18 \sec^2θ − 16 \tan θ \sec θ − 15 = 0$$
I'm getting $θ=14.1°, 55.5°, 124.5°, 166°$ but apparently this is incorrect. Can anyone spot why this isn't correct?

A: Multiplying throughout by $\cos^2(\theta)$, we get
$$18-16 \sin(\theta) - 15 \cos^2(\theta) = 0 \implies 18-16 \sin(\theta) - 15 (1-\sin^2(\theta)) = 0$$
Hence, we get
$$15 \sin^2(\theta) -16 \sin(\theta) + 3 = 0 \implies \sin(\theta) = \dfrac{8 \pm \sqrt{19}}{15}$$
This gives us
$$\theta = 2n \pi + \arcsin\left(\dfrac{8 \pm \sqrt{19}}{15}\right), (2n+1) \pi - \arcsin\left(\dfrac{8 \pm \sqrt{19}}{15}\right)$$
i.e.,
$$\theta \approx 360n^{\circ} + 55.48^{\circ}, 360n^{\circ} + 14.05^{\circ}, 360n^{\circ} 180^{\circ} - 55.48^{\circ}, 360n^{\circ} + 180^{\circ} - 14.05^{\circ}$$

A: $\dfrac{18}{\cos^2x} - \dfrac{16\sin x}{\cos^2x} - 15 = 0 \to 18 - 16\sin x - 15\cos^2x = 0 \to 18 - 16\sin x - 15(1 - \sin^2x) = 0 \to 15\sin^2x - 16\sin x + 3 = 0$.
$\triangle = (-16)^2 - 4\cdot 15\cdot 3 = 256 - 180 = 76$. So:
$\sin x = \dfrac{-(-16) + \sqrt{76}}{2\cdot 15} = \dfrac{16 + \sqrt{76}}{30} = 0.8239$. So:
$x = \sin^{-1}(0.8239) = 55.477$ degrees. Also we can take $x = 180 - 55.477 = 124.523$ degrees.
and $\sin x = \dfrac{16 - \sqrt{76}}{30} = 0.2427$. So: $x = \sin^{-1}(0.2427) = 14.04$ degrees.
We can also take: $x = 180 - 14.04 = 165.96$ degrees.
So the $4$ answers are: $55.47, 124.52, 14.04, 165.96$ degrees.


text:
Q: Sinatra: modular routes class not recognizing helper methods I am building an API in Sinatra, and have converted to a modular style. However, I am having an issue with method calls inside the routes files not being recognized.
I have simplified the app so the post is shorter, but the basic problem is that if I GET /test in WorkoutHandler - it cannot recognize methods in WardenStrategies or LoginHelper unless I also include those files in the Handler (they are already included in app.rb). However once I do that, the methods declared in the gems they use are unrecognized. All of these are registered in app.rb, and are required in my Rackup file.
Here is my app.rb file
require 'sinatra/base'
require 'sinatra/activerecord'

class WorkoutApp < Sinatra::Base

  register Sinatra::ActiveRecordExtension
  register WardenStrategies

  use WorkoutHandler

  helpers LoginHelper
  helpers HashHelpers

  use Rack::Session::Cookie
  use Warden::Manager do |manager|
    manager.default_strategies :password
    manager.intercept_401 = false
    manager.failure_app = WorkoutApp
    manager.serialize_into_session(&:id)
    manager.serialize_from_session { |id| User.find(id) }
  end
  set :database_file, '../config/database.yml'

  Warden::Manager.before_failure do |env, _opts|
    env['REQUEST_METHOD'] = 'POST'
  end
end

Here are the config.ru, Handler, and Helper files. (Handlers are just the name I use for Controller/Route files.
module LoginHelper
  def warden_handler
    env['warden']
  end

  def current_user
    warden_handler.user
  end

  def check_authentication
    return if warden_handler.authenticated?
    body 'User not authenticated'
    halt 401
  end
end

I was under the assumption that helpers, use, and register only need to be declared in app.rb (since I require all files in my rackup file and run the app from there). However the check_authentication method isn't recognized unless I register the helper here as well.
class WorkoutHandler < Sinatra::Base
  helpers LoginHelper                   # Is there a way to not need this?
  register WardenStrategies             # Or this?

  get '/test' do
    check_authentication
  end
end

module WardenStrategies
  Warden::Strategies.add(:password) do
    def valid?
      params['email'] || params['password']
    end

    def authenticate!
      user = User.find_by(email: params['email'])
      if user && user.authenticate(params['password'])
        success!(user)
      else
        fail!('Could not log in')
      end
    end
  end
end

require 'rubygems'
require 'bundler'

Bundler.require     #Shouldn't this give my Handler access to gem methods?

ENV['APP_NAME'] = 'workout'

require_all 'app'

run WorkoutApp

As of the time of this writing, I am getting the following error when running specs:
NoMethodError: undefined method `authenticated?' for nil:NilClass

This means that env doesn't have a :warden key/value (which I confirmed in console). The authenticated? method is in the Warden gem directory, so I guess I could require 'warden' in each Handler file - I don't think that's the way modular Sinatra apps are supposed to be constructed.
I've read all the blog posts and book chapters I can find on modular Sinatra apps, and I can't seem to debug my issue. From what I understand, needing to re-register (include) helpers in all files that use them is extraneous. I thought that by extending Sinatra::Base, I would have access to all declared classes in app.rb.
Any help would be appreciated. Thanks!

A: The short answer to your question is that every time you subclass Sinatra::Base, it creates a completely independent Sinatra application. Just because multiple classes subclass Sinatra::Base doesn't mean they all inherit each others' attributes. This is why it's called a "modular" style!
If you have some common functionality to be shared between different Sinatra applications, you can either create a mixin and extend/include it in every application (which is basically what you're doing now with helpers and register), or you can create an intermediate class that your applications subclass. For example:
my_base_app.rb:
require 'sinatra/base'
require 'warden'

require_relative 'login_helper'

class MyBaseApp < Sinatra::Base
  register WardenStrategies

  helpers LoginHelper
end

workout_app.rb:
require 'sinatra/activerecord'
require 'warden'

require_relative 'my_base_app'
require_relative 'hash_helpers'
require_relative 'workout_handler'

class WorkoutApp < MyBaseApp
  register Sinatra::ActiveRecordExtension

  use WorkoutHandler

  helpers HashHelpers

  use Rack::Session::Cookie
  use Warden::Manager do |manager|
    # yadda yadda...
  end
end

workout_handler.rb:
require_relative 'my_base_app'

class WorkoutHandler < MyBaseApp
  get '/test' do
    check_authentication
  end
end

As far as your question "Shouldn't this give my Handler access to gem methods?" that depends on how your Gemfile is laid out. If you have something like this:
gem 'sinatra', :require => 'sinatra/base'
gem 'sinatra-activerecord', :require => 'sinatra/activerecord'
gem 'warden'

Then yes, doing Bundle.require in your rackup script would eliminate the need to do individual require statements in your class files.


text:
Q: Move li to the right in menu I have a menu, and I would like to have the last 3 options (some images for Facebook/Twiter/Gmail) to be aligned to the right. So far I tried:
li:last-child { float:right;}- combine the 3 images in one to have the last option to the right, but not even so works
float: right; - the same result as above
text-align: right; - no change

#nav {
    background-color: #e26a63;
    padding: 0;
    margin: 0;
    font-family: FONT;
    font-size: 20px;
}

#wrap {
    padding-left: 60px;
    height: 100px;
    width: 100%;
    margin: 0 auto;
    display: table-cell;
    vertical-align: bottom;

}
#nav ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
    position: relative;
    min-width: 225px;
}
#nav ul li {
    display: inline-block;
}
#nav ul li:hover {
    background-color: #cb5f59;
}

#nav ul li:after {
  content: "";
  font-size: 0;
  display: block;
  height: 5px;

}
#nav ul li:hover:after {
  background: #9e4a45;
}
#nav ul ul li:hover:after {
  background: transparent;
}
#nav ul li a, visited {
    color: white;
    display: block;
    padding: 15px;
    text-decoration: none;
}
#nav ul li:hover ul {
    display: block;
}
#nav ul ul {
    display: none;
    position: absolute;
    background-color: #e26a63;
    border-top: 0;
    margin-top: 5px;
        z-index: 10;
}
#nav ul ul li {
    display: block;
}
#nav ul ul li a:hover {
    color: white;
}

Home

        Study

        Games

Riddles

                Flip card game

                Spot the mistake

                Multiple choice

        Read

        Contact

        About Us

        FB

            Twitter

            Gmail

A: Flexbox can do that:
JSfiddle Demo

#nav {
  background-color: #e26a63;
  padding: 0;
  margin: 0;
  font-family: FONT;
  font-size: 20px;
}
#wrap {
  height: 100px;
}
#nav ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
  position: relative;
  display: flex;
  align-items: center;
}
#nav ul li {} #nav ul li:hover {
  background-color: #cb5f59;
}
#nav ul li:after {
  content: "";
  font-size: 0;
  display: block;
  height: 5px;
}
#nav ul li:hover:after {
  background: #9e4a45;
}
#nav ul ul li:hover:after {
  background: transparent;
}
#nav ul li a {
  color: white;
  display: block;
  padding: .5em;
  text-decoration: none;
}
#nav ul li:hover ul {
  display: block;
}
#nav ul ul {
  display: none;
  position: absolute;
  background-color: #e26a63;
  border-top: 0;
  margin-top: 5px;
  z-index: 10;
}
#nav ul ul li {
  display: block;
}
#nav ul ul li a:hover {
  color: white;
}
#alignright {
  margin-left: auto;
}

Home

        Study

        Games

Riddles

            Flip card game

            Spot the mistake

            Multiple choice

        Read

        Contact

        About Us

        FB

        Twitter

        Gmail

A: First of all:
#nav {
    display: table;
    width: 100%;
}

.alignright { float: right; }


text:
Q: Replacing @selector with direct code
Possible Duplicate:
Can I pass a block as a @selector with Objective-C?

I have this code:
[myButton addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];

But since doSomething contains so little code, I was wondering if it is possible to put the code straight in here rather than making it run doSomething.
I have tried this already:
[myButton addTarget:self action:^ { /* code here */ } forControlEvents:UIControlEventTouchUpInside];

But it just gives an error of "sending (void)^(void) to incompatible type SEL".
Is there a way to do this? If so what is the correct syntax?
Thanks!

A: Well, all of your answers use a lot of unnecessary code which is horribly outdated and no longer works.
I found one answer myself though which I adapted and got this:
[myButton addTarget:[^{NSLog(@"Pressed the button");} copy] action:@selector(invoke) forControlEvents:UIControlEventTouchUpInside];

Which works fine.


text:
Q: Excel - matching 2 cells from one sheet in another I am trying to work out a formula that says if one cell in a sheet, and another cell in the same sheet match the same names of cells in a different sheet, then the answer is a cell between those sheets.
I've tried MATCH and INDEX but can't seem to get it to work. Is anyone able to assist?
Cheers