Q: Python 2: insert existing list inside of new explicit list definition This may not be possible, but if it is, it'd be convenient for some code I'm writing:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox', ListOne, 'lazy', 'dog!']

If I do this, I'll end up with ListOne being a single item being a list inside of ListTwo.
But instead, I want to expand ListOne into ListTwo, but I don't want to have to do something like:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox']
ListTwo.extend(ListOne)
ListTwo.extend(['lazy', 'dog!']

This will work but it's not as readable as the above code.
Is this possible?

A: You can just use the + operator to concatenate lists:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']

ListTwo will be:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: Another alternative is to use slicing assignment:
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo = ['The', 'quick', 'brown', 'fox', 'lazy', 'dog!']
>>> ListTwo[4:4] = ListOne
>>> ListTwo
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: >>> ListOne = ['jumps', 'over', 'the']
>>> from itertools import chain
>>> [x for x in chain(['The', 'quick', 'brown', 'fox'], ListOne, ['lazy', 'dog!'])]
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']

A: Why not concatenate?
>>> ListTwo = ['The', 'quick', 'brown', 'fox']
>>> ListOne = ['jumps', 'over', 'the']
>>> ListTwo + ListOne
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the']
>>> ListTwo + ListOne + ['lazy', 'dog!']
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog!']


Q: Laravel group by not working if only one key exists? I have this following code:
        $groupedRates = $result->rates->groupBy('minimum_age');

when I try to return it, I get this:
  "rates": [
                [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ]
            ]

however, if I were to add one more key, it returns an associative array as expected.
  "rates": {
                "0": [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ],
                "50": [
                    {
                        "id": 4,
                        "cpf_scheme_id": 1,
                        "minimum_age": 50,
                        "minimum_wage": 100,
                    }
                ]
            }

How do I fix this? It will break apis if it returns an associative array sometimes and a normal array other times!


Q: Unequilateral triangular icosahedron I am doing a project and making a triangular icosahedron. I am thinking I might not use equilateral triangles to make it smaller. Is this possible?


Q: Can NSNotificationCenter be used between different frameworks to communicate? An app can make internal use of NSNotificationCenter for different parts to communicate with each other, but can this be extended such that different frameworks can use it to communicate on iOS?

A: In the same app, frameworks all get executed on the same process. They just locate at different places in memory allocated by the app.
On the same running process, NSNofitcationCenter can communicate with each other no matter which framework the sender or receiver locates at.
If you are talking about app and its extension, they run on different process and thus NSNofitcationCenter can not send notification to each other. You have to use CFNotificationCenter


Q: How can I edit and transfer output tables from R? I am working with R for analyzing data for my research paper. I have run some regressions and marginal effects and would like to get the output in a format that I can include in my research paper (best would be tables as images). How can I do this?
I have tried using the sumtable() command, but it only provides a table that summarizes the overall data that I am using and not the specific regressions or the marginal effect output.
I have also used htmlreg() but as far as I know it is only for regressions, and I do not know how to transfer the html output into my word document where I am writing the paper.


Q: Compare date and hour together I am using Amazon Redshift . In my tables I have two columns (Date and Hour) ,along with other columns with values like
requestdate  requesthour
2016-10-10     1
2016-10-10     2
 ...          ...

Now I want to compare two dates with hours (day between 2016-10-1005 && 2016-11-1109) . Generally comparing with qyery like
Where date>=xxxx && date<=yyyy && hour>=hhhh && hour<hhhh

will give incomplete results . Can I do something which can be useful here , I tried certain things after searching the web like concat , to_timestamp but could not come up with proper query .
Can anyone help here?

A: Here is one explicit way:
where (date > xxxx or (date = xxxx and hour >= hhhh)) and
      (date < yyyy or (date = yyyy and hour < hhhh))

Another method would use date arithmetic:
where date + hour * interval '1 hour' >= xxxx + hhhh * interval '1 hour' and
      date + hour * interval '1 hour' < yyyy + hhhh * interval '1 hour'

A: You can cast your date + hour to timestamp and let database to compare them
select (requestdate ||' '|| requesthour ||':00:00')::timestamp  between ('2016-10-10 05:00:00')::timestamp and ('2016-08-01 04:00:00')::timestamp  from bbt


Q: Automatic brightness control including external monitor There are existing threads about controlling in software the brightness of an external display ( control brightness on the second monitor , Changing the screen brightness of the external screen , Artificially lower brightness on all screens).
That's great, but it's all very manual. I love the automatic brightness feature. However, when the main display of my laptop changes brightness, the external lags stays unchanged unless I manually change it.
Is there any way to extend this automatic brightness so that it also applies to the external monitor? And ideally also to use my laptop's brightness control keys to change the brightness of both screens simultaneously.

A: Have a look at eyesome Multi-monitor brightness and color temperature based on sun times. Below is a snipped from  the Ask Ubuntu answer.

eyesome
Eyesome is a bash script running as a daemon and sleeping most of the time 24/7. It automatically adjusts screen brightness (and optionally gamma too) for your laptop display via hardware interface and up to two other monitors using xrandr software control.
At sunrise (the time is automatically obtained from the internet each day), your screen brightness and gamma (aka color temperature, hue or tint) is adjusted gradually. Before sunset gradual adjustments are made for nighttime settings. In between these periods they eyesome daemon sleeps many hours.
What distinguishes eyesome from Redshift, Night Light and similar products is the ability to simultaneously control three monitors with unique settings. Also notable is eyesome controls brightness (both hardware and software) in addition to color temperature.
Edit Configuration - Monitor 1 tab
Clicking on Monitor 1 tab reveals this panel in my configuration (yours may be different):

Don't be daunted by these settings because most are automatically obtained by eyesome. You will need to set the daytime and night brightness/levels though.
If the gamma values for Red, Green and Blue are intimidating, you can fine tune them later with the Override button from the Main Menu. There you have access to a slider control for color temperature where 3500 is typical nighttime setting and 6500 is typical daytime setting. Typical daytime setting is 1.0 for Red, Green and Blue channels which is every systems default.
Edit Configuration - Monitor 3 Tab
Clicking on Monitor 3 Tab reveals this panel in my configuration (yours may be different):
Monitor 2 Tab is not shown because it is a new TV with adaptive brightness and Smart OS. It requires no overrides by Eyesome.

When eyesome is installed configuration is automatically created for the most part. If later on you attach a different monitor you may have to enter the xrandr monitor name.

Where to find Eyesome
The full program can be found on github.
A new website called Pippim is under construction and Eyesome will be moved there soon.


Q: What causes the pronunciation "nucular"? What is the name of the phonetic shift behind the common mispronunciation of the word nuclear (nucular)?
Or, if the answer is "none", then I would appreciate learning the origin of the pronunciation.

A: This phenomenon is known as metathesis.
Two major hypotheses for the metathesis in this particular case:

Steven Pinker has proposed a phonotactic explanation for the conversion of nuclear to nucular: the unusual and disfavored sequence [kli.ər] is gradually transformed to a more acceptable configuration via metathesis.
However, Arnold Zwicky notes that [kli.ər] presents no difficulty for English speakers in words such as pricklier. He also regards the proposition of metathesis as unnecessary. Zwicky suggests a morphological origin, combining the slang nuke with the common sequence -cular (molecular, particular, etc.). Supporting Zwicky's hypothesis, Geoffrey Nunberg quotes a government weapons specialist: "Oh, I only say 'nucular' when I'm talking about nukes." Nunberg argues that this pronunciation by weapons specialists and by politicians such as Bush – who are aware of the more accepted pronunciation – may be a "deliberate choice". He suggests that the reasons for this choice are to "assert authority" or to sound folksy.

I personally find the Zwicky hypothesis more compelling: the pronunciation is formed by analogy with words like "molecular" and "particular". But both are possible, and in fact, it doesn't necessarily have to be the same method of production for all speakers — there could be interspeaker variation.
(Note that Zwicky's explanation isn't actually "metathesis" per se at all; instead, being  nuke + ular, it is formed "as it should be".)

A: Causes of the metathesis nuclear > nucular
It occurred to me that very few other words have the syllabic make-up of nùclear,
but there is a host of words in  `-cular (with antepenultimate stress) eg binocular, vascular, muscular, particular, spectacular to name a few.
Thus the shift nuclear > nucular makes perfectly good sense, as a case where an isolated make-up is adapted to a more prevalent pattern.


Q: Outer margins in pairs() function I have too much whitespace around the outside of my pairs() plot. How can one control the outer margins in a pairs() plot?
Changing oma for example does nothing (i.e. par(oma=c(0,0,0,0)) makes no difference).

A: tl;dr use oma as an argument within your pairs() call.
As usual, it's all in the documentation, albeit somewhat obscurely. ?pairs states:

Also, graphical parameters can be given as can arguments to
            ‘plot’ such as ‘main’.  ‘par("oma")’ will be set
            appropriately unless specified.

This means that pairs() tries to do some clever stuff internally to set the outer margins (based on whether a main title is requested); it will ignore external par("oma") settings, only paying attention to internal settings.  The "offending" line within the code of stats:::pairs.default is:
  if (is.null(oma))
        oma <- c(4, 4, if (!is.null(main)) 6 else 4, 4)

Thus setting oma within the call does work:
par(bg="lightblue")  ## so we can see the plot region ...
z <- matrix(rnorm(300),ncol=3)
pairs(z,oma=c(0,0,0,0))


Q: How to make a multi-user file server system with PHP? I'm just looking a big picture idea here; I can google specifics once provided with guidelines.
I want to make a relatively simple file hosting website such as dropbox or skydrive for mainly pedagogical reasons.
Making a multi-user login and registration system with PHP and MySQL is pretty straight forward, but how would I go about managing file directories and permissions for each user?

A: There are probably hundreds of ways to do this, but this is what I would do:

*

*They should never have a direct download path as it can be abused.

*All files could be stored in the same place.

*File names should be changed to unique ids to avoid dupilcates.

*Store the file name, unique id, and user id in a database.

*When they visit the page for the unique id, you can do your checks and display the file info.

*You will then pass the file to them rather than having them download it directly.

*Their user page would show file names and links to those pages, etc.

I hope that is a good jumping off point.

A: At its simplest: Store files somewhere in any hierarchy you want in a location that's not simply publicly accessible through the web server. Store meta information about each file in a database. In said database, store who the owner of the file is. Write a script that allows people to download those files (see readfile), require that users are logged in and that only owners of files can them.


Q: What's the correct way of waiting for detached threads to finish? Look at this sample code:
void OutputElement(int e, int delay)
{
    this_thread::sleep_for(chrono::milliseconds(100 * delay));
    cout << e << '\n';
}

void SleepSort(int v[], uint n)
{
    for (uint i = 0 ; i < n ; ++i)
    {
        thread t(OutputElement, v[i], v[i]);
        t.detach();
    }
}

It starts n new threads and each one sleeps for some time before outputting a value and finishing. What's the correct/best/recommended way of waiting for all threads to finish in this case? I know how to work around this but I want to know what's the recommended multithreading tool/design that I should use in this situation (e.g. condition_variable, mutex etc...)?

A: Don't detach, but instead join:
std::vector<std::thread> ts;

for (unsigned int i = 0; i != n; ++i)
    ts.emplace_back(OutputElement, v[i], v[i]);

for (auto & t : threads)
    t.join();

A: And now for the slightly dissenting answer.  And I do mean slightly because I mostly agree with the other answer and the comments that say "don't detach, instead join."
First imagine that there is no join().  And that you have to communicate among your threads with a mutex and condition_variable.  This really isn't that hard nor complicated.  And it allows an arbitrarily rich communication, which can be anything you want, as long as it is only communicated while the mutex is locked.
Now a very common idiom for such communication would simply be a state that says "I'm done".  Child threads would set it, and the parent thread would wait on the condition_variable until the child said "I'm done."  This idiom would in fact be so common as to deserve a convenience function that encapsulated the mutex, condition_variable and state.
join() is precisely this convenience function.
But imho one has to be careful.  When one says:  "Never detach, always join," that could be interpreted as:  Never make your thread communication more complicated than "I'm done."
For a more complex interaction between parent thread and child thread, consider the case where a parent thread launches several child threads to go out and independently search for the solution to a problem.  When the problem is first found by any thread, that gets communicated to the parent, and the parent can then take that solution, and tell all the other threads that they don't need to search any more.
For example:
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <thread>
#include <vector>

void OneSearch(int id, std::shared_ptr<std::mutex> mut,
                   std::shared_ptr<std::condition_variable> cv,
                   int& state, int& solution)
{
    std::random_device seed;
//     std::mt19937_64 eng{seed()};
    std::mt19937_64 eng{static_cast<unsigned>(id)};
    std::uniform_int_distribution<> dist(0, 100000000);
    int test = 0;
    while (true)
    {
        for (int i = 0; i < 100000000; ++i)
        {
            ++test;
            if (dist(eng) == 999)
            {
                std::unique_lock<std::mutex> lk(*mut);
                if (state == -1)
                {
                    state = id;
                    solution = test;
                    cv->notify_one();
                }
                return;
            }
        }
        std::unique_lock<std::mutex> lk(*mut);
        if (state != -1)
            return;
    }
}

auto findSolution(int n)
{
    std::vector<std::thread> threads;
    auto mut = std::make_shared<std::mutex>();
    auto cv = std::make_shared<std::condition_variable>();
    int state = -1;
    int solution = -1;
    std::unique_lock<std::mutex> lk(*mut);
    for (uint i = 0 ; i < n ; ++i)
        threads.push_back(std::thread(OneSearch, i, mut, cv,
                          std::ref(state), std::ref(solution)));
    while (state == -1)
        cv->wait(lk);
    lk.unlock();
    for (auto& t : threads)
        t.join();
    return std::make_pair(state, solution);
}

int
main()
{
    auto p = findSolution(5);
    std::cout << '{' << p.first << ", " << p.second << "}\n";
}

Above I've created a "dummy problem" where a thread searches for how many times it needs to query a URNG until it comes up with the number 999.  The parent thread puts 5 child threads to work on it.  The child threads work for awhile, and then every once in a while, look up and see if any other thread has found the solution yet.  If so, they quit, else they keep working.  The main thread waits until solution is found, and then joins with all the child threads.
For me, using the bash time facility, this outputs:
$ time a.out
{3, 30235588}

real    0m4.884s
user    0m16.792s
sys 0m0.017s

But what if instead of joining with all the threads, it detached those threads that had not yet found a solution.  This might look like:
    for (unsigned i = 0; i < n; ++i)
    {
        if (i == state)
            threads[i].join();
        else
            threads[i].detach();
    }

(in place of the t.join() loop from above).  For me this now runs in 1.8 seconds, instead of the 4.9 seconds above.  I.e. the child threads are not checking with each other that often, and so main just detaches the working threads and lets the OS bring them down.  This is safe for this example because the child threads own everything they are touching.  Nothing gets destructed out from under them.
One final iteration can be realized by noticing that even the thread that finds the solution doesn't need to be joined with.  All of the threads could be detached.  The code is actually much simpler:
auto findSolution(int n)
{
    auto mut = std::make_shared<std::mutex>();
    auto cv = std::make_shared<std::condition_variable>();
    int state = -1;
    int solution = -1;
    std::unique_lock<std::mutex> lk(*mut);
    for (uint i = 0 ; i < n ; ++i)
        std::thread(OneSearch, i, mut, cv,
                          std::ref(state), std::ref(solution)).detach();
    while (state == -1)
        cv->wait(lk);
    return std::make_pair(state, solution);
}

And the performance remains at about 1.8 seconds.
There is still (sort of) an effective join with the solution-finding thread here.  But it is accomplished with the condition_variable::wait instead of with join.
thread::join() is a convenience function for the very common idiom that your parent/child thread communication protocol is simply "I'm done."  Prefer thread::join() in this common case as it is easier to read, and easier to write.
However don't unnecessarily constrain yourself to such a simple parent/child communication protocol.  And don't be afraid to build your own richer protocol when the task at hand needs it.  And in this case, thread::detach() will often make more sense.  thread::detach() doesn't necessarily imply a fire-and-forget thread.  It can simply mean that your communication protocol is more complex than "I'm done."


Q: sas difference between sum and +? data whatever;
 infile '';
 input price cost;
 <statement>;
run;

In <statement>, what's the difference between using total = sum(total,cost) and total = total + cost ?

A: You'd probably have trouble with either of those if you actually including it after the input statement.
The information that ProgramFOX posted is correct, but if you're asking about the difference between these three statements, there's a little more to it:
total = sum(total,cost);
total + cost;

The second of these implies a retain total; statement and will also treat nulls as zero.  You run into the null problem when you're using this type of expression:
total = total + cost;

A: The differnce can be seen below:
If you want to calculate cumulative total , you should use sum statement.
total = sum(total,cost) /* its a sum function */
total+cost /* its a sum statement,the form is variable+expression */
Here :
"total" specifies the name of the accumulator variable, which contains a numeric value.
1) The variable(total in this case) is automatically set to 0 before SAS reads the first observation. The variable's value is retained from one iteration to the next, as if it had appeared in a RETAIN statement.
2) To initialize a sum variable to a value other than 0, include it in a RETAIN statement with an initial value.
and
"Cost" is an expression
1) The expression is evaluated and the result added to the accumulator variable.
2) SAS treats an expression that produces a missing value as zero.
A sum statement is differ from a sum function in a way that a sum statement retains the value which it has calculated earlier.
However,
The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
retain total 0;
total=sum(total,cost);


Q: Install node and npm using ant build.xml Could someone help to download node and ant from a URL and install them using ant build.xml?
I tried different ways. but it requires sudo privilege. but, it may/may not be available on the server. so, I need common support with normal user privilege.


Q: Divs in template are pushing page out of alignment I have, with advice from members here, attempted to create divs rather than a table for article layout template. I had reasonable success - the content displayed, but not correctly and it also scrambled the page - I had the comments module, which should sit below the article, pushed up on the right and the article content pushed left and down.  I'm posting the table code along with the divs in the hope that someone can assist (One issue, I think, is that there is a single column spanning 8 rows, 4 of which span 2 columns and 4 contain 2 columns, then below this is a further row which spans all 3 columns. I'm confused. For now I've retained the table, but I would really like to learn how to do this correctly. Any help would be appreciated.
Thanks,
Jude
Table:

        <?php echo $item->fields_by_id[3]->result; ?>
        Author:
        <?php echo $item->fields_by_id[1]->result; ?>

        Publisher:
        <?php echo $item->fields_by_id[2]->result; ?>

        Genre:
        <?php echo $item->fields_by_id[9]->result; ?>

        CRR Heat Rating:
        <?php echo $item->fields_by_id[11]->result; ?>

        <?php echo $item->fields_by_id[12]->result; ?>

        <?php echo $item->fields_by_id[10]->result; ?>

        <?php echo $item->fields_by_id[13]->result; ?>

        <?php echo $item->fields_by_id[4]->result; ?>

        <?php echo $item->fields_by_id[5]->result; ?>

Divs:

<?php echo $item->fields_by_id[3]->result; ?>

Author:

Publisher:

Genre:

CRR Heat Rating:

<?php echo $item->fields_by_id[12]->result; ?>

<?php echo $item->fields_by_id[10]->result; ?>

<?php echo $item->fields_by_id[13]->result; ?>

<?php echo $item->fields_by_id[5]->result; ?>

<?php echo $item->fields_by_id[1]->result; ?>

<?php echo $item->fields_by_id[2]->result; ?>

<?php echo $item->fields_by_id[9]->result; ?>

<?php echo $item->fields_by_id[11]->result; ?>

<?php echo $item->fields_by_id[4]->result; ?>

A: float makes that the element has no height anymore, which causes all kinds of 'funny' stuff. I think you are searching for display: table and display: table-cell. Otherwise you can use clear: left; or clear: both on the element that should be displayed under the left-floating elements.

To get the display: table and display: table-cell working, you'll have to remove one div-wrapper around each column.

<?php echo $item->fields_by_id[3]->result; ?>

Author:

Publisher:

Genre:

Then use the following CSS:
#article {
  display: table;
}

#article > div {
  display: table-cell;
}


Q: How to call versioned graph API services in Facebook .NET SDK? It seems that Facebook now wants us to call versioned endpoints of the Graph API. E.g., https://graph.facebook.com/v2.0/me...
Does the Facebook SDK for .NET make versioned calls? Do I/can I do something to specify the version?

A: Sanjeev got it, there is a parameter you can add to specify version:
FacebookClient fbClient = new FacebookClient();
fbClient.Version = "v2.2";
fbClient.Post("me/feed", new
{
    message = string.Format("Hello version 2.2! - Try #2"),
    access_token = "youraccesstokenhere"
});

If you are not specifying a version, it'll default to the oldest supported version:
https://developers.facebook.com/docs/apps/versions#unversioned_calls
Facebook will warn you that you are nearing end of support for that version.
Don't take any chances that the auto-upgrade to newer version will work, better to develop, test and deliver with the latest version.


Q: Application on spark using java langage I'm new on a spark , and I want to run an application on this framework using java language. I tried the following code :
  public  class Alert_Arret  {

  private static final SparkSession sparkSession = SparkSession.builder().master("local[*]").appName("Stateful Streaming Example").config("spark.sql.warehouse.dir", "file:////C:/Users/sgulati/spark-warehouse").getOrCreate();

    public static Properties Connection_db () {

            Properties connectionProperties = new Properties();
            connectionProperties.put("user", "xxxxx");
            connectionProperties.put("password", "xxxxx");
            connectionProperties.put("driver","com.mysql.jdbc.Driver");
            connectionProperties.put("url","xxxxxxxxxxxxxxxxx");

       return connectionProperties;
    }
   public static void GetData() {
        boolean checked = true;
        String dtable = "alerte_prog";
        String dtable2 = "last_tracking_tdays";
        Dataset<Row> df_a_prog = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable, Connection_db());
       // df_a_prog.printSchema();
        Dataset<Row> track = sparkSession.read().jdbc("jdbc:mysql://host:port/database", dtable2, Connection_db());

        if (df_a_prog.select("heureDebut") != null && df_a_prog.select("heureFin") != null ) {
            track.withColumn("tracking_hour/minute", from_unixtime(unix_timestamp(col("tracking_time")), "HH:mm")).show()    }
    }
     public static void main(String[] args) {

     Connection_db();
     GetData();

    }
    }

when I run this code nothing is displayed and I get this:
   0/05/11 14:00:31 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped

  # A fatal error has been detected by the Java Runtime Environment:
   #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006c40022a,pid=3376, tid=0x0000000000002e84

I use IntelliJ IDEA and version of spark: 3.0.0.


Q: Creating an inner stroke of semi transparency on coloured squares? I am drawing different colored squares on canvas with a fixed size of 50px x 50px.
I have successfully added a transparent inner stroke of 5px to these colored squares but it seems like massive overkill the way I am doing it.
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
ctx.fillRect(this.x, this.y, engine.cellSize, engine.cellSize);
ctx.fillStyle = this.color;
ctx.fillRect(this.x + 5, this.y + 5, engine.cellSize - 10, engine.cellSize - 10);

Is there a better way than drawing 3 separate rectangles to achieve what I am after?

A: Yes!
You can use both a fill color inside your rectangle and a stroke color around your rectangle.
Here is code an a Fiddle: http://jsfiddle.net/m1erickson/myGky/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

      var canvas=document.getElementById("canvas");
      var ctx=canvas.getContext("2d");

      ctx.beginPath();
      ctx.fillStyle = "red";
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
      ctx.fillRect(100,100,50,50);
      ctx.fillStyle = this.color;
      ctx.fillRect(105, 105, 40, 40);
      ctx.fill();

      ctx.beginPath();
      ctx.rect(160,102.5,45,45);
      ctx.fillStyle = 'rgb(163,0,0)';
      ctx.fill();
      ctx.lineWidth = 5;
      ctx.strokeStyle = 'rgb(204,0,0)';
      ctx.stroke();

    }); // end $(function(){});
</script>

</head>

<body>
   <canvas id="canvas" width=600 height=400></canvas>
</body>
</html>


Q: Regex help: My regex pattern will match invalid Dictionary I hope you guys can help me out.
I'm using C# .Net 4.0
I want validate file structure like

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

PZ 11
{
IA_return()
}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
";

So far I managed to build this regex pattern

const string patternFileScr = @"
^
((?:\[|\s)*

     (?<Section>[^\]\r\n]*)
 (?:\])*
 (?:[\r\n]{0,}|\Z))
(
    (?:\{)                  ### !! improve for .ini file, dont take {
    (?:[\r\n]{0,}|\Z)
        (                          # Begin capture groups (Key Value Pairs)
        (?!\}|\[)                    # Stop capture groups if a } is found; new section

          (?:\s)*                     # Line with space
          (?<Key>[^=]*?)            # Any text before the =, matched few as possible
          (?:[\s]*=[\s]*)                     # Get the = now
          (?<Value>[^\r\n]*)        # Get everything that is not an Line Changes

         (?:[\r\n]{0,})
         )*                        # End Capture groups
    (?:[\r\n]{0,})
    (?:\})?
    (?:[\r\n\s]{0,}|\Z)
)*

                ";

and c#

  Dictionary <string, Dictionary<string, string>> DictDataFileScr
            = (from Match m in Regex.Matches(dataFileScr,
                                            patternFileScr,
                                            RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
               select new
               {
                   Section = m.Groups["Section"].Value,

                   kvps = (from cpKey in m.Groups["Key"].Captures.Cast().Select((a, i) => new { a.Value, i })
                           join cpValue in m.Groups["Value"].Captures.Cast().Select((b, i) => new { b.Value, i }) on cpKey.i equals cpValue.i
                           select new KeyValuePair(cpKey.Value, cpValue.Value)).OrderBy(_ => _.Key)
                           .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)

               }).ToDictionary(itm => itm.Section, itm => itm.kvps);

It works for

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

GDC 7
{
    Message = 6
    RepeatCount = 2
    ErrorMessage = 10
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
";

in other words

Section1
{
key1=value1
key2=value2
}

Section2
{
key1=value1
key2=value2
}

, but

*1. not for multiple keyname,  i want group by key and output

DictDataFileScr["GDC 7"]["Message"] = "6|7|8|8"
DictDataFileScr["GDC 7"]["ErrorMessage"] = "10|11"

*2. not work for .ini file like

....
[Section1]
key1 = value1
key2 = value2

[Section2]
key1 = value1
key2 = value2
...

*3. dont see next section after

....
PZ 11
{
IA_return()
}
.....

A: Do yourself and your sanity a favor and learn how to use GPLex and GPPG.  They are the closest thing that C# has to Lex and Yacc (or Flex and Bison, if you prefer) which are the proper tools for this job.
Regular expressions are great tools for performing robust string matching, but when you want to match structures of strings that's when you need a "grammar".  This is what a parser is for.  GPLex takes a bunch of regular expressions and generates a super-fast lexer.  GPPG takes the grammar you write and generates a super-fast parser.
Trust me, learn how to use these tools ... or any other tools like them.  You'll be glad you did.

A: Here is a complete rework of the regex in C#.
Assumptions : (tell me if one of them is false or all are false)

*

*An INI file section can only have key/value pair lines in its body

*In an non INI file section, function calls can't have any parameters

Regex flags :
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.Singleline

Input test:

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

PZ 11
{
IA_return()
}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}

[Section1]
key1 = value1
key2 = value2

[Section2]
key1 = value1
key2 = value2
";

Reworked regex:

const string patternFileScr = @"
(?<Section>                                                              (?# Start of a non ini file section)
  (?<SectionName>[\w ]+)\s*                                              (?# Capture section name)
     {                                                                   (?# Match but don't capture beginning of section)
        (?<SectionBody>                                                  (?# Capture section body. Section body can be empty)
         (?<SectionLine>\s*                                              (?# Capture zero or more line(s) in the section body)
         (?:                                                             (?# A line can be either a key/value pair, a comment or a function call)
            (?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]*))    (?# Capture key/value pair. Key and value are sub-captured separately)
            |
            (?<Comment>/\*.+?\*/)                                        (?# Capture comment)
            |
            (?<FunctionCall>[\w]+\(\))                                   (?# Capture function call. A function can't have parameters though)
         )\s*                                                            (?# Match but don't capture white characters)
         )*                                                              (?# Zero or more line(s), previously mentionned in comments)
        )
     }                                                                   (?# Match but don't capture beginning of section)
)
|
(?<Section>                                                              (?# Start of an ini file section)
  \[(?<SectionName>[\w ]+)\]                                             (?# Capture section name)
  (?<SectionBody>                                                        (?# Capture section body. Section body can be empty)
     (?<SectionLine>                                                     (?# Capture zero or more line(s) in the section body. Only key/value pair allowed.)
        \s*(?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]+))\s*  (?# Capture key/value pair. Key and value are sub-captured separately)
     )*                                                                  (?# Zero or more line(s), previously mentionned in comments)
  )
)
";

Discussion
The regex is build to match either non INI file sections (1) or INI file section  (2).
(1) Non-INI file sections These sections are composed by a section name followed by a body enclosed by { and }.
The section name con contain either letters, digits or spaces.
The section body is composed by zero or more lines. A line can be either a key/value pair (key = value), a comment (/* Here is a comment */) or a function call with no parameters (my_function()).
(2) INI file sections
These sections are composed by a section name enclosed by [ and ] followed by zero or more key/value pairs. Each pair is on one line.

A: # 2. not work for .ini file like
Won't work because as stated by your regular expression, an { is required after [Section].
Your regex will match if you have something like this :

[Section]
{
key = value
}

A: Here is a sample in Perl. Perl doesen't have named capture arrays. Probably because of backtracking.
Maybe you can pick something out of the regex though. This assumes there is no nesting of {} bracktes.
Edit Never content to leave well enough alone, a revised version is below.
use strict;
use warnings;

my $str = '
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
 /*  Description = simple
 */
}

asdfasdf

PZ 11
{
IA_return()
}

[ section 5 ]
  this = that
[ section 6 ]
  this_ = _that{hello() hhh = bbb}

TOC{}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
';

use re 'eval';

my $rx = qr/

\s*
( \[ [^\S\n]* )?                     # Grp 1  optional ini section delimeter '['
(?<Section> \w+ (?:[^\S\n]+ \w+)* )  # Grp 2  'Section'
(?(1) [^\S\n]* \] |)                 # Condition, if we matched '[' then look for ']'
\s*

(?<Body>                   # Grp 3 'Body' (for display only)
   (?(1)| \{ )                   # Condition, if we're not a ini section then look for '{'

   (?{ print "Section: '$+{Section}'\n" })  # SECTION debug print, remove in production

   (?:                           # _grp_
       \s*                           # whitespace
       (?:                              # _grp_
            \/\* .*? \*\/                    # some comments
          |                               # OR ..
                                             # Grp 4 'Key'  (tested with print, Perl doesen't have named capture arrays)
            (?<Key> \w[\w\[\]]* (?:[^\S\n]+ [\w\[\]]+)* )
            [^\S\n]* = [^\S\n]*              # =
            (?<Value> [^\n]* )               # Grp 5 'Value' (tested with print)

            (?{ print "  k\/v: '$+{Key}' = '$+{Value}'\n" })  # KEY,VALUE debug print, remove in production
          |                               # OR ..
            (?(1)| [^{}\n]* )                # any chars except newline and [{}] on the condition we're not a ini section
        )                               # _grpend_
        \s*                          # whitespace
    )*                           # _grpend_  do 0 or more times
   (?(1)| \} )                   # Condition, if we're not a ini section then look for '}'
)
/x;

while ($str =~ /$rx/xsg)
{
    print "\n";
    print "Body:\n'$+{Body}'\n";
    print "=========================================\n";
}

__END__

Output
Section: 'Start 0'
  k/v: 'Next' = '1'
  k/v: 'Author' = 'rk'
  k/v: 'Date' = '2011-03-10'

Body:
'{
    Next = 1
    Author = rk
    Date = 2011-03-10
 /*  Description = simple
 */
}'
=========================================
Section: 'PZ 11'

Body:
'{
IA_return()
}'
=========================================
Section: 'section 5'
  k/v: 'this' = 'that'

Body:
'this = that
'
=========================================
Section: 'section 6'
  k/v: 'this_' = '_that{hello() hhh = bbb}'

Body:
'this_ = _that{hello() hhh = bbb}

'
=========================================
Section: 'TOC'

Body:
'{}'
=========================================
Section: 'GDC 7'
  k/v: 'Message' = '6'
  k/v: 'Message' = '7'
  k/v: 'Message' = '8'
  k/v: 'Message' = '8'
  k/v: 'RepeatCount' = '2'
  k/v: 'ErrorMessage' = '10'
  k/v: 'ErrorMessage' = '11'
  k/v: 'onKey[5]' = '6'
  k/v: 'onKey[6]' = '4'
  k/v: 'onKey[9]' = '11'

Body:
'{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}'
=========================================


Q: How to update element at the arraylist on Android I had used arraylist to recycleview like this :
product.add(new InfoProduct(R.drawable.cloth, Product_title, "0", Product_data2, lunch));

I want to overwrite R.drawable.cloth when I click it , how can I do ?!

A: productList.get(0).setDrawableId(R.drawable.new_cloth_id); Type any position what you want instead of '0'. And then notify adapter.

A: Please make model(get/set) class of InfoProduct and in onClick of item you'll get the position. On that position you can set drawable to different drawable.


Q: I'm simply trying to create a file in python3, but the standard answers are not working Simple task with answers all over the web. I just can't get any of them to work. When I run the code below on macOS, I get the following error messages:
open error: [Errno 1] Operation not permitted: 'test_60'
Path error: [Errno 1] Operation not permitted: 'test_60'
mknod error: [Errno 1] Operation not permitted
The complete test program follows. What stupid thing am I doing wrong?
#!/usr/local/bin/python3
from pathlib import Path
import os

db_file = "test_60"
#
try:
    open(db_file, 'a').close()
except OSError as e:
    print('open error:', e)
try:
    Path(db_file).touch()
except OSError as e1:
    print('Path error:', e1)

try:
    os.mknod(db_file)
except OSError as e2:
    print('mknod error:', e2)


Q: ngInfiniteScroll handler not firing with specific CSS & div structure I've purchased an Angular template to build a web app and I'm struggling to get the scroll event handler to fire using ngInfiniteScroll v1.2.0 (NOTE: the handler does fire once if I set infinte-scoll-immediate-check to true) . I've reproduced the issue by building the same div structure and CSS that came with the template using jsFiddle:
jsFiddle link
This is the structure that I have to work within because of the template:

And this is the CSS that is being used by each of the divs:
.padding {
    padding: 32px 32px;
}
.box .box-inner {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
.box .box-row .box-cell {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}
.box .box-row {
    display: table-row;
    height: 100%;
}
.box {
    display: table;
    width: 100%;
    height: 100%;
    border-spacing: 0;
    table-layout: fixed;
}
.app-content {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    overflow-y: auto;
}

If I comment out the five surrounding divs, everything works fine. I'm not a CSS guy so this "table structure" that is being used is causing me some problems. Any help would be appreciated!


Q: Make a DIV cover entire page, but WITHOUT using CSS position I want to make a div with a background-color of red to cover my entire page, but I do not want to use CSS position: absolute. Here is my example with CSS position:

CSS position works for the most part, but then I am unable to create more than one of these divs (they overlap or cancel each other out because of top: 0 and left: 0). When you scroll down, I want you to see additional divs.
It would really help if there was a pure CSS solution, but JavaScript and HTML are open to me as well. JUST NO JQUERY.

A: What about using viewport height and viewport width?
I've created an example in this JSFiddle.

body, html {
    margin: 0;
    padding: 0;
}

div {
    width: 100vw;
    height: 100vh;
}

.one {
    background-color: blue;
}

.two {
    background-color: green;
}

.three {
    background-color: yellow;
}

A: If you want to make div to occupy entire space use vw and vh
because making div alone height:100% and width:100% would not do it
without using viewport units
check this snippet

div{
 width: 100%;
  height:100%;
  background:red;

}

html,body{
  height:100%;
   width:100%;
  }

but making html and body to have height and width is a bad idea
so to skip it use view port units
check this with viewport unist

div {
  width: 100vw;
  height: 100vh;
  background: red;
}

Hope it helps

A: Older browsers such as IE7 and 8 could be supported without using visual height and width units by using a single absolutely positioned container with inner divs inheriting height and width property values.
CSS
body {
   margin: 0px;  /* optional */
}
#box {
   position:absolute;
   height: 100%;
   min-width: 100%;
}
.page {
   padding: 5px; /* optional */
   height: inherit;
}

HTML

25em

2

3

Update: the width property of the container has been replaced by a min-width property, introduced in IE7, to fix an ugly horizontal scrolling issue. Supplying width for inner div elements was removed as being unnecessary.

A: Simply change the top: value for each one. The first one would be 0, the second 100%, the third 200%, and so on. Here's a working example:


Q: Error: error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found I have both VS 2012 and 2013 installed in my computer and for some projects need 2012 version. using msbulid in shell command I have the following error:
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Platform.targets(44,5): error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found

Would you please let me know how could I change msbuild option to use VS 2013?
Please Do not ask me to uninstall the VS 2012 version, because it is crucial for some other projects.


Q: Workaround for piping to an if-statement in powershell? I wanted to pipe an object to a PowerShell if-statement, but it doesn't work:
for($i = 1; $i -le 70; $i++) {
    Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | if ($_.ProvisioningState -eq 'Succeeded') {
    Remove-AzureRmRedisCache $_ -Force
}}

"The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program". So what should I do instead?

A: you need to do something like this:
Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | where { $_.ProvisioningState -eq 'Succeeded' } |
    Remove-AzureRmRedisCache -Force

You filter with Where-Object.
Alternatively you can do:
$cache = Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101"
if ( $cache.ProvisioningState -eq 'Succeeded' ) { do stuff }

or this (UGLY):
if ( (Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101").ProvisioningState -eq 'Succeeded' ) { do stuff }


Q: Jest: How to test get descriptor of Object I'm trying to test object and return his descriptors using jest. In my case the object contains get function. I believe my syntax is wrong here:
get: function number() {
    return this.x;
},

Any ideas how to fix it?
Here the example:
let obj = {
    x: 10,
    get number() {
        return this.x;
    },
};

test('Return property descriptors of obj', () => {
    expect(Object.getOwnPropertyDescriptors(obj)).toMatchObject({
        x: {
            value: 10,
            writable: true,
            enumerable: true,
            configurable: true
        },
        number: {
            get: function number() {
                return this.x;
            },
            set: undefined,
            enumerable: true,
            configurable: true
        }
    });
});

And result:

A: The assertion fails because get: function number() {...} isn't the same function as in the descriptor, function number() {} !== function number() {}.
It should be asserted to be any function with:
    ...
    number: {
        get: expect.any(Function),
        set: undefined,
        enumerable: true,
        configurable: true
    }
    ...


Q: Undefined class OneSignal I use Laravel 5.2 and want to use berkayk/laravel-onesignal package, and I installed this package step by step according to Guide on github.
But when I want to use this package I get "Undefined class OneSignal", also I run this artisan command in the terminal:
php artisan config:clear
php artisan config:cache

I try this code in controller
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use OneSignal;
use App\Http\Requests;

class SignalController extends Controller
{

    public function index()
    {
        OneSignal::sendNotificationToAll("Some Message");
    }
}

I get this error

A: You should use full namespace for the facade:
\OneSignal::sendNotificationToAll("Some Message");

Or add this to the top of your class:
use OneSignal;

A: You should write use OneSignal top of the class underneath the namespace.
Hope this work for you!


Q: Not receiving emails, but Mailgun shows 100% delivery rate I'm using a CMS to send emails when a form is submitted. Its configured to use smtp.mailgun.org:587 with the username postmaster@domain.com. I'm using Google Apps for my email, so in this case the email account I'm receiving emails at is support@domain.com. Customers fill out a form and enter their email address is used as the "from" address and the "to" address is support@domain.com. I don't see anything in my Junk folder in Gmail. Mailgun is getting all the emails and marking them as sent/received, but I simply am not getting the emails in Gmail, thus not getting support emails from my customers. What gives?

A: Issue was I had mxa.mailgun.org and mxb.mailgun.org added in my MX Records on my host (Linode). Removing those records fixed the issue.


Q: Mos amplifier numerical
Can anyone please explain how do I get this variation of Ix vs Vx curve?How do I determine whether the current will be in positive region or negetive?

A: Using KCL in the output node, you find that
$$I_X = i_{DS1} - i_{DS2}$$
(I'm using positive quantities for the PMOS here).
You can see that the current is negative if \$i_{DS1} < i_{DS2}\$. Otherwise, the current is positive. When is this the case?
For small \$V_X\$, M1 will not conduct a lot of current because of the small \$v_{DS}\$ applied. If \$V_X < v_{GS1} - V_{TH1}\$ then M1 is in the triode region.
For large \$V_X\$ we have the same situation for M2. It is in the triode region.
If \$V_{DD}\$ is large enough for one or both of the transistors to go into saturation, then the situation can change a little bit.

*

*M1 in saturation, M2 in triode
M1 will behave like a current source, while M2 can be better approximated by a resistor. So the slope will be somewhat linear, but M1 will add a relatively constant current to \$I_X\$.

*M1 in triode, M1 in saturation
The situation is identical, but the slope will be somewhat linear while M2 will subtract a constant current.

*M1 and M2 are both in saturation
Both transistors act more or less like a current source, so the net current \$I_X\$ will be pretty much constant. However, because both transistor currents are slightly dependent on \$v_{DS}\$ (ie. output impedance), \$I_X\$ will not be perfectly constant.


Q: How can I read another program's STDOUT from a Ruby program line by line? I have a small test Ruby program called "count", which counts 1..50.
#!/usr/bin/ruby
#count
for i in 1..50 do
 STDOUT.puts i
 sleep 1
end

I want to call it from another program, and read the outputted numbers line by line, and output them from the other program, line by line.
However my construction doesn't work:
IO.popen("count","r+") {|f| puts f.readline}

What should I do to make it work? Maybe some modification in the test program "count"?

A: If you have some patience (about 50s worth), you'll see that you do get one line of output and that line will be "1\n". You have two problems:

*

*count is using buffered output. This means that nothing will show up in your stdin until count's output buffer is full; given the small number of bytes that you're printing, the buffer won't be flushed until count finishes.

*Your popen block is only looking for one line.

You can solve the first one by using STDOUT.sync = true to turn off the output buffering in count:
STDOUT.sync = true
for i in 1..50 do
  STDOUT.puts i
  sleep 1
end

Then in your popen, you can iterate over the lines using each:
IO.popen("count","r+") { |fp| fp.each { |line| puts line } }

Then you should one line of output showing up each second.


Q: How to modify selectWithKeyChar()'s function in JComboBox.java? I have a combo box that contains items that start with special characters (ie. À).
Currently, when using the combo box, if you press a key (ie. "a"), it selects an item that starts with the same first letter - but it wouldn't select the one that starts with the special character..
Is there a way to modify the method selectWithKeyChar() in JComboBox.java to ignore the special characters and and treat it like a regular character?
Solutions I have thought of but don't know how to implement:
1) Passing in a temporary combo box model to selectWithKeyChar() that doesn't include the accents. If this is possible, how do you pass in the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run instead of the one that already exists in JComboBox.java?
Here is a minimal example of my setup:

*

*create a new project

*create a new file that has a JPanel form file type

*add a combo box with the following items: "Àpplebee", "Test", "Able"

*call the JPanel in the main:

   SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(new B());
            frame.pack();
            frame.setVisible(true);
        }
    });

A:
1) Passing in a temporary combo box model to selectWithKeyChar() that
  doesn't include the accents. If this is possible, how do you pass in
  the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run
  instead of the one that already exists in JComboBox.java?

All of this are possible, You can create a temp ComoBoxModel and you extends JComboBox to override selectWithKeyCharacter on your CustomComboBox. Here is the sample of a code:
CustomComboBox.java
public class CustomComboBox extends JComboBox<String>{

private static final long serialVersionUID = 1L;

public CustomComboBox(String[] items) {
    super(items);
}

@Override
public boolean selectWithKeyChar(char keyChar) {
    int index;

    ComboBoxModel<String> tempModel = getModel(); // Put the model on temp variable for saving it for later use.

    String[] itemsArr = new String[getModel().getSize()];
    for(int i = 0; i < getModel().getSize(); i++) {
        // This will normalizes the Strings
        String normalize = Normalizer.normalize(getModel().getElementAt(i), Normalizer.Form.NFD);
        normalize = normalize.replaceAll("\\p{M}", "");
        itemsArr[i] = normalize;
    }

    if ( keySelectionManager == null )
        keySelectionManager = createDefaultKeySelectionManager();

    setModel(new DefaultComboBoxModel<String>(itemsArr)); // Set the Temporary items to be checked.
    index = keySelectionManager.selectionForKey(keyChar,getModel());
    setModel(tempModel); // Set back the original items.

    System.out.println(index);
    if ( index != -1 ) {
        setSelectedIndex(index);
        return true;
    }
    else
        return false;
}
}

If you will test it, even if you enter a normal char 'a', it will select the element in JComboBox with accent or with non-accent.
TestMain.java
public class TestMain {
public static void main(String[] args) {
    String[] lists = {"ápa","Zabra","Prime"};
    CustomComboBox combo = new CustomComboBox(lists);
    System.out.println(combo.selectWithKeyChar('A'));

    JFrame frame = new JFrame("Sample");
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setVisible(true);
    combo.setSize(70, 30);
    combo.setLocation(100, 100);
    frame.add(combo);
}
}


Q: Ruby gem mechanize throwing an error : undefined method `<=>' I am using the Ruby gem mechanize to scrape some html... When I load my page and display the necessary results, the page laods fine. After a reload, I get this error when doing "search_results = @agent.submit(search_form)":
undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem

Before I post any code, just does this ring any bells?
Thanks.
Code:
    start = Time.now

    # initial set up
    @agent = Mechanize.new
    Mechanize.html_parser = Hpricot
    page = @agent.get("http://www.google.com/")
    search_form = page.forms.first

    # conduct initial search
    @search_term = search_form.q = params[:search].to_s
    search_results = @agent.submit(search_form)

    # helper variables
    search_qs = ""; @page_number = 1; i = 0; @flag = false;

    # get the query string structure
    search_results.links.each { |li| search_qs = li.href if li.href.match(/.*search\?q=.*start=.*/) }

    # search through all paginated pages
    while (i < 500)
      search_qs = search_qs.gsub(/start=\d+/,"start=#{i}")
      @search_url = "http://google.com#{search_qs}"
      search_results = @agent.get(@search_url)
      search_results.links.each { |li| @flag = true if li.text.match("All Bout Texas Tailgating") }
      break if @flag
      i+=10; @page_number+=1
    end

@execution_time = Time.now-start

render :layout => false

VIEW:

Query results for "<%= @search_term %>" on Google

<% if @flag %>

What page is this keyword found: <%= @page_number %>

<%= link_to  "Click to see page", "#{@search_url}", {:target => "_blank"} %>

How long did this query take to run?: <%= @execution_time %> seconds

<% else %>

Keyword not found in Google search reults

<% end %>

STACK TRACE:
 NoMethodError (undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem):
  mechanize (1.0.0) lib/mechanize/form/field.rb:30:in `<=>'
  mechanize (1.0.0) lib/mechanize/form.rb:171:in `sort'
  mechanize (1.0.0) lib/mechanize/form.rb:171:in `build_query'
  mechanize (1.0.0) lib/mechanize.rb:373:in `submit'
  app/controllers/admin/importer_controller.rb:24:in `check_page_rank'
  /opt/local/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /opt/local/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /opt/local/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /opt/local/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /opt/local/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:82:in `start'

Rendered rescues/_trace (98.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (internal_server_error)

A: So if you look through the source for mechanize in form.rb - form submitting is calling a function called build_query which sorts the fields on the form.  Since sort uses the <=> operator, and it's undefined on Hpricot elements, you are getting an exception.
It seems as if mechanize was built to use Nokogiri - it may have unfixed bugs with other parsing implementations.  I did not get too deep into mechanize's source and don't want to blame anyone, but you may want to try switching to Nokogiri for this project (if possible).  It doesn't seem from this snippet as if you're relying heavily on Hpricot.  It seems strange to me that mechanize is throwing an exception on a hidden form field from Hpricot, but the stack trace is pretty clear in this regard.
Your other major option is to hop into the mechanize source and see if you can fix it yourself (or file a bug on the mechanize github and hope somebody gets to it).
Good luck.


Q: How do I assign 2 different variable to the return values from a function that return 2 values? Sorry for the very messy title. What I have is a function that returns 2 different values:
def func(name):

return value1, value2

Now I would like to assign these 2 values to variables in one line. This is what I have tried:
x,y = func(name)[0] , [1]

The x variable is assigned correctly, but the y variable is assigned just assigned as [1].
If it relevant: The [0] is an array and the [1] is a DataFrame form a .csv file.

A: You are close. It's even simpler than you think, you can extract without reference to indices:
def func(name):
    # do something
    return value1, value2

x, y = func(var)

func returns a tuple (note parentheses are not required). You can then unpack via sequence unpacking. I would advise you choose variable names that are informative.


Q: Calling a URL in jQuery I would like to call a URL. Currently I am using a hidden iFrame to call this URL:
var data = {File: file,NAME: 'file.txt'};
<iframe src="requestFile?'+ $.param(data) + '" style="display: none;" ></iframe>

Now I would like to use AJAX to call the file. The file just has to be called.
I tried it with a GET request:
$.ajax({
    'url' : 'requestFile?'+ decodeURIComponent($.param(data)),
    'type' : 'GET',
    'success' : function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });

Unfortunately this does not work. May there be a problem with the length of the URL? The file string is quite long. I do not get an error message.

A: Rather than use the decodeURIComponent($.param(data)), simply use the encode method .param as $.param(data),
decodeURIComponent does just what it says, decodes it and you want to use the encoded which $.param should do for you:  http://api.jquery.com/jquery.param/
NOTE: on that page they use the decodeURIComponent in an example so you can see the original decoded value/put it in a variable.
Reworked code (my assumption is that you DO return "success" string and not the actual file here?):
var myparam = var data = {File: file,NAME: 'file.txt'};
$.ajax({
    url: 'requestFile?' + $.param(myparam),
    type: 'GET'
}).done(function (data) {
    if (data == "success") {
        alert('request sent!');
    }
});

NOTE: You did not show how file was defined so I can only make the assumption that it is a JavaScript object somewhere.


Q: Can't build apk with the last android studio when the sdk version is changed to 4.4 I am creating a project that can run on android 4.4.
When pressing 'F4'  ( open module setting ), I see that the 'Compile sdk version is on API 23: Android 6.0 (Marshmallow)
But my cellPhone is with version 4.4.2, so I move the version back as I define when I create the project => to  API 19: Android 4.4 (KitKat)
Now, nothing works ... the IDE can't find the 'R' anywhere ... and I can't compile it.
I try to clear and rebuild the project
I try to click on the 'sync'
when i leave compile SDK at 23 and set your TARGET SDK to 19 .. the debug is not run on my cellphone.
but nothing .. not working.
Any help please ...
10x

A: Leave your compile SDK at 23, set your TARGET SDK to 19.


Q: shell command with unexpected quotes I am running a script it has:
...
echo 3:${WRITE_TIME}
WRITE_TIME_QUOTES=\"${WRITE_TIME}\"
echo 4:${WRITE_TIME_QUOTES}
${ADDR_BEELINE}/beeline ... --hivevar write_time=${WRITE_TIME_QUOTES} ;hive_status=$?

I pass the date time with spaces as argument to this script and both the 2 variables: WRITE_TIME and WRITE_TIME_QUOTES are displayed as expected:
3:2021-11-24 17:00:00
4:"2021-11-24 17:00:00"

The command is expected to be:
/home/data/hive/bin/beeline ... --hivevar write_time="2021-11-24 17:00:00"

However, the command actually executed comprises extra quotes which are not written in the script:
/home/data/hive/bin/beeline ... --hivevar 'write_time="2021-11-24' '17:00:00"'

I did not put them at all, why did they appear and how to get rid of them? Any help is appreciated.


Q: Suppress line numbers in front of 'repeat' and 'until' keywords in algorithmic Here is my minimal example:
\documentclass{article}

\usepackage{algorithm}
\usepackage{algorithmic}

\begin{document}

\begin{algorithm}
\caption{Test}
\begin{algorithmic}[1]
    \REQUIRE
    \REPEAT
    \STATE state
    \STATE state
    \STATE state
    \UNTIL condition
\end{algorithmic}
\end{algorithm}

\end{document}

I get this result:

But I would prefer this result:

How can I achive this?

A: algorithmic creates all of the necessary pseudocode macros at the start of the algorithmic environment. As such, it's not as easy to merely patch \REPEAT and/or \UNTIL in the "usual" way.
The following MWE inserts the patch after the algorithmic environment starts. The patch uses a "no step" \item in the form of \ALC@it@nostep rather than the default \ALC@it:

\documentclass{article}

\usepackage{algorithm,algorithmic}% http://ctan.org/pkg/algorithms
\usepackage{xpatch,letltxmacro}% http://ctan.org/pkg/etoolbox
\makeatletter
\newcommand{\ALC@it@nostep}{\item[]}% No-step algorithmic item
% \patchcmd{<cmd>}{<search>}{<replace>}{<success>}{<failure>}
\LetLtxMacro\oldalgorithmic\algorithmic
\LetLtxMacro\endoldalgorithmic\endalgorithmic
\renewenvironment{algorithmic}[1][0]{%
  \oldalgorithmic[#1]%
  \xpatchcmd{\REPEAT}{\ALC@it}{\ALC@it@nostep}{}{}%
  \xpatchcmd{\UNTIL}{\ALC@it}{\ALC@it@nostep}{}{}%
}{\endoldalgorithmic}
\makeatother

\begin{document}

\begin{algorithm}
\caption{Test}
\begin{algorithmic}[1]
  \REQUIRE
  \REPEAT
  \STATE state
  \STATE state
  \STATE state
  \UNTIL condition
\end{algorithmic}
\end{algorithm}

\end{document}


Q: Auto It Script Debugging I have a simple script that works on my PC but not on three others. I am running the script directly from SciTE on all the machines, including my own. Anyway, is there something I can turn on to see what's happening?
Script:
While True
WinSetOnTop("[TITLE:Production Floor Display]","", 1)
Sleep(20000)
WinSetOnTop("[TITLE:Production Floor Display]","", 0)
WinSetOnTop("[TITLE:Preview Image]","", 1)
Sleep(5000)
WinSetOnTop("[TITLE:Preview Image]","", 0)
Wend

A: No, at least not natively.
What are you trying to achieve?
Try compiling the program before doing anything else.
If that is what it looks like (something to do with an industrial camera feed), then you're better off just using Javascript, PHP, NGINX and HTML. That would also be uncomparable to your approach in terms of reliability.


Q: Knockout foreach binding inside a binding (array within an array) i have two classes; users and readings. this relates to healthcare to each user has an array of readings:
/*
 * Reading class
 * containts health readings
 */
function Reading(date,weight,glucose)
{
    var self = this;

    self.date=ko.observable(date);
    self.weight=ko.observable(weight);
    self.glucose=ko.observable(glucose);

      self.formattedWeight = ko.computed(function(){
        var formatted = self.weight();

        return formatted+" lb"
    });
}

/*
 * User class
 * contains a user name, date, and an array or readings
 */
function User(name,date,readings) {
    var self = this;

    self.name = name;
    self.date = date;
    self.readingsArray = ko.observableArray([
        new Reading(99,99)
    ]);
}

i know how to use a foreach binding to display the information for a reading or a user. but im not sure how to show the readings inside of a user?
is there a way to use a nested foreach binding or a with binding? here is my html:

Users ()

        User name	Date

        <input data-bind="value: name" />
        <input data-bind="value: date" />

        Remove

<button data-bind="click: addUser">Add User</button>

Readings ()

       Date	Weight	Glucose

and here is my model if anyone is interested. any help would be greatly appreciated! Thanks in advance!
// Overall viewmodel for this screen, along with initial state
function userHealthModel() {
    var self = this;
    self.inputWeight = ko.observable();
    self.inputDate = ko.observable();
    self.inputId = ko.observable();
    self.inputGlucose = ko.observable();

    // Operations
    self.addUser = function(){
        self.users.push(new User("",0,0,(new Reading(0,0))));
    }
    //adds a readings to the edittable array of readings (not yet the reading array in a user)
    self.addReading = function(){
        var date = self.inputDate();
        var weight = self.inputWeight();
        var glucose = self.inputGlucose();
        if((weight&&date)||(glucose&&date))
        {
            self.readings.push(new Reading(date,weight,glucose));
        }
        else{
            alert("Please complete the form!")
        }
    }

    self.removeUser = function(userName){self.users.remove(userName)}

    //editable data
     self.readings = ko.observableArray([
        new Reading(12,99,3),new Reading(22,33,2),
        new Reading(44,55,3)
    ]);

      self.users = ko.observableArray([
        new User("George",2012),
        new User("Bindu",2012)
    ]);

}

ko.applyBindings(new userHealthModel());

A: I'm not sure how you want the Readings rendered, but here is an example:
http://jsfiddle.net/jearles/aZnzg/
You can simply use another foreach to start a new binding context, and then render the properties as you wish.


Q: How To Enter Words Into This Program? He told me to put any words into this program and I can see one transform to the other, but I have no idea where to insert the words I want. I downloaded CodeBlocks because it looked like the best C++ runner according to Google but when I click run it just says I need two strings. Guessing that means words.
Can anyone look at this and tell me how to insert 2 words?
The Program:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

#define MIN(X,Y) ((X <= Y) ? X:Y)
#define MIN3(A,B,C) ((A <= MIN(B,C)) ? A : MIN(B,C))

class EDIST {
private:
  string _s1, _s2;
  int _edit_distance;

  enum backtrace_pointer { L, D, U };
  // L==left, D==diagonal, U==up.

  vector<vector<int> > dp_table;
  vector<vector<int> > backtrace;

public:
  EDIST(const char *a, const char *b) {
    _s1 = a;
    _s2 = b;
    _edit_distance = 0;
  }

  void run();

private:
  int edit_distance() const { return _edit_distance; }
  void dp_edit_distance();
  void print_dp_tables();
  void init_dp_tables();
  void print_solution();
};

void EDIST :: print_dp_tables()
{
  cout << "\nPrinting dynamic programming table\n";

  cout << "\t_";
  for ( int i=0; i < _s2.size(); i++ )
    cout << "\t" << _s2[i];
  cout << endl;

  for ( int i=0; i <= _s1.size(); i++ ) {
    if ( i ) cout << _s1[i-1];
    else cout << "_";

    for ( int j=0; j <= _s2.size(); j++ )
      cout << "\t" << dp_table[i][j];
    cout << endl;
  }

  cout << "\nPrinting backtrace table\n";

  cout << "\t_";
  for ( int i=0; i < _s2.size(); i++ )
    cout << "\t" << _s2[i];
  cout << endl;

  for ( int i=0; i <= _s1.size(); i++ ) {
    if ( i ) cout << _s1[i-1];
    else cout << "_";

    for ( int j=0; j <= _s2.size(); j++ ) {
      cout << "\t";
      if ( backtrace[i][j] == L ) cout << "L";
      else if ( backtrace[i][j] == D ) cout << "D";
      else cout << "U";
    }
    cout << endl;
  }
}

void EDIST :: init_dp_tables()
{
  for ( int i=0; i <= _s1.size(); i++ ) {
    vector <int> v;
    vector<int> b;

    for ( int j=0; j <= _s2.size(); j++ ) {
      int n=0, op=0;;

      if ( !i ) { n=j; op=L; }
      else if ( !j ) { n=i; op=U; }
      else { n=0; op=D; }

      v.push_back(n);
      b.push_back(op);
    }

    dp_table.push_back(v);
    backtrace.push_back(b);
  }

  for ( int i=0; i <= _s1.size(); i++ )
    dp_table[i][0] = i;

  for ( int j=0; j <= _s2.size(); j++ )
    dp_table[0][j] = j;
}

void EDIST :: dp_edit_distance()
{
  for ( int j=1; j <= _s2.size(); j++ ) {

    for ( int i=1; i <= _s1.size(); i++ ) {

      int a = dp_table[i-1][j]+1;
      int b = dp_table[i-1][j-1];
      int c = dp_table[i][j-1]+1;

      if ( _s1[i-1] != _s2[j-1] )
    b++;

      dp_table[i][j] = MIN3(a,b,c);

      if ( a == dp_table[i][j] ) backtrace[i][j] = U;
      else if ( b == dp_table[i][j] ) backtrace[i][j] = D;
      else backtrace[i][j] = L;
    }
  }
}

void EDIST :: print_solution()
{
  vector<string> string_sequence;
  string_sequence.push_back(_s2);

  int i = _s1.size();
  int j = _s2.size();

  while ( i || j ) {

    string s = string_sequence[string_sequence.size()-1];

    bool add_string=true;
    int new_i=i, new_j=j;

    if ( backtrace[i][j] == L ) {//LEFT :: insert
      new_j--;
      s.erase(j-1,1);
    }
    else if ( backtrace[i][j] == U ) {//UP : delete
      new_i--;
      string sub1 = (j >= 1 ? s.substr(0,j) : "");
      string sub2 = (j < s.size() ? s.substr(j) : "");
      s = sub1 + _s1[i-1] + sub2;
    }
    else {//DIAGONAL : replace OR no-operation
      new_i--;
      new_j--;
      if ( i && j && dp_table[i][j] != dp_table[new_i][new_j] )
    s.replace(j-1,1,_s1.substr(i-1,1));
      else
    add_string = false;
    }

    if ( add_string ) {
      string_sequence.push_back(s);
      _edit_distance++;
    }

    i = new_i;
    j = new_j;
  }

  cout << "\nEdit distance : " << edit_distance() << endl;

  if ( string_sequence.size() )
    cout << "\nPrinting mutations : \n";

  for ( int i=string_sequence.size()-1; i >= 0; i-- )
    cout << "\t" << string_sequence[i] << endl;

}

void EDIST :: run()
{
  cout << "\nFinding edit-distance between strings `";
  cout << _s1 << "' and `" << _s2 << "'" << endl;

  init_dp_tables();
  dp_edit_distance();
  print_dp_tables();
  print_solution();
}

int main(int argc, char *argv[])
{
  if ( argc != 3 ) {
    cerr << "Need 2 strings as input!\n" << endl;
    exit(1);
  }

  EDIST e(argv[1], argv[2]);
  e.run();

  return 0;
}

A: When you downloaded the program you probably got a .exe file, you need to execute this program with two command line arguments like so:
programname.exe word1 word2

If your friend didn't give you a executable file you need to compile the source into an executable. CodeBlocks provides this functionality and automatically runs the compiled result. Unfortunately it doesn't pass any arguments to the result which is why the program is telling you that it needs two words. (CodeBlocks is just executing programname.exe)
One solution to this problem is to configure code blocks to provide the arguments. As danben pointed out you can use the "Set program arguments" option in the "Project" menu to configure it to provide arguments. If you set your program arguments as word1 word2 then CodeBlocks will execute programname.exe word1 word2 which is what you want.
If you want to run this program elsewhere you need to compile it. Luckily whenever you click "run" in CodeBlocks it actually does compile an executable somewhere, typically in the project folder under bin\debug or bin\release you'll find a exectuable file. You can use this file as outlined above.

A: This is a question about CodeBlocks rather than about C++, but a quick Google search reveals that you need to select the "Set program arguments" option under the "Project" menu.


Q: EC2 Instance not available in ECS I have created an EC2 instance via Terraform with the following configuration:

*

*EC2 instance is using the latest Amazon ECS-Optimized Amazon Linux 2 AMI.

*Instance is sitting in a private subnet, with a route to a NAT GW. Tested internet connectivity fine.

*SG rules are configured correctly.

*EC2 Instance profile is using AmazonEC2ContainerServiceforEC2Role

*EC2 user-data is configured (with my cluster name) with:
echo ECS_CLUSTER=my-cluster-name >> /etc/ecs/ecs.config
When I go to my ecs-cluster, no instances show in the EC2 Instance section of the console.
Is there anything else I'm missing as to why this cluster can't register with the EC2 instance?


Q: Simfony2-Twig: Render only a single part of a template I have a homepage wich dynamically loads a bunch of "posts" (similar to facebook wall).
There is the option to follow a post, but when someone clicks on the follow button, which has a counter on following people, I need to reload all the homepage to update this value. How can I update just the part corresponding to the post? Actually the post is in an extern hmtl.twig file which I render from the homepage code:

         {% for sueno in suenos %}
            {% if loop.index0 is even %}
                {{ render(controller('SuenoBundle:Default:suenoFrontend', { 'sueno': sueno } )) }}
            {% endif %}
         {% endfor %}

This is the controller:
public function suenoFrontendAction($sueno)
{
        return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
        'sueno' => $sueno));
}

This the post html file:

{{ sueno.usuario.nombre ~ ' ' ~ sueno.usuario.apellido }}

                  {% if sueno.necesitaAyuda == 1 %}

                  {% endif %}
                  {% if sueno.rol == 'foto' %}

                  {% elseif sueno.rol == 'video' %}

                  {% endif %}

{{ sueno.titulo }}

{{ sueno.quePido }}

{{ sueno.texto }}

                            {% set size = sueno.usuariosColaboradores | length %}
                            {% set size2 = sueno.usuariosSeguidores | length %}

                             {{ size }}

                             {{ size2 }}

Here you can see the action correpsonding to follow a post(its in the previous code, I remark the line):
 {{ size2 }}

size2 value is the one to update. the controller called when clicking here is this(and where I suppose the failure is):
    public function seguirAction($suenoid)
{

    $em = $this->getDoctrine()->getManager();

    $usuario = $this->getUser();

    $sueno = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array('id' => $suenoid));

    $usuario->getSuenosSigue()->add($sueno);
    $em->persist($usuario);
    $em->flush();

  // $suenos = $em->getRepository('SuenoBundle:Sueno')->findBy(array('usuario' => $usuario->getId()));

    //esto hay que cambiarlo entero para conseguir los sueños apropiados
        //return $this->render('EstructuraBundle:Home:home.html.twig', array('suenos'=> $suenos , 'usuario' => $usuario));
                return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
        'sueno' => $sueno));
}

