text:
Q: count unique text values based on condition in another column between date criteria What i need  is formula to count unique values in TITLE based on criteria of column FIAP/Medium & Year.
This needs to begin by looking at the date in worksheet column M/Year, the range is 23/03/13 - 01/06/16.  It then needs to check column I/FIAP Medium looking for 'Digital' and finally count the unique images in A/Title.
This is the working sheet column
   Title              FIAP/Medium      Year
  Conors Push        Digital         3/23/2013
  Conors Push        Digital         4/1/2013
  Flippin Hell       Digital         4/1/2013
 Narrowing the Gap   Digital         4/1/2013
 The Perfect Storm   Digital         4/8/2013
 Conors Push         Digital         4/12/2013
 Splash and Dash     Digital         4/12/2013
 Wind Power          Digital         4/12/2013
 Conors Push           -             4/28/2013
 Eyes On The Ball      -             4/28/2013
 Narrowing the Gap     -             4/28/2013
 The Bunkers Demise    -             4/28/2013
 A Few Inches More   Digital         5/1/2013
 Entwined            Digital         5/1/2013
 Conors Push         Digital         5/14/2013
 Fosbury Delight     Digital         5/14/2013
 Narrowing The Gap   Digital         5/14/2013
 Sprint For The Lin  Digital         5/14/2013

I have come up with formula
=SUM(--(FREQUENCY(IF(International!M2:M1000>="6/1/2016",IF(International!M2:M1000<="3/23/2013",IF(International!I2:I1000<>"",IF(International!I2:I1000="Digital",MATCH(International!A2:A1000,International!A2:A1000,0))))),ROW(International!A2:A1000)-ROW(International!A2)+1>0)))

but its showing zero value. It may be because date condition requires two condition with one column.
Please help me with this formula or any other method to count unique based on this conditions.Specially dates

A: There is a fairly common method of a pseudo-COUNTUNIQUE¹ based on the SUMPRODUCT and COUNTIF functions that looks like this.
=SUMPRODUCT(1/COUNTIF(A2:A19, A2:A19&""))

But that does compensate for the conditions. To add conditions, you need to change to a COUNTIFS function. Additionally, both the numerator and denominator of the division operation have to be adjusted by the conditions and the inverse of the conditions in order that you return a true count without erroring on with a #DIV/0!.
=SUMPRODUCT(((C$2:C$19>=F2)*(C$2:C$19<=G2)*($B$2:$B$19=E2))/
             (COUNTIFS(A$2:A$19, A$2:A$19&"", C$2:C$19, ">="&F2, C$2:C$19, "<="&G2, $B$2:$B$19, E2)+
              (C$2:C$19<F2)+(C$2:C$19>G2)+($B$2:$B$19<>E2)))

Now that formula is hard to maintain of there are constant additions and deletions to the number of rows. To create dynamic ranges, we can INDEX each full column and use MATCH to locate the last date as the terminator for each column.
=SUMPRODUCT(((C$2:INDEX(C:C, MATCH(1E+99,C:C ))>=F2)*(C$2:INDEX(C:C, MATCH(1E+99,C:C ))<=G2)*($B$2:INDEX(B:B, MATCH(1E+99,C:C ))=E2))/
    (COUNTIFS(A$2:INDEX(A:A, MATCH(1E+99,C:C )), A$2:INDEX(A:A, MATCH(1E+99,C:C ))&"", C$2:INDEX(C:C, MATCH(1E+99,C:C )), ">="&F2, C$2:INDEX(C:C, MATCH(1E+99,C:C )), "<="&G2, B$2:INDEX(B:B, MATCH(1E+99,C:C )), E2)+
      (C$2:INDEX(C:C, MATCH(1E+99,C:C ))<F2)+(C$2:INDEX(C:C, MATCH(1E+99,C:C ))>G2)+($B$2:INDEX(B:B, MATCH(1E+99,C:C ))<>E2)))

Yes, that looks like a mess but it dynamically adds and subtracts rows processed by the SUMPRODUCT function so that calculation efficiency is at a premium.

¹ For an explanation on how this works see Count Unique with SUMPRODUCT() Breakdown.

A: You formula works with a few tweaks:

*

*The date strings need to be converted to date values using DateValue() function

*The comparison operators for the dates are interchanged (it should be <= 2016 date and >= 2013 date)

*The comparison against "digital" needs to be reversed

*The innermost IF statement needs a zero as value for situations where the condition fails

*I removed the outermost parentheses which are not needed
Here is the modified version that works:
=FREQUENCY(IF(International!M2:M1000<=DATEVALUE("6/1/2016"),IF(International!M2:M1000>=DATEVALUE("3/23/2013"),IF(International!I2:I1000<>"",IF(International!I2:I1000<>"Digital",MATCH(International!A2:A1000,International!A2:A1000,0),0)))),ROW(International!A2:A1000)-ROW(International!A2)+1>0)


text:
Q: Escape character in LIKE within user variable I'm trying to load data from a local file with two columns, one of which isn't inserted directly but mapped to an id found in a lookup table. However, the strings I'm looking for contain an underscore, which is interpreted by LIKE and is not the desired effect.
When making a normal query, I would've just escaped _ with \_, but as it's in a user variable, I can't find how to escape this character directly. Take this example, with the following LOAD DATA statement:
LOAD DATA statement:
LOAD DATA INFILE 'file.csv' INTO TABLE my_table
FIELDS TERMINATED BY '\t'
ESCAPED BY ''
LINES TERMINATED BY '\n'
(@foo, bar)
SET foo = (
  SELECT id FROM lookup_table
  WHERE foo_string
  LIKE @foo
  LIMIT 1
);

file.csv
STR_1   hi
STR_2   hey

Table my_table
+--------+---------+-------+
| id     | foo     | bar   |
+--------+---------+-------+
|      1 |       2 | hello |
|      2 |       1 | world |
+--------+---------+-------+

Table lookup_table
+--------+------------+
| id     | foo_string |
+--------+------------+
|      1 |      STR_1 |
|      2 |      STR_2 |
+--------+------------+

In this example, @foo is interpreted by LIKE as STR_1 and won't match any entries, I'd like it to be STR\_1.
Changing the csv file format is a possibility, by adding an escape character myself, but I want to know if there is a "cleaner" way first.

A: Well, looks like it does that automatically. I thought that was the culprit to my problem but I had an entirely other issue I didn't see, which can't be seen here but I'll explain what I did anyways.
In my SQL query on my end, I was using LOAD DATA INFILE ... (@foo, bar) SET foo_id = (SELECT ...) thinking that SET would map foo_id to its corresponding column in the table. All it actually does is create an unused user variable named @foo_id.
The solution here is to use the exact column name as a user variable everywhere, giving something like LOAD DATA INFILE ... (@foo_id, bar) SET foo_id = (SELECT ...)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ambiguity errors with variadic templates and mixins I am trying to create a callback registration class tat allows registration of callbacks against  string identifier for different types.  Each callback has the signature void function( T val ) where T is the changing type.
I have created the following base registrar class that maps strings to functions.
#include <string>
#include <map>
#include <functional>
#include <cstdint>
#include <iostream>

using namespace std;

template< typename ValueType >
class BasicConfigCallbackRegistrar
{
public:
    typedef ValueType value_type;
    typedef BasicConfigCallbackRegistrar< value_type > type;
    typedef function< void( const value_type ) > signature_type;
    typedef map< string, signature_type > callback_map_type;

    /// @brief constructor
    BasicConfigCallbackRegistrar() : callbackMap_()
    {
    }

    /// @brief register a create callback
    /// @param nodePath the path identifying the node in config database
    /// @param callback the callback to register
    type& RegisterCallback( string nodePath, signature_type callback )
    {
        callbackMap_.insert( make_pair( move(nodePath), callback ) );
        return *this;
    }

    void MakeCallback( const string& nodePath, value_type val )
    {
        // no checking assumes item is in map,
        // do not do this in production code
        auto iter = callbackMap_.find( nodePath );
        iter->second( val );
    }

private:
    callback_map_type callbackMap_;       ///< the callback map
};

I then use variadic templates to create a derived class for each of the types I want to support.
template< typename... Types >
class ConfigCallbackRegistrar : public BasicConfigCallbackRegistrar<Types>...
{
public:
    /// @brief constructor
    ConfigCallbackRegistrar() : BasicConfigCallbackRegistrar<Types>()...
    {}
};

This is then typedefed as:
typedef ConfigCallbackRegistrar< uint32_t, string > CallbackRegistrar;

When I try to use this class as follows:
struct UintFtor
{
    void operator()( uint32_t val )
    {
        cout << val << "\n";
    }
};

struct StringFtor
{
    void operator ()( string val )
    {
        cout << val << "\n";
    }
};

int main()
{
    CallbackRegistrar registrar{};

    registrar.RegisterCallback( "SomeNode", UintFtor() );
    registrar.RegisterCallback( "SomeNode", StringFtor() );

    return 0;
}

Unfortunately when I try to compile this I get the following ambiguity errors:
variadic-wrap.cpp: In function 'int main()':
variadic-wrap.cpp:87: error: request for member 'RegisterCallback' is ambiguous
variadic-wrap.cpp:27: error: candidates are: BasicConfigCallbackRegistrar<ValueType>&  BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
variadic-wrap.cpp:27: error:                 BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = unsigned int]
variadic-wrap.cpp:88: error: request for member 'RegisterCallback' is ambiguous
variadic-wrap.cpp:27: error: candidates are: BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
variadic-wrap.cpp:27: error:                 BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = unsigned int]

Calls to MakeCallback which takes a parameter of type value_type also produce the same ambiguity error.
How can I resolve this without an explicit cast of  registrar to the base class type?

A: I have a solution. All tat is needed is an extra level of indirection. In the Derived class I added a template function that dispatches to the correct base, as follows:
template< typename... Types >
class ConfigCallbackRegistrar : public BasicConfigCallbackRegistrar<Types>...
{
    typedef ConfigCallbackRegistrar<Types...> type;
public:
    /// @brief constructor
    ConfigCallbackRegistrar() : BasicConfigCallbackRegistrar<Types>()...
    {}

    template<typename T>
    type& Register( string nodePath,
            typename BasicConfigCallbackRegistrar<T>::signature_type callback )
    {
        BasicConfigCallbackRegistrar<T>::RegisterCallback( std::move(nodePath),
                std::move(callback) );
        return *this;
    }
};

The calling code becomes:
int main()
{
    CallbackRegistrar registrar{};

    registrar.Register<uint32_t>( "SomeNode", UintFtor() );
    registrar.Register<string>( "SomeNode", StringFtor() );

    return 0;
}


text:
Q: Is it useful to use multithreading to handle files on a hard drive? In terms of performance and speed of execution it is useful to use multithreading to handle files on a hard drive? (to move files from a disk to another or to check integrity of files)
I think it is mainly the speed of my HDD that will determine the speed of my treatment.

