text:
Q: Instagram API: SyntaxError: Unexpected token < I'm using the 'tag/media/recent?' endpoint of the Instagram API and I'm getting an error. When the value sent over isn't available, I understand that I'm getting a 404 page because the tag isn't available but how do I handle the error. With the Twitter API, I could search for the screen name 'hemidemisemiquaver' and it'll return my profile data as a fallback because there is no profile by that name. With the Instagram API, it returns a 404 page.
The Instagram API documentation states I should get an response object that looks like this:
{
"meta": {
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "..."
 }
}

I don't understand why this is happening. Does you understand why?
    app.post('/instaInputQuery', function (req, res, next) {
    console.log('INPUT_QUERY: ' + typeof req.body.query); // returns string
    var popular_tag_search_tag_name_recent = {
        url: 'https://api.instagram.com/v1/tags/ ' + req.body.query + '/media/recent?access_token=' + tokenContainer[0] + '&count=200',
        method: 'GET'
    };

request(popular_tag_search_tag_name_recent, function (error, response, body) {
    if (error && response.statusCode != 200) {
        console.error(error);
        res.send(error);
    } else {
        var JSONobjArray = JSON.parse(body);
        console.log('*******************************************************'.black.bgGreen);
        console.log(JSONobjArray);
        console.log('*******************************************************'.black.bgGreen);
        res.send(JSONobjArray);
    }
});
});

Thank you Vishnu for sending solving half the problem!

A: In if condition use (error || response.statusCode != 200) insted of (error && response.statusCode != 200)

Update: remove the space after the tags/ in the url.

try this:
app.post('/instaInputQuery', function (req, res, next) {

var popular_tag_search_tag_name_recent = {
    url: 'https://api.instagram.com/v1/tags/' + req.body.query + '/media/recent?access_token=' + tokenContainer[0] + '&count=200',
    method: 'GET'
};

request(popular_tag_search_tag_name_recent, function (error, response, body) {
    if (error || response.statusCode != 200) {
        error = error || response;
        console.error(error);
        res.send(error);
    } else {
        var JSONobjArray = JSON.parse(body);
        console.log('*******************************************************'.black.bgGreen);
        console.log(JSONobjArray);
        console.log('*******************************************************'.black.bgGreen);
        res.send(JSONobjArray);
    }
});
});

I hope this will work :)


text:
Q: Bootstrap x-editable combodate I've been playing a bit with X-editable for Bootstrap lately.
I am programming a webpage which displays data from a MySQL database. When I click on a button, I want all my data to become editable. When I click on save, the page automatically saves the changes in MySQL.
I have successfully programmed this for text fields and lists. But I can't make it work with dates. Perhaps someone has an idea that can help me?
Here is an example of the part that works:

NameJohn

I use the following code to call the editable
$('#f-name').children('a').editable({
        placement: 'bottom'
    });

And I can use jQuery to get the value (after modification) with this code
var $val=$('#f-name').children('a').html();

Until this point, the code works well. But now let's see the part that doesn't work:

Date:

I call the editable using:
$('#f-date').children('a').editable({
    placement: 'bottom',
});

I've tried using the same $('#f-date').children('a').html(); code as before, but it didn't work. If I print it, it says Undefined. I don't really understand.
If I look in the Google Chrome code inspector (after the editable has been used), I get the following:
17 Jan 1999

So I think it should work. How should I proceed?
Thanks for your help!
Best regards,
Yann

A: You should use $('#f-date').find('a').text(); to retrieve the value as text.
Check this example
https://jsfiddle.net/wfeog8mc/
You can also use params.newValue to get the value from the x-editable event but I now that I look at it, it may not be UNIX timestamp...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lodash reduce to build a time series collection from json I am a beginner and am trying to make a transformation from an array of object arrays.
 [
    [
        {
        date: 2020-01-01,
        price: 4.8588,
        },
        {
        date: 2020-01-02,
        price: 4.8588,
        },
        {
        date: 2020-01-03,
        price: 4.8588,
        },
    ],
    [
        {
        date: 2020-01-01,
        price: 4.8588,
        },
        {
        date: 2020-01-02,
        price: 4.8588,
        },
        {
        date: 2020-01-03,
        price: 4.8588,
        },
    ]
 ]

I have to process the result on a time series. As it is, I would be forced to nest loops and the computation time is too long.
So I try to use the lodash library to transform the set into an array of objects with the dates as keys. All this while performing calculations at each iteration. Moreover, each array, which corresponds to the historical prices of shares, has its own variable not present in the array (weight).
I hope to get a result like this:
 {2020-01-01:
    {
    price:1,
    perf:1
    }
 },
 {2020-01-02:
    {
    price:1,
    perf:1
    }
 },
 {2020-01-03:
    {
        price:1,
        perf:1
    }
 },
 {2020-01-04:
    {
    price:1,
    perf:1
    }
 },

With a calculation: perf = ((today's price1 / yesterday's price1) * weight1) + ((today's price2 / yesterday's price2) * weight2)
Can anyone help me with a lead to work on?
Edit : At the moment I am halfway to the desired result; reorganising the data into an object whose keys are the dates. I used this code:
 let prices = $var.responses,
    result = prices.reduce(function (r, a) {
        r[a.date] = r[a.date] || [];
        r[a.date].push(a);
        return r;
    }, Object.create(null));

 return result;

enter image description here


text:
Q: Showing that $U_{A,B}$ is a subspace Show that
$$
U_{A,B} = \{X \in \mathbb{K}^{n \times n}, f(X^T) = f(X)^T \}
$$
is a subspace of $V = \mathbb{K}^{n \times n}$ with $f: V \to V, X \mapsto AXB$ and $A,B \in V$.
I'm not sure what to show. Showing $f((v+w)^T) = f(v+w)^T $, with $v,w \in V$ does not get me anywhere and it feels not right. But this could just be me lacking intuition.

A: Note that the kernel of any linear map is a subspace. With that said, it suffices to verify that $U_{A,B}$ is indeed the kernel of the linear map $g:V \to V$ defined by $g(X) = f(X^T) - f(X)^T$.

A: To show that $U_{A,B}$ is a subspace you need to show two things:

*

*$X+Y\in U_{A,B} \forall X, Y \in U_{A,B}.$ This is straightforward since, $$f((X+Y)^T) = A(X+Y)^TB = A(X^T + Y^T)B \\= AX^TB + AY^TB \\= f(X^T)+f(Y^T) \\= f(X)^T + f(Y)^T \\= (f(X)+f(Y))^T \\= f(X+Y)^T$$
since $f$ is linear.

*Next $aX\in U_{A,B}$ for scalar $a\in \mathbb{K}$ and matrix $X\in U_{A,B}.$ This is again trivial since $$f(aX^T) \\= aAX^TB \\= af(X)^T \\ =(af(X))^T \\= (f(aX))^T$$
where I used the fact that $f$ is linear.