The thing is that when this render happens, the post fills the full page.
What I want is just to re-render this post in the homepage


Q: How to validate the Content-MD5 header (from the actual content) in a RequestInterceptor (WCF REST Starter Kit) - REST web service I'm implementing REST web services by means of the WCF REST Starter Kit.
I get the request in a System.ServiceModel.Channels.RequestContext.
Specifically: the interceptor starts this way: Public Overrides Sub ProcessRequest(ByRef requestContext As RequestContext)
If the request includes the Content-MD5 header, I must validate the provided hash against the actual content body, right? Because this does not happen 'automatically'. Nobody (IIS, or whoever) is verifying this for me, as I first thought it would happen.
I thought doing this content verification would be easy. I just have to get the request body as a string and compare the result of my GenerateChecksumForContent() with the hash included in the header.
How to compute the MD5 from the content:
Public Shared Function GenerateChecksumForContent(ByVal content As String) As String
    ' Convert the input string to a byte array and compute the hash.
    Dim hashed As Byte() = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(content))
    ' Convert the hash to a Base64 Encoded string and return it
    Return Convert.ToBase64String(hashed)
End Function

How to get the Content-MD5 request Header value:
Dim message As Message = requestContext.RequestMessage
Dim reqProp As HttpRequestMessageProperty = DirectCast(message.Properties(HttpRequestMessageProperty.Name), HttpRequestMessageProperty)
Dim contentMD5HeaderValue As String = reqProp.Headers("Content-MD5")