A: Multithreading can help, at least sometimes.  The reason is that if you are writing to a "normal" hard drive (e.g. not a solid state drive) then the thing that is going to slow you down the most is the hard drive's seek time (that is, the time it takes for the hard drive to reposition its read/write head from one distance along the the disk's radius to another).  That movement is glacially slow compared to the rest of the system, and the time it takes for the head to seek is proportional to the distance it must travel.  So for example, the worst case scenario would be if the head had to move from the edge of the disk to center of the disk after each operation.
Of course the ideal solution is to have the disk head never seek, or seek only very rarely, and if you can arrange it so that your program only needs to read/write a single file sequentially, that will be fastest.   Or better yet, switch to an SSD, where there is no disk head, and the seek time is effectively zero.  :)
But sometimes you need your drive to be able to read/write multiple files in parallel, in which case the drive head will (of necessity) be seeking back and forth a lot.  So how can multithreading help in this scenario?  The answer is this:  with a sufficiently smart disk I/O subsystem (e.g. SCSI, I'm not sure if IDE can do this), the I/O logic will maintain a queue of all currently outstanding read/write requests, and it will dynamically re-order that queue so that the requests are fulfilled in the order that minimizes the amount of travel by the read/write head.  This is known as the Elevator Algorithm, because it is similar to the logic used by an elevator to maximize the number of people it can transport in a given period of time.
Of course, the OS's I/O subsystem can only implement this optimization if it knows in advance what I/O requests are pending... and if you have only one thread initiating I/O requests, then the I/O subsystem will only know about the current request.  (i.e. it can't "peek" into your thread's userland request queue to see what your thread will want next).  And of course your userland thread doesn't know the details of the disk layout, so it's difficult (impossible?) to implement the Elevator Algorithm in user space.
But if your program has N threads reading/writing the disk at once, then the OS's I/O subsystem will be aware of up to N I/O requests at once, and can re-order those requests as it sees fit to maximize disk performance.

A: Perhaps your main concern should be code maintainability.  Threading helps hugely, IMO, because it does not permit the kind of hackery that single-threading permits.


text:
Q: .Net C# Microsoft.Office.Interop.Excel ListObject refresh datasource asynchronously I have a messaging application set up in C# and will add the messages received asynchronously into a list. I am using only the Microsoft.Office.Interop.Excel namespace and not VSTO extensions thus faces a problem with the listobject.
What I want to do is to create a listobject using the method below and use a timer object to write to excel spreadsheet.
public static ListObject AddListObject()
    {
        oXL = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

        oWB = oXL.Workbooks.get_Item(1);
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;

        activeRow = oXL.ActiveCell.Row;

        //content
        oSheet.Cells[activeRow , 1] = Store[0].name;
        oSheet.Cells[activeRow , 2] = Store[0].address;
        oSheet.Cells[activeRow , 3] = Store[0].number;
        oSheet.Cells[activeRow , 4] = Store[0].dob;

        Excel.ListObject listObject1 = oSheet.ListObjects.Add(
            Excel.XlListObjectSourceType.xlSrcRange, oXL.ActiveCell.CurrentRegion, false,
            Microsoft.Office.Interop.Excel.XlYesNoGuess.xlNo, Type.Missing);
        listObject1.TableStyle = "TableStyleLight9";

        oXL.Visible = true;
        oXL.UserControl = false;

        return listObject1;

    }

In the main program, after starting the messaging portion, I will get the listobject and pass it to the timer to update the spreadsheet.
listobject1 = AddListObject();
timer = new Timer(DoSomething, listobject1, 0, 1000);

How do I do that when the timer object calls the DoSomething method every second?
public void DoSomething(ListObject obj)
    {
        //refresh listobject and write and update to spreadsheet every second

    }

In VSTO, I will do the following:
listobject1 = AddListObject();
listobject1.DataSource=Store;
listobject1.AutSetDataBoundColumnHeaders=true;
timer = new Timer(DoSomething, listobject1, 0, 1000);

public void DoSomething(object state)
    {
        //refresh listobject and write and update to spreadsheet every second
        ListObject lbo = (ListObject)state;
        lbo.RefreshDataRows();

    }

How do I do the following without VSTO extensions?


text:
Q: Swift3 Microphone Audio Input - play without record I am trying to play microphone audio input using swift3 without recording. I can record the audio with the following code:
let session = AVAudioSession.sharedInstance()
    try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, with:AVAudioSessionCategoryOptions.defaultToSpeaker)

    try! audioRecorder = AVAudioRecorder(url: filePath!, settings: [:])
    audioRecorder.delegate = self
    audioRecorder.isMeteringEnabled = true
    audioRecorder.prepareToRecord()
    audioRecorder.record()

and then play it back ultimately after picking up the recorded file with:
audioPlayerNode.play()

But I would like to skip the recording step and play directly from the microphone input to the audio out (in this case the player node).  It then functions like an actual microphone. Can I do this directly or does an interim file need to exist? I combed the AVFoundation documentation but I can't seem to get a handle on the direct route. Any ideas or suggestions are appreciated. Thank you!

A: You can do this with AVAudioEngine, although you will hear feedback:
import AVFoundation

class ViewController: UIViewController {
    let engine = AVAudioEngine()

    override func viewDidLoad() {
        super.viewDidLoad()

        let input = engine.inputNode!
        let player = AVAudioPlayerNode()
        engine.attach(player)

        let bus = 0
        let inputFormat = input.inputFormat(forBus: bus)
        engine.connect(player, to: engine.mainMixerNode, format: inputFormat)

        input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) -> Void in
            player.scheduleBuffer(buffer)
        }

        try! engine.start()
        player.play()
    }
}


text:
Q: How to solve this congruence? Given that $6^{12} ≡ 16\pmod {109}$. Is there a $k$ such that $16^k ≡ 6 \pmod {109}$? If there is, then find all the $k$'s.
Does anyone know how to do this?
Thanks

A: Hint:

*

*$109$ is prime;

*if $16^k\equiv6\pmod{109}$ then $6^{12k-1}\equiv1\pmod{109}$;

*but you also know $6^{108}\equiv1\pmod{109}$;

*obtain a contradiction from the last two points.

A: This is a hard question, I can give an answer relying on the fact that $6$ has order $108$ mod $109$. So then we have the elements $6,6^2,6^3\dots 6^{168}\equiv1 \bmod 109$ are all different. the powers of $16$ are precisely $6^{12},6^{24},6^{36}\dots 6^{168}$ and no more, since they cycle (this is because $12$ divides $108$ which is the order of $6\bmod 108$, however you need to know the order of this beforehand).
In general if you want for an integer $k$ to exist so that  $(n^a)^k \equiv n \bmod m$ this happens if and only if $a$ and the order of $n$ mod $m$ are relatively prime.

I just noticed we can find a shortcut in this particular case. Notice $108$ is $2^2\cdot 3^2$. Now, notice the order of $6$ mod $109$  needs to be a nontrivial divisor of $108$ by Lagrange's theorem in group theory, this number cannot be relatively prime to $12$ because of the prime decompositon of $108$, so you don't actually have to calculate the order of $6$ to know, although this only works because $12$ contains all of the prime divisors of $108$ in its prime factorization.


text:
Q: How to compare many values with an OR statement in Word mergefields? What I want to do is:
{ IF v1 = 0 OR v2 = 0 "Lorem Ipsum.." }

How to write an OR in Word mergefield syntax?
I'm asking especially for Word 2013 - I think the syntax has changed in 2013.

