text:
Q: Best way to generate a List sequence of values given start, end, and step? I'm actually very surprised I was unable to find the answer to this here, though maybe I'm just using the wrong search terms or something. Closest I could find is this, but they ask about generating a specific range of doubles with a specific step size, and the answers treat it as such. I need something that will generate the numbers with arbitrary start, end and step size.
I figure there has to be some method like this in a library somewhere already, but if so I wasn't able to find it easily (again, maybe I'm just using the wrong search terms or something). So here's what I've cooked up on my own in the last few minutes to do this:
import java.lang.Math;
import java.util.List;
import java.util.ArrayList;

public class DoubleSequenceGenerator {

     /**
     * Generates a List of Double values beginning with `start` and ending with
     * the last step from `start` which includes the provided `end` value.
     **/
    public static List<Double> generateSequence(double start, double end, double step) {
        Double numValues = (end-start)/step + 1.0;
        List<Double> sequence = new ArrayList<Double>(numValues.intValue());

        sequence.add(start);
        for (int i=1; i < numValues; i++) {
          sequence.add(start + step*i);
        }

        return sequence;
    }

    /**
     * Generates a List of Double values beginning with `start` and ending with
     * the last step from `start` which includes the provided `end` value.
     *
     * Each number in the sequence is rounded to the precision of the `step`
     * value. For instance, if step=0.025, values will round to the nearest
     * thousandth value (0.001).
     **/
    public static List<Double> generateSequenceRounded(double start, double end, double step) {

        if (step != Math.floor(step)) {
            Double numValues = (end-start)/step + 1.0;
            List<Double> sequence = new ArrayList<Double>(numValues.intValue());

            double fraction = step - Math.floor(step);
            double mult = 10;
            while (mult*fraction < 1.0) {
                mult *= 10;
            }

            sequence.add(start);
            for (int i=1; i < numValues; i++) {
              sequence.add(Math.round(mult*(start + step*i))/mult);
            }

            return sequence;
        }

        return generateSequence(start, end, step);
    }

}

These methods run a simple loop multiplying the step by the sequence index and adding to the start offset. This mitigates compounding floating-point errors which would occur with continuous incrementation (such as adding the step to a variable on each iteration).
I added the generateSequenceRounded method for those cases where a fractional step size can cause noticeable floating-point errors. It does require a bit more arithmetic, so in extremely performance sensitive situations such as ours, it's nice to have the option of using the simpler method when the rounding is unnecessary. I suspect that in most general use cases the rounding overhead would be negligible.
Note that I intentionally excluded logic for handling "abnormal" arguments such as Infinity, NaN, start > end, or a negative step size for simplicity and desire to focus on the question at hand.
Here's some example usage and corresponding output:
System.out.println(DoubleSequenceGenerator.generateSequence(0.0, 2.0, 0.2))
System.out.println(DoubleSequenceGenerator.generateSequenceRounded(0.0, 2.0, 0.2));
System.out.println(DoubleSequenceGenerator.generateSequence(0.0, 102.0, 10.2));
System.out.println(DoubleSequenceGenerator.generateSequenceRounded(0.0, 102.0, 10.2));

[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8, 2.0]
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
[0.0, 10.2, 20.4, 30.599999999999998, 40.8, 51.0, 61.199999999999996, 71.39999999999999, 81.6, 91.8, 102.0]
[0.0, 10.2, 20.4, 30.6, 40.8, 51.0, 61.2, 71.4, 81.6, 91.8, 102.0]

Is there an existing library that provides this kind of functionality already?
If not, are there any issues with my approach?
Does anyone have a better approach to this?

A: Me personally, I would shorten the DoubleSequenceGenerator class up a bit for other goodies and use only one sequence generator method that contains the option to utilize whatever desired precision wanted or utilize no precision at all:
In the generator method below, if nothing (or any value less than 0) is supplied to the optional setPrecision parameter then no decimal precision rounding is carried out. If 0 is supplied for a precision value then the numbers are rounded to their nearest whole number (ie:  89.674 is rounded to 90.0). If a specific precision value greater than 0 is supplied then values are converted to that decimal precision.
BigDecimal is used here for...well....precision:
import java.util.List;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class DoubleSequenceGenerator {

     public static List<Double> generateSequence(double start, double end,
                                          double step, int... setPrecision) {
        int precision = -1;
        if (setPrecision.length > 0) {
            precision = setPrecision[0];
        }
        List<Double> sequence = new ArrayList<>();
        for (double val = start; val < end; val+= step) {
            if (precision > -1) {
                sequence.add(BigDecimal.valueOf(val).setScale(precision, RoundingMode.HALF_UP).doubleValue());
            }
            else {
                sequence.add(BigDecimal.valueOf(val).doubleValue());
            }
        }
        if (sequence.get(sequence.size() - 1) < end) {
            sequence.add(end);
        }
        return sequence;
    }

    // Other class goodies here ....
}

And in main():
System.out.println(generateSequence(0.0, 2.0, 0.2));
System.out.println(generateSequence(0.0, 2.0, 0.2, 0));
System.out.println(generateSequence(0.0, 2.0, 0.2, 1));
System.out.println();
System.out.println(generateSequence(0.0, 102.0, 10.2, 0));
System.out.println(generateSequence(0.0, 102.0, 10.2, 0));
System.out.println(generateSequence(0.0, 102.0, 10.2, 1));

And the console displays:
[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2, 1.4, 1.5999999999999999, 1.7999999999999998, 1.9999999999999998, 2.0]
[0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]

[0.0, 10.2, 20.4, 30.599999999999998, 40.8, 51.0, 61.2, 71.4, 81.60000000000001, 91.80000000000001, 102.0]
[0.0, 10.0, 20.0, 31.0, 41.0, 51.0, 61.0, 71.0, 82.0, 92.0, 102.0]
[0.0, 10.2, 20.4, 30.6, 40.8, 51.0, 61.2, 71.4, 81.6, 91.8, 102.0]

A: *

*
Is there an existing library that provides this kind of functionality already?

Sorry, I don't know, but judging by other answers, and their relative simplicity - no, there isn't. No need. Well, almost...

*
If not, are there any issues with my approach?

Yes and no. You have at least one bug, and some room for performance boost, but the approach itself is correct.

*

*Your bug: rounding error (just change while (mult*fraction < 1.0) to while (mult*fraction < 10.0) and that should fix it)

*All the others do not reach the end... well, maybe they just weren't observant enough to read comments in your code

*All the others are slower.

*Just changing condition in the main loop from int < Double to int < int will noticeably increase the speed of your code

*
Does anyone have a better approach to this?

Hmm... In what way?

*

*Simplicity? generateSequenceDoubleStream of @Evgeniy Khyst looks quite simple. And should be used... but maybe no, because of next two points

*Precise? generateSequenceDoubleStream is not! But still can be saved with the pattern start + step*i.
And start + step*i pattern is precise. Only BigDouble and fixed-point arithmetic can beat it. But BigDoubles are slow, and manual fixed-point arithmetic is tedious and may be inappropriate for your data.
By the way, on the matters of precision, you can entertain yourself with this: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

*Speed... well now we are on shaky grounds.
Check out this repl https://repl.it/repls/RespectfulSufficientWorker
I do not have a decent test stand right now, so I used repl.it... which is totally inadequate for performance testing, but it's not the main point. The point is - there is no definite answer. Except that maybe in your case, which is not totally clear from you question, you definitely should not use BigDecimal (read further).
I've tried to play and optimize for big inputs. And your original code, with some minor changes - the fastest. But maybe you need enormous amounts of small Lists? Then that can be a totally different story.
This code is quite simple to my taste, and fast enough:
    public static List<Double> genNoRoundDirectToDouble(double start, double end, double step) {
    int len = (int)Math.ceil((end-start)/step) + 1;
    var sequence = new ArrayList<Double>(len);
    sequence.add(start);
    for (int i=1 ; i < len ; ++i) sequence.add(start + step*i);
    return sequence;
    }

If you prefer a more elegant way (or we should call it idiomatic), I, personally, would suggest:
public static List<Double> gen_DoubleStream_presice(double start, double end, double step) {
    return IntStream.range(0, (int)Math.ceil((end-start)/step) + 1)
        .mapToDouble(i -> start + i * step)
        .boxed()
        .collect(Collectors.toList());
}

Anyway, possible performance boosts are:

*

*Try switching from Double to double, and if you really need them, you can switch back again, judging by the tests, it still may be faster. (But don't trust my, try it yourself with your data in your environment. As I said - repl.it sucks for benchmarks)

*A little magic: separate loop for Math.round()... maybe it has something to do with data locality. I do not recommend this - result is very unstable. But it's fun.
double[] sequence = new double[len];
for (int i=1; i < len; ++i) sequence[i] = start + step*i;
List<Double> list = new ArrayList<Double>(len);
list.add(start);
for (int i=1; i < len; ++i) list.add(Math.round(sequence[i])/mult);
return list;

*You should definitely consider to be more lazy and generate numbers on demand without storing then in Lists

*
I suspect that in most general use cases the rounding overhead would be negligible.

If you suspect something - test it :-) My answer is "Yes", but again... don't believe me. Test it.
So, back to the main question: Is there an better way?
Yes, of course!
But it depends.

*

*Choose BigDecimal if you need very big numbers and very small numbers. But if you cast them back to Double, and more than that, use it with numbers of "close" magnitude - no need for them! Checkout the same repl: https://repl.it/repls/RespectfulSufficientWorker - last test shows that there will be no difference in results, but a dig loss in speed.

*Make some micro-optimizations based on your data properties, your task, and your environment.

*Prefer short and simple code if there is not to much to gain from performance boost of 5-10%. Don't waist your time

*Maybe use fixed-point arithmetic if you can and if it's worth it.

Other than that, you are fine.
PS. There's also a Kahan Summation Formula implementation in the repl... just for fun. https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#1346 and it works - you can mitigate summation errors

A: Sequences can be easily generated using Java 11 Stream API.
The straightforward approach is to use DoubleStream:
public static List<Double> generateSequenceDoubleStream(double start, double end, double step) {
  return DoubleStream.iterate(start, d -> d <= end, d -> d + step)
      .boxed()
      .collect(toList());
}