My problem is that I don't know how to do something so apparently simple as compute the Content-MD5 of the request's body.
I could not find any built-in property telling me this information (the content's MD5 current hash value).
I've tried this, but it does not work:
Dim content As String = requestContext.RequestMessage.GetBody(Of String)()
Dim computedMD5 As String = GenerateChecksumForContent(content)

In addition, what would happen after the RequestInterceptor run and the 'real' method process the content? The content would be lost because it was already read?
Should I in addition do something like ".CreateBufferedCopy()" to keep the request body available for the post-RequestInterceptor processing?
I cannot understand why this is so complicated! It should be something trivial, but as you can see, I'm completely lost.
Please someone, help me...
Many thanks,
Horacio.-

A: Here are two MSDN pages that give an answer to your question:

*

*http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx

*http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx
Hopefully one of them will be sufficient.


Q: I have a question regarding the proper usage of the word "nor" Is "...not legal advice, nor is it intended to be" the proper usage of "nor" in the prior partial statement?

A: There is nothing wrong with the fragment.  Usually we would see:
This is not legal advice and it is not intended to be.
and in this case using neither is a bit awkward.


Q: Connected with Open V Switch, connection issue between Docker container and other machines I'm using open vSwitch(with DPDK) for communicating my machines. I have 2 physical PC. Nginx is working on one of them and its ip=10.10.10.6/24. Open vSwitch and Docker is working on the other machine. I create a bridge via this command:
ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev

And I add one port to physical port via this command which is using DPDK driver and connected to the Ngnix machine with a cable:
ovs-vsctl add-port br0 dpdk0 -- set Interface dpdk0 \
        type=dpdk options:dpdk-devargs=0000:05:00.1

And assign an IP to the br0:
ifconfig br0 10.10.10.11 netmask 255.255.255.0 up

After this I create a container using my image:
Dockerfile:
FROM ubuntu:latest
MAINTAINER Zekeriya Akgul

RUN apt-get update -y && \
    apt-get upgrade -y && \
    apt-get install -y apache2 iputils-ping iputils-tracepath iproute2 net-tools wget

EXPOSE 80 443 444

And run the container using following command:
docker run --rm -P -it --cap-add NET_ADMIN --name ubuntu1 zkryakgul/ubuntu /bin/bash

After this I assign a port to the container using the following command:
ovs-docker add-port br0 eth1 ubuntu1 --ipaddress=10.10.10.12/24

After all of this steps my nginx machine pinging the container and container pinging nginx.
But when I try to wget 10.10.10.6:80, the container cannot connect. But on the other hand, my physical machine(ip:10.10.10.11) can do. When I run the same command (wget) it gets the page from 10.10.10.6:80.
What am I doing wrong?

A: I finally catch the problem.The problem is tcp offloading on the docker container.When i close the tcp offloading via this command:
ethtool -K eth6 tx off rx off

Everything works fine.


Q: In a json embedded YAML file - replace only json values using Python I have a YAML file as follows:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {
    "ip" : "1.1.1.1",
    "login" : "fad-login",
    "vip" : "1.1.1.1",
    "interface" : "port1",
    "port" : "443"
  }

I am trying to read this data from a file, only replace the values of ip and vip and write it back to the file.
What I tried is:
open ("test.yaml", w) as f:
    yaml.dump(object, f) #this does not help me since it converts the entire file to YAML

also json.dump() does not work too as it converts entire file to JSON. It needs to be the same format but the values need to be updated. How can I do so?

A: What you have is not YAML with embedded JSON, it is YAML with some the value for annotations being
in YAML flow style (which is a superset of JSON and thus closely resembles it).
This would be
YAML with embedded JSON:
api: v1
hostname: abc
metadata:
  name: test
  annotations: |
    {
      "ip" : "1.1.1.1",
      "login" : "fad-login",
      "vip" : "1.1.1.1",
      "interface" : "port1",
      "port" : "443"
    }

Here the value for annotations is a string that you can hand to a JSON parser.
You can just load the file, modify it and dump. This will change the layout
of the flow-style part, but that will not influence any following parsers:
import sys
import ruamel.yaml

file_in = Path('input.yaml')

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 1024
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout)