text:
Q: Kill a method in an infinite loop (golang) I am working with a piece of code that has an intentional infinite loop, I can't modify that code. I want to write some tests on that method (e.g. make sure it triggers actions at the right times) but I don't want to orphan a bunch of go routines. So I am trying to find a way that I can kill/interrupt that goroutine.
I was thinking of trying to wrap it in a wrapper function that would kill it after a signal. Like this (doesn't work).
func wrap(inf func()) func() {
  return func() {
    select {
    case inf():
    case <-time.After(5 * time.Second):
    }
  }
}

func main() {
  go wrap(inf())()
  // do things
}

All the variations I can think of don't really work. I was thinking of wrapping the inf in a function that writes to a channel (that will never get called), or something with a return statement. And then the select can read from that. The problem is then you have to launch that. If you do it in this routine you're never getting to the select. If you do it in another routine, you've just made the problem worse.
So, is there a way that I can kill that routine?
(yes - I would rather change the infinite loop code, but can't here)

A: If you can't change the loop code, you can't kill the loop.  Go is rather intentionally designed such that there's no way to kill a goroutine from outside of the goroutine, short of actually terminating the program itself.
If you can change the loop itself, the typical method of killing a routine is to provide a quit channel to the goroutine, and then close (or send on) that channel to tell the loop to exit.  Example:
quitCh := make(chan struct{})
go func() {
    for {
        select {
        case <-quitCh:
            return
        // other cases to handle what you need to do
        }
    }
}()

// Once you're done
close(quitCh) // goroutine exits

But without some way to coding that closure behavior into the loop itself, there's no way (to my knowledge) of specifically killing that goroutine or terminating the loop within it (unless you can trigger a panic in it, but that's a terrible way to handle that issue)


text:
Q: Enable application pool 32-bit mode on 64-bit server We have 64-bit Windows server and we need to explicitly enable the 32-bit mode in the Application Pool used by our web site, because the MS Jet Engine Data Provider used to import data from Excel does not run.
I am not sure, if we enable the 32-bit mode will we still get the advantage of 64-bit Server?

A: In IIS 7.x, there is a Advanced Settings property of the application pool called "Enable 32-bit Applications". If you run the application as a 32-bit applications it should be able to use 4 GB but obviously no more. So, in that respect, it can take advantage of running on a 64-bit server. On a 32-bit server (without special switches) it would only be able to use the 2GB of address space allocated to applications (the other 2 GB is presumed to be used by the OS).

A: ACE driver 64 bit is now available as a replacement of Jet driver. So you can use it instead,
http://blogs.msdn.com/b/psssql/archive/2010/01/21/how-to-get-a-x64-version-of-jet.aspx
(Read the last few paragraphs.)


text:
Q: Return a fixed pointer in C# I was wondering is it safe to return a fixed pointer from one method to another method - does the pinned object still stay fixed? e.g.
struct TestData
{
    public int value;
}

public class Class1
{
    private TestData data;

    public unsafe TestData* GetDataPtr()
    {
        fixed (TestData* ptr = &data)
        {
            // IS THIS SAFE?
            return ptr;
        }
    }
}

public class Class2
{
    public unsafe void Test()
    {
        Class1 x = new Class1();

        TestData* ptr = x.GetDataPtr(); // is this still fixed?
        ptr->value = 2;
    }
}

The reason i'm asking is using something in this style I've been getting AccessViolation exceptions. But since I changed it to e.g. set value direct from Class1 i haven't seen the issue occur.
EDIT:
the reason i thought it may be fixed is if from outside the "TestData* ptr = x.GetDataPtr()" you try to put fixed( ) you get "you cannot take the address of an already fixed expression". .. i get it now though it's speaking about my var "ptr" in "Test()" already being fixed..

A: Returning from the method ends the scope of fixed, hence the pointer is no longer fixed once you return. It is safe to pass fixed pointers up the chain, e.g.
fixed(TestData* ptr = &data) {
    MyFunction1(ptr);
    MyFunction2(ptr);
}

But returning makes the pointer non-fixed again.
Logically, this makes sense: there is no alternative way for the CLR to decide when the pointer should become non-fixed after you have returned it from the call.


text:
Q: SQL Group records by a custom weekly time range This is probably simple but I am constantly over-thinking my issues.
I need to pull all records within a certain date range (Jan - Mar 2018) that are between Sunday 12PM to Friday 1PM. Grouped by week
SELECT col1,
       Sum(col2)
FROM   (SELECT *
        FROM   (SELECT col1,
                       col2,
                       Datename(dw, [date_col]) AS day_of_week,
                       date_col
                FROM   table
                WHERE  Datename(dw, [update_date]) != 'Saturday'
               --eliminate Saturday records
               ) a
        WHERE  ( Cast(update_date AS TIME) < '12:00'
                 AND day_of_week != 'Sunday' )
       --eliminate Sunday records before noon
       ) b
WHERE  ( day_of_week != 'Friday'
          OR Cast(update_date AS TIME) > '13:00' )

--eliminate Friday records after 1PM

A: Edited to reflect correct return values for DATEPART(dw, ...)
You can perform the logic to determine which day/hour combos are valid inside a CASE statement in a sub-query SELECT and then group by week number in an outer query. This would simplify the WHERE clause.  I find this style a little less opaque and easier to maintain long-term.
The example below was tested on Microsoft SQL SERVER.
SELECT
    DATEPART(wk, Update_Date) AS GroupByWeek
    , col1
    , SUM(col2)
FROM (
    SELECT
        col1
        , col2
        , Update_Date
        , CASE
            WHEN DATEPART(dw, Update_Date) = 1 AND DATEPART(hh, Update_Date) >= 12 THEN 1
            WHEN DATEPART(dw, Update_Date) = 6 AND DATEPART(hh, Update_Date) < 13 THEN 1
            WHEN DATEPART(dw, Update_Date) BETWEEN 2 AND 5 THEN 1
            ELSE 0
        END AS FallsInWindow
    FROM table
) RowsInWindow
WHERE
    RowsInWindow.Update_Date BETWEEN '2018-01-01' AND '2018-04-01'
    AND RowsInWindow.FallsInWindow = 1
GROUP BY
    DATEPART(wk, Update_Date)
    , col1
ORDER BY GroupByWeek

A: SELECT col1, Sum(col2)
                FROM   [table]
                WHERE  Datename(dw, [update_date]) <> 'Saturday'
                OR
                NOT ( Cast(update_date AS TIME) < '12:00'
                      AND Datename(dw, [update_date]) == 'Sunday' )
                OR
                NOT ( Datename(dw, [update_date]) == 'Friday'
                      AND Cast(update_date AS TIME) > '13:00' )
group by col1, datepart(week, update_date);

A: You can use the following condition:
WHERE update_date >= '2018-01-01' -- between Jan 2018
AND   update_date <  '2018-04-01' -- and Mar 2018
AND (
    DATENAME(dw, update_date) = 'Sunday' AND CAST(update_date AS TIME) >= '12:00' OR
    DATENAME(dw, update_date) IN ('Monday', 'Tuesday', 'Wednesday', 'Thursday') OR
    DATENAME(dw, update_date) = 'Friday' AND CAST(update_date AS TIME) < '13:00'
)


text:
Q: The algorithm "bcrypt" is not supported. Symfony Symfony does't work with bcrypt algorithm, it's so strange anyone know what could be ?
Thanks.
security:
   encoders:
    AppBundle\Entity\Usuario:
      algorithm: bcrypt

The app says me

The algorithm "bcrypt" is not supported.

A: Could you please put this code in somewhere to make sure you can run bcrypt algorithm for hashing password
$encoder = new \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder(4);
$password = $encoder->encodePassword('your_plain_password', 'your_salt');

If you receive error like To use the BCrypt encoder, you need to upgrade to PHP 5.5 or install the "ircmaxell/password-compat" via Composer.. So unfortunately, I think you should reinstall PHP. otherwise, that must be a bug in symfony document. Because I've just had a check the PHP function hash_algos(), it doesn't return bcrypt algorithm, strange! My PHP version is 5.6.11

A: Finaly "fixed", I've reinstaled the symfony version, I had a old version.
Thanks all for answers.

A: Don't use  AppBundle\Entity\Usuario:
security:
   encoders:
      App\Entity\User:
         algorithm: bcrypt


text:
Q: How does a JVM execute the Inheritance tree structure? class Vehicle {
    public int wheels;
    public int lights;
}

class Car extends Vehicle {
    public int wheels =4;
    public int lights =2;

    public void lights_on( int lights) {
        //Code to onlights
    }
}

class BMWCar extends Car {
     public int wheels = 4;
     public int lights = 4;
}

public class TestCar {
    public static void main(String args[]) {
        //Creating a new instance of BMWCAR by calling the default
        // constructor provided by the constructor

        bmwCar = new BMWCAR();
        bmwCar.lights_on();
    }
}

In the above example, when I run the TestCar.java file, The JVM's class loader loads the TestCar file into the method area, and it executes the main method. When a bmwCar instance is created, it calls the default constructor of the BMWCar class and executes the super constructor, which is the Car class's default constructor. I would like to know why when the bmwCar.lights_on(); method is called the JVM looks for the lights_on method and in the bmwCar object it initalizes the value of instance variables wheels and lights i.e. 4 and 4.
When the lights_on(); method is executed in the Car class, does the JVM reintialize the value? How is the reference passed from bmwCar.lights_on to the Car class lights_on method? I am looking for a detailed answer about the workflow.

A: You are declaring member variables wheels and lights in class Vehicle, and then you're declaring member variables with the same name in subclasses Car and BMWCar.
Note that member variables are not overridden like methods; the member variables in your subclasses hide the variables in the superclasses.
So, there is not one set of member variables - there are three! You see one of those three depending in which class your method is. The member variables of the superclasses are not somehow reinitialized. Inside the method lights_on in class Car, you'll see the variables wheels and lights of class Car, with the values 4 and 2.
Using member variables with the same name as in a superclass should be avoided, as it's confusing, and it's not doing what you might think it does.

A: Don't redeclare the member variables put do it like this
public class Vehicle {
  public int wheels = -1;
  public int lights = -1;
}

class Car extends Vehicle {
  {
    wheels = 4; //set inherited member variable
    lights = 2; //set inherited member variable
  }

  public void lights_on(int lights){
    System.out.println("Parameter to lights_on: "+lights);
    System.out.println("Wheels: "+wheels);
    System.out.println("Lights: "+this.lights);
  }
}

class BMWCar extends Car {
  {
    wheels = 4;
    lights = 4;
  }
}

public  class  TestCar {
  public static void main(String args[]){
    //Creating a New Instance of BMWCAR by calling the default Constructor provided by the constructor
    Car car = new BMWCar();
    car.lights_on(1);
    car = new Car();
    car.lights_on(1);
  }
}

A: Conceptually, the JVM refers to and looks up the field by its name, type and class. See the GETFIELD opcode in the JVM spec.
In practice, the JIT compiler (at least in Hotspot) compiles to native code which simply access memory at a given offset of the object's data (i.e. the JIT compiler pre-computes the field offset). (Sorry, I don't have a reference for this, but if you get the debug version of the JVM you can ask it to output its assembler code and see that that's what it does.)


text:
Q: Android - Get Data From MySql Database Using Inner Join (Codeigniter) I want to get data from android to my server that have made with CodeIgniter framework. But I have problems when I want to take the "marker" data by performing inner join on mysql database. But on android, it always get the result==false.
It's my android source code
protected void onPostExecute(final Boolean result) {
        dialog.cancel();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result == false) {
                    showInfo();
                } else {
                    for (int i = 0; i < array.size(); i++) {
                        HashMap<String, String> newMap = new HashMap<String, String>();
                        newMap = array.get(i);
                        mMyMarkersArray.add(new MyMarker(newMap.get("nama"), newMap.get("deskripsi"), newMap.get("foto"), newMap.get("marker"), Double.parseDouble(newMap.get("lat")), Double.parseDouble(newMap.get("lng"))));
                    }
                    plotMarkers(mMyMarkersArray);
                }
            }
        });

    }

Codeigniter (controller) source code
public function getContentLocation(){
    $response=array();
    $result = $this->m_krb->getAllContent();
    if ($result->num_rows() > 0) {
        $response["konten"] = array();

        foreach($result->result() as $row):
            $pendaftaran = array();
            $pendaftaran["id"] = $row->id_table_petakrb;
            $pendaftaran["nama"] = $row->nama_petakrb;
            $pendaftaran["deskripsi"] = $row->deskripsi;
            $pendaftaran["foto"]='http://192.168.43.137/navigasikrb/assets/img/foto/'.$row->foto;
            $icon = $row->marker_icon;
            $marker = $this->m_krb->checkGroup($icon)->result();
            $pendaftaran["marker"] = $marker->nama_group;
            $pendaftaran["lng"] = $row->longitude;
            $pendaftaran["lat"] = $row->latitude;
            array_push($response["konten"], $pendaftaran);
        endforeach;

    // sukses
    $response["success"] = 1;

    // echo JSON response
    echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "Tidak ada data yang ditemukan";

        echo json_encode($response);
    }
}

Codeigniter (model) source code
    function getAllContent(){
       $query=$this->db->query("select * from table_petakrb ");
       return $query;
    }

    function checkGroup($icon){
       $query=$this->db->query("select table_group.nama_group FROM table_group INNER JOIN table_petakrb ON table_petakrb.marker_icon = table_group.file_icon WHERE table_petakrb.marker_icon = '$icon'  ");
       return $query;
    }

But if i change the codeigniter controller source code like this, it can get the data sucessfully on android.
public function getContentLocation(){
    $response=array();
    $result = $this->m_krb->getAllContent();
    if ($result->num_rows() > 0) {
        $response["konten"] = array();

        foreach($result->result() as $row):
            $pendaftaran = array();
            $pendaftaran["id"] = $row->id_table_petakrb;
            $pendaftaran["nama"] = $row->nama_petakrb;
            $pendaftaran["deskripsi"] = $row->deskripsi;
            $pendaftaran["foto"]='http://192.168.43.137/navigasikrb/assets/img/foto/'.$row->foto;
            $pendaftaran["marker"] = $row->marker_icon;
            $pendaftaran["lng"] = $row->longitude;
            $pendaftaran["lat"] = $row->latitude;
            array_push($response["konten"], $pendaftaran);
        endforeach;

    // sukses
    $response["success"] = 1;

    // echo JSON response
    echo json_encode($response);
    } else {
        $response["success"] = 0;
        $response["message"] = "Tidak ada data yang ditemukan";

        echo json_encode($response);
    }
}

But the problem is i can't take the data with the inner join as I wrote the source code above. Is there something wrong with my code?