On ranges with a large number of iterations, double precision error could accumulate resulting in bigger error closer to the end of the range.
The error can be minimised by switching to IntStream and using integers and single double multiplier:
public static List<Double> generateSequenceIntStream(int start, int end, int step, double multiplier) {
  return IntStream.iterate(start, i -> i <= end, i -> i + step)
      .mapToDouble(i -> i * multiplier)
      .boxed()
      .collect(toList());
}

To get rid of a double precision error at all, BigDecimal can be used:
public static List<Double> generateSequenceBigDecimal(BigDecimal start, BigDecimal end, BigDecimal step) {
  return Stream.iterate(start, d -> d.compareTo(end) <= 0, d -> d.add(step))
      .mapToDouble(BigDecimal::doubleValue)
      .boxed()
      .collect(toList());
}

Examples:
public static void main(String[] args) {
  System.out.println(generateSequenceDoubleStream(0.0, 2.0, 0.2));
  //[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2, 1.4, 1.5999999999999999, 1.7999999999999998, 1.9999999999999998]

  System.out.println(generateSequenceIntStream(0, 20, 2, 0.1));
  //[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8, 2.0]

  System.out.println(generateSequenceBigDecimal(new BigDecimal("0"), new BigDecimal("2"), new BigDecimal("0.2")));
  //[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
}

Method iterate with this signature (3 parameters) was added in Java 9. So, for Java 8 the code looks like
DoubleStream.iterate(start, d -> d + step)
    .limit((int) (1 + (end - start) / step))

A: Try this.
public static List<Double> generateSequenceRounded(double start, double end, double step) {
    long mult = (long) Math.pow(10, BigDecimal.valueOf(step).scale());
    return DoubleStream.iterate(start, d -> (double) Math.round(mult * (d + step)) / mult)
                .limit((long) (1 + (end - start) / step)).boxed().collect(Collectors.toList());
}

Here,
int java.math.BigDecimal.scale()

Returns the scale of this BigDecimal. If zero or positive, the scale is the number of digits to the right ofthe decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. For example, a scale of -3 means the unscaled value is multiplied by 1000.
In main()
System.out.println(generateSequenceRounded(0.0, 102.0, 10.2));
System.out.println(generateSequenceRounded(0.0, 102.0, 10.24367));

And Output:
[0.0, 10.2, 20.4, 30.6, 40.8, 51.0, 61.2, 71.4, 81.6, 91.8, 102.0]
[0.0, 10.24367, 20.48734, 30.73101, 40.97468, 51.21835, 61.46202, 71.70569, 81.94936, 92.19303]


text:
Q: Virtualbox tunnel localhost to windows I'm running ubuntu on my laptop but need to be able to test my work in windows xp where I'm using virtualbox. is it possible to tunnel my localhost so that it can be accessed by IE inside virtualbox?

A: You don't need to tunnel. Just request either the IP address of the Ubuntu machine or it's FQN. I use that all the time when doing testing on my machine. Basically Vbox acts as a NAT so if you do an ifconfig and then hit the IP address of the machine you should be good.

A: If you are using the default networking mode (NAT), then the guest can access the host at 10.0.2.2, or via it's 'normal' IP address.

A: Virtualbox can see your host machine as just another machine on the network - if that's what you are asking?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy Multiple Rows into Single Column in another sheet using vba I have this huge date of Activity of various process which looks like this.

I need output like this.

and i try to use this bellow Macro.
Sub lrow()
 Dim lcol As Long, rw As Long, j As Long, rc As Range
 j = 1
      For rw = 2 to Cells(Rows.Count, "A").End(xlUp).Row
      For lcol = 2 to Cells(rw, Columns.Count).End(xlToLeft).Column
        set rc = Cells(rw, lcol)
          If IsDate(rc.Value) Then
           With Sheet2
             Range(j, 2) = rc.Value
             j = j + 1
           End With
          End If
      Next lcol
      Next rw
  End Sub

I need help on this Code pls. thanks in advance

A: You can perform a serpentine transfer:
Sub Serpentine()
   Dim N As Long, i As Long, K As Long, j As Long
   Dim sh1 As Worksheet, sh2 As Worksheet
   K = 1
   Set sh1 = Sheets("Sheet1")
   Set sh2 = Sheets("Sheet2")
   N = sh1.Cells(Rows.Count, "A").End(xlUp).Row

   For i = 1 To N
      For j = 1 To Columns.Count
         If sh1.Cells(i, j) <> "" Then
            sh2.Cells(K, 1).Value = sh1.Cells(i, j).Value
            K = K + 1
         Else
            Exit For
         End If
      Next j
   Next i
End Sub

For example in Sheet1:

Will produce in Sheet2:

A: It's hard to come up with a solution if you're not telling us what the problem is, but here's my stab at it. No need for a double-nested loop; just walk over all input cells until you reach an empty one, then jump to the beginning of the next line:
Public Sub Test()
    Dim rng As Range
    Set rng = Worksheets(1).Cells(1, 1)
    While rng.Column > 1 Or Not IsEmpty(rng)
        Debug.Print rng.Value
        Set rng = rng.Offset(0, 1)
        If IsEmpty(rng) Then Set rng = ws.Cells(rng.Row + 1, 1)
    Wend
End Sub

The loop halts when it encounters an empty cell in the first column. You'll notice I didn't bother to write the dates to a second worksheet, but that's trivial.

A: This code is effectively taking all dates from the first sheet and pasting them in the A column of Sheet 2:
Sub lrow()

j As Long, rc As Range

j = 1

For Each rc In Sheets(1).Range("A1", Sheets(1).Cells.SpecialCells(xlCellTypeLastCell))
    If IsDate(rc.Value) Then
        With Worksheets(2)
             .Cells(j, 1) = rc.Value
             j = j + 1
        End With
    End If
Next rc

End Sub

Don't know if that's what you want.


text:
Q: How to reload edit options for widget in iOS? I am building an iOS app that user can add new option for widget edit options
but the new option doest not show immediately
I have to wait few minutes for new option displaying
How can I reload option list for widget right now?

A: import WidgetKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    func sceneDidEnterBackground(_ scene: UIScene) {
        WidgetCenter.shared.reloadAllTimelines()
    }
}

reload widget when app enters background


text:
Q: Clojure mutable storage types I'm attempting to learn Clojure from the API and documentation available on the site. I'm a bit unclear about mutable storage in Clojure and I want to make sure my understanding is correct. Please let me know if there are any ideas that I've gotten wrong.
Edit: I'm updating this as I receive comments on its correctness.

Disclaimer: All of this information is informal and potentially wrong. Do not use this post for gaining an understanding of how Clojure works.

Vars always contain a root binding and possibly a per-thread binding. They are comparable to regular variables in imperative languages and are not suited for sharing information between threads. (thanks Arthur Ulfeldt)
Refs are locations shared between threads that support atomic transactions that can change the state of any number of refs in a single transaction. Transactions are committed upon exiting sync expressions (dosync) and conflicts are resolved automatically with STM magic (rollbacks, queues, waits, etc.)
Agents are locations that enable information to be asynchronously shared between threads with minimal overhead by dispatching independent action functions to change the agent's state. Agents are returned immediately and are therefore non-blocking, although an agent's value isn't set until a dispatched function has completed.
Atoms are locations that can be synchronously shared between threads. They support safe manipulation between different threads.
Here's my friendly summary based on when to use these structures:

*

*Vars are like regular old variables in imperative languages. (avoid when possible)

*Atoms are like Vars but with thread-sharing safety that allows for immediate reading and safe setting. (thanks Martin)

*An Agent is like an Atom but rather than blocking it spawns a new thread to calculate its value, only blocks if in the middle of changing a value, and can let other threads know that it's finished assigning.

*Refs are shared locations that lock themselves in transactions. Instead of making the programmer decide what happens during race conditions for every piece of locked code, we just start up a transaction and let Clojure handle all the lock conditions between the refs in that transaction.

Also, a related concept is the function future. To me, it seems like a future object can be described as a synchronous Agent where the value can't be accessed at all until the calculation is completed. It can also be described as a non-blocking Atom. Are these accurate conceptions of future?

A: It sounds like you are really getting Clojure! good job :)
Vars have a "root binding" visible in all threads and each individual thread can change the value it sees with out affecting the other threads. If my understanding is correct a var cannot exist in just one thread with out a root binding that is visible to all and it cant be "rebound" until it has been defined with (def ... ) the first time.
Refs are committed at the end of the (dosync ... ) transaction that encloses the changes but only when the transaction was able to finish in a consistent state.

A: I think your conclusion about Atoms is wrong:

Atoms are like Vars but with thread-sharing safety that blocks until the value has changed

Atoms are changed with swap! or low-level with compare-and-set!. This never blocks anything. swap! works like a transaction with just one ref:

*

*the old value is taken from the atom and stored thread-local

*the function is applied to the old value to generate a new value

*if this succeeds compare-and-set is called with old and new value; only if the value of the atom has not been changed by any other thread (still equals old value), the new value is written, otherwise the operation restarts at (1) until is succeeds eventually.

A: I've found two issues with your question.
You say:

If an agent is accessed while an action is occurring then the value isn't returned until the action has finished

http://clojure.org/agents says:

the state of an Agent is always immediately available for reading by any thread

I.e. you never have to wait to get the value of an agent (I assume the value changed by an action is proxied and changed atomically).
The code for the deref-method of an Agent looks like this (SVN revision 1382):
public Object deref() throws Exception{
    if(errors != null)
    {
        throw new Exception("Agent has errors", (Exception) RT.first(errors));
    }
return state;

}
No blocking is involved.
Also, I don't understand what you mean (in your Ref section) by

Transactions are committed on calls to deref

Transactions are committed when all actions of the dosync block have been completed, no exceptions have been thrown and nothing has caused the transaction to be retried. I think deref has nothing to do with it, but maybe I misunderstand your point.

A: Martin is right when he say that Atoms operation restarts at 1. until is succeeds eventually.
It is also called spin waiting.
While it is note really blocking on a lock the thread that did the operation is blocked until the operation succeeds so it is a blocking operation and not an asynchronously operation.
Also about Futures, Clojure 1.1 has added abstractions for promises and futures.
A promise is a synchronization construct that can be used to deliver a value from one thread to another. Until the value has been delivered, any attempt to dereference the promise will block.
(def a-promise (promise))
(deliver a-promise :fred)