which gives:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {"ip": "4.3.2.1", "login": "fad-login", "vip": "1.2.3.4", "interface": "port1", "port": "443"}

The type(annotations['vip'])() establishes that the replacement string in the output has the same
quotes as the original.
ruamel.yaml currently doesn't preserve newlines in a flow style mapping/sequence.
If this has to go back into some repository with minimal chances, you can do:
import sys
import ruamel.yaml

file_in = Path('input.yaml')

def rewrite_closing_curly_brace(s):
    res = []
    for line in s.splitlines():
        if line and line[-1] == '}':
            res.append(line[:-1])
            idx = 0
            while line[idx] == ' ':
                idx += 1
            res.append(' ' * (idx - 2) + '}')
            continue
        res.append(line)
    return '\n'.join(res) + '\n'

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 15
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout, transform=rewrite_closing_curly_brace)

which gives:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {
    "ip": "4.3.2.1",
    "login": "fad-login",
    "vip": "1.2.3.4",
    "interface": "port1",
    "port": "443"
  }

Here the 15 for width is of course highly dependent on your file and might influence other lines if they
were longer. In that case you could leave that out, and make the wrapping
that rewrite_closing_curly_brace() does split and indent the whole flow style part.
Please note that your original, and the transformed output are, invalid YAML,
that is accepted by ruamel.yaml for backward compatibility. According to the YAML
specification the closing curly brace should be indented more than the start of annotation