text:
Q: "Thank you for your kindness, but I am not fond of this" Suppose somebody gives you something — for instance, a chocolate — and you do not like it, so you give it back to the person.  Is it then correct to say something like this:

Thank you for your kindness,  but I am not fond of this.

Which I think means:

Thank you, but I don't like it.

I think it sounds formal.

A: If someone offered you a chocolate, it would be enough to politely decline their offer and no-one would expect you to give a reason: "No thank you", or "That is very kind, but no thank you"
If you feel the need to give a reason, I would stay quite general. For example, saying "I'm not fond of this" suggests that there is something wrong with their chocolate in particular. If you say "I'm not fond of chocolate" that is more general and less likely to cause offence.
The more general you can be with your decline, the more polite it will seem. Even better, it may be more polite to suggest that you like chocolate, but not right now: "Thank you, but not right now", or "Maybe later".

A: "The correct thing to do, even if you don't like it, is to take it, say 'Thank you very much', and then either eat it with a smile on your face, or say you'll keep it for later."
I agree with this answer which was in the comments.
At the risk of sounding racist there is a saying: "Do not accept gifts from Greeks".
"Beware of Greeks bearing gifts"
http://en.wikipedia.org/wiki/Timeo_Danaos_et_dona_ferentes
There are some contexts in which it is inappropriate to accept gifts.  In that case you would probably say something like:
"I am very sorry but I cannot accept your gift" or "I am very sorry but we are not allowed to accept gifts".
There is also a problem when something is given as a substitute for a payment.  If you have agreed to teach English for a couple of hours you might but unhappy to receive a bunch of flowers for your troubles.
There is an interesting expression:
Cannot be had for love nor money.
http://idioms.thefreedictionary.com/for+love+nor+money


text:
Q: Big-O complexity of iterating over every substring What is the Big-O complexity of iterating over every possible non-empty substring of a string of length $N$?
The simple way to do the iteration over string $S$ is:
for i in 1 .. N:
    for j in (i+1) .. N:
        S[i .. j]

Clearly this is more complex than $\mathcal{O}\left(N\right)$ but less complex than $\mathcal{O}\left(N^2\right)$, but I'm not sure how to understand the complexity of these nested loops.

A: $$
S = (1+ 1+ \ldots 1) + //\text {n times}\\
  (1+1+ \ldots 1) +  //\text{n-1 times} \\
  \ldots 1
$$
Hence $S = 1 + 2 + \ldots (n-1) +n = \frac{n(n+1)}{2}$


text:
Q: Using induction to prove $\sum_{k=0}^{N-1} 2^k = 2^N-1$ I have this summation and I was attempting to prove it by induction however I have gotten stuck and not sure how to carry on further, if anyone could help point me in the right way that would be much appreciated!
$$\sum_{k=0}^{N-1} 2^k = 2^N-1$$
So first I have the base case: $n=2$:
$$\sum_{k=0}^{1} 2^k = 3, \iff 2^2-1=3$$
Then I assumed true for $n=r$ so:
$$\sum_{k=0}^{r-1} 2^k = 2^r-1$$
Then I considered $n=r+1$ so I want to show:
$$\sum_{k=0}^{r} 2^k = 2^{r+1}-1$$
$$\sum_{k=0}^{r} 2^k = \sum_{k=0}^{r-1} 2^k + (r+1)^\mathrm{th}\text{ term}$$
$$\sum_{k=0}^{r} 2^k = 2^r -1+ (2^{r+1}-1)$$
But now I'm not sure how to go further or whether I got the "$(r+1)^{th}$" term correct or if I can even do this? If anyone can help me complete it and give me tips on induction as I always fail on the inductive step!

A: You made a minor mistake in your induction: you're not pulling out the $(r+1)^{th}$ term. Well, you are, if you count from $0$, but the summand you're pulling out is meant to correspond to the final index, where the index is $k=r$. (You took the $k=r+1$ term out instead.) That is,
$$\sum_{k=0}^r 2^k = 2^r + \sum_{k=0}^{r-1} 2^k$$
By your induction hypothesis then
$$2^r + \sum_{k=0}^{r-1} 2^k = 2^r + 2^r - 1 = 2(2^r) - 1 = 2^{r+1} - 1$$
which is what you sought to prove in your induction step.

A: You assume:
$$\sum_{k=0}^{r-1}2^k=2^r-1$$
Then, it follows:
$$\sum_{k=0}^r2^k=(2^r-1)+2^r=2(2^r)-1=2^{r+1}-1$$


text:
Q: Where is the main app class in an Android kotlin project? I'm new to Android app dev, and I'm trying to use a library (LocaleHelper) that says to extend my App class:
class App : LocaleAwareApp() {
}

And to extend my base activity class:
open class BaseActivity : LocaleAwareCompatActivity() {
}

but I don't have either of these in my Android Kotlin project. All I see for source code generated is the MainActivity class.
I'm using Android Studio 3.4.2 with min sdk set to 22. Is there a different way to integrate this library?

A: You have to create a new App class like this:
class App : LocaleAwareApp() {
}

and in AndroidManifest add this line inside the application tag:
android:name=".App"

After that you create a BaseActivityClass:
open class BaseActivity : LocaleAwareCompatActivity() {
}

and your MainActivity and every other activity you create should inherit from this BaseActivity like this:
class MainActivity: BaseActivity() {
}

For more customization you should look into https://github.com/zeugma-solutions/locale-helper-android

A: App (I assume you mean Application) and Activity classes are part of the std android library, so you don't have to "have them". Extending them means you have to write your own implementation with "extends Activity" and "extends Application" in class prototype.
more info here: https://medium.com/@balakrishnanpt/android-application-class-a8a1d64c82d1
hope that helps

A: Assuming that you mean this library, LocaleAwareApplication is a class in the library. You would create a subclass of it in your project:
class MyAwesomeApplication : LocaleAwareApplication() {
}

Then, in your manifest, in the <application> tag, add an android:name attribute that points to your subclass:
<application android:name=".MyAwesomeApplication"
  // other attributes go here
>

I do not know why the README has the wrong class name (LocaleAwareApp instead of LocaleAwareApplication).


text:
Q: Is it ok to create React custom hooks that don't actually call other hooks? I understand that React custom hooks are just regular functions but prefixed with 'use' to indicate to React that they are custom hooks. This lets them use the built-in React hooks (or other custom hooks).
I created a function prefixed with 'use' originally intended to be a custom hook, but I realized that it doesn't actually need to call any other React hooks. Should I rename my function so that it is no longer considered a hook? Are there any other implications to consider (like performance?). Are there standard conventions for this topic?

A: If your hook is not dependent on any other hooks then it should be converted to normal function instead.
Custom Hooks offer the flexibility of sharing logic that wasn't possible in React components before.

*

*Hooks can be called from the React code only not from the Regular
JS functions. Hence, Hooks' scope is limited to the React code world
and has more power to do a lot with React code. Rather than JS,
regular functions could be used across application but as react code
guidelines keep the code more aligned to react syntax.

*In the class-based components, the Hooks won't work but regular
functions will.

*In the regular JS functions, you can't access useState,
useEffect, useReducer etc. but in react custom hooks I can.

Answered here: https://stackoverflow.com/a/60133908/1723410


text:
Q: Sparkjava Error: org.eclipse.jetty.http.HttpParser - Header is too large >8192 We are developping an internal web component based on sparkjava framework, and HTTP GET is used but not POST for convenient.
An error is returned when request URL contains large data (more than 8K) as follow:
org.eclipse.jetty.http.HttpParser - Header is too large >8192.
How to solve it?

A: Sparkjava runs on an embedded Jetty server, but most of Jetty configuration is hardcode by default in sparkjava framework.
One solution is to customize EmbeddedServerFactory:
    static Server server = null;

    private static void startup() {
        EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, createEmbeddedServerFactory());

        awaitInitialization();

        Stream.of(server.getConnectors()).map(Connector::getConnectionFactories).flatMap(Collection::stream)
                        .filter(t -> t.getClass().isAssignableFrom(HttpConnectionFactory.class))
                        .map(t -> ((HttpConnectionFactory) t).getHttpConfiguration()).forEach(t -> {
                            t.setRequestHeaderSize(512 * 1024 * 1024);
                            t.setSendServerVersion(false);
                            t.setSendDateHeader(false);
                        });
    }

    private static EmbeddedServerFactory createEmbeddedServerFactory() {
        return new EmbeddedJettyFactory(new JettyServerFactory() {
            @Override
            public Server create(int maxThreads, int minThreads, int threadTimeoutMillis) {
                return create(maxThreads <= 0 ? null
                                : new QueuedThreadPool(maxThreads, minThreads, threadTimeoutMillis));
            }

            @Override
            public Server create(ThreadPool threadPool) {
                return server = new Server(threadPool);
            }

        });
    }


text:
Q: How to fetch body of email using Mail Core2 IOS Swift I am building a app which receive emails
I fetched the subject of email but i am not able to get the body Email.
here is my code
let imapsession = MCOIMAPSession()
imapsession.hostname = "xxxx"
imapsession.port = 993
imapsession.username = "xxxx"
imapsession.password = "xxxx"
imapsession.connectionType = MCOConnectionType.TLS

let requestKind : MCOIMAPMessagesRequestKind = MCOIMAPMessagesRequestKind.Headers
let folder : String = "INBOX"
let uids : MCOIndexSet = MCOIndexSet(range: MCORangeMake(1, UINT64_MAX))

let fetchOperation : MCOIMAPFetchMessagesOperation = imapsession.fetchMessagesOperationWithFolder(folder, requestKind: requestKind, uids: uids)

fetchOperation.start { (err, msg, vanished) -> Void in
let msgs = msg as! [MCOIMAPMessage]
print("error from server \(err)")

for i in 0..<msgs.count
{
    // Here i want the body of all emails fetched...

    if let m = msgs[i].header.subject
    {
        print("\(i). \(m)")
    }
}

}
i have seen this answer as well but i could not understand it
Fetch an email body in mailcore2 OSX with swift
so please guide me about this

A: Try this code it will help you:
var session: MCOIMAPSession = MCOIMAPSession()
session.hostname = "imap.gmail.com"
session.port = 993
session.username = UICKeyChainStore.stringForKey("username")
session.password = UICKeyChainStore.stringForKey("password")
session.connectionType = MCOConnectionTypeTLS
var operation: MCOIMAPFetchContentOperation = session.fetchMessageByUIDOperationWithFolder("INBOX", uid: message.uid)
operation.start({(error: NSError, data: NSData) -> Void in
    var messageParser: MCOMessageParser = MCOMessageParser(data: data)
    var msgHTMLBody: String = messageParser.htmlBodyRendering()
    webView.loadHTMLString(msgHTMLBody, baseURL: nil)
})