Futures represent asynchronous computations. They are a way to get code to run in another thread, and obtain the result.
(def f (future (some-sexp)))
(deref f) ; blocks the thread that derefs f until value is available

A: Vars don't always have a root binding. It's legal to create a var without a binding using
(def x)

or
(declare x)

Attempting to evaluate x before it has a value will result in
Var user/x is unbound.
[Thrown class java.lang.IllegalStateException]


text:
Q: Microsoft Graph - Why permission/scope "Group.ReadWrite.All" is able to do PATCH on user profile properties? Tool: postman

*

*Created azure ad app, granted app-only permission Group.ReadWrite.All for Microsoft Graph app, the app has standard delegation permissions as "Sign-in and read user profile on" "Windows Azure Active Directory" app.

*Requested token for AzureAD graph api at endpoint https://login.windows.net/ with resource parameter "https://graph.windows.net", using client credential grant flows;

*Got token back

*Used the token and did a GET on a User OK

*Did a PATCH on a user ( modification went successfully with http code 204 back);

This looks very strange to me, why an app was able to do patch on a user in azure ad when app is only granted Group.ReadWrite.All on Microsoft Graph API?

A: We are working on an experience in the new Azure portal to "consent/approve" the app in your tenant. Until then, you'll need to follow the final step in the instructions that go with this sample app (to consent the app): https://github.com/Azure-Samples/active-directory-dotnet-graphapi-console.
After doing so, you should see a "roles" claim in the access token (containing Group.ReadWrite.All).
The other issue you are reporting (it looks like your app has been added to the Directory Writers role, enabling your app to be able to perform more than just group manipulation) - this will require some more investigation, as this should not be happening.  Will report back.
Hope this helps,

A: There are two issues here;
Issue #1) Wrong documentaiton for Add Owner graph.microsoft.io/en-us/docs/api-reference/v1.0/api/… (One of the following scopes is required to execute this API: Group.ReadWrite.All or Directory.ReadWrite.All or Directory.AccessAsUser.All), It requires both Directory.ReadWrite.All AND Group.ReadWrite.All ,
Issue #2) Azure AD portal does not remove Application service principal from Directory Writer Role if you remove "Read and write directory data" permission from Windowes AzureAD App


text:
Q: ¿Como soluciono un error por pasarle un objeto a un método en un archivo aparte? C# Les consulto, tengo estos 2 archivos que interactuan realizando el alta de un producto a través de un menu, ademas de tener una clase en otro donde se debería imprimir el contenido de los objetos. Pero al pasarle la lista de objetos me sale un error de referencia.  ¿Que estoy omitiendo en el codigo?
Primero archivo con el menu.
namespace TP_Integrador
{

    public class MenuProductos
    {
        public MenuProductos()
        {

        }

        public static void mascara()
        {
            int opcion = 1;

            List<Productos> arrAlta = new List<Productos>();

            while(opcion!=5)
            {

                Console.Write( "----------------------MODULO PRODUCTOS----------------------"+"\n"+"\n"+"\n");
                Console.WriteLine("¿Que desea hacer?"+"\n"+"\n"+"\n");
                Console.WriteLine("1 - Dar de Alta Productos");
                Console.WriteLine("2 - Imprimir");
                Console.WriteLine("3 - ");
                Console.WriteLine("4 - ");
                Console.WriteLine("5 - ");

                Console.Write("Opcion: ");
                opcion = int.Parse(Console.ReadLine());

                switch(opcion)
                {
                    case 1:
                        arrAlta = AltaDeProducto.alta();
                        break;
                    case 2:
                        ImprimirProducto.Imprimir(arrAlta);
                        //Promociones.descuento(arrAlta);
                        break;
                    case 3:
                        Console.WriteLine("Compras");
                        break;
                    case 4:
                        Console.WriteLine("");
                        break;
                    default:
                        Console.WriteLine("");
                        break;

                }

            }
        }

    }
}

Segundo archivo con el Alta del producto:
using System;
using System.Collections;
using System.Collections.Generic;

namespace TP_Integrador
{

 public class AltaDeProducto
 {

    List<Productos> AProducto = new List<Productos>();

    public List<Productos> alta()
    {
        string respuesta = "si";

        do
        {
            //Declaro los objetos y comienzo con la carga de datos
            var producto = new Productos();

            Console.WriteLine("Usted eligio: Productos y Promociones"+"\n");
            Console.Write("Ingrese Tipo: ");
            producto.tipo = Console.ReadLine();

            Console.Write("Ingrese Marca: ");
            producto.marca = Console.ReadLine();

            Console.Write("Ingrese Talle: ");
            producto.talle = int.Parse(Console.ReadLine());

            Console.Write("Ingrese Precio: ");
            producto.precio = int.Parse(Console.ReadLine());

            //Agrego el objeto cargado a la lista...
            AProducto.Add(producto);

            Console.Write("Cargado!"+"\n");
            Console.Write("Desea ingresar otro? ");
            respuesta=Console.ReadLine();
        }while(respuesta=="si");

        return AProducto;
    }

 }

}

Tercer archivo que posee un método al que se le pasa por parámetro el objeto cargado y lo muestra:
namespace TP_Integrador
{
    /// <summary>
    /// Description of ImprimirProducto.
    /// </summary>
    public class ImprimirProducto
    {

        public static void Imprimir(List<Productos> AProducto)
        {
            foreach(Productos item in AProducto)
                {
                    Console.WriteLine("Tipo: " + item.tipo);
                    Console.WriteLine("Marca: " + item.marca);
                    Console.WriteLine("Talle: " + item.talle);
                    Console.WriteLine("Precio: " + item.precio);
                }
        }

    }
}

ERROR:
An object reference is required for the non-static field, method, or property 'TP_Integrador.AltaDeProducto.alta()' (CS0120) - C:\Users\Mloprete\Documents\SharpDevelop Projects\TP Integrador\TP Integrador\MenuProductos.cs:48,17
Razonamiento: El error puede estar en como defino los métodos? Sea en estado static? o seguro debo tener alguna referencia errónea.

A: Mariano, en tu primer código el switch - case debería ser:
switch(opcion)
{
     case 1:
         //Debes instanciar tu clase
         var prod = new AltaDeProducto();
         arrAlta = prod.alta();
     break;
     case 2:
         ImprimirProducto.Imprimir(arrAlta);
         //Promociones.descuento(arrAlta);
     break;
     case 3:
         Console.WriteLine("Compras");
     break;
     case 4:
         Console.WriteLine("");
     break;
     default:
         Console.WriteLine("");
     break;
}


text:
Q: CakePHP3 Linking Table Together in Same Model (Inner Join) i've a table named 'customers' with following (shortened) schema:
id | customer_id | type | salutation | forename | surname | created | modified

In this table, I want to store people, which are may be associated:

id | customer_id | type    | salutation | forename | surname | created             | modified
 1 | NULL        | husband | Mr.        | John     | Doe     | 2016-01-05 10:00:00 | 2016-01-05 10:00:00
 2 |  1          | wife    | Mrs.       | Jane     | Doe     | 2016-01-05 10:01:00 | 2016-01-05 10:01:00
 3 |  1          | child   | Mr.        | Jim      | Doe     | 2016-01-05 10:02:00 | 2016-01-05 10:02:00

Customers with "customer_id" = NULL are the master customers, but #2 and #3 refers to #1.
I've created the table in phpmyadmin and do:
"bin/cake bake all customers" without errors.
Then I created the 'master customer'. When I create the second account, I expect that the select-field shows customer #1, but the dropdown-field is empty.
The model:
public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('customers');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsTo('Customers', [
        'foreignKey' => 'customer_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('Customers', [
        'foreignKey' => 'customer_id'
    ]);
}

If you need further information or more piece of code, let me know.
Many thanks in advance.
best regards
Martin

SQL to reproduce
CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(11) NOT NULL,
  `typ` varchar(10) NOT NULL,
  `customer_id` int(11) DEFAULT NULL,
  `salutation` varchar(4) NOT NULL,
  `prename` varchar(255) NOT NULL,
  `surname` varchar(255) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

INSERT INTO `customers` (`id`, `typ`, `customer_id`, `salutation`, `prename`, `surname`, `created`, `modified`) VALUES
(1, 'husband', NULL, 'Mr.', 'John', 'Doe', '2016-03-02 21:26:32', '2016-03-02 21:26:32'),
(2, 'wife', 1, 'Ms.', 'Jane', 'Doe', '2016-03-02 21:27:25', '2016-03-02 22:10:05'),
(3, 'child', 1, 'Mr.', 'Jim', 'Doe', '2016-03-02 21:27:41', '2016-03-02 22:10:15');