A: If the v1, v2 are MERGE fields, in the general case you need { MERGEFIELD v1 } and { MERGEFIELD v2 }. You can then do an OR using a construct like this:
{ IF { =OR({ COMPARE { MERGEFIELD v1 } = 0 },{ COMPARE { MERGEFIELD v2 = 0 }) } = 0 "Lorem Ipsum.." }

(As usual, all the { } have to be the special field code brace pairs that you can insert on Windows Word using ctrl-F9.
Or for short result texts you can use a numeric picture switch to produce the correct result, e.g.
{ =OR({ COMPARE { MERGEFIELD v1 } = 0 },{ COMPARE { MERGEFIELD v2 = 0 }) }) \#"'';'';'Lorem Ipsum..'" }

For more comparands you need to nest the ORs
In this case you could also do stuff such as
{ IF { =ABS({ MERGEFIELD v1 })+ABS({ MERGEFIELD v2 }) } = 0 "Lorem Ipsum.. }

FWIW I do not believe the syntax has changed in Word 2013 in this area, but if you have an example of such a difference, please share!

A: The first example above is I think in error.  The second looks correct.
COMPARE gives 1 if true; 0 if false.  =OR works this way, too - arithmetically.
So if either of your COMPARE propositions are true, the OR on them will yield 1.
You want to output "Lorem Ipsum" if either of the COMPARE propositions are true.
Therefore the IF should compare with 1, not with 0.
Alternatively, comparing with 0, "Lorem Ipsum" could be output for a FALSE match.
I think this is the other error: I think IF expects both true and false arguments to output.  {IF <condition> <true-text> <false-text>}.
More complex logical conditions can be expressed economically (without nesting) by again using arithmetic creatively.  If, say, it is sufficient for any one of three items to be true, the sum of their truth values can be used as a condition for IF.  If all are false, the result will be zero. General arithmetic can be applied in Word fields using {=}.  For example:
{IF {=({COMPARE {MERGEFIELD v1} = 0} + {COMPARE {MERGEFIELD v2} = 0} + {COMPARE {MERGEFIELD v3} = 0})} = 0 "None are zero." "At least one is zero."}


text:
Q: What I'm doing wrong filling this vector of pair? If I do:
vector<string> vec_jets;

double values[] = {
    transEnergy(map_jets, "jet1"),
    transEnergy(map_jets, "jet2"),
    transEnergy(map_jets, "jet3"),
    transEnergy(map_jets, "jet4"),
    transEnergy(map_jets, "jet5"),
    transEnergy(map_jets, "jet6"),
    transEnergy(map_jets, "jet7") };

for( int j = 1; j <= Njets; j++){
  oss << "jet" << j;
  vec_jets.push_back( oss.str() );
  oss.str("");
}

vector<pair<string,double> > jets_pt( vec_jets.size() );

// for( int k = 0; k < Njets; k++ ){
  // if( jet_preselection(map_jets,map_leps,vec_jets[k],jets_emfr[k]) )

        transform(
            vec_jets.begin(),
            vec_jets.end(),
            values,
            jets_pt.begin(),
            make_pair<string,double>
        );

//    }

I have the output I want, which is, for example
jet1 32.4717

But, if I uncomment the for loop and the if condition, it seems that the vector is not filled anymore, if I ask to cout it, I get only 0 always.
The function in the if statement is just a bool
bool jet_preselection(
    map<string, TLorentzVector> map_jets,
    map<string, TLorentzVector> map_leps,
    string vec_jets,
    double jet_emfr )
{

        return ( map_jets[vec_jets].E()*sin(map_jets[vec_jets].Theta()) > 15
            && jet_emfr < 0.9
            && fabs(map_jets[vec_jets].PseudoRapidity()) > 2.5
            && ( map_jets[vec_jets].DeltaR(map_leps["lep1"]) > 0.4
                && map_jets[vec_jets].DeltaR(map_leps["lep2"]) > 0.4
                && map_jets[vec_jets].DeltaR(map_leps["lep3"]) > 0.4 );
}

A: There are a lot of complex interdependancies in your code that make it difficult to diagnose the problem.  But I can tell you that in:
bool jet_preselection(map<string, TLorentzVector> map_jets, map<string, TLorentzVector> map_leps, string vec_jets, double jet_emfr)

...you are passing map_jets and map_leps by value rahter than by-reference (preferred) or by-pointer, so that when you call this function a complete copy of those maps is constructed.
You may consider changing how you pass these parameters.  Perhaps passing copies of these maps would change the states of them in such a way so that jet_preselection would fail.


text:
Q: i have many data-self element, but how can i get all of them? just like this:

// with jquery i have tried

$('body').data('self'); // undefined
$('body').data('date-self'); //undefined

// but i can use this method to get the defined element

$('button').data('self'); // self

// with javascript

document.querySelector('button').dataset.self // self

self

    span self

li1 self

li2 self

    <button data-self="self">button self</button>

but i can't find a way to get all elements with 'data-self'.
if someone know, please tell me, any help would be greatly appreciated.

A: You're just going to have to iterate over them all.
var $elems = $('[data-self]');
var selfs = [];
$elems.each(function ($elem) {
  selfs.push($elem.data('self'));
});

A: Well, first off, your HTML is invalid. date-self should probably be data-self, yes?
Second, getting the value in data-* attributes is done using the .data() method:
var dataSelf = $(".elem").data("self");

You can also get it directly from the attribute, like so:
var dataSelf = $(".elem").attr("data-self");

Selecting elements that have the data-self attribute is done as follows:
var elementsWithDataSelf = $("[data-self]");

A: You can get all elements where 'data-self' attribute is set using this query:
var elementList=document.querySelectorAll('[data-self]');

If you need to select all elements where 'data-self' attribute is equal to something then you can use next line:
var elementList=document.querySelectorAll('[data-self="something"]');


text:
Q: Mysql CHECKSUM TABLE not working for ndbcluster In mysql the command CHECKSUM TABLE table1name is working for InnoDB & MyISAM but not for ndbcluster. Is any other way to find the checksum or something relevant attribute so as to know if the table is the same after any interaction upon it.

A: If I understand the question correctly, you are asking how to obtain a checksum of a mysql table when it is based on NDB engine.
The following query will do the trick:
SELECT @crc as crc FROM
(
   select @crc := ''
) tmp,
(
  SELECT min(
          length(
             @crc := sha1(
                      concat(
                        @crc, sha1(
                          concat_ws('#', field_1, field_2, ...)
                                  )
                            )
                         )
                 )
               )
            )
            FROM
            (
                SELECT field_1, field_2, ... FROM your_table
                ORDER BY yourtable_some_key_id
            ) tmp_1
) final

Under InnoDB this would not need the second sub-query and would work, but then the native
    CHECKSUM TABLE your_table
would also work. Despite any ordering you may specify in an ORDER BY clause, the internal processing occurs before the sorting of the results, and on NDB this order is not always the same. This being the case, we need to force it, hence the second sub-query with the specific sort ordering.
The first price you pay for getting this to work on NDB is the internal ordered temporary table created by the second sub-query which is as large as your table, and this is one thing to keep in mind when using this query.
The second price paid is the time it takes to create this temporary ordered table. In my tests on a table with 100K rows, the query took about 1.5 to 2 seconds with the sub-query, and approximately 100 msec without it.
This solution is based on a more general one found at this blog
Hope this helps.


text:
Q: Query about pandas copy() method df1 = pd.DataFrame({'A':['aaa','bbb','ccc'], 'B':[1,2,3]})
df2=df1.copy()
df1.loc[0,'A']='111' #modifying the 1st element of column A
print df1
print df2

When modifying df1 the object sf2 is not modified. I expected it because I used copy()
s1=pd.Series([[1,2],[3,4]])
s2=s1.copy()
s1[0][0]=0 #modifying the 1st element of list [1,2]
print s1
print s2

But why did s2 changed as well in this case? I expected no change of s2 because I used copy() to create it, but for my surprise, when modifying s1 the object s2 is also modified. I don't get why.

A: This is occurring because your pd.Series is of dtype=object, so it essentially copied a bunch of references to python objects. Observe:
In [1]: import pandas as pd

In [2]: s1=pd.Series([[1,2],[3,4]])
   ...:

In [3]: s1
Out[3]:
0    [1, 2]
1    [3, 4]
dtype: object

In [4]: s1.dtype
Out[4]: dtype('O')

Since list objects are mutable, then the operation:
s1[0][0]=0

Modifies the list in-place.
This behavior is a "shallow copy", which normally isn't an issue with pandas data structures, because normally you would be using a numeric data type in which case shallow copies don't apply, or if you do use the object dtype you would be using python string objects, which are immutable.
Note, pandas containers have a different notion of a deep-copy. Notice the .copy method has a default deep=True, but from the documentation:

When deep=True (default), a new object will be created with a copy
  of the calling object's data and indices. Modifications to the data or
  indices of the copy will not be reflected in the original object (see
  notes below).
When deep=False, a new object will be created without copying the
  calling object's data or index (only references to the data and index
  are copied). Any changes to the data of the original will be reflected
  in the shallow copy (and vice versa). ... When deep=True, data is
  copied but actual Python objects will not be copied recursively, only
  the reference to the object. This is in contrast to copy.deepcopy in
  the Standard Library, which recursively copies object data (see
  examples below).

Again, this is because pandas is designed for using numeric dtypes, with some built-in support for str objects. A pd.Series of list objects is very strange indeed, and really not a good use-case for a pd.Series.

A: When you copied the s1 object, it actually created a new, separate Series object and referenced it to s2 - just as you expected. However, the two list within the s1 Series object were not duplicated with the Series. It simply copied their references.
See here for a good starting point towards understanding the difference between a Python reference and an object.
Simply put, a Python variable is not the same thing as the actual  Python object. Variables (like s1 and s2) are simply references that point to the memory location where the actual object lives.
Because the original Series object s1 contained two list references, versus two list objects, only the references for the internal list objects were copied (not the list objects themselves).
import pandas as pd

s1=pd.Series([[1,2],[3,4]])
# The oject referenced by variable "s1" has a memory address
print ("s1:", hex(id(s1)))
s2=s1.copy()
# The oject referenced by variable "s2" has a different memory address
print ("s2:", hex(id(s2)))
# However when you copied "s1", the
# list items within only had their references copied
# So "s1[0]" and "s2[0]" are simply references to the same object
print ("s1[0]:", hex(id(s1[0])))
print ("s2[0]:", hex(id(s2[0])))

OUTPUT:
s1: 0x7fcdf5678898 # A different address form s2
s2: 0x7fcddee25240 # A different address form s1
s1[0]: 0x7fcdddf9f6c8 # The same address for the first list
s2[0]: 0x7fcdddf9f6c8 # The same address for the first list

@juanpa.arrivillaga is correct in her answer that you need to use a deep copy


text:
Q: How to execute only the most recent queued job in Jenkins? I've got a commit build project in Jenkins which schedules an acceptance build project on completion. Since commits come in faster than the acceptance build job finishes, after a short time there are now six queued acceptance build jobs. I would like the acceptance build project to work like the "Poll SCM" functionality - On completion, start the most recently queued job, skipping the rest.
I can't use the "Build after other projects are built" without more hacks since I need to pass information from the commit build job to the acceptance build job.

A: @l0b0,
Jenkins behavior is to coalesce builds so that the queue only contains the currently running build and one enqueued job. The depth only increases if the newly enqueued jobs takes parameters that differ from what's already on the queue.
So I'm gathering that your downstream (acceptance) job takes some sort of parameters, but you need to supply more details of how it's working.
If you're using parameterized trigger plugin then you should check out this existing SO thread
More generally speaking, you should look into your parameters. It sounds like you are passing too much information from upstream to downstream jobs, resulting in the the Jenkins queue treating them as distinct parameters when then is not necessarily the case.
Are you passing in the run number of the last successful upstream job as a parameter? If so, then yeah you've got problems. What you should do instead is use the Promoted Build Plugin on the upstream job to mark the last successful build, and then have the downstream job simply jump to the most recent promoted build.
Hope that helps.


text:
Q: JFrame defined in one class, JComponent extended in another Relatively new to Java, coding for a school project.
I'm using JFrame and JComponent, drawing patterns and strings and all that fun stuff.
Currently, I have a class written that extends JComponent. This is the class where I am defining most of my shapes. The issue is that I initialized my Jframe
(Code: JFrame myFrame = new JFrame() ) in the main of one class, but I need to access myFrame.getWidth() in the JComponent class that I'm working in.
How can I access variables getWidth() and getHeight() in "public class MyJComponent extends JComponent" , when I defined myFrame in 'public class Lab2' ??
Edit for code:
public class Lab2 {
    public static void main(String[] args) {
    System.out.println("Hello Java");

    JFrame myFrame = new JFrame();

    myFrame.setSize(500, 500);
    myFrame.setTitle("Color Test");
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MyJComponent myComponent = new MyJComponent(500, 500);
    myFrame.add(myComponent);
    myFrame.getContentPane().setBackground(Color.white); //sets background color.

    myFrame.setVisible(true);   // setVisible() *after* add() is the norm

    //Deciding geometry of hidden shape. paintComponent is called once per run, this is called afterwards.

}

}

/**/
public class MyJComponent extends JComponent {

int[] circleX;
int[] circleY;
int[] circleR;
final int MIN_RADIUS = 5;
final int MAX_RADIUS = 15;
final int MIN_SEPARATION = 1;
final int MAX_ATTEMPTS = 5000;
final int MAX_CIRCLES = 1000;
Random rand;
int initialWidth;
int initialHeight;
int numCircles;   // actual number of circles drawn

// are circles at index i and index j separated by *<= tolerance* pixels?

boolean twoCirclesOverlap(int i, int j, int tolerance) {
    double distanceBetweenCenters =
            Math.sqrt((circleX[i] - circleX[j]) * (circleX[i] - circleX[j]) +
                    (circleY[i] - circleY[j]) * (circleY[i] - circleY[j]));
    return (distanceBetweenCenters <= (circleR[i] + circleR[j] + tolerance));
}

// are any existing circles separated from the proposed one at index i by *<= tolerance* pixels?

boolean anyCirclesOverlap(int i, int tolerance) {
    for (int j = 0; j < i; j++) {
        if (twoCirclesOverlap(i, j, tolerance)) {
            return true;
        }
    }
    return false;
}

// attempt to randomly place the largest-possible circle that does not overlap any existing one

boolean tryToPlaceCircle(int i) {

    for (int j = 0; j < MAX_ATTEMPTS; j++) {

        // pick a random position, set initial radius to minimum

        circleX[i] = rand.nextInt(initialWidth);
        circleY[i] = rand.nextInt(initialHeight);
        circleR[i] = MIN_RADIUS;

        // grow circle until it touches another or reaches max size

        while (!anyCirclesOverlap(i, MIN_SEPARATION) && circleR[i] < MAX_RADIUS)
            circleR[i]++;

        // it was touching from the start -- must try again

        if (circleR[i] == MIN_RADIUS) {
            continue;
        }

        // grew to max size -- well done

        else if (circleR[i] == MAX_RADIUS) {
            return true;
        }

        // grew some, but then touched

        else {
            circleR[i]--;   // retract to the step before touch
            return true;
        }
    }

    // all attempts failed

    return false;
}

MyJComponent(int width, int height) {

    circleX = new int[MAX_CIRCLES];
    circleY = new int[MAX_CIRCLES];
    circleR = new int[MAX_CIRCLES];

    initialWidth = width;
    initialHeight = height;

    rand = new Random();

    numCircles = 0;
    while (numCircles < MAX_CIRCLES && tryToPlaceCircle(numCircles)) {
        numCircles++;
    }
}

//Override paintComponent
public void paintComponent(Graphics g) {

    for (int i = 0; i < numCircles; i++) {
        g.drawOval(circleX[i] - circleR[i], circleY[i] - circleR[i], 2 * circleR[i], 2 * circleR[i]);
    }
}

//Shape decision
public void shapeDecision() {
    double randomShapeDecider = Math.random();
    if (randomShapeDecider > .50) {
        //shape is circle, define it's properties
        hiddenCircleDiameter = myFrame.getWidth();

    }
    else {
        //shape is rectangle
        hiddenRectangleWidth = myFrame.getWidth();
    }
}
}


text:
Q: When is the quotient of an algebra by a polynomial algebra a free module? Let $A$ be a $k$-algebra and let $V$ be a subalgebra of $A$ that is a polynomial algebra.  Is $A$ a free module over $V$?
One example is when $A=\mathbb{C}[x_1, x_2, \ldots x_n]$ and $V$ is the ring of symmetric polynomials in $n$ variables.  Can you prove that $A$ is free over $V$?


text:
Q: Silent device using CoreBluetooth framework I am building an application for accessory on iPhone that requires to silent the iPhone. Now I know from the app itself silenting the phone is not possible as explained here and here or it is possible with private apis as explain here.
Now I also read Apple bluetooth accessory guidelines for volume control and it has a profile known as Audio/Video Remote Control Profile which accessory can use to control the volume of the device. Also explained in Section 2.2.5.5 Volume Handling
But my question is can this profile be used to silent the device?


text:
Q: Enter a Code, Change Displayed Price When User Presses Enter I have a chunk of a website that I need to allow a user to enter a code and have the displayed price change.  The code is arbitrary as the actual price IS the price the the code will cause to be displayed - I just wanted the user to feel that they're 'special'.

Your choice for a one-time investment of just:

$797

If you'd prefer a totally custom design, click here.

<input type="text" id="EnterCode" />
Enter Code

(The link in the "a title=" line is there because the theme I'm using won't let me change the font color, so to get it to use the color I want, I have to make it think it's a link..I'll have to go into the css and change it later)
So, given the above code, the current price displayed is $797.  When the user enters ANY code and presses enter, I would like the $797 to change to $397.
I couldn't locate anything online that would point me in the right direction, so I came here, to ask you guys.  I really do appreciate any help you can provide.
Thanks!

A: First of all, you need to add an ID to your  tag that contains the code. Something like this:
$797

Then you can easily use Javascript to do what you want, using an event listener that checks if the user pressed the Enter key, like this:
var input = document.getElementById("EnterCode"),
    price = document.getElementById("yourPriceId");

input.addEventListener('keyup', function(e) {
    if (e.keyCode === 13 && !!this.value) {
        price.textContent = "$397";
    }
});

Note: this will only work if the user enters something in the input before pressing Enter. If you want to chenge the price even if the user doesn't enter anything then just remove && !!this.value from the if statement.


text:
Q: Three.js : intersectObjects object not responding to color change [jsfiddle] For some reason I am not able to change the color of a cube when a person mouses over it.  I distilled the code down to the most barebones I could.
http://jsfiddle.net/pgd3d5rf/
<script>
var container;
var scene, camera, renderer, mouse, raycaster;
var grid_items = [];

init();
grid();
render();

function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    scene = new THREE.Scene();
    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();

    camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set( 500, 800, 1300 );
    camera.lookAt( new THREE.Vector3() );

    // Lights
    var ambientLight = new THREE.AmbientLight( 0x606060 );
    scene.add( ambientLight );

    var directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = Math.random() - 0.5;
    directionalLight.position.y = Math.random() - 0.5;
    directionalLight.position.z = Math.random() - 0.5;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    var directionalLight = new THREE.DirectionalLight( 0x808080 );
    directionalLight.position.x = Math.random() - 0.5;
    directionalLight.position.y = Math.random() - 0.5;
    directionalLight.position.z = Math.random() - 0.5;
    directionalLight.position.normalize();
    scene.add( directionalLight );

    renderer = new THREE.CanvasRenderer();
    renderer.setClearColor( 0xf0f0f0 );
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild(renderer.domElement);

    window.addEventListener('mousemove', onDocumentMouseMove, false );
}

function grid(){
    var geometry = new THREE.BoxGeometry(100, 100, 100);
    var material = new THREE.MeshBasicMaterial({ color: 0x0000ff });
    var cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    grid_items.push(cube);
}

function onDocumentMouseMove(event) {

    mouse.x = (event.clientX / renderer.domElement.width) * 2 - 1;
    mouse.y = - (event.clientY / renderer.domElement.height) * 2 + 1;

    console.log(mouse.x+"-"+mouse.y);

    raycaster.setFromCamera(mouse, camera);

    var intersects = raycaster.intersectObjects(grid_items);
    if (intersects.length > 0) {
        for (var i = 0; i < intersects.length; i++) {
            console.log("OBJECT "+intersects[i])
            intersects[i].object.material.color.set(0xff0000);
        }
    }
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);

    render();
}

