text:
Q: Why are coefficient and standard errors zero? I am having a problem with OLS regression. I am doing a relative time model (leads and lags model) to prove the robustness of my Difference in differences model. Problem is that some of my coefficients and standard errors are having 0 value. I think it means that there's something wrong with the model but I don't know what's causing the problem. Here are the results.

dist_5 is when the treatment effect first appeared. I want to prove that there is a positive significant effect starting from dist_5 (lags) and no significant effect on the leads.
Thank you
+) I'm running the model with python and the result is too long to attach so I had to cut the rest of the coefficients.
These are the coefficient of each parameters;

and these are the standard error of the parameters;

This is what the result summary looks like (not full result);

A: The standard errors of your estimated coefficients
The standard errors of your estimated coefficients, $\hat\beta$, are estimated according to:
$$\widehat{s.e.}(\hat\beta_j
) = \sqrt{s^2(X^TX)_{jj}^{-1}}$$
where $s^2$ is an estimate of the deviation/variance of the noise and $X$ is the matrix of your regressors.

*

*In other words the standard error of the coefficient $\beta_j$ scales with the inverse of the root mean square of the column/regressor $X_j$. (you should be able to verify this easily which helps you with debugging)

*Note that these are marginal errors and the formula can be generalized to provide a covariance matrix of the variance of the estimated coefficients. If there is correlation then the marginal errors might be very large but will not reflect the distribution of error correctly

Example of direct (manual) computation of standard error of coefficients
Computational example (in R, but I hope that the annotations make it clear for you to turn it into python code):
###
### creating data
###
set.seed(1)

### matrix with three columns
x <- cbind(c(1,1,1,1,1,1),
           c(1,2,3,4,5,6),
           c(0,0,0,1,1,1))

### some output based on the second column
### with added normal distributed noise with sigma=0.1
y <- x[,2] + rnorm(6,0,0.1)

### computing the model with the standard lm function
mod <- lm(y~0+x)
summary(mod)

### computing the std.err manually based on
### sd of the residuals
### the inverse (using the function solve) of the matrix product t(x)*x
### a correction sqrt(5/3) because the residuals should be based on n-p degrees of freedom and not n-1
###                                                                (and we have p=3, three parameters)
sd(residuals(mod))*sqrt(solve(t(x) %*% x)[c(1,5,9)])*sqrt(5/3)

output lm function:
> summary(mod)

Call:
lm(formula = y ~ 0 + x)

Residuals:
       1        2        3        4        5        6
-0.08565  0.06098  0.02467  0.05709 -0.00386 -0.05323

Coefficients:
   Estimate Std. Error t value Pr(>|t|)
x1  0.08863    0.08888   0.997 0.392139
x2  0.93438    0.03848  24.279 0.000153 ***
x3  0.27629    0.13145   2.102 0.126334
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.07697 on 3 degrees of freedom
Multiple R-squared:  0.9998,    Adjusted R-squared:  0.9996
F-statistic:  5126 on 3 and 3 DF,  p-value: 4.625e-06

output manual:
> sd(residuals(mod))*sqrt(solve(t(x) %*% x)[c(1,5,9)])*sqrt(5/3)
[1] 0.08887551 0.03848422 0.13144865

This above code shows where those standard errors 0.089, 0.038, 0.131 come from.

Check the root mean square size of your regressors
So in your situation you probably have some very large (root mean squared) size for several of the columns/regressors $\vert X_j \vert$. And that is why the parameters (and the estimated error) have such low values.
(I would also suspect that there might be some computational errors, however this is difficult to inspect with the given information. Anyway, at least you can now verify with this answer whether it is the standard case, ie. the relation with $X^TX$)
In addition: Possibly you might want to do a mixed effects model? Those fixed effects per user do they make sense to be considered fixed effects, or can we more specifically regard them as following a normal distribution?


text:
Q: Change workspace directory of eclipse to www I have Ubuntu 12.04 installed.
I have Eclipse Indigo installed.
I have LAMP installed, with the localhost being /var/www.
However, my Eclipse workspace location is /workspace.
How can I change it to /var/www same as localhost for the reasons of when I set up a project, the folder automatically is viewable via localhost on the browser.
I have tried just setting up a second workspace to /var/www. But it gives me the error:
The folder /var/www/.metadata is read-only

A: This is a permissions issue. There are several workarounds for that.

*

*sudo chmod 777 /var/www : Works definitely if its a permissions issue, but to be used with caution. It is not advisable, since that would be compromising security.

*ls -l /var |grep www , look at the group, and add yourself to that group, and then sudo chmod g+rwx /var/www. you may also create a new group and add yourself to it, then sudo chgrp <newGrp> /var/www and then sudo chmod g+rwx /var/www

*sudo chown <yourUserName> /var/www : Better than 777'ing, but not so elegant.

If you have a choice, I recommend the second one. Its the most elegant way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fats' words were fairly persuasive
(1) Andrew's words were persuasive.
  (2) Fats' words were fairly persuasive.

Sentence (1) is a preposition; in (2) adverb, fairly, is added. Whose words were more persuasive to the speaker, if the speaker the same one?
In this contrast, '(3) he is a liar,' and '(4) he must be a liar,' the former must be stronger, Applied to this, (1) could be more persuasive. But is that really so?

A: How persuasive would depend on the context. There's no absolute answer, unless the two forms were used side-by-side.
Fats must be fairly persuasive to convince you that he runs marathons on weekends.
There, "fairly" is an intensifier, like "quite" or "rather".
 Did you do well on the test?
 -- I did fairly well.

There, "fairly"  might mean a good performance, but not as good a performance as hoped. It isn't a foregone conclusion that one could substitute "quite" or "rather" for "fairly" there.
It would depend on the intonation pattern.
I did fáirly well.   (I could have done better. I'm disappointed.)

I did fairly wéll.   (I did quite well. I'm pleased.)


text:
Q: React & Fetch async/await... Why I'm receiving a promise? I'm having some troubles about react, fetch and async/await.
I have this code as a fetch wrapper:
export const fetcher = (url, options = null) => {

  const handle401Response = error => {
    throw error;
  }

  const isResponseValid = response => {
    if (!response.ok)
      throw response;
    else
      return response.json();
  }

  return fetch(url, { ...options, credentials: 'include' })
    .then(isResponseValid)
    .catch(handle401Response);
}

Then I define some API calls functions like:
export const getGroups = (id = null) => {
  return fetcher(`${API_GROUP_URL}${id !== null ? `?id=${id}` : ''}`);
}

And then I try to use it like:
export function SomeComponent(props) {

  const groups = async () => {
    try {
      const ret = await getGroups();
      return ret;
    } catch (err) {
      console.log(err);
    }
  };

  console.log(groups());

  return
Component

}

The result in console is: Promise{}.
I have read docs about async/await but can't understand why await is not waiting for promise to end.
Thanks in advance!

A: Async functions always return a promise. The time when you call that function it will give you back a promise instantly. You have used await inside the function and it is waiting for getGroup promise.
In normal javascript function console.log(await) this will fix the issue but in react you have to do it inside a another function because you cant make react components async (at least not in React 17 and below)

A: export function SomeComponent(props) {

  const [data, setData] = useState()

  const groups = async () => {

  };

  useEffect(() => {

    const fetchData = async () => {
    try {
      const ret = await getGroups();
      // process and set data accordingly
      setData(ret)
    } catch (err) {
      console.log(err);
    }
    }

    // fetch data inside useEffect
    fetchData()

  }, [])

 // console.log(groups());

  return
Component {data?.prop}

}

Hope this gives you an idea on how to fetch in a functional component


text:
Q: Support Multidex Android studio Below 5.0 Multidex: Dex Loader] Unable to execute dex: method ID not in [0, 0xffff]: 65536

A: By adding below line will solve this issue.
    dependencies {
      compile 'com.android.support:multidex:1.0.+'
     }


text:
Q: Apache ActiveMQ - Transport Connection to: tcp:/ failed: java.io.EOFException /java.net.SocketException: Software caused connection abort: recv failed I am using following configuration for ActiveMQ:
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <value>file:${activemq.conf}/credentials.properties</value>
        </property>
    </bean>

    <bean id="logQuery" class="io.fabric8.insight.log.log4j.Log4jLogQuery"
          lazy-init="false" scope="singleton"
          init-method="start" destroy-method="stop">
    </bean>
    <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}">

        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry topic=">" >
                  <pendingMessageLimitStrategy>
                    <constantPendingMessageLimitStrategy limit="1000"/>
                  </pendingMessageLimitStrategy>
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>
        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

        <persistenceAdapter>
            <kahaDB directory="${activemq.data}/kahadb"/>
        </persistenceAdapter>
          <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage percentOfJvmHeap="70" />
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>

        <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=90000&wireFormat.maxInactivityDuration=10000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=90000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=90000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=90000&wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=90000&wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

        <!-- destroy the spring context on shutdown to stop jetty -->
        <shutdownHooks>
            <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
        </shutdownHooks>

    </broker>

    <!--
        Enable web consoles, REST and Ajax APIs and demos
        The web consoles requires by default login, you can disable this in the jetty.xml file

        Take a look at ${ACTIVEMQ_HOME}/conf/jetty.xml for more details
    -->
    <import resource="jetty.xml"/>

</beans>
<!-- END SNIPPET: example -->

When I try to run on 61616 then I am getting following error constantly and ActiveMQ does not work or does not get started properly,
INFO   | jvm 2    | 2021/09/07 17:30:21 |  WARN | Transport Connection to: tcp://IP1:61040 failed: java.io.EOFException
INFO   | jvm 2    | 2021/09/07 17:30:37 |  WARN | Transport Connection to: tcp://IP2:61464 failed: java.net.SocketException: Software caused connection abort: recv failed
INFO   | jvm 2    | 2021/09/07 17:30:37 |  WARN | Transport Connection to: tcp://IP3:53301 failed: java.net.SocketException: Software caused connection abort: recv failed
INFO   | jvm 2    | 2021/09/07 17:30:51 |  WARN | Transport Connection to: tcp://IP4:51592 failed: java.io.EOFException
INFO   | jvm 2    | 2021/09/07 17:30:51 |  WARN | Transport Connection to: tcp://IP5:57330 failed: java.io.EOFException
INFO   | jvm 2    | 2021/09/07 17:31:05 |  WARN | Transport Connection to: tcp://IP6:51593 failed: java.io.EOFException

