text:
Q: Displaying date to month dd, yyyy given time_cancel = 2019-01-06T23:29:35.000Z, would like to format it to month dd, yyyy (in this example, it is January 06, 2019)
In the following code, I have to write 12 if else block to convert mm to month
i.e. in this case, is to convert 01 to January.
is there a better /faster way to convert time_cancel to format month dd, yyyy in Javascript or Typescript/es6/react. Thanks in advance!
let date = time_cancel.split("T")[0];
var dateArray = date.split("-");
var month;

// 12 if else code
if(dateArray[1]=='01') month='January';
else if(dateArray[1]=='02') month='February';
 ....
else if (dateArray[1]=='12') month='December;

var res=month+" "+dateArray[2]+", "+dateArray[0];

A: .toLocaleDateString() can give you DD Month YYYY, but it doesn't let you customise the order. I would be very tempted to stick with this default behaviour, but you can chop it up if your really must. You still profit from the locale awareness and translations...

const formattedDate = new Date("2019-01-06T23:29:35.000Z")
.toLocaleDateString({},
  {timeZone:"UTC",month:"long", day:"2-digit", year:"numeric"}
  )
  console.log(formattedDate)
const sp = formattedDate.split(' ')
console.log(`${sp[1]} ${sp[0]}, ${sp[2]}`)

A: You can make an array like
let months = ["January", "February", "March", /*etc*/];

Read about getMonth()
lets say you have a date let date = new Date();
Simply do let m = date.getMonth() and it will return values from 0 to 11.
Then you can just say months[m] and you will get your desired date.
Here is a JSFiddle, feel free to edit the months in date to check it's validity.
http://jsfiddle.net/snqwg7vd/

A:

function formatraw(date, format, utc) {

    let raw = new Date(date.split(" ").join("T"));

    let res = format.slice();

    const MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    const ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    function ii(i, len) {
        let s = i + "";
        len = len || 2;
        while (s.length < len) s = "0" + s;
        return s;
    }

    const y = utc ? raw.getUTCFullYear() : raw.getFullYear();
    res = res.replace(/(^|[^\\])yyyy+/g, "$1" + y);
    res = res.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2));
    res = res.replace(/(^|[^\\])y/g, "$1" + y);

    const M = (utc ? raw.getUTCMonth() : raw.getMonth()) + 1;
    res = res.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]);
    res = res.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]);
    res = res.replace(/(^|[^\\])MM/g, "$1" + ii(M));
    res = res.replace(/(^|[^\\])M/g, "$1" + M);

    const d = utc ? raw.getUTCraw() : raw.getDate();
    res = res.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]);
    res = res.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]);
    res = res.replace(/(^|[^\\])dd/g, "$1" + ii(d));
    res = res.replace(/(^|[^\\])d/g, "$1" + d);

    const H = utc ? raw.getUTCHours() : raw.getHours();
    res = res.replace(/(^|[^\\])HH+/g, "$1" + ii(H));
    res = res.replace(/(^|[^\\])H/g, "$1" + H);

    const h = H > 12 ? H - 12 : H == 0 ? 12 : H;
    res = res.replace(/(^|[^\\])hh+/g, "$1" + ii(h));
    res = res.replace(/(^|[^\\])h/g, "$1" + h);

    const m = utc ? raw.getUTCMinutes() : raw.getMinutes();
    res = res.replace(/(^|[^\\])mm+/g, "$1" + ii(m));
    res = res.replace(/(^|[^\\])m/g, "$1" + m);

    const s = utc ? raw.getUTCSeconds() : raw.getSeconds();
    res = res.replace(/(^|[^\\])ss+/g, "$1" + ii(s));
    res = res.replace(/(^|[^\\])s/g, "$1" + s);

    let f = utc ? raw.getUTCMilliseconds() : raw.getMilliseconds();
    res = res.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3));
    f = Math.round(f / 10);
    res = res.replace(/(^|[^\\])ff/g, "$1" + ii(f));
    f = Math.round(f / 10);
    res = res.replace(/(^|[^\\])f/g, "$1" + f);

    const T = H < 12 ? "AM" : "PM";
    res = res.replace(/(^|[^\\]){TT}/g, "$1" + T);
    res = res.replace(/(^|[^\\]){T}/g, "$1" + T.charAt(0));

    const t = T.toLowerCase();
    res = res.replace(/(^|[^\\]){tt}/g, "$1" + t);
    res = res.replace(/(^|[^\\]){t}/g, "$1" + t.charAt(0));

    let tz = -raw.getTimezoneOffset();
    let K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
    if (!utc) {
        tz = Math.abs(tz);
        let tzHrs = Math.floor(tz / 60);
        let tzMin = tz % 60;
        K += ii(tzHrs) + ":" + ii(tzMin);
    }

    res = res.replace(/(^|[^\\])K/g, "$1" + K);

    const day = (utc ? raw.getUTCDay() : raw.getDay()) + 1;
    res = res.replace(new RegExp(dddd[0], "g"), dddd[day]);
    res = res.replace(new RegExp(ddd[0], "g"), ddd[day]);

    res = res.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
    res = res.replace(new RegExp(MMM[0], "g"), MMM[M]);

    res = res.replace(/\\(.)/g, "$1");

    return res;
}

console.log(formatraw("2019-01-06T23:29:35.000Z","MMMM dd, yyyy"))


text:
Q: Django test discovery does not find non django test cases I have am building an application that involves and some non-django functionality.
I have an app 'wit' under the source  directory that is a django application and that has test cases that are being deferred.
src/wit/   test_django_file1.py, test_django_file2.py etc.

But there are also test cases under that are not being discovered or run
src/utils/ test_nondjango1.py and test_nondjango2.py

src/utils is not a django application in the installed apps list
When I run do
cd src/
python manage.py test

The tests under src/utils are not being discovered or run
I am using django jenkins report coverage to get coverage reports.
I would idealy like all the test cases to be invoked with one invocation so that over all code coverage reporting works.
Or else I would like to know how to invoke separately if the above is not possibly so that I get to run all my test cases anyway.
How do I debug this, and figure out which directories are being explored.

A: Debugging
Is your utils dir a valid python package (has an __init__.py?).
And, are the modules under it importable? E.g can you do the following:
cd root_dir/
python -c "from src.utils import test_nondjango1"

If the above raises an ImportError, making it importable is one way you can make the tests "discoverable". Another way would be to specify the directory explicitly when running the tests:
python manage.py tests src.wit src/utils/

This provides two labels to the test runner: src.wit which a full Python dotted path and src/utils/ which is a relative directory.
Explanation
[Django docs state] that it "unittest module's built-in test discovery". The first paragraphs in the linked docs say:

Unittest supports simple test discovery. In order to be compatible
  with test discovery, all of the test files must be modules or packages
  (including namespace packages) importable from the top-level directory
  of the project (this means that their filenames must be valid
  identifiers).
Test discovery is implemented in TestLoader.discover(), but can also
  be used from the command line...

Just to clarify further, the discover() method docs says:

discover(start_dir, pattern='test*.py', top_level_dir=None)
Find all the test modules by recursing into subdirectories from the
  specified start directory, and return a TestSuite object containing
  them. Only test files that match pattern will be loaded. (Using shell
  style pattern matching.) Only module names that are importable (i.e.
  are valid Python identifiers) will be loaded.
All test modules must be importable from the top level of the project.
  If the start directory is not the top level directory then the top
  level directory must be specified separately.
If importing a module fails, for example due to a syntax error, then
  this will be recorded as a single error and discovery will continue.
  If the import failure is due to SkipTest being raised, it will be
  recorded as a skip instead of an error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Index on multiple bit fields in SQL Server We currently have a scenario where one table effectively has several (10 to 15) boolean flags (not nullable bit fields).  Unfortunately, it is not really possible to simplify this too much on a logical level, because any combination of the boolean values is permissible.
The table in question is a transactional table which may end up having tens of millions of rows, and both insert and select performance is fairly critical.  Although we are not quite sure of the distribution of the data at this time, the combination of all flags should provide relative good cardinality, i.e. make it a "worthwhile" index for SQL Server to make use of.
Typical select query scenarios might be to select records based on 3 or 4 of the flags only, e.g. WHERE FLAG3=1 AND FLAG7=0 AND FLAG9=1.  It would not be practical to create separate indexes for all combinations of the flags used by these select queries, as there will be many of them.
Given this situation, what would be the recommended approach to effectively index these fields?  The table is new, so there is no existing data to worry about yet, and we have a fair amount of flexibility in the actual implementation of the table.
There are two main options that we are considering at the moment:

*

*Create a single index which includes all the bit fields (this would probably include 1 or 2 other int fields which would always used).  My concern is that given the typical usage of only including a few of the fields, this approach would skip the index and resort to a table scan.  Let's call this Option A (Having read some of the replies, it seems that this approach would not work well, since the order of the fields in the index would make a difference making it impossible to index effectively on ALL the fields).

*Effectively do what I believe SQL Server is doing internally, and encode the bit fields into a single int field using binary operators (AND-ing and OR-ing numbers together: 1, 2, 4, 8, etc).  My concern here is that we'd need to do some kind of calculation to query on this encoded field, which would skip the index again.  Maintenance and the complexity of this solution is also a concern.  Let's call this Option B.  Additional info: The argument for this approach is that we could have a relatively simple and short index which includes one or two other fields from the table and this field.  The other fields would narrow down the number of records needing to be evaluated, and since the encoded field would contain all of our bit fields, SQL Server would be able to perform the calculation using the data retrieved from the index directly (i.e. an index scan) as opposed to the table (i.e. a table scan).

At the moment, we are heavily leaning towards Option B.  For completeness, this would be running on SQL Server 2008.
Any advice would be greatly appreciated.
Edit:  Spelling, clarity, query example, additional info on Option B.

A: A single BIT column typically is not selective enough to be even considered for use in an index. So an index on a single BIT column really doesn't make sense - on average, you'd always have to search about half the entries in the table (50% selectiveness) and so the SQL Server query optimizer will instead use a table scan.
If you create a single index on all 15 bit columns, then you don't have that problem - since you have 15 yes/no options, your index will become quite selective.
Trouble is: the sequence of the bit columns is important. Your index will only ever be considered if your SQL statement uses at least 1-n of the left-most BIT columns.
So if your index is on
Col1,Col2,Col3,....,Col14,Col15