function render() {
    renderer.render( scene, camera );
}

A: You need to re-render after changing the color. So add a call to render(); just after you changed the colors:
if (intersects.length > 0) {
     for (var i = 0; i < intersects.length; i++) {
        console.log("OBJECT "+intersects[i]);
        intersects[i].object.material.color.set(0xff0000);
    }
    render();
}

Updated fiddle: http://jsfiddle.net/pgd3d5rf/1/

A: With the CanvasRenderer() your fiddle is not working but if I change it to WebGLRenderer() then if you add a render() call at the end of your onDocumentMouseMove() function it should work.


text:
Q: Xamarin.Forms - Why keyboard not hide when switching to another page? The page has no input fields(only one label), but the keyboard does not disappear when you switch to this page. Is this normal behavior? How to make the keyboard not open on a new page? thank
First page xaml
<ContentPage.Content>
    <StackLayout x:Name="stackLayout2">
        <Label x:Name="code_label" HorizontalOptions="CenterAndExpand" Font="Bold, Micro" TextColor="black" FontSize="19" Margin="15, 30, 15, 0" />
        <Entry x:Name="code_field" TextChanged="CodeFieldTextChanged"  Keyboard="Telephone" MaxLength="4" Margin="15, 30, 15, 0" />
    </StackLayout>
</ContentPage.Content>

First page CodeFieldTextChanged method
private void CodeFieldTextChanged(object sender, TextChangedEventArgs args)
{
    if (args.NewTextValue == "3333")
    {
        Application.Current.MainPage = new HomePage();
    }
}

HomePage xaml
<ContentPage.Content>
    <StackLayout>
        <Label Text="Authorization ok!"
            VerticalOptions="CenterAndExpand"
            HorizontalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>

If Application.Current.MainPage = new HomePage(); is replaсed by Application.Current.MainPage = new NavigationPage(new HomePage()); then keyboard disappears, but in the first case keyboard stays

A: This issue only seems to occur on Android. And what is happening is that you are changing the page without ever hitting "Return" (green Check mark on the Telephone keyboard) so the keyboard does not get dismissed by the OS, so you have to dismiss it manually. Try this:
private void CodeFieldTextChanged(object sender, TextChangedEventArgs args)
{
    if (args.NewTextValue == "3333")
    {
        // Add the following two lines to dismiss the keyboard
        Entry entry = sender as Entry;
        entry.Unfocus();
        Application.Current.MainPage = new HomePage();
    }
}


text:
Q: Can't load jQuery locally in node-webkit app I get the following error in my console:
Failed to load resource file:///var/folders/n7/94blrknd6639zt8ngcfp9l4m0000gn/T/.org.chromium.Chromium.RRLqW8/js/jquery-2.0.3.min.js

index.html loads it with:
<script src="js/jquery-2.0.3.min.js"></script>

A: I didn't include the -r in my zip command to recursively add sub-directories...so it missed everything in ./js.


text:
Q: JSON stringify with variables in jQuery I'm trying to POST some JSON where I need to include some values from input fields. I have two input fields with the IDs of username and password.
data = JSON.stringify({
  "jsonrpc": "2.0",
  "method": "POST",
  "params": {
    "params": {"username": $('#username').val(), "password":  $('#password').val()}
  }
});