But when I try to run it on different port other than 61616 it works fine as there are no incoming requests on that port from any source.
Can anyone help me out here what could be the possible reason for this failure?


text:
Q: Laravel Javascript Working with Pagination i am using laravel V9 and have used an Excel eport javascript i found.
from here, credit to these people as it works well,
https://www.codexworld.com/export-html-table-data-to-excel-using-javascript/
but my issue is, i am using pagination, it gives you X rows per page and you click next to got the the net page, the script only downloads one page not the complete table, is there a way of being about to adjus the script to download the whole table,
`
function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';

    // Create download link element
    downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }
}

`
I have tried adjust the script myself and googling other functions to do this.


text:
Q: Container of pointers to derived class from template class with common ancestor as template argument

I have a super class that models a Measurement and two derived classes: PointCloudMeasurement and ImageMeasurement.
Another templated super class, Handler<MeasT> defines the interface to process the measurement.
Two handler classes, PointCloudHandler and ImageHandler specialize the Handler class with the corresponding measurement types as template arguments.
I would like to keep track of all the handlers using a container of pointers to the super class, and call the appropriate method depending on the derive type of handler at hand.
Here is the code (link):
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Measurement {
public:
  uint64_t time;
  virtual ~Measurement() {}
};

class PointCloudMeasurement : public Measurement {
public:
  uint64_t n_points = 64*1024;

};

class ImageMeasurement : public Measurement {
public:
  uint64_t n_pixels = 640*480;

};

template<class MeasT = Measurement>
class Handler {
public:
  virtual void addMeasurement(MeasT& m) = 0;
};

class PointCloudHandler : public Handler<PointCloudMeasurement> {
public:
  void addMeasurement(PointCloudMeasurement& m) override {
    std::cout << m.n_points << std::endl;
  }
};

class ImageHandler : public Handler<ImageMeasurement> {
  void addMeasurement(ImageMeasurement& m) override {
    std::cout << m.n_pixels << std::endl;

  }

};

int main(void){
  std::vector<std::unique_ptr<Handler<Measurement>>> handlers;

  handlers.push_back(std::make_unique<PointCloudHandler>());
  handlers.push_back(std::make_unique<ImageHandler>());

  PointCloudMeasurement pcm;
  ImageMeasurement im;

  handlers[0]->addMeasurement(pcm);
  handlers[1]->addMeasurement(im);
}

which gives me:
In function 'int main()':
50:59: error: no matching function for call to 'std::vector<std::unique_ptr<Handler<Measurement> > >::push_back(std::_MakeUniq<PointCloudHandler>::__single_object)'
50:59: note: candidates are:
In file included from /usr/include/c++/4.9/vector:64:0,
                 from 4:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<Handler<Measurement> >; _Alloc = std::allocator<std::unique_ptr<Handler<Measurement> > >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Handler<Measurement> >]
       push_back(const value_type& __x)
       ^
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note:   no known conversion for argument 1 from 'std::_MakeUniq<PointCloudHandler>::__single_object {aka std::unique_ptr<PointCloudHandler, std::default_delete<PointCloudHandler> >}' to 'const value_type& {aka const std::unique_ptr<Handler<Measurement> >&}'
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = std::unique_ptr<Handler<Measurement> >; _Alloc = std::allocator<std::unique_ptr<Handler<Measurement> > >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Handler<Measurement> >]
       push_back(value_type&& __x)
       ^
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note:   no known conversion for argument 1 from 'std::_MakeUniq<PointCloudHandler>::__single_object {aka std::unique_ptr<PointCloudHandler, std::default_delete<PointCloudHandler> >}' to 'std::vector<std::unique_ptr<Handler<Measurement> > >::value_type&& {aka std::unique_ptr<Handler<Measurement> >&&}'
51:54: error: no matching function for call to 'std::vector<std::unique_ptr<Handler<Measurement> > >::push_back(std::_MakeUniq<ImageHandler>::__single_object)'
51:54: note: candidates are:
In file included from /usr/include/c++/4.9/vector:64:0,
                 from 4:
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<Handler<Measurement> >; _Alloc = std::allocator<std::unique_ptr<Handler<Measurement> > >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Handler<Measurement> >]
       push_back(const value_type& __x)
       ^
/usr/include/c++/4.9/bits/stl_vector.h:913:7: note:   no known conversion for argument 1 from 'std::_MakeUniq<ImageHandler>::__single_object {aka std::unique_ptr<ImageHandler, std::default_delete<ImageHandler> >}' to 'const value_type& {aka const std::unique_ptr<Handler<Measurement> >&}'
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = std::unique_ptr<Handler<Measurement> >; _Alloc = std::allocator<std::unique_ptr<Handler<Measurement> > >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Handler<Measurement> >]
       push_back(value_type&& __x)
       ^
/usr/include/c++/4.9/bits/stl_vector.h:931:7: note:   no known conversion for argument 1 from 'std::_MakeUniq<ImageHandler>::__single_object {aka std::unique_ptr<ImageHandler, std::default_delete<ImageHandler> >}' to 'std::vector<std::unique_ptr<Handler<Measurement> > >::value_type&& {aka std::unique_ptr<Handler<Measurement> >&&}'

I don't understand why the pointer conversion does not work, since all the derived classes inherit from a Handler<MeasT> where MeasT is a derivation of Measurement.
I've seen similar questions but most of them keep the template even in the derived class (which I don't) or refer to the CRTP. However, the CRTP uses directly the derived class as template argument, while here I'm using a different derived class.

A: Just think that C++ compiler is going to substitute the class name when we template.
So your hash map declaration is translated in this way
std::vector>> handlers; --> std::vector> handlers;
means the compiler will automatically create a "templated class" from class template Handler as below
class Handler_Measurement {
  public:
   virtual void addMeasurement(Measurement& m) = 0;
 };

but when compiler sees handlers.push_back(std::make_unique()); it creates the following templated classes.
  class Handler_PointCloudMeasurement {
  public:
   virtual void addMeasurement(PointCloudMeasurement& m) = 0;
 };

  class PointCloudHandler : public Handler_PointCloudMeasurement {
    public:
      void addMeasurement(PointCloudMeasurement& m) override {
         std::cout << m.n_points << std::endl;
      }
    };

and for handlers.push_back(std::make_unique()); the compiler creates
        class Handler_ImageMeasurement {
         public:
            virtual void addMeasurement(ImageMeasurement& m) = 0;
         };
     class ImageHandler : public Handler_ImageMeasurement{
       void addMeasurement(ImageMeasurement& m) override {
         std::cout << m.n_pixels << std::endl;
       }
      };

From the hand crafted code sample you can see that the base classes are different. So a solution like below may help you.
#include <iostream>
#include <string>
#include <vector>
#include <memory>

class Measurement {
 public:
uint64_t time;
virtual ~Measurement() {}
virtual void display() = 0;
 };

 class PointCloudMeasurement : public Measurement {
  public:
uint64_t n_points = 64 * 1024;

void display()
{
    std::cout << n_points << std::endl;
}

  };

  class ImageMeasurement : public Measurement {
   public:
uint64_t n_pixels = 640 * 480;

void display()
{
    std::cout << n_pixels << std::endl;
}
  };

  class Handler {
  public:
virtual void addMeasurement(Measurement& m) = 0;
  };

  class PointCloudHandler : public Handler {
  public:
void  addMeasurement(Measurement& m) override {
    m.display();
}
  };

  class ImageHandler : public Handler {
void  addMeasurement(Measurement& m) override {
    m.display();
}
  };

  int main(void) {
std::vector<std::unique_ptr<Handler>> handlers;

handlers.push_back(std::make_unique<PointCloudHandler>());
handlers.push_back(std::make_unique<ImageHandler>());

PointCloudMeasurement pcm;
ImageMeasurement im;

handlers[0]->addMeasurement(pcm);
handlers[1]->addMeasurement(im);
 }

Also your derived classes are different in data member wise. The only common thing about them is "they are a measurement type" but they don't have nothing in common.
I hope it helps.


text:
Q: Why won't my function run? Here are my HTML and JavaScript files. The html file runs properly but the JavaScript file has an error in it and I was wondering why there's an error and how to correct it. I'm trying to draw a flower using user input.
<DOCTYPE html>

      <title> Lab 8: Arrays </title>
      <meta charset = "UTF-8"/>

      Number of Petals
      <input id = "text1" type = "text" value = "">

      Number of Points
      <input id = "text2" type = "text" value = "">

      <input id = "draw" input type ="button" value="Draw" onclick="draw()">

      <canvas id = "drawingSurface" width = "600" height = "600" style = "border-style: solid"></canvas>

javascript :
var N, M, r;
var ctx;
var coordinates;
var arr = [];
function setup(){
ctx = document.getElementById("drawingSurface").getContext("2d");
ctx.translate(300,300);
}

function drawShape(){
    var numPetals = document.getElementById("text1").value;
    var numPoints = document.getElementById("text2").value;
    coordinates = getCoordinates(numPetals,NumPoints, 300);
    draw(coordinates);
}

function GenerateXY(M,N,r){
    coordinates = [[10,10],[20,20]];

    for(var i = 0; i <= M; i += 1){
        var angle = i * 2 * Math.PI / M;
        var r2 = Math.abs(Math.sin(angle * N / 2));
        var x = r2*Math.sin(angle);
        var y = r2*Math.cos(angle);

        coordinates[i] = [x,y];

    }
    return coordinates;
}

function draw(arr){
    ctx = document.getElementById("drawingSurface").getContext("2d");
    ctx.save();
    ctx.beginPath();
    for(var i = 0; i < arr.length; i+=1){
        ctx.lineTo(arr[i][0], arr[i][1]);
    }
    ctx.stroke();
    ctx.restore();
}

im having trouble with my last function,(draw). the console says it cannot read property "length" and I don't know how to fix that.

A: Your HTML click handler here:
<input id = "draw" input type ="button" value="Draw" onclick="draw()">