text:
Q: How to set value for hidden in filed in selenium script> I'm novice in selenium script and trying to setup a value for a hidden field. After providing user id and password in the login form, i have to set a hidden field value (" <<--- HERE SET HIDDEN FIELD VALUE--->>").
I tried something like this

    type
    id=AppIDhidden
    test
    #SEP#id=AppIDhidden#SEP#name=AppIDhidden#SEP#css=#AppID#SEP#xpath=//input[@id='AppIDhidden']#XPATH#//form[@id='myLoginForm']/div[2]/div/div[2]/div/input#XPATH#//div[2]/div/input#XPATH##SEP#dom=document.forms[0].AppIDhidden#DOM#document.forms[0].elements[3]#DOM##SEP#
    0

    field value

but didn't work, I got error "Element id=AppIDhidden is not visible".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://www.example.com/" />
<title>New Test</title>

New Test

    newStep
    Loading - https://www.example.com/

    3825
    https://www.example.com/

    open
    /

    0

    type
    id=DisplayUserMask
    myuser
    #SEP#id=DisplayUserMask#SEP#name=DisplayUserMask#SEP#css=#DisplayUserMask#SEP#xpath=//input[@id='DisplayUserMask']#XPATH#//form[@id='myLoginForm']/div[3]/div/input#XPATH#//div/input#XPATH##SEP#dom=document.forms[0].DisplayUserMask#DOM#document.forms[0].elements[1]#DOM##SEP#
    0

    Type DisplayUserMask

    type
    id=Password
    mypassword
    #SEP#id=Password#SEP#name=Password#SEP#css=#Password#SEP#xpath=//input[@id='Password']#XPATH#//form[@id='myLoginForm']/div[6]/div/input#XPATH#//div[6]/div/input#XPATH##SEP#dom=document.forms[0].Password#DOM#document.forms[0].elements[3]#DOM##SEP#
    isPassword

    Type Password

<<--- HERE SET HIDDEN FIELD VALUE--->>

    newStep
    Click subLogin

    6070
    https://www.example.com/myhome

A: Use the runScript command:

    runScript
    document.getElementById('AppIDhidden').value='test'


text:
Q: How do I get rid of the package e1071 installation error? I am trying to run the confusionMatrix function but it shows this error and when I try to install the package it shows the error in bold below it.
Error: package e1071 is required
Traceback:

*

*confusionMatrix(factor(test_data$area, levels = 1:100), factor(test_data$pred_rf,
.     levels = 1:100))

*confusionMatrix.default(factor(test_data$area, levels = 1:100),
.     factor(test_data$pred_rf, levels = 1:100))

*getFromNamespace("confusionMatrix.table", "caret")(classTable,
.     positive, prevalence = prevalence, mode = mode)

*requireNamespaceQuietStop("e1071")

*stop(paste("package", package, "is required"), call. = FALSE)

also installing the dependency 'proxy'
Warning message in install.packages("e1071"):
"installation of package 'proxy' had non-zero exit status"Warning message in install.packages("e1071"):
"installation of package 'e1071' had non-zero exit status"Updating HTML index of packages in '.Library'
Making 'packages.html' ... done

How do I solve this?


text:
Q: Sum column values if the value from next column appears multiple times i have a column A with formula values: 1 op, 2 op, 4 op, 9 op, 234 op and another with names corresponding to those values: mike1, mike3, mike8, mike2, mike1. How can i sum the values for each name? i have tried with sumif, count but it just doesn't sum them. I have the formula to show the unique names in alphabetic order but i can't make the sum. Thank you.
------------------------------------------
|  A    |  B    |  C    |  D    |   E    |
------------------------------------------
|1 OP   | mike1 |       | mike1 | 235 op |
------------------------------------------
|2 OP   | mike3 |       | mike3 | 11 op  |
------------------------------------------
|4 OP   | mike8 |       | mike8 | 4 op   |
------------------------------------------
|9 OP   | mike3 |       |       |        |
------------------------------------------
|234 OP | mike1 |       |       |        |
------------------------------------------

A: As @Dirk said - column A needs to be numerical.  "1" is numerical, "OP" isn't.
Based on the example table you gave this formula would work if column A was numerical:  =SUMIF($B$1:$B$5,$D1,$A$1:$A$5)
If you wanted column A to be numerical you need to remove the OP text from the cell.  You could display the OP by using a custom number format of: # "OP" - the SUMIF formula will work then.
Or you could use this formula to remove the OP from the cell and calculate the number: =SUMPRODUCT(($B$1:$B$5=$D1)*(SUBSTITUTE($A$1:$A$5," OP",""))) & " OP"


text:
Q: Removing PageFactory from design C# We have an existing UI automation framework in C# and based on knowledge at the time we used PageFactory to initialize the elements within the page files. Recently I've read more on the subject and there appears to be no real benefit to using PageFactory in C# so I'm attempting to re-write the pages using fields instead. One thing I'm having an issue with now those is getting my extended methods to work.
For example: In the current implementation I have an element identified like this:
        [FindsBy(How = How.LinkText, Using = "Authenticate")]
        private IWebElement BstHomePageHeader;
    public IWebElement getBstHomePageHeader()
    {
        return BstHomePageHeader;
    }

There is a helper method which checks if the element exists in certain cases and it's called like this from within a test:
home.getBstHomePageHeader().DoesElementExist().Should().BeTrue("User was not taken to the home page.");
The code within the "DoesElementExist" method has a 5 second wait applied, continually validating the element.Displayed check and it's ignoring the NoSuchElementException, ElementNotVisibleExpection and WebDriverTimeoutException. If the element is not returned within 5 seconds a false is returned to the main call and the fluent assertion message is thrown.
When I remove PageFactory the element is now created like below (in the same page file):
public IWebElement getBstHomePageHeader => driver.FindElement(By.LinkText("Authenticate"));
If I try to apply the same helper method to it like below the DoesElementExist part of the line of code no longer applies. The NoSuchElementException is thrown directly in my page file and therefore the fluent assertion message isn't returned.
home.getBstHomePageHeader.DoesElementExist().Should().BeTrue("User was not taken to the home page.");
Is it possible in a non-PageFactory design to not have the page class throw the NoSuchElementException so the test can handle the failure?

A: Well, for what it's worth I've come up with a different solution. I'm not sure it's the best one but I believe it will work. In my page file I'm looking the elements up with this:
public IWebElement getBstHomePageHeader => LookUpElement(By.LinkText("Authenticate")); I created a base class which is hosting the LookUpElement method and that looks like protected IWebElement LookUpElement(By locator)
        {
            try
            {
                return wait.Until(driver => driver.FindElement(locator));
            }
            catch (NoSuchElementException)
            {
            }
            catch (ElementNotVisibleException)
            {
            }
            catch (WebDriverTimeoutException)
            {
            }
            return null;
        }
The wait logic is the same as before. The only other change is I've changed how I was asking the question within the test. It now looks like this
                if (home.getBstHomePageHeader == null)
                    false.Should().BeTrue("User was not taken to the home page.");
                test.Log(Status.Pass, "User is on the home page.");
So, I guess I didn't really answer my own original question but this workaround appears to work. We'll just have some re-writing to do in how we ask the questions.

A: In java you would throw the exception up to the caller. Can you do that at all in C#?
This looks like it might help: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/creating-and-throwing-exceptions
Side note: We removed page factory containers from our code base too and it is so much cleaner. Each page class contains its own required elements and selectors at the top of the class. We also noticed stale element exceptions with the containers, even when it was setup properly.


text:
Q: Accessing a non-Silverlight assembly in Silverlight using COM I'm trying to access a non SL assembly  in my SL application. I have wrap the non SL assembly in COM wrapper using "Register for COM introp".
Internally this assembly loaded another assembly using reflection and calls its method using Method.Invoke.
Application is getting crash when I call this COM component. It looks like it is able to load the assembly through reflection but it is unable to make the call to  methods using reflection (Mehtod.Invoke).
I can only see the following log in Event viewer
Faulting application name: IEXPLORE.EXE, version: 8.0.7601.17514, time stamp: 0x4ce79912
Faulting module name: ntdll.dll, version: 6.1.7601.17725, time stamp: 0x4ec49b8f
Exception code: 0x4000001f
Fault offset: 0x000ce695
Faulting process id: 0x2f8
Faulting application start time: 0x01ce47e8417f56c3
Faulting application path: C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE
Faulting module path: C:\Windows\SysWOW64\ntdll.dll
Report Id: 86ef1dd9-b3db-11e2-8faa-b499baf11a4f


text:
Q: Is there a way to make a For Loop iteration continue after a certain time? I have a for loop that is making POST requests. Each one takes around 1-8 minutes to complete and I want my loop to continue and skip over if a certain amount of time goes by, such as 15 minutes.
What would be a good way of accomplishing this? I've looked into potentially using asynchronous functions but I'm not sure how to go about that yet or if it's even the right approach.
its a super simple loop, its basically:
for url in list_of_urls:
   request = requests.post(url)
   excel_sheet = #write header, status code, etc to document

    #save excel

A: You can use requests "timeout" argument. It will throw an exception if the request takes longer than this number of seconds, which you can easily catch:
for url in list_of_urls:
    try:
        request = requests.post(url, timeout=60)
    except requests.exceptions.ReadTimeout:
        print("Timeout requesting %s, skipping..." % url)
        continue
    # do your stuff here
    pass


text:
Q: App freezes when idle after "Background concurrent copying GC freed" log messages Steps to reproduce the problem:
The way I reproduce this problem is

*

*I run my android application & I enter the MainActivity

*I leave my phone idle for about ten minutes or more, having configured the device in its settings to not sleep if idle less than 30 minutes.

*While waiting, in Android Studio's "Run" tab I see messages such as this one:

Background concurrent copying GC freed 237478(18MB) AllocSpace objects, 52(1756KB) LOS objects, 69% free, 5507KB/17MB, paused 217us total 164.170ms

*After 5 to 10 messages as the one above, I see this couple of messages:

Background concurrent copying GC freed 257288(11MB) AllocSpace objects, 0(0B) LOS objects, 66% free, 6204KB/18MB, paused 86us total 165.671ms

Background young concurrent copying GC freed 217214(10MB) AllocSpace objects, 0(0B) LOS objects, 56% free, 8108KB/18MB, paused 112us total 129.379ms

*If I wait more, I keep receiving the above couple of messages and if I touch the screen nothing is interactable and the whole app seems frozen. Also, the device's "Home" & "Back" buttons don't do anything. If I minimize the app when I try to maximize it again there's a great delay and when the app finally opens, everything keeps not responding (buttons don't do anything and you can't even scroll). So, I am forced to kill the app.

Observations & Notes:

*

*The problem described in the above steps doesn't always occur. But, when I try to reproduce it, it occurs about half of the times that the app is run.

*I have run my app using the profiler while reproducing the problem and the memory consumption remains at the same level from start to finish, throughout all the above steps.