Q: issue with fx scene builder Hey I got this error when trying to start my fx application. I'm using icons which I believe are part of an external jar (com.gluonhq.charm.glisten.control). So I downloaded the jar and put it in referenced libraries, nothing happened. Then added it as an external annotation to the fx library. Didn't solve the problem. Any idea's?

javafx.fxml.LoadException:  /C:/Users/Gebruiker/eclipse-workspace/Pyxus/bin/application/Layout.fxml

at
  javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2863)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2707)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2676)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2542)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)    at
  application.Main.start(Main.java:18)  at
  javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
    at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native
  Method)   at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at
  javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at
  javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
  Method)   at
  javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    at java.base/java.lang.Thread.run(Thread.java:844) Caused by:
  java.lang.ClassNotFoundException:
  com.gluonhq.charm.glisten.control.Icon    at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2931)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2920)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2861)
    ... 15 more


Q: Force couchdb to reference attachments instead of duplicate in new revision I have a problem with attachments in couchdb.
Let's say I have a document with a big attachment (100 MB). It means that each time you're modifying the document (not the attachment, just one field of the document), it will duplicate the 100 MB attachment.
Is it possible to force couchdb to create references of attachments when they are not modified (couchdb can easily verify if the attachment has been modified with the MD5)?
Edit:
According to this it should be able to do it but how? Mine (personal install) doesn't do it by default!