then it might be used for a query that uses

*

*Col1

*Col1 and Col2

*Col1 and Col2 and Col3
....

and so on. But it cannot be used for a query that specifies Col6,Col9 and Col14.
Because of that, I don't really think an index on your collection of BIT columns really makes a lot of sense.
Are those 15 BIT columns the only columns you use for querying? If not, I would try to combine those BIT columns that you use most for selection with other columns, e.g. have an index on Name and Col7 or something (then your BIT columns can add some additional selectivity to another index)

A: Whilst there are probably ways to solve your indexing problem against your existing table schema, I would reduce this to a normalisation problem:
e.g I would highly recommend creating a series of new tables:

*

*Lookup table for the names of this bit flags. e.g. CREATE TABLE Flags (id int IDENTITY(1,1), Name varchar(256)) (you don't have to make id an identity-seed column if you want to manually control the id's - e.g. 2,4,8,16,32,64,128 as binary flags.)

*Create a new link-table that contains the id's of the original data table and the new link table e.g. CREATE TABLE DataFlags_Link (id int IDENTITY(1,1), MyFlagId int, DataId int)
You could then create an index on the DataFlags_Link table and write queries like:
SELECT Data.*
FROM Data
INNER JOIN DataFlags_Link ON Data.id = DataFlags_Link.DataId
WHERE DataFlags_Link.MyFlagId IN (4,7,2,8)

As for performance, that's where good DBA maintenance comes in.  You'll want to set the INDEX fill-factor and padding on your tables appropriately and run regular index defragmentation or rebuild your indexes on a schedule.
Performance and maintenance go hand-in-hand with databases. You can't have one without the other.

A: Whilst I think Neil Fenwick's answer is probably right, I think the real answer is to try out the different options and see which one is fast enough.
Option 1 is probably the most straightforward solution, and therefore likely the most maintainable - and it may well be fast enough.
I would build a prototype database, with the "option 1" schema, and use something like http://www.red-gate.com/products/sql-development/sql-data-generator/ or http://sourceforge.net/projects/dbmonster/ to create twice as much data as you expect to need, and then build the queries you expect to need. Agree an acceptable response time, and only consider a "faster" schema if you exceed those response times (and you can't throw hardware at the problem).
Neil's solution is probably just as obvious and maintainable as "option 1" - and it should be easy to index. However, I'd still test it by creating a prototype schema and generating a lot of test data...


text:
Q: How does angular escape bound values? Let's take this simple angular snippet:
<input type="text" ng-model="name" />

Hello {{name}}

If I enter the text  it looks as this is not executed but displayed as is. But if have a look at the generated HTML I see the script tag without any escapes.
I expected to see the angular brackets as HTML escape characters. So how does angular make sure this code is not executed?
(See Plunker http://plnkr.co/DeUCP74RZSGE2ypLqyRY)

A: It is actually html encoding it, which is why it isn't running. If you're using the chrome dev tools, it is showing them as regular angle brackets just for readability.
If you right click on the value and click "Edit as HTML", you'll see the content html encoded.


text:
Q: Getting latests messages depending on time query I have a table which has fields
i AM Saving messages for each type of user. so idValue is different for all the users.

idValue    message    time_added    type

I am using following query to get at start
SELECT * FROM messages WHERE idValue = 'iO9I22-AOI' ORDER BY time_added DESC LIMIT 30

This query gets the latest 30 messages (Kindly check if this query is alright).
Now upon button click , i want to get 30 or variable more messages. E.g If first query got 30 latest messages , now on button click I need to get 30 more latests messages but previous than the first 30.
I am not getting , how am i suppose to make its query.

A: You could modify the LIMIT on your query
let the page has a 'next' link which can generate pagination.
e.g clicking on
page.php?pagenum=2
would change the LIMIT to LIMIT 30,30
when you click on
page.php?pagenum=3
would make LIMIT 60,30
so the formula to change the LIMIT is
(pagenum-1)*30


text:
Q: Does moving vertexes split them? When i try to move my vertexes from my line feature in QGIS 2.10, the line is getting "separated", also when i delete the vertexes my line is getting holes. Any ideas why?

A: The feature that you need was added into QGIS six years ago based on this ticket http://hub.qgis.org/issues/748
The trick you must to do is to drag a rectangle around the end/start nodes for selecting them both so that you can move them together.

However, it you delete the selected nodes the result will be unexpected and surely not what you want. For reducing the number of vertices and keeping one contiguous linestring you should convert and merge/dissolve the multilinestrings into simple linestrings first.


text:
Q: Java MIDI Sequencer SyncMode Hi: I'm trying to get an instance of the MIDI Sequencer sync to an external clock. I did:
S_p = MidiSystem.getSequencer(false);
D2 = MidiSystem.getMidiDevice(MidiSystem.getMidiDeviceInfo()[1]);
S_p.open();
D2.open();
R2=S_p.getReceiver();
T2=D2.getTransmitter();
T2.setReceiver(R2);

but
for(int i=0;i<S_p.getMasterSyncModes().length;i++)
{System.out.println("Available modes are "+i+ " "+S_p.getMasterSyncModes()[i].toString());}

returns
 Available modes are 0 Internal Clock

which means this will be useless.
S_p.setMasterSyncMode(Sequencer.SyncMode.MIDI_SYNC);

What am I doing wrong ?
Of course I have confirmation of messages going out of D2 and into another receiver custom written to notify to system.out, and sequencer plays normally, it just appears that it doesn't support the SyncModes docs say it should. Specifically this phrase confuses me (from MIDI_SYNC:  "This mode only applies as the master sync mode for sequencers that are also MIDI receivers."
What's the meaning of the sequencer BEING a receiver. I thought it should be enough with my approach of getReceiver()
Regards and thanks !

A: For the future generations:
Homebrew, works-for-me, MIDI-clocked-sequencer.  (Guess it's now clear what it says about the sequencer BEING a receiver): (ASSUMES that receivers listen on different MIDI channels, and tracks are created accordingly. Sends all notes off at closing. Track_Master is from my implementation, keeps track of the channel the receiver is listening)
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;

/**
 * @author claudio
 *
 */

public class MIDI_Clocked_Sequencer implements Receiver {

private Sequence S;
private int[] playheads;
private long counter=0;
private Receiver[] receivers;
private long counter_reset;

/**
 * @throws MidiUnavailableException
 *
 */
public MIDI_Clocked_Sequencer(Sequence S,long counter_reset,int[]  where_to_get_receivers) throws MidiUnavailableException {
    this.setSequence(S);
    this.counter_reset=counter_reset;
    playheads=new int[S.getTracks().length];
    receivers=new Receiver[where_to_get_receivers.length];
    for(int i=0;i<where_to_get_receivers.length;i++){
        this.receivers[i]=MidiSystem.getMidiDevice(MidiSystem.getMidiDeviceInfo()[where_to_get_receivers[i]]).getReceiver();
        MidiSystem.getMidiDevice(MidiSystem.getMidiDeviceInfo()[where_to_get_receivers[i]]).open();
    }
}

@Override
public void close() {
    for(int j=0;j<receivers.length;j++){
        try {
            receivers[j].send(new ShortMessage(ShortMessage.CONTROL_CHANGE+Track_Master.channel_map.get(Track_Master.gui_map.get(j)),123,0), 0);
        } catch (InvalidMidiDataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
receivers[j].close();}
}

@Override
public void send(MidiMessage msg, long arg1) {
    Set<MidiMessage> message_buffer = new HashSet<MidiMessage>();
    if(msg.getMessage()[0]==-8){
        if(counter==counter_reset){counter=0;}
            for(int j=0;j<S.getTracks().length;j++){
                if(playheads[j]==S.getTracks()[j].size()){playheads[j]=0;};
                while(playheads[j]<S.getTracks()[j].size() &&   S.getTracks()[j].get(playheads[j]).getTick()==counter){
                message_buffer.add(S.getTracks()[j].get(playheads[j]).getMessage());
                playheads[j]=playheads[j]+1;
                }
            }
            for(Iterator<MidiMessage> it=message_buffer.iterator();it.hasNext();){
            MidiMessage f=it.next();
                for(int j=0;j<receivers.length;j++)
                {
                    receivers[j].send(f, -1);}
            }
            counter=counter+1;
      }
}

public Sequence getSequence() {
    return S;
}

public void setSequence(Sequence s) {
    this.S = s;
  }

}

A: Many questions at once!
1) The most important information is that Sequencers in Java Sound are plugins (service providers, SPI). Java ships with at least one Sequencer, but there is no mention that it does support all features imaginable. In particular, the existence of the getMasterSyncModes() query is an indication for the fact that not every Sequencer implementation will support all sync modes. And as you have found out, the default Sequencer in Oracle's Java happens to not support any sync modes except Internal. To be clear about it: the Java specification does not say that a Sequencer must support any particular sync mode.
2) It is, however, possible to add an own implementation of Sequencer with external sync in form of a plugin.

What's the meaning of the sequencer BEING a receiver?

3) I assume what is meant is that in order to sync to another master sync provider, a Sequencer must be able to receive the MIDI Sync messages, i.e. also receive MIDI messages. I agree that the terminology of Receiver and Transmitter is indeed confusing in Java Sound.

What am I doing wrong?

4) You're not doing anything wrong. You can query the sync modes, and if the Sequencer supports the sync mode you're after, it'll work. But chances are, you won't find such a Sequencer implementation...

S_p = MidiSystem.getSequencer(false);

5) As said above, in Java Sound, Sequencers are plugins just like MIDI devices and Synthesizers. So your system might provide multiple Sequencers. You can query MidiSystem.getMidiDeviceInfo(), get the various devices, and see if they are instanceof Sequencer to find all available Sequencers.
But I think the main answer is: there is probably no implementation of Sequencer publicly available which supports external synchronization.
It is possible to get active and fix it in OpenJDK's RealTimeSequencer...