I can send it perfectly fine when I hardcode the values, the issue is that it doesn't send the values from the input fields. What am I doing wrong?
I'm sending it like this:
$.ajax({
  url:url,
  type:"POST",
  crossDomain: true,
  dataType: "json",
  data : data,
  headers: {
    'content-type': "application/json; charset=utf-8"
  },
  success: function(data){
        $("#result").append('
Token: ' + data.result.token + '
');
        $("#result").append('
Name: ' + data.result.Customer.Name.value + '
');
        $("#result").append('
ID: ' + data.result.Customer.ID + '
');
  },
  error: function(data, status, xhr) {
alert("Error");
  }

});

I tried simplifying things, so I'm adding the value to a div on the click of a button. That works just fine:
$("#login").click(function() {
  $('#test').append($('#username').val());
});

ANSWER: As David mentioned in the comments, it's because I declared the data variable outside the function.

A: Change:
"params": {
 "params": {"username": $('#username').val(), "password":  $('#password').val()}
}

in
"params": {"username": $('#username').val(), "password":  $('#password').val()}

you are declaring params twice in a moment

A: Maybe you can use dataType: "string"

A: Added the answer in the original question. Especially thanks to David Hedlund that helped me in the right direction.


text:
Q: need help web3.js to read return value of smart contract I need help to locate web3.js function that can send parameters to an existing smart contract function that changes the state of the blockchain. In the smart contract function I am returning a return value which I need to capture using web3.js
For example the below node file calls web3.eth.sendRawTransaction, but when it returns, it gets only the transaction hash and not the return value of the function "addfund".
Using the transaction hash I can see details about the transaction like the block number etc, however, the return value of addfund is not captured anywhere. Is there a way to achieve this ? I know that I can use
contract.methods.totalSupply().call((err, result) => { console.log(result) })

function to get the return values, but those methods are NOT state changing functions so it is not applicable in my case
My File.js:
var contractAddress = '0x17a8fd94665bd5f73e7fede9c69f64959cefd8df';
   var txOptions = {
   nonce: web3.toHex(web3.eth.getTransactionCount(address)),
   gasLimit: web3.toHex(800000),
   gasPrice: web3.toHex(20000000000),
   to: '0x17a8fd94665bd5f73e7fede9c69f64959cefd8df'
  };
 var rawTx = txutils.functionTx(interfaceABI, 'addfund',
  ['0xc66ed658f1e75c21df3e50890e983fda34b6052e',100], txOptions);

function sendRaw(rawTx) {
   var privateKey = new Buffer(key, 'hex');
   var transaction = new tx(rawTx);
   console.log('transaction '+ JSON.stringify (transaction));
   transaction.sign(privateKey);
   var serializedTx = transaction.serialize().toString('hex');
   console.log('serializedTx ' +serializedTx);
   web3.eth.sendRawTransaction(
   '0x' + serializedTx, function(err, result) {
      if(err) {
        console.log('error is' + err);
      } else {
        console.log('result is ' + result);
    }
   });
  }`
  sendRaw(rawTx);

Solidity function :
function addfund(address sender, uint value ) payable public {

    if (partifunded[msg.sender] == true) {
            for ( uint i = 0; i < participants.length; i++) {
                    if (participants[i].partaddr == msg.sender)
                     {
                            participants[i].amount += msg.value;
                            totalamountcol = address(this).balance;
                     }
            }
    }
    else
    {
            partifunded[msg.sender] = true;
            participants.push(Participant(msg.value,msg.sender));
            numberofparti = numberofparti+1;
            totalamountcol = address(this).balance;
    }

}

Beyond that: Is there a boilerplate code available for capturing events in web3.js that are fired by smart contracts ?


text:
Q: when child element has only :focus-visible, how to get parent element :focus-within? When a child element has only focus-visible, how to get parent parent element focus-within?
I want the parent get outline when focus child by keyboard.
But this code is always has focus(outline) when I click to label or checkbox.
How can I do this?
I'm trying
.parent:focus-within:not(:focus){ ~~ }

but it failed.
This is my code:

.parent:focus-within {
    outline: red auto 1px;
}
.child:focus {
    outline-color: red;
}
.child:focus:not(:focus-visible) {
    outline: 0;
}

  <input type="checkbox" class="child">

A: This is behavior is not supported by :focus-within, but it is possible using :has()

.parent:has(:focus-visible) {
  outline: red auto 1px;
}

.child:focus {
  outline-color: red;
}

.child:focus:not(:focus-visible) {
  outline: 0;
}

  <input type="checkbox" class="child">

At the moment, :has() does not yet have full support in all major browsers


text:
Q: Call Lua table function from C++ w/ self in function My goal is to simply call a table function from C++ that uses 'self' inside of the function to access fields and functions of that table. I keep getting the lovely 'attempt to call a nill value (local self)' on the line that has 'self.name'. Below is my Lua script.
Foo = { name = 'Foo' }

function Foo:OnUpdate()
  print('In OnUpdate in Lua')
  print(self.name)
end

Below is my C++ code (ignoring any error handling for now).
lua_State* L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "foo.lua");
lua_getglobal(L, "Foo");
lua_getfield(L, -1, "OnUpdate");
lua_pcall(L, 0, 0, 0);

When 'lua_pcall' is called, I see 'In OnUpdate in Lua' in the CLI, but never 'Foo'. If I check the error from 'lua_pcall' I get the error message mentioned above. Am I missing a certain Lua C API function prior to calling 'lua_pcall'? I am aware of the '.' vs. ':' in lua for utilizing 'self'. If I add a call in the Lua script like 'Foo:Update()', everything works perfectly. This has got me stumped.

A: You need to send the value of Foo as the first argument. So, do
lua_pushvalue(L, -2);
lua_pcall(L, 1, 0, 0);


text:
Q: swapping between mobile view and desktop view on window resize How can I swap desktop view and mobile view based on browser dimensions.
Like bostonglobe.com site it automatically swaps between mobile and desktop when i resize my window.
Is it HTML5 property or a jquery plugin ?

A: An awesome question.
There are a few resources I would like to send your way, for things like this I personally find it neat to try and piece it all together on your own.
First, read this thoroughly - Responsive Web Design
get a firm grasp of media queries, what you can and can't do with them.

Other alternative resources - clever us of js event_listeners to detect browser window resolution changes
This is another alternative route, perhaps a little more work involved, but all the code is there.

lessframework
this is a css framework with a grid system designed with exactly what you are thinking in mind. not my favored approach, but the more options the better rite?
Good Luck..or er ahem, may your application of knowledge and determination bring you success, or something.


text:
Q: A scientist catches 8 butterflies I A scientist catches $8$ butterflies, each of which may appear in one of $4$ different colors:

*

*White

*Brown

*Red

*Black

What is the probability that the last butterfly caught is the second white?
The optional answers are:

*

*$0.078$

*$0.089$

*$0.311$

*$0.356$

My attempts:
We have equal space and independent events.
Every butterfly can be in any of the $4$ different colors.
The probability of catching a butterfly with a specific color is $\frac14$.
Therefore, using Binomial distribution, the answer should be $\binom71\cdot\left(\frac14\right)^1\cdot\left(\frac34\right)^6\cdot\left(\frac14\right)$.
For the first $7$ multiplied with $\frac14$ for the last like geometric distribution $=0.07786$?

A: The total number of sequences is $4^8$.
The number of sequences containing $2$ white butterflies with one of them at the end is:

*

*Put the second white butterfly at the $8$th place

*Choose $1$ out of the remaining $7$ places for the first white: $\binom71$

*In the remaining $6$ places, choose any of the remaining $3$ colors: $3^6$

Hence the probability is $\frac{\binom71\cdot3^6}{4^8}\approx0.078$.


text:
Q: Unexpected sub-type Upgraded to v3 from the latest 2.x and getting the error:
Unexpected sub-type: Product

In the method:
internal static byte[] GetBytes<T>(T sourceObject)
{
    using (var stream = new MemoryStream())
    {
        Serializer.Serialize(stream, sourceObject);
        return stream.ToArray();
    }
}

The Product class has the header:
[ProtoContract]
public partial class Product : CachableModel, iDeletable, iFilesUploadable, iUserGeneratedContent

CachableModel has the header:
[ProtoContract]
[ProtoInclude(200, typeof(Product))]
public abstract class CachableModel : BaseObject, iInstanceType
{

And BaseObject has the header:
[ProtoContract]
[ProtoInclude(1, typeof(CachableModel))]
public abstract class BaseObject

Why is this not working?

A: Figured it out, due to AsReference being depricated, serialisation of these properties in Protobuff is no longer possible -  however the error message indicates it's a problem with the model itself and not the AsReferenced property.
I can fix this with a lot of refactoring to remove the AsReference requirement in my project.


text:
Q: Adding controls to an ItemsControl within a UserControl using XAML I want to write an control that behaves a bit like the CommandBar.
Using CommandBar you can write:
<CommandBar>
    <CommandBar.PrimaryCommands>
        <AppBarButton>B1</AppBarButton>
        <AppBarButton>B2</AppBarButton>
    </CommandBar.PrimaryCommands>
</CommandBar>

My control also has properties to which controls can be added within xaml.
Like this:
<Page
    x:Class="TheApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:App27"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <local:MyControl>
            <local:MyControl.LeftStuff>
                <Button>L1</Button>
                <Button>L2</Button>
            </local:MyControl.LeftStuff>
            <local:MyControl.MidStuff>
                <Button>M1</Button>
                <Button>M2</Button>
            </local:MyControl.MidStuff>
            <local:MyControl.RightStuff>
                <Button>R1</Button>
                <Button>R2</Button>
            </local:MyControl.RightStuff>
        </local:MyControl>
    </Grid>
</Page>

So far I've come up with the following UserControl.
MyControl.xaml:
<UserControl
    x:Class="TheApp.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:App27"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DesignHeight="300"
    d:DesignWidth="400"
    mc:Ignorable="d">

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ItemsControl Grid.Column="0" ItemsSource="{x:Bind LeftStuff}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
        <ItemsControl Grid.Column="1" ItemsSource="{x:Bind MidStuff}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
        <ItemsControl Grid.Column="2" ItemsSource="{x:Bind RightStuff}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>
</UserControl>

MyControl.xaml.cs:
namespace TheApp
{
    using System.Collections.ObjectModel;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    public sealed partial class MyControl: UserControl
    {
        public MyControl()
        {
            this.InitializeComponent();
        }

        public static readonly DependencyProperty LeftStuffProperty =
            DependencyProperty.Register("LeftStuff", typeof(ObservableCollection<FrameworkElement>), typeof(MyControl), new PropertyMetadata(null));

        public ObservableCollection<FrameworkElement> LeftStuff
        {
            get { return (ObservableCollection<FrameworkElement>)GetValue(LeftStuffProperty); }
            set { SetValue(LeftStuffProperty, value); }
        }

        public static readonly DependencyProperty MidStuffProperty =
            DependencyProperty.Register("MidStuff", typeof(ObservableCollection<FrameworkElement>), typeof(MyControl), new PropertyMetadata(null));

        public ObservableCollection<FrameworkElement> MidStuff
        {
            get { return (ObservableCollection<FrameworkElement>)GetValue(MidStuffProperty); }
            set { SetValue(MidStuffProperty, value); }
        }

        public static readonly DependencyProperty RightStuffProperty =
            DependencyProperty.Register("RightStuff", typeof(ObservableCollection<FrameworkElement>), typeof(MyControl), new PropertyMetadata(null));

        public ObservableCollection<FrameworkElement> RightStuff
        {
            get { return (ObservableCollection<FrameworkElement>)GetValue(RightStuffProperty); }
            set { SetValue(RightStuffProperty, value); }
        }
    }
}

This compiles and MainPage is rendered as expected in designer.

But when I run the code I get this exception:

An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in App27.exe but was not handled in user code
  WinRT information: Cannot add instance of type 'Windows.UI.Xaml.Controls.Button' to a collection of type 'System.Collections.ObjectModel.ObservableCollection`1'. [Line: 16 Position: 13]
  ...

So what is wrong?

A: To answer the question myself:
the dependency properties need to be initialized so that xaml can add the elements.
public static readonly DependencyProperty ...StuffProperty =
    DependencyProperty.Register(
        "...Stuff",
        typeof(ObservableCollection<FrameworkElement>),
        typeof(MyControl),
        // The property needs to be initialized
        new PropertyMetadata(new ObservableCollection<FrameworkElement>())
    );


text:
Q: How to Get a Cut in Timeline? I want to get three dots in timeline, not next to it like in the following picture.
Code
\documentclass[xcolor=x11names]{beamer}
% http://tex.stackexchange.com/a/196808/13173
% http://tex.stackexchange.com/a/303021/13173

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}
\usepackage{graphicx}
\usepackage[x11names]{xcolor}
\usepackage{colortbl}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}

\begin{document}

\begin{frame}
\begin{table}
\renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
\captionsetup{singlelinecheck=false, font=blue, labelfont=sc, labelsep=quad}
\caption{Timeline}\vskip -1.5ex
\begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
\toprule
\addlinespace[1.5ex]
1969 & Lassa virus. \\
... \\
1989 & Guanarito virus, Venezuela.\\
\end{tabular}
\end{table}
\end{frame}

\end{document}

Output

where I do not like that three dots are next to the line.
I actually do not want any separate dots but those dots should be along the vertical timeline
Expected out: some dots in the timeline vertically such that no separate entry needed. I do not want those dots next to the timeline but integral parts of the timeline like you can cut axis in some Excel versions.
cuts here for axes without dots

Such a cut is also ok. It just must show that there is a gap in timeline.
Minimize Tobi's Vertical Space
% http://tex.stackexchange.com/a/303060/13173
\newlength{\CVbreakdotsep}% length to change spacing between dots
\setlength{\CVbreakdotsep}{0.1mm}

\newcommand{\CVbreakdot}{% command for smaller dots
   \scalebox{0.4}{\textbullet}% % 0.6 too big!
}

\newcommand{\CVbreak}{% command for the break itself
   \multicolumn{2}{l}{%
      \hspace*{8.715mm}% <--- align dots with vertical line
      \rotatebox[origin=c]{-90}{%
         \color{LightSteelBlue3}%
         \hspace{0mm}% <--- extra vertical space; No
         \CVbreakdot\kern\CVbreakdotsep\CVbreakdot\kern\CVbreakdotsep\CVbreakdot
         \hspace{0mm}% <--- extra vertical space; No
      }%
   } \\%
}

\newcommand{\foo}{\color{LightSteelBlue3}
\makebox[0pt]{\textbullet}\hskip-0.5673pt\vrule width 1pt\hspace{\labelsep}}

% - -
\begin{document}
% - -
\begin{table}
% - -
   \begin{tabular}{@{\,}r <{\hskip 1.3pt} !{\foo} >{\raggedright\arraybackslash}p{9cm}}
% - -

Output where uneven distance to top and tail, and too much vertical distance around the cut

2nd Iteration on Tobi's Minimal Vertical Space
I found out that two dots is the optimum amount to indicate the cut.
Three is just too much and one is too little.
I find little different horizontal alignment and also a little change in the vertical alignment
\newcommand{\CVbreakdot}{% command for smaller dots
   \scalebox{0.4}{\textbullet}%
}

\newcommand{\CVbreak}{% command for the break itself
   \multicolumn{2}{l}{%
      \hspace*{8.7mm}% <--- align dots with vertical line
      \rotatebox[origin=c]{-90}{%
         \color{LightSteelBlue3}%
         \hspace{-5.3mm}% <--- extra vertical space
         \CVbreakdot\kern\CVbreakdotsep\CVbreakdot
      }%
   } \\[-3.6mm]%
}

Output which shows that the timeline's head and tail are taking much space in the region so I think they can be shortened

How can you get a Cut in Timeline?

A: You could use a \multicolumn to overwrite the general column specification. In the column I used \rotatexbox to get three dots below each other and \hspace to align them with the time line. You may adjust the values to your needs.

\documentclass[xcolor={x11names,table}]{beamer}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}