ALTER TABLE `customers` ADD PRIMARY KEY (`id`), ADD KEY `customers_fk0` (`customer_id`);
ALTER TABLE `customers` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
ALTER TABLE `customers` ADD CONSTRAINT `customers_fk0` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`);

Than, run
bin/cake bake all customers

EDIT
I've checked, the possible duplicate, and changed my model
$this->belongsTo('Customers', [
    'foreignKey' => 'customer_id',
    'joinType' => 'INNER'
]);
$this->hasMany('ChildCustomers', [ // <-- changed this line
    'className' => 'Customers',    // <-- added this line
    'foreignKey' => 'customer_id'
]);

Now, if I try to add/edit, no changes to the select. But if I view an existing customer, i got:

Error: SQLSTATE[42000]: Syntax error or access violation: 1066 Not
  unique table/alias: 'Customers'

This is the code for displaying the select:
echo $this->Form->input('customer_id');

This code was genereated by "bin/cake bake all customers"

EDIT 2
I'll will summarize my current state:
Model:
public function initialize(array $config)
{
    parent::initialize($config);

    $this->table('customers');
    $this->displayField('id');
    $this->primaryKey('id');

    $this->belongsTo('ParentCustomers', [
        'className' => 'Customers',
        'foreignKey' => 'customer_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('ChildCustomers', [
        'className' => 'Customers',
        'foreignKey' => 'customer_id'
    ]);
}

public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['customer_id'], 'ParentCustomers'));
    return $rules;
}

Controller:
public function view($id = null)
{
    $customer = $this->Customers->get($id, [
        'contain' => ['ParentCustomers']
    ]);

    $this->set('customer', $customer);
    $this->set('_serialize', ['customer']);
}

If an user has an association (wife, child), the view displays a headline "Related Customers" on bottom of the page, but no additional table which shows the related customers. If an user has "customer_id = 0", the view said 'Record not found in table "customers"'.
I've also added
$this->set('customers', $this->Customers->find('list'));

to the add() and edit() function, but I found no way to allow also an empty value.
For clarification:
Later, the front page (index()) should only list the "master customer" with customer_id = 0 with a small nested table, if he have a wife and/or children.
I think I am on the right way... Am I?
Thanks again in Advance

A: You should also use ParentCustomers for the first association. Customers duplicates itself.

$this->belongsTo('ParentCustomers', [ // <-- You need to change here
    'className' => 'Customers', // <-- You need to change here
    'foreignKey' => 'customer_id',
    'joinType' => 'INNER'
]);
$this->hasMany('ChildCustomers', [
    'className' => 'Customers',
    'foreignKey' => 'customer_id'
]);

A: Are you sure you did load the model already in the controller?
Put following into controller's initialize(): $this->loadModel('Customers');
EDIT: So it's like:
    public function initialize()
    {
        parent::initialize();

        $this->loadModel('Customers');
    }

A: I've solved the issue by using CakePHPs TreeBehavior.
I use parent_id instead of customer_id and added rght and lft column as discribed in Blog Tutorial - Part 3.
It is working for me now! Thanks everyone!


text:
Q: Domain controller with HyperV just a question, is a good idea to host machines with HyperV on a DC?
This is my Idea.
if the answer is no, can you explain why?
Thanks
Have a nice day

A: First of all, your question doesn't seem to be related to programming in any way and should hence be considered off topic for SO. Server Fault would probably be a more suitable place for (the question is somewhat old by now as well and you might already have found the info you need but I've flagged it for the moderators to perhaps consider a move from SO to SF or have it closed altogether).
Secondly, as for your question;
Generally no, it's not a good idea but there could be ifs and buts to everything I guess.
For a smaller company with perhaps only the one existing server (and no budget to add machines or get professional help to make any bigger changes to their current setup) which also happenes to be their DC, I guess it all comes down to what kind of workload the DC is under to begin with and just what will be hosted in Hyper-V. I'd personally still recommend against it though.

A: It's not a good idea as it's not a supported scenario from MS. I don't even know if server manager lets you install both.
You can host a VM with AD, but depending on your setup (cluster/HyperV in domain or not, ...) you really should add an AD physical server (even a very small one) for hyper-V to authenticate his services against when your AD VM has not started. It can save you a lot of time...


text:
Q: Average, max, and min program in C So I'm coding in C, and I need to come up with code that will take n numbers from the user, and find their minimum, maximum, average, and sum of squares for for their values. So far I have the average and sum of squares portion, but the minimum and maximum is biting me.
Keep in mind I'm at a very rudimentary level, and I have not reached arrays yet. All I know are logical operators, functions, loops, and the use of the stdlib.h, math.h, and stdio.h libraries.
This is what I have so far.
The average function gave me a lot of problems when I tried to put float and double during compiling, so multiply it by a 1.0 fixed that. I have everything, just the minimum and maximum. I keep getting the last entry as my maximum, and a 0 for my minimum.
#include<stdio.h>
int main()
{
    float average;
    int i, n, count=0, sum=0, squaresum=0, num, min, max;

    printf("Please enter the number of numbers you wish to evaluate\n");
    scanf_s("%d",&n);

    printf("Please enter %d numbers\n",n);

    while(count<n)
    {
        min=0;
        max=0;

            if(num>max)
               max=num;
            if(num<min)
               min=num;

            scanf_s("%d",&num);

        sum = sum+num;
        squaresum = squaresum + (num*num);

        count++;
    }
        average = 1.0*sum/n;

    printf("Your average is %.2f\n",average);
    printf("The sum of your squares is %d\n",squaresum);

    printf("Your maximum number is %d\n",max);
    printf("Your minimum number is %d\n",min);

return(0);
}

A: Your algorithm is not quite right.  Below is the correct implementation:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
    float average;
    int n, num, count = 0, sum = 0, squaresum = 0;
    int min = INT_MAX, max = INT_MIN;
    bool gotAnswer = false;

    /* Don't Let User Enter Wrong Input */
    while(!gotAnswer)
    {
        printf("Please enter the number of numbers you wish to evaluate: ");
        if(scanf_s("%d", &n) != 1)
        {
            /* User Entered Wrong Input; Clean Up stdin Stream*/
            while(getchar() != '\n')
            {
                 continue;
            }
        }
        else
        {
            /* User Input Was Good */
            gotAnswer = true;
        }
    }

    /* Clear stdin Stream Just In Case */
    while(getchar() != '\n')
        continue;

    while(count < n)
    {
        /* Don't Let User Enter Wrong Input */
        gotAnswer = false;
        printf("Enter number %d: ", count + 1);
        if(scanf_s("%d", &num) != 1)
        {
            /* User Entered Wrong Input; Clean Up stdin Stream */
            while(getchar() != '\n')
                continue;

            /* Let User Try Again */
            continue;
        }
        else
        {
            /* User Input Was Correct */
            gotAnswer = true;

            /* Clear stdin Stream Just In Case */
            while(getchar() != '\n')
                continue;
        }

        if(num > max)
            max = num;
        if(num < min)
            min = num;

        sum += num;
        squaresum += num * num;
        count++;
    }

    average = 1.0 * sum / n;

    printf("Your average is %.2f\n", average);
    printf("The sum of your squares is %d\n", squaresum);
    printf("Your maximum number is %d\n", max);
    printf("Your minimum number is %d\n", min);

    system("pause");
    return 0;
}

I've added error checking and recovery.  Please ask if you have any questions about the logic.

A: The way your code is currently written, min has to start out at a high value (not 0), or the code won't work.  The best value to choose is the maximum possible value for an int.
You should also consider whether or not you want to reset these variable each time through the loop.

A: Enter the first num outside the loop and assign that to max min
scanf("%d",&num);
max = min = num;

Change your while loop to infinite loop
while(1) {...}

and now check for the condition that whether your counter count is equal to n is or not to break out from the infinite loop
if(count == n)
    break;

Full code after modification:
#include<stdio.h>
int main()
{
    float average;
    int i, n, count=0, sum=0, squaresum=0, num, min, max;

    printf("Please enter the number of numbers you wish to evaluate\n");
    scanf_s("%d",&n);

   printf("Please enter %d numbers\n",n);

   scanf_s("%d",&num);
   max = min = num;

   while(1)
   {
        if(num>max)
           max=num;
        if(num<min)
           min=num;

     sum = sum+num;
     squaresum = squaresum + (num*num);

     count++;
     if(count == n)
        break;
     scanf_s("%d",&num);

   }
    average = 1.0*sum/n;

printf("Your average is %.2f\n",average);
printf("The sum of your squares is %d\n",squaresum);

printf("Your maximum number is %d\n",max);
printf("Your minimum number is %d\n",min);

return(0);
}

A: Assume your first number in the list as the minimum and maximum.
Compare every next character with the current minimum and the current maximum and update accordingly.

A: your while loop should look like
   min=3;
   max=0;
while(count<n)
    {

     scanf("%d",&num);
    if(num>max)
    max=num;
    if(num<min)
    min=num;

    sum = sum+num;
    squaresum = squaresum + (num*num);

    count++;
}

And I agree with Robert Harvey♦.. You must set min

A: There're some issues in your code:

*

*Where num is read? You should do it before min and max

*When while loop executes first time you should just assign num to max and   min.

Something like that:
  int min = 0;
  int max = 0;

  // If your compiler supports C99 standard you can put
  // bool first_time = true;
  int first_time = 1;

  while (count < n) {
    printf("Please, enter the next number\n");
    scanf_s("%d", &num);

    // If your compiler supports C99 you can put it easier:
    // if (first_time) {
    if (first_time == 1) {
      first_time = 0;
      max = num;
      min = num;
    }
    else {
      if(num > max)
        max = num;

      if(num < min)
        min = num;
    }
  ...

A: Add a boolean, moved giving the values min, max 0 are the start of loop
#include<stdio.h>
int main()
{
    float average;
    int i, n, count=0, sum=0, squaresum=0, num, min, max;

    bool first = true;
    printf("Please enter the number of numbers you wish to evaluate\n");
    scanf_s("%d",&n);

    printf("Please enter %d numbers\n",n);
        min=0;
        max=0;

    while(count<n)
    {
            scanf_s("%d",&num);

        if (first) {
           first = false;
           min = max = num;
        }
            if(num>max)
               max=num;
            if(num<min)
               min=num;

        sum = sum+num;
        squaresum = squaresum + (num*num);

        count++;
    }
        average = 1.0*sum/n;

    printf("Your average is %.2f\n",average);
    printf("The sum of your squares is %d\n",squaresum);

    printf("Your maximum number is %d\n",max);
    printf("Your minimum number is %d\n",min);

return(0);
}

Should also consider to check the return value of scanf

A: int marks , marks_count=0 , max=0 , min=100 , marks_number=1;
float total , avg;

printf("Hit enter to input marks of 10 student.\n\n");
getchar();

do
{
    printf("Input %d Mark : " , marks_number);
    scanf("%d" ,& marks);

    if (marks>max)
    {
        max=marks;
    }

    else if (marks<min)
    {
        min=marks;
    }

    marks_count++;
    marks_number++;

    total=total+marks;
}

while (marks_count<10);
while (marks_number<10);

avg=total/marks_count;

printf("\n\nAverage marks are : %.2f\n" , avg);
printf("Maximum marks are : %d\n" , max);
printf("Minimum marks are : %d\n\n\n" , min);

A: You can use this code, it checks if the loop starts for the first time or not. If it runs for the first time it assigns the value of n to the minimum and the maximum variable and after that, it continues. When it runs a second time it checks and finds that the program runs a second time thus it does not initialize the variables with the value of n without comparing.
int n, limit, sum = 0, minimum, maximum;
float average;
bool firstTime = "true";

printf("\nEnter Limit: ");
scanf("%d", &limit);

printf("\nEnter %d numbers: \n", limit);
for (int i = 0; i < limit; i++)
{
    scanf("%d", &n);
    if (firstTime)
    {
        minimum = n;
        maximum = n;
        firstTime = false;
    }
    if (minimum > n)
    {
        minimum = n;
    }

    if (maximum < n)
    {
        maximum = n;
    }
    sum = sum + n;
}

average = sum / limit;
printf("\nMinimum: %d", minimum);
printf("\nMaximum: %d", maximum);
printf("\nSum: %d", sum);
printf("\nAverage: %.3lf", average);


text:
Q: Convex Hull reading XY co-ords in Python I need to come up with a convex hull algorithm to read through a bunch of X , Y co-ordinates and outline the image..
i'm coding in python
Any ideas?

A: Are there any more details or constraints to your question? After searching wikipedia for "Convex hull algorithms", it gave me a list of algorithms, of which I clicked "Monotone Chain"
http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain


text:
Q: Find all Points on the Surface at which the Tangent is Parallel to the Plane The problem: Find all points on the surface $z=x^3+xy^2$ at which the tangent plane is parallel to the plane $2x+2y+z=0$
So I established $f(x,y,z)=x^3+xy^2-z$ and the normal vector determined from the plane being $<2,2,1>$.
The normal vector for a tangent plane at the point $(x_0,y_0,z_0)$ on the surface is such:
$$\nabla f(x_0,y_0,z_0)=<3x_0^2+y_0^2, 2x_0y_0,-1>=k<2,2,1>$$
Anyway I try to solve this equation, I can't find any points. Is this a possible solution, or am I wrong?

A: You are correct, there are no such points.

A: It seems to me that one might suspect  this outcome, since the surface has odd symmetry about the $ \ yz-$ plane ($ \ x \ = \ 0 \ $) and even symmetry about the $ \ xy-$ plane ( $ \ y \ = \ 0 \ $ ) , but the given plane,  $ \ z \ = \ -2x \ - \ 2y \ $ , has only diagonal symmetry (the normal vector is in the plane $ \ y \ =  \ x \ $ ) .  So there is no value of $ \ c \ $ for which a plane $  \ 2x \ + \ 2y \ + \ z \ = \ c \ $ will not simply "cut through" the surface.  Here is a picture of the surface and the given plane:


text:
Q: camel-netty causing deadlock when multiple tcp stations are configured in route I m getting the following exception when trying to use more than two netty endpoints in a single route.
java.lang.IllegalStateException: await*() in I/O thread causes a dead lock or sudden performance drop. Use addListener() instead or call await*() from a different thread.
Sample route :
                            from("netty:tcp://localhost:7000?textline=true")
                            .bean(DummyProcessor.class)
                            .to("netty:tcp://localhost:7001?textline=true")
                            .bean(DummyProcessor.class)
                            .to("netty:tcp://localhost:7002?textline=true")
                            .bean(DummyProcessor.class)
                            .to("netty:tcp://localhost:7003?textline=true")
                            .bean(DummyProcessor.class)
                            .to("netty:tcp://localhost:7004?textline=true")
                            .bean(DummyProcessor.class);

camel version : 2.11
netty 3.6.5
possible duplicate Deadlock when using netty with Apache Camel

A: This has been fixed by CAMEL-6442: https://issues.apache.org/jira/browse/CAMEL-6442


text:
Q: Is there a way to allow access to specific files via git from bitbucket/any other provider to maintain privacy of code files from all? I have repo of a sdk and the team spread across. We need to keep the code private and secure from getting corrupted.
So can we have an option to enable single/specific file access to the bitbucket users via git repo setup?

A: I cant post images on comments so if this is what you are looking for I will update the answer with the full explanation on how and what to do.
You can limit and restrict access to your repo & ranches from the settings screen:
Restrict access to repository/ranches

Restrict changes to specific files (or allow it to certain users)
pre-receive hook
#!/bin/sh

# Check to see if this is the first commit in the repository or not
if git rev-parse --verify HEAD >/dev/null 2>&1
then
    # We compare our changes against the previous commit
    against=HEAD^
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Redirect output to screen.
exec 1>&2

# Check to see if we have updated the given file
if [ $(git diff-tree -r --name-only $against | grep <ANY FILE YOU WANT TO FILTER OUT HERE> ) ];
then

# -> ADD YOUR CODE TO CHECK CERTAIN USER
# -> (grab it from the commit for example)

    # Output colors
    red='\033[0;31m';
    green='\033[0;32m';
    yellow='\033[0;33m';
    default='\033[0;m';

    # personal touch :-)
    echo "${red}"
    echo "                                         "
    echo "                   |ZZzzz                "
    echo "                   |                     "
    echo "                   |                     "
    echo "      |ZZzzz      /^\            |ZZzzz  "
    echo "      |          |~~~|           |       "
    echo "      |        |-     -|        / \      "
    echo "     /^\       |[]+    |       |^^^|     "
    echo "  |^^^^^^^|    |    +[]|       |   |     "
    echo "  |    +[]|/\/\/\/\^/\/\/\/\/|^^^^^^^|   "
    echo "  |+[]+   |~~~~~~~~~~~~~~~~~~|    +[]|   "
    echo "  |       |  []   /^\   []   |+[]+   |   "
    echo "  |   +[]+|  []  || ||  []   |   +[]+|   "
    echo "  |[]+    |      || ||       |[]+    |   "
    echo "  |_______|------------------|_______|   "
    echo "                                         "
    echo "                                         "
    echo "${red} You are not allowed to commit this file    "
    echo "                                         "
    echo "${default}"
fi;

# set the exit code to 0 or 1 based upon your needs
# 0 = good to push
# 1 = exit without pushing.
exit 0;

A: No, it's not.
For bitbucket git repo, there is no way to specify access permission for files for now.
There are three kinds of premissions you can set on bitbucket repo: Admin, Write and Read.
Even for the users who have only read permission, they can access to all the files of the repo.
More details, you can refer the document Using repository permissions, and the post Can i set files & folders permissions in Bitbucket.
BTW: if you want to suggest the feature (enable to set permission for files/folders) to bitbucket, you can feedback by creating a new issue here.


text:
Q: Upload large files in .NET I've done a good bit of research to find an upload component for .NET that I can use to upload large files, has a progress bar, and can resume the upload of large files.  I've come across some components like AjaxUploader, SlickUpload, and PowUpload, to name a few.  Each of these options cost money and only PowUpload does the resumable upload, but it does it with a java applet.  I'm willing to pay for a component that does those things well, but if I could write it myself that would be best.
I have two questions:

*

*Is it possible to resume a file upload on the client without using flash/java/Silverlight?

*Does anyone have some code or a link to an article that explains how to write a .NET HTTPHandler that will allow streaming upload and an ajax progress bar?

Thank you,
Austin
[Edit]
I realized I do need to be able to do resumable file uploads for my project, any suggestions for components that can do that?

A:
1) Is it possible to resume a file upload on the client without using flash/java/Silverlight?

No. The actual HTTP protocol itself does not support resume of partial uploads, so even if you did use flash or silverlight, you'd still need to use something else like FTP on the server.
I've "solved" this problem in the past by writing a custom client application in C# which broke the file down into small chunks (2meg), transmitted those separately, and then the server combines them all back together.

2) Does anyone have some code or a link to an article that explains how to write a .NET HTTPHandler that will allow streaming upload and an ajax progress bar?

While this doesn't solve the 'resume' problem, I've used SWFUpload on the client side and it worked brilliantly. It provides a smart file browser (where you can prompt the user for only jpeg files, etc) and upload progress tracking, all without needing to modify your server at all.

A: It's not possible to resume an upload using standard HTML file input control, because the whole file gets submitted with the HTTP request.
I've used NeatUpload in the past, which gives you a progress bar.  It's under an LGPL license, so you don't need to pay for it and it's open source.

A: Nothing more to add about the resume problem.
I used (and keep on using) telerik radUpload and I am quite satisfied with it
(it can even be used in medium trust mode which was quite important for me). The only problem I had (and was not able to fix) is to upload files bigger than 2GB...

A: SlickUpload is pretty solid and a lot of big companies use it from what the site says.

A: This is probably too late for your project, but POW Upload have now implemented auto resume upload in their new version. We're about to implement it on our site.


text:
Q: How do I use a regex to remove a "." at the end of the a string which may be inside a markup too? I want to write a regex that can remove the "." at the end (can be inside a centa or centb) markup and put it infront of
String input1 = "this is a   <centa> test.</centa>"
String output1 = "this is a . <centa> test</centa>"

or
 String input1b = "this is a   <centb> test.</centb>"
    String output1b = "this is a . <centb> test</centb>"

or
String input3 = "this is a   test."
String output3 = "this is a .  test"

I can only use replaceAll on the string so, how do I create the pattern in the code below ? and what should the replacement string be ?
Pattern rulerPattern1 = Pattern.compile("", Pattern.MULTILINE);
System.out.println(rulerPattern1.matcher(input1).replaceAll(""));

This edge case was presented by the requester in comments
string input4 = "“[<deleted.material>[</deleted.material>]§ 431:10A–126 [<deleted.material>]Chemotherapy services.</deleted.material>] <added.material>Cancer treatment.</added.material>test snl."
string output4 = "“[<deleted.material>[</deleted.material>]§ 431:10A–126. [<deleted.material>]Chemotherapy services.</deleted.material>] <added.material>Cancer treatment.</added.material>test snl"

A: Description
This regex will find find   and move the last dot in the string to just before the
Regex:  ([&]emsp;[^.]*)\.
Replace with .$1

Given your input text samples:
this is a   <centa> test.</centa>
this is a   <centb> test.</centb>
this is a   test.

This returns the following lines respectivly
this is a . <centa> test</centa>
this is a . <centb> test</centb>
this is a .  test

If you're looking to move the last dot in your string then you can use this
Regex: ([&]emsp;.*)\.
Replace with  .$1

Given your input text:
“[<deleted.material>[</deleted.material>]§ 431:10A–126 [<deleted.material>]Chemotherapy services.</deleted.material>] <added.material>Cancer treatment.</added.material>test snl.

Returns
“[<deleted.material>[</deleted.material>]§ 431:10A–126. [<deleted.material>]Chemotherapy services.</deleted.material>] <added.material>Cancer treatment.</added.material>test snl

A:
I can only use replaceAll on the string

Ok, weird requirement but here's my solution. I needed to use replaceAll twice to cover with/without tags scenarios.
private String parse(final String input) {
    return input.replaceAll("this is a   <(cent(a|b))> test\\.</\\1>",
        "this is a . <$1> test</$1>")
        .replaceAll("  test.", ".  test");
}

@Test
public void centa() {
    // Arrange
    final String input = "this is a   <centa> test.</centa>";

    // Act
    final String output = parse(input);

    // Assert
    assertEquals("this is a . <centa> test</centa>", output);
}

@Test
public void centb() {
    // Arrange
    final String input = "this is a   <centb> test.</centb>";

    // Act
    final String output = parse(input);

    // Assert
    assertEquals("this is a . <centb> test</centb>", output);
}

@Test
public void noTags() {
    // Arrange
    final String input = "this is a   test.";

    // Act
    final String output = parse(input);

    // Assert
    assertEquals("this is a .  test", output);
}

A: Trying to match your code with a single replaceAll. This should satisfy the 3 of your test cases.
Group 1 and 2 are separated, so that we can put a dot within.
Group 2 and 4 are separated, so that we can remove the dot within.
Pattern rulerPattern1 = Pattern.compile("([\\W\\w]+)( (<cent[ab]>)?[\\W\\w]+)\\.(</cent[ab]>)?", Pattern.MULTILINE);
System.out.println(rulerPattern1.matcher(input1).replaceAll("$1.$2$4"));


text:
Q: Login to the API manager through Eclipse Developer Tools I'm unable to connect to the API Manager when using Developer Tools for WSO2. I'm following the instructions on this page. When I try to log in to the publisher I get this error

When I try connecting to the publisher through port 9443 I get this error.

The environment I'm running is APIM 2.1.0 with the IDS 5.3.0 as key manager. I'm using a clustered environment as well with two gateway workers and the gate manager on the APIM side. Then two IDS servers.
I'm trying to connect from my Windows device, so I'm not on the actual Linux server. Also, I have a secondary user store added and when I login to the store and publisher I use those credentials. I tried both my secondary user store credentials and the admin credentials both return same error.
What are some possible fixes I can do? Or I'm I off with some configurations?

A: This error happens because you have to use the WSO2 trust store in your Java Application. If the plugin doesn't allow you to pass the JVM args, you probably need to add them on the eclipse.ini file, located inside the Eclipse folder.
Assuming you didn't change the default settings, pass the following JVM parameters to and you're good to go.
-Djavax.net.ssl.trustStore=<path_to_wso2_apim>/repository/resources/security/wso2carbon.jks
-Djavax.net.ssl.trustStorePassword=wso2carbon
-Djavax.net.ssl.trustStoreType=JKS

If your Eclipse and the WSO2 installation are not int he same computer you just need to copy the wso2carbon.jks to your PC and update the location on the -Djavax.net.ssl.trustStore argument above.

A: I had to download a fresh installation of Eclipse IDE for Java EE Developers (Mars 2). Then added the plugins manually from http://product-dist.wso2.com/p2/developer-studio-kernel/4.1.0/apim-tools/releases/2.0.0/ repo. I originally had the eclipse download from the wso2 website http://wso2.com/products/developer-studio/. I thought that it had all the right plugins, but I guess there is something missing in it.

A: I had the same problem with Developer Studio for WSO2 and I installed Spring Tool Suite 4 and followed the steps mentioned in https://docs.wso2.com/display/AM200/Installing+the+API+Manager+Tooling+Plug-In for APIM Tool and it solved the problem.


text:
Q: XPath with selectsinglenode I have this XML input :
<BIEN>
    <AGENCE></AGENCE>
    <INFO_GENERALES></INFO_GENERALES>
    <VENTE></VENTE>
    <FORET></FORET>
    <LOCALISATION></LOCALISATION>
    <PROPRIETAIRE>
        <COMMENTAIRES>This is the comment i don't want to see</COMMENTAIRES>
    </PROPRIETAIRE>
    <COMMENTAIRES>
          <FR>This is the comment I want to see</FR>
    </COMMENTAIRES>
    </BIEN>

When I do :
XmlDocument docxml = new XmlDocument();
docxml.LoadXml("myfile.xml");
XmlNode root = docxml.DocumentElement;
XmlNode nodeCommentaires = root.SelectSingleNode("descendant::COMMENTAIRES");

I have : This is the comment i don't want to see
But I want to see : This is the comment I want to see
What is the correct syntax that I have to use in selectSingleNode ?

A: Use a child instead of a descendant:
"child:COMMENTAIRES"

or simply
"./COMMENTIRES"

or
"COMMENTAIRES"

They are all equivalent.


text:
Q: Beaglebone Black Persistent Internet Over USB - Debian Image 2016-05.13 am335x_evm.sh My internet over usb used to just work on my BBB but now every time I boot I have to manually add
route add default gw 192.168.7.1
echo "nameserver 8.8.8.8" >> /etc/resolv.conf

I as following this guide but in /opt/scripts/boot/am335x_evm.sh
I can no longer find
/sbin/ifconfig usb0 192.168.7.2 netmask 255.255.255.252
/usr/sbin/udhcpd -S /etc/udhcpd.conf`

