text:
Q: Why is 0 divided by 0 an error? I have come across this problem in a calculation I do in my code, where the divisor is 0 if the divident is 0 too. In my code I return 0 for that case. I am wondering, while division by zero is generally undefined, why not make an exception for this case? My understanding why division by zero is undefined is basically that it cannot be reversed. However, I do not see this problem in the case 0/0.
EDIT OK, so this question spawned a lot of discussion. I made the mistake of over-eagerly accepting an answer based on the fact that it received a lot of votes. I now accepted AakashM's answer, because it provides an idea on how to analyze the problem.

A: Let's say:
0/0 = x

Now, rearranging the equation (multiplying both sides by 0) gives:
x * 0 = 0

Now do you see the problem? There are an infinite number of values for x as anything multiplied by 0 is 0.

A: This is maths rather than programming, but briefly:

*

*It's in some sense justifiable to assign a 'value' of positive-infinity to some-strictly-positive-quantity / 0, because the limit is well-defined

*However, the limit of x / y as x and y both tend to zero depends on the path they take. For example, lim (x -> 0) 2x / x is clearly 2, whereas lim (x -> 0) x / 5x is clearly 1/5. The mathematical definition of a limit requires that it is the same whatever path is followed to the limit.

A: Here's a full explanation:
http://en.wikipedia.org/wiki/Division_by_zero
( Including the proof that 1 = 2 :-)  )
You normally deal with this in programming by using an if statement to get the desired behaviour for your application.

A: The problem is with the denominator. The numerator is effectively irrelevant.
10 / n
10 / 1 = 10
10 / 0.1 = 100
10 / 0.001 = 1,000
10 / 0.0001 = 10,000
Therefore: 10 / 0 = infinity (in the limit as n reaches 0)

The Pattern is that as n gets smaller, the results gets bigger. At n = 0, the result is infinity, which is a unstable or non-fixed point. You can't write infinity down as a number, because it isn't, it's a concept of an ever increasing number.
Otherwise, you could think of it mathematically using the laws on logarithms and thus take division out of the equation altogther:
    log(0/0) = log(0) - log(0)

BUT
    log(0) = -infinity

Again, the problem is the the result is undefined because it's a concept and not a numerical number you can input.
Having said all this, if you're interested in how to turn an indeterminate form into a determinate form, look up l'Hopital's rule, which effectively says:
f(x) / g(x) = f'(x) / g'(x)

assuming the limit exists, and therefore you can get a result which is a fixed point instead of a unstable point.
Hope that helps a little,
Tony Breyal
P.S. using the rules of logs is often a good computational way to get around the problems of performing operations which result in numbers which are so infinitesimal small that given the precision of a machine's floating point values, is indistinguishable from zero. Practical programming example is 'maximum likelihood' which generally has to make use of logs in order to keep solutions stable

A: Look at division in reverse: if a/b = c then c*b = a. Now, if you substitute a=b=0, you end up with c*0 = 0. But ANYTHING multiplied by zero equals zero, so the result can be anything at all. You would like 0/0 to be 0, someone else might like it to be 1 (for example, the limiting value of sin(x)/x is 1 when x approaches 0). So the best solution is to leave it undefined and report an error.

A: You may want to look at Dr. James Anderson's work on Transarithmetic. It isn't widely accepted.
Transarithmetic introduces the term/number 'Nullity' to take the value of 0/0, which James likens to the introduction 'i' and 'j'.

A: The structure of modern math is set by mathematicians who think in terms of axioms.
Having additional axioms that aren't productive and don't really allow one to do more stuff is  against the ideal of having clear math.

A: (Was inspired by Tony Breyal's rather good answer to post one of my own)
Zero is a tricky and subtle beast - it does not conform to the usual laws of algebra as we know them.
Zero divided by any number (except zero itself) is zero. Put more mathematically:
 0/n = 0      for all non-zero numbers n.

You get into the tricky realms when you try to divide by zero itself.  It's not true that a number divided by 0 is always undefined. It depends on the problem. I'm going to give you an example from calculus where the number 0/0 is defined.
Say we have two functions, f(x) and g(x). If you take their quotient, f(x)/g(x), you get another function.  Let's call this h(x).
You can also take limits of functions. For example, the limit of a function f(x) as x goes to 2 is the value that the function gets closest to as it takes on x's that approach 2. We would write this limit as:
 lim{x->2} f(x)

This is a pretty intuitive notion. Just draw a graph of your function, and move your pencil along it. As the x values approach 2, see where the function goes.
Now for our example. Let:
 f(x) = 2x - 2
 g(x) = x - 1

and consider their quotient:
 h(x) = f(x)/g(x)

What if we want the lim{x->1} h(x)? There are theorems that say that
 lim{x->1} h(x) = lim{x->1} f(x) / g(x)
                = (lim{x->1} f(x)) / (lim{x->1} g(x))
                = (lim{x->1} 2x-2) / (lim{x->1} x-1)
                =~ [2*(1) - 2] / [(1) - 1]  # informally speaking...
                = 0 / 0
                  (!!!)

So we now have:
 lim{x->1} h(x) = 0/0

But I can employ another theorem, called l'Hopital's rule, that tells me that this limit is also equal to 2. So in this case, 0/0 = 2 (didn't I tell you it was a strange beast?)
Here's another bit of weirdness with 0. Let's say that 0/0 followed that old algebraic rule that anything divided by itself is 1.  Then you can do the following proof:
We're given that:
 0/0 = 1

Now multiply both sides by any number n.
 n * (0/0) = n * 1

Simplify both sides:
 (n*0)/0 = n
 (0/0) = n

Again, use the assumption that 0/0 = 1:
 1 = n

So we just proved that all other numbers n are equal to 1!  So 0/0 can't be equal to 1.
walks on back to her home over at mathoverflow.com

A: How many times does 0 go into 0?  5.  Yes - 5 * 0 = 0, 11.  Yes - 11 * 0 = 0, 43. Yes - 43 * 0 = 0. Perhaps you can see why it's undefined now?  :)

A: Since x/y=z should be equivalent to x=yz, and any z would satisfy 0=0z, how useful would such an 'exception' be?

A: Another explanation of why 0/0 is undefined is that you could write:
0/0 = (4 - 4)/0 = 4/0 - 4/0

And 4/0 is undefined.

A: If a/b = c, then a = b * c.
In the case of a=0 and b=0, c can be anything because 0 * c = 0 will be true for all possible values of c. Therefore, 0/0 is undefined.

A: This is only a Logical answer not a mathamatical one,
imagine Zero as empty how can you  Divide an empty by an empty this is the case in division by zero also how can you divide by something which is empty.

A: 0 means nothing, so if you have nothing, it does not imply towards anything to distribute to anything. Some Transit Facilities when they list out the number of trips of a particular line, trip number 0 is usually the special route that is routed in a different way. Typically, a good example would be in the Torrance Transit Systems where Line 2 has a trip before the first trip known as trip number 0 that operates on weekdays only, that trip in particular is trip number 0 because it is a specialized route that is routed differently from all the other routes.
See the following web pages for details:
http://transit.torrnet.com/PDF/Line-2_MAP.pdf
http://transit.torrnet.com/PDF/Line-2_Time_PDF.pdf
On the map, trip number 0 is the trip that is mapped in dotted line, the solid line maps the regular routing.
Sometimes 0 can be used on numbering the trips a route takes where it is considered the "Express Service" route.

A: As Andrzej Doyle said:
Anything dived by zero is infinity. 0/0 is also infinity. You can't get 0/0 = 1. That's the basic principle of maths. That's how the whole world goes round. But you can sure edit a program to say "0/0 is not possible" or "Cannot divide by zero" as they say in cell phones.

A:
why not make an exception for this
  case?

Because:

*

*as others said, it's not that easy;)

*there's no application for defining 0/0 - adding exception would complicate mathematics for no gains.

A: This is what I'd do:
function div(a, b) {
    if(b === 0 && a !== 0) {
        return undefined;
    }
    if(b === 0 && a === 0) {
        return Math.random;
    }
    return a/b;
}

A: When you type in zero divided by zero, there's an error because whatever you multiply zero from will be zero so it could be any number.


text:
Q: Clearing Output Window in NetBeans How do I clear the output window in NetBeans?
I mean the window where the "System.out.print" prints.
I tried doing:
Runtime.getRuntime().exec("cls");

But it doesn't work.
How can I clear the output window, then?

A: You need to right click the console window and click clear.
Have a look here: http://mrhaki.blogspot.in/2008/08/clearing-output-window-in-netbeans.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I use std::string* argv as main function argument? Usually I see:
int main(int argc, char** argv)

But can I use:
int main(int argc, std::string* argv)

instead?
If it's not possible how can I convert  char* to std::string?
PS: I am using C++11.

A: main argument must be char** argv or char* argv[].
[basic.start.main]

2. An implementation shall not predefine the main function.
This function shall not be overloaded.
Its type shall have C++ language linkage and it shall have a declared return type of type int, but otherwise its type is implementation-defined.
An implementation shall allow both
(2.1).
a function of () returning int and
(2.2).
a function of (int, pointer to pointer to char) returning int

What you can do is to convert the arguments in the code by using one of the following:

*

*Simply assigning it:

    if(argc > 1)
    {
        std::string str = argv[1];
    }

*

*Constructing the string using the argument as the constructor parameter:

    std::string str(argv[1]);

*

*With initializer list:

    std::string str{argv[1]};

If you'd like to keep a collection of the arguments I would suggest keeping them in a variable size container std::vector using one of the following:

*

*Constructing vector in place using std::vector constructor, here using pointers to the beginning and to one past the end the array of strings argv as constructor arguments:

    std::vector<std::string> strs(&argv[1], &argv[argc]); //*

*

*Using initializer list:

    std::vector<std::string> strs{&argv[1], &argv[argc]}; //*

*

*Adding the arguments in a loop:

    std::vector<std::string> strs;

    for(int i = 1; i < argc; i++) //*
        strs.push_back(argv[i]);
    }

*Not including argv[0] program name.

A: No, but you can create a std::vector<std::string> by using the vector constructor that takes iterators:
template< class InputIt >
vector( InputIt first, InputIt last, const Allocator& alloc = Allocator());

So to put the arguments (excluding the program name) in a vector:
std::vector<std::string> args(argv + 1, argv + argc);

To separate your ordinary main from your enhanced main you could do it like this:
#include <iostream>
#include <string>
#include <vector>

int cppmain(std::string program, std::vector<std::string> args) {
    std::cout << program << " got " << args.size() << " argument(s):\n";

    for(auto& arg : args) { // each argument as a string
        std::cout << " " << arg << '\n';
    }
    return 0;
}

int main(int argc, char* argv[]) {
    //
    //         string from char*
    //                |
    //                V
    return cppmain(argv[0], {argv + 1, argv + argc});
    //                      ^                     ^
    //                      |                     |
    //                     vector<string> from char*[]
}

A: No, but there has been some discussion of this in standards committee
In Paper P0781, Erich Keane suggests having the standard allow for the following:
int main(const some_container<const some_string_type> args){
  for (auto Arg : args) {
    // some usage of this character array...
  }
}

There's the question of which container and which string type should be used.  Mr. Keane suggests an initializer_list of string_view's - not std::string's, because the latter ones require a bunch of resources, while string_view's are very lightweight.

A: No, you can't. But you can use something like the following to store them as std::strings
#include <iostream>
#include <string>
#include <vector>

int main(int argc,char** argv){
    std::vector<std::string> strings(argc-1);
    for(size_t i{}; i < strings.size();++i){
        strings[i] = std::string{argv[i+1]};
    }
    for(const auto& el :strings)
        std::cout << el << " ";

    return 0;
}


text:
Q: Woocommerce plugin for minimum order and add-to-card-step I am looking for a way (plugin or code) to set for specific woocommerce products the minimum quantity to add to cart and the quantity increasing step. For example for product A the minimum quantity is 50 pcs. So when the user increases the quantity it should get these steps: 0-50-100-150.... If 0 is selected then it should display a message regarding the minimum quantity. Each product can have a different minimum quantity.

A: I think YITH Woocommerce Minimum Maximum Quantity plugin is the best solution for your purpose. It enables you to set a minimum or maximum quantity for product selection. It also shows quantity/amount error messages to your customers. Moreover, you can use the plugin to set a different minimum quantity for each of the product. So, I think it's the best option for you.


text:
Q: Restlet implementation with Guice Java development took a huge step forward with the introduction of Guice. My projects heavily depend on Warp-persist and its successor GuicePersist for persistency.
But there seems to be a mismatch between the use of Guice and Restlet.
It looks like its only possible to @Inject session and persistence factories from the servlet level.
For transaction handling i need Guice to create Restlet ServerResources which enable me to @Inject persistence stuff like @Transactional or UnitOfWork.

*

*Is there any change for Guice on the roadmap of Restlet?

*Are there best practices for the use of Guice with Restlet?
Regards,
Roland Beuker

A: Stackoverflow Related already pointed me to the blog "Restlet Guice extension considered ... unnecessary"
And indeed there's already a Guice extension for Restlet; Restlet Extensions => Guice


text:
Q: AppendChild (Javascript) and Internet Explorer As a student and someone fairly new to web development, I'm experiencing the following seemingly strange problem in Javascript - but only in IE (IE9 to be precise; haven't yet tried IE10). In Firefox, the script works without any problems.
The code is like this:
item = document.createElement('li'); alert("alert1");
message = document.createTextNode("Hallo"); alert("alert2");
item.appendChild(message); alert("alert3");