\newcommand{\foo}{%
   \color{LightSteelBlue3}%
   \makebox[0pt]{\textbullet}%
   \hskip-0.5pt\vrule width 1pt%
   \hspace{\labelsep}%
}

\newlength{\CVbreakdotsep}% length to change spacing between dots
\setlength{\CVbreakdotsep}{0.6mm}

\newcommand{\CVbreakdot}{% command for smaller dots
   \scalebox{0.6}{\textbullet}%
}

\newcommand{\CVbreak}{% command for the break itself
   \multicolumn{2}{l}{%
      \hspace*{8.715mm}% <--- align dots with vertical line
      \rotatebox[origin=c]{-90}{%
         \color{LightSteelBlue3}%
         \hspace{2mm}% <--- extra vertical (horizontal–90°) space
         \CVbreakdot\kern\CVbreakdotsep\CVbreakdot\kern\CVbreakdotsep\CVbreakdot
         \hspace{2mm}% <--- extra vertical (horizontal–90°) space
      }%
   } \\%
}

\begin{document}

\begin{frame}
\begin{table}
   \renewcommand\arraystretch{1.4}
   \arrayrulecolor{LightSteelBlue3}
   \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
      \toprule
      \addlinespace[1.5ex]
      1969 & Lassa virus. \\
      \CVbreak
      1989 & Guanarito virus, Venezuela. \\
   \end{tabular}
\end{table}
\end{frame}

\end{document}

smaller spaces:

\documentclass[xcolor={x11names,table}]{beamer}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}

\newcommand{\foo}{%
   \color{LightSteelBlue3}%
   \makebox[0pt]{\textbullet}%
   \hskip-0.5pt\vrule width 1pt%
   \hspace{\labelsep}%
}

\newlength{\CVbreakdotsep}% length to change spacing between dots
\setlength{\CVbreakdotsep}{0.1mm}

\newcommand{\CVbreakdot}{% command for smaller dots
   \scalebox{0.4}{\textbullet}% % 0.6 too big!
}

\newcommand{\CVbreak}{% command for the break itself
   \multicolumn{2}{l}{%
      \hspace*{8.97mm}% <--- align dots with vertical line
      \rotatebox[origin=c]{-90}{%
         \color{LightSteelBlue3}%
         \hspace{-5.5mm}% <--- extra vertical (horizontal–90°) space;
         \CVbreakdot\kern\CVbreakdotsep\CVbreakdot\kern\CVbreakdotsep\CVbreakdot
      }%
   } \\[-3.6mm]%
}

\begin{document}

\begin{frame}
\begin{table}
   \renewcommand\arraystretch{1.4}
   \arrayrulecolor{LightSteelBlue3}
   \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
      \toprule
      \addlinespace[1.5ex]
      1969 & Lassa virus. \\
      \CVbreak
      1989 & Guanarito virus, Venezuela. \\
   \end{tabular}
\end{table}
\end{frame}

\end{document}

A: Here is a solution with the nccrules package. I define a \vdashrule, slightly thinner than the rule of the time line, and a \addvdashrule commands. The parameters for the vertical dashline are specific to this context but can easily be adapted to another. You can stack vertical dashlines.
\documentclass[xcolor={x11names, table}]{beamer}
% http://tex.stackexchange.com/a/196808/13173
% http://tex.stackexchange.com/a/303021/13173

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, erewhon}
\usepackage{array, booktabs}
\usepackage{nccrules}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{{\textbullet}}\hskip-0.5pt\vrule width 1pt}
\newcommand\vdashrule{\color{LightSteelBlue3}\dashrule[-0.75ex]{0.8}{2.5 2 2.5 2 2.5 2 2.5}}%
\newcommand\addvdashrule{%
 \multicolumn{1}{@{}r@{}}{\begin{tabular}{@{\,}r <{\hskip 2pt} !{\hspace{\labelsep}\hskip-0.5pt \vdashrule\hskip0.1pt }}~\end{tabular}}}%

\begin{document}

\begin{frame}
    \begin{table}
    \renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
    \captionsetup{singlelinecheck=false, font=blue, labelfont=sc, labelsep=quad}
    \caption{Timeline}\vskip -1.5ex
        \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
        \toprule
        \addlinespace[1.5ex]
        1969 & Lassa virus. \\%
        \addvdashrule \\[-0.4ex]
         \addvdashrule \\
         1989 & Guanarito virus, Venezuela. 1993 - Sabia virus (BrHF), Brazil. 2004 - \end{tabular}
    \end{table}
\end{frame}

\end{document}

A: well, rather a quick hack, than a solution, but perhaps it does, what you want.
\documentclass[xcolor=x11names,table]{beamer}
% http://tex.stackexchange.com/a/196808/13173
% http://tex.stackexchange.com/a/303021/13173

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}

\begin{document}

    \begin{frame}
        \begin{table}
            \renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
            \captionsetup{font=blue, labelfont=sc, labelsep=quad}
            \caption{Timeline}\vskip -1.5ex
            \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
                \toprule
                \addlinespace[1.5ex]
                1969 & Lassa virus.
            \end{tabular}

            \begin{tabular}{@{\,}r <{\hskip 2pt} !{\color{LightSteelBlue3}\makebox[0pt]{\textbullet\textbullet\textbullet}} >{\raggedright\arraybackslash}p{4.4cm}}
                {} & {}
            \end{tabular}

            \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
                1989 & Guanarito virus, Venezuela. 1993 - Sabia virus (BrHF), Brazil. 2004 - \end{tabular}
        \end{table}
    \end{frame}

\end{document}

A: Here's a way of drawing the non-dotted cut using TikZ:
\documentclass[xcolor={x11names,table}]{beamer}% edited in light of Tobi's comment on samcarter's answer at http://tex.stackexchange.com/questions/303039/how-to-get-a-cut-in-timeline/303060?noredirect=1#comment734775_303059
% http://tex.stackexchange.com/a/196808/13173
% http://tex.stackexchange.com/a/303021/13173
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[TS1,T1]{fontenc}
\usefonttheme{professionalfonts}% otherwise fourier's font configuration will be partially overridden
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}
\usepackage{caption}
\usepackage{tikz}
\usetikzlibrary{tikzmark,calc}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}
\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}
\begin{document}
\begin{frame}
  \begin{table}
    \renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}%
    \captionsetup{singlelinecheck=false, font=blue, labelfont=sc, labelsep=quad}%
    \caption{Timeline}\vskip -1.5ex
    \begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
      \toprule
      \addlinespace[1.5ex]
      1969\tikzmark{a} & \tikzmark{b}Lassa virus. \\
      1989\tikzmark{c} & \tikzmark{d}Guanarito virus, Venezuela. 1993 - Sabia virus (BrHF), Brazil. 2004 - \end{tabular}
    \begin{tikzpicture}[overlay,remember picture]
      \path [draw=LightSteelBlue3, double distance=2.5pt, thick] ([xshift=3pt,yshift=4.5pt]$({pic cs:a})!1/2!({pic cs:c})$) .. controls +(10pt,5pt) and +(-10pt,-5pt) .. ([xshift=-5pt, yshift=2pt]$({pic cs:b})!1/2!({pic cs:d})$);
    \end{tikzpicture}
  \end{table}