so I can add /sbin/route add default gw 192.168.7.1 metric 1
Where can I add this line?
edit: Host computer is windows 10.

A: The kernel maintainers update the kernel for that chip-family daily, so you should git pull that /opt directory you mentioned and then run the ./kernel_update in /opt/path/to/tools.
All of the directories on the BBB that can be updated in this manner are on https://github.com/RobertCNelson.
ps. I also updated my device tree files.


text:
Q: What is the volatile keyword useful for? At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.
Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?

A: Assume that a thread modifies the value of a shared variable, if you didn't use volatile modifier for that variable. When other threads want to read this variable's value, they don't see the updated value because they read the variable's value from the CPU's cache instead of RAM memory. This problem also known as Visibility Problem.
By declaring the shared variable volatile, all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory.
public class SharedObject {
    public volatile int sharedVariable = 0;
}

With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads data from main memory into CPU caches, or writes data from CPU caches to main memory. This can cause several problems which I will explain in the following sections.

Example:
Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:
public class SharedObject {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.
If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory. This situation is illustrated here:

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called a "visibility" problem. The updates of one thread are not visible to other threads.

A: volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.
To answer your question: Yes, I use a volatile variable to control whether some code continues a loop. The loop tests the volatile value and continues if it is true. The condition can be set to false by calling a "stop" method. The loop sees false and terminates when it tests the value after the stop method completes execution.
The book "Java Concurrency in Practice," which I highly recommend, gives a good explanation of volatile. This book is written by the same person who wrote the IBM article that is referenced in the question (in fact, he cites his book at the bottom of that article). My use of volatile is what his article calls the "pattern 1 status flag."
If you want to learn more about how volatile works under the hood, read up on the Java memory model. If you want to go beyond that level, check out a good computer architecture book like Hennessy & Patterson and read about cache coherence and cache consistency.

A: volatile is very useful to stop threads.
Not that you should be writing your own threads, Java 1.6 has a lot of nice thread pools.  But if you are sure you need a thread, you'll need to know how to stop it.
The pattern I use for threads is:
public class Foo extends Thread {