text:
Q: How to write print statements to a csv file without using csvwriter I am trying to write few print statements along with some variable to a csv file without using csv writer.
sys.stdout = open("result.csv", "w")
..///...
print("something",variable)
...///...
.///..
print("something",variable)
..////...
sys.stdout.close()

I am using this to start writing to the csv file. But since I am running it from bash I want to have some print some statements from the code to reflect in the bash terminal.
Right now all the print statements are written directly to the csv file. Anyway I can print some statements to the terminal directly or any other way to write to csv file ?

A: You can try the following way.
import sys

variable_1 = 1
variable_2 = 2

# Open the csv file in writing mode
with open("result.csv", "w") as file:
    # Set the standard output to the csv file
    sys.stdout = file

    # Write to the csv file
    print(f"something1 {variable_1}")
    print(f"something2 {variable_2}")

    # Set the standard output to the console
    sys.stdout = sys.__stdout__

    # Print to the console
    print("This line is printed to the console")

sys.__stdout__ is the default output of the print function, thus you should set sys.stdout back to the default value (i.e., sys.stdout = sys.__stdout__) before closing the file, if not, you will get an ValueError: I/O operation on closed file..
You don't need to care about these things by using @Timus's method in the comment area, his method is more simple and efficient.
variable_1 = 1
variable_2 = 2

# Open the csv file in writing mode
with open("result.csv", "w") as file:

    # Write to the csv file
    print(f"something1 {variable_1}", file=file)
    print(f"something2 {variable_2}", file=file)

    # Print to the console
    print("This line is printed to the console")