*Keep in mind that I have seen and reproduced this problem in a Xiaomi Mi A2 Lite device, which has only 3GB RAM. I haven't tried to reproduce it in any other devices.

*The Activity where this problem occurs contains some views with many images. When I don't populate some views from the Activity's layout with any images, then the above log messages report more free memory percentage. The problem still occurs at times but you have to leave the phone idle for much more time for the app to freeze. Also, the greater the size of the images is, the easier it is for this problem to be reproduced.
My conclusion:
I've observed that when I receive the above log messages the free memory percentage gradually decreases and the app starts freezing when it reaches values below 60%. So, I assume that the device's memory can't handle that much data and that's why the garbage collector keeps reallocating the memory for optimization purposes. Of course, the easiest solution would be to have a device with more memory or use less and smaller size images, but I'd prefer a more robust solution.
Questions:

*

*I'd like to know if someone else has observed this same kind of behavior in their app and how they have dealt with it.

*In the beginning I receive log messages that start with "Background concurrent copying GC freed" (see step 3) and after a bunch of them I receive the couple of messages (see step 4) where the first message starts with "Background concurrent copying GC freed" and the second message starts with "Background young concurrent copying GC freed". Does that "young concurrent" mean anything different or should I ignore this change?

*Is there any other tool that may help me investigate this matter any further?

A: I solved the problem, it turns out that a colleague of mine had created a new thread that kept being alive even when idle. As a result, the message "Background young concurrent copying GC freed" appeared and the device gradually started running out of memory. So, for anyone that observes the same messages or behavior I would suggest they check analytically their app's memory consumption and especially the multi-threaded functionalities.

A: When the same situation happened to me, I noticed that when I tried to use my ListenerRegistrations that were listening to data in firebase again
For example;
private var dataListener: ListenerRegistration? = null

Before operating this object after making a definition in the form of
dataListener?.remove()
dataListener= null

do it. And now you can use this object again for different or same purpose


text:
Q: Different results for the very same method I'm trying to scrape and parse some data from one web page. The problem is that the script act's different after several attempts.
import mLib
import requests
import urlparse

URL = 'http://www.distrelec.sk/'

class base():

    def __init__(self):
        self.soup = mLib.getSoup(URL)

    def get_info(self,url):

        soup = mLib.getSoup(url)
        up_left_table_outer = soup.find('table',class_='validate-checkbox-group')

        for row_outer in up_left_table_outer.find_all('tr'):
            key_value = row_outer.find_all('td')
            key = key_value[0].label.text
            value = key_value[1].span.text
            yield key,value

bs = base()
for i in range(1,20):
    print dict(bs.get_info('http://www.distrelec.sk/sk/socket-mm-cerna-multi-contact-lb4-black/p/11034944?q=*&filter_Buyable=1&filter_Category3=Laborat%C3%B3rne+konektory&page=1&origPageSize=10&simi=99.8'))

Here is a part of the output (it should be the same each line). As you can see, the key Contact B and Contact A are sometimes different. The problem is probably that there is more than one line of text on the web page:
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'Z\xe1suvka', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'\xf8 4 mm', u'Velikost': u'\xf8 4 mm', u'Contact B': u'P\xe1jen\xed'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'Z\xe1suvka', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'\xf8 4 mm', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'Z\xe1suvka', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'Z\xe1suvka', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'\xf8 4 mm', u'Velikost': u'\xf8 4 mm', u'Contact B': u'P\xe1jen\xed'}
{u'Barva': u'\u010cern\xe1', u'Jmenovit\xe9 nap\u011bt\xed': u'30 VAC 60 VDC, 20 A', u'Contact A': u'\xf8 4 mm', u'Velikost': u'\xf8 4 mm', u'Contact B': u'M6'}

Do you have any idea where is the problem?

A: The contents of the URL are changing. Try refreshing it a few times.
Compare this:

With this:

Each Contact changes independently, so there are four different combinations in this case.


text:
Q: How to repeat the header (Grey area) in apache POI
I am creating the table with apache POI . I need to repeat the header in the word.
This question is a follow up question of that question: How to split the row in apache POI header. There the used code is given in the accepted answer.

A: XWPFTableRow has a method XWPFTableRow.setRepeatHeader which controls whether to repeat a table's header row at the top of a table split across pages. So you need set that for each of your table header rows. This are the rows which also have the grey background, I guess.
So extend your code as follows:
...
  for (int row = 0; row < 4; row++) {
   for (int col = 0; col < 9; col++) {
    //table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
    if (row < 3) { // header rows
     table.getRow(row).getCell(col).setColor("D9D9D9"); // header rows color
     table.getRow(row).setRepeatHeader(true); // header rows shall repeat on new pages
    }
   }
  }
...

Complete example again:
import java.io.File;
import java.io.FileOutputStream;

import java.math.BigInteger;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

public class CreateWordTableMerge3 {

 static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) {
  for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
   XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
   CTVMerge vmerge = CTVMerge.Factory.newInstance();
   if(rowIndex == fromRow){
    // The first merged cell is set with RESTART merge value
    vmerge.setVal(STMerge.RESTART);
   } else {
    // Cells which join (merge) the first one, are set with CONTINUE
    vmerge.setVal(STMerge.CONTINUE);
    // and the content should be removed
    for (int i = cell.getParagraphs().size(); i > 0; i--) {
     cell.removeParagraph(0);
    }
    cell.addParagraph();
   }
   // Try getting the TcPr. Not simply setting an new one every time.
   CTTcPr tcPr = cell.getCTTc().getTcPr();
   if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
   tcPr.setVMerge(vmerge);
  }
 }

 //merging horizontally by setting grid span instead of using CTHMerge
 static void mergeCellHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
  XWPFTableCell cell = table.getRow(row).getCell(fromCol);
  // Try getting the TcPr. Not simply setting an new one every time.
  CTTcPr tcPr = cell.getCTTc().getTcPr();
  if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
  // The first merged cell has grid span property set
  if (tcPr.isSetGridSpan()) {
   tcPr.getGridSpan().setVal(BigInteger.valueOf(toCol-fromCol+1));
  } else {
   tcPr.addNewGridSpan().setVal(BigInteger.valueOf(toCol-fromCol+1));
  }
  // Cells which join (merge) the first one, must be removed
  for(int colIndex = toCol; colIndex > fromCol; colIndex--) {
   table.getRow(row).getCtRow().removeTc(colIndex);
   table.getRow(row).removeCell(colIndex);
  }
 }

 static void setColumnWidth(XWPFTable table, int row, int col, int width) {
  CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
  tblWidth.setW(BigInteger.valueOf(width));
  tblWidth.setType(STTblWidth.DXA);
  CTTcPr tcPr = table.getRow(row).getCell(col).getCTTc().getTcPr();
  if (tcPr != null) {
   tcPr.setTcW(tblWidth);
  } else {
   tcPr = CTTcPr.Factory.newInstance();
   tcPr.setTcW(tblWidth);
   table.getRow(row).getCell(col).getCTTc().setTcPr(tcPr);
  }
 }

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

  XWPFDocument document= new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The table:");

  //create table
  //4 rows 9 columns
  XWPFTable table = document.createTable(4,9);

  for (int row = 0; row < 4; row++) {
   for (int col = 0; col < 9; col++) {
    //table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
    if (row < 3) { // header rows
     table.getRow(row).getCell(col).setColor("D9D9D9"); // header rows color
     table.getRow(row).setRepeatHeader(true); // header rows shall repeat on new pages
    }
   }
  }

  //defining the column widths for the grid
  //column width values are in unit twentieths of a point (1/1440 of an inch)
  int defaultColWidth = 1*1440*6/9; // 9 columns fits to 6 inches
  int[] colunmWidths = new int[] {
   defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth,
   defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth, defaultColWidth
  };

  //create CTTblGrid for this table with widths of the 8 columns.
  //necessary for Libreoffice/Openoffice to accept the column widths.
  //first column
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[0]));
  //other columns
  for (int col = 1; col < colunmWidths.length; col++) {
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[col]));
  }

  //using the merge methods and setting the column widths
  //horizontally merge all columns in first row
  mergeCellHorizontally(table, 0, 0, 8);
  setColumnWidth(table, 0, 0, colunmWidths[0]+colunmWidths[1]+colunmWidths[2]+colunmWidths[3]
                              +colunmWidths[4]+colunmWidths[5]+colunmWidths[6]+colunmWidths[7]+colunmWidths[8]);

  //horizontally merge last two columns in second row
  mergeCellHorizontally(table, 1, 7, 8);
  setColumnWidth(table, 1, 7, colunmWidths[7]+colunmWidths[7]);

  //vertically merge row 2 and 3 in column 1 to 7
  for (int c = 0; c < 7; c++) {
   mergeCellVertically(table, c, 1, 2);
  }

  //add more rows to fill the page; note: for apache poi the table has only one column because of all the merging
  for (int row = 4; row < 50; row++) {
   XWPFTableRow tableRow = table.createRow();
   for (int col = 1; col < 9; col++) {
    tableRow.createCell();
   }
  }

  paragraph = document.createParagraph();

  FileOutputStream out = new FileOutputStream("create_table.docx");
  document.write(out);
  out.close();

 }
}


text:
Q: Find largest TRUE row number of each column in Matlab I have a binary image BW, and I want to find out the largest row number of each column. I know I can do it in a loop, and in each iteration I return max(find(BW(:,i))); as the row number in column i. But is there some simpler method to achieve this?
Note all the true values in BW are connected, I guess this may simplify the search process.
Thank you in advance.

A: Do the following vectorized thing instead. I think that's 30 characters.
  [~,idx]=max(flipud(BW), [], 1);

  result=(size(BW,1)+1) - idx;


text:
Q: SWIM protocol how does a new node get an address of an existing node in a cluster Background:
  I've been looking into microservices more specifically service discovery,
one thing thats interested me is the SWIM protocol. But I'm a little confused when it comes to new nodes joining the network.
How does a new node joining the cluster get an address of 1 or more nodes of the existing cluster, without their being a single point of faliure?
If you need any further information or have any questions just let me know.

A: please check out scalecube that implements microservices based on swim protocol with gossip protocol improvement
https://github.com/scalecube/scalecube
you can find references:
https://github.com/scalecube/scalecube/wiki/Distributed-Computing-Research
in general when new node joining to the network it joins one of the already running cluster nodes (seeds or members) and the cluster gossip about the new member and creating a "cluster" the gossip protocol "infects" the cluster with the membership information.
usually there is a set of nodes that serve as the entry point to the cluster called seeds and they can be a well known members or discovered using diffident methods such as dns name so when new member join the cluster it can look for a host name "seed" and that is resolved to its current or one of the seed ips.
in microservices architecture seeds can also be the api-gateways or specific nodes that act as seeds usually its best to choose the seeds as the members that least subject to changes and upgrades.
I have written a post discussing the topic
https://www.linkedin.com/pulse/swim-cluster-membership-protocol-ronen-nachmias/