  private volatile boolean close = false;

  public void run() {
    while(!close) {
      // do work
    }
  }
  public void close() {
    close = true;
    // interrupt here if needed
  }
}

In the above code segment, the thread reading close in the while loop is different from the one that calls close(). Without volatile, the thread running the loop may never see the change to close.
Notice how there's no need for synchronization

A: You'll need to use 'volatile' keyword, or 'synchronized' and any other concurrency control tools and techniques you might have at your disposal if you are developing a multithreaded application. Example of such application is desktop apps.
If you are developing an application that would be deployed to application server (Tomcat, JBoss AS, Glassfish, etc) you don't have to handle concurrency control yourself as it already addressed by the application server. In fact, if I remembered correctly the Java EE standard prohibit any concurrency control in servlets and EJBs, since it is part of the 'infrastructure' layer which you supposed to be freed from handling it. You only do concurrency control in such app if you're implementing singleton objects. This even already addressed if you knit your components using frameworkd like Spring.
So, in most cases of Java development where the application is a web application and using IoC framework like Spring or EJB, you wouldn't need to use 'volatile'.

A: volatile only guarantees that all threads, even themselves, are incrementing. For example: a counter sees the same face of the variable at the same time. It is not used instead of synchronized or atomic or other stuff, it completely makes the reads synchronized. Please do not compare it with other java keywords. As the example shows below volatile variable operations are also atomic they fail or succeed at once.
package io.netty.example.telnet;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static volatile  int a = 0;
    public static void main(String args[]) throws InterruptedException{

        List<Thread> list = new  ArrayList<Thread>();
        for(int i = 0 ; i<11 ;i++){
            list.add(new Pojo());
        }

        for (Thread thread : list) {
            thread.start();
        }

        Thread.sleep(20000);
        System.out.println(a);
    }
}
class Pojo extends Thread{
    int a = 10001;
    public void run() {
        while(a-->0){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Main.a++;
            System.out.println("a = "+Main.a);
        }
    }
}

Even you put volatile or not results will always differ. But if you use AtomicInteger as below results will be always same. This is same with synchronized also.
    package io.netty.example.telnet;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.atomic.AtomicInteger;

    public class Main {

        public static volatile  AtomicInteger a = new AtomicInteger(0);
        public static void main(String args[]) throws InterruptedException{

            List<Thread> list = new  ArrayList<Thread>();
            for(int i = 0 ; i<11 ;i++){
                list.add(new Pojo());
            }

            for (Thread thread : list) {
                thread.start();
            }

            Thread.sleep(20000);
            System.out.println(a.get());

        }
    }
    class Pojo extends Thread{
        int a = 10001;
        public void run() {
            while(a-->0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Main.a.incrementAndGet();
                System.out.println("a = "+Main.a);
            }
        }
    }

A: While I see many good Theoretical explanations in the answers mentioned here, I am adding a practical example with an explanation here:
1.
CODE RUN WITHOUT VOLATILE USE
public class VisibilityDemonstration {

private static int sCount = 0;

public static void main(String[] args) {
    new Consumer().start();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        return;
    }
    new Producer().start();
}