is calling draw(), but your function signature is expecting an array to be passed to draw as in draw(arr).  That's why arr is not defined so arr.length throws an error.
If you mean for draw() to just work off the global variable arr, then you can remove it from the function definition like this:
function draw(){
    ctx = document.getElementById("drawingSurface").getContext("2d");
    ctx.save();
    ctx.beginPath();
    for(var i = 0; i < arr.length; i+=1){
        ctx.lineTo(arr[i][0], arr[i][1]);
    }
    ctx.stroke();
    ctx.restore();
}

As a general observation on your code, variables which are used within a function should be declared as local variables with var inside the function as in:
var ctx = document.getElementById("drawingSurface").getContext("2d");

This prevents multiple functions from accidentally clobbering each other by using the same global variable for their own private use and prevents the pollution of the global namespace.  It also allows projects to scale and share without conflicts.


text:
Q: jQuery mousemove workaround I'm looking for a workaround for .mousemove() method on Chrome. It's a known issue.
Chrome keeps firing mousemove repeatedly even if the mouse is still.
I can't use .hover() method because the area is the window's height and width...
I think about checking the mouse cursor coordinates and check if they changed, but I really don't know where to start.

I reported to Chromium project:
    http://code.google.com/p/chromium/issues/detail?id=170631

A: Still got the Problem in Chrome Version 29.0.1547.66 m and searched for a "real" solution. Nothing found so far.
Like you said, i start to write a function to check if the mouse are really moved or not.
Specially, you can change some settings for your own needs.
var my_mouseMovements = {
    readNewPos : true, //indicates if time since last check are elapsed
    oldPos : [0,0], //pos from the last check
    minX_Distance: 10, //only look at movements thats are big enough(px)
    minY_Distance: 10, //only look at movements thats are big enough(px)
    timeBetweenEachCheck : 100, //Just checking every x ms for movements
    saveNewPos : function(pos,callback){
    if(this.readNewPos === true)
    {
        this.readNewPos = false;

        var xDistance = pos[0] - this.oldPos[0];
        var yDistance = pos[1] - this.oldPos[1];
        //Just making the distances positive
        xDistance = xDistance < 0 ? -xDistance : xDistance;
        yDistance = yDistance < 0 ? -yDistance : yDistance;

        //Check if mouse moved more then expected distance
        if(xDistance >=  this.minX_Distance || yDistance >= this.minY_Distance)
        {
            console.log("Mouse has moved a lot since last check!");
            if(callback !== undefined)
            {
                callback();
            }
        }

        this.oldPos = pos;

        var that = this;
        //reset readNewPos after a while
        setTimeout(function(){
            that.readNewPos = true;
        },this.timeBetweenEachCheck);
    }
    else //Just for debug right now
    {
        console.log("the last time was not far away");
    }
}
};

jQuery('body').mousemove(function(e){
    my_mouseMovements.saveNewPos([e.pageX,e.pageY]);
});


text:
Q: Res/Arrays affecting TextView I populate a listview from a JSON object. This works fine
    setListAdapter(new ArrayAdapter<String>(this, R.layout.list_items, name){
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.list_items, null);
            }
            TextView mDistanceTextView = (TextView) v.findViewById(R.id.listitems_distancetxt);
            TextView mNameTextView = (TextView) v.findViewById(R.id.listitems_nametxt);
            TextView mCategoryTextView = (TextView) v.findViewById(R.id.listitems_categorytxt);
            if (mDistanceTextView != null) {
                mDistanceTextView.setText(distance[position]);
            }
            if (mNameTextView != null) {
                mNameTextView.setText(name[position]);
            }
            if(mCategoryTextView != null) {
                mCategoryTextView.setText(type[position]);
                setImage(type[position], v);
            }

            return v;
        }

However in a different activity I want to populate a spinner object so I created a new XML file called arrays.xml and it was located in the res/values folder. When I do this and run the program (without changing any code) the textViews all show null and so don't enter the if statement and so don't populate the view.

A: In case anybody has stumbled upon this question. It was just a matter of running a clean build


text:
Q: Nginx config for subdomains My app structure is like so:

*

*/var/www/app/htdocs (the base app)

*/var/www/app/sites/example (where 'example' is a child site).

I want to set the root to /var/www/app/htdocs when www.mydomain.com or mydomain.com is requested.
I want to set the root to /var/www/app/sites/example when example.mydomain.com is requested.
How can I achieve this?
So far I've got:
server {
  listen 80;

  index index.php index.html index.htm;
  server_name ~^www\.(?P<sub>.+)\.mydomain\.com$ ~^(?P<sub>.+)\.mydomain\.com$;
  root /var/www/app/sites/$sub;

  location / {
  try_files $uri $uri/ =404;
  }

  location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
  }

  location ~ /\.ht {
        deny all;
  }
}

This will correctly display example.mydomain.com, but not www.mydomain.com, or mydomain.com. Any ideas? Also is there any way to whitelist subdomains?
Thanks.

A: You can create a new file in  /etc/nginx/sites-enabled
name it as example.mydomain.com
edit the file, use following config :
    server {
        listen 80 ;
        server_name example.mydomain.com;
        root /var/www/app/sites/example;
  return         301 https://$server_name$request_uri;
        large_client_header_buffers 8 32k;
  if ($http_user_agent ~* Googlebot) {
    return 403;
  }

    location / {
        try_files $uri $uri/ =404;
    }

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

        location ~ /\.ht {
                deny all;
        }
}

use nginx -t reload to check the config file
make an entry in your Domain name service provider.


text:
Q: Building JAR at runtime and use it as a referenced library I'm building at runtime a JAR which include some file ".class" generated at runtime too. So, to be able to use these ".class" I've added the JAR as a referenced library to the project.
But when I try to use these classe I get the following error:
The type com.Crilin cannot be resolved. It is indirectly referenced from required .class files

What am I missing?