text:
Q: ggplot2: Combine/merge legends of color and shape into one My code worked early, but the legends for shape and color become separated now.
## loading packages
library(tibble)
library(ggplot)
## an example of data
my_data <- tibble(x = seq(1:10),
                 y = rnorm(10, mean = 0, sd = 1),
                 z = rep(c("{ }^{2}*H", "{ }^{18}*O"), 5))

An example of a data set can be like this:
my_data
# A tibble: 10 x 3
       x       y z
   <int>   <dbl> <chr>
 1     1  0.631  { }^{2}*H
 2     2  1.43   { }^{18}*O
 3     3 -0.548  { }^{2}*H
 4     4 -1.42   { }^{18}*O
 5     5  1.72   { }^{2}*H
 6     6 -0.816  { }^{18}*O
 7     7  0.0297 { }^{2}*H
 8     8 -0.471  { }^{18}*O
 9     9 -0.565  { }^{2}*H
10    10  0.448  { }^{18}*O

When I wanted to draw a simple point-line plot, with the following code:
my_colors <- c("#00BFC4", "#F8766D")

ggplot(data = my_data,
       mapping = aes(x = x, y = y, color = z, shape = z)) +
  geom_point() +
  geom_line() +
  scale_color_manual(name = "",
                     labels = parse_format(),
                     values = my_colors) +
  scale_shape_manual(name = "",
                     labels = parse_format(),
                     values = c(16:17))

The legends are separated, as shown in the following figure:

But it was worked smoothly ealier, as shown in the following figure:

A: Here is my newest update. You can use as.expression and bquote
ggplot(data = my_data, mapping = aes(x = x, y = y, color = z, shape = z, group = z)) +
  geom_point() +
  geom_line() +
  scale_color_discrete(name = "", labels = c(as.expression(bquote({ }^{2}*"H")), as.expression(bquote({ }^{18}*"O"))))+
  scale_shape_discrete(name = "", labels = c(as.expression(bquote({ }^{2}*"H")), as.expression(bquote({ }^{18}*"O"))))


text:
Q: C# lambda expression joining 4 tables situation I am joining 4 tables (Productos, ProductosFotos, Marca, Categoria) to find the product by CategoriaId. The ProductoFotos table contains 3 images but I only need to show 1 of them. What do I need to do and not repeat the result for each image.
Here is my code:
var productoInCategoriaInDb = _productoRepository.GetAll()
            .Where(x => x.Publicado == true && x.CategoriaId == id)
            .GroupJoin(
                _productoFotoRepository.GetAll(), <-- here take only one image
                p => p.ProductoId,
                pf => pf.ProductoId,
                (p, pf) => new { p, pf })
            .SelectMany(
                p => p.pf.DefaultIfEmpty(),
                (p, pf) => new { p.p, pf })
            .GroupJoin(
                _marcaRepository.GetAll(),
                ppf => ppf.p.MarcaId,
                pm => pm.MarcaId,
                (ppf, pm) => new { ppf, pm })
            .SelectMany(
                ppfpm => ppfpm.pm.DefaultIfEmpty(),
                (ppfpm, pm) => new { ppfpm.ppf, pm })
            .GroupJoin(
                _categoriaRepository.GetAll(),
                ppfpm => ppfpm.ppf.p.CategoriaId,
                pc => pc.CategoriaId,
                (ppfpm, pc) => new { ppfpm, pc })
            .SelectMany(
                ppfpmpc => ppfpmpc.pc.DefaultIfEmpty(),
                (ppfpmpc, pc) => new ProductoBuscarViewModel
                {
                    Producto = ppfpmpc.ppfpm.ppf.p,
                    ProductoFoto = ppfpmpc.ppfpm.ppf.pf,
                    Marca = ppfpmpc.ppfpm.pm,
                    Categoria = pc
                }
            );

Update
Relational contraints diagram

A: This will work:
var productoInCategoriaInDb = from prod in _productoRepository.GetAll()
    join imag in _productoFotoRepository.GetAll()
        on p.ProductoId equals imag.ProductoId into imags
    from imag in imags.DefaultIfEmpty()
    join marca in _marcaRepository.GetAll()
        on prod.MarcaId equals marca.MarcaId into marcas
    from marca in marcas.DefaultIfEmpty()
    join cat in _categoriaRepository.GetAll()
        on cat.CategoriaId equals prod.CategoriaId into cats
    from cat in cats.DefaultIfEmpty()
    group new { prod, imag, marca, cat } by new { P = prod, M = marca, C = cat } into prodGroup
    select new ProductoBuscarViewModel(){
        Producto = prodGroup.Key.P
        ProductoFoto = prodGroup.FirstOfDefault().imag
        Marca = prodGroup.Key.M
        Categoria = prodGroup.Key.C
    }

This will generate a subselect with top(1) to get the first image of all with the same product. I proved it in LinqPad with similar entities. I usually put a bit field in the ProductoFoto entity to set the 'default' image of a Proveedor. Then filter the _productoFotoRepository.GetAll() to get only the default image. With that you dont need to call to a group by and the query will execute faster.