static class Consumer extends Thread {
    @Override
    public void run() {
        int localValue = -1;
        while (true) {
            if (localValue != sCount) {
                System.out.println("Consumer: detected count change " + sCount);
                localValue = sCount;
            }
            if (sCount >= 5) {
                break;
            }
        }
        System.out.println("Consumer: terminating");
    }
}

static class Producer extends Thread {
    @Override
    public void run() {
        while (sCount < 5) {
            int localValue = sCount;
            localValue++;
            System.out.println("Producer: incrementing count to " + localValue);
            sCount = localValue;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                return;
            }
        }
        System.out.println("Producer: terminating");
    }
}
}

In the above code, there are two threads - Producer and Consumer.
The producer thread iterates over the loop 5 times (with a sleep of 1000 milliSecond or 1 Sec) in between. In every iteration, the producer thread increases the value of sCount variable by 1. So, the producer changes the value of sCount from 0 to 5 in all iterations
The consumer thread is in a constant loop and print whenever the value of sCount changes until the value reaches 5 where it ends.
Both the loops are started at the same time. So both the producer and consumer should print the value of sCount 5 times.
OUTPUT
Consumer: detected count change 0
Producer: incrementing count to 1
Producer: incrementing count to 2
Producer: incrementing count to 3
Producer: incrementing count to 4
Producer: incrementing count to 5
Producer: terminating

ANALYSIS
In the above program, when the producer thread updates the value of sCount, it does update the value of the variable in the main memory(memory from where every thread is going to initially read the value of variable). But the consumer thread reads the value of sCount only the first time from this main memory and then caches the value of that variable inside its own memory. So, even if the value of original sCount in main memory has been updated by the producer thread, the consumer thread is reading from its cached value which is not updated. This is called VISIBILITY PROBLEM .
2.
CODE RUN WITH VOLATILE USE
In the above code, replace the line of code where sCount is declared by the following :
private volatile  static int sCount = 0;

OUTPUT
Consumer: detected count change 0
Producer: incrementing count to 1
Consumer: detected count change 1
Producer: incrementing count to 2
Consumer: detected count change 2
Producer: incrementing count to 3
Consumer: detected count change 3
Producer: incrementing count to 4
Consumer: detected count change 4
Producer: incrementing count to 5
Consumer: detected count change 5
Consumer: terminating
Producer: terminating

ANALYSIS
When we declare a variable volatile, it means that all reads and all writes to this variable or from this variable will go directly into the main memory. The values of these variables will never be cached.
As the value of the sCount variable is never cached by any thread, the consumer always reads the original value of sCount from the main memory(where it is being updated by producer thread). So, In this case the output is correct where both the threads prints the different values of sCount 5 times.
In this way, the volatile keyword solves the VISIBILITY PROBLEM .

A: A variable declared with volatile keyword, has two main qualities which make it special.

*

*If we have a volatile variable, it cannot be cached into the computer's(microprocessor) cache memory by any thread. Access always happened from main memory.

*If there is a write operation going on a volatile variable, and suddenly a read operation is requested, it is guaranteed that the write operation will be finished prior to the read operation.
Two above qualities deduce that

*

*All the threads reading a volatile variable will definitely read the latest value. Because no cached value can pollute it. And also the read request will be granted only after the completion of the current write operation.

And on the other hand,

*

*If we further investigate the #2 that I have mentioned, we can see that volatile keyword is an ideal way to maintain a shared variable which has 'n' number of reader threads and only one writer thread to access it. Once we add the volatile keyword, it is done. No any other overhead about thread safety.

Conversly,
We can't make use of volatile keyword solely, to satisfy a shared variable which has more than one writer thread accessing it.

A: Absolutely, yes. (And not just in Java, but also in C#.) There are times when you need to get or set a value that is guaranteed to be an atomic operation on your given platform, an int or boolean, for example, but do not require the overhead of thread locking. The volatile keyword allows you to ensure that when you read the value that you get the current value and not a cached value that was just made obsolete by a write on another thread.

A: Yes, I use it quite a lot - it can be very useful for multi-threaded code.  The article you pointed to is a good one.  Though there are two important things to bear in mind:

*

*You should only use volatile if you
completely understand what it does
and how it differs to synchronized.
In many situations volatile appears,
on the surface, to be a simpler more
performant alternative to
synchronized, when often a better
understanding of volatile would make
clear that synchronized is the only
option that would work.

*volatile doesn't actually work in a
lot of older JVMs, although
synchronized does.  I remember seeing a document that referenced the various levels of support in different JVMs but unfortunately I can't find it now.  Definitely look into it if you're using Java pre 1.5 or if you don't have control over the JVMs that your program will be running on.

A: Every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value.
Only member variable can be volatile or transient.

A: One common example for using volatile is to use a volatile boolean variable as a flag to terminate a thread.  If you've started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag.  To stop it, set the flag to true.  By making the flag volatile, you can ensure that the thread that is checking it will see it has been set the next time it checks it without having to even use a synchronized block.

A: There are two different uses of volatile keyword.

*

*Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.

*Reduces the risk of memory in-consistency errors.

Prevents JVM from reading values in register, and forces its
  value to be read from memory.

A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:
while (busy) {
    /* do something else */
}

The testing thread will continue when another thread turns off the busy flag:
busy = 0;

However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

Reduces the risk of memory consistency errors.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a
"happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
The technique of reading, writing without memory consistency errors is called atomic action.
An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.
Below are actions you can specify that are atomic:

*

*Reads and writes are atomic for reference variables and for most
primitive variables (all types except long and double).

*Reads and writes are atomic for all variables declared volatile
(including long and double variables).

Cheers!

A: "… the volatile modifier guarantees that any thread that reads a field will see the most recently written value." - Josh Bloch
If you are thinking about using volatile, read up on the package java.util.concurrent which deals with atomic behaviour.
The Wikipedia post on a Singleton Pattern shows volatile in use.

A: Volatile does following.
1> Read and write of volatile variables by different threads are always from memory, not from thread's own cache or cpu register. So each thread always deals with the latest value.
2> When 2 different threads work with same instance or static variables in heap, one may see other's actions as out of order. See jeremy manson's blog on this. But volatile helps here.
Following fully running code shows how a number of threads can execute in predefined order and print outputs without using synchronized keyword.
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3
thread 0 prints 0
thread 1 prints 1
thread 2 prints 2
thread 3 prints 3

To achieve this we may use the following full fledged running code.
public class Solution {
    static volatile int counter = 0;
    static int print = 0;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Thread[] ths = new Thread[4];
        for (int i = 0; i < ths.length; i++) {
            ths[i] = new Thread(new MyRunnable(i, ths.length));
            ths[i].start();
        }
    }
    static class MyRunnable implements Runnable {
        final int thID;
        final int total;
        public MyRunnable(int id, int total) {
            thID = id;
            this.total = total;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                if (thID == counter) {
                    System.out.println("thread " + thID + " prints " + print);
                    print++;
                    if (print == total)
                        print = 0;
                    counter++;
                    if (counter == total)
                        counter = 0;
                } else {
                    try {
                        Thread.sleep(30);
                    } catch (InterruptedException e) {
                        // log it
                    }
                }
            }
        }
    }
}

The following github link has a readme, which gives proper explanation.
https://github.com/sankar4git/volatile_thread_ordering

A: Volatile(vɒlətʌɪl):  Easily evaporated at normal temperatures
Important point about volatile:

*

*Synchronization in Java is possible by using Java keywords synchronized and volatile and locks.

*In Java, we can not have synchronized variable. Using synchronized keyword with a variable is illegal and will result in compilation error. Instead of using the synchronized variable in Java, you can use the java volatile variable, which will instruct JVM threads to read the value of volatile variable from main memory and don't cache it locally.

*If a variable is not shared between multiple threads then there is no need to use the volatile keyword.