\end{frame}
\end{document}

A: Three dots on the timeline, without date or text appended to those dots, is achieved by adding {} & {} three times to the timeline data.
\documentclass[xcolor=x11names]{beamer}
% http://tex.stackexchange.com/a/196808/13173
% http://tex.stackexchange.com/a/303021/13173

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage[TS1,T1]{fontenc}
\usepackage{fourier, heuristica}
\usepackage{array, booktabs}
\usepackage{colortbl}
\usepackage{caption}
\DeclareCaptionFont{blue}{\color{LightSteelBlue3}}

\newcommand{\foo}{\color{LightSteelBlue3}\makebox[0pt]{\textbullet}\hskip-0.5pt\vrule width 1pt\hspace{\labelsep}}

\begin{document}

\begin{frame}
\begin{table}
\renewcommand\arraystretch{1.4}\arrayrulecolor{LightSteelBlue3}
\captionsetup{singlelinecheck=false, font=blue, labelfont=sc, labelsep=quad}
\caption{Timeline}\vskip -1.5ex
\begin{tabular}{@{\,}r <{\hskip 2pt} !{\foo} >{\raggedright\arraybackslash}p{5cm}}
\toprule
\addlinespace[1.5ex]
1969 & Lassa virus. \\
{} & {} \\
{} & {} \\
{} & {} \\
1989 & Guanarito virus, Venezuela. 1993 - Sabia virus (BrHF), Brazil. 2004 - \end{tabular}
\end{table}
\end{frame}

\end{document}


text:
Q: NSSortDescriptor not working I have a core data entity called "TruckNumber" which has a string as it's only property.  The string is usually a 1-3 digit integer (as a string) but sometimes can have letters such as TMP9.  The name of the property is "itsNotANumma".  I am doing a fetch request to populate a picker, but they are not being sorted and I don't know why.  I've used this exact technique on other entities for other pickers and never had a problem.  Please help... Here's the relevant code:
// Fetch truck numbers
NSFetchRequest *truckNumberFetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *truckEntity = [NSEntityDescription entityForName:@"TruckNumber" inManagedObjectContext:self.managedObjectContext];
[truckNumberFetchRequest setEntity:truckEntity];

// Sort Descriptor
NSSortDescriptor *truckDescriptor = [[NSSortDescriptor alloc] initWithKey:@"itsNotANumma" ascending:YES];

NSArray *truckSortDescriptors = [[NSArray alloc] initWithObjects:truckDescriptor, nil];
[inventoryFetchRequest setSortDescriptors:truckSortDescriptors];
error = nil;
NSArray *truckResults = [managedObjectContext executeFetchRequest:truckNumberFetchRequest error:&error];

if (error)
    NSLog(@"Unresolved error while saving context: %@, %@", error, [error userInfo]);

truckNumbersArray = [[NSMutableArray alloc] init];
for (TruckNumber *truckNumber in truckResults)
{
    [truckNumbersArray addObject:truckNumber.itsNotANumma];
}

Here is my data model for truck number:

These are the results:

A: Looks like you have a simple typo:
[inventoryFetchRequest setSortDescriptors:truckSortDescriptors];

Should be:
[truckNumberFetchRequest setSortDescriptors:truckSortDescriptors];

I would assume anyway, from reading that code.

A: [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES comparator:^(id obj1, id obj2){
    return [(NSString*)obj1 compare:(NSString*)obj2 options:NSNumericSearch];
}];

It works so perfectly if you have numbers in a range from 1-5000 or onwards.


text:
Q: How to get report of "those users who were excluded" using multiple where-object conditions in get-aduser command? I have put together a script which uses the get-aduser command in ActiveDirectory module to fetch report of users who have logged in since last 30 days. The script also excludes users based on certain parameters which are specified beforehand in an array list (for example, exclude users with description 'admin', ' test' etc). I have included the code as well.
The report works OK without any issues.
Now, is there a way to get a report of those users who were excluded as part of these filters?
I know the script can be re-run by reversing the -nomatch switches to -match and few other adjusts to get the desired data - but is there a better, cleaner way ???  See code below:
import-module activedirectory
$excludeOU = @("service accounts","exchange accounts","monitoring mailboxes","Test","Support Users")
$excludedescription = @("admin","logistik","test","serviceaccount","service account","Anonymous","logistics","logistiek","gen_","automation")
$excludesam = @("adm-","support","service","install","invoice","floor","svc-","sa-","gen_","alg_","dev.ops")
$excludefirstname = @("Gateway")

get-aduser -filter * -properties whencreated, lastlogondate, description, telephonenumber, city, country, title, department, company, manager, mail, displayname |
Where-Object {($_.lastlogondate -ge (Get-Date).AddDays(-30)) -and ($_.distinguishedname -notmatch ('(' + [string]::Join(')|(', $excludeOU) + ')')) -and ($_.enabled -eq "TRUE") -and ($_.description -notmatch ('(' + [string]::Join(')|(', $excludedescription) + ')')) -and ($_.givenname -notmatch ('(' + [string]::Join(')|(', $excludefirstname) + ')')) -and ($_.samaccountname -notmatch ('(' + [string]::Join(')|(', $excludesam) + ')'))} |
select-object givenname, surname, whencreated, description, lastlogondate, telephonenumber, city, country, title, department, company, @{Name='Manager';Expression={(Get-ADUser $_.Manager -properties displayname).displayname}}, samaccountname, mail, displayname, userprincipalname, @{Name='OU';Expression={$_.distinguishedname -replace '^.+?,(CN|OU.+)','$1'}}, enabled |
export-csv C:\ADreporter\powershell\report_$(Get-Date -UFormat "%B-%d-%Y").csv -notypeinformation

A: Programming/formatting style IS as matter of presonal prefernces,
but the way you do it in your script renders it nearly unreadable.

*