text:
Q: How to represent a integer by a chain of 8 bit numbers I am wondering how you can represent an integer as a chain of 8-bit numbers.
That is, (and I don't know how to actually calculate this so the example is wrong, but should demonstrate the basic idea), say you have an integer of arbitrary size, meaning it can be extremely large like Math.pow(100, 100) ≈ 1e+200 or some small number like 1 or 0. You want to be able to compute that number by using a chain of 8-bit values. The question is how to do that.
For example, I can represent 255 like this:
[ 255, 1 ]

That is, our representation has the first value be 8-bits, and then the second value is also 8-bits, and we multiply them together as 255 * 1 = 255. Another case would be 256. We could represent that like this:
[ 255, 1, 1 ]

Meaning (255 * 1) + 1 = 256, but now we don't necessarily know what to add vs. what to multiply. Imagine a large number like 1589158915. I have no idea what it's array of values would be, but say they ended up being like this:
[ 15, 12, 1, 141, 12, 250 ]

And say that from those numbers we could compute the value like this:
15 * 12 + 1 * 141 / 12 - 250

That wouldn't be very ideal, unless perhaps the system also stored the operation with the value, like this:
[ 15, 2, 12, 0, 1, 2, 141, 3, 12, 1, 250 ]

But I have no idea where to begin to figure out how to calculate the number like this, or how to say "given some integer, figure out how to break it apart into some equation that will generate its value". That is the basis of the question. I guess (actually) this would probably be the best approach.
As a sidenote, you can't take the integer 1589158915 and just represent it like this:
[ 1589158914, 1 ] == (1589158914 + 1)

because 1589158915 is not an 8-bit value. This is why it's tricky. In addition, we don't want to do it like this:
[ 255, 255, 255, 255, ... ]
==
255 + 255 + 255 + 255 + ...

Because that would be very inefficient. The solution should be a compact representation.
So the question is, how to take an integer and create an equation from it that will generate its value, where each component of the equation can be represented as an 8-bit integer.

A: So, here's the conversion to and from the 256 system:

const To256 = x => {
  var res = [];
  while (x > 0) {
    res.push(x % 256);
    x = Math.floor(x / 256)
  }
  return res;
}

const From256 = x => {
  var res = 0;
  while (x.length) res = 256 * res + x.pop();
  return res;
}

var t = 9483593483;
console.log(t);
t = To256(t);
console.log(t);
t = From256(t);
console.log(t);

Note that the array is in reverse order.

A: It sounds like you're essentially describing base-256 arithmetic, although in a kind of circuitous way. Given some list of integers [a, b, c, d] you could compute the number they represent as (parentheses added for clarity):
a*(256**3) + b*(256**2) + c*(256**1) + d*(256**0)

The power to use for the 256 base is determined by the position of the integer in the list. Using this scheme, your example number of 15809158915 could be represented as:
[3, 174, 76, 159, 3]
# 3*256**4 + 174*256**3 + 76*256**2 + 159*256**1 + 3*256**0

This can of course extend to any arbitrarily-sized list. Of course, you could always write out the list of integers in their hexadecimal form instead of base-10:
[0x3, 0xae, 0x4c, 0x9f, 0x03]

Taking things further, you could write the list out as a string with a single 0x prefix to identify the entire string as a hexadecimal number:
0x3ae4c9f03

And voila: you've now duplicated python's hex() function!
>>> hex(15809158915)
'0x3ae4c9f03'

And since python already supports arbitrarily-sized integers, you can represent really, really big numbers this way:
hex(861324987629387561923756912874369128734619287346921367419273)
'0x89378c76db3e9b3e808eea75a42d7ff7d43840e0f41cf43989L'

The "L" at the end of the string indicates that this is a "long" integer, meaning python has engaged its arbitrarily-sized integer support behind the scenes.
In summary, all modern PCs represent numbers internally as a chain of 8-bit integers. 32-bit ints are a chain of 4 8-bit integers, 64-bit ints are a chain of 8 8-bit integers, etc.
If you get a tiny bit fancier, you can represent negative numbers using twos-complement, or floating point numbers using IEEE-754. (Note that I'm ignoring endianness for now.)


text:
Q: Flagging makes comment meaningless With relation to this Question which is about editing the question makes a comment meaningless, today I saw another situation where when a comment was flagged and deleted comments following the flagged comment, became meaningless as in this question.
In that scenario, after Jon Skeet's comment (2nd comment), other comments address the now deleted 3rd comment by the OP, which insulted one of the commentors. And since it is deleted, those comments following it, make no sense.
How can we avoid such a situation?

A: Just as stated in the other meta question, flag as obsolete the comments that depend on the rude comment for context. Or if there are too many such comments and you don't want to flag them all, flag the question itself and inform us of the overall situation.
You don't have to do it now, though, as I've already taken care of it.


text:
Q: Insert html into div with angular keeping ui-router ui-sref property working Here is my case:
I have a div which needs to get some html injected from a function:

in my controller I have:
this.getMyLink = function () {
    return 'my link';
}

It works but not at all. All I have at the end in my html is only
my link

It's a link but the ui-sref redirection is not working.
There is surely something I'm missing.
How can I fix that?

A: ng-bind-html does not work with ui-sref directive. Just use href="path/to/state1" instead

A: The content inside ng-bind-html doesn't get compiled by angular, it is intended for static html.
You would need to use your own directive instead and either set a template or do your own compiling with $compile.
Alternatively you might be able to use ng-include. There aren't enough details given for your use case to help much more


text:
Q: XML Parsing error in Swift I'm trying to "modernize" one of our apps that takes XML data from NOAA.  The existing app, using this "simple XML to NSDictionary converter" (http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/) works like a champ.  Because it works and because I'm aiming for the rebuilt app to be converted to Swift as much as possible, I attempted a faithful conversion of that XML to NSDictionary code.  Unfortunately, I'm getting NSXMLParserErrorLineNumber=1, NSXMLParserErrorColumn=47, NSXMLParserErrorMessage=Space required after the Public Identifier.
The URL of the XML source is http://forecast.weather.gov/MapClick.php?FcstType=digitalDWML&lat=40.501368&lon=-79.865723  I'd love to skip the XML option just to avoid the headaches, but NOAA's not consistent with what it presents in the different data formats (DWML, XML, JSON).
Any ideas where I'm messing up?
The code that calls the object below is:
    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Task completed")
        if(error) {
            // if there is an error in the request, print it to the console
            self.delegate?.didCompleteWithError(error.localizedDescription)
            //println(error.localizedDescription)
            println("oops!")
        }
        var err: NSError?
        if self.responseFormat == "JSON" {
            // blah blah blah ... the code here does work fine. Snipped for brevity
        } else if self.responseFormat == "XML" {
            // Put XML parsing code here
            var error = NSError()
            var xmlReader = XMLDictionary(error: error)
            var xmlResult = xmlReader.dictionaryForXMLData(data, error: error) as NSDictionary
            self.delegate?.didCompleteWithDictionary(xmlResult)
        }

The "XML to NSDictionary converter:
//
//  XMLDictionary.swift
//
//

import Foundation

class XMLDictionary: NSObject, NSXMLParserDelegate {

    var dictionaryStack = NSMutableArray()

var textInProgress = ""
let XMLReaderTextNodeKey = "text"
var errorP = NSError()

func dictionaryForXMLData(data: NSData, error: NSError) -> NSDictionary {
   var reader = XMLDictionary(error: error)
    return reader.objectWithData(data, error: error) as NSDictionary
}

func dictionaryForXMLString(string: String, error: NSError) -> NSDictionary {
    var data : NSData = string.dataUsingEncoding(NSUTF8StringEncoding)
    return dictionaryForXMLData(data, error: error)
}

init(error: NSError) {
    self.errorP = error
}

func objectWithData(data:NSData, error:NSError) -> NSDictionary {
    // clear out any old data
    dictionaryStack.removeAllObjects()
    textInProgress = ""

    // Initialize the stack with a fresh dictionary
    dictionaryStack.addObject(NSMutableDictionary())

    // Parse the XML
    var parser = NSXMLParser(data: data)
    parser.delegate = self

    // some more needed
    var success:Bool = parser.parse()

    if success {
        println("parse success!")
    } else {
        println("parse failure!")
    }

    // Return the stack's root dictionary on success
    var resultDict : NSDictionary! = dictionaryStack[0] as NSDictionary
    NSLog(" in parser: %@", resultDict)
    return resultDict as NSDictionary

}

func parser(parser: NSXMLParser!,didStartElement elementName: String!, namespaceURI: String!, qualifiedName : String!, attributes attributeDict: NSDictionary!) {

    // Get the dictionary for the current level in the stack
    var elementCount = dictionaryStack.count - 1
    if elementCount < 0 {
        elementCount = 0
    }
    NSLog("element: %d", elementCount)
    var parentDict = dictionaryStack[elementCount] as NSMutableDictionary

    // Create the child dictionary for the new element and initialize it with the attributes
    var childDict = NSMutableDictionary()
    childDict.addEntriesFromDictionary(attributeDict)

    // If there's already an item for this key, it means we need to create an array
    var existingValue : AnyObject? = parentDict[elementName]! as AnyObject
    if let eValue : NSMutableArray = existingValue as? NSMutableArray {
        var array = NSMutableArray()
        if eValue.isKindOfClass(NSMutableArray) {
            // The array exists, so use it
            array = eValue
        } else {
            array.addObject(eValue)
            // Replace the child dictionary with an array of children dictionaries
            parentDict.setObject(array, forKey: elementName)
        }

        // Add the new child dictionary to the array
        array.addObject(childDict)
    } else {
        // No existing value, so update the dictionary
        parentDict.setObject(childDict, forKey: elementName)
    }

    // Update the stack
    dictionaryStack.addObject(childDict)

}

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {

    // Update the parent dict with text info
    var elementCount = dictionaryStack.count - 1
    if elementCount < 0 {
        elementCount = 0
    }
    var dictInProgress = dictionaryStack[elementCount] as NSMutableDictionary

    // Set the text property
    if countElements(textInProgress) > 0 {
        // Get rid of leading + trailing whitespace
        dictInProgress.setObject(textInProgress, forKey: XMLReaderTextNodeKey)

        // Reset the text
        textInProgress = ""

    }

    // Pop the current dict
    dictionaryStack.removeLastObject()

}

func parser(parser: NSXMLParser!, foundCharacters string: String!) {
    // Build the text value
    textInProgress += string
}

func parser(parser: NSXMLParser!, parseErrorOccurred parseError: NSError!) {
    self.errorP = parseError
    NSLog("failure error: %@", parseError)
    }
}

Thanks
EDIT:  Added other file's code as requested.
//
//  GovDataRequest.swift
//
//
//  Created by Michael Pulsifer (U.S. Department of Labor) on 6/18/14.
//  License: Public Domain
//

import Foundation

protocol GovDataRequestProtocol {
    func didCompleteWithError(errorMessage: String)
    func didCompleteWithDictionary(results: NSDictionary)
}

class GovDataRequest {

    var delegate: GovDataRequestProtocol? = nil

    var APIKey = ""
    var APIHost = ""
    var APIURL = ""
    var responseFormat = "JSON"
    var timeOut = 60.0

    init(APIKey: String, APIHost: String, APIURL:String) {
        self.APIKey = APIKey
        self.APIHost = APIHost
        self.APIURL = APIURL
    }

    func callAPIMethod (#method: String, arguments: Dictionary<String,String>) {
        // Construct the base url based on the provided information
        var url = APIHost + APIURL + "/" + method
        // Start building the query string
        var queryString = ""

        // Where appropriate, add the key
        switch APIHost {
        case "http://api.dol.gov":
            queryString = "?KEY=" + APIKey
        case "http://api.census.gov", "http://pillbox.nlm.nih.gov":
            queryString = "?key=" + APIKey
        case "http://api.eia.gov", "http://developer.nrel.gov", "http://api.stlouisfed.org", "http://healthfinder.gov":
            queryString = "?api_key=" + APIKey
        case "http://www.ncdc.noaa.gov":
            queryString = "?token=" + APIKey
        default:
            // do nothing for now
            println("doing nothing for now")
        }

        //Construct the arguments part of the query string
        for (argKey, argValue) in arguments {
            switch APIHost {
            case "http://api.dol.gov":
                // DOL's V1 API has specific formatting requirements for arguments in the query string
                switch argKey {
                case "top", "skip", "select", "orderby", "filter":
                    queryString += "&$" + argKey + "=" + argValue
                case "format", "query", "region", "locality", "skipcount":
                    queryString += "&" + argKey + "=" + argValue
                default:
                    println("nothing to see here")
                }
            case "http://go.usa.gov":
                // go.usa.gov requires that the apiKey be the 2nd argument
                if countElements(queryString) == 0 {
                    queryString += "?" + argKey + "=" + argValue + "&apiKey=" + APIKey
                } else {
                    queryString += "&" + argKey + "=" + argValue
                }
            default:
                if countElements(queryString) == 0 {
                    queryString += "?" + argKey + "=" + argValue
                } else {
                    queryString += "&" + argKey + "=" + argValue
                }
            }

        }

        //If there are arguments, append them to the url
        if countElements(queryString) > 0 {
            url += queryString
        }

        //DOT FMCSA requires that the key be placed at the end.
        if APIHost == "https://mobile.fmcsa.dot.gov" {
            if countElements(queryString) > 0 {
                url += "&webKey=" + APIKey
            } else {
                url += "?webKey=" + APIKey
            }
        }

        /*
            ASSUMPTION: data retrieved is in JSON format.
            TODO: consider situation when XML is received.
        */

            // Send the request to the API and parse
            var urlToPackage = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
            println(urlToPackage)
            var urlToSend: NSURL = NSURL(string: urlToPackage)
            var apiSessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
            apiSessionConfiguration.timeoutIntervalForRequest = timeOut
            var session = NSURLSession(configuration:apiSessionConfiguration)
            var request = NSMutableURLRequest(URL:urlToSend)
            request.addValue("application/json",forHTTPHeaderField:"Accept")
            var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
                println("Task completed")
                if(error) {
                    // if there is an error in the request, print it to the console
                    self.delegate?.didCompleteWithError(error.localizedDescription)
                    //println(error.localizedDescription)
                    println("oops!")
                }
                var err: NSError?
                if self.responseFormat == "JSON" {
                    var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
                    if(err?) {
                        // If there is an error parson JSON, print it to the console
                        NSLog ("Error parsing the JSON")
                    }
                    self.delegate?.didCompleteWithDictionary(jsonResult)
                } else if self.responseFormat == "XML" {
                    // Put XML parsing code here
                    var error = NSError()
                    var xmlReader = XMLDictionary(error: error)
                    var xmlResult = xmlReader.dictionaryForXMLData(data, error: error) as NSDictionary
                    self.delegate?.didCompleteWithDictionary(xmlResult)
                }
                })
            task.resume()
    }

}


text:
Q: Why is the request event being fired twice I have a server which looks like this:
const http2 = require('http2');
const {
    HTTP2_HEADER_METHOD,
    HTTP2_HEADER_PATH,
    HTTP2_HEADER_STATUS,
    HTTP2_HEADER_CONTENT_TYPE
  } = http2.constants;

const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('./ssl/localhost-privkey.pem'),
  cert: fs.readFileSync('./ssl/localhost-cert.pem')
});

server.on('error', (err) => {
    console.error(err);
});