In IE, alert1 and alert2 are shown, but not alert3. In other words, IE9 chokes on the third statement above (the appendChild), and never reaches alert3. Strange indeed.
Using Google, I've found that there are known problems with appendChild in IE (at least in earlier versions). But none of the problems described, or the workarounds suggested, seem to match my simple code, as cited above.
Thanks in advance for any suggestions.
Edit to add: The console gives the following error message: "object doesn't support the property or method appendChild".

A: item is a native method in IE's window object.
You can rename your variable, or declare it properly:
var item = document.createElement('li');


text:
Q: cordova 4.3: danwilson/google-analytics-plugin throwing Cannot read property 'trackView' of undefined i successfully installed the plugin with instructions at https://github.com/danwilson/google-analytics-plugin using command
cordova plugin add https://github.com/danwilson/google-analytics-plugin.git
below is my tracker in index.js
    var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        console.log('Received Event: ' + id);
// replaced with fake tracker id
        window.analytics.startTrackerWithId('UA-1234-1');
    }
};
app.initialize();

now i am trying to use window.analytics.trackView('Landing') in landing.js file, but it throws Uncaught TypeError: Cannot read property 'trackView' of undefined
$(document).on('pagebeforeshow', '#landing', function(){
    window.analytics.trackView('Landing');
$(document).on('click', '#guest', function() {
        event.preventDefault();
        window.location.href = "guest_search.html";
});

below is the head tag of my home.html where i am getting my .js files
<head>
        <meta charset="utf-8" />
        <!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
        <meta name="viewport" content="initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
        <link href="css/style.css" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
        <script src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
        <script src="cordova.js" type="text/javascript"></script>
        <script src="js/index.js" type="text/javascript"></script>
        <script src="js/landing.js" type="text/javascript"></script>
    </head>

This is supposed to be very easy. dont know what i am doing wrong, any suggestions?


text:
Q: h:selectOneMenu default item to null, clear empty item value, required field Hello I'm having trouble with the following piece of code:
<h:selectOneMenu id="selectTipoAutorizacion"
                                                    value="#{autorizacion.codigoTipoAutorizacion}"
                                                    required="true">
                                                    <f:selectItems
                                                        value="#{cc.attrs.controller.getListaTiposAutorizacion(autorizacion)}"
                                                        var="tipoAutorizacion"
                                                        itemLabel="#{tipoAutorizacion.nombreTipoAutorizacion}"
                                                        itemValue="#{tipoAutorizacion.id.codigoTipoAutorizacion}" />

                                                    <a4j:ajax event="change" execute="@this"
         listener = #{myListener.listener}                                                                                render="selectAutorizador" />
                                                </h:selectOneMenu>

The problem is that the default selected value is always the first one of the  tag. And that's bothering the users, cause some data is loaded based on the selected item value..., however that info it's not loaded until the change event occurs (a4j:ajax tag), so right now the user has to select another item, and then select the previous one in order to see the default's item related info.
I addressed the problem by loading the default's item related info at the beginning, however the user doesn't like this. Because it could lead to confusion. So the question is... how could I avoid that behaviour? What I want is the selectOneMenu to load with a clear value( Like if there weren't any f:selectItems). Thanks a lot.

A: Your field is required, there should be nothing valid to default to in this case. Add an empty selectItem to the top of the list: selectItems.add(0, new SelectItem("", "")); or this way: <f:selectItem itemValue="" itemLabel="" />
By default it would then select the empty selectItem.
The user will be forced to make a choice as the required="true" does not allow an empty selection.

A: Just preload the desired data in the (post)constructor of the bean.
if (codigoTipoAutorizacion != null) {
    // Preload all other desired data as well.
}

A: Add an f:selectItem before the f:selectItems, with an empty value, or something like "please select ...", and mark it as non-selectable.


text:
Q: issue in calling UPDATE api retrofit2 I have a issue in calling update API, when i call api it's show success Toast message but execution is break from call.enqueue method i don't know where i mistake.
This is my Api url
My Url
https://56aba649.ngrok.io/api/update
My Interface class
public interface Api {
    @FormUrlEncoded
        @POST("update")
        Call<Message> updateUser( @Field("id") String id,
                               @Field("username") String username,
                               @Field("email") String email,
                               @Field("password") String password);
    }

My Model Class
public class user {

@SerializedName("id")
@Expose
private String  id;
@SerializedName("username")
@Expose
private String username;
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;

public user(String  id, String username, String email, String password) {
    this.id = id;
    this.username = username;
    this.email = email;
    this.password = password;
}

public String  getId() {
    return id;
}

public String getUsername() {
    return username;
}

public String getEmail() {
    return email;
}

public String getPassword() {
    return password;
}

public void setId(String  id) {
    this.id = id;
}

when i debug code it's going till call.enqueue(new Callback<Message>() this line after this line execution is break,
but Sucess Toast message is printed i don't know how it will success message without calling successfully
MainActivity class
private void updateUser(){

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Updating...");
        progressDialog.show();

        String   id = (ed1.getText().toString().trim());
        String email = ed2.getText().toString().trim();
        String username = ed3.getText().toString().trim();
        String password = ed4.getText().toString().trim();

        Api service = RetroClient.getApiService();

 user usr = new user(id,email,username,password);
 Call<Message> call = service.updateUser(
            usr.getId(),
            usr.getUsername(),
            usr.getEmail(),
            usr.getPassword());

 call.enqueue(new Callback<Message>() {
            @Override
            public void onResponse(Call<Message> call, Response<Message> response) {
                progressDialog.dismiss();
                Toast.makeText(Main2Activity.this,"Sucess",Toast.LENGTH_LONG).show();
}
          @Override
            public void onFailure(Call<Message> call, Throwable t) {

                progressDialog.dismiss();
                Toast.makeText(Main2Activity.this,"fail", Toast.LENGTH_SHORT).show();
}
        });
}

@Override
    public void onClick(View view) {

        if (view == btn1){

            updateUser();
        }
}


text:
Q: Undo with multitouch drawing in iOS I am working with multitouch while writing, So basically what I am doing is, I am writing with hand support, because typically, its how user rights, I followed this link How to ignore certain UITouch Points in multitouch sequence
Everything is working fine, but their is some problem with undo when I write with my hand touching the screen, otherwise it works fine.
Below is my code
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* topmostTouch = self.trackingTouch;
    for (UITouch *touch in touches)
    {
        ctr = 0;

        touchStartPoint1 = [touch locationInView:self];

        [m_undoArray removeAllObjects];
        [m_redoArray removeAllObjects];
        [m_parentRedoArray removeAllObjects];

        if(!topmostTouch || [topmostTouch locationInView:self].y > touchStartPoint1.y)
        {
            topmostTouch = touch;
            pts[0] = touchStartPoint1;
        }
    }

    if (self.trackingTouch != nil && self.trackingTouch != topmostTouch)  //              ![touches containsObject:self.trackingTouch])
    {
        [self discardDrawing];

    }

    self.trackingTouch = topmostTouch;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(self.trackingTouch== nil)
    {
        return;
    }

    CGPoint p = [self.trackingTouch locationInView:self];
    ctr++;
    pts[ctr] = p;

    if (ctr == 4)
    {
        pts[3] = midPoint(pts[2], pts[4]);

        self.currentPath = [[DrawingPath alloc] init];

        [self.currentPath setPathColor:self.lineColor];
        self.currentPath.pathWidth = [NSString stringWithFormat:@"%f",self.lineWidth];

        [self.currentPath.path moveToPoint:pts[0]];
        [self.currentPath.path addCurveToPoint:pts[3] controlPoint1:pts[1] controlPoint2:pts[2]];

        CGPathRef cgPath = self.currentPath.path.CGPath;
        mutablePath = CGPathCreateMutableCopy(cgPath);

        [m_undoArray addObject:self.currentPath];
        [self setNeedsDisplay];

        pts[0] = pts[3];
        pts[1] = pts[4];
        ctr = 1;
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches)
    {
        if(touch == self.trackingTouch)
        {
             [m_parentUndoArray addObject:[NSArray arrayWithArray:m_undoArray]];
        }
   }
}

-(void)undoButtonClicked
{
    NSMutableArray *undoArray = [m_parentUndoArray lastObject];

    NSLog(@"%@",undoArray);

    [m_parentUndoArray removeLastObject];
    [m_parentRedoArray addObject:undoArray];
     m_drawStep = UNDO;

    [self setNeedsDisplay];

}

- (void)drawRect
{
   I have different cases here, I am showing Of Undo

   for(int i = 0; i<[m_parentUndoArray count];i++)
   {
       NSMutableArray *undoArray = [m_parentUndoArray objectAtIndex:i];
       NSLog(@"%@",undoArray);

      for(int i =0; i<[undoArray count];i++)
      {
         DrawingPath *drawPath = [undoArray objectAtIndex:i];
         GPathRef path = drawPath.path.CGPath;
         mutablePath = CGPathCreateMutableCopy(path);

         //Draw into CgLayer
     }
   }
}

Here is the image to understand my problem better, I first wrote this

After clicking on Undo once,you can see above that, some other part has been undone, instead of the last part. So I need you help in this regard.

A: m_redoArray appears to be the big daddy, the one you draw from.  I don't understand why you empty this out out in 'touchesBegan...', surely one of these arrays must carry through touchesBegan unaltered, or you'll be dropping stuff from the start of your drawing all the way through, no?
It appears to me that this is how you dropped the 'Hell' in your example here..

A: Well in my case i have used bezierPath to draw on touch and have successfully implemented undo functionality. Here is the code :
- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    // Initialization code

    self.backgroundColor = [UIColor clearColor];
    myPath = [[UIBezierPath alloc] init];
    myPath.lineCapStyle = kCGLineCapRound;
    myPath.miterLimit = 0;
    bSize=5;
    myPath.lineWidth = bSize;
    brushPattern = [UIColor whiteColor];

    // Arrays for saving undo-redo steps in arrays
    pathArray = [[NSMutableArray alloc] init];
    bufferArray = [[NSMutableArray alloc] init];

  }
 return self;
}

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect
{
    [brushPattern setStroke];
    for (id path in pathArray){
        if ([path isKindOfClass:[UIBezierPath class]]) {
            UIBezierPath *_path=(UIBezierPath *)path;
            [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
        }
    }
}

#pragma mark - Touch Methods
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

             UITouch *mytouch = [[touches allObjects] objectAtIndex:0];
            myPath = [[UIBezierPath alloc] init];
            myPath.lineWidth = bSize;
            [myPath moveToPoint:[mytouch locationInView:self]];
            [pathArray addObject:myPath];

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
        [myPath addLineToPoint:[[touches anyObject] locationInView:self]];
        [self setNeedsDisplay];
}

#pragma mark - Undo Method
-(void)undoButtonClicked
{
    if([pathArray count]>0)
    {
    UIBezierPath *_path = [pathArray lastObject];
    [bufferArray addObject:_path];
        [pathArray removeLastObject];
        [self setNeedsDisplay];
    }

}
-(void)setBrushSize: (CGFloat)brushSize
{
    bSize=brushSize;
}

-(void)redoButtonClicked
{
    if([bufferArray count]>0){
    UIBezierPath *_path = [bufferArray lastObject];
    [pathArray addObject:_path];
    [bufferArray removeLastObject];
    [self setNeedsDisplay];
    }
}

Hope it will help you.


text:
Q: C# Calling C++ DLL Function which returns a struct I have an C++ dll which defines a struct and an dll call like this:
typedef const char* FString;

typedef struct {
    FString version;
    FString build_no;
    FString build_type;
    FString build_date;
    FString build_info;
    FString comment;
} FVersionInfo;

extern "C" FAPI_EXPORT FVersionInfo CALLINGCONV fGetVersion(void);

On the c# side i using an dynamic loading:
    [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
    static extern int LoadLibrary(
        [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

    [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
    static extern IntPtr GetProcAddress(int hModule,
        [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

    [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
    static extern bool FreeLibrary(int hModule);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct FVersionInfo
    {
        public string Version;
        public string Build_No;
        public string Build_Type;
        public string Build_Date;
        public string Build_Info;
        public string Comment;
    }

    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    public delegate FVersionInfo fGetVersion();

    public fGetVersion GetVersion;

    FHandle = LoadLibrary(@pName);
    IntPtr intPtr;
    intPtr = GetProcAddress(FHandle, "fGetVersion");
    GetVersion = (fGetVersion)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(fGetVersion));

The calling code should be:
FVersionInfo version = new FVersionInfo();
version = GetVersion();

My first problem is, that i become an "System.Runtime.InteropServices.MarshalDirectiveException" on the call of Marshal.GetDelegateForFunctionPointer in the c# loading part.
I have then tested using IntPtr as struct return parameter like that:
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public delegate IntPtr fGetVersion();

So i got the Marshal.GetDelegateForFunctionPointer to work, but later i've got the same problems with marshaling:
IntPtr DllValue = new IntPtr();
FVersionInfo version = new FVersionInfo();
DllValue = fGetVersion();
Marshal.PtrToStructure(DllValue, FVersionInfo);

Here it crashes at the fGetVersion() call with "Managed Debugging Assistant 'PInvokeStackImbalance'". I think it means, that the stack is corrupted (imbalanced).
I have tested with many variants of the structure definition, but no result.
Any ideas or suggestions would be welcome!

A: Thanks for the direction, but i found an working solution:

*

*I changed the declaration of the struct to

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct FVersionInfo
{
    public IntPtr Version;
    public IntPtr Build_No;
    public IntPtr Build_Type;
    public IntPtr Build_Date;
    public IntPtr Build_Info;
    public IntPtr Comment;
}

*So i passed the Marshal.GetDelegateForFunctionPointer without any problems.

*I changed my using code to:

GF.FVersionInfo vi = new GF.FVersionInfo();
vi = gf.GetVersion();

*After that, i could access the strings for example with

string MyVersion = Marshal.PtrToStringAnsi(VersionInfos.Version);

A: An example when using a struct with const char * members. This can be a scenario where you have your own C++ DLL structure to pass back and forth.
// CPP Source code
// ----------------------------------

// Struct definition
struct MyStruct_t {
    const char * sStr;
    size_t       iInt;
};
// ----------------------------------

// C# Source code
// ----------------------------------

// Struct definition
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct_t {
    public string sStr;
    public int    iInt;
};

// DLL prototype
[DllImport("Cpp.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void MyFunctionCall(IntPtr MyStruct_t);

// Prepare a struct pointer to pass to DLL
MyStruct_t pMyStruct_t = new MyStruct_t();
IntPtr pMyStructPTR    = Marshal.AllocHGlobal(Marshal.SizeOf(pMyStruct_t));
Marshal.StructureToPtr(pMyStruct_t, pMyStructPTR, false);

// Call C++ DLL
MyFunctionCall(pMyStructPTR);

// The DLL updated struct, get the struct
MyStruct_t pMyStruct = (MyStruct_t)Marshal.PtrToStructure(pMyStructPTR, typeof(MyStruct_t));

// Show data
MessageBox.Show(pMyStruct.sStr);

// clean up
if (pMyStructPTR != IntPtr.Zero) { Marshal.FreeHGlobal(pMyStructPTR); pMyStructPTR = IntPtr.Zero; }
// ----------------------------------


text:
Q: Matrix exponential of $4 \times 4$ (almost) skew-symmetric matrix I have a skew-symmetric matrix $A \in \mathbb{R}^{4 \times 4} $
$$ A = \begin{bmatrix} 0 & a & b & 0 \\ -a & 0 & c & 0 \\-b & -c & 0 & 0 \\ 0& 0 & 0 & 0\end{bmatrix} $$
another matrix $B\in \mathbb{R}^{4 \times 4} $
$$ B = \begin{bmatrix} 0 & 0 & 0 & t_1 \\ 0 & 0 & 0 & t_2 \\0 & 0 & 0 & t_3 \\ 0 & 0 & 0 & 0\end{bmatrix} $$
Also $C = A+ B$ and the question is what is
$$ D = e^{A + B} $$
I have checked that
$$ D = \begin{bmatrix} e^A & x \\ 0 & 1\end{bmatrix} \in \mathbb{R}^{4 \times 4}$$
But I cannot figure out what $x$ is. Has anyone thoughts on this? Thanks

A: Write
$$
(A+B)^n = \pmatrix{A^{(n)} & x^{(n)}\\0&0}
$$
We have
$$
(A+B)(A+B)^{n} = \pmatrix{AA^{(n)} & Ax^{(n)}\\0&0}
$$
So, we may show inductively that $A^{(n)} = A^n$, and $x^{(n)} = A^n x$ for $n \geq 1$, where $x = (t_1,t_2,t_3)^T$.  That is, $(A + B)^0 = I$, and
$$
(A + B)^n = \pmatrix{A^n & A^n x\\0&0} \quad n \geq 1
$$
As such, we have
$$
\exp(A + B) = \sum_{n=0}^\infty \frac 1{n!}(A+B)^n =
\pmatrix{\sum_{n=0}^\infty \frac 1{n!} A^n & \sum_{\color{red}{n=1}}^\infty \frac 1{n!}A^n x\\0&1} = \\
=\pmatrix{e^A & (e^A - I) x\\0&1}
$$


text:
Q: Organizing .xhtml files in subfolders I have a JSF 2.0 project wiht lots of .xhtml files. Due to a security filter I want to put some of the files in a /secure folder to then aply the filter on.
I tried simply moving the files to a folder. But then I get an exception
"/selectRole.xhtml Not Found in ExternalContext as a Resource"
Do I need to add something to the faces-config or web.xml?

A: Your application is trying to read /selectRole.xhtml from a bean, or redirect action.
In JSF2, the navigation rules are written in the beans. The return String of the method, may return the location of the file relatively to WebContent folder.
EDIT:
Please note, that it may appear also in faces-config.xml file, though is not recommended.
Look where you have declared it, (usually in the bean file that redirects to it) and change it to return "/secure/selectRole"
For example:
Public class myBean{
  public String save(){
    return "/secure/selectRole";
   }
}

Another place where I can think of, is in another .xhtml file - where in h:link you link to this page.


text:
Q: remedy for a no scroll wheel trackball? I am thinking to buy an trackball and my option is Logitech trackman marble. But then I found that there is no scroll wheel. How do you tackle with that? Do I definitely want to buy a trackball with scroll wheel? I scroll a lot using facebook.
I don't want to click with my index and middle fingers, so some trackball mice will not work for me, like the Trackman Wheel.

A: You could try the Marble Mouse Scroll Wheel, developed especially for that mouse :

Marble Mouse Scroll Wheel, or just Marble Scroll, is a small program
  designed to simulate a scroll wheel on any trackball or mouse without
  one. It was specifically designed for the Logitech Marble Mouse but
  can work with any standard mouse or trackball. It is designed for
  Windows 2000 and up.
Marble Scroll is a replacement for Logitech's Autoscroll and Universal
  Scroll functions; neither properly emulate a real scroll wheel and
  both have limitations and flaws.
Marble Scroll works with any mouse or trackball and does not require
  Logitech's SetPoint or MouseWare drivers to be installed.
Features

*

*Add a scroll wheel to any mouse with more than two buttons

*Compatiblity with most applications that support a scroll wheel (for any type of input)

*Adjustable acceleration

*Adjustable scrolling distance (per "step" - see below)

*Stepped scrolling to simulate a real mouse wheel

*Quick left/right handed mode switcher

*Quick enable/disable by clicking on the tray icon

*Small and light on system resources

The product's website seems currently down,
but here is a copy of the site's text on Archive.org.
A download link is here.

A: Here's the AutoHotKey script that I use.  You scroll by holding down the left small button and rolling the ball up/down.  However clicking the left small button still does BACK.  It can also scroll left/right but that was too sensitive for me so it's commented out here (the block that starts with ;timesX := Abs(movedx) / 4).
I found the original version at
http://www.autohotkey.com/board/topic/30816-simulate-scroll-wheel-using-right-mouse-button/.  I posted my version there as anotherperson8923.
$*XButton1::
Hotkey, $*XButton1 Up, XButton1up, off
;KeyWait, XButton1, T0.4
;If ErrorLevel = 1
;{
   Hotkey, $*XButton1 Up, XButton1up, on
   MouseGetPos, ox, oy
   SetTimer, WatchTheMouse, 5
   movedx := 0
   movedy := 0
   pixelsMoved := 0
;   TrayTip, Scrolling started, Emulating scroll wheel
;}
;Else
;   Send {XButton1}
return

XButton1up:
Hotkey, $*XButton1 Up, XButton1up, off
SetTimer, WatchTheMouse, off
;TrayTip
If (pixelsMoved = 0)
{
    ;The mouse was not moved, send the click event
    ; (May want to make it PGUP or something)
    Send {XButton1}
    Send {XButton1Up}
}
return

WatchTheMouse:
MouseGetPos, nx, ny
movedx := movedx+nx-ox
movedy := movedy+ny-oy

pixelsMoved := pixelsMoved + Abs(nx-ox) + Abs(ny-oy)

;timesX := Abs(movedx) / 4
;ControlGetFocus, control, A
;Loop, %timesX%
;{
;    If (movedx > 0)
;    {
;        SendMessage, 0x114, 1, 0, %control%, A ; 0x114 is WM_HSCROLL
;        movedx := movedx - 4
;    }
;    Else
;    {
;        SendMessage, 0x114, 0, 0, %control%, A ; 0x114 is WM_HSCROLL
;        movedx := movedx + 4
;    }
;}

timesY := Abs(movedy) / 4
Loop, %timesY%
{
    If (movedy > 0)
    {
        Click WheelDown
        movedy := movedy - 4
    }
    Else
    {
        Click WheelUp
        movedy := movedy + 4
    }
}

MouseMove ox, oy
return

A: It's such a shame Logitech didn't implement a scroll wheel simulation. Their driver promises a feature to do so, but it does not work for all applications, rendering it quite useless. They were so close to creating the perfect mouse! :s
The only workaround I've found is to use an AutoHotkey script for it. With it you can make the tiny left/right buttons scroll up and down. It works perfectly, but it is a real hassle to get it configured: you'll need to learn the AutoHotkey basics first. If you decide to do so, here is my AutoHotkey script. It is an adaptation of Jerbo's original script. A single click will start scrolling at a normal pace, but a double or tripple click will start scrolling faster.
; This script remaps the two small buttons on a Logitech Trackman® Marble® Mouse
; to act as scroll up and scroll down

global lastXButton1ClickTime := 0
global nrSubsequentXButton1Clicks := 0

ScrollTheWheel(direction, scrollKey)
{
    now := A_TickCount
    timeSinceLastClick := now - lastXButton1ClickTime
    lastXButton1ClickTime := now
    if (timeSinceLastClick < 300)
    {
        nrSubsequentXButton1Clicks := nrSubsequentXButton1Clicks + 1
    }
    else
    {
        nrSubsequentXButton1Clicks := 1
    }

    sleepingFraction := 5

    if (nrSubsequentXButton1Clicks <= 1)
        scrollSpeed := 30
    if (nrSubsequentXButton1Clicks == 2)
        scrollSpeed := 15
    if (nrSubsequentXButton1Clicks >= 3)
        scrollSpeed := 5

    timeSlept := scrollSpeed

    loop
    {
        if (direction == 1) ; Scroll down
        {
            static downKeyState
            if (scrollKey == 0)
                GetKeyState, downKeyState, XButton1, P
            else
                GetKeyState, downKeyState, PgDn, P

            if downKeyState = U ; The key has been released, so break out of the loop
               break

            if (timeSlept >= scrollSpeed)
            {
                Send {WheelDown}
                timeSlept = 0
            }
        }
        else ; Scroll up
        {
            static upKeyState
            if (scrollKey == 0)
                GetKeyState, upKeyState, XButton2, P
            else
                GetKeyState, upKeyState, PgUp, P

            if upKeyState = U ; The key has been released, so break out of the loop
               break

            if (timeSlept >= scrollSpeed)
            {
                Send {WheelUp}
                timeSlept = 0
            }
        }

        Sleep, sleepingFraction
        timeSlept := timeSlept + sleepingFraction
    }
}

XButton2::
    ScrollTheWheel(0, 0)
    return
XButton1::
    ScrollTheWheel(1, 0)
    return
!PgUp::
    ScrollTheWheel(0, 1)
    return
!PgDn::
    ScrollTheWheel(1, 1)
    return

A: I just got a Logitech Marble mouse and also had the problem of scrolling. So I have made this script on AutoHotKey. The left Xbutton enables scrolling, meaning that while down you can scroll vertically and horizontally with the ball, and move forward and backwards in the browser with the left and right buttons. The right Xbutton has the same action as the middle button.
Im on windows 7.
#SINGLEINSTANCE FORCE
GLOBAL status := "basic"
GLOBAL cnt_x
GLOBAL cnt_y

XButton2::MButton

$*XButton1::
    status := "scroll"
    cnt_x := 0
    cnt_y := 0
    MOUSEGETPOS, st_x, st_y
    SETTIMER, _scroll, 30
RETURN

$*XButton1 UP::
    status := "basic"
    SETTIMER, _scroll, OFF
RETURN

_scroll:
    MOUSEGETPOS, cur_x, cur_y
    MOUSEMOVE, st_x, st_y

IF(abs(cur_x-st_x) > abs(cur_y-st_y)) {
    cnt_x := cnt_x + (cur_x-st_x)
    ControlGetFocus, control, A
    IF (cnt_x > 7) {
        cnt := floor(cnt_x / 8)
        LOOP, %cnt% {
            SendMessage, 0x114, 0, 0, %control%, A
        }
        cnt_x := cnt_x - 8*floor(cnt_x / 8)
    } ELSE IF (cnt_x < -7) {
        cnt := -ceil(cnt_x / 8)
        LOOP, %cnt% {
            SendMessage, 0x114, 1, 0, %control%, A
        }
        cnt_x := cnt_x - 8*ceil(cnt_x / 8)
    }
} ELSE {
    IF (cur_y >= st_y) {
        cnt_y := cnt_y + (cur_y-st_y)**1.2
    } ELSE {
        cnt_y := cnt_y -(st_y-cur_y)**1.2
    }
    IF (cnt_y > 7) {
        cnt := floor(cnt_y / 8)
        LOOP, %cnt% {
            CLICK WheelUp
        }
        cnt_y := cnt_y - 8*floor(cnt_y / 8)
    } ELSE IF (cnt_y < -7) {
        cnt := -ceil(cnt_y / 8)
        LOOP, %cnt% {
            CLICK WheelDown
        }
        cnt_y := cnt_y - 8*ceil(cnt_y / 8)
    }
}
RETURN

$*LButton::
    IF (status = "basic") {
        CLICK DOWN Left
    } ELSE IF (status = "scroll") {
        SEND {Browser_Back}
    }
RETURN

$*LButton UP::
    IF (status = "basic") {
        CLICK UP Left
    }
RETURN

$*RButton::
    IF (status = "basic") {
        CLICK DOWN Right
    } ELSE IF (status = "scroll") {
        SEND {Browser_Forward}
    }
RETURN

$*RButton UP::
    IF (status = "basic") {
        CLICK UP Right
    }
RETURN

A: Another solution for Windows 7 that allows scrolling in all applications, including Internet Explorer:

*

*Install AutoHotKey.

*Save this script as scroll.ahk to the Desktop.

*Right-click on scroll.ahk.

*Select Run Script.

*Confirm, if prompted.

This will make holding the small right button scroll vertically when moving the trackball. The small left button is the back button.

In case the link to Erik Elmore's code disappears, here it is:
;;
;; Emulate_Scrolling_Middle_Button.ahk
;; Author: Erik Elmore <erik@ironsavior.net>
;; Version: 1.1 (Aug 16, 2005)
;;
;; Enables you to use any key with cursor movement
;; to emulate a scrolling middle button.  While
;; the TriggerKey is held down, you may move the
;; mouse cursor up and down to send scroll wheel
;; events.  If the cursor does not move by the
;; time the TriggerKey is released, then a middle
;; button click is generated.  I wrote this for my
;; 4-button Logitech Marble Mouse (trackball),
;; which has no middle button or scroll wheel.
;;

;; Configuration

;#NoTrayIcon

;; Higher numbers mean less sensitivity
esmb_Threshold = 7

;; This key/Button activates scrolling
esmb_TriggerKey = XButton2

;; End of configuration

#Persistent
CoordMode, Mouse, Screen
Hotkey, %esmb_TriggerKey%, esmb_TriggerKeyDown
HotKey, %esmb_TriggerKey% Up, esmb_TriggerKeyUp
esmb_KeyDown = n
SetTimer, esmb_CheckForScrollEventAndExecute, 10
return

esmb_TriggerKeyDown:
  esmb_Moved = n
  esmb_FirstIteration = y
  esmb_KeyDown = y
  MouseGetPos, esmb_OrigX, esmb_OrigY
  esmb_AccumulatedDistance = 0
return

esmb_TriggerKeyUp:
  esmb_KeyDown = n
  ;; Send a middle-click if we did not scroll
  if esmb_Moved = n
    MouseClick, Middle
return

esmb_CheckForScrollEventAndExecute:
  if esmb_KeyDown = n
    return

  MouseGetPos,, esmb_NewY
  esmb_Distance := esmb_NewY - esmb_OrigY
  if esmb_Distance
    esmb_Moved = y

  esmb_AccumulatedDistance := (esmb_AccumulatedDistance + esmb_Distance)
  esmb_Ticks := (esmb_AccumulatedDistance // esmb_Threshold) ; floor divide
  esmb_AccumulatedDistance := (esmb_AccumulatedDistance - (esmb_Ticks * esmb_Threshold))
  esmb_WheelDirection := "WheelDown"
  if (esmb_Ticks < 0) {
    esmb_WheelDirection := "WheelUp"
    esmb_Ticks := (-1 * esmb_Ticks)
  }

  ;; Do not send clicks on the first iteration
  if esmb_FirstIteration = y
    esmb_FirstIteration = n
  else {
    Loop % esmb_Ticks {
      MouseClick, %esmb_WheelDirection%
    }
  }

  MouseMove,esmb_OrigX,esmb_OrigY,0
return

A: If you're on Windows I'd suggest trying out AutoHotKey, other users have already tackled scrolling with the Marble Mouse (I used the script a the bottom):
http://www.autohotkey.com/board/topic/4677-wheel-button-emulation-script/
Logitech's solution that comes with their drivers is strange: you click once to enable 4 way scrolling and click again to disable it. You can't hold and scroll which is what I was after. I wound up uninstalling their software.

A: There is a simple 100 line C++ alternative which is quite similar to the AutoHotKey solutions, that is

*

*sending vertical/horizontal scroll wheel events by moving the trackball while holding one of the X-Buttons and

*middle click when pressing and releasing an X-Button without moving the trackball.

https://github.com/Seelge/TrackballScroll
Edit: Newer versions provide a systray-icon, work on Windows 10 and are based on C#.

A: I have the same trackball and the solution is very elegant: when you click on a chosen button, the ball itself become a scrolling wheel. I've chosen the big right button that I press with the little finger.
This is very convenient and it takes only a few day to get used.
You will quickly consider that any scrollwheel (on a mouse or a trackball) is something unusable. Trust me, it worth it ;-)
Advantages:

*

*2D scrolling instead of 1D

*quicker and more precise scrolling than a wheel

*more comfortable for long scroll (thanks to the ball's inertia). Perfect for your facebook example.

I cannot live without it anymore.
Configuring that under any Linux OS is not hard. It only requires you to create a /etc/X11/xorg.conf file (see my config here: Configure a trackball under Linux without editing Xorg.conf )
More details can be found here: https://help.ubuntu.com/community/Logitech_Marblemouse_USB
On Windows, I've no experience but I think a configuration tool is delivered with the trackball.

A: Depending on your OS, you may be able to configure one of the buttons to enable scrolling via moving the pointer when held. E.g. the following script enables this on button 10 of my mouse (the "top middle" button of the Logitech MX310):
#!/bin/sh
xinput set-prop "Logitech USB-PS/2 Optical Mouse" 290 10
xinput set-prop "Logitech USB-PS/2 Optical Mouse" 286 1
xinput set-prop "Logitech USB-PS/2 Optical Mouse" 287 6 7 4 5

A: There are such marble mouse (mice) that have a scroll wheel included. Otherwise,it looks like an app or some script would be required for a non wheeled mouse along with the use of one of the buttons to engage a scroll function (that you noted in a comment to another answer, as not an acceptable solution).
So "Why reinvent the wheel?" is a good adage in this case.
In these examples, the element is physically installed and there are many types to choose from. Below are two examples and styles.

Or something like this:Adesso

A: I'm on Windows7 and using the Kensington Orbit Optical Trackball without scrollring - it's a two-button trackball, without the X-buttons required by most of the AHK scripts and applications pointed out by others.
However, MouseImp is working for me on Windows7. IT's configurable, but I have it set up for right-click + roll to get me a screen of scrolling. It's more like a drag, so the pointer moves, and you've only got one screen at a time [update: the scroll rate is configurable, so it can be more than "one page"].
At the same time, Kensington's TrackballWorks has been configured to give me a page-down scroll on left-click + right-click. Unfortunately it can't then scroll back up a page at a time (one or the other).
This is not a product plug - it's just what I've found to work with this model/type of trackball.
Caveat: you are constantly right and left clicking, and this can lead to confusing, and links being followed/js-activated when you just want to stop scrolling. :::sigh:::

A: A simple (and ergonomic dare I say) solution is to put the function of scrolling on your lefthand.
This could be achieved by using a mouse with your left hand/ by using a keyboard with a built-in scroll wheel on its left edge/ by assigning scrolling functions to the keys of a programmable keypad with a program like Mkey (http://www.seriosoft.org/en/index.php).
Why do I think this is more ergonomic - because this approach distributes tension more evenly on both hands. (More about this: http://capsoff.org/checklist).

A: I actually made something for this using AutoHotkey a while back and figured I'd share it here as well: Mouse Wheel Emulator
This emulates mouse wheel scrolling by moving the mouse around while holding the left and right mouse buttons.
You can also emulate a middle click by clicking the left and right mouse buttons at the same time.

A: Another Trackman Marble user here.
I'm using X-Mouse Button Control for scroll emulation. This feature implementation isn't perfect there (yet?), but it is much more usable than the Logitech implementation in their own SetPoint™ software.
I recommend XMBC to anyone who don't want to mess with AutoHotKey and looking for something that just works.

A: Two non conventional options

*

*Use an Apple Magic Trackpad in addition to the trackball. (This is my current solution)
http://www.apple.com/magictrackpad/

*Purchase a leapmotion controller and use it in addition to the trackball. Wave your hand in front of the device to scroll up and down. https://www.leapmotion.com/product

Image credit http://www5.pcmag.com/media/images/393268-leap-motion-controller.jpg

A: I just got an orbit wireless trackball from kensington, it it´s pretty amazing. You have the ball, you have both buttons on each side and you have a kind of circle outside the trackball that makes possible to scroll up or down the page. It really works, and I am using on Windows and Mac OSX.

A: (Yet) another solution is to use this simple program called MarbleScroll for Logitech Trackman Marble.

Few details about MarbleScroll:

*

*works on Windows XP, Vista, 7, 8, 8.1, 10, …

*build for .NET framework 4.5, but it should compile on any other if you choose it in project source

*compiled for right handed mouse, but it works for left handed too.

*runs in system tray where you can close it if you require to

*vertical and horizontal scrolling with back button + marble movement

*back button without marble movement produces normal back operation

*scrolls the windows under mouse pointer without focusing it

The author even shared the source code as well as the visual studio project.
Note that it is compatible with SetPoint.

A: I just bought Kensington Orbit Trackball which only has 2 buttons and one ball without scroll ring. https://www.kensington.com/en-ca/p/products/ergonomics/ergonomic-input-devices/orbit-optical-trackball-1/ .
I found this autohotkey script which works great on Windows 10 PC.
Here is the link. https://github.com/mmikeww/DragToScroll . The little tweak you might need to do is to adjust the "MovementCheckDelay" to a bigger number. You might also need to run this script as admin, otherwise it will not work with those apps running as admin.
I tried most methods mentioned in this thread. DragToScroll is the most effective.
The shape of this trackball is great, the angle is more comfortable compare to their expensive trackballs.


text:
Q: How do you check the order of a set of actions, given ranks for each of them? I have this dataframe.
user    action    date        rank
AAA     jump      2018-01-01  1
AAA     climb     2018-01-02  2
AAA     leap      2018-01-03  3
BBB     jump      2018-01-01  1
BBB     climb     2018-01-03  2
BBB     leap      2018-01-05  3
BBB     gallop    2018-01-08  4
CCC     leap      2018-01-01  1
CCC     climb     2018-01-02  2
CCC     gallop    2018-01-04  3

It takes the actions and adds a rank per user according to the date, in ascending order.
I want to locate any users who took actions in the wrong order. The order should be jump -> climb -> leap -> gallop.
The output would be CCC since that user did leap before climb.
user
CCC

How do you make a reference to a particular row? I am using dplyr and I can group it by each user and add the rank for each user, with row_number(), but I don't know how to make rules that check whether the actions are happening in the correct order.
Note - I realized this was unclear. Not every user takes all the actions, but the order still matters.
This is what I have working so far
badData <- NULL
for (i in df$user){
  filtered <- filter(df, user == i)

  first <- ifelse(filtered[filtered$action == "jump",]$rank > 1, TRUE, FALSE)
  second <- ifelse(filtered[filtered$action == "climb",]$rank < filtered[filtered$action == "jump",]$rank, TRUE, FALSE)
  #and so on for the rest of the rules

  if(first + second > 0) badData <- c(badData, i)
}

A: If you make action a factor and use the levels argument to set the order, you can group by user, then test if the actions are unsorted using is.unsorted:
library(dplyr)

df %>%
  mutate(action = factor(action, levels = c("jump", "climb", "leap", "gallop"))) %>%
  group_by(user) %>%
  filter(is.unsorted(action)) %>%
  pull(user) %>%
  unique

[1] "CCC"

A: Here is a small example you can achieve this.
You first create a refrence dataframe  (refdata) which contains the correct order.
Then you can easily work with the tidyverse package:
mydata <- tibble(id = rep(c("aaa", "bbb", "ccc"), each = 4), action = letters[c(1:4, 1,2 ,4, 3, 4,1,2,3)],
       date = rep(1:3, 4))

refdata <- tibble(action = letters[1:4], right_order = 1:4)

mydata %>% left_join(refdata, by = "action") %>% group_by(id) %>%
  summarise(test = identical(right_order, sort(right_order)))


text:
Q: AndEngine sprites are locked when setting velocity after collision in onManagedUpdate method I have to create a game in which there is one player sprite and several(approx 30) other sprites who moves randomly on the screen without colliding within themselves. I have problem in avoiding collision, since when detecting collision all the moving sprites are locked.
Below is my code..In my code I have created two classes one is MainActivity( This is the main class which extends BaseGameActivity and creates approx 30 AnimatedSprites using the NewSprite class and contains a static array list 'playerSprite' of NewSprite objects(approx 30 objects created randomly) and the second is NewSprite( which extends AnimatedSprite and overloads the method onManagedUpdate() to prevent these moving AnimatedSprites from going offscreen and collision between them.)
I have only shown NewSprite class..
public class NewSprite extends AnimatedSprite{
public PhysicsHandler physicsHandler;
Random randPos;

public NewSprite(final float pX, final float pY, final ITiledTextureRegio pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
    super(pX, pY, pTiledTextureRegion, pVertexBufferObjectManager);

    randPos = new Random();
    float x1;
    float y1;
    while((x1 = randPos.nextFloat()) < 0.8f);
    while((y1 = randPos.nextFloat()) < 0.8f);
    if(randPos.nextInt() % 2 == 0)
        x1 *= -1;
    if(randPos.nextInt() % 2 == 0)
        y1 *= -1;

    physicsHandler = new PhysicsHandler(this);
    this.registerUpdateHandler(physicsHandler);

    physicsHandler.setVelocity(x1 * 100, y1 * 100);
}

@Override
protected void onManagedUpdate(float pSecondsElapsed) {
    // TODO Auto-generated method stub

    if(this.mX < 0){
        this.move++;
        float x2,y2;
        while((x2 = randPos.nextFloat()) < 0.8f);
        while((y2 = randPos.nextFloat()) < 0.8f);
        if(randPos.nextInt() % 2 == 0)
            y2 *= -1;
        physicsHandler.setVelocity( x2*40,  y2*40);
        this.prevX = this.mX;
        this.prevY = this.mY;
    }
    else if(this.mY < 0){
        this.move++;
        float x2,y2;
        while((x2 = randPos.nextFloat()) < 0.8f);
        while((y2 = randPos.nextFloat()) < 0.8f);
        if(randPos.nextInt() % 2 == 0)
            x2 *= -1;
        physicsHandler.setVelocity( x2*40,  y2*40);
        this.prevX = this.mX;
        this.prevY = this.mY;
    }
    else if(this.mX > (MainActivity.CAMERA_WIDTH - MainActivity.MONSTER_WIDTH)){
        this.move++;
        float x2,y2;
        while((x2 = randPos.nextFloat()) < 0.8f);
        while((y2 = randPos.nextFloat()) < 0.8f);
        x2 *= -1;
        if(randPos.nextInt() % 2 == 0)
            y2 *= -1;
        physicsHandler.setVelocity( x2*40,  y2*40);
        this.prevX = this.mX;
        this.prevY = this.mY;
    }
    else if(this.mY > (MainActivity.CAMERA_HEIGHT - MainActivity.MONSTER_HEIGHT)){
        this.move++;
        float x2,y2;
        while((x2 = randPos.nextFloat()) < 0.8f);
        while((y2 = randPos.nextFloat()) < 0.8f);
        if(randPos.nextInt() % 2 == 0)
            x2 *= -1;
        y2 *= -1;
        physicsHandler.setVelocity( x2*40,  y2*40);
        this.prevX = this.mX;
        this.prevY = this.mY;
    }

    for(int i=0 ; i < MainActivity.playerSprite.size(); i++){

        if(( MainActivity.playerSprite.get(i)).collidesWith(this) || this.collidesWith(MainActivity.playerSprite.get(i))){

            float x2, y2;
            while((x2 = randPos.nextFloat()) < 0.8f);
            while((y2 = randPos.nextFloat()) < 0.8f);

            if(randPos.nextInt() % 2 == 0)
                x2 *= -1;
            if(randPos.nextInt() % 2 == 0)
                y2 *= -1;

            this.physicsHandler.setVelocity( x2*100,  y2*100);
            break;
        }
    }
    super.onManagedUpdate(pSecondsElapsed);
}

A: Did you tried to put your code after the super.onManagedUpdate(pSecondsElapsed); ?


text:
Q: How to find the code for color I like? There is a color I like in an image, but how can I find the code [ i.e. #FFC6A5 ] for it ? The image is in .png format.

A: Open the file in an image editing program, then use the Eyedropper tool to select that color. You should be able to retrieve the hex value from there.
Alternatively, you could download ColorPic. It's a free utility that allows you to do the same thing, but without opening the image first. You can simply move the Eyedropper tool around the screen and select any color you hover over (whether it's in an image or not).

A: ColorZilla lets you do this. Its a handy Firefox Add-on. Of course you will hav to open the image in firefox but its handy if you want to know the color code of an image in a website.


text:
Q: C# - Raw socket cannot capture outgoing UDP I'm using raw socket to capture incoming and outgoing UDP packet. My code is something like this:
public void Start() {
  if (m_Monitor == null) {
    try {
      m_Monitor = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
      m_Monitor.Bind(new IPEndPoint(IP, 0));
      m_Monitor.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes((int)1), BitConverter.GetBytes((int)1));
      m_Monitor.BeginReceive(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
    } catch {
      m_Monitor = null;
      throw new SocketException();
    }
  }
}

private void OnReceive(IAsyncResult ar) {
  try {
    int received = m_Monitor.EndReceive(ar);
    try {
      if (m_Monitor != null) {
        byte[] packet = new byte[received];
        Array.Copy(Buffer, 0, packet, 0, received);
        OnNewPacket(new Packet(packet));
      }
    } catch
    {
    } // invalid packet; ignore

    m_Monitor.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);

  } catch {
    Stop();
  }
}

Incoming is ok but I cannot see any outgoing packet while Wireshark can (I'm using packet player to replay my old .pcap record). Firewall is off. Windows 10 1709.
Mostly it based on http://www.mentalis.org/soft/projects/pmon/
Any suggest? Thanks.


text:
Q: how to calculate derivatives of integer valued functions? Definitions:

*

*$[x]$ is the integer value of $x$. For example: $[4.3]=4$.

*$\{x\}=x-[x]$.
Can someone help me calculate the derivative of the following functions, and determine where the derivative are not defined?

*

*$[x^2]\sin^2(\pi x)$

*$\{x^2\}\sin^2(\pi x)$
Thank you!!

A: For the first one:
Consider 2 intervals $ A = [ \sqrt n, \sqrt{n+1} )$ and $ B = [ \sqrt {n+1}, \sqrt{n+2} )$. Of course, $n$ is an integer.
Now, in the first interval, your function becomes $ n\sin^2(\pi x) $. It's derivative is $ n\pi\sin(2\pi x) $. Call it $ f'_1(x) $.
Consider the second interval. Your function becomes $ (n+1)\sin^2(\pi x) $. It's derivative is $ (n+1)\pi\sin(2\pi x) $. Call it $ f'_2(x) $
Clearly it is differentiable within each interval. We now have to check if it is differentiable even at the point $ x = \sqrt {n+1} $.
For that, we must have $ \lim _{x\to(\sqrt{n+1})^-} f'_1(x) = \lim _{x\to(\sqrt{n+1})^+} f'_2(x) $.
That is, we must have:
$ n\pi\sin(2\pi \sqrt{n+1}) = (n+1)\pi\sin(2\pi \sqrt{n+1}) $
Which will be true when $ \sqrt{n+1} $ is an integer. In other words, it is differentiable when $n+1$ is a perfect square.

So, your function is differentiable everywhere, except at those integers which are not perfect squares. Note, here our intervals consisted only of positive integers, but a simple sign change will give the same result for negative integers.
I think the same logic can be applied to the second function.

A: Derivate Fourier expansion
$$\{x\}= \frac{1}{2} - \frac{1}{\pi} \sum_{k=1}^\infty \frac{\sin(2 \pi k x)} {k}$$


text:
Q: How can I set up error_log by folder? My company has a large hosting, but it's not managed by us, we don't see configuration files, but I want to reply this feature on our local test server.
I'm new in my company and want to start some debug of applications to fix some minors and majors issues to clients, but the amount of files is so big that single error_file is huge.. and there are many people working on this so each time I check log (like 30 secs to 1 min) has hundreds of added lines.
I don't know if this is set up on Apache, through .htaccess files or in php.ini.
I am talking about PHP errors, but I don't know if this is set in PHP, Apache, or maybe using a third-party library.
I'm not talking about setting a specific folder error_log. I'm talking about if errors are logged in the scripts folder.
Example: I create a folder named test1. Inside it I make some buggy PHP script that throws some errors. When I run the script I can see an error_log file created in the folder. So it works on the fly.
I have tried to ask the hosting company support how they do this, but they haven't answered me.

I don't know if maybe could be some kind of cPanel setting (BTW, the hosting support stuff doesn't understand this question either, but well.. usually level 1 of support can't handle technical stuff).

A: I found it.
You have to set a directive in the php.ini file as follows, string "error_log". On the right side is the file name you want for the log,
error_log = error_log

This will generate a PHP error log in the folder where script executed are,
I'll try to explain.
Script test.php in folder /www/site/lib:
include "./db_conn.php";

If file db_conn.php is not located in the same directory, this will fire a warning and error. Usually this will be lead to the servers/vhost log, but using this directive you will get an error_log file under the /www/site/lib directory.
Why was I looking or this? Well, as I wrote, I'm working on a huge application, with thousands of files many fires warnings, notices, etc. I'm not the only one in the project and the site error_log file was so huge it was hard to keep tracking debug evolution for one or just some files. Now I just have to track the log from directories where I'm working.

A: You can manage the logs by adding this to your vhost or htaccess file
ErrorLog /path/to/a/writable/directory/error.log

For more information, have a look at this article on advanced PHP error handling via htaccess.

A: To do this in PHP, edit file php.ini and add the line
error_log = /path/to/where/you/want/your/php-errors.log

Then restart the web server. This should give you PHP errors, and only PHP errors, to that file. Provided, of course, that the scripts aren't written to throw away all errors.
To do it in Apache, you can use SetEnvIf to add an environment variable to any request ending in PHP, and then printing all logs with that particular environment variable. E.g.:
SetEnvIf Request_URI "\.php$" phplog
CustomLog /path/to/php.log env=phplog

To use this in multiple folders, make one environment variable per folder and one CustomLog per folder, like this:
SetEnvIf Request_URI "/folder1/.*\.php$" log_folder1
Customlog /path/to/folder1/php.log env=log_folder1

SetEnvIf Request_URI "/folder2/.*\.php$" log_folder2
Customlog /path/to/folder2/php.log env=log_folder2


text:
Q: Can hardware threads access main memory at the same time? I am trying to understand microarchitecture.
When an operating system schedules code to run on a CPU hardware thread (as in Intel HyperThreading), can each execution context issue memory reads in parallel or is the pipeline shared?
I am trying to do some rough calculations and complexity analysis and I want to know if memory bandwidth is shared and if I should divide my calculation by the number of cores or hardware threads (assuming the pipeline is shared) or hardware threads (the memory bandwidth is parallel).

A: Yes, the pipeline is shared, so it's possible for each the two load execution units in a physical core to be running a uop from a different logical core, accessing L1d in parallel.  (e.g. https://www.realworldtech.com/haswell-cpu/5/ / https://en.wikichip.org/wiki/amd/microarchitectures/zen_2#Block_Diagram)
Off-core (L2 miss) bandwidth doesn't scale with number of logical cores, and one thread per core can fairly easily saturated it, especially with SIMD, if your code has high throughput (not bottlenecking on latency or branch misses),  and low computational intensity (ALU work per load of data into registers. Or into L1d or L2 cache, whichever you're cache-blocking for).  e.g. like a dot product.
Well-tuned high-throughput (instructions per cycle) code like linear algebra stuff (especially matmul) often doesn't benefit from more than 1 thread per physical core, instead suffering more cache misses when two threads are competing for the same L1d / L2 cache.
Cache-blocking aka loop tiling can help a lot, if you can loop again over a smaller chunk of data while it's still hot in cache.  See How much of 'What Every Programmer Should Know About Memory' is still valid? (most of it).


text:
Q: Why is the next statement executed before yield? I'm expecting the program to pause until yield is executed but it's not. The DisplayTileBacks() function runs while PauseGame() is being executed:
void Start()
{
...
        DisplayTileFronts();
        StartCoroutine(PauseGame(3f));
        DisplayTileBacks();
}

public IEnumerator PauseGame(float waitTime)
{
    Time.timeScale = 0f;
    float waitEndTime = Time.realtimeSinceStartup + waitTime;
    while (Time.realtimeSinceStartup < waitEndTime)
    {
        yield return 0;
    }
    Time.timeScale = 1f;
}

What am I doing wrong?

A: You need to edit code similar to the following.
void Start()
{
...

    StartCoroutine(Display(3f));
}

public IEnumerator Display(float waitTime)
{
    DisplayTileFronts();
    yield return new WaitForSeconds(waitTime));
    DisplayTileBacks();
}


text:
Q: After place order moving to empty cart page. 502 bad gateway error We are using Magento 1.14 enterprise edition. We are moving to new AWS server.
I have place order using Guest user it is working fine. I will try to place order using register user.order was placed and it is redirect to Empty cart page.
I have checked inspect element. in Prototype.js 502 bad gateway error occurs
Any idea on this issue?

A: I think it might be the issue with your nginx configuration. Please add the below in nginx configuration. Basically, it may be the problem with the header and it is unable to pass too big data. It might solve your problem.
proxy_buffers 8 16k;
proxy_buffer_size 32k;
If it doesn't workout, please check by disabling the full page cache and try again. If it works fine after disabled the full page cache, then it is something wrong with the cache storage. Please increase the storage space for cache. Also, check if APC cache enabled and increase the space.

A: The actual error will be displayed if you edit app/bootstrap.php and enable display_errors
Change
#ini_set('display_errors', 1);

To
ini_set('display_errors', 1);

Then try the same scenario as before and then you will get the actual error in your Inspector


text:
Q: ComboBox control shows no items I'm trying to learn the basics of C# and decided to make a simple windows form to demonstrate the Dictionary class, but when I start my program, the Combo-/ListBox controls stay blank, although I loaded some data to them. Hope you could help me out with this.
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ClassDictionaryExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Dictionary<string, string[]> CountryList = new Dictionary<string, string[]>();

        private void Form1_Load(object sender, EventArgs e)
        {
            CountryList["Bulgaria"] = new string[] { "Sofia University St Kliment Ohridski", "Technical University of Sofia",
                "Plovdiv University Paisii Hilendarski" };
            CountryList["Romania"] = new string[] { "Alexandru Ioan Cuza University", "Babes-Bolyai University",
                "University of Bucharest" };
            CountryList["Serbia"] = new string[] { "University of Belgrade", "University of Novi Sad", "University of Niš" };

            foreach (var CountryKey in CountryList.Keys)
            {
                comboBoxCountry.Items.Add(CountryKey);
            }

            comboBoxCountry.SelectedIndex = 0;
        }

        private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedCountry = comboBoxCountry.SelectedItem.ToString();

            if (comboBoxCountry.SelectedIndex == 0)
                listBoxUniversities.Items.Clear();
            else
            {
                listBoxUniversities.Items.Clear();
                listBoxUniversities.Items.AddRange(CountryList[selectedCountry]);
            }
        }
    }
}

A: I tried to reproduce your problem but could not. You need to keep in mind that you have to assign 2 events to your code. One on FormLoaded and other on ComboboxSelectionChanged.
I have reduced your code to show universities when selected Index is zero.
public Form1()
{
    InitializeComponent();

    this.Load += Form1_Load;
    comboBoxCountry.SelectedIndexChanged += comboBoxCountry_SelectedIndexChanged;
}

private Dictionary<string, string[]> _countryList;
public Dictionary<string, string[]> CountryList
{
    get
    {
        if (_countryList == null)
        {
            _countryList = new Dictionary<string, string[]>();
            _countryList["Bulgaria"] = new string[] { "Sofia University St Kliment Ohridski", "Technical University of Sofia", "Plovdiv University Paisii Hilendarski" };
            _countryList["Romania"] = new string[] { "Alexandru Ioan Cuza University", "Babes-Bolyai University", "University of Bucharest" };
            _countryList["Serbia"] = new string[] { "University of Belgrade", "University of Novi Sad", "University of Niš" };
        }

        return _countryList;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    foreach (var CountryKey in CountryList.Keys)
        comboBoxCountry.Items.Add(CountryKey);

    comboBoxCountry.SelectedIndex = 0;
}

private void comboBoxCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    string selectedCountry = comboBoxCountry.SelectedItem.ToString();

    listBoxUniversities.Items.Clear();
    listBoxUniversities.Items.AddRange(CountryList[selectedCountry]);
}


text:
Q: List of Maps returns undefined in DynamoDB query I am querying a DynamoDB. It has an attribute called 'Multiple Units' with the following structure: List [ Map { Map { S }, S }, ... ]
I test a lambda locally:
module.exports.getByAddress = async (event) => {
  const params = {
    TableName: process.env.tableName,
    Key: {
      Address: event.pathParameters.address
    }
  };
  var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
  docClient.get(params).promise().then(
    returnResult => console.log(returnResult)
  )
}

This is the output:
Item: {
...
license: '',
Coordinates: { lng: '-71.075985', lat: '42.346096' },
'Multiple Units': [ [Object], [Object], [Object], [Object], [Object], [Object] ],
...
}

When I attempt to console.log Multiple Units list specifically, I get undefined.
In reading about DynamoDB get/getItem, I am guessing it has to do with async but I cannot configure a change that will result in correct output.

A: Based on your comment, you mention that you're getting undefined when you execute console.log(returnResult['Multiple Units']).
Take a closer look at what console.log(returnResult) is printing:
Item: {
   ...
   license: '',
   Coordinates: { lng: '-71.075985', lat: '42.346096' },
   'Multiple Units': [ [Object], [Object], [Object], [Object], [Object], [Object] ],
...
}

Notice that it's printing a map with the key of Item.  Therefore, to get at your data, try to console.log(returnResult.Item['Multiple Units'])
You can check out the DynamoDB SDK API for more info regarding the result of a get call.


text:
Q: Calculating Sample Size for Cluster Randomized Trials with Person-level or Cluster-Level Outcomes I have been looking for a formula to calculate the estimated sample size for a two-level cluster-randomized controlled trial with cluster-level outcome data. To my reading, several authors do not make this distinction in their formulae; they refer to a 'group mean difference' or 'effect size' without specifying whether it is at the individual-level or cluster-level (assuming level 1 = individual and level 2 = site).
Rutterford, Copas, and Aldridge (2015) mention the following:

"For example, with continuous
  outcomes a cluster-level analysis is equivalent to
  an individual-level analysis if all the clusters are the same
  size." p. 1053

I used Optimal Design Software to calculate the number of clusters needed for a person-level continuous outcome with an effect size of .5 at 90% power and an equal cluster size.
Would this sample size estimate be the same if the outcome was at the cluster level (assuming a continuous measure and equal allocation, as suggested by Rutterford et al.)? In other words, are the sample size estimates interchangeable for person- and cluster-level outcomes, which is why authors do not usually make this distinction?
If not, can you recommend a software (preferably a freeware) for calculating the the number of clusters needed for a cluster-randomized trial with cluster level outcomes? I know Optimal Design Software has this feature, but there is no option to change the cluster size, which I feel will be important in the estimate.


text:
Q: Big React App - How to improve my app structure Can you help me with ideas on how to improve my structure because it becomes very big
Please read my code
My current structure is like so.

This is the parent component (App.js) Biggest component I have
import React, { PureComponent } from 'react';
import { Route, withRouter } from 'react-router-dom';
import Home from "./public/home";
import Dashboard from "./private/dashbaord";
...(around 66 component/packages imports)

class App extends PureComponent {
        constructor(props){
        super(props);
        this.state = {
            pathname: '/public',
            ...(around 15 states)
        };
    }

     componentDidMount() {
       this.checkAccepedCookies();
       this.isLogged();
       this.check404();
       this.insertGTM();
       this.insertTrustPiloit();
       this.checkDarkMode();
     }

     updateData(); //The updateData function used to update the pathname state so I can know if it's public or private
     connectWebSocket();
     signout();
     ...(around 21 functions)

    render(){
        return(

                {this.state.isPolicy && <PolicyModal isPolicy={this.state.isPolicy} openPolicy={(boolean)=>this.setState({isPolicy: boolean})} />}
                {this.state.isOpenTrack && <TrackOrderModal isOpenTrack={this.state.isOpenTrack} ...(passing 3 props functions) />}
                {this.state.openUsers && <LoginModal ...(passing 3 props functions) />}
                {this.state.isOpenContact && <ContactSupportModal isOpenContact={this.state.isOpenContact} onClose={this.} />}
                {this.state.pathname === '/public' && <NavHome />}
                {!this.state.isCookiesAccepted && <CookiesModal openPolicy={()=>this.setState({isPolicy: true})} accept={()=>this.setState({isCookiesAccepted: true})} />}

                 //Buyers Routers
                    <Route path='/buy/' render={()=><BuyersBuy  updateData={this.updateData} />} />
                    <Route path='/refund/' render={()=><BuyersRefund  updateData={this.updateData} />} />
                    <Route path='/download/' render={()=><BuyersDownload updateData={this.updateData} />} />
                    ...(Around 18 Routes for Buyers)

                    //Then I have the sellers routers it's around 5 routers wrapped in a div like so

                //Sellers Routers

                    {this.state.pathname === '/private' && <TopNavBarSellers />}
                    {this.state.pathname === '/private' && <LeftNavBarSellers />}
                    <Route path='/dashbaord/' render={()=><SellersDash updateData={this.updateData} />} />
                    (4 routers more)

                //Users Routers (I haven't implemented the users section yet because I'm confused
                // because the users section will be around 5 routers with 5 function extra I'm feeling I'm harming the app performance and this not a correct structure.)

            {this.state.pathname === '/public' && <FooterBuyers />}

        )
    }
}

This App.js is the biggest file I have the other I have a just small
Please guide me with corect structer that could have Buyers Routers - Sellers Routers - Users Routers

A: My Approach for smaller files would be some nested routing.
For example: Group all buyer routes into one component.
class App extends PureComponent {
  ...
  render() {
    return(

        ...
        <Route path='/buyers/' component={BuyersRoot} />
        ...

    )
  }
}

...

const BuyersRoot = (props) => {
  const { path }  = useRouteMatch();
  return (
    <Switch>
      <Route path={path +'buy'} render={()=><BuyersBuy  updateData={this.updateData} />} />
      <Route path={path +'refund'} render={()=><BuyersRefund  updateData={this.updateData} />} />
      <Route path={path +'download'} render={()=><BuyersDownload updateData={this.updateData} />} />
      ...(Around 18 Routes for Buyers)
  </Switch>
  )
}

Edit1:

*

*You can exclude the RouteRoots to separate Files.

*Split up the logic in your App Component into separate Files

*Use some state management to reduce the amount of logic inside your component files.

*Build service files that only contain logic stuff.

*Exclude the conditional display logic into the rendering of the
Subcomponents and let every component decide whether it should be
rendered or not

*Split up /private and /public routes into RoutingComponents where you can handle authentication and so on.

*Build higher-order-components to inherit state or context to childs.

So basically:
Pull everything logically apart to shrink your components.
But keep everything in context together.
Be sure that you don't pull your app too far apart so that no one understands what belongs together.
Sometimes this is a very fine line.


text:
Q: Error con android studio 2.3.3 >> :Failed to find target with hash string 'android-26' ¿Qué puedo hacer para resolver el siguiente error?

Error:Failed to find target with hash string 'android-26' in: E:\ARIEL\Carrera\Programas\AndroidSDK
Install missing platform(s) and sync project

Actualmente tengo la version 2.3.3 de android studio, graddle 3.5 y en la carpeta SDK/plataforms tengo esto:

Y tambien tengo esto cuando intento instalar nuevas API, ya lo he reinstalado varias veces y me sale lo mismo, y no se si es porque soy cubano y lo instalo sin internet o algo:

Gracias por su ayuda

A: Para descargar la API 26, debes entrar al SDK MANAGER:

Luego, en la pestaña que dice SDK PLATFORMS seleccionas la versión que deseas descargar:

Por ultimo, en la pestaña SDK TOOLS seleccionas las herramientas necesarias como lo son Support-Repository, Android-Sdk tools, Android-Sdk Platforms Tools y el Android-Sdk Build Tools.

PD: Recuerda siempre mantener actualizadas todas estas herramientas para evitar posibles errores al compilar.


text:
Q: Bundle React build results into single html file I'm using React and Webpack to create report page with test logs. I'm planning to distribute and store them offline and I'd prefer to have these reports each in a single html file. So I basically would like this html file to store inline js code. I can copy it manually after each release but is there any tool that can do it for me in a webpack? Thanks in advance!

A: Maybe this will work for you, with "html-webpack-plugin" you can generate an HTML file with a script tag to your index.js bundle. You can view documnetation here.
The code will be like this:
var HtmlWebpackPlugin = require('html-webpack-plugin');
...
...
plugins: [
new HtmlWebpackPlugin({
  template: 'app/index.html'
  })
],


text:
Q: How to compile objc(c++, c) source on jailbroken iPad? I've installed gcc but when I execute this comand:

    gcc test.c

It says me:

    test.c:1:18: error: stdio.h: No such file or directory
test.c: In function 'main':

test.c:5: warning: incompatible implicit declaration of builit-in function 'printf'

Test.c:

#include <stdio.h>
int main(void)
{
    printf("Hello, World!\n");
    return 0;
}

A: Well i just did the same, but you need to copy the header files into the ipad /usr/include via SSH but after that i keep getting other errors so there must be another step after copying the headers.

A: You need to add -I/var/include. iphone-gcc fails to notice that most of the main headers needed are under that folder and search on other directory that you can see with gcc -v test.c.
Try this way or copy all the headers and libraries from an SDK (preferably from the same of the iOS version you have) to /usr/include and /usr/lib.
You'll still need the Frameworks under /Library/Frameworks or you'll have to add the location they are via -F/path/to/framework/from/sdk


text:
Q: Recylerview with header showing data but minus 1 So i have three records, but when i trying to show it via my android app it is only showing two .
Here is my adapter for my recylerview
   public class Sales_header_adapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_ITEM = 1;
    private List<Sales_header_model> salesheaderlist;

    public Sales_header_adapter(List<Sales_header_model> salesheaderlist) {
        this.salesheaderlist = salesheaderlist;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View VHItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.sales_header_rec, parent, false);
            return new VHItem(VHItem);
        } else if (viewType == TYPE_HEADER) {
            View VHHeader = LayoutInflater.from(parent.getContext()).inflate(R.layout.sales_header_rec_header, parent, false);
            return new VHHeader(VHHeader);
        }
        throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VHItem) {
            Sales_header_model as =  salesheaderlist.get(position);
            VHItem VHitem = (VHItem)holder;
            VHitem.nonota.setText(as.getNoNota());
            VHitem.tanggal.setText(as.getTanggalTransaksi());
            VHitem.total.setText("Rp. 1.000.000");

        } else if (holder instanceof VHHeader) {
            Sales_header_model dataItem = getItem(position);
            VHHeader VHheader = (VHHeader)holder;
            VHheader.nonota_h.setText("No Nota");
            VHheader.tanggal_h.setText("Tanggal");
            VHheader.total_h.setText("Total");
        }
    }

    @Override
    public int getItemCount() {
        return salesheaderlist.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;
        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position  == -1;
    }

    private Sales_header_model getItem(int position) {
        return salesheaderlist.get(position);
    }

    class VHItem extends RecyclerView.ViewHolder {
        public TextView  tanggal, total,nonota;
        public VHItem(View itemView) {
            super(itemView);
            tanggal         =  itemView.findViewById(R.id.tanggalnota);
            total           =  itemView.findViewById(R.id.total);
            nonota          =  itemView.findViewById(R.id.nonota);
        }
    }

    class VHHeader extends RecyclerView.ViewHolder {
        public TextView  tanggal_h, total_h,nonota_h;
        public VHHeader(View itemView) {
            super(itemView);
            tanggal_h               = itemView.findViewById(R.id.tanggalnota_h);
            total_h                 = itemView.findViewById(R.id.total_h);
            nonota_h                = itemView.findViewById(R.id.nonota_h);
        }
    }
}

from my getItemCount i get 3 . how can i fix it , thanks in advance . Reference Is there an addHeaderView equivalent for RecyclerView?

A: Do this :
private boolean isPositionHeader(int position) {
        return position == 0;
    }

private Sales_header_model getItem(int position) {
    return salesheaderlist.get(position - 1);
}

instead of :
private boolean isPositionHeader(int position) {
        return position  == -1;
    }
private Sales_header_model getItem(int position) {
    return salesheaderlist.get(position);
}


text:
Q: Html2pf/html2canvas/jsPDF not showing borders using bootstrap modal I'm not sure which of the required libraries is raising this issue, or if it has something to do with Bootstrap, but I can't get the output PDF to show borders.
I've tried increasing the width of the border but it just gets ignored, not sure what to do here.
Fiddle : https://jsfiddle.net/8q7ce58y/233/
I have tried using .clone() in the modal body, but then it only renders down to what was on the window view.
Code : (it's best to check the fiddle)

Doc Preview

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                      </button>

Text

Field :

{Field_Name}

Images

            Image1

            Image2

<button class="ml-auto btn btn-primary ld-ext-right">Download PDF

</button>

Css :
.modal-dialog.modal-a4{
    width: 8.27in !important;
    padding: 0;
}
.modal-a4 .modal-body>*:last-child {
  border-bottom: 10px solid black;
}

.modal-a4 .modal-body>* {
  border-left: 10px solid black;
  border-right: 10px solid black;
}

.modal-a4 .modal-body>*:not(.attachment-row) {
  border-top: 10px solid black;
}

A: I used html2canvas with jsPDF
function savePdf(){
    // body tag of html
    html2canvas(document.body).then(function(canvas) {
        var jpegUrl = canvas.toDataURL("image/jpeg");
        var doc = new jsPDF('l', 'mm', [318, 210]);
        doc.addImage(jpegUrl, 'JPEG', 10, 10);
        doc.save('sample-file.pdf');
    });
 }

Libraries

Download html2canvas:
https://html2canvas.hertzen.com/
html2canvas.js
html2canvas.min.js

and call the function by button or input:
<button id="cmd" onclick="savePDF()">generate PDF</button>

A: html2canvas does not support the css border-left / border-right properties. It only supports border-color, border-width, border-style.
See documentation : https://html2canvas.hertzen.com/features

A: I solved the problem of adding modal, for your reference. GOOD JOB!
Library jsPdf
    let imageUrl = "url your file image"
    var doc = new jsPDF();
    doc.addImage(imageUrl, 'png', 15, 40, 180, 160);

    var blob = doc.output('blob');
    $('#iframe_view').attr('src', URL.createObjectURL(blob))

if you want new tab ==>

    window.open(URL.createObjectURL(blob))