text:
Q: MongoDB (Java) if statement equals value So I'm working on a piece of code with a if statement and in the if statement i want to check if a value of my MongoDB equals "test"
I currently have this it isn't much but i really don't know how to do this
  if (DBManager.getInstance().getTestCollection()) {

Example of my MongoDB
{
"_id": {
    "$oid": "56fd47ea18de75129095d841"
},
"foo": "test"
}

A: Once you get the collection, you need to Aquire cursor on it and loop through it. see below.
    DBCollection testCollection = DBManager.getInstance().getTestCollection()
    DBCursor cursor = testCollection.find();

        while (cursor.hasNext()) {
            BasicDBObject obj = (BasicDBObject) cursor.next();
            if ("test".equals(obj.get("foo")) {
               System.out.println("Found");
            }
        }


text:
Q: GitVersion configuration is not incrementing I'm trying to setup GitVersion to handle our project's semantic versioning (GitFlow), but it's not incrementing automatically as I'm expecting. I'm also struggling with reading the project's documentation, it's not the easiest to follow.
Basically we're hoping to setup a versioning system with Major.Minor.Patch convention, where we increment Major manually, Minor automatically when a release branch gets merged into master, and Patch automatically when a feature branch gets merged into develop.
Here is my current GitVersion.yml
mode: ContinuousDeployment
branches:
  feature:
    increment: Patch
    regex: feature?[/-]
  release:
    increment: Minor
    regex: release?[/-]
  develop:
    regex: develop$
  master:
    regex: master$
ignore:
  sha: []

Also to test it I wrote a small ruby script to speed up the tedious process. I included it just to make sure I'm using GitVersion and GitFlow in the intended way.
require "git"

def new_feature_branch i
  g = Git.open(Dir.pwd)

  branch_name = "feature/number-#{i}"
  g.checkout("develop")
  g.branch(branch_name).checkout

  open('README.md', 'a') do |f|
    f.puts "\r#{i}"
  end

  g.add("README.md")
  g.commit("##{i}")

  g.branch("develop").checkout
  g.merge(branch_name)
  g.branch(branch_name).delete

  print(`gitversion`)
end

new_feature_branch(ARGV[0])

Output of gitversion
{
  "Major":1,
  "Minor":1,
  "Patch":0,
  "PreReleaseTag":"alpha.39",
  "PreReleaseTagWithDash":"-alpha.39",
  "PreReleaseLabel":"alpha",
  "PreReleaseNumber":39,
  "WeightedPreReleaseNumber":39,
  "BuildMetaData":"",
  "BuildMetaDataPadded":"",
  "FullBuildMetaData":"Branch.develop.Sha.57a536a5c6b6abb4313a2067468413447cb49c86",
  "MajorMinorPatch":"1.1.0",
  "SemVer":"1.1.0-alpha.39",
  "LegacySemVer":"1.1.0-alpha39",
  "LegacySemVerPadded":"1.1.0-alpha0039",
  "AssemblySemVer":"1.1.0.0",
  "AssemblySemFileVer":"1.1.0.0",
  "FullSemVer":"1.1.0-alpha.39",
  "InformationalVersion":"1.1.0-alpha.39+Branch.develop.Sha.57a536a5c6b6abb4313a2067468413447cb49c86",
  "BranchName":"develop",
  "Sha":"57a536a5c6b6abb4313a2067468413447cb49c86",
  "ShortSha":"57a536a",
  "NuGetVersionV2":"1.1.0-alpha0039",
  "NuGetVersion":"1.1.0-alpha0039",
  "NuGetPreReleaseTagV2":"alpha0039",
  "NuGetPreReleaseTag":"alpha0039",
  "VersionSourceSha":"27938c50fc6f364eff52bccec8dbc10297bce87b",
  "CommitsSinceVersionSource":39,
  "CommitsSinceVersionSourcePadded":"0039",
  "CommitDate":"2019-10-28"
}

The problem I'm expecting the Patch number to increment each time I merge a feature branch into develop but that isn't happening.

A: There are still some minor issues but this config setting is working much more as I intended.
mode: Mainline
tag-prefix: '[vV]'
commit-message-incrementing: MergeMessageOnly
branches:
  feature:
    regex: feature?[/-]
    source-branches: ['develop']
  release:
    increment: Minor
    regex: release?[/-]
  develop:
    is-mainline: true
    increment: Patch
    regex: develop$
  master:
    regex: master$

A: This is not really an answer, as you want to use gitversion, but perhaps it shows a different way to handle your issue and it is too long for a comment:

*

*Put a file "pre-commit" with the content below in /.git/hooks/

*In our case, we are working with R and the version is "tracked" in a file called "DESCRIPTION" in the folder of a package (that is why I asked for the file and how it is called.

If you then commit, the patch is increased by +1, the minor/ major version have to be set by hand in the way x+1.0.-1 (which gets x+1.0.0). I guess you should be able to adapt the script to your needs.
Hope that helps.
#!C:/R/R-3.3.0/bin/x64/Rscript

# License: CC0 (just be nice and point others to where you got this)
# Author: Robert M Flight <rflight79@gmail.com>, github.com/rmflight
#
# This is a pre-commit hook that checks that there are files to be committed, and if there are, increments the package version
# in the DESCRIPTION file.
#
# To install it, simply copy this into the ".git/hooks/pre-commit" file of your git repo, change /path/2/Rscript, and make it
# executable. Note that /path/2/Rscript is the same as your /path/2/R/bin/R, or may be in /usr/bin/Rscript depending on your
# installation. This has been tested on both Linux and Windows installations.
#
# In instances where you do NOT want the version incremented, add the environment variable inc=FALSE to your git call.
# eg "inc=FALSE git commit -m "commit message".
# This is useful when you change the major version number for example.

inc <- TRUE # default

# get the environment variable and modify if necessary
tmpEnv <- as.logical(Sys.getenv("inc"))
if (!is.na(tmpEnv)) {
  inc <- tmpEnv
}

# check that there are files that will be committed, don't want to increment version if there won't be a commit
fileDiff <- system("git diff HEAD --name-only", intern = TRUE)

if ((length(fileDiff) > 0) && inc) {

  currDir <- getwd() # this should be the top level directory of the git repo
  currDCF <- read.dcf("DESCRIPTION")
  currVersion <- currDCF[1,"Version"]
  splitVersion <- strsplit(currVersion, ".", fixed = TRUE)[[1]]
  nVer <- length(splitVersion)
  currEndVersion <- as.integer(splitVersion[nVer])
  newEndVersion <- as.character(currEndVersion + 1)
  splitVersion[nVer] <- newEndVersion
  newVersion <- paste(splitVersion, collapse = ".")
  currDCF[1,"Version"] <- newVersion
  currDCF[1, "Date"] <- strftime(as.POSIXlt(Sys.Date()), "%Y-%m-%d")
  write.dcf(currDCF, "DESCRIPTION")
  system("git add DESCRIPTION")
  cat("Incremented package version and added to commit!\n")
}


text:
Q: How to Hold position on cylinder/pendulum using unity3d I'm new on Unity and trying to create a cylinder moving as a rigid pendulum. I use a hinge joint in top of cylinder and a motor to ad force.
How do I get the cylinder to hold position and not fall back to "dead" position when the I stop applying force?
JointMotor m = new JointMotor();
m.force = 10000;
m.targetVelocity = 0;
m.freeSpin = true;
GetComponent<HingeJoint>().motor = m;

A: You can try to calculate it manually.
Create an empty object as a pivot, make the arm and bob it's child objects and rotate your pivot using Lerp(). Something like this might work:
public class Penduluum : MonoBehaviour {
 public float angle = 45.0f;
 public float speed = 1.5f;

 Quaternion Start, End;

 void Start () {
     Start = Quaternion.AngleAxis ( angle, Vector3.forward);
     End   = Quaternion.AngleAxis (-angle, Vector3.forward);
 }

 void Update () {
   transform.rotation = Quaternion.Lerp (Start, End, (Mathf.Sin(Time.time * speed) + 1.0f) / 2.0f);
 }

}


text:
Q: Get Python Shell open So i open Python 3.7.3 and all i get is a black window that looks like the command prompt window. Where is the shell? Where do I write my code? I saw an example with this same version of python where there were 2 white windows, one with the code and the other being the shell but i am confused how to set that up.
Is there a difference between just python 3.7.3 and IDLE? As you can see I am basically lost in this whole situation.
The window that I see looks like this: https://imgur.com/a/rMOMEh5

A: You have a few options, to name the basic ones:

*

*Write your python code as a plain text file with an editor of your choice, and execute using:

python myfile.py

*Write your python code in a simple IDE (e.g. sublime, atom) that has fancy features such as auto-indentation and colour coding, and execute using:

python myfile.py

*Write your code in a fancy IDE that allows you to have shell and code at the same time, and execute within the IDE (e.g. PyCharm)

A: That's the python shell where you can issue python commands. You can call a python script as stated above and even code python directly in that window. Here is an example:

*

*Type from secrets import token_urlsafe and hit return. Now you've imported your first python module.

*Type ran_num = token_urlsafe(16) and hit return. Now we've declared a variable called ran_num and gave it the value of 16 random number, letters, and characters.

*Type print(ran_num) and look at the output, which should be something like this - W2Z6O4XGebDa-eXbJY5p3Q
This is just one example. There are a lot of uses.


text:
Q: SQL Server all(select ...) is null I search but i cannot find anything about it. I need SQL server query like
select t1.x
 from @tablename as t1
 where all
   (select t2.y from @tablename as t2 where t1.x=t2.x) is null

@tablename's are same
But I can't use all(select ...) is null part of query.
Thanks.

A: Do you want not exists?
select t1.x
from @tablename as t1
where not exists (select t2.y from @tablename as t2 where t1.x = t2.x)

This tests that there are no matching values.
Or, perhaps,
select t1.x
from @tablename t1
where not exists (select 1
                  from @tablename as t2
                  where t1.x = t2.x and t2.y is not null
                 ) ;

This tests that any matching value has NULL for y.


text:
Q: How to check cursor null or not in android? I'm trying to check values of field ID in BangCauHoi table.
This is my function:
public boolean checkID(String ndCauHoi){
        boolean check = true;
        String query = "select ID from BangCauHoi where CauHoi=?";
        Cursor c = database.rawQuery(query, new String[] { ndCauHoi });
        if (c != null)
        {
             c.moveToFirst();
                 if (c.isNull(c.getColumnIndex("ID")))
                 {
                     check = false;
                 }
        }
         c.close();
    return check;
}

And result:
java.lang.RuntimeException: Unable to start activity ComponentInfo{us.datn_02/us.datn_02.ShowQuestion}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Somebody can help me please?
if I change my code to:
public boolean checkID(String ndCauHoi){
        boolean check = true;
        String query = "select ID from BangCauHoi where CauHoi=?";
        Cursor c = database.rawQuery(query, new String[] { ndCauHoi });
        if (c.moveToFirst())
        {
                 if (c.isNull(c.getColumnIndex("ID")))
                 {
                     check = false;
                 }
        }
         c.close();
    return check;
}

then it always return true even field ID have no value with this where clause.
Help me please!...
Sorry because my english.

A: Your database does not have any rows mathing the selection and moveToFirst() returns false. When unchecked, you'll get the exception about trying to retrieve values from a nonexisting row. When checked, it returns the default value true you've specified.

A: You can check to see whether or not it is empty with the following statement:
if (c.moveTofirst() && c.getCount > 0)

or
if (c != null && c.moveToFirst())

As to why it is empty, I would guess that you have mistyped a statement somewhere. I always use the query method in the SQLiteDatabase class instead of rawQuery, and use constants for my column names instead of hardcoding them to try and avoid these problems.
public static final String KEY_ID = "_id";
public static final String TABLE_NAME="BangCauHoi";
public static final String CAUHOI = "CauHoi";

Cursor c = yourDatabaseInstance.getReadabledatabase().query(
    YourDatabaseName.TABLE_NAME,
    new String[] { YourDatabaseName.KEY_ID },
    YourDatabaseName.CAUHOI + "=?",
    new String[] { ndCauHoi },
    null, null, null);


text:
Q: Is $\delta:C_2[0,1]\to \Bbb{R}, \delta(f)=f(0)$ discontinuous? Is the functional $\delta:C_{2}[-1,1]\to \Bbb{R}, \delta(f)=f(0)$ with $L_2$ norm discontinuous?
I understood I should show whether or not the functional is unbounded, but I can't seem to understand how to use the fact that $f\in C_{2}[-1,1]$. I am still trying to find a series of functions with the right properties.
I think I should take a function $f_n$ with $||f_n||\to 0$ and $||f_n||\ne 0$ while $f_n(0)$ is bounded. Any notes?


text:
Q: why chrome extensions not exctute in background tab page? I am using a chrome extension(third party) to download specific info automatically. When I open the target page in the background tab, the extension does not execute even the page has been loaded. When the page is visible, it can show the button on the page, after all elements show.
Is there any js script or setting that is stopping the extension to run ?


text:
Q: CSS3 non-linear Animation paths how do you do non-linear animation with css3?
Basically, if I need to bring a box in from out of the view port, and its a straight down path, then its easy enough to do with the following code:
*{
    transition: transform 0.5s ease-in;
}

-- And some JS to trigger the animation with a transform: translate3d(0,300px,0);

But what happens when the element is rotated? Say by 25 deg? Then for the animation to look somewhat natural, it'll need to progress in a 25 deg offset line, and cannot just be top-down, or left-right animations...
I hope I'm making sense here... Look at the demo here http://jsfiddle.net/YMHT4/8/
I'm trying to get the blue box to animate in on a slanted path...

A: I'm not sure if I'm understanding correctly, but if you're trying to do what I'm thinking, then the answer is quite simple:
function ani()
{
    if (!state)
    {
        $('#otherbox').css('-webkit-transform', 'translate3d(100px,150px,0) rotate(25deg)');
        state=true;
    }
    else
    {
        $('#otherbox').css('-webkit-transform', 'translate3d(0,0,0) rotate(25deg)');
        state=false;
    }
}

If you change both x and y in translate3d(x,y,z), then both dimensions will animate, and you will get a diagonal path animation.
http://jsfiddle.net/YMHT4/17


text:
Q: breakpoint() using ipdb by default Is it possible that installing ipdb (or some other package written to do it explicitely) will result in breakpoint() running ipdb instead of pdb without binding sys.breakpointhook() to ipdb?
https://www.python.org/dev/peps/pep-0553/
I'm not asking if ipdb does that or if it will, but if its possible to code that. I know that I can set environment variable PYTHONBREAKPOINT=ipdb.set_trace. The question is if its possible to trigger this behavior by just installing ipdb.

A: During the installation one could programmatically create either a usercustomize.py or a sitecustomize.py in the correct directories and alter os.environ['PYTHONBREAKPOINT'] in there.
These modules are imported by site.py early in the startup sequence and are suited for this sort of customization. Personally, I've never seen a package alter/create these files so I wouldn't expect ipdb to ever do it.


text:
Q: how to disable gcc warning "cc1: warning: command line option '-std=c++11' is valid for C++/ObjC++ but not for C [enabled by default]" I am new to cmake and gcc.
The first assignment in my new role in the company was to clean the errors from our linux compilation
I did most of it, and now the only warning I see is
cc1: warning: command line option '-std=c++11' is valid for C++/ObjC++ but not for C [enabled by default]
I want wither to suppress the warning or to solve the issue in the cmake file.
Unfortunately, I still haven't found the correct -Wno-xxx statement that fits here.
Thanks!

A: Code issue warnings can be silenced with -Wno-xxx options because sometimes you don't have control over the source code. But a warning telling you that a command-line option is incorrect cannot be silenced with yet another command-line option — if you can affect compiler invocation, then why not just remove the incorrect option?
This particular warning tells you that you cannot set standard to C++11 when compiling C code. To get rid of it, find where -std=c++11 is defined in the build configuration, and make sure it is only applied to C++ compilation, and not for C. For example, move it from CFLAGS to CXXFLAGS, or cmake's equivalent thereof.


text:
Q: MyFirebaseInstanceIDService get has no default constructor So, i have this class. This class will save the device token to shared preference.
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";

    Context myCon;

    public MyFirebaseInstanceIDService(Context mCon){
        this.myCon=mCon;
    }

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        storeToken(refreshedToken);
    }

    private void storeToken(String token) {
        SessionHandler.getInstance(myCon).saveDeviceId(token);
    }
}

and here is how i use that class from other activity
MyFirebaseInstanceIDService firebaseService = new MyFirebaseInstanceIDService(Login_activity.this);
firebaseService.onTokenRefresh();

and here is my manifest
<service
   android:name=".custom_services.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

So, in my manifest above i get this message

MyFirebaseInstanceIDService has no default constructor

How can i fix it ? thanks in advance

A: You don't need to call service object directly. Android will handle your service once your declare it inside manifest file.
You also don't need to add a constructor to pass context, since service will have context available inside it.
If you need to refresh token forcefully do this (it will throw error is run on main thread so use a aync task or use other thread) :
FirebaseInstanceId.getInstance().deleteInstanceId();
FirebaseInstanceId.getInstance().getToken();

Once the token is refreshed the method public void onTokenRefresh() will get called and your functionality inside will run.

A: Add this line in your MyFirebaseInstanceIDService :
public MyFirebaseInstanceIDService(){

    }

A: You do not need to define constructor. Your class should simply be like
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";
    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    private void sendRegistrationToServer(String token) {
        Log.d("mDeviceToken", token);

    }
}