A: Normally, what you expect to find is the default behaviour of CouchDB. I think it could depend on how the API is used however. For example, following sample scenario works fine (on CouchDB 1.5)
All commands are given in bash syntax, so you can reproduce easily (just make sure to use correct document id and revision numbers).
Create 10M sample file for upload
dd if=/dev/urandom of=attach.dat bs=1024 count=10240
Create test DB
curl -X PUT http://127.0.0.1:5984/attachtest
Database expected data_size is about few bytes at this point. You can query it as follows, and look for data_size attribute.
curl -X GET http://127.0.0.1:5984/attachtest
which gives in my test:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":2,"purge_seq":0,"compact_running":false,"disk_size":8287,"data_size":407,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":2}
Create sample document
curl -X POST -d '{"hello": "world"}' -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest
This command gives an output with document id and revision, which are then should be used hereafter
Now, attach sample file to the document; command should use id and revision as logged in the output of the previous one:
curl -X PUT --data-binary @attach.dat -H "Content-Type: application/octet-stream" http://127.0.0.1:5984/attachtest/DOCUMENT-ID/attachment\?rev\=DOCUMENT-REVISION-1
Last command output denotes that revision 2 have been created, so the document was updated indeed. One can check the database size now, which should be around 10000000 (10M). Again, looking for data_size in the following command's output:
curl -X GET http://127.0.0.1:5984/attachtest
Now, geting the document back from DB. It will be used then to update it. Important to have in it:

*

*the _rev in the document, to be able to update it

*attachment stub, to denote that attachment should not be deleted, but kept intact

curl -o document.json -X GET http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Update document content, not changing the attachment itself (keeping the stub there). Here this will simply change one attribute value.
sed -i 's/world/there/' document.json
and update document in the DB
curl -X PUT -d @document.json -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Last command output denotes that revision 3 have been created, so we now that the document is updated indeed.
Finally, now we can verify the database size! Expected data_size is still around 10000000 (10M), not 20M:
curl -X GET http://127.0.0.1:5984/attachtest
And this should work fine. For example, on my machine it gives:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":8,"purge_seq":0,"compact_running":false,"disk_size":10535013,"data_size":10493008,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":8}
So, still 10M.

A:
It means that each time you're modifying the document (not the
  attachment, just one field of the document), it will duplicate the 100
  MB attachment.

In my testing I found the opposite - the same attachment is linked through multiple revisions of the same document with no loss of space.
Please can you retest to be certain of this behaviour?


Q: Copying Conditional Formatting without adding to the data set I have an inventory and ordering management Sheet where I use color coding via Sheets Conditional Formatting to make some cells quickly visible as having outstanding orders.  In my particular case, I am using conditional formatting based on a neighboring cell.
The sheet I built utilizes several columns for ordering cycles with our suppliers.  When I am ready to move on to the next ordering cycle, I copy and paste a set of columns to create the new cycle.
The problem that I encounter is this: the new column's Conditional Formatting gets added to the old, both in terms of adding a new column to format, but also referencing the cell from which the copied columns use to decide whether to format.
Original Order Block
In this second image, I have pasted a new order block from Columns AD-AL to Columns AM -AU.
Pasted Order Block
There are two things that I am trying to solve:

*

*I would expect the custom formula to update to =$AR5<>"", but it holds on to the Original Order Block's formula, thus applying the formatting from cells that are in the Original Order Block.

*I would expect the range to update to only the new range of AQ5:AQ397, rather than add the additional range to the original order block range.
Each order block needs the conditional formatting to be independent from the one which it was copied.
Thanks in advance.

A: In this case, you can just remove the "$" from your custom formula and it will move just fine
Your ranges are going to be together as you shown, but will look at the cell at its right


Q: Python Binary Search Tree with key and value I need to implement a Binary Search Tree class as homework but I struggle making the insert function. I have looked through Google a lot to find some solutions or possibilities on how to do it but none of them has used a key and value (mostly just value) or if they used a key aswell, they had tons of seperate functions which I am not allowed to do I think.
So the pre-built is simply that:
class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.left = self.right = None

class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.size = 0

    def __len__(self):
        return self.size

    def insert(self, key, value):
        pass

    def remove(self, key):
        pass

    def find(self, key):
        pass

Now the thing is, if I want to check for example whether the value is smaller or bigger than a current Node to put it either right or left, I get Errors such as "root is not defined" or "root.right" has no such attribute etc...
And I guess that makes sense because self.root is declared as None.
But how do I actually fix it now to make the insert function work?
I am a little confused by this task as it uses key + value, so I need to insert the value bound to the specific key and in case the key already existed, overwrite its value.

A: its 5 in the morning so this might be all wrong, but here goes:
the key is what we are sorting by, the values aren't interesting
your insert function should probably look something like this:
def insert(self, key, value):
        if self.root = None:
            self.root = Node(key,value)
            return
        #regular binary tree traversal (comparing the key) to find where to insert, lets assume we need to insert on the left
        parent.left = Node(key,value)

can you figure it out from here or would you like more direction

A: You didn't specify, but I'm guessing the point of the keys is to determine if a particular key is already in the tree, and if so, replace the related node's value in O(1) runtime complexity.
So when you're inserting a node, you will first check the dictionary for the key (you will initialize an empty dictionary yourself in __init__). If it already is there, then you simply just need to replace the value of the node for that particular key. Otherwise, you add the new node the same way that you would in any BST, and also remember to update your dictionary to map the key to it's node.