source
Example usage of volatile:
public class Singleton {
    private static volatile Singleton _instance; // volatile variable
    public static Singleton getInstance() {
        if (_instance == null) {
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    }
}

We are creating instance lazily at the time the first request comes.
If we do not make the _instance variable volatile then the Thread which is creating the instance of Singleton is not able to communicate to the other thread. So if Thread A is creating Singleton instance and just after creation, the CPU corrupts etc, all other threads will not be able to see the value of _instance as not null and they will believe it is still assigned null.
Why does this happen? Because reader threads are not doing any locking and until the writer thread comes out of a synchronized block, the memory will not be synchronized and value of _instance will not be updated in main memory. With the Volatile keyword in Java, this is handled by Java itself and such updates will be visible by all reader threads.

Conclusion: volatile keyword is also used to communicate the content of memory between threads.

Example usage of without volatile:
public class Singleton {
    private static Singleton _instance;   //without volatile variable
    public static Singleton getInstance() {
        if (_instance == null) {
            synchronized(Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
            }
        }
        return _instance;
    }
}

The code above is not thread-safe. Although it checks the value of instance once again within the synchronized block (for performance reasons), the JIT compiler can rearrange the bytecode in a way that the reference to the instance is set before the constructor has finished its execution. This means the method getInstance() returns an object that may not have been initialized completely. To make the code thread-safe, the keyword volatile can be used since Java 5 for the instance variable. Variables that are marked as volatile get only visible to other threads once the constructor of the object has finished its execution completely.
Source

volatile usage in Java:
The fail-fast iterators are typically implemented using a volatile counter on the list object.

*

*When the list is updated, the counter is incremented.

*When an Iterator is created, the current value of the counter is embedded in the Iterator object.

*When an Iterator operation is performed, the method compares the two counter values and throws a ConcurrentModificationException if they are different.

The implementation of fail-safe iterators is typically light-weight.  They typically rely on properties of the specific list implementation's data structures.  There is no general pattern.

A: No one has mentioned the treatment of read and write operation for long and double variable type. Reads and writes are atomic operations for reference variables and for most primitive variables, except for long and double variable types, which must use the volatile keyword to be atomic operations. @link

A: Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

A: Volatile
volatile -> synchronized[About]
volatile says for a programmer that the value always will be up to date. The problem is that the value can be saved on different types of hardware memory. For example it can be CPU registers, CPU cache, RAM... СPU registers and CPU cache belong to CPU and can not share a data unlike of RAM which is on the rescue in multithreading envirompment

volatile keyword says that a variable will be read and written from/to RAM memory directly. It has some computation footprint
Java 5 extended volatile by supporting happens-before[About]

A write to a volatile field happens-before every subsequent read of that field.

Read is after write

volatile keyword does not cure a race condition[About] situation to sove it use synchronized keyword[About]
As a result it safety only when one thread writes and others just read the volatile value

A: In my opinion, two important scenarios other than stopping thread in which volatile keyword is used are:

*

*Double-checked locking mechanism. Used often in Singleton design
pattern. In this the singleton object needs to be declared volatile.

*Spurious Wakeups. Thread may sometimes wake up from wait call even if no notify call has been issued. This behavior is called spurious wakeup. This can be countered by using a conditional variable (boolean flag). Put the wait() call in a while loop as long as the flag is true. So if thread wakes up from wait call due to any reasons other than Notify/NotifyAll then it encounters flag is still true and hence calls wait again. Prior to calling notify set this flag to true. In this case the boolean flag is declared as volatile.

A: From oracle documentation page, the need for volatile variable arises to fix memory consistency issues:

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

This means that changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
As explained in Peter Parker answer, in absence of volatile modifier, each thread's stack may have their own copy of variable. By making the variable as volatile, memory consistency issues have been fixed.
Have a look at jenkov tutorial page for better understanding.
Have a look at related SE question for some more details on volatile & use cases to use volatile:
Difference between volatile and synchronized in Java
One practical use case:
You have many threads, which need to print current time in a particular format for example : java.text.SimpleDateFormat("HH-mm-ss"). Yon can have one class, which converts current time into SimpleDateFormat and updated the variable for every one second. All other threads can simply use this volatile variable to print current time in log files.

A: Volatile Variables are light-weight synchronization. When visibility of latest data among all threads is requirement and atomicity can be compromised , in such situations Volatile Variables must be preferred. Read on volatile variables always return most recent write done by any thread since they are neither cached in registers nor in caches where other processors can not see. Volatile is Lock-Free. I use volatile, when scenario meets criteria as mentioned above.

A: volatile variable is basically used for instant update (flush) in main shared cache line once it updated, so that changes reflected to all worker threads immediately.

A: If you have a multithread system and these multiple threads work on some shared data, those threads will load data in their own cache. If we do not lock the resource, any change made in one thread is NOT gonna be available in another thread.

With a locking mechanism, we add read/write access to the data source. If one thread modifies the data source, that data will be stored in the main memory instead of in its cache. When others threads need this data, they will read it from the main memory. This will increase the latency dramatically.
To reduce the latency, we declare variables as volatile. It means that whenever the value of the variable is modified in any of the processors, the other threads will be forced to read it. It still has some delays but better than reading from the main memory.

A: The     volatile key when used with a variable, will make sure that threads reading this variable will see the same value . Now if you have multiple threads reading and writing to a variable, making the variable volatile will not be enough and data will be corrupted . Image threads have read the same value but each one has done some chages (say incremented a counter) , when writing back to the memory, data integrity is violated . That is why it is necessary to make the varible synchronized (diffrent ways are possible)
If the changes are done by 1 thread and the others need just to read this value, the volatile will be suitable.

A: Below is a very simple code to demonstrate the requirement of volatile for variable which is used to control the Thread execution from other thread (this is one scenario where volatile is required).
// Code to prove importance of 'volatile' when state of one thread is being mutated from another thread.
// Try running this class with and without 'volatile' for 'state' property of Task class.
public class VolatileTest {
    public static void main(String[] a) throws Exception {
        Task task = new Task();
        new Thread(task).start();

        Thread.sleep(500);
        long stoppedOn = System.nanoTime();

        task.stop(); // -----> do this to stop the thread

        System.out.println("Stopping on: " + stoppedOn);
    }
}

class Task implements Runnable {
    // Try running with and without 'volatile' here
    private volatile boolean state = true;
    private int i = 0;

    public void stop() {
        state = false;
    }

    @Override
    public void run() {
        while(state) {
            i++;
        }
        System.out.println(i + "> Stopped on: " + System.nanoTime());
    }
}

When volatile is not used: you'll never see 'Stopped on: xxx' message even after 'Stopping on: xxx', and the program continues to run.
Stopping on: 1895303906650500

When volatile used: you'll see the 'Stopped on: xxx' immediately.
Stopping on: 1895285647980000
324565439> Stopped on: 1895285648087300

Demo: https://repl.it/repls/SilverAgonizingObjectcode


text:
Q: Retrieving column names with column values in sqlite using cursor I want to display column names with column values in the Listview using cursor.
My present code shows only the column values.
public void openAndQueryDatabase() {

    db = openOrCreateDatabase( "mydatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY , null );

    Cursor cursor = db.rawQuery("select * from "+ table + " where name='"+ name + "'",  null);

    int count = cursor.getColumnCount();

    if (cursor!=null )
    {

        if  (cursor.moveToFirst())
        {
            do
            {
                 for (int i =0 ; i< count; i++)
                {
                String data = cursor.getString(i);
                details.add(data);
                }
            }
            while (cursor.moveToNext());
        }

         }
}

A: Use getColumnName(int columnIndex) to get the name of the row for a given index.

A: In this case you should use hashmap
for (int i =0 ; i< count; i++)
{
    String data = cursor.getString(i);
    String column_name = cursor.getColumnName(i);

    HashMap<String,String> map = new HashMap<String,String>();
    map.put("column_value",data);
    map.put("column_name",column_name);

    details.add(map); //change the type of details from ArrayList<String> to arrayList<HashMap<String,String>>
}

A: Use this.
 for (int i =0 ; i< count; i++)
  {
      String data = cursor.getString(i);
      String column_name = cursor.getColumName(i);
      details.add(data);
  }

A: Simply retrieve String array with names like that:
cursor.getColumnNames()


text:
Q: Possible alternative for finding the Area under the floor function (aka, the integral of floor(x)) So, I had to ask myself the question as to what the area under the floor function could possibly be.
I started by graphing the basic $\mbox{floor}(x)$ function (I personally use desmos.com for a nice online graphing calculator), then I plotted $y=x$. I then, I noticed that the line of best fit for the $\mbox{floor}$ function was $x-(1/2)$, or $x-0.5$. So, I decided to integrate that result with respect to $x$. So, I ended with $(x^2 -x)/2$. I have tested this out several times, and so far the numbers are accurate.
In summary:
$\mbox{floor}(x)$ has trendline $x-0.5$.
Take the antiderivative of the trendline -> $(x^2 -x)/2$.
Then find the area under the steps.
I personally took it analytically by looking at graphs and manually computing the area underneath the steps.
So, what do you guys think?

A: Your formula $\dfrac{x^2-x}2$ works as an approximation, but it fails as an actual formula.
For example, the actual area "under" the floor function (below it and above the $x$-axis) between $x=0$ and $x=\frac 12$ is zero, but your formula gives
$$\left[\frac{x^2-x}2\right]_0^{1/2}=-\frac 18$$
Are you trying for an approximation or for an actual formula? For an actual formula, recognize the that area under the floor of $x$ (I'll call it $\lfloor x\rfloor$) is the triangular number corresponding to $\lfloor x\rfloor-1$ plus the thin rectangle under the graph which has height $\lfloor x\rfloor$ and width $x-\lfloor x\rfloor$. Therefore the area under $f(u)=\lfloor u\rfloor$ between $0$ and $x$ is
$$\int_0^x \lfloor u\rfloor\,du = \frac{\lfloor x\rfloor(\lfloor x\rfloor-1)}2+\lfloor x\rfloor(x-\lfloor x\rfloor)$$
That expression can be simplified in various ways, of course. As @DavidK points out in a comment, my expression becomes yours when $x$ is an integer: my first term becomes your expression and my second term becomes zero since $x-\lfloor x\rfloor=0$ for integral $x$. Your expression just needs a "correction" term to make it work for non-integral $x$. So this may be the best expression for your purpose (note that it shows that the maximum error of your expression is $\frac 18$):

$$\int_0^x \lfloor u\rfloor\,du = \frac{x^2-x}2+\frac{(x-\lfloor x\rfloor)-(x-\lfloor x\rfloor)^2}2$$

Here is a graph showing your expression and the corrected one.

A: Rory Daulton already gave a complete answer, but here's a slightly
different way of coming to an equivalent conclusion.
Compare the region of the plane between the $x$ axis and the
graph of the function $f_1(x) = x$.
Now do the same for the function $f_2(x) = \lfloor x \rfloor$.
The difference between the two regions is a sequence of right triangles
that lie along the line $y=x$.
If $b \geq 0$, the area of those triangles between the lines $x=0$ and $x=b$
is the difference between $\int_0^b x\,dx$ and
$\int_0^b \lfloor x \rfloor\,dx$.
That is, to compute $\int_0^x \lfloor t \rfloor\,dt$ for $x \geq 0$
(choosing the name $x$ for the upper limit of integration
so the result is more consistent with your formula, and choosing a different name for the variable of integration to avoid confusion),
you can first find $\int_0^x t\,dt$ and then subtract the area of the right triangles.
Each triangle has two legs of length $1$ and area $\frac12$, except that
if $x$ is not an integer, the last triangle will be smaller than the others:
its legs will be only $x - \lfloor x \rfloor$.
The result is
$$
\int_0^x \lfloor t \rfloor\,dt
= \frac12 x^2 - \frac12 \lfloor x \rfloor - \frac12(x - \lfloor x \rfloor)^2,
$$
which is exactly equal to Rory Daulton's formula. (I checked it.)


text:
Q: How to close thread when application deactivated? I have some thread in some page (e.g page1) in wp7. I want to close these thread when the application deactivated in this page, not in the global application file.When application deactivated from some other page only this page onNvavigateFrom is called, bit page1 onNavigateFrom isn't called. How can I do that? Or what is the best practice to close such threads?

A: If your thread is the result of using BackgroundWorker (the recommended approach), you should be periodically checking CancellationPending as described on the DoWork documentation.
If you are creating your own Thread, you can emulate this behavior by setting a boolean flag that is checked periodically (in a loop or whatever) by your thread. What you shouldn't do is call Thread.Abort as that could leave you with corrupted state if you write to the isolated storage or a database.