There is no need of
  MyFirebaseInstanceIDService firebaseService = new MyFirebaseInstanceIDService(Login_activity.this);
    firebaseService.onTokenRefresh();

You just need to save your token(may be in sharedPreference) in OnTokenRefresh().

A: No need to call MyFirebaseInstanceIDService class
You can get Device Token from any Activity calling...
String deviceToken = FirebaseInstanceId.getInstance().getToken();

A: See the Clas Architecture .
public class FirebaseInstanceIdService extends Service

i.e FirebaseInstanceIdService is a Service So you do not have to pass Context to it cause it has its own Context So you do not have to have a parameterized constructor.
And If you do not have any constructor a default Constructor is injected by the compiler automatically . That's it . Just keep it Simple .
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();

    Log.d(TAG, "Refreshed token: " + refreshedToken);
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {
    Log.d("mDeviceToken", token);

}
}


text:
Q: specify a date for an event for example i want to start  the event on monday at 13:30 and finish it at 15:30 , how can i do it ?
Calendar cal = Calendar.getInstance();
ContentValues event = new ContentValues();
event.put("calendar_id",1);
event.put("title", "dd");
event.put("description","dd");
event.put("eventLocation", calc.getEventLocation());
event.put("dtstart",???);
event.put("rrule", "FREQ=WEEKLY;WKST=SU;BYDAY=WE");
event.put("allDay", 1);   // 0 for false, 1 for true
event.put("eventStatus", 1);
event.put("hasAlarm", 1); // 0 for false, 1 for true
event.put("duration","P3600S");
getContentResolver().insert(eventsUri, event);

A: Create a java.util.Date object, set the desired date and time. If you DB needs a String then convert date to string, if long then date to long. And provide appropriate value to "dtstart"
Along with stStart, you also need to have dtEnd. Here the date wil lremain same but the time will change.
Do the above for both objects - ststart & dtend.
If you don't have to add another field to your DB, then you will have to pass a customized String. Like : "Feb-6-2012|13:30|15:30" or so. Here I have seperated Date, Start Time & end Time with a "|" (pipe) char. When you retrieve the value from DB, you got to parse accordingly and can make 2 instances of Date for start and end time.
Hope this helps.


text:
Q: How to apply gamma correction for cv::mat? I am new to opencv. There is such a question: I have an image that I get and save this way
    Decoder decoder;
    decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    bool isOk = cv::imwrite(save_location, image);

I need to apply gamma correction to the cv::mat before it is saved. I tried to google but it looks like openCV doesn't have a direct method like cv::gamma(image, 2.2) for this purpose.
How to do it?

A: Gamma correction is not directly implemented in opencv.
What you can do is to implement a lookup table that maps each value from 0 to 255 to the corresponding value after the gamma correction: ((value/255) ** (1/gamma)) * 255.  After creating the LUT you can use the cv2.LUT to map the values of the image to the values after correction - cv2.LUT(image, table).
Link to python implementation:
https://www.pyimagesearch.com/2015/10/05/opencv-gamma-correction/#:~:text=There%20are%20two%20(easy)%20ways,range%20%5B0%2C%20255%5D.