*You know that you can insert line breaks where ever PowerShell expects a continuation?
That is after a |{,,operators -and or in front of a } or explicitly after a single backtick >`<

*constructing the RegEx Alternation inside that monstruous Where-Object is not helpful
why not doing that just after defining the arrays?

*IMO obeying the camel type notation of cmdlets/parameters helps reading; but that's debatable.

I applied some of that to your script for better readability:
## Q:\Test\2019\08\23\SO_57627751.ps1
Import-Module activedirectory

$excludeOU = @("service accounts","exchange accounts","monitoring mailboxes","Test","Support Users")

$excludedescription = @("admin","logistik","test","serviceaccount","service account",
                        "Anonymous","logistics","logistiek","gen_","automation")

$excludesam = @("adm-","support","service","install","invoice","floor",
                "svc-","sa-","gen_","alg_","dev.ops")

$excludefirstname = @("Gateway")

Get-ADUser -filter * -properties whencreated, lastlogondate, description, telephonenumber,
               city, country, title, department, company, manager, mail, displayname |
  Where-Object {($_.lastlogondate -ge (Get-Date).AddDays(-30)) -and
                ($_.distinguishedname -notmatch ('(' + [string]::Join(')|(', $excludeOU) + ')')) -and
                ($_.enabled -eq "TRUE") -and
                ($_.description -notmatch ('(' + [string]::Join(')|(', $excludedescription) + ')')) -and
                ($_.givenname -notmatch ('(' + [string]::Join(')|(', $excludefirstname) + ')')) -and
                ($_.samaccountname -notmatch ('(' + [string]::Join(')|(', $excludesam) + ')'))} |
  Select-Object givenname, surname, whencreated, description, lastlogondate,
                telephonenumber, city, country, title, department, company,
               @{Name='Manager';Expression={(Get-ADUser $_.Manager -properties displayname).displayname}},
               samaccountname, mail, displayname, userprincipalname,
               @{Name='OU';Expression={$_.distinguishedname -replace '^.+?,(CN|OU.+)','$1'}}, enabled |
  Export-Csv C:\ADreporter\powershell\report_$(Get-Date -UFormat "%B-%d-%Y").csv -NoTypeInformation

but is there a better, cleaner way ?
Store your first Get-ADUser output in a variable, apply your Where-Object on it and
store the result in another variable to then use Compare-Object on them.
Depending on the size of your AD there might be other better ways.

A: Another approach could be to create a custom helper function to do all testing on the user's properties and use that in the Where-Object clause.
For efficiency, it exits with $false on the first test that fails, and therefore all tests are 'reversed'.
(-notmatch --> -match, -ge --> -lt).
Also, on the Get-ADUser cmdlet itself, I've added -Filter 'Enabled -eq $true' so we don't have to deal with disabled users at least..
Import-Module ActiveDirectory

function Test-User {
    # a dedicated helper function to test several properties of a user object
    # returns $true or $false. Bails out with $false on the first failed test.
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Microsoft.ActiveDirectory.Management.ADUser]$User
    )
    # test LastLogonDate
    if ($User.LastLogonDate -lt (Get-Date).AddDays(-30)) { return $false }

    # test DistinghuishedName
    $exclude = '({0})' -f ('service accounts','exchange accounts',
                           'monitoring mailboxes','Test','Support Users' -join '|')
    if ($User.DistinguishedName -match $exclude) { return $false }

    # test Description
    $exclude = '({0})' -f ('admin','logistik','test','serviceaccount','service account',
                           'Anonymous','logistics','logistiek','gen_','automation' -join '|')
    if ($User.Description -match $exclude) { return $false }

    # test firstname
    $exclude = '({0})' -f (@('Gateway') -join '|')  # add more firstnames if needed
    if ($User.GivenName -match $exclude) { return $false }

    # test SamAccountName
    $exclude = '({0})' -f ('adm-','support','service','install','invoice',
                           'floor','svc-','sa-','gen_','alg_','dev.ops' -join '|')
    if ($User.SamAccountName -match $exclude) { return $false }

    # if you've come this far, the user object passed all tests
    return $true
}

$properties = 'Created', 'LastLogonDate', 'Description', 'telephoneNumber', 'City',
              'Country', 'Title', 'Department', 'Company', 'Manager', 'EmailAddress', 'DisplayName'
$outputFile = 'C:\ADreporter\powershell\report_{0:MMMM-d-yyyy}.csv' -f (Get-Date)

Get-ADUser -Filter 'Enabled -eq $true' -Properties $properties |
    Where-Object { (Test-User -User $_) } |
    Select-Object GivenName, Surname, Created, Description, LastLogonDate, telephoneNumber,
                  City, Country, Title, Department, Company,
                  @{Name='Manager'; Expression={(Get-ADUser $_.Manager -Properties DisplayName).DisplayName}},
                  SamAccountName, EmailAddress, DisplayName, UserPrincipalName,
                  @{Name='OU'; Expression={$_.DistinguishedName -replace '^.+?,(CN|OU.+)','$1'}},
                  Enabled |
    Export-Csv $outputFile -NoTypeInformation

IMO this code reads a lot nicer than using a Where clause that never seems to end..


text:
Q: Is there a difference between exit(0) and exit(True) in Python? I don't like to use integers and can not remember (even in years) what they mean. So I would like to have constants for that.
Is there a difference between this two calls?
sys.exit(0)
sys.exit(True)

Or are there other contstants for that?
The background of my question is that I had a situation where the caller of my script act different between the two cases.

A: Using sys.exit(True) suggests to the user that the script exited with an error because it's non-zero:
Ξ /tmp → cat true_exit.py
import sys
sys.exit(True)
Ξ /tmp → python true_exit.py
↑1 /tmp → echo $?
1

If you want to use True/False instead of exit numbers, you can either define your own constants or use True/False:
Ξ /tmp → cat false_exit.py
import sys
sys.exit(False)
Ξ /tmp → python false_exit.py
Ξ /tmp → echo $?
0

Note that it may be helpful for other maintainers of your code if you use the same constants as defined in sysexits.h (probably available to you on *nix and OS X in /usr/include/sysexits.h).

A: From the official documentation for sys.exit() :
sys.exit([arg])
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered "successful termination" and any nonzero value is considered "abnormal termination" by shells and the like. Most systems require it to be in the range 0-127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.
Here True corresponds to 1.
Exit codes can be from 0 to 127 as they say in the documentation, you can choose which exit code you want to assign, it defaults to 0 though and True will correspond to 1.


text:
Q: Is it possible to use my css in jquery I got jquery script that I can use for my site and it works as intended. The only problem is that the fonts and size used by this jquery don't even look the same with the rest of the page.
According to the site where I got that jquery, in order for the jquery to work I have to include these links:
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

How can I incorporate or change the css to my own css so the jquery fonts can look the same with the rest of the fonts in my site? for example, the font in jquery auto complete looks so much bigger than the rest of the font in the page

A: Put your desired font property declaration.
.ui-widget { font-family: Verdana,Arial,sans-serif; font-size: 10px; }


text:
Q: absolute positioning not aligning properly The following code...
<article id="post-<?php the_ID(); ?>" style="background-image:url('<?php echo $thumbnail_url ?>')" <?php post_class('container-fluid'); ?> >

<a href="<?php the_permalink(); ?>" rel="bookmark"><?php  the_title(); ?>

     <?php the_category(', '); ?>

... Creates the posts for my Wordpress theme. It makes a row (100% width) with title, category, and background-image. Each post is stacked on top of each other.
I want the title and category to stay at the bottom of the article ( I put a class of 'textr' on the div so they are grouped together.
However that div now sits on top of the article it should be in, not inside and at the bottom
css
article {
  background-repeat: no-repeat;
  background-size: cover;
  border-top: 1px solid #000;
  background-position: left center;
  height: 400px;
  margin: 0;
  padding: 0;
}

.text-cell {
  position: relative;
  margin: 0;
  padding: 0;
}

.textr{
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

A: Try moving position: relative; from .text-cell to article
or
You can also modify .text-cell to this:
.text-cell {
    position:absolute;
    width:100%;
    height:100%;
    margin:0;
    padding:0;
}


text:
Q: @Qualifier won't work for me to resolve the beans ambguity problems I am using Spring 4 with Java 8. I am using @Qualifier to resolve the ambiguity problem in Spring beans but when I tried to run the application it will showing me error having same ambiguity problem.
Car.Java
package beans;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Qualifier;

public class Car {
    @Autowired
    @Qualifier("e1")
    private Engine engine;

    public void printData() {

        System.out.println("Car Model Year "+engine.getModelyear());
    }
}

Engine.java
package beans;

public class Engine {
    private String modelyear;

    public String getModelyear() {
        return modelyear;
    }

    public void setModelyear(String modelyear) {
        this.modelyear = modelyear;
    }
}

Spring.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" >
   <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>
   <bean id="e1" class="beans.Engine">
   <property name="modelyear" value="2017"/>
   </bean>
   <bean id="e2" class="beans.Engine">
   <property name="modelyear" value="2018"/>
   </bean>
    <bean id="c" class="beans.Car">

   </bean>

</beans>

My Test class is:
package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import beans.Car;

public class Client {
    public static void main(String[] args) {
        ApplicationContext ap=new ClassPathXmlApplicationContext("resources/spring.xml");
        Car c=(Car) ap.getBean("c");
        c.printData();
    }
}

A: Add primary="true" to the e1 declaration
<bean id="e1" class="beans.Engine" primary="true">

A: You are mixing xml and non-xml configuration. In order to enable autowire, you need to add
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config />

to your xml file.
Or you can set the bean manually in xml
<bean id="c" class="beans.Car">
    <property name="engine" ref="e1"/>
</bean>

but then you need to modify your Car class:
private Engine engine;

public void setEngine(Engine engine) {
    this.engine = engine;
}

A: Actually, your problem is the following:
You have defined AutowiredAnnotationBeanPostProcessor in your spring xml to process @Autowired annotations but you don't have any post bean processor for your @Qualifier annotation.That is why your @qualifier is ignored.Hence bean ambiguity.
Just add
<context:annotation-config/>

and remove
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean>

since it won't be needed anymore.


text:
Q: Multiple -notmatch strings in powershell I am struggeling to combine -notmatch expressions using powershell, just like what I do under Linux e.g. with grep -v "/aaa/" | grep -v "/bbb/". In other words I have the input in.txt looking as follows:
/aaa
/aaa/x.txt
/bbb
/bbb/y.txt
/ccc
/ccc/z.txt

I want to end up with an file out.txt
/aaa
/bbb
/ccc
/ccc/z.txt

What I have so far is cat in.txt | ?{$_ -notmatch '/aaa/'}  > out.txt;, but how do I generalize this?
PS: Yes, I searched the web for examples or manpage, but I guess I am stuck in my bubble.
References

*

*Similar title on stackoverflow, but not clear to me

A: Pipe a second -notmatch:
cat in.txt | ?{$_ -notmatch '/aaa/'} | ?{$_ -notmatch '/bbb/'} > out.txt;

Or to shorten it:
cat in.txt | ?{$_ -notmatch '/aaa/|/bbb/'}  > out.txt;

It should produce your expected result.


text:
Q: Java concurrent hashmap missing values I'm using Java's Concurrent Executors to read in several files at once and write the info to a hashmap. The files are for daily logs that look something like this:
+-----------+-------+-----------+-------+
| Member ID | Time  | Weight    | Fat % |
+-----------+-------+-----------+-------+
| 1123141   | 1:03  | 162       | 21.2  |
| 5321430   | 1:10  | 131       | 25.3  |
| ...       | ...   | ...       | ...   |
+-----------+-------+-----------+-------+

And the hashmap has Member names as keys, and for the values I've created a class "MemberProperties" that has lists for the time and other properties. I'm trying to use multiple threads to read in multiple days at once, write the data to the hashmap, and then do data analysis on a per-member basis. Here's how the code looks
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.ArrayList;
import java.util.Date;
import java.io.IOException;

class MemberProps {
    ArrayList<Date>    time;
    ArrayList<Integer> weight;
    ArrayList<Float>   fat;

    public MemberProps() {
        this.time   = new ArrayList<>();
        this.weight = new ArrayList<>();
        this.fat    = new ArrayList<>();
    }
}

public class MemberFileReader {

    public ConcurrentHashMap<Integer, MemberProps> MemberHash;
    public ExecutorService executor = Executors.newFixedThreadPool(2);

    public void readFiles() {

            //Get this week's files
            File folder = new File("C:\\User\\Temp");
            File[] files = folder.listFiles();

            for (File fl : files) {
                executor.execute(new FileReader(fl.toString()));
            }
            executor.shutdown();
    }

    private final class FileReader implements Runnable {

        private String filepath;

        public FileReader(String filepath) {
            this.filepath = filepath;
        }

        @Override
        public synchronized void run() {

            try {
                String line = null;
                BufferedReader in = new BufferedReader(new FileReader(filepath));
                while ((line = in.readLine()) != null) {

                    MemberProps member = new MemberProps();

                    String[] split_line = line.split("\\t");
                    int member_id = Integer.parseInt(split_line[0]);
                    member.time.add(Date.parse(split_line[1]));
                    member.weight.add(Integer.parseInt(split_line[2]));
                    member.fat.add(Float.parseFloat(split_line[3]));

                    // If not absent, will return member's values
                    member = MemberHash.putIfAbsent(member_id, member);

                    if (member != null){
                        member.time.add(Date.parse(split_line[1]));
                        member.weight.add(Integer.parseInt(split_line[2]));
                        member.fat.add(Float.parseFloat(split_line[3]));
                        MemberHash.put(member_id, member);
                    }
                }

            } catch (IOException E){
                // caught exception
            }
        }
    }
}

My issue is that for some reason, values come up missing in the lists. For example, for a member with 10 logs, I might have 10 times but only 9 weights/fats, or similar 9 times but 10 weights, etc. From debugging, it seems like the issue might happen when different threads try to get the same member and put at the same time, but I'm not sure. Any ideas? To fix this I'm thinking about having different hashmaps for each thread, and then joining the maps after, but idk if there's a simpler solution.

A: ArrayList.add is not thread safe. You should synchronize adding to those lists in MemberProps e.g.
class MemberProps {
    private ArrayList<Date>    time;
    private ArrayList<Integer> weight;
    private ArrayList<Float>   fat;

    public MemberProps() {
        this.time   = new ArrayList<>();
        this.weight = new ArrayList<>();
        this.fat    = new ArrayList<>();
    }

    public synchronized add(Date d, Integer w, Float f) {
        this.time.add(d);
        this.weight.add(d);
        this.fat.add(f);
    }
}

Then use those synchronized methods like this:
if (member != null)) {
    Date d = Date.parse(split_line[1]);
    Integer w = Integer.parseInt(split_line[2]);
    Float f = Float.parseFloat(split_line[3]);
    member.add(d, w, f);
}

Note that you should not put the member into the map a second time since it is already there, you just need to add to the existing instance.

A: You're not adding to the ArrayLists safely. You need to externally synchronize structural modifications, as stated in the Javadoc.
Specifically, your approach of "put if absent, then put again if there was already something there" doesn't work because multiple threads can be executing that code at the same time.
Use compute:
MemberHash.compute(member_id, (k, member) -> {
  if (member == null) {
    member = new MemberProps();
  }
  // Add things to member.
  return member;
});

compute executes atomically, so you won't get two threads trying to add at the same time.