server.on('stream', (stream, headers,flags) => {
  stream.respond({
    'content-type': 'text/html',
    [HTTP2_HEADER_STATUS]: 200,
    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'
  });
  stream.end('
Hello World 2
');
});

server.on('request', (msg) => {
  /* THIS IS BEING FIRED TWICE*/
   console.log('request:' + JSON.stringify(msg) );
});

server.on('session', (msg) => {
 /* THIS IS ALSO BEING FIRED TWICE*/
    console.log('session:' + JSON.stringify(msg) );
});

 server.listen(8443);

From my browser I type into the url https://myserver:8443. On my server I can see the session event is consoled log twice. Why is this happening since I am only making one request? As well everytime I refresh the page the request event is being fired twice instead of only once. I am using nodejs 11.0.0

A: You should log the URL that is being requested with console.log(msg.url).  You will likely find that one of the requests is for the favicon.ico as this is something that a browser will request when it doesn't already have a favicon cached for a particular domain.
All requests of a web server have to look at the actual resource being requested and respond appropriately based on the exact resource being requested.


text:
Q: Can we create a stored procedure to copy detached .mdf and .ldf files from original location to new location? I am trying to create a script to attach database, move .mdf and .ldf files to new location and then attach the database. I created a stored procedure to detach and attach the database. Can I get a suggestion as to how I can move the files from the script itself?
Use master;
Go
Create procedure User_sp_detach_attach
    @db_name varchar(max),
    @new_mdf_path varchar(max),
    @new_ldf_path varchar(max)
As
Set NoCount On;
declare @db_id smallint;
declare @mdf_file varchar(max);
declare @ldf_file varchar(max);
declare @ori_mdf nvarchar(max);
declare @ori_ldf nvarchar(max);
declare @new_mdf_file nvarchar(max);
declare @new_ldf_file nvarchar(max);
declare @sql varchar(max);
set @db_id=DB_ID(@db_name);
set @mdf_file=@db_name+'.mdf';
set @ldf_file=@db_name+'_log.ldf';
select @ori_mdf=physical_name from sys.master_files where database_id=@db_id and file_id=1;
select @ori_ldf=physical_name from sys.master_files where database_id=@db_id and file_id=2;
set @new_mdf_file=@new_mdf_path+'\'+@mdf_file;
set @new_ldf_file=@new_ldf_path+'\'+@ldf_file;
print 'New location of .mdf file: '+@new_mdf_file;
print 'New location of .ldf file: '+@new_ldf_file;
EXEC sp_detach_db @db_name;
--Move files
Set @sql='CREATE DATABASE ' + @db_name + ' ON (FILENAME=''' + @new_mdf_file + '''), (FILENAME=''' + @new_ldf_file + ''') FOR ATTACH;'
Print @sql;
Exec (@sql);
Print 'Moved and attached successfully';
Go

A: Well you can use xp_cmdshell, write (or find and use) a CLR routine to do file copies and things like that. For example, the unrecomnended use of xp_cmdshell.
EXEC xp_cmdshell "COPY \\share\path\file.mdf \\othershare\otherpath\file.mdf"

However, you would be better just making a backup (which from SQL Server 2008 R2 supports compressed backups) and you will get a faster transfer than detaching and copying files.  Not to mention the risks of detaching a file and not being able to reattach.
Recommendation: Use BACKUP and RESTORE.


text:
Q: Adjust MatLab window focus I've done some searching regarding this question but no luck so far, and I'm hoping somene here can help me out.
I'm using MatLab's Editor, but when I run the program, the console is in the main window. Is there a way I can make MatLab open its main window just below the Editor window?
For example, I'm on Chrome and then I open the Editor and run the program. But the main window is still hidden below Chrome. Is there any way I can configure it so that any time I open any MatLab window it makes sure that the main window is below that one?
Please let me know if I didn't make myself clear, and sorry for bad english!
Thanks in advance

A: It sounds like you want to "dock" your window.
There is a little curly arrow in the top right hand corner of each window (pointing to the right and down when the window is floating, if I recall correctly). If I understand your question correctly, that would solve it for you..


text:
Q: Renaming child items after moving til another directory - powershell I have been handed over a Powershell script that searches a folder for new items, if there are any items, it sends an email with the items attached and moves them to another directory. However, my problem is that the files in the first directory will always be named the same so i would need to rename the files as i move them to the back-up directory with date and time to prevent the older files from being overwritten. How would i go about the code to do so?
I should probably add that i have no experience with powershell, hence the probably stupid question.
$Folders = @( 'C:\Users\PAT\Desktop\attachement testfolder'
                )
$DestFolder = 'C:\Users\PAT\Desktop\Backup folder'

$EmailList = @( 'recieving-email@hotmail.com'
             )

$From       = 'pat@email.com'
$Subject    = 'New files'
$SMTPServer = '111.111.111.111'

#  Get new files
$NewFiles = $Folders | Get-ChildItem -File -Recurse

#  If there are an new files...
If ( $NewFiles )
{
#  Add the file count and file names to the body of the email
$Body = '$($NewFiles.Count) new files attached'
$NewFiles | ForEach { $Body += $_.Name + "" }

#  Send the email with attachments
Send-MailMessage -From $From -To $EmailList -Subject $Subject -Body $Body -
BodyAsHTML -Attachments $NewFiles.FullName -SmtpServer $SMTPServer

#  Move the emailed files to the destination folder
$NewFiles.FullName | Move-Item -Destination $DestFolder -Force
}

A: Ended up figuring it out
I changed the Move-Item with this code
#  Rename files with current date and time and moves them to backup directory
$NewFiles | ForEach-Object {
Move-Item -Path $_.FullName -Destination "C:\Users\PAT\Desktop\Backup
mappe\$($_.BaseName,(Get-Date).ToString("MMddyyyy hhmmss"),$_.Extension)"}

A: Also, as an alternative:
$NewFiles | Rename-Item -NewName { "$(Get-Date -Format "yyyyMMddHHmmss")-$($_.Name)" } -PassThru | Move-Item -Destination $DestFolder


text:
Q: Complex find in Ruby on Rails to match equivalent render I'm trying to do a find in Ruby on Rails that matches this render:
render :json => user.friendships.visible,
       :only => [],
       :include => [{:friend => {:except => [:password]}}, :status]

So basically get all friendships from a user that are visible, but with none of the association table.  I just want the friend object (except the password) and the status.  This works fine when rendering but I'm not sure how to do a find to get all the same info.  All I can ever get back are the friendships rows which just define the association.  I'm just trying to get these back and store them in a variable.  So I can't render them just yet.  Maybe find isn't what I'm looking for.
The visible property is a defined scope on friendships.

A: This should return an array of the visible friends for a given user:
user.friendships.visible.includes(:friend).map(&:friend)

I'm writing this off the cuff without knowing exactly what your models look like, or what your use case is.


text:
Q: PHP catch a failed include I'm trying to include a file, and catch it if the file does not exist / can not be opened. I would have thought that a simple try/catch statement would have worked but PHP seems to completely ignore it, and error out.
Any ideas? I know there are other questions like this on stackoverflow, I've seen them, but none of them seem to have a proper, working answer.

A: Since include() returns false when fails, just check if it returns true and then do something like die() or show an error.
if (!include('page.php'))
   die('Error.');

A: You can check the return value of include to see if it failed or not:
if((@include $filename) === false)
{
    // handle error
}

You'll note I included the error suppression operator (@ ) to hide the standard error messages from being displayed.


text:
Q: Cant select any options with Eclipse I'm having a problem with Eclipse: I have just installed it in my mac, and I can't select any option in the file or edit header or any header in the top:

I have uninstalled and installed a few times both, Eclipse IDE for Java Developers and Eclipse IDE for Java EE Developers now, and many different versions and its still not working.
Do you guys have any solutions for my problem?

A: This is a known issue with recent versions of macOS, see https://www.eclipse.org/org/press-release/20170925criticalbug.php. There's a workaround described in the page, but you can also upgrade your Eclipse to the just released Oxygen.1a version, which contains a fix for that issue the does not require a workaround.


text:
Q: The tabhost and fragment combination transaction throw error expection in android There are a tab host in my app. it uses an fragment activities and contain 5 tabs (fragment)
In the 3rd tab , there is a button, when I click on it , it will go to another fragment, which is to replace the original fragment
gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                tracker.send(MapBuilder.createEvent("click_button","Gallery","Gallery_select_" + Utility.getLocale(getActivity()),null).build());
                Bundle bundle = new Bundle();
                bundle.putSerializable("imageObj", images.get(position));
                Fragment newFragment = (Fragment) new GalleryDetail();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                newFragment.setArguments(bundle);
                transaction.replace(R.id.tabcontent, newFragment,"gallery_detail");
                transaction.addToBackStack("gallery_detail");
                transaction.commit();
            }
        });

Then the problem will happen in this flow:
1) open the 3rd tab
2) click on the button go to the next level fragment
3) click on the other tab e.g. 1st tab
4) return to the 3rd tab (at this time , it will in the next level fragment instead of the first level)
5) press back button
 02-19 02:16:46.427: E/AndroidRuntime(27697): java.lang.IllegalStateException: Fragment already added: PhotoGallery{43bc3500 #1 id=0x7f04003b Gallery}

How can I return the first level if I exit from the 3rd tab? I believe this will fix the problem ? Thanks for helping

A: You can try to replace replace() method with a pair of add() and remove() method. Or you may try to use SupportFragmentManager


text:
Q: Hiding a form from user in c# windows application I have form, which i dont want the user to see it. "Dont ask me why :)"
I am using the following to achive it.
        this.ClientSize = new System.Drawing.Size(1, 1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.Name = "Logout";
        this.Opacity = 0;
        this.ShowInTaskbar = false;
        this.Text = "Logout";
        this.ResumeLayout(false);

But, when i press Alt + Tab it is showing the form in the list.
I want to hide that too from the user.
Possible ? How ? Thanks.
Okay, okay guys....i can share why... This is a logout form. Since the requirement is like logging out of application when the user pressed ctrl + Alt + Q, i need to use the KeyPress event handler which can be done only in a windows form. So i used a invisible form to achieve this. Got it..:) Thanks. Now please help me on this.

A: Hide Form from Alt+Tab
Ultimate question:
Why do you need this?


text:
Q: Need help "sanitizing" a custom function that pulls category slug into body class Not sure if "sanitizing" is really the correct phrase to use for this but it was the best one I could think of...anyways, here is the problem:
My function works great like so...
// add category id to body & post classes
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes [] = $category->cat_name;
        return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');

That works great until the user inputs a category such as "Category 1" with a space. Spaces are obviously not desirable as CSS classes so if we could maybe just have a dash added to replace the space that would be perfect - just not sure how to accomplish that?
Thanks!

A: sanitize_html_class sanitizes a html classname to ensure it only contains valid characters.
foreach((get_the_category($post->ID)) as $category)
    $classes [] = sanitize_html_class($category->cat_name);

A: sanitize_title_with_dashes should do the trick.
Example:
foreach((get_the_category($post->ID)) as $category)
    $classes [] = sanitize_title_with_dashes($category->cat_name);

A: Just use $category->slug instead of $category->cat_name. Slugs are already lowercase and with dashes instead of spaces.


text:
Q: Kubernetes NodePort - Ufw/Iptables ignored? I opened a Kubernetes NodePort on a machine and blocked all traffic to this port with the following rule:
sudo ufw deny 30001

But I can still access that port via browser. Is it common? I can't find any information on that in the docs.

A: Finally found the issue: kube-proxy is writing iptables rules (https://kubernetes.io/docs/tasks/debug-application-cluster/debug-service/#is-kube-proxy-writing-iptables-rules) which are catched before the ufw rules one added manually. This can be confirmed by checking the order in the output of iptables -S -v.