A: Eventually, I found the way to do it (according to this tutorial https://docs.opencv.org/3.4/d3/dc1/tutorial_basic_linear_transform.html):
    //>>>Get Frame
    Decoder decoder;
    decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
    //<<<

    //>>> Collor conversion from BGR to RGB
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    //<<<

#if 1
    //>>> Gamma correction
    cv::Mat new_image = cv::Mat::zeros(image.size(), image.type());
    double alpha = 2.2; /*< Simple contrast control */
    int beta = 0;       /*< Simple brightness control */

    for (int y = 0; y < image.rows; y++) {
        for (int x = 0; x < image.cols; x++) {
            for (int c = 0; c < image.channels(); c++) {
                new_image.at<cv::Vec3b>(y, x)[c] =
                    cv::saturate_cast<uchar>(alpha*image.at<cv::Vec3b>(y, x)[c] + beta);
            }
        }
    }

    image = new_image;
    //<<<
#endif // 0

    bool isOk = cv::imwrite(save_location, image);


text:
Q: Unable to register or ask questions on SuperUser I am not able to register to or ask questions at SuperUser from my office machine (same with registering at ServerFault - haven't tried asking questions there). I guess the reason is that I am behind a proxy server and is using DHCP. I tried to register at SU and SF from this machine for so long but it didn't work. Finally I tried from another machine that doesn't use DHCP and is connected to the proxy server with a permanent IP address, and it worked like charm. Now I tried asking my first question on SU from my machine and I got the same issue again.
At first I thought it was some internal proxy related issue but I am able to register/ask questions at SO and meta from the very same machine without any hurdles.
This is the error message:

The requested URL could not be retrieved
While trying to retrieve the URL: https://superuser.com/questions/ask/submit
The following error was encountered:

*

*Read Error

  The system returned:
(104) Connection reset by peer

I've tried from Vista and Ubuntu, if that matters.

Just to clarify  - SU isn't blocked here - I'm able to open the site and browse through all the pages, including the Ask question one. I get this error when I type in the question and click submit. Similarly while registering, I am forwarded to the Open-ID provider and asked to login - but when I submit my details at Google and click login, the address bar shows su/authenticate (if I remember correctly) but I get this error after 5-10 seconds.

UPDATE: Don't know what the issue was, but it seems to be fixed now. I just asked a question on SU successfully.

A: This report makes no sense; if you can post on SO and meta there's no reason you wouldn't be able to post on SU and SF.
The configurations of Meta, SU, and SF are virtually identical. SO is behind HAProxy.

A: I assume, that your employer blocks SU and you circumvented this block by using that other machine.


text:
Q: Tipi Shelter Formula Autumn is quickly approaching in my neck of the woods and with it brings the start of camping and backpacking season. This year I want to work on my bushcraft skills with one particular project in mind: building a tipi shelter.
I suppose I could just start building one, hoping it turns out the right size and shape to accommodate a certain number of occupants. But the engineer in me wants to first see if math can help me out and save me some time and natural resources.
Basically, I am trying to come up with a plug-n-play style formula that can be used to build a tipi. For example, I foresee a few variables that the formula would use:

*

*occupants: the number of people laying down in the tipi

*occupant height: the average height of one occupant, in inches

*fireplace size: diameter, in inches, located at the center of the tipi

*slant: whatever is optimal, 45 degrees?

Here is a diagram I created that illustrates how the occupants will be laying down:

I would like the ability to simply plug in my numbers to each variable and have the formula return the following variables:

*

*tipi diameter: the diameter of the tipi

*pole length: the length of the vertical poles

*number of structural poles: traditionally, this is the core tri-pod, but maybe 4, 5, or 6 poles is better?

*fireplace diameter: the diameter of the fireplace

*whatever else is useful
My hat goes off to anyone who can figure that out :) I admire your skills and would feel very grateful for your help.


text:
Q: Expo sdk-46, handle css files Expo cli (sdk 46)
I am building an embeddable widget like application using expo sdk-46. Just like a chat app in a website.
Used a react/auth library which renders Social login buttons with specific classnames.
Bundler
Using built in metro bundler.
I know css handling is not yet supported yet.
Problem
Is there a way I can target those classes and apply custom styles ? The recommended way for styling is through StyleSheet as per expo doc , but how can I target existing classNames in Stylesheet


text:
Q: Use variable value in Xpath I have the following XML
<root>
  <ns:Search xmlns:ns="http://example.com/1.0/">
    <ns:AllClass>
      <ns:class1>
        <ns:node1>fhgfjh</ns:node1>
        <ns:node2>Aprtyrtyril</ns:node2>
        <ns:node3>Juklyuiyly</ns:node3>
      </ns:class1>
      <ns:class2>
        <ns:node1>dfgd</ns:node1>
        <ns:node2>trytyu</ns:node2>
        <ns:node3>sgsdfg</ns:node3>
      </ns:class2>
      .
      .
      .
      .
      .
      .
    </ns:AllClass>
  </ns:Search>
  <ns:Req xmlns:ns="http://example.com/1.0/">
    <ns:classId>class1</ns:classId>
    <ns:othertag>asdfg</ns:othertag>
    .
    .
    .
    .
    .
  </ns:Req>
</root>

and the following XSL
<xsl:template match="root">
    <xsl:variable name="class" select="/root/Req/classId" />
    <ns1:Request xmlns:ns1="http://example.com/ns1">
      <ns1:node>
        <xsl:value-of xmlns:ns="http://example.com/1.0/" xmlns:ns1="http://abc.xyz.com/1.0/" select="/root/Search/AllClass[Value=$class]/node1" />
      </ns1:node>
    </ns1:Request>
  </xsl:template>

I am getting a class name inside my XML in 'classId' node. I want to get the value of 'node1' of the class same as my value inside the 'classId' tag. I am using a variable'class' and storing the value of classId and trying to get the value of 'node1' by using the variable inside Select Xpath. But it is not working. Please help.

A: You have to use namespace in XPATH expressions:
<xsl:template match="root">
    <xsl:variable name="class_tmp" xmlns:ns="http://example.com/1.0/" select="/root/ns:Req/ns:classId" />
    <xsl:variable name="class" select="concat('ns:',$class_tmp)" />
    <xsl:message><xsl:value-of select="$class"/></xsl:message>
    <ns1:Request xmlns:ns1="http://example.com/ns1">
        <ns1:node>
            <xsl:value-of xmlns:ns="http://example.com/1.0/" xmlns:ns1="http://abc.xyz.com/1.0/" select="/root/ns:Search/ns:AllClass/*[name()=$class]/ns:node1" />
        </ns1:node>
    </ns1:Request>
</xsl:template>


text:
Q: Install Compass on OS X Yosemite I'm trying to install compass using GEM but i have a lot of error.
My macbook pro is running OS X Yosemite.
Anyone have the same problem ?
Thank you for your time.
Have a nice day
sudo gem install compass
Password:
ERROR:  Error installing compass:
    ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20141019-17085-1dv9dek.rb extconf.rb
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/universal-darwin14/rbconfig.rb:213: warning: Insecure world writable dir /Library/Ruby/Gems/2.0.0/gems/ffi-1.9.5/ext/ffi_c in PATH, mode 040777
checking for ffi.h... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:434:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:549:in `block in try_compile'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:502:in `with_werror'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:549:in `try_compile'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:1044:in `block in have_header'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:895:in `block in checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:340:in `block (2 levels) in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:310:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:340:in `block in postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:310:in `open'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:336:in `postpone'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:894:in `checking_for'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:1043:in `have_header'
    from extconf.rb:16:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/ffi-1.9.5 for inspection.
Results logged to /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-14/2.0.0/ffi-1.9.5/gem_make.out

A: Actually, this seems to be successfully answered at Installing 'Compass' via the command line receive error "extconf failed, exit code 1"
You evidently need to first install development tools   (xcode-select --install), then install compass
good luck!

A: well you should not be installing gems globally for one thing. I would highly recommend installng rbenv and then the version of ruby you would like to have, before you install compass and other gems. Then you can install gems at a user level and don't have to worry about setting write permissions on directories outside of the users. - which appears to be the problem in this case.
Just follow the instructions here for rbenv https://github.com/sstephenson/rbenv and then install the ruby build plugin https://github.com/sstephenson/ruby-build

A: Just run sudo chmod go-w /usr/local/ from terminal as administrator.
This worked for me


text:
Q: php ::Array references any idea why
foreach ($groups as &$group)
  $group = trim(str_replace(',', '', $group));

echo '
';
print_r($groups);
echo '
';

$groupsq = $groups;
foreach ($groupsq as &$group)
  $group = '\'' . $group . '\'';

echo '
';
print_r($groups);
echo '
';

Yields
Array
(
    [0] => Fake group
    [1] => another group
    [2] => non-existent
)
Array
(
    [0] => Fake group
    [1] => another group
    [2] => 'non-existent'
)

The part i am interested in is,
Why does the second array modification effect the last item on the first array?

A: First, you need to clean up the references after each foreach loop using unset(), like so:
foreach ($groups as &$group)
  $group = trim(str_replace(',', '', $group));

unset($group);

// ...

foreach ($groupsq as &$group)
  $group = '\'' . $group . '\'';

unset($group);

Secondly, you're printing $groups instead of $groupsq:
echo '
';
print_r($groups);
echo '
';

The last item of $groups is being modified because you didn't clean up the reference after the first foreach loop.

A: Here is an in-depth article explaining the technical details behind this behavior: http://schlueters.de/blog/archives/141-References-and-foreach.html


text:
Q: Trying to open a popup on clicking the text in mvc i' want to make the given link ( @Html.DisplayFor(model => item.Status) 	) a hyperlink in mvc where data is coming from database dynamically.
And also on clicking this text a popup should be opened .
Any idea would be appreciated.

A: You can not open popup by clicking on @html.displayfor but you can use this method for open popup.
put @Html.DisplayFor(model => item.Status) in the 'div'or 'span' and give them unique id
Eaxmple:

$(document).ready(function(){
    $("#displayfor").click(function(){
       alert('message !..or use can use popup here');
    });

   $("#span").click(function(){
        alert('message !..or use can use popup here');
    });
});

Click on

    "@Html.DisplayFor(model => item.Status)"

Click on

     "@Html.DisplayFor(model => item.Status)"


text:
Q: Using TeamCity build templates how can I remove "Clean all files before build" from the template? I have a number of daily and in-response-to-svn-change builds that all derive from the same configuration template. I can set it so I can choose what branch to look at, what build steps to carry out and of course what triggers the build.
However I would like the daily builds to do a completely clean checkout, whereas the svn dependent ones (that obviously happen throughout the day) I am happy for them to simply to an update.
Simply un-setting the option in the template does not let me set them in each of the derived builds. Is there a build parameter that I can use to switch on clean builds for those builds that require it?

A: In each Project's "Version Control Settings", look under "Checkout setting". There are options to specify the checkout dir and also a checkbox to clean files before a build.

A: There is an Additional Build Feature (Swabra) you can add that does a clean checkout if required.I have enabled this for our nightly builds but have not yet investigated the consequences.
See here for more detail on Swabra

A: Seems to me that you need one template for daily and one for nightly builds.

A: I so disliked the Accepted Answer that I put a conditional scorch into my built script.
Then I you can either set a default in the template and override in the one that needs the scorching or define it on an opt-out basis.
Get-ChildItem . -Include obj,bin -Recurse -Force | Remove-Item -Recurse -Force
Remove-Item Artifacts -Recurse -Force

Why answer with such an unsightly hack? I'm hoping someone will chime in with a real solution and [then downvote this or preferably] comment.

A: There's a way to declare variables in the template and substitute them with configuration parameters in each build project. Please refer more details at [link] http://blogs.jetbrains.com/teamcity/2010/10/14/overriding-template-settings/


text:
Q: OnClickListener on Tabs not working Greetings,
I am trying to get the Click - event when clicking on the currently selected tab of my TabActivity. The onTabChangedHandler is only called whenever the tab is changed, not if the currently active Tab is clicked. The debugger tells me i have the onClickListener Registered for the TabWidget within my TabHost.
Am i registering for the wrong View?
Also, I am unable to create a Context Menu for the Tabs, only for its content, is this problem related?
public class TestDroidViewTab extends TabActivity
                              implements TabContentFactory
                              , OnTabChangeListener, OnClickListener {

  private static final String LOG_KEY = "TEST";
  ListView listView;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      final TabHost tabHost = getTabHost();

      TabHost.TabSpec ts = tabHost.newTabSpec("ID_1");
      ts.setIndicator("1");
      ts.setContent(this);
      tabHost.addTab(ts);

      ts = tabHost.newTabSpec("ID_2");
      ts.setIndicator("2");
      ts.setContent(this);
      tabHost.addTab(ts);

      ts = tabHost.newTabSpec("ID_3");
      ts.setIndicator("3");
      ts.setContent(this);
      tabHost.addTab(ts);
      tabHost.setOnClickListener(this);
      tabHost.setOnTabChangedListener(this);
  }
  public void onClick(View v) {
      Log.d(LOG_KEY, "OnClick");
  }

  public void onTabChanged(String tabId) {
      Log.d(LOG_KEY, "OnTabChanged");
  }

A: Your clause is wrong, use:
...
if (getTabHost().getCurrentTabTag().equals(myTabTag) == false) {
            getTabHost().setCurrentTab(myTabIndex );
   }

...

A: If you want to see that a particular tab is clicked, you need to add your listener to the tab itself, not the TabHost.
The hierarchy of views in a tab implementation is:

*

*TabHost

*

*TabWidget

*

*(tab)

*(tab)

*FrameLayout

The tabs are added at runtime by calling: tabHost.addTab(tabHost.newTabSpec(""));
You can then get a handle to the individual tabs by calling: getTabWidget().getChildAt(4);
In essence, you are adding your OnClickListener to a child of the TabWidget. You can now pick up the clicks on your individual tab. However, this will override the default behavior which changes the content when a tab is clicked. So, to get your content to change, your OnClickListener will need to do that for you.
Here is a full example, which lets you intercept the click event, and change the content below the tab:
final String myTabTag = "My Tab";
final int myTabIndex = 3;

getTabHost().addTab( getTabHost().newTabSpec(myTabTag) );

getTabWidget().getChildAt(myTabIndex).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (getTabHost().getCurrentTabTag().equals(myTabTag)) {
            getTabHost().setCurrentTab(myTabIndex );
        }
    }
});

A: use setOnTabChangedListener instead of OnClickListener ;)
    static TabHost tabHost;

    tabHost = getTabHost();

    tabHost.setOnTabChangedListener(new OnTabChangeListener() {
       @Override
      public void onTabChanged(String arg0) {
       Log.i("******Clickin Tab number ... ", "" + tabHost.getCurrentTab());
      }
});

A:
into my code, it shows some errors and ask me to create new methods in
  those names like getTabWidget(), getTabHost(), etc. Waiting for your
  response.

Try this
 tabHost.getTabHost().setCurrentTab(myTabIndex);


text:
Q: How to log exception in InvariantCulture? In my MVC solution I have two handlers for exception.
First logs exceptions to Logs database:
public sealed class LogErrorAttribute : Attribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // some handling with filterContext.Exception
    }
}

Second shows exception to user:
public sealed class AsyncAwareHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
         // some handling with filterContext.Exception
    }
}

Both of them are fired when any unhandled exception occurs:
throw new ArgumentNullException("email", i18n.someErrorMessage);

i18n.someErrorMessage is translated string from resx file.
In both handlers in filterContext.Exception.Message I have got string which is already translated.
How can I log exception message only in CultureInfo.InvariantCulture which is set to en-US in my solution?

A: The notion that exceptions should contain their own human-readable messages is very prevalent but also very misguided.
In concept,

The message conveyed by an exception is the type of the exception
along with any member variables contained within the exception.

What this also means is that:

You have to have a different exception class for every single
conceptually different exception that you throw.

You cannot have a wildcard "MyAllPurposeException" and differentiate among conceptually different exception situations by constructing different human-readable messages at the point where you throw them. The entity that will be trying to make sense out of your exceptions should not be limited to humans: conceptually, a catch block also has the right to be able to make sense out of exceptions thrown by your code, at the very least in the context of unit tests, but often also in production code.
For convenience we often just stuff a human readable message into our exceptions, but that's just a quick and dirty solution.  When you have an application with actual real-world internationalization needs you can't be doing hacks like that.
So, my recommendation would be to never add any message to an exception.  Let the Message member be blank; I would go as far as to say that the inclusion of the string Message member in the original Exception class was a mistake on behalf of the designers of the runtime of the language. Instead, the handler of an exception, which knows what to do with it, should decide whether a human-readable message should be generated for the exception, and if so, whether it should be readable only by programmers or also by users, and thus, what the locale (culture) should be.
Conceptually, you would have a two-dimensional table where on the X axis you would have locales, on the Y axis you would have exception type names, and each cell in the table would contain a string such as "Parameter %d cannot be null", in the right language. The first column would presumably be the neutral locale, i.e. the Invariant culture, containing programmer-readable messages.
Of course, in reality it will need to be slightly more complicated than that, because you will have to somehow read the type-specific members of the exception and pass them to the string formatting function.  For exceptions that you have control over, you can add an overridable and implement it like this:
public ParameterCannotBeNullException extends MyException
{
    private final int parameterNumber;

    public ParameterCannotBeNullException( int parameterNumber )
    {
        this.parameterNumber = parameterNumber;
    }

    public override String FormatMessage( String localeSpecificMessage )
    {
        return String.Format( localeSpecificMessage, parameterNumber );
    }
}

For exceptions that you have no control over, you can have a huge cascaded if statement, going like this:
String formatString = (look it up by exception.GetType() and locale)
String message;
if( exception is SomeException )
{
     SomeException temp = (SomeException)exception;
     message = String.Format( formatString, temp.X );
}
else if( exception is SomeOtherException )
{
     SomeOtherException temp = (SomeOtherException)exception;
     message = String.Format( formatString, temp.A, temp.B );
}
else
{
     message = exception.GetType().Name;
}

One final thing: sometimes while writing code we realize that we have come across a situation where an error may occur, so there is a need for a new exception to be thrown, but we do not want to interrupt what we are doing and go declare a new exception class at that moment. For such situations I have found it useful to have a GeneralPurposeException which does in fact accept a string in its constructor containing a programmer-readable message. But this class contains a great big huge comment that reads like this:

XXX FIXME TODO:
For development purposes only!
Thus class must not make it to production!


text:
Q: SwipeRefreshLyout not Working Properly So I have Fragment that is supposed to fetch some data from Internet using RecyclerView i want to add the Swipe Refresh Gesture to my Fragment so the user can check out if any new piece of data is on .
Here is my code :
Fragment :
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{

public HomeFragment() {
    // Required empty public constructor
}

RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_home, container, false);

    swipeRefreshLayout=(SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
    recyclerView = (RecyclerView) view.findViewById(R.id.recylerview);

    ReadRss readRss = new ReadRss(getContext(), recyclerView);
    readRss.execute();

    return view;
}

@Override
public void onRefresh() {

    new ReadRss(getContext(), recyclerView).execute();
    if(swipeRefreshLayout.isRefreshing())swipeRefreshLayout.setRefreshing(false);

}
}

XML Layout :
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipeRefreshLayout"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.essat.essat.HomeFragment"
    >

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/recylerview"
        />

>
</android.support.v4.widget.SwipeRefreshLayout>

The Problem is that the SwipeRefreshLayout never stops turning even with this piece of code :
if(swipeRefreshLayout.isRefreshing())swipeRefreshLayout.setRefreshing(false);

I Hope someone knows how to fix this , Thank You :)
UPDATE :
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://www.sciencemag.org/rss/news_current.xml";
ProgressDialog progressDialog;
URL url;
ArrayList<FeedItem>feedItems;
RecyclerView recyclerView;

public ReadRss(Context context,RecyclerView recyclerView  ) {
    this.recyclerView=recyclerView;
    this.context = context;

    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading...");
}

@Override
protected void onPreExecute() {
    progressDialog.show();
    super.onPreExecute();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressDialog.dismiss();
    ((IWithHttpRequest) context).onDataUpdate();
    Adapter adapter = new Adapter(context, feedItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.addItemDecoration(new VerticalSpace(20));
    recyclerView.setAdapter(adapter);

}

@Override
protected Void doInBackground(Void... params) {
    ProcessXml(Getdata());
    return null;
}

private void ProcessXml(Document data) {
    if (data != null) {
        feedItems=new ArrayList<>();
        Element root = data.getDocumentElement();
        Node channel = root.getChildNodes().item(1);
        NodeList items = channel.getChildNodes();
        for (int i = 0; i < items.getLength(); i++) {
            Node cureentchild = items.item(i);
            if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
                FeedItem item=new FeedItem();
                NodeList itemchilds = cureentchild.getChildNodes();
                for (int j = 0; j < itemchilds.getLength(); j++) {
                    Node cureent = itemchilds.item(j);
                    if (cureent.getNodeName().equalsIgnoreCase("title")){
                        item.setTitle(cureent.getTextContent());
                    }else if (cureent.getNodeName().equalsIgnoreCase("description")){
                        item.setDescription(cureent.getTextContent());
                    }else if (cureent.getNodeName().equalsIgnoreCase("pubDate")){
                        item.setPubDate(cureent.getTextContent());
                    }else if (cureent.getNodeName().equalsIgnoreCase("link")){
                        item.setLink(cureent.getTextContent());
                    }else if (cureent.getNodeName().equalsIgnoreCase("media:thumbnail")) {
                        String url = cureent.getAttributes().item(0).getTextContent();
                        item.setThumbnailUrl(url);
                    }
                }
                feedItems.add(item);
            }
        }
    }
}

public Document Getdata() {
    try {
        url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDoc = builder.parse(inputStream);
        return xmlDoc;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
}

Fragment Updated :
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,IWithHttpRequest{

public HomeFragment() {
    // Required empty public constructor
}

RecyclerView recyclerView;
SwipeRefreshLayout swipeRefreshLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_home, container, false);

    swipeRefreshLayout=(SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
    swipeRefreshLayout.setOnRefreshListener(this);
    recyclerView = (RecyclerView) view.findViewById(R.id.recylerview);

    ReadRss readRss = new ReadRss(getContext(), recyclerView);
    readRss.execute();

    return view;
}

@Override
public void onRefresh() {

    new ReadRss(getContext(), recyclerView).execute();

}

@Override
public void onDataUpdate() {
    swipeRefreshLayout.setRefreshing(false);
}
}

A: You forgot this in onCreateView
swipeRefreshLayout.setOnRefreshListener(this);

Also, new ReadRss(getContext(), recyclerView).execute(); is asynchronous, or at least should be (don't block the UI thread), so the it will look like the refresh is instantaneous.
The best solution here should be to create an interface
public interface IWithHttpRequest {
    void onDataUpdate()
}

Make your activity implement IWithHttpRequest
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, IWithHttpRequest {
    ...
    @Override
    public void onDataUpdate() {
        swipeRefreshLayout.setRefreshing(false);
    }
}

and in ReadRss, when you finished fetching data call
((IWithHttpRequest) context).onDataUpdate()

A: in order to refresh you should do this :
mSwipeRefreshLayout = (SwipeRefreshLayout) myFragmentView.findViewById(R.id.refreshContainer);
mSwipeRefreshLayout.setOnRefreshListener(new    SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
      // refresh logic
       if (mSwipeRefreshLayout.isRefreshing()) {
                mSwipeRefreshLayout.setRefreshing(false);
        }
}

You may also try to clear your data in recyclerview like this
YourAdapter.clearData();

A: You need to set setOnRefreshListener for the swipeRefreshLayout.
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(this);


text:
Q: Passing multi-dimensional arrays into functions errors I'm trying to pass a 2-D array into a function from the main function but I keep getting errors. What am I doing wrong?
Here's the code:
void modifyArray(int *array);
int main(int argc, char *argv[])
{
int array[3][3];
modifyArray(&array, 3, 3, 3);
}

void modifyArray(int *array, int value, int row, int column)
{
array[row][column] = value;
}

Errors:
 error #2140: Type error in argument 1 to 'modifyArray'; expected 'int *' but found 'int (*)[3][3]'.

Thanks in advance :)

A: Please read the error message properly, it explains what's wrong.
Furthermore, you should be getting more errors than the one you mention, as inside the modifyArray function you use array as an array of arrays which that variable isn't. Not to mention that you have two different declarations of modifyArray.
What every decent beginners book, tutorial or class should have told you is that arrays can decay to pointers to their first element. That is, in the main function when you use plain array then it's the same as &array[0]. And since each element of array is in turn an array, then &array[0] will be a pointer to such an array.
So the correct way to pass your array is simply to pass it as array, and the type needed to handle it will then be int (*)[3]:
void modifyArray(int (*array)[3], int value, size_t row, size_t column)
{
    array[row][column] = value;
}

int main(void)
{
    int array[3][3];

    modifyArray(array, 3, 1, 1);  // Will be the same as array[1][1] = 3
}

On another note, your current code also passes the indexes 3 for both row and column. For an array of 3 elements, the valid indexes are 0 to 2 (inclusive), which means an index of 3 will be out of bounds.

A: int array[3][3]; declares array to be an array of three arrays of three int.
&array takes its address, so the result is a pointer to an array of three arrays of three int.
In the declaration of modifyArray, int *array declares the parameter array to be a pointer to an int.
A pointer to an int is a different thing from a pointer to an array of three arrays of three int. So the compiler complains.
In general, if something is declared as a foo, and you pass it to a function, you can declare it in the function declaration as a foo:
void modifyArray(int array[3][3], int value, int row, int column);
int main(int argc, char *argv[])
{
    int array[3][3];
    modifyArray(array, 5, 1, 2);
}

C does engage in some shenanigans with array expressions and parameters. When a parameter is declared as an array, the compiler will adjust it to be a pointer. So declaring int array[3][3] for a parameter actually declares a pointer to an array of three int, int (*array)[3]. Only the outer/base parameter type of array is adjusted; further arrays inside the type are not adjusted.
Similarly, when an array is used in an expression other than as the operand of sizeof or of unary &, or, for string literals, to initialize an array, the compiler converts it to a pointer to its first element. So the call modifyArray(array, 5, 1, 2) actually passes &array[0] to the function. That matches the adjusted type, int (*array)[3], so it works. The resulting pointer can be used with the usual array notation, such as array[row][column].

A: If you had a one-dimensional array then this function declaration
void modifyArray(int *array);

is correct because it is equivalent to the following declaration
void modifyArray(int array[]);

That is the parameter having an array type is adjusted by the compiler to pointer to the array element type.
Though in general it is much better also to pass the number of elements in the array like
void modifyArray(int *array, size_t n);

And if you want to supply an initializer then the function declaration can look like
void modifyArray(int *array, size_t n, int value );

Pay attention to that the two function declarations in your program are different
void modifyArray(int *array);

and
void modifyArray(int *array, int value, int row, int column)

Moreover within the function this statement
array[row][column] = value;

will invoke undefined behavior because there is an access to memory beyond the array.
So if you have an array like this
int array[3][3];

then the corresponding function parameter will look like
void modifyArray( int array[][3], size_t n, int value );

or equivalently like
void modifyArray( int ( *array )[3], size_t n, int value );

So it is better to use a named constant for the integer literal 3 either like
#define  N  3

or like
enum { N = 3 };

And the function declaration will look like
void modifyArray( int ( *array )[N], size_t n, int value );

and the array declaration in main will look like
int array[N][N];

and the function itself can be called like
modifyArray( array, N, 3 );

If you want to set all elements of the array to the initializer then within the function you should write
for ( size_t i = 0; i < n; i++ )
{
    for ( size_t j = 0; j < N; j++ )
    {
        array[i][j] = value;
    }
}

If your compiler supports variable length arrays then the function declaration can look like
void modifyArray( size_t rows, size_t cols, int array[][cols], int value );

and the function can be called like
modifyArray( 3, 3, array, 3 );

In this case the function can be called for any two-dimensional array with arbitrary values of rows and columns.
Within the function the loops can look like
for ( size_t i = 0; i < rows; i++ )
{
    for ( size_t j = 0; j < cols; j++ )
    {
        array[i][j] = value;
    }
}

A: First, the boring background:
Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T" and the value of the expression will be the address of the first element.
The type of array is "3-element array of 3-element array of int".  Unless it is the operand of the sizeof or unary & operators, it "decays" to an expression of type "pointer to 3-element array of int", or int (*)[3].  The expression &array has type "pointer to 3-element array of 3-element array of int", or int (*)[3][3].
So, you have several possible avenues to deal with this. You can keep the function call the same and make the following changes to the function definition:
modifyArray( &array, 3, 2, 2 ); // A 3-element array is only indexed from 0 to 2
...                             // so writing to array[3][3] writes outside the
                                // bounds off the array, leading to undefined behavior

void modifyArray(int (*array)[3][3], int value, int row, int column)
{
  (*array)[row][column] = value;
}

Alternately, you can change the function call to leave off the & operator:
modifyArray( array, 3, 2, 2 );

and change the function definition to
void modifyArray(int (*array)[3], int value, int row, int column)
{
  array[row][column] = value;
}

Remember that the subscript operation a[i] is equivalent to *(a + i) - given an address a, offset i elements (not bytes) from that address and dereference the result.  array is the address of the beginning of a 3-element array, so array + i yields the address of the i'th 3-element array following that address.  Thus, *(array + row) is the same as array[row].
Final option - pass a pointer to the first element and treat it as  1D array in the function:
modifyArray( &array[0][0], 3, 2, 2 );
...
void modifyArray(int *array, int value, int row, int column)
{
  array[row * 3 + column] = value;
}

The first two options are limited in that they can only deal with arrays of a specific size - the first can only work with 3x3 arrays and the second can only work with Nx3 arrays.  The last option can deal with 2D arrays with any number of rows and columns, you just have to find some way to pass the number of rows.


text:
Q: Liberación memoria proceso vb.net Buenas a todos!
Tengo una aplicación en .net en la que exporto los datos de varias tablas y el formato de un Excel a varias hojas de otro excel.
En dicha exportación, voy copiando desde un template el formato de las celdas al Excel en el que a continuación importo los datos de las tablas.
Dicho proceso es el siguiente:
    Public Sub Copy_Paste(workbook_copy As Microsoft.Office.Interop.Excel.Workbook, sheet_copy As Microsoft.Office.Interop.Excel.Worksheet, range_copy As String, workbook_paste As Microsoft.Office.Interop.Excel.Workbook, sheet_paste As Microsoft.Office.Interop.Excel.Worksheet, Row_paste As Integer, Column_paste As Integer)
    workbook_copy.Activate()
    With sheet_copy
        .Select()
        .Range(range_copy).Copy()
    End With

    workbook_paste.Activate()
    With sheet_paste
        .Select()
        .Cells(Row_paste, Column_paste).select()
        .Paste()
    End With
End Sub

El problema que me surge es que debido al número de veces que repito este proceso llega un momento en el que se colapsa por saturación ya que creo que va guardando el copy-pega que va realizando. He probado con 'Clipboard.Clear()' y con el 'GC.collect() pero sigue produciéndose la excepción:

Ocurrió DisconnectedContext
  Message: El Asistente para la depuración administrada 'DisconnectedContext' ha detectado un problema.
  Información adicional: Transition into COM context 0x88ceb8 for this RuntimeCallableWrapper failed with the following error: System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED)).

Se que el problema es la saturación de información almacenada ya que el otro proceso que tengo (exportación de los datos de las tablas al Excel) me pasaba lo mismo, pero como utilizaba un objeto al finalizar su ejecución lo eliminaba y este espacio de memoria se liberaba pero en este caso estoy perdido.
Muchas gracias de antemano!

A: Tengo el mismo problema. Tomo los datos de una base de datos y creo el archivo xls. Cuando hay 600 líneas está bien, los tiempos son razonables pero si llego a más de 3000 líneas se necesitan más de dos horas. Comienza rápido pero luego se ralentiza hacia el final. ¿Has encontrado una solución?


text:
Q: Django: How can I implement a low level login using a md5 password column since I'm porting over my users table from an old site? Basically, I currently have login/ in urls.py redirect to the django.contrib.auth.views.login and that seems to work out fine.
However I'm porting over passwords from a legacy mysql/php site and I believe I should just create a new model profile per http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users. This new model/table will have the old md5 password column, and I'll port over the usernames to the main users table.
How could I change the login method such that I first check if the user has a password in the auth_user table, and if not then md5 the POST password field and attempt to match it to my new profile password column, if so save the password in the new auth_user table by SHA1 encrypting like how the admin does it?

A: I would create a new view that does something along the following:
from django.contrib.auth.models import User, check_password
import hashlib

def login_with_lookup(request):
    if request.POST: # If you want to restrict to POST
        username = request.POST['username']
        password = request.POST['password']
        user = User.objects.get(username=username)
        profile = user.get_profile()
        if profile.old_password != '' and profile.old_password == hashlib.md5(password).hexdigest():
            user.set_password(password)
            profile.old_password = ''
            user.save() # Might need to save profile as well, not sure how it works
        if check_password(password, user.password):
            login(request, user)
    #Whatever else you want to do, followed by a render to template or redirect

This is un-tested, so it will need a bit of clean-up.  It will also need error checking at different points to handle failure cases (this example assumes success).

A: Write a custom authentication backend:
http://docs.djangoproject.com/en/1.1/topics/auth/#writing-an-authentication-backend


text:
Q: How to use docker compose to make changes to application's configuration Is there any way I can make changes to my application's configuration before deployment?
I have 2 appservers that are connected up in a network. I have set the host endpoint in a config file call setting.json on the client.
{
"host_url" : "http://0.0.0.0:3201",
}
But I will be required to change this port number depending on production environment requirements. (Deployment done by another engineer using docker compose).
Is there any way I can set the host_url in the docker-compose and I tell him to change to the host_url depending on the requirement.

A: You can use a configuration like below. The app will use redis based on the REDIS_HOST set as the redis service. Similarly the MYSQL_HOST will be set to the db service.
version: '3.8'
services:
  redis:
    image: redis
  db:
    image: mysql
    ports: "6033:3306"
  app:
    build: .
    ports: "12345:8990"
    env:
      REDIS_HOST: redis
      REDIS_PORT: 6379
      MYSQL_HOST: db
      MYSQL_PORT: 3306

A: If the deployment should be different between development and production, the compose files should set different environment variables in each scenario for the application to pick up.
web:
  environment:
    - PORT

In CLI -
docker-compose run -e PORT=3201 web

At this point the PORT environment variable is available for your application to get the value from.

A separate environment file can be created for convenience too.
web:
  env_file:
    - web-variables.env

Complete documentation: https://docs.docker.com/compose/environment-variables/