text:
Q: Swagger-ui anchor link to model definitions Is it possible to access a model definition of via swagger-ui directly via an anchor?
In the example page http://petstore.swagger.io/ I see that the anchor works for a groups of endpoints, e.g.
http://petstore.swagger.io/#/pet.
Hovering the mouse over a model description shows me an anchor (e.g. #/definitions/Category for the Category model), but
http://petstore.swagger.io/#/definitions/Category does not bring me there.
If I inspect the elements, I see a real link to anchor pet:
pet
while for Category this is a model-hint:
#/definitions/Category
So I wonder if anchoring models is supported at all..

A: Swagger UI does not support permalinks for schemas/models. There's an existing feature request:
https://github.com/swagger-api/swagger-ui/issues/1369


text:
Q: Elixir "case clause error" while pattern matching HTTPoison response I'm using Httpoison to perform a get request and I want to pattern match the response using a case statement. Here is the code:
  def current() do
    case HTTPoison.get!(@api_url) do
      {:ok, %HTTPoison.Response{body: body, status_code: 200}} ->
        IO.puts body
      {:error, %HTTPoison.Error{reason: reason}} ->
        IO.inspect reason
    end
  end

When the status code is 200, print the body.
When there is an error, inspect the reason.
I get response from the server like so,
%HTTPoison.Response{body: "{\"USD\":10067.08}", headers: <<removed for readability>>, status_code: 200}

And the error of,  (CaseClauseError) no case clause matching:
Why am I getting a "no clause" error when I'm getting a response with a body and status code of 200?

A: Issue is the ! after get
HTTPoison.get!(@api_url) will return %HTTPoison.Response{body: body, ...} or raise exception.
If you want {:ok, %HTTPoison.Response{body: body, ...} then use HTTPoison.get(@api_url) (without !) instead.
Either this:
def current() do
    case HTTPoison.get(@api_url) do
      {:ok, %HTTPoison.Response{body: body, status_code: 200}} ->
        IO.puts body
      {:error, %HTTPoison.Error{reason: reason}} ->
        IO.inspect reason
    end
end

OR
def current() do
    %HTTPoison.Response{body: body, status_code: 200}} = HTTPoison.get!(@api_url)
    IO.puts body
end


text:
Q: The use of ReferenceArrayInput I've an issue with ReferenceArrayInput that I try to use for a group membership representation.
Here the code related to a group editing UI
export const UserGroupEdit = (props) => (
    <Edit title={<UserGroupTitle />} {...props}>
        <SimpleForm>
            <TextInput label="Common Name" source="commonName" />
            <TextInput label="E-mail" source="email" type="email" />
            <TextInput label="Shortname (UNIX purpose)" source="shortname" />
            <ReferenceArrayInput label="Members" source="members" reference="users">
                 <SelectArrayInput optionText="fullName" />
            </ReferenceArrayInput>
            <DisabledInput label="Record UUID" source="id" />
            <DisabledInput label="Record ID" source="numericID" />
        </SimpleForm>
    </Edit>
);

I've two issue.
First, if the related property in the represented object is empty, the UI does not display the input field. It show the title of the field, a whitespace with no input possible and the next one. When I pass the mouse over the whitespace, I get the same icon attached to the mouse as a DisabledInput, the forbidden sign.
Second, if there is already one value, I can add new one, I've the text input available and the autocompletion is working well. However, once I select one value to add, it immediately disappear. It does not stay in memory until the save or cancel action.
And if in the second case, I remove existing values, they get properly removed and once I remove everything I'm back to the first issue.
Is there something I'm doing wrong?

A: About your first issue, you can try to add a allowEmpty prop to your ReferenceArrayInput :
<ReferenceArrayInput label="Members" source="members" reference="users" allowEmpty>

A: It's a bug indeed. This issue has been fixed on master which will be released soon as version 1.4.0.


text:
Q: Different strategies to get a clean Kernel. Quit, Exit, ClearAll, Remove, CleanSlate? Often new users face problems with lingering definitions that, if unaware, may cause unexpected and frustrating behaviour.
There are several answers that illustrate different aspects of the solution, but not a single place that can serve as a guide where the best strategies are compared side by side.
For example, in this answer @celtschk points to the need of using
ClearAll[Evaluate[$Context <> "*"]]

instead of
ClearAll["Global`*"]

in the cases when the Notebook has a Context set to "unique to this Notebook".
This answer by @LeonidShifrin compares Remove versus ClearAll.
In this other answer @Szabolcs gives an extensive explanation to the "significant practical differences" between Quit versus ClearAll["Global`*"].
And here  @C.E. points to the use of
Needs["Utilities`CleanSlate`"]
CleanSlate[];
ClearInOut[];

Ultimately the advice seems to come to actually closing the kernel and starting one fresh, either via Exit or Quit.
Quit[]

But that doesn't cover preventive measures nor the possibility of a Dynamic cell in the notebook, or initialization commands or any other mechanism that could re-spawn definitions.
Here I'm hoping for a canonical guide to the problem of a fresh kernel.

*

*Prevention

*New kernel

*Cleaning

A:
NEW KERNEL

This is a Community Wiki answer, experienced users are welcome to add to it and correct mistakes.

To get a fresh kernel for the current notebook, one can either kill the current kernel and re-start it or associate and start a new different kernel.

Killing current kernel

Quit and Exit both terminates a Wolfram Language kernel session.
Simply
Quit[]

Alternately, one can select

Evaluation > Quit Kernel > Local

from the menu bar.  If you have set up alternate kernels (see below), replace "Local" with that kernel's name instead.

Configure alternative local kernels

Sometimes killing the current kernel may not be desirable, and the best approach is to start a second kernel.
If you don't have a second kernel already configured, then start by configuring a new kernel:

Evaluation > Kernel configuration options > Add > OK

or
CurrentValue[
  $FrontEnd,
  {EvaluatorNames, "Local2"}
  ] = {"AutoStartOnLaunch" -> False}

Associate a new kernel to the notebook

Then, associate a different kernel to the current notebook:

Evaluation > Notebook's kernel > #kernel-name#

or
CurrentValue[
  EvaluationNotebook[],
  Evaluator
  ] = "Local2"

Example

The animation shows the process to configure and associate a secondary local kernel.

A: The following may not be so useful in packages, but in open notebook evaluation the kernel can be repeatedly quit like so, using a tip from Arnoud Buzing.
In this case the orange cells evaluate repeatedly until b reaches 4. The value of a is lost on each quit.

Code text
ClearEvaluationQueueOnKernelQuit /. Options[$FrontEndSession]

SetOptions[$FrontEndSession, "ClearEvaluationQueueOnKernelQuit" -> False]

Clear[a, b]

a = If[ValueQ[a], a + 1, 1];
b = If[ValueQ[b], b + 1, 1];
SetOptions[EvaluationNotebook[], TaggingRules -> {"b" -> b}]

Quit[]

b = CurrentValue[{TaggingRules, "b"}];
If[b < 4,
 SelectionMove[nb = EvaluationNotebook[], Previous, Cell, 3];
 FrontEndExecute[FrontEndToken[nb, "SelectNextLine"]];
 FrontEndExecute[FrontEndToken[nb, "SelectNextLine"]];
 SelectionEvaluate[nb],
 {a, b}]

A: Cleaning

This is a Community Wiki answer, experienced users are welcome to add to it and correct mistakes.

Most of the solutions are already listed in the question.
ClearAll
In general this should be enough
ClearAll@"`*"

Here "`*" means all the symbols in current context. You may be more familiar with
ClearAll["Global`*"]

However, in the cases when the Notebook has a Context set to "unique to this Notebook" (See here), it won't work.
Please notice a single
ClearAll

with no argument won't have any effect!
❌Remove
Remove should not be used for this, see 37624 and 4921 .
Quit and Exit
Just quitting or exiting the Kernel and starting a new one will remove all lingering definitions, expect for the ones that are re-defined by initialization files like init.m. This other answer discussed new Kernel in detail.
Utilities`CleanSlate`
Undocumented utility
Needs["Utilities`CleanSlate`"]
CleanSlate[];
ClearInOut[];

Caveat
But that doesn't cover preventive measures nor the possibility of a Dynamic cell in the notebook, or initialization commands or any other mechanism that could re-spawn definitions.

A:
PREVENTION

This is a Community Wiki answer, experienced users are welcome to add to it and correct mistakes.

Best practice is to avoid the need to clean the kernel at all, by avoiding the creation of lingering definitions that may later obscures the behaviour of Mathematica.
Mathematica advises :

When you write a program in the Wolfram Language, you should always try to set it up so that its parts are as independent as possible.

Some ways to avoid lingering definitions are:

*

*Avoid creating variables

*Use nameless pure functions

*Scoping, keep variables local

*Use ReplaceAll

*Use long descriptive names

1. No variables

Take full advantage of Functional Programming and nest or compose all or most of your operations.
Do
f[g[h[x]]]

Instead of
a=h[x];
b=g[a];
c=f[b];
c

2. Pure functions

You can create functions without a name, using  Function or its short form (#)&. Read about Pure Functions.
Do
Map[(2 # + 1) &, Range[4]]

Instead of
f[n_] := 2 n + 1;
Map[f, Range[4]]

3. Scoping

You can limit the scope where a variable is defined using Scoping Constructs, effectively creating local variables. Look at Module, Block, With and when to use each.
With[
 {a = 3, b = 4},
 a^2 + b^2
 ]

4. ReplaceAll

If you need to evaluate your expression for a particular argument or parameter you can use ReplaceAll or its short form /.
π r^2 /. r -> 3.656365
(* 42. *)

5. Variable names

The shorter and common-place is your variable name, the most likely is to collide with something else. Don't store your data in a variable called x and then complain that Series[Sin[x], {x,0,3}] doesn't work. Use long names that start lowercase, to avoid using Symbols that have built-in meaning in Mathematica, like C, D, E, I, K, N, O.

A: rhermans mentioned using long descriptive variable names. Those variable names are even less likely to collide with other variables if they are a regular characters mixed with Script, Gothic and DoubleStruck characters. For example:

This approach is used in the source code of the Notation` package. Also keep in mind that the full name of built-in symbols always starts with a capital letter. If your variable starts with a capital letter and doesn't use Script, Gothic or DoubleStruck characters, it may be a built-in symbol in a future Mathematica release.


text:
Q: cannot update from Ubuntu 12.10 to 13.04 I have been trying to update from ubuntu 12.10 to 13.04 for several days.  Whenever I try to run the upgrade, I get the following message:
W:Failed to fetch http://extras.ubuntu.com/ubuntu/dists/raring/main/source/Sources  404  Not Found
, W:Failed to fetch http://extras.ubuntu.com/ubuntu/dists/raring/main/binary-i386/Packages  404  Not Found
, E:Some index files failed to download. They have been ignored, or old ones used instead.

The update then terminates.
Is there any work around to this?

A: These errors are coming because Ubuntu has stopped support for 13.04.
It is preferable you download and install the new and more secure 14.04 LTS(Long Term Support) version which will be in support for long.  But if you have update to 13.04 as your only option then you change your software sources to a server where files are still present.

For that you do the following:-

*

*Open Ubuntu Software Center

*Goto Edit -> Software Sources -> Ubuntu Software Tab

*Click the drop-down showing "Main Server"

*Select Other.

*Goto India -> choose ftp.iitb.ac.in

*Give Password if asked.

Retry your update.


text:
Q: Visual Studio Code App Center: Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8 I used Visual Studio Code App Center for Building my android apps, It was ok after but now build failed with below exception. How can I fix this issue?
FAILURE: Build failed with an exception.

* Where:
Build file '/Users/runner/work/1/s/app/build.gradle' line: 1

* What went wrong:
A problem occurred evaluating project ':app'.
> Failed to apply plugin 'com.android.internal.application'.
   > Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.
     You can try some of the following options:
       - changing the IDE settings.
       - changing the JAVA_HOME environment variable.
       - changing `org.gradle.java.home` in `gradle.properties`.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 45s
Error: /Users/runner/work/1/s/gradlew failed with return code: 1
    at ChildProcess.<anonymous> (/Users/runner/work/_tasks/Gradle_8d8eebd8-2b94-4c97-85af-839254cc6da4/1.128.0/node_modules/vsts-task-lib/toolrunner.js:569:30)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:920:16)
    at Socket.<anonymous> (internal/child_process.js:351:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:509:12)
##[error]Error: /Users/runner/work/1/s/gradlew failed with return code: 1

A: If you are using Visual Studio Code App Center, you may face the same kind of issue when you use JAVA 11 in your android project. If you are looking a solution for MS App Center issue, This may help you!

*

*Go to https://appcenter.ms/users/user1/apps/yourapp/build/branches

*Click settings icon to go to Build configuration

*Scroll down to Environment and turn on.

*Set JAVA_HOME to $(JAVA_HOME_11_X64)


text:
Q: improve array of hashes performance while returning subset
*

*1.I am trying to get the subset of array of hashes which will reject duplicate names that are greater than >=3

*for every 'number' key, return the subset of array of hashes with highest cost. If cost collides for that number return the first number (this number
was converted off a timestamp to reflect 1..24 hours)

I was able to achieve the results with the following code:
a= [{:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe3", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>300},
    {:name=>"John Doe2", :number=>2, :cost=>300},
    {:name=>"John Doe1", :number=>3, :cost=>400}]

a.group_by { |el| el[:name] }.
  reject { |_, v| v.size >= 3 }.
  values.
  flatten.
  sort_by {|h| h[:number]}.group_by{|el| el[:number]}.
  values.
  map{|el| el.max_by{|x| x[:cost]}}

  #=> [{:name=>"John Doe3", :number=>1, :cost=>100},
  #    {:name=>"John Doe2", :number=>2, :cost=>300}]

Would the above result in O(n^2)
What would be a better approach?

A: This appears to be more efficient than your current solution: (by ~20% according to the fruity gem)
a.group_by {|h| h[:name] }.each_with_object({}) do |(_,v),obj|
  if v.size < 3
    v.each do |sv|
      if obj[sv[:number]].nil? || obj[sv[:number]][:cost] < sv[:cost]
        obj[sv[:number]] = sv
      end
    end
  end
end.sort_by(&:first).map(&:last) # or just end.values if the sort is not a requirement
#=> [{:name=>"John Doe3", :number=>1, :cost=>100},
#    {:name=>"John Doe2", :number=>2, :cost=>300}]

First we group by name.
Then we build a new Hash and for each group that has less than 3 members we rotate through the list and add the member to the Hash under its number if the number does not exist or the member's cost is greater than the current cost.
Then we sort by the keys (number) and output the values. If you do not need the sorting then you can just use values
Benchmarking: (provided by the fruity gem)
Since the original post included sorting but the accepted answer did not I benchmarked both options.
Code
def cary_swoveland(a)
  a.group_by { |el| el[:name] }.
  each_value.
  reject { |v| v.size >= 3 }.
  flatten.
  group_by { |h| h[:number] }.
  transform_values { |v| v.max_by { |h| h[:cost] } }
end
def cary_swoveland_no_sort(a)
  cary_swoveland(a).values
end
def cary_swoveland_sorted(a)
  cary_swoveland(a).sort_by(&:first).map(&:last)
end
def engineers_mnky(a)
  a.group_by {|h| h[:name] }.each_with_object({}) do |(_,v),obj|
    if v.size < 3
      v.each do |sv|
        if obj[sv[:number]].nil? || obj[sv[:number]][:cost] < sv[:cost]
          obj[sv[:number]] = sv
        end
      end
    end
  end
end
def engineers_mnky_no_sort(a)
  engineers_mnky.values
end
def engineers_mnky_sorted(a)
  engineers_mnky.sort_by(&:first).map(&:last)
end

def original_post_no_sort(a)
  a.group_by { |el| el[:name] }.
  reject { |_, v| v.size >= 3 }.
  values.
  flatten.
  group_by{|el| el[:number]}.
  values.
  map{|el| el.max_by{|x| x[:cost]}}
end

def original_post(a)
  a.group_by { |el| el[:name] }.
  reject { |_, v| v.size >= 3 }.
  values.
  flatten.sort_by {|h| h[:number]}.
  group_by{|el| el[:number]}.
  values.
  map{|el| el.max_by{|x| x[:cost]}}
end

Data:
a= [{:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe3", :number=>2, :cost=>400},
    {:name=>"John Doe3", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>100},
    {:name=>"John Doe1", :number=>1, :cost=>300},
    {:name=>"John Doe2", :number=>2, :cost=>300},
    {:name=>"John Doe1", :number=>3, :cost=>400}]

Results:
# UNSORTED
Running each test 524288 times. Test will take about 4 minutes.
engineers_mnky_no_sort is faster than original_post_no_sort by 30.000000000000004% ± 1.0%
original_post_no_sort is faster than cary_swoveland_no_sort by 10.000000000000009% ± 1.0%

# SORTED
Running each test 262144 times. Test will take about 3 minutes.
engineers_mnky_sorted is faster than original_post by 19.999999999999996% ± 1.0%
original_post is faster than cary_swoveland_sorted by 10.000000000000009% ± 1.0%

Data:
a = n.times.map do
  {:name=>"John Doe#{rand(n / 2)}", :number=>(1..200).to_a.sample, :cost=>rand(1000)}
end

Results:
# Run 1 (n == 500)
# UNSORTED
Running each test 8192 times. Test will take about 3 minutes.
engineers_mnky_no_sort is faster than original_post_no_sort by 19.999999999999996% ± 1.0%
original_post_no_sort is similar to cary_swoveland_no_sort

# SORTED
Running each test 8192 times. Test will take about 4 minutes.
engineers_mnky_sorted is faster than cary_swoveland_sorted by 19.999999999999996% ± 1.0%
cary_swoveland_sorted is similar to original_post

# Run 2 (n == 1_000)
# UNSORTED
Running each test 4096 times. Test will take about 3 minutes.
engineers_mnky_no_sort is faster than original_post_no_sort by 10.000000000000009% ± 1.0%
original_post_no_sort is similar to cary_swoveland_no_sort

# SORTED
Running each test 4096 times. Test will take about 4 minutes.
engineers_mnky_sorted is faster than cary_swoveland_sorted by 10.000000000000009% ± 1.0%
cary_swoveland_sorted is faster than original_post by 10.000000000000009% ± 1.0%

A: a.group_by { |el| el[:name] }.
  each_value.
  reject { |v| v.size >= 3 }.
  flatten.
  group_by { |h| h[:number] }.
  transform_values { |v| v.max_by { |h| h[:cost] }[:name] }
    #=> {1=>"John Doe3", 2=>"John Doe2"}

This return value seems consistent with what is being asked in the question. If the value of each number is to be the hash h for which h[:cost] is largest, simply remove [:name]:
  ...
  transform_values { |v| v.max_by { |h| h[:cost] } }
    #=> {1=>{:name=>"John Doe3", :number=>1, :cost=>100},
    #    2=>{:name=>"John Doe2", :number=>2, :cost=>300}}

or, if desired:
  ...
  transform_values { |v| v.max_by { |h| h[:cost] } }.values
    #=> [{:name=>"John Doe3", :number=>1, :cost=>100},
    #    {:name=>"John Doe2", :number=>2, :cost=>300}]

This has a computational complexity of O(n) (n = a.size) because each step requires a single pass through at most a.size elements.
The steps are as follows.
b = a.group_by { |el| el[:name] }
  #=> {"John Doe1"=>[
  #      {:name=>"John Doe1", :number=>1, :cost=>100},
  #      {:name=>"John Doe1", :number=>1, :cost=>100},
  #      {:name=>"John Doe1", :number=>1, :cost=>100},
  #      {:name=>"John Doe1", :number=>1, :cost=>300},
  #      {:name=>"John Doe1", :number=>3, :cost=>400}
  #    ],
  #    "John Doe3"=>[{:name=>"John Doe3", :number=>1, :cost=>100}],
  #    "John Doe2"=>[{:name=>"John Doe2", :number=>2, :cost=>300}]
  #   }

We don't need the keys of this hash so we may as well extract the values now.
c = b.each_value
  #=> #<Enumerator:
  #     {"John Doe1"=>[
  #        {:name=>"John Doe1", :number=>1, :cost=>100},
  #        {:name=>"John Doe1", :number=>1, :cost=>100},
  #        {:name=>"John Doe1", :number=>1, :cost=>100},
  #        {:name=>"John Doe1", :number=>1, :cost=>300},
  #        {:name=>"John Doe1", :number=>3, :cost=>400}
  #      ],
  #      "John Doe3"=>[{:name=>"John Doe3", :number=>1, :cost=>100}],
  #      "John Doe2"=>[{:name=>"John Doe2", :number=>2, :cost=>300}]
  #     }:each_value>

Now remove the arrays containing 3 or more elements and flatten the result.
d = c.reject { |v| v.size >= 3 }
  #=> [
  #     [{:name=>"John Doe3", :number=>1, :cost=>100}],
  #     [{:name=>"John Doe2", :number=>2, :cost=>300}]]

e = d.flatten
  #=> [{:name=>"John Doe3", :number=>1, :cost=>100},
  #    {:name=>"John Doe2", :number=>2, :cost=>300}]

We need to group the hashes once again, this time by the key :number.
f = e.group_by { |h| h[:number] }
  #=> {1=>[{:name=>"John Doe3", :number=>1, :cost=>100}],
  #    2=>[{:name=>"John Doe2", :number=>2, :cost=>300}]}

Lastly, for each value (array of hashes) of fselect the element h for which h[:cost] is largest.
f.transform_values { |v| v.max_by { |h| h[:cost] } }
  # => {1=>{:name=>"John Doe3", :number=>1, :cost=>100},
  #     2=>{:name=>"John Doe2", :number=>2, :cost=>300}}


text:
Q: Windows Batch "dir" command change? It seems unlikely, but I can only assume that something changed recently (this week) during a Windows Update.
At least two scripts that use to work now do not.  That is, scripts I use almost every day. Among them are my script builder for a small Java project.
dir /s /B /a:-d *.java >sources.txt

"%JAVA_HOME%"\bin\javac %javaopts% -d ..\classes -nowarn -classpath %clspath% @sources.txt

Standard, right?  Except "dir" no longer removes the directory name (per a:-d) as it used to.  Hence, my java compile script is failing.  (Why yes, I also use Eclipse.)
As in, the files listed in the sources contain the full path of the file ("C:\X\Y\Z\src\foo.java").  By manually remove the path preceding src ("c:\x\y\z") the same script works.  I've tried different case on the options, changing around the javac command, but I always get the parsing error "unknown option c:...:) because of the full paths identified in the sources file.
Regardless of why it happened, it's happening now and I am looking for an alternative which I haven't found yet.  A simple alternative - I probably could write a loop that removes anything before "src" (for example) - but these two commands are cited many, many places so I thought I'd save someone the time and post myself.

A: The folks who commented are correct. the argument /a:-D does not remove directories.
See dir.
When you think abut it, if you want to "build a small Java project" (using the 2nd line of your script), why would you want to delete the folders that contain the java files whose fully qualified file names are written to sources.txt?

/s: Lists every occurrence of the specified file name within the
  specified directory and all subdirectories.
/b: Displays a bare list of directories and files (fully qualified names), with no additional information (i.e, date, time, size are omitted).
/a[[:]]: Displays only the names of those directories and
  files with the attributes that you specify.

If you use /a specifying the
-d attribute, Directories (d means Directories) are Not displayed (- means Not)
The bottom line is that sources.txt will have a bare list of fully qualified file names matching the mask *.java at and below whatever the current directory is at the time you run your script


text:
Q: Looking for title of book about a man with nanomachines in blood Back in the 90's I read a book and I have not been able to remember an author or a title, numerous searches have also found nothing.
I can only remember random details about the book. It is about a man who crash lands on a planet. He has nano machines of some kind in his blood that make him stronger, can heal a broken bone and administer morphine when he is injured, increase the length of his life, and they turn is skin a metallic color, I believe gold but maybe it was silver. They are powered by a power unit installed in the base of his spine.
The planet he crash(?) lands on plays a game involving tiles to work out their political issues instead of fighting wars, at the end of the book when they use the tiles to quickly advance technology to develop weapons.
At some point in the book/series the man gets imprisoned and has nothing to do but play the game, when he gets out of prison he has become a genius at it.
I would really love to reread this book, please help!

A: The description is also pretty close to The Last Hawk by Catherine Asaro, published 1997. Kelric, the protagonist, is a golden-skinned (not just tan or yellowish; they have metallic tints in their skin in his race) Jagernaut, a warrior with nanotech biological enhancements. He's also a telepath. On the planet he crash-lands, there is a matriarchal society, and the woman he marries "owns" him to a great extent. The game played is Quis, with crystalline "dice" of various shapes that are arranged in patterns on the table.

A: Also applies to Greg Bear's"Blood Music"


text:
Q: Gradle: How to add a custom task after compilation but before packaging files into a Jar? My build.gradle is currently:
project(':rss-middletier') {
    apply plugin: 'java'

    dependencies {
        compile project(':rss-core')
        compile 'asm:asm-all:3.2'
        compile 'com.sun.jersey:jersey-server:1.9.1'
        compile group: 'org.javalite', name: 'activejdbc', version: '1.4.9'
    }

    jar {
        from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
            exclude "META-INF/*.SF"
            exclude "META-INF/*.DSA"
            exclude "META-INF/*.RSA"
        }
        manifest { attributes 'Main-Class':
'com.netflix.recipes.rss.server.MiddleTierServer' }
    }
}

But rather than packaging these compiled classes into a jar directly, I'd like to instrument them first by running the following task:
task instrument(dependsOn: 'build', type: JavaExec) {
    main = 'org.javalite.instrumentation.Main'
    classpath = buildscript.configurations.classpath
    classpath += project(':rss-middletier').sourceSets.main.runtimeClasspath
    jvmArgs '-DoutputDirectory=' + project(':rss-middletier').sourceSets
        .main.output.classesDir.getPath()
}

Only after I have instrumented these classes, I will then want to package them into a JAR file. Is there a way so that I can do this instrumentation before the packaging?
Thanks a lot!!!

A: Finally figured out the way to do it!
task instrument(type: JavaExec) {
    //your instrumentation task steps here
}
compileJava.doLast {
    tasks.instrument.execute()
}
jar {
    //whatever jar actions you need to do
}

Hope this can prevent others from being stuck on this problem for days :)

A: This is a bit irrelevant to what is asked in the question. But thought to mention by thinking it may help to someone.
I was trying to execute a task with the type Copy before the Jar task.
task copyFilesTask(type: Copy) {

   //do whatever you want in here
}

compileJava.dependsOn(copyFilesTask)

jar {
    // jar actions. example below
    //manifest {
    //    attributes 'Main-Class': '<target-class-name-here>'
    //}
}

I have done this before the compileJava task because I need the relevant files to be available at the time of creating jar archive.


text:
Q: NG5 & RxJS: Make an Http Call on Load and Use the Data Once Available I need to make a call in Angular 5 on app load and then use the returned data throughout the app. The goal is to pre-load the data. Later, I need to use the data immediately, or wait for it to load, without duplicating the call.
I believe I have achieved the desired functionality as shown in this plunk, but I didn't do it correctly at all. I just made the call and subscribed to it right away so the observable is hot. So, this is mistake one - not making the observable hot correctly.
Here is my code, note the commented parts:
  constructor(private http: Http) {
    const testUrl: string = 'http://httpbin.org/delay/3';
    this.vlData = this.http.get(testUrl)
      .map( (res) => res.json() ).publishReplay(1).refCount()
      .catch( (err) => Observable.throw(error.json().error) )
      //.publish();

//this.vlData.connect();

  this.vlData.subscribe(
  (next) => {console.log('INITIAL DATA RETURN: ', next)},
  (err) => {console.log(`ERR: ${err}`)});

}
THE QUESTION: Is this code "bad"? If so, how do I accomplish the same result using the commented out operators publish and connect? Do I need to here?
P.S. I have about 15 articles / SO posts on the topic open, none of them seem to help, or I don't get it.

A: If you want to ensure that the data is cached after the first call then store the observable in a private field and return it after it has a value. The returned value(s) will resolve just the first time and be served up again on subsequent calls.
services/vl-data.service.ts (body code)
Note that this code was taken from the plunk link you posted, not the code posted in the question.
private _vlData: Observable<any>;

constructor(private http: Http) {}

getVlData(): Observable<any> {
    if(!this._vlData) {
        const testUrl: string = 'http://httpbin.org/delay/3';
        this._vlData = this.http.get(testUrl)
          .map( (res) => res.json() )
          .catch( (err) => Observable.throw(error.json().error) );
      }
    return this._vlData;
}

Some side notes:

*

*Try not to put any business logic or calls in your constructors, this makes them more difficult to test and ideally you want executions to occur explicitly instead of as a side effect of some other process (like when your service is created which you).

*You should consider using HttpClient instead of Http, the latter is considered obsolete/deprecated.

*You should consider using the RxJs pipable operators over the "older" patch operators.


text:
Q: How can I write a setup.py that ensures a non-code (data) file is at the same relative path from my script as in my repository? When I'm developing a project, and a script script.py needs access to some data file data.txt, I will usually write something like this:
path = Path(__file__).parent.parent / "resources" / "text" / "data.txt"

I then commit data.txt to source control, and when people clone the repo, everything will work. This works nicely until the project matures to the point that I want to write a setup.py to let people just install it straight from the repo with pip. At this point, I can't figure out how to tell setup.py to just put the resources folder in the "same place" in the package as it is in my repository. I've looked into package_data, data_files and MANIFEST.in but I haven't been able to get any solution working. How can I do this?


text:
Q: 'Search Result' windows opens during every boot in Sony Vaio S Series laptop I have a Sony Vaio S Series laptop running on Windows 7. Every time I turn on my system, the 'Search Result' window opens automatically at the very beginning.

As you can see from the screenshot, usually 4 or 5 'Search Result' windows opens at startup and the last window will remain with a blinking cursor. Also sometimes(not always) it cause Explorer to stop working. Everything works smooth after restarting Explorer.
For the last 2 weeks I searched everywhere for a solution including here. I have gone through more than 50 links at least. I have tried everything even restoring Windows through Vaio Care. But the problem is still there. Earlier 30+ windows were opening at startup and now only 4 or 5. This was the only change occurred after trying all the solutions found.
Please help me to solve this issue.

UPDATE:
Today when I started my system, I got a message from Explorer. See the screenshot.

After performing sfc /scannow cmd gave me this message:

The CBS Log of the sfc /scannow can be viewed from the following link- http://pasted.co/78df588f
NB: Search Results window also opens when the system wakes up from a sleep.

A: I would try this dism command for your new error as well, it also recommends trying them more than once if it doesn't work the first time.
It looks like this command should get past the errors with sfc.  Dism /Online /Cleanup-Image /RestoreHealth from this link http://www.eightforums.com/performance-maintenance/23398-running-system-file-checker-sfc-cbs-log.html .  There is a command prompt screenshot that I'm hoping are the same errors as you had with sfc.
You can also try this findstr /c:"[SR]" %windir%\logs\cbs\cbs.log >sfcdetails.txt which puts the .txt file here Windows\system32or replace sfcdetails.txt with %userprofile%\Desktop\sfcdetails.txt
This link http://www.sevenforums.com/performance-maintenance/371252-large-size-cbs-log-files-creating-never-before.html says to uninstall the Win 10 Prep update if you have it. Then run sfc.
This doesn't necessarily answer your question yet, but when sfc gives an error, we should probably listen and fix that first, then go from there.
Edit: Have you run sfc/scannow in safe mode?  All I could see at first glance in your CBS.log were desktop.ini files that were broken, it could be causing this issue but I kinda doubt it.  I'm still looking so I'll keep you posted.
Also, I'm assuming 'when you turn on the system' means when you login since I see Win Explorer?  I would try logging in as a different user/create a new user and see if these errors still occur as another test.


text:
Q: nextjs Build failed because of webpack errors on CentOS 7 I want to deploy a nextjs application on a centos server. But when i try to build using npm run build it gives me the following error

Browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
info  - Creating an optimized production build
Failed to compile.

ModuleNotFoundError: Module not found: Error: Can't resolve '../context/auth/AuthState' in '/var/www/html/projectname/pages'

> Build error occurred
Error: > Build failed because of webpack errors
    at build (/var/www/html/projectname/node_modules/next/dist/build/index.js:15:918)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! client-ubii-app@0.1.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the client-ubii-app@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-03-31T21_10_01_066Z-debug.log

But when i do the same on my local machine runnig windows 10 it works fine

A: If you has been change in name of file or folder only case sensitive character, this problem may be happen if your remote branch is not updated. Please, make sure if remote branch has the old name of file or folder. If true, fix it because the CentOs is Linux, so file and folder with same words in lower case is different with upper case.


text:
Q: How to launch a Desktop site from my app? I'm uploading a URL to CustomTabs. I want to enable pinch zoom in CustomTabs. By default it does not enable zoom pinch, but if you go to the menu and tapDesktop Site, enable pinch zoom.
I want to know that if there is a way to open Desktop site by default when the user launches a web URL from my app.

A: Checkout this answer...
I've tried this and it works well
How to open desktop site in webview in android
You can set user agent for your webView programmatically
In case something happens to the link, here's the answer for your question from that link:
private static final String DESKTOP_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36";
private static final String MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; U; Android 4.4; en-us; Nexus 4 Build/JOP24G) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";

//Choose Mobile/Desktop client.
WebSettings settings = mWebView.getSettings();
settings.setUserAgentString(DESKTOP_USER_AGENT);


text:
Q: Any difference between malloc and Marshal.AllocHGlobal? I write a module in C# that exports some functions to be used in C.
I need to allocate some memory for some structs to be passed between C <-> C#.
What I allocate in C I do with malloc, and in C# I do with Marshal.AllocHGlobal() (to allocate unmanaged memory to be passed to C).
Is there any problem if I free() the memory allocated with Marshal.AllocHGlobal, and if I release memory with Marshal.FreeHGlobal() which was allocated with malloc?
Thanks

A: There might or might not be a problem - this is totally implementation-dependant. Never rely on an implementation detail for your app functionality!
So I recommend not to use Marshal.AllocHGlobal(), malloc(), Marshal.FreeHGlobal() and free() crosswise.
One example, where you will run into dire trouble is if you use a library, that does some sort of fancy malloc()/free() magic - you might even not know that.

A: The golden rule is that you must deallocate from the same heap that was used to allocate the memory.
If you allocate it with malloc(), you must deallocate it with the free() from the same C RTL. And likewise on the managed side, AllocHGlobal() should be balanced by FreeHGlobal().
Now, AllocHGlobal() is implemented by calling the Win32 function LocalAlloc. So you could free such memory with a call to LocalFree on the native side. And vice versa.
If you want to use a heap that is shared between native and managed, it is more common to use the COM heap. On the native side use CoTaskMemAlloc() and CoTaskMemFree(). On the managed side use Marshal.AllocCoTaskMem() and Marshal.FreeCoTaskMem().
However, you should avoid designing the system like this. It is much simpler to stick to a rule that all memory allocated in the managed side is deallocated there, and likewise for the native side. If you don't follow that rule you will likely soon lose track of who is responsible for what.


text:
Q: Creating Eclipse Code Format XML From Java File (Reverse Engineering) I am working on a large project with thousands of java files, original author of project used some custom formatting to format java file which we don't have now, I tried to create a similar format in eclipse but it did't worked for me because there is still many differences, after writing code when i do press Ctrl+Shift+F it formats the document, but main problem comes when we have to merge file or compare with previous SVN version of file, because formatting of file changes, SVN shows thousands of changes which are not even true changes, and it even become impossible to merge it properly, What i want if i could extract format XML by giving my java file is it possible , Reverse engineering.

A: I don't know a way to reverse engineer a XML file from your code, but here is what you can certainly do:

*

*Check out the code and freeze the trunk so that noone else can commit the code

*Apply whatever formatting rules you want to apply - and apply this across your codebase

*Once you have done formatting changes- do whatever sanity checks you do before committing code (Like build, basic tests etc.)

*Now commit this code as "Formatting changes only- NO CODE CHANGED" - that way you have a logical commit of only formatting changes

*Now ask other developers to update their codebase. Thus you will have changed to new formatting rules without affecting anything.

*Also whatever rules you have in XML - ask other developers to implement in their IDE - so future commits are consistent in style and formatting.


text:
Q: MaterializeCSS tall input I have a MaterializeCSS input field which I want to be taller. I've tried setting a class "large" on the <div class="input-field"> and on the <input> itself, but that doesn't seem to do anything. Setting the css font-height makes the text larger but the input field itself stays the same size.
Is there any way to make a large MaterializeCSS input field?
Thank you!

A: Add those CSS lines to input, it will make the text higher and visible
.validate{
    font-size: 100px;
    height: 100px;
}


text:
Q: Adding shell variable to file path in Jenkins pipeline script I am writing a pipeline script in Jenkins, I have created a directory based on the $BUILD_NUMBER* environment variable using shell script by sh 'mkdir build/$BUILD_NUMBER'.
Now I want to artifact the zipfile I created into this BUILD_NUMBER folder. So I have written the below code:
zip zipFile: 'build/ResultsApp.zip', archieve: false, dir:'/Users/username/.jenkins/ProjectName/build/$BUILD_NUMBER'**
archiveArtifacts artifacts: 'build/$BUILD_NUMBER/ResultsApp.zip'

I am getting an error as /Users/username/.jenkins/ProjectName/build/$BUILD_NUMBER" does not exist. I have earlier created the BUILD_NUMBER folder using mkdir, but in dir option its not recognizing the BUILD_NUMBER Folder which I have created earlier.
$BUILD_NUMBER is not recognized as already created "number", instead recognizing as $BUILD_NUMBER name itself.
Can anyone tell me what have I written wrong?

A: I think you are missing the {}, the variable should look like:

archiveArtifacts artifacts: "logs_${params.ENVIRONMENT}.tar.gz",
fingerprint: true

that worked for me, hope it helps others too


text:
Q: Llamar a constructor plantilla en clase no-plantilla desde clase hija Estoy haciendo un wrapper en C++ para una librería en C (libuv, por si hay curiosidad).
Para mantener el código lo mas portable posible, estoy usando punteros a las struct originales.
Cada tipo de struct cuenta con una función de inicialización propia; pero, en mi wrapper, parto de una clase base que encierra en una union todos los posibles tipo de punteros a usar.
Para inicializar esos punteros, tengo que realizar una llamada a una función C concreta; para ello, mi clase base no es plantilla, pero cuenta con un constructor plantilla; la idea es que, desde cada clase hija, se llame a la especialización concreta a usar en cada caso.
Sin embargo, estoy teniendo problemas para llamar al constructor-plantilla de la clase base:
struct uv_loop_t {
  void *data;
};

struct uv_tcp_t {
  void *data;
};

void uv_loop_init( uv_loop_t * );
void uv_tcp_init( uv_tcp_t * );

namespace uv {

class uvbase {
protected:
  static uv_loop_t *currentLoop;

  union {
    uv_loop_t *loop;
    uv_tcp_t *tcp;
  };

  template< typename T > uvbase( void * = nullptr );

public:
  uvbase( ) = delete;
};

class uvloop: public uvbase {
public:
  uvloop( void *d = nullptr ) : uvbase< ::uv_loop_t >( d ) { }
};

}

template< > uv::uvbase::uvbase< uv_loop_t >( void *d ) {
  loop = new uv_loop_t;
  uv_loop_init( loop );
  loop->data = d;
}

template< > uv::uvbase::uvbase< uv_tcp_t >( void *d ) {
  tcp = new uv_tcp_t;
  uv_tcp_init( tcp );
  tcp->data = d;
}

Para probar que está correcto, ejecuté

g++ -std=c++11 -Wall -Wextra -pedantic -c test.hpp

Y obtuve una bonita secuencia de errores:

test.hpp: In constructor 'uv::uvloop::uvloop(void*)':
  test.hpp:31:33: error: 'class uv::uvbase uv::uvbase::uvbase' is not a non-static data member of 'uv::uvloop'
          uvloop( void *d = nullptr ) : uvbase< ::uv_loop_t >( d ) { }
test.hpp:31:39: error: expected '(' before '<' token
     uvloop( void *d = nullptr ) : uvbase< ::uv_loop_t >( d ) { }
test.hpp:31:39: error: use of deleted function 'uv::uvbase::uvbase()'
  test.hpp:26:3: note: declared here
     uvbase( ) = delete;
test.hpp:31:39: error: expected '{' before '<' token
     uvloop( void *d = nullptr ) : uvbase< ::uv_loop_t >( d ) { }

A continuación, cambié mi clase uvloop a
class uvloop: public uvbase {
public:
  uvloop( void *d = nullptr ) : uvbase::uvbase< ::uv_loop_t >( d ) { }
};

en un intento de indicar explicitamente que quiero llamar a un constructor plantilla.
Los resultados no mejoraron mucho:

test.hpp: In constructor 'uv::uvloop::uvloop(void*)':
  test.hpp:31:47: error: expected template-name before '<' token
     uvloop( void *d = nullptr ) : uvbase::uvbase< ::uv_loop_t >( d ) { }
test.hpp:31:47: error: use of deleted function 'uv::uvbase::uvbase()'
  test.hpp:26:3: note: declared here
     uvbase( ) = delete;
test.hpp:31:47: error: expected '{' before '<' token
     uvloop( void *d = nullptr ) : uvbase::uvbase< ::uv_loop_t >( d ) { }

*

*¿ Como llamo a una especialización concreta del constructor de la clase base desde el constructor de la clase hija ?

A: El problema es que no puedes especificar el argumento template en la llamada al constructor. Es que, literalmente, no tienes donde ponerlo; se debe confiar en la deducción automática del tipo.
Yo creo que debe haber algunas otras soluciones, incluida el uso de herencia, pero confiando en la deducción automática de tipos, una solución te propongo es:
struct uv_loop_t {
    void *data;
};

struct uv_tcp_t {
    void *data;
};

void uv_loop_init(uv_loop_t *) { }
void uv_tcp_init(uv_tcp_t *) { }

namespace uv {

    class uvbase {
    protected:
        static uv_loop_t *currentLoop;

        union {
            uv_loop_t *loop;
            uv_tcp_t *tcp;
        };

        template<typename T> uvbase(T *d = nullptr) { };
        template<> uvbase(uv_loop_t* d);
        template<> uvbase(uv_tcp_t* d);

    public:
        uvbase() = delete;
    };

    class uvloop : public uvbase {
    public:
        uvloop(uv_loop_t *d = nullptr) : uvbase(d) { }
    };

    class uvtcp : public uvbase {
    public:
        uvtcp(uv_tcp_t *d = nullptr) : uvbase(d) { }
    };
}

template<>
uv::uvbase::uvbase(uv_loop_t *d)
{
    loop = new uv_loop_t;
    uv_loop_init(loop);
    loop->data = d;
}

template<>
uv::uvbase::uvbase(uv_tcp_t *d)
{
    tcp = new uv_tcp_t;
    uv_tcp_init(tcp);
    tcp->data = d;
}

A: Problema.
Es un problema curioso, reproducible con el siguiente código:
struct base { template <typename T> base() {} };
struct derivada : public base {};

Estamos indicando que la clase base tiene un constructor por defecto, que incluso definimos, no debería ser un problema crear una instancia derivada con constructor por defecto ya que llamaría al constructor por defecto de base.
Pero, el problema es que base tiene constructor por defecto (constructor sin parámetros) plantilla y como tal, no existe hasta que se instancia, como problema adicional el hecho de que tenga un constructor definido (aunque inexistente) hace que otros constructores no sean considerados así que el verdadero constructor por defecto se considera borrado, dado que la clase base no tiene constructor por defecto la derivada no puede construirse.
Solución.
Una solución que podríamos pensar es indicar el parámetro plantilla de la clase base en las clases derivadas:
struct base { template <typename T> base() {} };
struct derivadaint : public base<int> {};
struct derivadachar : public base<char> {};

Pero falla porque esa sintaxis le indica al compilador que la clase base es plantilla, cuando no es cierto, la plantilla es tan sólo el constructor no la clase entera.
Así pues, la única manera de desambiguar el constructor plantilla de la clase base es al instanciarlo, en ese momento se podrá deducir el tipo subyacente de la plantilla ¡pero al carecer de parámetros, el constructor e la clase base no tiene ningún tipo sobre el que hacer deducciones!.
Por lo tanto, sólo queda la alternativa de añadir un parámetro al constructor para que el tipo de la plantilla pueda deducirse:
struct base { template <typename T> base(const T &) {} };
// parametro auxiliar para forzar deuccion --> ^^^

struct derivadaint : public base { derivadaint() : base(int{}) {} };
//                   usa el constructor base de int --> ^^^^^
struct derivadachar : public base { derivadachar() : base(char{}) {} };
//                    usa el constructor base de char --> ^^^^^^


text:
Q: Pattern matching email address in SQL Server We're getting fraudulent emails in our database, and are trying to make an alert to find them. Some example of email addresses we are getting:
addisonsdsdsdcfsd@XXXX.com
agustinasdsdfdf@XXXX.com
I want the query to search for:
pattern of consonants and pattern length > 4 characters
Here's what I have so far, I can't figure out how to get it to search for the length of the string. Right now it's catching addresses that have even two consonants back to back, which I want to avoid because that catches emails like bobsaget@xxxx.com.
select * from recips
where address like like '%[^aeiou]@%'

UPDATE
I think there is some misunderstanding of what I am trying to find, this is not a query for validating emails, we are simply trying to spot patterns in our signups for fraudulent emails.
we are searching on other criteria besides this, such as datelastopened/clicked, but for the sake of keeping the question simple I only attached the string that searches for the pattern. We don't mail to anyone who has hardbounced more than once. However, these emails in particular are bots that still find a way to click/open and don't hardbounce. They are also coming from particular sets of IP blocks where the first octets are the same, and these IP blocks vary.
this is by no means our first line of defense, this is just a catch-all to make sure we catch anything that slips through the cracks

A: I'd think your current query is finding bobsaget@xxxxx.com because it contains t@ which matches [^aeiouy]@ because that character-class between [] only matches 1 character unless you quantify it like so: [^aeiouy]{4,}@
Maybe that works, but what I'm getting from Googling about the using Regex in the WHERE clause in SQL-Server, you need to define a User Defined Function to do this for you. If that is too cumbersome, maybe doing something like this would do the trick:
WHERE address LIKE '%[^aeiouy][^aeiouy][^aeiouy][^aeiouy]@%'

Side note, just 4 seems strict to me, I know languages where Heinsch would be a valid name. So I'd go for 6 or more I think, in which case it would be [^aeiouy]{6,}@ or repeating the [^aeiouy] part 6 times in the above query.


text:
Q: JavaFx displaying info when a thread is terminated Here is my code in a loop I display the value of I in a label
   private void doLongOperation() throws InterruptedException {
        for (int i=1;i<=10;i++){
            System.out.println(i);
            Thread.sleep(500);
            int finalI = i;
            Platform.runLater(()->
            {
                monLabel.setText("Value From thread : "+ finalI);
                monBouton.setText("counting ..."+finalI);
            });
        }
    }

I call this function on a thread :
  Thread t11= new Thread(() -> {
        try {
            doLongOperation();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
 t11.start();

It works but I'd like to set my button text to "Something ..." when the thread is terminated, how can I implement this ?
I've tried if(t11.getState()== Thread.State.TERMINATED) but it's never terminated, I've tried t11.Join() but it no longer update the UI ??
Thanks for your help
I also try
finally {
/*                monBouton.setText("Do long operation");
                monBouton.disableProperty().set(false);*/
            }

But it tells me it's not a javas thread ...

A: Thanks Fabian
    }finally {
        Platform.runLater(()->{
            monBouton.setText("Do long operation");
            monBouton.disableProperty().set(false);
        });

    }
});


text:
Q: Find changesets based on workitem ID linked I'm looking for an API endpoint which can result me into the Changesets associated with the workItemID I provide as body of the API.
i.e. if I give workitemID as 12, it should return all the Changesets associated/linked with that workItem.
My project is in Azure DevOps and using TFVC.

A: You can use Get Work Item Rest Api with expand parameter. Then you can find ArtifactLink that started with vstfs:///VersionControl/Changeset/ URL. Powershell example:
$user = ""
$token = "<YOUR PAT>"
$teamProject = "<YOUR PROJECT>"
$orgUrl = "<YOUR ORG URL>"
$chUrlTemplate = "vstfs:///VersionControl/Changeset/"

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$uriGetWI = "$orgUrl/$teamProject/_apis/wit/workitems/2155?api-version=6.0&`$expand=all" #update id here (2155)

$result = Invoke-RestMethod -Uri $uriGetWI -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

foreach ($rel in $result.relations)
{
    if ($rel.rel -eq "ArtifactLink" -and $rel.url.StartsWith($chUrlTemplate))
    {
        $changeSetId = $rel.url.Replace($chUrlTemplate, "");

        Write-Host "ChangeSet Id:" $changeSetId
    }
}


text:
Q: QGradient ellipse blending I am currently working on generating "heat-maps" with QPainter and QImage. My method consists of drawing multiple circles with black to transparent QRadialGradients as the QBrush (see "Intensity Map"). Then I apply a gradient map to the intensity map to get the desired "heat-map" effect (see "After Gradient Map").
The issue I am having, which is more apparent in the "After Gradient Map" image, is that the circles are not blending correctly. Where circles overlap do seem to partially blend, but towards the edges you can clearly see where the circles end (almost a outer-glow). I would like an effect which has no visible borders between the circles and blends correctly.
Intensity Map

After Gradient Map (different intensity map)

Code
// Setup QImage and QPainter
QImage *map = new QImage(500, 500, QImage::Format_ARGB32);
map->fill(QColor(255, 255, 255, 255));
QPainter paint(map);
paint.setRenderHint(QPainter::HighQualityAntialiasing);

// Create Intensity map
std::vector<int> record = disp_data[idx]; // Data
for(int j = 1, c = record.size(); j < c; ++j) {
    int dm = 150 + record[j] * 100 / 255; // Vary the diameter

    QPen g_pen(QColor(0, 0, 0, 0));
    g_pen.setWidth(0);
    QRadialGradient grad(sensors[j-1].x, sensors[j-1].y, dm/2); // Create Gradient
    grad.setColorAt(0, QColor(0, 0, 0, record[j])); // Black, varying alpha
    grad.setColorAt(1, QColor(0, 0, 0, 0)); // Black, completely transparent
    QBrush g_brush(grad); // Gradient QBrush
    paint.setPen(g_pen);
    paint.setBrush(g_brush);
    paint.drawEllipse(sensors[j-1].x-dm/2, sensors[j-1].y-dm/2, dm, dm); // Draw circle
}

// Convert to heat map
for(int i = 0; i < 500; ++i) {
    for(int j = 0; j < 500; ++j) {
        int b = qGray(map->pixel(i, j));
        map->setPixel(i, j, grad_map->pixel(b, 0)); //grad_map is a QImage gradient map
    }
}

As you can see, there is no QPen for the circles. I have been trying a variety of blending modes with no success. I have also changed the rendering hint to HighQualityAntialiasing. I have also tried making the circles much larger than the radial gradient, so there is no way the gradient is cut-off or a border is applied to the outside of the circle.
Any ideas? Thanks!

A: I think this is a form of mach-banding, which is an optical illusion where changes in luminance are enhanced by the visual system, causing the appearance of bright or dark bands which are not actually present in the image. Typically these are seen on the boundary between two distinct areas, but in the case here I believe it is the sharp discontinuity in the gradients being observed.
Here are some images to demonstrate the issue:
This first image is calculated in software, and consists of three circles each drawn with a radial linear gradient. Mach-band effects should be visible at the edges of the overlap between circles, as these are the points where the gradient sharply changes.

This second image is exactly the same calculation, but instead of being linear along the radius, the gradient is mapped to a curve (I used the first hermite basis function). The bands should almost entirely have disappeared:

As to why this affects a colourised image more, I'm not sure it does. I think in the case above, perhaps there is additional banding caused by the colourisation effectively being a palette lookup, resulting in additional banding.
I performed roughly the same colourisation locally, also simply mapping a palette, and the effect is similar:

Fixing this using QT's linear gradients is probably non-trivial (you could try adding a lot more control points to the gradient, but you'll have to add quite a few...), but calculating such an image in software is not hard. You could also consider some other post-processing effects, such as adding a blur, and/or adding noise. Anything breaking the discontinuity in the gradient would likely help.

A: I agree with JasonD.
Furthermore, please keep in mind that Qt is doing linear blending in sRGB color space, which is not linear (it has a gamma 2.2 applied).
To do this right, you need to do the blending or interpolation in linear light, then convert to sRGB (apply gamma) for display.


text:
Q: Enforcing Restritions On DataContracts Is there any way one can enforce restrictions on values passed in the form of data contracts as parameters to a given WCF Service?
For instance, please consider the contrived and certainly non-compilable example of this Vehicle class:
[DataContract]
public class Vehicle
{
    [DataMember]
    [Restriction(MinValue = 1, MaxValue = 30)] // Certainly not allowed... or is it?
    public int NumberOfWheels { get; set; }
}

Since, of course, nobody expects to find a vehicle with more than, say, 30 wheels, I would like to limit the range of the NumberOfWheels to a value between 1 and 30. Is there any way one can use XSD restrictions/facets to limit the range of acceptable values in this case?
(Please note that I could, of course, change the type of the NumberOfWheels from int to, say, byte to further limit the range of possible values. However, that wouldn't solve the problem... Of course, no one expects a vehicle to have 255 wheels.)

A: Here is an example using dataannotations:
using System.ComponentModel.DataAnnotations;

[DataContract]
public class Test
{
    [DataMember]
    [Range(1, 30)]
    public int MyProperty { get; set; }
}

public void DoWork(Test t)
{
    // this will throw validation exceptions, overloads are available to trap and handle
    Validator.ValidateObject(t, new ValidationContext(t), true);
    //do stuff here
}

Again it should be noted that behavior cannot be sent/forced to the client using this method. It will only validate that the object fulfills as described validation.


text:
Q: implementing variable class types I have a list of objects which, depending on the condition that applies, has a variable type. However, I have not found a way to make this happen.
issue:
cannot implicitly convert type List<TABLE_ONE> to type list<object>
 List<object> listName;

    switch (sourceTableName)
    {
        case "TABLE_ONE":
            listName = m_api.Database.ExecuteQuery<TABLE_ONE>($"SELECT * FROM {sourceTableName}");
            break;
        case "TABLE_TWO":
            listName = m_api.Database.ExecuteQuery<TABLE_TWO>($"SELECT * FROM {sourceTableName}");
            break;
        case "TABLE_THREE":
            listName = m_api.Database.ExecuteQuery<TABLE_THREE>($"SELECT * FROM {sourceTableName}");
            break;
    }

foreach (var row in listName)
     {
        var dif3 = new DataInterfaceFactory(DatabaseTypes.SqlServer, row.DatabaseName, row.ServerName);
        do stuff...
     }

the variable sourceTableName is a string that contains the name of a class.
Classes that are used as types:
    public class TABLE_ONE
    {
        public int TableOneColumnUid;
        public string ServerName;
        public string DatabaseName;
        public DateTime LastCheckDate;
        public int IsRunning;
    }
    public class TABLE_TWO
    {
        public int TableTwoColumnUid;
        public string ServerName;
        public string DatabaseName;
        public DateTime LastCheckDate;
        public int IsRunning;
    }
    public class TABLE_THREE
    {
        public int TableThreeColumnUid;
        public string ServerName;
        public string DatabaseName;
        public DateTime LastCheckDate;
        public int IsRunning;
    }

A: It would work, if you added a .ToList<Object>(); at the end of your three calls.
I'm not sure whether that will actually solve your logic problem or just move it further down, but it would solve your immediate syntactical problem.

A: Since the List<T> class implements IEnumerable, you can use the System.Linq extension method Enumerable.Cast<TResult>(IEnumerable) to cast a List<T> into a List<Object>.
To do so you would first want to ensure you have the using directive for System.Linq at the top of your file, then you would do something along the lines of the following:
List<ICALC_SCHED> calcSched; //note the interface being used here.

switch (sourceTableName)
{
    case "CALCULATION_SCHEDULE":
        calcSched = m_api.Database.ExecuteQuery<CALCULATION_SCHEDULE>($"SELECT * FROM {sourceTableName}").Cast<ICALC_SCHED>().ToList();
        break;
    case "UKPMS_CALCULATION_SCHEDULE":
        calcSched = m_api.Database.ExecuteQuery<UKPMS_CALCULATION_SCHEDULE>($"SELECT * FROM {sourceTableName}").Cast<ICALC_SCHED>().ToList();
        break;
    case "RCI_CALCULATION_SCHEDULE":
        calcSched = m_api.Database.ExecuteQuery<RCI_CALCULATION_SCHEDULE>($"SELECT * FROM {sourceTableName}").Cast<ICALC_SCHED>().ToList();
        break;
    default:
        calcSched = null; //at this point you might want to leave your method early depending on context.
        //probably display some form of error message, note the "return" rather than "break" at the end of this case, this will leave the method early.
        return;
}

EDIT:
One way that you can access the common members of a set of classes is by having them inherit those members from an Interface, and then treat the results all as instances of that interface. You could easily cast them back to the individual classes too, since the other data isn't lost - just the reference to the object is typed differently.
public interface ICALC_SCHED
{
    string ServerName;
    string DatabaseName;
    DateTime LastCheckDate;
    int IsRunning;
}

public class CALCULATION_SCHEDULE : ICALC_SCHED
{
    public int CalculationScheduleUid;
    public string ServerName;
    public string DatabaseName;
    public DateTime LastCheckDate;
    public int IsRunning;
}

public class UKPMS_CALCULATION_SCHEDULE : ICALC_SCHED
{
    public int UkpmsCalculationScheduleUid;
    public string ServerName;
    public string DatabaseName;
    public DateTime LastCheckDate;
    public int IsRunning;
}

public class RCI_CALCULATION_SCHEDULE : ICALC_SCHED
{
    public int RciCalculationScheduleUid;
    public string ServerName;
    public string DatabaseName;
    public DateTime LastCheckDate;
    public int IsRunning;
}


text:
Q: Regular initial data I have a very basic question. What exactly is meant by "regular" initial data in general relativity? Does it mean smooth? at least $C^{2}$?
All literature on the subject just uses this term without exact explanation, so it seems that it's something very trivial, but I just wanted to know for sure.